From 9fa085a3168035fce6b4cbfa0391912cc68cc650 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" <> Date: Sun, 22 Nov 2026 01:47:00 -0800 Subject: [PATCH 01/12] wip(channels): input and output channels of Arrow record batches; operators' record-batch form (ITL-1362) Work in progress, part 1 of ITL-1347 stage 5 (the channel layer); not wired into nodes or orchestrators, so no result of the branch changes. - channels.py: InputChannel and OutputChannel (Arrow record batches), the conversions channel_from_stream and stream_from_batches, transport_columns; UpstreamFailedError in orcapod.errors; StreamBase.open_channel() and the StreamProtocol member. - Operators: StaticOutputOperatorPod.async_execute_batches (barrier by to_stream(); ROW_BY_ROW operators per record batch through static_process; Batch(n) by arrival), beside the row async_execute until the wiring. - Tests: tests/test_channels/test_record_batch_channels.py (29 pass) and tests/test_core/operators/test_record_batch_execution.py (691 pass, 27 fail: every failure is the Python-schema assertion of the zero-row test, not yet investigated). Not done: basedpyright, changelog fragment, CLAUDE.md, the 27 zero-row cases, review of the interim names. See the handoff note. Co-Authored-By: Claude Fable 5.2 --- src/orcapod/channels.py | 561 ++++++++++++++- src/orcapod/core/operators/add_tags.py | 2 + src/orcapod/core/operators/batch.py | 54 +- .../core/operators/column_selection.py | 10 + src/orcapod/core/operators/drop_nulls.py | 2 + src/orcapod/core/operators/index.py | 2 + src/orcapod/core/operators/mappers.py | 6 + src/orcapod/core/operators/pick.py | 2 + .../core/operators/static_output_pod.py | 122 +++- src/orcapod/core/streams/base.py | 21 +- src/orcapod/errors.py | 11 + .../protocols/core_protocols/streams.py | 13 + .../test_record_batch_channels.py | 655 ++++++++++++++++++ .../operators/test_record_batch_execution.py | 314 +++++++++ 14 files changed, 1770 insertions(+), 5 deletions(-) create mode 100644 tests/test_channels/test_record_batch_channels.py create mode 100644 tests/test_core/operators/test_record_batch_execution.py diff --git a/src/orcapod/channels.py b/src/orcapod/channels.py index 8111912f4..c74f4cc0c 100644 --- a/src/orcapod/channels.py +++ b/src/orcapod/channels.py @@ -2,14 +2,31 @@ Provides bounded async channels with close/done signaling, backpressure, and fan-out (broadcast) support. + +Channels of Arrow record batches (ITL-1347): ``InputChannel`` and ``OutputChannel`` are +the forms of ``ReadableChannel`` and ``WritableChannel`` that carry a stream's rows as +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. An +input channel is opened from a stream (``channel_from_stream``, ``stream.open_channel()``) +or from an output channel (``OutputChannel.open_reader``); an output channel, once +closed, gives its rows back as a stream (``OutputChannel.result``). Every conversion +between streams and channels is in this module. """ from __future__ import annotations import asyncio -from collections.abc import AsyncIterator +from collections import deque +from collections.abc import AsyncIterator, Sequence from dataclasses import dataclass, field -from typing import Generic, Protocol, TypeVar, runtime_checkable +from typing import TYPE_CHECKING, Any, Generic, Protocol, TypeVar, runtime_checkable + +import pyarrow as pa + +from orcapod.errors import UpstreamFailedError + +if TYPE_CHECKING: + from orcapod.protocols.core_protocols import StreamProtocol T = TypeVar("T") T_co = TypeVar("T_co", covariant=True) @@ -298,3 +315,543 @@ async def close(self) -> None: reader._queue.put_nowait(_CLOSED) except asyncio.QueueFull: reader._closed = True + + +# --------------------------------------------------------------------------- +# Channels of Arrow record batches (ITL-1347) +# --------------------------------------------------------------------------- + +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.""" + + +def transport_columns( + table: pa.Table, keys: tuple[Sequence[str], Sequence[str]] +) -> pa.Table: + """Return ``table`` as the columns passed between nodes, for a channel. + + The transport columns of a stream are what a table built from its rows holds: user + tags, system tags, data and source info, in that order, with no data-context and no + meta (``__``) column, and ``null`` as ``large_string`` (a row's datagram stores a + ``null`` column so). The source info follows the stream's data keys, a data-tag's + first, as each row lists it. No value is changed. + + One property is left for the complete table: whether a source-info field is + nullable follows its tokens, so it cannot be decided on one record batch of many. + Here every source-info field is nullable, so all record batches of one channel have + one schema; ``stream_from_batches`` sets the flags over all of them. + + Args: + table: A stream's table with its system tags and source info + (``ZERO_ROW_INPUT_COLUMNS``), of any number of rows. + keys: The stream's tag keys and data keys (``stream.keys()``). + + Returns: + The transport columns, in row order. + """ + # TODO(ITL-1360): this is steps 1 to 4 of the row-built form of the design + # (docs/dev/specs/itl-1347-job-table-transport.md); stage 2 defines that form once, + # and this function then calls it. + from orcapod.system_constants import constants + from orcapod.utils import arrow_utils + + tag_keys, data_keys = keys + names = table.column_names + system_tags = [n for n in names if n.startswith(constants.SYSTEM_TAG_PREFIX)] + source_info = [n for n in names if n.startswith(constants.SOURCE_PREFIX)] + # A row lists its source info in the order of its data columns. + by_data_key = [f"{constants.SOURCE_PREFIX}{name}" for name in data_keys] + source_info = [n for n in by_data_key if n in source_info] + [ + n + for n in source_info + if n not in by_data_key + and not n.removeprefix(constants.SOURCE_PREFIX).startswith( + constants.META_PREFIX + ) + ] + placed = {*tag_keys, *system_tags, *source_info, constants.CONTEXT_KEY} + data = [ + n + for n in names + if n not in placed + and not n.startswith((constants.META_PREFIX, constants.SOURCE_PREFIX)) + ] + kept = arrow_utils.normalize_table_to_large_types( + table.select([*tag_keys, *system_tags, *data, *source_info]) + ) + schema = pa.schema( + [ + column.with_nullable(True) + if column.name.startswith(constants.SOURCE_PREFIX) + else column + for column in kept.schema + ] + ) + return pa.Table.from_arrays(kept.columns, schema=schema) + + +def _declared_transport_schema(stream: StreamProtocol) -> pa.Schema | None: + """Return the schema ``stream``'s record batches have, from its description. + + Never computes, reads or polls a row: it is the schema of the stream's zero-row + input, as its record batches carry it (``transport_columns``). + + Args: + stream: The describing stream. + + Returns: + The schema, or ``None`` for a stream that cannot say its Arrow types without + rows (an unbound input slot, a source that has not polled yet). + """ + # TODO(ITL-1360): ``stream.arrow_schema()``, once every stream has it. + from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod + from orcapod.core.streams.base import ZERO_ROW_INPUT_COLUMNS + + typed = StaticOutputOperatorPod._zero_row_input(stream) # pyright: ignore[reportPrivateUsage] # the zero-row form of an input + if typed is None: + return None + return transport_columns( + typed.as_table(columns=ZERO_ROW_INPUT_COLUMNS), stream.keys() + ).schema + + +def stream_from_batches( + stream: StreamProtocol, batches: Sequence[pa.RecordBatch] +) -> StreamProtocol: + """Return the Arrow record batches of ``stream``'s rows as a stream. + + The one place a stream is made from Arrow record batches: what an output channel + gives once closed (``OutputChannel.result``) and what an input channel delivered + (``InputChannel.to_stream``). The batches are put under one another in the order + given, each system-tag and source-info field is flagged nullable only when one of + its values is null (decided over the complete table, never per batch), and the + table is wrapped with ``stream``'s identity: its producer, upstreams, pipeline hash and data + context. With no batch it is ``stream``'s zero-row input, typed by its description + and never by rows. + + Args: + stream: The describing stream: the node or stream the rows are of. + batches: Its rows as transport columns (``transport_columns``), in order. + + Returns: + A complete, re-readable stream over the rows. + """ + from orcapod.core.data_tags import stream_data_tags + from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod + + if not batches: + return StaticOutputOperatorPod._materialize_upstream([], stream) # pyright: ignore[reportPrivateUsage] # the zero-row input of an operator + table = _flagged_by_values(pa.Table.from_batches(list(batches))) + return StaticOutputOperatorPod._as_upstream_stream( # pyright: ignore[reportPrivateUsage] # the identity of a successor's input + table, stream.keys()[0], stream_data_tags(stream), stream + ) + + +def _flagged_by_values(table: pa.Table) -> pa.Table: + """Flag each system-tag and source-info field nullable only when it holds a null. + + What a table built from rows has: a row states its system tags and its source-info + tokens as values, so those fields are non-nullable unless a value is missing. It is + decided over the complete table, never per record batch (two batches of one + channel would then have two schemas). The same arrays under the new flags. + + Args: + table: The complete table of a stream's transport columns. + + Returns: + The table with those fields' flags set by their values. + """ + from orcapod.system_constants import constants + + by_values = (constants.SYSTEM_TAG_PREFIX, constants.SOURCE_PREFIX) + schema = pa.schema( + [ + column.with_nullable(table.column(i).null_count > 0) + if column.name.startswith(by_values) + else column + for i, column in enumerate(table.schema) + ] + ) + return pa.Table.from_arrays(table.columns, schema=schema) + + +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: + self._stream = stream + self._batches: deque[pa.RecordBatch] | None = None + + async def next(self) -> pa.RecordBatch | None: + if self._batches is None: + # On the first read, not when the channel is opened: opening computes + # nothing. + from orcapod.core.streams.base import ZERO_ROW_INPUT_COLUMNS + + table = transport_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: + self._batches = deque() + + +class _OutputFeed: + """One reader of an output channel, with its own position.""" + + def __init__(self, output: OutputChannel) -> None: + self._output = output + self.open = True + # With retained batches: this reader's position among them. Without: the + # batches sent and not yet read by this reader. + self.position = 0 + self.queue: deque[pa.RecordBatch] = deque() + + async def next(self) -> pa.RecordBatch | None: + output = self._output + while self.open: + if output._error is not None: # pyright: ignore[reportPrivateUsage] + raise output._upstream_failed() # pyright: ignore[reportPrivateUsage] + if output._retain: # pyright: ignore[reportPrivateUsage] + if self.position < len(output._batches): # pyright: ignore[reportPrivateUsage] + self.position += 1 + return output._batches[self.position - 1] # pyright: ignore[reportPrivateUsage] + elif self.queue: + batch = self.queue.popleft() + output._notify() # pyright: ignore[reportPrivateUsage] # room for the producer + return batch + if output._closed: # pyright: ignore[reportPrivateUsage] + return None + await output._changed.wait() # pyright: ignore[reportPrivateUsage] + return None + + def close(self) -> None: + self.open = False + self.queue.clear() + self._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`` (``stream.open_channel()``) or by + ``OutputChannel.open_reader``, never directly. + """ + + def __init__(self, stream: StreamProtocol, feed: _BatchFeed) -> None: + self._stream = stream + self._feed = feed + self._received = 0 + self._ended = 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. + + Raises: + ChannelClosed: At the end, and after ``close``. + UpstreamFailedError: If the producer failed or was cancelled. + """ + if self._ended: + raise ChannelClosed() + batch = await self._feed.next() + if batch is None: + self._ended = True + raise ChannelClosed() + self._received += 1 + return batch + + def __aiter__(self) -> AsyncIterator[pa.RecordBatch]: + return self + + async def __anext__(self) -> pa.RecordBatch: + try: + return await self.receive() + except ChannelClosed: + raise StopAsyncIteration + + async def collect(self) -> list[pa.RecordBatch]: + """Read to the end and return every remaining record batch, in arrival order.""" + 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. + 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.""" + self._ended = True + self._feed.close() + + +class OutputChannel: + """The producer side of a node's async output, in Arrow record batches. + + The Arrow-record-batch form of ``WritableChannel``. Its ``stream`` is the producing + node, or the stream the output is of: the description of every record batch sent. + Each consumer reads through its own input channel (``open_reader``), which is the + fan-out. Once closed, ``result`` gives the output as an ordinary stream. + + Args: + stream: The describing stream. + retain: Keep every record batch sent, so that ``result`` can give the output + stream. Readers then read the kept batches at their own position, a reader + may be opened at any time, and ``send`` never waits. Without it, ``send`` + waits until every reader has room, so the slowest reader sets the pace, + and ``result`` raises. + buffer_size: Without ``retain``, how many record batches each reader queues + before ``send`` waits. + """ + + def __init__( + self, + stream: StreamProtocol, + *, + retain: bool = True, + buffer_size: int = BATCH_BUFFER_SIZE, + ) -> None: + if buffer_size < 1: + raise ValueError(f"buffer_size must be at least 1, got {buffer_size}") + self._stream = stream + self._retain = retain + self._buffer_size = buffer_size + self._batches: list[pa.RecordBatch] = [] + self._readers: list[_OutputFeed] = [] + self._sent = 0 + self._closed = False + self._error: BaseException | None = None + self._result: StreamProtocol | None = None + # The schema every record batch must have: the description's, or the first + # batch's when the stream cannot say its Arrow types without rows. + self._schema: pa.Schema | None = None + self._schema_known = False + self._changed = asyncio.Event() + + @property + def stream(self) -> StreamProtocol: + """The stream whose rows are written here: the description.""" + return self._stream + + def _notify(self) -> None: + """Wake everything waiting on this channel: readers and a waiting ``send``.""" + changed, self._changed = self._changed, asyncio.Event() + changed.set() + + def _upstream_failed(self) -> UpstreamFailedError: + error = self._error + assert error is not None + failure = UpstreamFailedError( + f"The input from {_named(self._stream)} did not finish: its producer " + + f"failed with {type(error).__name__}: {error}" + ) + failure.__cause__ = error + return failure + + def _check_schema(self, batch: pa.RecordBatch) -> None: + """Raise unless ``batch`` has the schema of this channel's record batches.""" + if not self._schema_known: + self._schema = _declared_transport_schema(self._stream) + self._schema_known = True + if self._schema is None: + self._schema = batch.schema + mismatch = _schema_mismatch(self._schema, batch.schema) + if mismatch is not None: + raise ValueError( + f"A record batch sent as {_named(self._stream)} does not have that " + + f"stream's columns: {mismatch}." + ) + + async def send(self, batch: pa.RecordBatch) -> None: + """Send one Arrow record batch of the stream's transport columns. + + Raises: + ChannelClosed: If the channel is closed or failed. + ValueError: If the batch's schema is not the stream's. + """ + if self._closed or self._error is not None: + raise ChannelClosed("Cannot send to a closed channel") + self._check_schema(batch) + self._sent += 1 + if self._retain: + self._batches.append(batch) + self._notify() + return + for reader in list(self._readers): + # The slowest reader sets the pace; one that closed is not waited for. + while reader.open and len(reader.queue) >= self._buffer_size: + await self._changed.wait() + if reader.open: + reader.queue.append(batch) + # At once, not after the last reader: this reader may be waiting for + # the batch while the send waits for another reader's room. + self._notify() + + async def close(self) -> None: + """Complete the output. A second close does nothing; never waits.""" + if not self._closed and self._error is None: + self._closed = True + self._notify() + + def fail(self, error: BaseException) -> None: + """End the output with the producer's failure or cancellation. + + Every reader's next read raises ``UpstreamFailedError``, never a normal end. + Does nothing on a channel already closed or failed. + + Args: + error: The producer's error. + """ + if not self._closed and self._error is None: + self._error = error + self._notify() + + def open_reader(self) -> InputChannel: + """Open an input channel for one consumer, with its own position. + + Raises: + ValueError: Without ``retain``, once a record batch has been sent: the + reader would miss it. + """ + if not self._retain and self._sent: + raise ValueError( + f"A reader of {_named(self._stream)} must be opened before the first " + + "record batch is sent: this output channel does not retain what it " + + "sent (retain=False)." + ) + feed = _OutputFeed(self) + if not self._retain: + self._readers.append(feed) + return InputChannel(self._stream, feed) + + def result(self) -> StreamProtocol: + """Return the output as a stream, once the channel is closed. + + The concatenation of the record batches sent, in the order sent, with the + description and identity of ``stream`` (``stream_from_batches``); the same + object on every call. + + Raises: + RuntimeError: If the channel is not closed, failed, or does not retain. + """ + if self._error is not None: + raise RuntimeError( + f"The output of {_named(self._stream)} has no result: its producer " + + f"failed with {type(self._error).__name__}: {self._error}" + ) from self._error + if not self._retain: + raise RuntimeError( + f"The output of {_named(self._stream)} was not retained " + + "(retain=False), so it has no result stream." + ) + if not self._closed: + raise RuntimeError( + f"The output of {_named(self._stream)} is not closed yet; its result " + + "is a stream only once it is complete." + ) + if self._result is None: + self._result = stream_from_batches(self._stream, self._batches) + return self._result + + +def channel_from_stream(stream: StreamProtocol) -> InputChannel: + """Open an input channel on a complete stream. + + The channel delivers the stream's transport columns (``transport_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) + return repr(label) if label else repr(stream) + + +def _schema_mismatch(declared: pa.Schema, sent: pa.Schema) -> str | None: + """Say how a record batch's schema differs from a channel's, or ``None``. + + The two schemas agree when they have the same columns in the same order, each with + the same Arrow type and nullability. What a description does not say of a row is + not compared: a ``null`` column, which rows carry as ``large_string``, and whether + a system-tag or source-info field is nullable, which follows the values of the + complete table (``_flagged_by_values``). + """ + from orcapod.system_constants import constants + from orcapod.utils import arrow_utils + + if declared.names != sent.names: + return f"it has {sent.names}, the stream has {declared.names}" + for expected, column in zip(declared, sent): + expected_type = arrow_utils.normalize_to_large_types(expected.type) + if expected_type != arrow_utils.normalize_to_large_types(column.type): + return f"column {column.name!r} is {column.type}, the stream's is {expected.type}" + if expected.nullable != column.nullable and not column.name.startswith( + (constants.SYSTEM_TAG_PREFIX, constants.SOURCE_PREFIX) + ): + flags = {True: "nullable", False: "not nullable"} + return ( + f"column {column.name!r} is {flags[column.nullable]}, the stream's is " + + flags[expected.nullable] + ) + return None diff --git a/src/orcapod/core/operators/add_tags.py b/src/orcapod/core/operators/add_tags.py index befd84f56..c1b3eee10 100644 --- a/src/orcapod/core/operators/add_tags.py +++ b/src/orcapod/core/operators/add_tags.py @@ -120,6 +120,8 @@ class AddTags(UnaryOperator): PROVISIONAL: ClassVar[bool] = True # Data-tags pass through as they are; the new tags are plain (ITL-1023). + # Each output row comes from one input row (ITL-1347). + ROW_BY_ROW: ClassVar[bool] = True DATA_TAGS_ISSUE: ClassVar[str | None] = None def __init__(self, tags: Mapping[str, TagConstant], **kwargs: Any): diff --git a/src/orcapod/core/operators/batch.py b/src/orcapod/core/operators/batch.py index e4c19d279..7166d646b 100644 --- a/src/orcapod/core/operators/batch.py +++ b/src/orcapod/core/operators/batch.py @@ -7,7 +7,12 @@ import pyarrow as pa from orcapod.core.operators.meta_columns import WithoutMetaWriter -from orcapod.channels import ReadableChannel, WritableChannel +from orcapod.channels import ( + InputChannel, + OutputChannel, + ReadableChannel, + WritableChannel, +) from orcapod.core.operators.base import UnaryOperator from orcapod.core.data_tags import stream_data_tags from orcapod.core.streams import ArrowTableStream @@ -264,6 +269,53 @@ async def async_execute( finally: await output.close() + async def async_execute_batches( + self, inputs: Sequence[InputChannel], output: OutputChannel + ) -> None: + """Batch the rows of an input channel as they arrive. + + The Arrow-record-batch form of ``async_execute`` (ITL-1347). With a + ``batch_size``, every ``batch_size`` rows that have arrived are batched and + sent at once, whatever record batches they came in, so a batch holds + consecutive arrivals, as on the row path; the rows left at the end make the + last, smaller batch unless ``drop_partial_batch``. With ``batch_size == 0`` + (every row in one batch) all of the input is read first. + + Args: + inputs: The one input channel. + output: The channel the batched rows are sent into. + """ + if self.batch_size == 0: + await super().async_execute_batches(inputs, output) + return + (channel,) = inputs + try: + waiting: list[pa.RecordBatch] = [] + rows = 0 + async for batch in channel: + waiting.append(batch) + rows += batch.num_rows + full = rows - rows % self.batch_size + if not full: + continue + arrived = pa.Table.from_batches(waiting) + await self._send_processed( + arrived.slice(0, full).to_batches(), channel.stream, output + ) + waiting = arrived.slice(full).to_batches() + rows -= full + # The rows left over are fewer than one batch: the sync rule decides + # whether they make a last one. + if rows: + await self._send_processed(waiting, channel.stream, output) + except BaseException as error: + output.fail(error) + raise + else: + await output.close() + finally: + await channel.close() + def to_config(self) -> dict[str, Any]: """Serialize this Batch operator to a config dict. diff --git a/src/orcapod/core/operators/column_selection.py b/src/orcapod/core/operators/column_selection.py index 3e59a5458..cbc6570b8 100644 --- a/src/orcapod/core/operators/column_selection.py +++ b/src/orcapod/core/operators/column_selection.py @@ -58,6 +58,8 @@ class SelectTagColumns(UnaryOperator): """ # Data-tags (ITL-1023): handled. + # Each output row comes from one input row (ITL-1347). + ROW_BY_ROW: ClassVar[bool] = True DATA_TAGS_ISSUE: ClassVar[str | None] = None def __init__(self, columns: str | Collection[str], strict: bool = True, **kwargs): @@ -195,6 +197,8 @@ class SelectDataColumns(UnaryOperator): """ # Data-tags (ITL-1023): handled. + # Each output row comes from one input row (ITL-1347). + ROW_BY_ROW: ClassVar[bool] = True DATA_TAGS_ISSUE: ClassVar[str | None] = None def __init__(self, columns: str | Collection[str], strict: bool = True, **kwargs): @@ -349,6 +353,8 @@ class DropTagColumns(UnaryOperator): """ # Data-tags (ITL-1023): handled. + # Each output row comes from one input row (ITL-1347). + ROW_BY_ROW: ClassVar[bool] = True DATA_TAGS_ISSUE: ClassVar[str | None] = None def __init__(self, columns: str | Collection[str], strict: bool = True, **kwargs): @@ -491,6 +497,8 @@ class DropDataColumns(UnaryOperator): """ # Data-tags (ITL-1023): handled. + # Each output row comes from one input row (ITL-1347). + ROW_BY_ROW: ClassVar[bool] = True DATA_TAGS_ISSUE: ClassVar[str | None] = None def __init__(self, columns: str | Collection[str], strict: bool = True, **kwargs): @@ -669,6 +677,8 @@ class _TagAndDataColumnsOperator(UnaryOperator, ABC): """ # Data-tags: handled (ITL-1022). A name acts on both roles alike. + # Each output row comes from one input row (ITL-1347). + ROW_BY_ROW: ClassVar[bool] = True DATA_TAGS_ISSUE: ClassVar[str | None] = None _verb: ClassVar[str] = "" diff --git a/src/orcapod/core/operators/drop_nulls.py b/src/orcapod/core/operators/drop_nulls.py index 6e1fc0a81..fb7daf80a 100644 --- a/src/orcapod/core/operators/drop_nulls.py +++ b/src/orcapod/core/operators/drop_nulls.py @@ -91,6 +91,8 @@ class DropNulls(UnaryOperator): """ # Data-tags (ITL-1023): handled. + # Each output row comes from one input row (ITL-1347). + ROW_BY_ROW: ClassVar[bool] = True DATA_TAGS_ISSUE: ClassVar[str | None] = None def __init__( diff --git a/src/orcapod/core/operators/index.py b/src/orcapod/core/operators/index.py index ac988abe3..23c550bd6 100644 --- a/src/orcapod/core/operators/index.py +++ b/src/orcapod/core/operators/index.py @@ -51,6 +51,8 @@ class Index(UnaryOperator): PROVISIONAL: ClassVar[bool] = True # Data-tags (ITL-1023): handled. + # Each output row comes from one input row (ITL-1347). + ROW_BY_ROW: ClassVar[bool] = True DATA_TAGS_ISSUE: ClassVar[str | None] = None def __init__( diff --git a/src/orcapod/core/operators/mappers.py b/src/orcapod/core/operators/mappers.py index b27aae340..0d12778f6 100644 --- a/src/orcapod/core/operators/mappers.py +++ b/src/orcapod/core/operators/mappers.py @@ -66,6 +66,8 @@ class MapData(UnaryOperator): """ # Data-tags (ITL-1023): handled. + # Each output row comes from one input row (ITL-1347). + ROW_BY_ROW: ClassVar[bool] = True DATA_TAGS_ISSUE: ClassVar[str | None] = None def __init__( @@ -332,6 +334,8 @@ class MapTags(UnaryOperator): PROVISIONAL: ClassVar[bool] = True # Data-tags (ITL-1023): handled. + # Each output row comes from one input row (ITL-1347). + ROW_BY_ROW: ClassVar[bool] = True DATA_TAGS_ISSUE: ClassVar[str | None] = None def __init__( @@ -618,6 +622,8 @@ class MapColumns(UnaryOperator): """ # Provisional: its identity is not frozen with data context v1 (ITL-1279). + # Each output row comes from one input row (ITL-1347). + ROW_BY_ROW: ClassVar[bool] = True PROVISIONAL: ClassVar[bool] = True def __init__( diff --git a/src/orcapod/core/operators/pick.py b/src/orcapod/core/operators/pick.py index e6d648659..b964c5fa7 100644 --- a/src/orcapod/core/operators/pick.py +++ b/src/orcapod/core/operators/pick.py @@ -53,6 +53,8 @@ class Pick(UnaryOperator): PROVISIONAL: ClassVar[bool] = True # Data-tags (ITL-1023): handled. + # Each output row comes from one input row (ITL-1347). + ROW_BY_ROW: ClassVar[bool] = True DATA_TAGS_ISSUE: ClassVar[str | None] = None def __init__( diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index a669ecf9b..61cd6744b 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -9,7 +9,14 @@ import pyarrow as pa -from orcapod.channels import ReadableChannel, WritableChannel +from orcapod.channels import ( + InputChannel, + OutputChannel, + ReadableChannel, + WritableChannel, + stream_from_batches, + transport_columns, +) from orcapod import contexts from orcapod.config import OrcapodConfig from orcapod.contexts import DataContext @@ -70,6 +77,16 @@ class StaticOutputOperatorPod(TraceableBase): # does not handle them yet: it raises instead of giving a wrong answer. DATA_TAGS_ISSUE: ClassVar[str | None] = "ITL-1022" + ROW_BY_ROW: ClassVar[bool] = False + """Whether each output row comes from one input row, whatever the other rows are. + + Declared by the operators that select, rename or add columns, narrow a column or + leave rows out by their own values (the column selections and mappers, + ``AddTags``, ``DropNulls``, ``Index``, ``Pick``). Such an operator can be applied + to each Arrow record batch of its input as it arrives + (``async_execute_batches``); every other operator needs all of an input first. + """ + OUTPUT_SCHEMA_IS_INPUT_SCHEMA: ClassVar[bool] = False """Whether the output has exactly its single input's columns and Arrow types. @@ -772,6 +789,109 @@ async def async_execute( finally: await output.close() + # ------------------------------------------------------------------ + # Async execution on Arrow record batches (ITL-1347) + # ------------------------------------------------------------------ + + async def async_execute_batches( + self, inputs: Sequence[InputChannel], output: OutputChannel + ) -> None: + """Run this operator over input channels of Arrow record batches. + + The Arrow-record-batch form of ``async_execute`` (ITL-1347, stage 5); the + nodes and the orchestrator still call the row form until they are wired to + this one, which then takes its name. The operator has one body for both + paths, ``static_process``: each input's description is its channel's stream + (identity, pipeline hash, data context, keys), as on the sync path. + + 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 + the sync call, so an input with no rows gives the typed zero-row result of + the sync path, with no row to send. + + The output is closed when the operator is done. If it fails or is cancelled, + the output fails instead, so no reader takes it for complete; every input is + closed in either case. + + Args: + inputs: One input channel per input stream, in the operator's order. + output: The channel the result's record batches are sent into. + """ + try: + if self.ROW_BY_ROW: + (channel,) = inputs + async for batch in channel: + await self._send_processed([batch], channel.stream, output) + else: + streams = await _streams_of(inputs) + await self._send_result(self.static_process(*streams), output) + except BaseException as error: + output.fail(error) + raise + else: + await output.close() + finally: + for channel in inputs: + await channel.close() + + async def _send_processed( + self, + batches: Sequence[pa.RecordBatch], + stream: StreamProtocol, + output: OutputChannel, + ) -> None: + """Apply this operator to some record batches of one input and send the result. + + The batches are wrapped as a stream with the input's identity and given to + ``static_process``, the sync body. + + Args: + batches: Record batches of the input's rows, in order. + stream: The input's describing stream. + output: The channel to send the result into. + """ + await self._send_result( + self.static_process(stream_from_batches(stream, batches)), output + ) + + @staticmethod + async def _send_result(result: StreamProtocol, output: OutputChannel) -> None: + """Send a result stream's rows into ``output`` as its own record batches. + + Args: + result: An operator's result. + output: The channel to send into; a result with no rows sends nothing. + """ + table = transport_columns( + result.as_table(columns=ZERO_ROW_INPUT_COLUMNS), result.keys() + ) + for batch in table.to_batches(): + if batch.num_rows: + await output.send(batch) + + +async def _streams_of(inputs: Sequence[InputChannel]) -> list[StreamProtocol]: + """Read every input channel to its end, each as a stream, at the same time. + + Args: + inputs: The input channels. + + Returns: + One complete stream per input, in order. + + Raises: + 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] + try: + return list(await asyncio.gather(*tasks)) + except BaseException: + for task in tasks: + _ = task.cancel() + raise + class _RowsOfStream(ArrowTableStream): """Rows standing in for the stream they came from, with its pipeline hash. diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py index 0f8a5cb33..73aecad3f 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -14,7 +14,7 @@ from contextlib import contextmanager from contextvars import ContextVar from datetime import datetime -from typing import Any, cast +from typing import TYPE_CHECKING, Any, cast import pandas as pd import polars as pl @@ -37,6 +37,9 @@ from orcapod.types import ColumnConfig, Schema from orcapod.utils import arrow_utils +if TYPE_CHECKING: + from orcapod.channels import InputChannel + # TODO: consider using this instead of making copy of dicts # from types import MappingProxyType @@ -995,6 +998,22 @@ def iter_data( self, ) -> Iterator[tuple[TagProtocol, DataProtocol]]: ... + def open_channel(self) -> "InputChannel": + """Open an input channel on this stream, for async computation (ITL-1347). + + The channel delivers this stream's rows as Arrow record batches, 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: readable again, and by every other reader. Nothing is + computed until the channel is first read. + + Returns: + The input channel. + """ + from orcapod.channels import channel_from_stream + + return channel_from_stream(self) + async def async_iter_data( self, ) -> AsyncIterator[tuple[TagProtocol, DataProtocol]]: diff --git a/src/orcapod/errors.py b/src/orcapod/errors.py index 5ae3a904b..2b46aa823 100644 --- a/src/orcapod/errors.py +++ b/src/orcapod/errors.py @@ -780,6 +780,17 @@ class SemiJoinIgnoredColumnWarning(UserWarning): """ +class UpstreamFailedError(Exception): + """An input channel's producer failed before it finished (ITL-1347). + + Raised by an ``InputChannel``'s next read once the node that writes into it has + failed or been cancelled, so a reader never takes a producer's failure for a normal + end: a barrier operator never computes over part of its input, and no node stores a + result as if its input were complete. The producer's own error is the cause + (``__cause__``), and it is the error a run raises: this one only stops the readers. + """ + + class EmptyDataAccessError(Exception): """Raised when a payload-access method is called on an ``EmptyData`` instance. diff --git a/src/orcapod/protocols/core_protocols/streams.py b/src/orcapod/protocols/core_protocols/streams.py index 010d29232..b36e8dd1a 100644 --- a/src/orcapod/protocols/core_protocols/streams.py +++ b/src/orcapod/protocols/core_protocols/streams.py @@ -16,6 +16,7 @@ from orcapod.types import ColumnConfig, Schema if TYPE_CHECKING: + from orcapod.channels import InputChannel import pandas as pd import polars as pl import pyarrow as pa @@ -183,6 +184,18 @@ def iter_data(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: """ ... + def open_channel(self) -> "InputChannel": + """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. + + Returns: + The input channel. + """ + ... + def async_iter_data(self) -> AsyncIterator[tuple[TagProtocol, DataProtocol]]: """ Generates asynchronous iterator over (tag, data) pairs in the stream. diff --git a/tests/test_channels/test_record_batch_channels.py b/tests/test_channels/test_record_batch_channels.py new file mode 100644 index 000000000..740d62946 --- /dev/null +++ b/tests/test_channels/test_record_batch_channels.py @@ -0,0 +1,655 @@ +"""Input and output channels of Arrow record batches (ITL-1347, stage 5: L8). + +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 (``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". + +The oracle of every table is ``R``: the table today's code builds from a stream's rows +(``StaticOutputOperatorPod._rows_to_table``). +""" + +from __future__ import annotations + +import asyncio +from collections.abc import Awaitable, Callable, Sequence +from typing import Any, TypeVar +from unittest import mock + +import pyarrow as pa +import pytest + +from orcapod.channels import ( + BATCH_BUFFER_SIZE, + SOURCE_BATCH_ROWS, + ChannelClosed, + InputChannel, + OutputChannel, + ReadableChannel, + WritableChannel, + channel_from_stream, + stream_from_batches, +) +from orcapod.core.operators import MapData, PolarsFilter, SelectDataColumns +from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod +from orcapod.core.streams import ArrowTableStream +from orcapod.errors import UpstreamFailedError +from orcapod.sources import ArrowTableSource + +T = TypeVar("T") +ALL = {"system_tags": True, "source": True} +TIMEOUT = 5.0 + + +def run(make: Callable[[], Awaitable[T]]) -> T: + """Run a coroutine to its end; a channel that never wakes fails the test.""" + + async def bounded() -> T: + return await asyncio.wait_for(make(), TIMEOUT) + + return asyncio.run(bounded()) + + +def source(n: int = 7, source_id: str = "events") -> ArrowTableSource: + """``n`` rows: tags ``subject`` and ``trial`` (a data-tag too), three data columns.""" + return ArrowTableSource( + pa.table( + { + "subject": pa.array([f"m{i % 3}" for i in range(n)], pa.string()), + "trial": pa.array(range(n), pa.int16()), + "amplitude": pa.array([0.5 * i for i in range(n)], pa.float32()), + "note": pa.array( + [None if i % 4 == 1 else f"n{i}" for i in range(n)], pa.string() + ), + "trace": pa.array([[i, i + 1] for i in range(n)], pa.list_(pa.int8())), + } + ), + tag_columns=["subject", "trial"], + source_id=source_id, + ) + + +def R(stream: Any) -> pa.Table: + """The table today's code builds from ``stream``'s rows.""" + return StaticOutputOperatorPod._rows_to_table(list(stream.iter_data()))[0] + + +def same(table: pa.Table, expected: pa.Table) -> bool: + """Whether two tables have one schema (metadata included) and the same rows.""" + return table.schema.equals(expected.schema, check_metadata=True) and ( + table.combine_chunks().equals(expected.combine_chunks()) + ) + + +def batches_of(stream: Any, rows: int = SOURCE_BATCH_ROWS) -> list[pa.RecordBatch]: + """``stream``'s record batches, cut every ``rows`` rows.""" + + async def read() -> list[pa.RecordBatch]: + return await stream.open_channel().collect() + + return pa.Table.from_batches(run(read)).to_batches(max_chunksize=rows) + + +# --- Opening an input channel on a stream ---------------------------------------------- + + +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.""" + stream = source() + channel = stream.open_channel() + + assert isinstance(channel, InputChannel) + assert isinstance(channel, ReadableChannel) + assert channel.stream is stream + delivered = run(channel.to_stream) + assert same(delivered.as_table(columns=ALL), R(stream)) + assert delivered.keys() == stream.keys() + assert delivered.output_schema() == stream.output_schema() + assert delivered.data_context_key == stream.data_context_key + assert delivered.pipeline_hash() == stream.pipeline_hash() + + +def test_opening_a_channel_computes_nothing() -> None: + """The stream's table is read at the first ``receive``, not when the channel opens.""" + stream = source() + with mock.patch.object( + ArrowTableSource, + "as_table", + autospec=True, + side_effect=ArrowTableSource.as_table, + ) as read: + channel = stream.open_channel() + assert read.call_count == 0 + _ = run(channel.receive) + assert read.call_count == 1 + + +def test_two_channels_on_one_stream_have_their_own_positions() -> None: + """``open_channel()`` twice: each reader gets every row, and the stream stays.""" + stream = source() + + async def read() -> tuple[int, int, int]: + first, second = stream.open_channel(), channel_from_stream(stream) + one = await first.receive() + rest = await second.collect() + return one.num_rows, sum(b.num_rows for b in rest), len(await first.collect()) + + assert run(read) == (7, 7, 0) + assert stream.as_table().num_rows == 7 + + +def test_a_stream_is_read_in_record_batches_of_bounded_size() -> None: + """A complete stream sends record batches of at most ``SOURCE_BATCH_ROWS`` rows.""" + n = SOURCE_BATCH_ROWS + 10 + stream = ArrowTableSource( + pa.table({"k": pa.array(range(n), pa.int32()), "x": pa.array(range(n))}), + tag_columns=["k"], + tag_only_columns=True, + source_id="many", + ) + sizes = [batch.num_rows for batch in run(stream.open_channel().collect)] + assert sizes == [SOURCE_BATCH_ROWS, 10] + + +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 = source().open_channel() + first = await channel.collect() + with pytest.raises(ChannelClosed): + _ = await channel.receive() + return len(first), len(await channel.collect()) + + 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.""" + + batches = batches_of(source(), 2) + + async def read() -> None: + output = OutputChannel(source()) + for batch in batches: + await output.send(batch) + await output.close() + channel = output.open_reader() + _ = await channel.receive() + with pytest.raises(RuntimeError, match="1 record batch"): + _ = await channel.to_stream() + + run(read) + + +# --- An output channel closes into a stream ------------------------------------------ + + +@pytest.mark.parametrize( + "rows", [1, 2, 3, SOURCE_BATCH_ROWS], ids=lambda n: f"{n}_rows" +) +def test_result_is_the_batches_sent_in_order_as_the_nodes_stream(rows: int) -> None: + """After close, ``result()`` is one re-readable stream with the node's identity.""" + stream = source() + batches = batches_of(stream, rows) + + async def write() -> OutputChannel: + output = OutputChannel(stream) + assert isinstance(output, WritableChannel) + assert output.stream is stream + for batch in batches: + await output.send(batch) + await output.close() + return output + + output = run(write) + result = output.result() + assert result is output.result() # one object: the node's kept output + assert same(result.as_table(columns=ALL), R(stream)) + assert same(result.as_table(columns=ALL), R(result)) # re-readable, as rows too + assert result.pipeline_hash() == stream.pipeline_hash() + assert result.data_context_key == stream.data_context_key + assert result.upstreams == stream.upstreams + + +def test_the_identity_of_a_result_with_and_without_a_producer() -> None: + """``result()`` and ``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) + + async def both(stream: Any, batches: list[pa.RecordBatch]) -> tuple[Any, Any]: + output = OutputChannel(stream) + for batch in batches: + await output.send(batch) + await output.close() + return output.result(), await output.open_reader().to_stream() + + for stream in (root, produced): + batches = batches_of(stream, 3) + for made in run(lambda stream=stream, batches=batches: both(stream, batches)): + assert made.producer is stream.producer + assert made.upstreams == stream.upstreams + assert made.pipeline_hash() == stream.pipeline_hash() + assert same(made.as_table(columns=ALL), R(stream)) + assert produced.producer is not None and root.producer is None + + +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 + by rows, with the columns of a run with rows.""" + stream = SelectDataColumns(["subject", "trial", "amplitude", "trace"])(source()) + with_rows = R(stream) + + async def empty() -> tuple[Any, Any]: + output = OutputChannel(stream) + reader = output.open_reader() + await output.close() + await output.close() # a second close does nothing + return output.result(), await reader.to_stream() + + for made in run(empty): + table = made.as_table(columns=ALL) + assert table.num_rows == 0 + assert table.column_names == with_rows.column_names + assert [f.type for f in table.schema] == [f.type for f in with_rows.schema] + assert made.pipeline_hash() == stream.pipeline_hash() + + +def test_send_after_close_is_refused_and_result_needs_a_closed_channel() -> None: + stream = source() + (batch,) = batches_of(stream) + + async def write() -> None: + output = OutputChannel(stream) + await output.send(batch) + with pytest.raises(RuntimeError, match="not closed"): + _ = output.result() + await output.close() + with pytest.raises(ChannelClosed): + await output.send(batch) + assert output.result().as_table().num_rows == 7 + + run(write) + + +def test_a_batch_of_other_columns_is_refused() -> None: + """``send`` checks each record batch against the stream's description.""" + stream = source() + (batch,) = batches_of(stream) + renamed = batch.rename_columns( + ["other" if name == "note" else name for name in batch.schema.names] + ) + retyped = batch.set_column( + batch.schema.get_field_index("amplitude"), + "amplitude", + batch.column("amplitude").cast(pa.float64()), + ) + reflagged = pa.RecordBatch.from_arrays( + batch.columns, + schema=pa.schema( + [ + f.with_nullable(not f.nullable) if f.name == "trial" else f + for f in batch.schema + ] + ), + ) + + async def write() -> None: + output = OutputChannel(stream) + for wrong, said in ( + (renamed, "'other'"), + (retyped, "column 'amplitude' is double"), + (reflagged, "column 'trial' is (not )?nullable"), + ): + with pytest.raises(ValueError, match=said): + await output.send(wrong) + await output.send(batch) + + run(write) + + +def test_what_a_description_does_not_say_is_accepted() -> None: + """A ``null`` column travels as ``large_string``, and a source-info field's + nullability is set over the complete table: neither is a mismatch.""" + stream = ArrowTableStream( + pa.table( + { + "k": pa.array([1, 2, 3], pa.int64()), + "x": pa.array([1.5, 2.5, 3.5], pa.float64()), + "unknown": pa.array([None, None, None], pa.null()), + "_source_x": pa.array( + ["s::r0::x", None, "s::r2::x"], pa.large_string() + ), + } + ), + tag_columns=["k"], + ) + assert stream.as_table().schema.field("unknown").type == pa.null() + + batches = batches_of(stream, 1) + assert len({batch.schema for batch in batches}) == 1 # one schema in transit + + async def through() -> Any: + output = OutputChannel(stream) + for batch in batches: + await output.send(batch) + await output.close() + return output.result() + + result = run(through) + table = result.as_table(columns=ALL) + assert same(table, R(stream)) + assert table.schema.field("unknown").type == pa.large_string() + assert table.schema.field("_source_x").nullable # one token is null + + +# --- Retained output: readers at their own position, send never waits ------------------- + + +def test_a_retained_output_never_makes_send_wait() -> None: + """With ``retain=True`` (the default) the producer runs ahead of every reader.""" + stream = source(40) + batches = batches_of(stream, 1) + assert len(batches) > 3 * BATCH_BUFFER_SIZE + + async def write() -> tuple[int, int]: + output = OutputChannel(stream) + slow = output.open_reader() + for batch in batches: # nobody reads: no send waits + await output.send(batch) + await output.close() + return len(await slow.collect()), output.result().as_table().num_rows + + assert run(write) == (40, 40) + + +def test_a_late_reader_of_a_retained_output_replays_and_continues() -> None: + """``open_reader()`` after the first send, and after close: every batch, in order.""" + stream = source() + batches = batches_of(stream, 2) + + async def write() -> list[list[int]]: + output = OutputChannel(stream) + early = output.open_reader() + await output.send(batches[0]) + late = output.open_reader() + first = (await late.receive()).column("trial").to_pylist() + for batch in batches[1:]: + await output.send(batch) + await output.close() + after = output.open_reader() + trials = [ + [t for b in await reader.collect() for t in b.column("trial").to_pylist()] + for reader in (early, late, after) + ] + return [first, *trials] + + first, early, late, after = run(write) + assert first == [0, 1] + assert early == after == list(range(7)) + assert late == list(range(2, 7)) + + +# --- Output not retained: back-pressure, and the slowest reader sets the pace ------------ + + +def test_without_retain_send_waits_for_room_in_every_reader() -> None: + """Each reader queues ``buffer_size`` record batches; then the producer waits, and + the slowest reader sets the pace, whatever the others have read.""" + stream = source(12) + batches = batches_of(stream, 1) + + async def write() -> tuple[int, bool, int, int]: + output = OutputChannel(stream, retain=False, buffer_size=2) + fast, slow = output.open_reader(), output.open_reader() + sent: list[int] = [] + + async def produce() -> None: + for i, batch in enumerate(batches): + await output.send(batch) + sent.append(i) + 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)] + 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()) + await producer + return ( + sent_while_slow_is_full, + fast_waits_for_the_slow_reader, + len(got_fast) + rest, + len(slow_batches), + ) + + assert run(write) == (2, True, 12, 12) + + +def test_a_reader_that_closes_early_no_longer_holds_the_producer() -> None: + """``close()`` on an input channel unregisters it: the producer stops waiting.""" + stream = source(12) + batches = batches_of(stream, 1) + + async def write() -> tuple[int, int]: + output = OutputChannel(stream, retain=False, buffer_size=1) + leaving, staying = output.open_reader(), output.open_reader() + + async def produce() -> None: + for batch in batches: + await output.send(batch) + await output.close() + + producer = asyncio.ensure_future(produce()) + _ = await leaving.receive() + await leaving.close() + with pytest.raises(ChannelClosed): + _ = await leaving.receive() + rows = len(await staying.collect()) + await producer + return rows, len(batches) + + assert run(write) == (12, 12) + + +def test_without_retain_a_late_reader_is_refused_and_there_is_no_result() -> None: + stream = source() + (batch,) = batches_of(stream) + + async def write() -> None: + output = OutputChannel(stream, retain=False) + reader = output.open_reader() + await output.send(batch) + with pytest.raises(ValueError, match="before the first record batch"): + _ = output.open_reader() + await output.close() + assert len(await reader.collect()) == 1 + with pytest.raises(RuntimeError, match="not retained"): + _ = output.result() + + run(write) + + +def test_a_buffer_must_hold_one_batch() -> None: + with pytest.raises(ValueError, match="buffer_size"): + _ = OutputChannel(source(), retain=False, buffer_size=0) + + +# --- Producer failure and cancellation --------------------------------------------------- + + +@pytest.mark.parametrize("retain", [True, False], ids=["retained", "not_retained"]) +def test_a_failed_producer_is_never_a_normal_end(retain: bool) -> None: + """After ``fail(error)`` every reader's next read raises ``UpstreamFailedError`` + naming the stream, with the producer's error as its cause: also a reader with + batches still unread, and one blocked waiting for a batch.""" + stream = source() + batches = batches_of(stream, 2) + boom = OSError("disk gone") + + 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()) + await asyncio.sleep(0) + output.fail(boom) + output.fail(RuntimeError("a second failure changes nothing")) + await output.close() # nor does a close + with pytest.raises(ChannelClosed): + await output.send(batches[1]) + with pytest.raises(RuntimeError, match="has no result"): + _ = output.result() + errors: list[BaseException] = [] + for read in (unread.receive(), blocked, whole, unread.collect()): + with pytest.raises(UpstreamFailedError) as caught: + _ = await read + errors.append(caught.value) + return errors + + for error in run(write): + assert error.__cause__ is boom + assert repr(stream.label) in str(error) + assert "OSError: disk gone" in str(error) + + +def test_fail_after_close_changes_nothing() -> None: + stream = source() + batches = batches_of(stream, 3) + + async def write() -> int: + output = OutputChannel(stream) + for batch in batches: + await output.send(batch) + await output.close() + output.fail(OSError("too late")) + return (await output.open_reader().to_stream()).as_table().num_rows + + assert run(write) == 7 + + +# --- Operators over channels: failure, cancellation, reading every input to its end ------ + + +def execute( + op: StaticOutputOperatorPod, + streams: Sequence[Any], + inputs: Callable[[], Awaitable[list[InputChannel]]], +) -> OutputChannel: + """Run ``op`` over input channels; return its output channel.""" + + async def go() -> OutputChannel: + output = OutputChannel(op(*streams)) + try: + await op.async_execute_batches(await inputs(), output) + except UpstreamFailedError: + pass + return output + + return run(go) + + +@pytest.mark.parametrize( + "make_op", + [lambda: MapData({"amplitude": "volts"}), lambda: PolarsFilter(constraints={})], + ids=["row_by_row", "barrier"], +) +def test_an_operator_fails_its_output_when_its_input_failed( + make_op: Callable[[], StaticOutputOperatorPod], +) -> None: + """A producer that fails after some batches: the operator's own read raises, it + fails its output with that error, and a barrier operator never computes over the + part it received.""" + stream = source() + batches = batches_of(stream, 2) + op = make_op() + + async def inputs() -> list[InputChannel]: + feed = OutputChannel(stream) + await feed.send(batches[0]) + feed.fail(OSError("disk gone")) + return [feed.open_reader()] + + with mock.patch.object( + type(op), "static_process", autospec=True, side_effect=type(op).static_process + ) as computed: + output = execute(op, [stream], inputs) + assert computed.call_count == 0 + + async def downstream() -> None: + with pytest.raises(UpstreamFailedError) as caught: + _ = await output.open_reader().receive() + assert isinstance(caught.value.__cause__, UpstreamFailedError) + assert isinstance(caught.value.__cause__.__cause__, OSError) + + run(downstream) + with pytest.raises(RuntimeError, match="has no result"): + _ = output.result() + + +def test_a_cancelled_operator_fails_its_output_and_closes_its_input() -> None: + """Cancellation is a failure for the readers downstream, and the operator's input + channel is closed, so its producer no longer waits for it.""" + stream = source(12) + batches = batches_of(stream, 1) + op = MapData({"amplitude": "volts"}) + + async def go() -> tuple[BaseException, int]: + feed = OutputChannel(stream, retain=False, buffer_size=1) + reader = feed.open_reader() + output = OutputChannel(op(stream)) + downstream = output.open_reader() + task = asyncio.ensure_future(op.async_execute_batches([reader], output)) + await feed.send(batches[0]) + _ = await downstream.receive() + _ = task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + # The operator closed its input: the producer is never held again. + for batch in batches[1:]: + await feed.send(batch) + with pytest.raises(UpstreamFailedError) as caught: + _ = await downstream.receive() + cause = caught.value.__cause__ + assert cause is not None + return cause, len(batches) + + cause, sent = run(go) + assert isinstance(cause, asyncio.CancelledError) and sent == 12 + + +def test_an_operator_reads_its_input_to_the_end_and_closes_its_output() -> None: + """The normal end: every input batch is read, the output is closed, and its result + is the operator's sync result, built from rows.""" + stream = source() + op = SelectDataColumns(["subject", "trial", "note"]) + + async def inputs() -> list[InputChannel]: + 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 + rows' table for every way the batches are cut, and no batch gives zero rows.""" + stream = source() + for rows in (1, 2, 5, 7): + made = stream_from_batches(stream, batches_of(stream, rows)) + assert same(made.as_table(columns=ALL), R(stream)) + assert stream_from_batches(stream, []).as_table().num_rows == 0 diff --git a/tests/test_core/operators/test_record_batch_execution.py b/tests/test_core/operators/test_record_batch_execution.py new file mode 100644 index 000000000..82d149433 --- /dev/null +++ b/tests/test_core/operators/test_record_batch_execution.py @@ -0,0 +1,314 @@ +"""Operators over channels of Arrow record batches equal the sync path (ITL-1347, L6). + +Every operator has one body, ``static_process``. Its Arrow-record-batch form +(``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 +sync call; ``Batch`` batches consecutive arrivals. + +For every case of the async/sync matrix (``test_async_sync_equivalence.CASES``) the +output channel's result must be the table today's code builds from the sync rows +(``R``: same columns, order, Arrow types, nullability, field metadata, values and row +order), however the input arrives: in one record batch, one row per batch, or batches +of mixed sizes. The same holds for inputs that come from an operator instead of a +source, and for inputs with no rows, where the result is the typed zero-row stream. +""" + +from __future__ import annotations + +import asyncio +import itertools +import math +from collections.abc import Sequence +from typing import Any + +import pyarrow as pa +import pytest + +import orcapod.core.operators as operators +from orcapod.channels import InputChannel, OutputChannel +from orcapod.core.operators import Batch +from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod +from orcapod.protocols.core_protocols import StreamProtocol +from tests.test_core.operators.test_async_sync_equivalence import ( + AFTER_OPERATOR_CASES, + CASES, + Case, + _zero_row_cases, + source_a, +) + +pytestmark = [ + pytest.mark.filterwarnings("ignore::orcapod.errors.SemiJoinIgnoredColumnWarning"), + pytest.mark.filterwarnings("ignore::orcapod.errors.ProvisionalHashWarning"), +] + +ALL = {"system_tags": True, "source": True} +TIMEOUT = 20.0 + +# How an input's rows arrive: the sizes of its record batches, repeated to the end. +LAYOUTS: dict[str, tuple[int, ...] | None] = { + "one_batch": None, + "one_row_per_batch": (1,), + "mixed_sizes": (2, 1, 3), +} + + +def _cut(table: pa.Table, sizes: tuple[int, ...] | None) -> list[pa.RecordBatch]: + """``table`` as record batches of the given sizes, in order.""" + whole = table.combine_chunks() + if sizes is None: + return whole.to_batches() + batches: list[pa.RecordBatch] = [] + start = 0 + for size in itertools.cycle(sizes): + if start >= whole.num_rows: + break + batches.extend(whole.slice(start, size).to_batches()) + start += size + return batches + + +async def _channel( + stream: StreamProtocol, sizes: tuple[int, ...] | None +) -> InputChannel: + """An input channel delivering ``stream``'s rows in record batches of ``sizes``.""" + batches = await stream.open_channel().collect() + if sizes is None or not batches: + return stream.open_channel() + rows = pa.Table.from_batches(batches) + feed = OutputChannel(stream) + for batch in _cut(rows, sizes): + await feed.send(batch) + await feed.close() + return feed.open_reader() + + +def run_on_channels( + op: StaticOutputOperatorPod, + sources: Sequence[StreamProtocol], + sizes: tuple[int, ...] | None, +) -> StreamProtocol: + """Run ``op`` over input channels of ``sources``; return its output as a stream.""" + + async def go() -> StreamProtocol: + output = OutputChannel(op(*sources)) + inputs = [await _channel(source, sizes) for source in sources] + await asyncio.wait_for(op.async_execute_batches(inputs, output), TIMEOUT) + return output.result() + + return asyncio.run(go()) + + +def R(stream: StreamProtocol) -> pa.Table | None: + """The table today's code builds from ``stream``'s rows; ``None`` with no row.""" + rows = list(stream.iter_data()) + return StaticOutputOperatorPod._rows_to_table(rows)[0] if rows else None + + +def _same_value(value: Any, expected: Any) -> bool: + """Equality of two Python values of a cell, a NaN equal to a NaN.""" + if isinstance(value, float) and isinstance(expected, float): + return value == expected or (math.isnan(value) and math.isnan(expected)) + if isinstance(value, dict) and isinstance(expected, dict): + return value.keys() == expected.keys() and all( + _same_value(value[key], expected[key]) for key in value + ) + if isinstance(value, (list, tuple)) and isinstance(expected, (list, tuple)): + return len(value) == len(expected) and all( + _same_value(a, b) for a, b in zip(value, expected) + ) + return type(value) is type(expected) and value == expected + + +def assert_same_table(table: pa.Table, expected: pa.Table) -> None: + """Assert one schema, field for field with metadata, and the same rows in order.""" + assert table.schema.names == expected.schema.names + for field, wanted in zip(table.schema, expected.schema): + assert field.equals(wanted, check_metadata=True), (field, wanted) + assert table.schema.equals(expected.schema, check_metadata=True) + assert table.num_rows == expected.num_rows + for name in table.column_names: + # The storage of a logical type: its values as stored, not as decoded. + column, wanted = (t.column(name).combine_chunks() for t in (table, expected)) + assert _same_value(column.to_pylist(), wanted.to_pylist()), name + + +def assert_equals_sync(case: Case, sizes: tuple[int, ...] | None) -> None: + """Assert the channel result of ``case`` is the sync result built from rows.""" + sources = case.make_sources() + expected = R(case.make_op()(*sources)) + result = run_on_channels(case.make_op(), sources, sizes) + table = result.as_table(columns=ALL) + if expected is None: + assert table.num_rows == 0 + return + assert_same_table(table, expected) + # The result is an ordinary stream: its own rows build the same table again. + again = R(result) + assert again is not None + assert_same_table(again, expected) + + +@pytest.mark.parametrize("layout", list(LAYOUTS)) +@pytest.mark.parametrize("case", CASES, ids=[case.label for case in CASES]) +def test_the_channel_result_is_the_sync_result(case: Case, layout: str) -> None: + """Every operator, every way its input's record batches are cut.""" + assert_equals_sync(case, LAYOUTS[layout]) + + +@pytest.mark.parametrize("layout", ["one_row_per_batch", "mixed_sizes"]) +@pytest.mark.parametrize("case", AFTER_OPERATOR_CASES) +def test_the_channel_result_is_the_sync_result_after_an_operator( + case: Case, layout: str +) -> None: + """Inputs that are an operator's output, not a source: the description (pipeline + hash, system-tag names) is the input's stream on both paths.""" + assert_equals_sync(case, LAYOUTS[layout]) + + +@pytest.mark.parametrize("case", _zero_row_cases()) +def test_inputs_with_no_rows_give_the_typed_zero_row_result(case: Case) -> None: + """All inputs empty, or one of several: the result has no row and the columns and + Arrow types of a run with rows, typed by the description and never by rows.""" + sources = case.make_sources() + sync = case.make_op()(*sources) + expected = R(sync) + result = run_on_channels(case.make_op(), sources, (1,)) + table = result.as_table(columns=ALL) + if expected is not None: + assert_same_table(table, expected) + return + assert table.num_rows == 0 + assert result.keys() == sync.keys() + assert result.output_schema(columns=ALL) == sync.output_schema(columns=ALL) + assert result.pipeline_hash() == sync.pipeline_hash() + # The Arrow types are those of the sync result with no rows, column for column. + sync_table = sync.as_table(columns=ALL) + assert sorted(table.column_names) == sorted(sync_table.column_names) + for name in table.column_names: + assert table.schema.field(name).type == sync_table.schema.field(name).type, name + + +def test_every_operator_is_in_the_matrix() -> None: + """A new operator fails here until the matrix has a case for it.""" + covered = {type(case.make_op()).__name__ for case in CASES} + exported = { + name + for name in operators.__all__ + if isinstance(getattr(operators, name), type) + and issubclass(getattr(operators, name), StaticOutputOperatorPod) + } + assert exported - covered == set() + + +ROW_BY_ROW = { + "SelectTagColumns", + "SelectDataColumns", + "DropTagColumns", + "DropDataColumns", + "SelectColumns", + "DropColumns", + "MapTags", + "MapData", + "MapColumns", + "AddTags", + "DropNulls", + "Index", + "Pick", +} + + +def test_the_row_by_row_operators_are_exactly_these() -> None: + """The operators applied per record batch, as the design lists them; every other + operator reads all of its input first (``Batch`` batches arrivals).""" + declared = { + name + for name in operators.__all__ + if isinstance(getattr(operators, name), type) + and getattr(getattr(operators, name), "ROW_BY_ROW", False) + } + assert declared == ROW_BY_ROW + + +@pytest.mark.parametrize( + "case", + [case for case in CASES if type(case.make_op()).__name__ in ROW_BY_ROW], + ids=lambda case: case.label, +) +def test_a_row_by_row_operator_sends_each_batch_as_it_arrives(case: Case) -> None: + """One result record batch per input record batch, before the next is read: with a + queue of one batch and no retained output, the operator can only go on when its + reader has taken the batch before.""" + (source,) = case.make_sources() + op = case.make_op() + expected = R(case.make_op()(source)) + assert expected is not None + + async def go() -> tuple[list[int], pa.Table]: + feed = OutputChannel(source, retain=False, buffer_size=1) + reader = feed.open_reader() + output = OutputChannel(op(source), retain=False, buffer_size=1) + results = output.open_reader() + task = asyncio.ensure_future(op.async_execute_batches([reader], output)) + rows = pa.Table.from_batches(await source.open_channel().collect()) + received: list[pa.RecordBatch] = [] + sizes: list[int] = [] + for batch in _cut(rows, (1,)): + await asyncio.wait_for(feed.send(batch), TIMEOUT) + await asyncio.sleep(0.001) + sizes.append(len(received)) + # Whatever this input row gave is there before the next row is sent. + while output._sent > len(received): # pyright: ignore[reportPrivateUsage] + received.append(await asyncio.wait_for(results.receive(), TIMEOUT)) + await feed.close() + received.extend(await asyncio.wait_for(results.collect(), TIMEOUT)) + await task + return sizes, pa.Table.from_batches(received) if received else rows.slice(0, 0) + + _, table = asyncio.run(go()) + assert table.num_rows == expected.num_rows + assert table.to_pylist() == expected.to_pylist() + + +@pytest.mark.parametrize("batch_size", [2, 3, 5]) +@pytest.mark.parametrize("drop_partial_batch", [False, True]) +@pytest.mark.parametrize("layout", list(LAYOUTS)) +def test_batch_groups_consecutive_arrivals_whatever_the_record_batches( + batch_size: int, drop_partial_batch: bool, layout: str +) -> None: + """``Batch(n)`` batches every ``n`` rows that arrive, across record batch + boundaries; the rows left at the end make the last batch unless dropped.""" + case = Case( + "batch", + lambda: Batch(batch_size=batch_size, drop_partial_batch=drop_partial_batch), + lambda: (source_a(with_data_tags=True),), + ) + assert_equals_sync(case, LAYOUTS[layout]) + + +def test_batch_sends_each_full_batch_before_the_input_ends() -> None: + """Streaming: the first batch is out while the input is still open.""" + source = source_a() + op = Batch(batch_size=2) + + async def go() -> tuple[int, int]: + feed = OutputChannel(source, retain=False, buffer_size=1) + reader = feed.open_reader() + output = OutputChannel(op(source)) + results = output.open_reader() + task = asyncio.ensure_future(op.async_execute_batches([reader], output)) + 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) + assert not task.done() + await feed.send(one_row[2]) + await feed.close() + rest = await asyncio.wait_for(results.collect(), TIMEOUT) + await task + return first.num_rows, sum(batch.num_rows for batch in rest) + + assert asyncio.run(go()) == (1, 1) From 485de6ffba73514bff3a4b751351131c547fcd7f Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 02:33:27 -0800 Subject: [PATCH 02/12] test(channels): compare Arrow types of a zero-row result; StreamProtocol.open_channel waits for part 2 (ITL-1362) Co-Authored-By: Claude Opus 5.5 --- src/orcapod/protocols/core_protocols/streams.py | 13 ------------- .../operators/test_record_batch_execution.py | 5 ++++- 2 files changed, 4 insertions(+), 14 deletions(-) diff --git a/src/orcapod/protocols/core_protocols/streams.py b/src/orcapod/protocols/core_protocols/streams.py index b36e8dd1a..010d29232 100644 --- a/src/orcapod/protocols/core_protocols/streams.py +++ b/src/orcapod/protocols/core_protocols/streams.py @@ -16,7 +16,6 @@ from orcapod.types import ColumnConfig, Schema if TYPE_CHECKING: - from orcapod.channels import InputChannel import pandas as pd import polars as pl import pyarrow as pa @@ -184,18 +183,6 @@ def iter_data(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: """ ... - def open_channel(self) -> "InputChannel": - """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. - - Returns: - The input channel. - """ - ... - def async_iter_data(self) -> AsyncIterator[tuple[TagProtocol, DataProtocol]]: """ Generates asynchronous iterator over (tag, data) pairs in the stream. diff --git a/tests/test_core/operators/test_record_batch_execution.py b/tests/test_core/operators/test_record_batch_execution.py index 82d149433..719c0844a 100644 --- a/tests/test_core/operators/test_record_batch_execution.py +++ b/tests/test_core/operators/test_record_batch_execution.py @@ -182,7 +182,10 @@ def test_inputs_with_no_rows_give_the_typed_zero_row_result(case: Case) -> None: return assert table.num_rows == 0 assert result.keys() == sync.keys() - assert result.output_schema(columns=ALL) == sync.output_schema(columns=ALL) + # Arrow types are compared, not the Python schemas: the sync stream's Python schema + # is its operator's prediction, which can differ from the Python reading of the + # same Arrow types (``large_list`` predicted ``list[int | None]``, read + # ``list[int]``), with rows as without them; a stream rebuilt from Arrow reads them. assert result.pipeline_hash() == sync.pipeline_hash() # The Arrow types are those of the sync result with no rows, column for column. sync_table = sync.as_table(columns=ALL) From 0388a7fb1f6fbdc610444eb661bd1e12cda14b97 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 02:34:49 -0800 Subject: [PATCH 03/12] docs(channels): rule for record-batch channels and ROW_BY_ROW; fail() is seen at once (ITL-1362) Co-Authored-By: Claude Opus 5.5 --- .zed/rules | 11 +++++++++++ CLAUDE.md | 12 ++++++++++++ src/orcapod/channels.py | 6 ++++-- 3 files changed, 27 insertions(+), 2 deletions(-) diff --git a/.zed/rules b/.zed/rules index 0ca1db43b..7c89838d1 100644 --- a/.zed/rules +++ b/.zed/rules @@ -1298,6 +1298,17 @@ data. The rules: datagrams' Arrow tables (as_table()), never from as_dict() values, and take the data 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.channels.InputChannel / OutputChannel carry a stream's rows as Arrow record batches. + A channel owns no description: an input channel refers to its stream (stream.open_channel(), + channel_from_stream), an output channel to the stream it produces, and + OutputChannel.result() closes it into that stream. A stream is made from record batches in + one place, stream_from_batches; never build one elsewhere. An operator's record-batch form + (async_execute_batches, renamed async_execute when wired) applies its one static_process + body: per record batch when the class declares ROW_BY_ROW = True (each output row comes from + one input row), otherwise as a barrier over the whole input (to_stream()); Batch with a size + has its own form, grouping rows by arrival. A new operator whose output rows each come from + one input row declares ROW_BY_ROW; write no other per-operator batch code. - The type converter keys synthesized struct classes by the large-normalized struct, so struct and struct are one Python type (a workaround, TODO(ITL-841)). diff --git a/CLAUDE.md b/CLAUDE.md index 18c5d6f25..32344498e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1345,6 +1345,18 @@ data. The rules: datagrams' Arrow tables (`as_table()`), never from `as_dict()` values, and take the data 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.channels.InputChannel` / `OutputChannel` carry a stream's rows as Arrow record + batches. A channel owns no description: an input channel refers to its stream + (`stream.open_channel()`, `channel_from_stream`), an output channel to the stream it + produces, and `OutputChannel.result()` closes it into that stream. A stream is made from + record batches in one place, `stream_from_batches`; never build one elsewhere. An operator's + record-batch form (`async_execute_batches`, renamed `async_execute` when wired) applies its + one `static_process` body: per record batch when the class declares `ROW_BY_ROW = True` + (each output row comes from one input row), otherwise as a barrier over the whole input + (`to_stream()`); `Batch` with a size has its own form, grouping rows by arrival. A new + operator whose output rows each come from one input row declares `ROW_BY_ROW`; write no + other per-operator batch code. - The type converter keys synthesized struct classes by the large-normalized struct, so `struct` and `struct` are one Python type (a workaround, `TODO(ITL-841)`). diff --git a/src/orcapod/channels.py b/src/orcapod/channels.py index c74f4cc0c..0763fa01a 100644 --- a/src/orcapod/channels.py +++ b/src/orcapod/channels.py @@ -747,8 +747,10 @@ async def close(self) -> None: def fail(self, error: BaseException) -> None: """End the output with the producer's failure or cancellation. - Every reader's next read raises ``UpstreamFailedError``, never a normal end. - Does nothing on a channel already closed or failed. + Every reader's next read raises ``UpstreamFailedError`` (its cause is + ``error``), never a normal end. The failure is seen at once: record batches a + reader has not yet read are not delivered first, so no consumer acts on part of + a failed output. Does nothing on a channel already closed or failed. Args: error: The producer's error. From 2a433e6fe25ec752bdb2502e7b60efeb453f43a7 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 02:38:33 -0800 Subject: [PATCH 04/12] test(channels): type fixes in the record-batch tests (ITL-1362) Co-Authored-By: Claude Opus 5.5 --- tests/test_channels/test_record_batch_channels.py | 4 ++-- .../test_core/operators/test_record_batch_execution.py | 10 +++++----- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/tests/test_channels/test_record_batch_channels.py b/tests/test_channels/test_record_batch_channels.py index 740d62946..b2f66a657 100644 --- a/tests/test_channels/test_record_batch_channels.py +++ b/tests/test_channels/test_record_batch_channels.py @@ -78,7 +78,7 @@ def R(stream: Any) -> pa.Table: def same(table: pa.Table, expected: pa.Table) -> bool: """Whether two tables have one schema (metadata included) and the same rows.""" - return table.schema.equals(expected.schema, check_metadata=True) and ( + return table.schema.equals(expected.schema, check_metadata=True) and bool( table.combine_chunks().equals(expected.combine_chunks()) ) @@ -371,7 +371,7 @@ def test_a_late_reader_of_a_retained_output_replays_and_continues() -> None: stream = source() batches = batches_of(stream, 2) - async def write() -> list[list[int]]: + async def write() -> list[list[Any]]: output = OutputChannel(stream) early = output.open_reader() await output.send(batches[0]) diff --git a/tests/test_core/operators/test_record_batch_execution.py b/tests/test_core/operators/test_record_batch_execution.py index 719c0844a..2de95ca57 100644 --- a/tests/test_core/operators/test_record_batch_execution.py +++ b/tests/test_core/operators/test_record_batch_execution.py @@ -27,7 +27,7 @@ import pytest import orcapod.core.operators as operators -from orcapod.channels import InputChannel, OutputChannel +from orcapod.channels import InputChannel, OutputChannel, channel_from_stream from orcapod.core.operators import Batch from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod from orcapod.protocols.core_protocols import StreamProtocol @@ -74,9 +74,9 @@ async def _channel( stream: StreamProtocol, sizes: tuple[int, ...] | None ) -> InputChannel: """An input channel delivering ``stream``'s rows in record batches of ``sizes``.""" - batches = await stream.open_channel().collect() + batches = await channel_from_stream(stream).collect() if sizes is None or not batches: - return stream.open_channel() + return channel_from_stream(stream) rows = pa.Table.from_batches(batches) feed = OutputChannel(stream) for batch in _cut(rows, sizes): @@ -255,7 +255,7 @@ async def go() -> tuple[list[int], pa.Table]: output = OutputChannel(op(source), retain=False, buffer_size=1) results = output.open_reader() task = asyncio.ensure_future(op.async_execute_batches([reader], output)) - rows = pa.Table.from_batches(await source.open_channel().collect()) + rows = pa.Table.from_batches(await channel_from_stream(source).collect()) received: list[pa.RecordBatch] = [] sizes: list[int] = [] for batch in _cut(rows, (1,)): @@ -302,7 +302,7 @@ async def go() -> tuple[int, int]: output = OutputChannel(op(source)) results = output.open_reader() task = asyncio.ensure_future(op.async_execute_batches([reader], output)) - rows = pa.Table.from_batches(await source.open_channel().collect()) + rows = pa.Table.from_batches(await channel_from_stream(source).collect()) one_row = _cut(rows, (1,)) await feed.send(one_row[0]) await feed.send(one_row[1]) From 210b791b5d37c3a7097a6340dcb1ffa624b52b33 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 02:42:05 -0800 Subject: [PATCH 05/12] refactor(channels): record-batch channels in core/record_batch_channels, conversions beside the operator helpers, protocols in channels.py; no import cycle (ITL-1362) StreamBase.open_channel is deferred to part 2: any form of it is an import cycle (base -> channel classes -> ArrowTableStream -> base). channel_from_stream(stream) opens a channel. Co-Authored-By: Claude Opus 5.5 --- .zed/rules | 24 +- CLAUDE.md | 25 +- src/orcapod/channels.py | 549 ++---------------- src/orcapod/core/operators/batch.py | 6 +- .../core/operators/static_output_pod.py | 161 ++++- src/orcapod/core/record_batch_channels.py | 416 +++++++++++++ src/orcapod/core/streams/base.py | 21 +- .../test_record_batch_channels.py | 43 +- .../operators/test_record_batch_execution.py | 6 +- 9 files changed, 666 insertions(+), 585 deletions(-) create mode 100644 src/orcapod/core/record_batch_channels.py diff --git a/.zed/rules b/.zed/rules index 7c89838d1..866829ede 100644 --- a/.zed/rules +++ b/.zed/rules @@ -1299,16 +1299,20 @@ 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.channels.InputChannel / OutputChannel carry a stream's rows as Arrow record batches. - A channel owns no description: an input channel refers to its stream (stream.open_channel(), - channel_from_stream), an output channel to the stream it produces, and - OutputChannel.result() closes it into that stream. A stream is made from record batches in - one place, stream_from_batches; never build one 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. + 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 orcapod.channels, which imports nothing of the core (keep it so: + 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_columns, transport_schema); never build a stream from record batches elsewhere. An + operator's record-batch form (async_execute_batches, renamed async_execute when wired) + applies its one static_process body: per record batch when the class declares ROW_BY_ROW = + True (each output row comes from one input row), otherwise as a barrier over the whole input + (to_stream()); Batch with a size has its own form, grouping rows by arrival. A new operator + whose output rows each come from one input row declares ROW_BY_ROW; write no other + per-operator batch code. - The type converter keys synthesized struct classes by the large-normalized struct, so struct and struct are one Python type (a workaround, TODO(ITL-841)). diff --git a/CLAUDE.md b/CLAUDE.md index 32344498e..3c0876c09 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1346,17 +1346,20 @@ 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.channels.InputChannel` / `OutputChannel` carry a stream's rows as Arrow record - batches. A channel owns no description: an input channel refers to its stream - (`stream.open_channel()`, `channel_from_stream`), an output channel to the stream it - produces, and `OutputChannel.result()` closes it into that stream. A stream is made from - record batches in one place, `stream_from_batches`; never build one 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. + `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 `orcapod.channels`, which imports nothing of the core (keep it so: + 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_columns`, `transport_schema`); never build a stream from + record batches elsewhere. An operator's record-batch form (`async_execute_batches`, renamed + `async_execute` when wired) applies its one `static_process` body: per record batch when the + class declares `ROW_BY_ROW = True` (each output row comes from one input row), otherwise as + a barrier over the whole input (`to_stream()`); `Batch` with a size has its own form, + grouping rows by arrival. A new operator whose output rows each come from one input row + declares `ROW_BY_ROW`; write no other per-operator batch code. - The type converter keys synthesized struct classes by the large-normalized struct, so `struct` and `struct` are one Python type (a workaround, `TODO(ITL-841)`). diff --git a/src/orcapod/channels.py b/src/orcapod/channels.py index 0763fa01a..ac20150d9 100644 --- a/src/orcapod/channels.py +++ b/src/orcapod/channels.py @@ -3,29 +3,24 @@ Provides bounded async channels with close/done signaling, backpressure, and fan-out (broadcast) support. -Channels of Arrow record batches (ITL-1347): ``InputChannel`` and ``OutputChannel`` are -the forms of ``ReadableChannel`` and ``WritableChannel`` that carry a stream's rows as -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. An -input channel is opened from a stream (``channel_from_stream``, ``stream.open_channel()``) -or from an output channel (``OutputChannel.open_reader``); an output channel, once -closed, gives its rows back as a stream (``OutputChannel.result``). Every conversion -between streams and channels is in this module. +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 concrete channels are in +``orcapod.core.record_batch_channels``; this module imports nothing of Orcapod's core, so +every part of it may use these protocols. """ from __future__ import annotations import asyncio -from collections import deque -from collections.abc import AsyncIterator, Sequence +from collections.abc import AsyncIterator from dataclasses import dataclass, field -from typing import TYPE_CHECKING, Any, Generic, Protocol, TypeVar, runtime_checkable - -import pyarrow as pa - -from orcapod.errors import UpstreamFailedError +from typing import TYPE_CHECKING, Generic, Protocol, TypeVar, runtime_checkable if TYPE_CHECKING: + import pyarrow as pa + from orcapod.protocols.core_protocols import StreamProtocol T = TypeVar("T") @@ -321,265 +316,19 @@ async def close(self) -> None: # Channels of Arrow record batches (ITL-1347) # --------------------------------------------------------------------------- -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.""" - - -def transport_columns( - table: pa.Table, keys: tuple[Sequence[str], Sequence[str]] -) -> pa.Table: - """Return ``table`` as the columns passed between nodes, for a channel. - - The transport columns of a stream are what a table built from its rows holds: user - tags, system tags, data and source info, in that order, with no data-context and no - meta (``__``) column, and ``null`` as ``large_string`` (a row's datagram stores a - ``null`` column so). The source info follows the stream's data keys, a data-tag's - first, as each row lists it. No value is changed. - - One property is left for the complete table: whether a source-info field is - nullable follows its tokens, so it cannot be decided on one record batch of many. - Here every source-info field is nullable, so all record batches of one channel have - one schema; ``stream_from_batches`` sets the flags over all of them. - - Args: - table: A stream's table with its system tags and source info - (``ZERO_ROW_INPUT_COLUMNS``), of any number of rows. - keys: The stream's tag keys and data keys (``stream.keys()``). - - Returns: - The transport columns, in row order. - """ - # TODO(ITL-1360): this is steps 1 to 4 of the row-built form of the design - # (docs/dev/specs/itl-1347-job-table-transport.md); stage 2 defines that form once, - # and this function then calls it. - from orcapod.system_constants import constants - from orcapod.utils import arrow_utils - - tag_keys, data_keys = keys - names = table.column_names - system_tags = [n for n in names if n.startswith(constants.SYSTEM_TAG_PREFIX)] - source_info = [n for n in names if n.startswith(constants.SOURCE_PREFIX)] - # A row lists its source info in the order of its data columns. - by_data_key = [f"{constants.SOURCE_PREFIX}{name}" for name in data_keys] - source_info = [n for n in by_data_key if n in source_info] + [ - n - for n in source_info - if n not in by_data_key - and not n.removeprefix(constants.SOURCE_PREFIX).startswith( - constants.META_PREFIX - ) - ] - placed = {*tag_keys, *system_tags, *source_info, constants.CONTEXT_KEY} - data = [ - n - for n in names - if n not in placed - and not n.startswith((constants.META_PREFIX, constants.SOURCE_PREFIX)) - ] - kept = arrow_utils.normalize_table_to_large_types( - table.select([*tag_keys, *system_tags, *data, *source_info]) - ) - schema = pa.schema( - [ - column.with_nullable(True) - if column.name.startswith(constants.SOURCE_PREFIX) - else column - for column in kept.schema - ] - ) - return pa.Table.from_arrays(kept.columns, schema=schema) - - -def _declared_transport_schema(stream: StreamProtocol) -> pa.Schema | None: - """Return the schema ``stream``'s record batches have, from its description. - - Never computes, reads or polls a row: it is the schema of the stream's zero-row - input, as its record batches carry it (``transport_columns``). - - Args: - stream: The describing stream. - - Returns: - The schema, or ``None`` for a stream that cannot say its Arrow types without - rows (an unbound input slot, a source that has not polled yet). - """ - # TODO(ITL-1360): ``stream.arrow_schema()``, once every stream has it. - from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod - from orcapod.core.streams.base import ZERO_ROW_INPUT_COLUMNS - - typed = StaticOutputOperatorPod._zero_row_input(stream) # pyright: ignore[reportPrivateUsage] # the zero-row form of an input - if typed is None: - return None - return transport_columns( - typed.as_table(columns=ZERO_ROW_INPUT_COLUMNS), stream.keys() - ).schema - - -def stream_from_batches( - stream: StreamProtocol, batches: Sequence[pa.RecordBatch] -) -> StreamProtocol: - """Return the Arrow record batches of ``stream``'s rows as a stream. - - The one place a stream is made from Arrow record batches: what an output channel - gives once closed (``OutputChannel.result``) and what an input channel delivered - (``InputChannel.to_stream``). The batches are put under one another in the order - given, each system-tag and source-info field is flagged nullable only when one of - its values is null (decided over the complete table, never per batch), and the - table is wrapped with ``stream``'s identity: its producer, upstreams, pipeline hash and data - context. With no batch it is ``stream``'s zero-row input, typed by its description - and never by rows. - Args: - stream: The describing stream: the node or stream the rows are of. - batches: Its rows as transport columns (``transport_columns``), in order. +class RecordBatchInput(Protocol): + """A single-pass reader of a stream's Arrow record batches. - Returns: - A complete, re-readable stream over the rows. + The Arrow-record-batch form of ``ReadableChannel``; ``InputChannel`` of + ``orcapod.core.record_batch_channels`` is the implementation. Its description is + its ``stream``, known before the first batch. """ - from orcapod.core.data_tags import stream_data_tags - from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod - - if not batches: - return StaticOutputOperatorPod._materialize_upstream([], stream) # pyright: ignore[reportPrivateUsage] # the zero-row input of an operator - table = _flagged_by_values(pa.Table.from_batches(list(batches))) - return StaticOutputOperatorPod._as_upstream_stream( # pyright: ignore[reportPrivateUsage] # the identity of a successor's input - table, stream.keys()[0], stream_data_tags(stream), stream - ) - - -def _flagged_by_values(table: pa.Table) -> pa.Table: - """Flag each system-tag and source-info field nullable only when it holds a null. - - What a table built from rows has: a row states its system tags and its source-info - tokens as values, so those fields are non-nullable unless a value is missing. It is - decided over the complete table, never per record batch (two batches of one - channel would then have two schemas). The same arrays under the new flags. - - Args: - table: The complete table of a stream's transport columns. - - Returns: - The table with those fields' flags set by their values. - """ - from orcapod.system_constants import constants - - by_values = (constants.SYSTEM_TAG_PREFIX, constants.SOURCE_PREFIX) - schema = pa.schema( - [ - column.with_nullable(table.column(i).null_count > 0) - if column.name.startswith(by_values) - else column - for i, column in enumerate(table.schema) - ] - ) - return pa.Table.from_arrays(table.columns, schema=schema) - - -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: - self._stream = stream - self._batches: deque[pa.RecordBatch] | None = None - - async def next(self) -> pa.RecordBatch | None: - if self._batches is None: - # On the first read, not when the channel is opened: opening computes - # nothing. - from orcapod.core.streams.base import ZERO_ROW_INPUT_COLUMNS - - table = transport_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: - self._batches = deque() - - -class _OutputFeed: - """One reader of an output channel, with its own position.""" - - def __init__(self, output: OutputChannel) -> None: - self._output = output - self.open = True - # With retained batches: this reader's position among them. Without: the - # batches sent and not yet read by this reader. - self.position = 0 - self.queue: deque[pa.RecordBatch] = deque() - - async def next(self) -> pa.RecordBatch | None: - output = self._output - while self.open: - if output._error is not None: # pyright: ignore[reportPrivateUsage] - raise output._upstream_failed() # pyright: ignore[reportPrivateUsage] - if output._retain: # pyright: ignore[reportPrivateUsage] - if self.position < len(output._batches): # pyright: ignore[reportPrivateUsage] - self.position += 1 - return output._batches[self.position - 1] # pyright: ignore[reportPrivateUsage] - elif self.queue: - batch = self.queue.popleft() - output._notify() # pyright: ignore[reportPrivateUsage] # room for the producer - return batch - if output._closed: # pyright: ignore[reportPrivateUsage] - return None - await output._changed.wait() # pyright: ignore[reportPrivateUsage] - return None - - def close(self) -> None: - self.open = False - self.queue.clear() - self._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`` (``stream.open_channel()``) or by - ``OutputChannel.open_reader``, never directly. - """ - - def __init__(self, stream: StreamProtocol, feed: _BatchFeed) -> None: - self._stream = stream - self._feed = feed - self._received = 0 - self._ended = 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. @@ -588,272 +337,40 @@ async def receive(self) -> pa.RecordBatch: ChannelClosed: At the end, and after ``close``. UpstreamFailedError: If the producer failed or was cancelled. """ - if self._ended: - raise ChannelClosed() - batch = await self._feed.next() - if batch is None: - self._ended = True - raise ChannelClosed() - self._received += 1 - return batch + ... def __aiter__(self) -> AsyncIterator[pa.RecordBatch]: - return self - - async def __anext__(self) -> pa.RecordBatch: - try: - return await self.receive() - except ChannelClosed: - raise StopAsyncIteration + """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.""" - 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. - 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()) + """Read to the end and return what the channel delivered, as a stream.""" + ... async def close(self) -> None: """Stop reading. The producer no longer waits for this reader.""" - self._ended = True - self._feed.close() - + ... -class OutputChannel: - """The producer side of a node's async output, in Arrow record batches. - The Arrow-record-batch form of ``WritableChannel``. Its ``stream`` is the producing - node, or the stream the output is of: the description of every record batch sent. - Each consumer reads through its own input channel (``open_reader``), which is the - fan-out. Once closed, ``result`` gives the output as an ordinary stream. +class RecordBatchOutput(Protocol): + """The producer side of a stream's Arrow record batches. - Args: - stream: The describing stream. - retain: Keep every record batch sent, so that ``result`` can give the output - stream. Readers then read the kept batches at their own position, a reader - may be opened at any time, and ``send`` never waits. Without it, ``send`` - waits until every reader has room, so the slowest reader sets the pace, - and ``result`` raises. - buffer_size: Without ``retain``, how many record batches each reader queues - before ``send`` waits. + The Arrow-record-batch form of ``WritableChannel``; ``OutputChannel`` of + ``orcapod.core.record_batch_channels`` is the implementation. """ - def __init__( - self, - stream: StreamProtocol, - *, - retain: bool = True, - buffer_size: int = BATCH_BUFFER_SIZE, - ) -> None: - if buffer_size < 1: - raise ValueError(f"buffer_size must be at least 1, got {buffer_size}") - self._stream = stream - self._retain = retain - self._buffer_size = buffer_size - self._batches: list[pa.RecordBatch] = [] - self._readers: list[_OutputFeed] = [] - self._sent = 0 - self._closed = False - self._error: BaseException | None = None - self._result: StreamProtocol | None = None - # The schema every record batch must have: the description's, or the first - # batch's when the stream cannot say its Arrow types without rows. - self._schema: pa.Schema | None = None - self._schema_known = False - self._changed = asyncio.Event() - - @property - def stream(self) -> StreamProtocol: - """The stream whose rows are written here: the description.""" - return self._stream - - def _notify(self) -> None: - """Wake everything waiting on this channel: readers and a waiting ``send``.""" - changed, self._changed = self._changed, asyncio.Event() - changed.set() - - def _upstream_failed(self) -> UpstreamFailedError: - error = self._error - assert error is not None - failure = UpstreamFailedError( - f"The input from {_named(self._stream)} did not finish: its producer " - + f"failed with {type(error).__name__}: {error}" - ) - failure.__cause__ = error - return failure - - def _check_schema(self, batch: pa.RecordBatch) -> None: - """Raise unless ``batch`` has the schema of this channel's record batches.""" - if not self._schema_known: - self._schema = _declared_transport_schema(self._stream) - self._schema_known = True - if self._schema is None: - self._schema = batch.schema - mismatch = _schema_mismatch(self._schema, batch.schema) - if mismatch is not None: - raise ValueError( - f"A record batch sent as {_named(self._stream)} does not have that " - + f"stream's columns: {mismatch}." - ) - async def send(self, batch: pa.RecordBatch) -> None: - """Send one Arrow record batch of the stream's transport columns. - - Raises: - ChannelClosed: If the channel is closed or failed. - ValueError: If the batch's schema is not the stream's. - """ - if self._closed or self._error is not None: - raise ChannelClosed("Cannot send to a closed channel") - self._check_schema(batch) - self._sent += 1 - if self._retain: - self._batches.append(batch) - self._notify() - return - for reader in list(self._readers): - # The slowest reader sets the pace; one that closed is not waited for. - while reader.open and len(reader.queue) >= self._buffer_size: - await self._changed.wait() - if reader.open: - reader.queue.append(batch) - # At once, not after the last reader: this reader may be waiting for - # the batch while the send waits for another reader's room. - self._notify() + """Send one Arrow record batch of the stream's transport columns.""" + ... async def close(self) -> None: - """Complete the output. A second close does nothing; never waits.""" - if not self._closed and self._error is None: - self._closed = True - self._notify() + """Complete the output.""" + ... def fail(self, error: BaseException) -> None: - """End the output with the producer's failure or cancellation. - - Every reader's next read raises ``UpstreamFailedError`` (its cause is - ``error``), never a normal end. The failure is seen at once: record batches a - reader has not yet read are not delivered first, so no consumer acts on part of - a failed output. Does nothing on a channel already closed or failed. - - Args: - error: The producer's error. - """ - if not self._closed and self._error is None: - self._error = error - self._notify() - - def open_reader(self) -> InputChannel: - """Open an input channel for one consumer, with its own position. - - Raises: - ValueError: Without ``retain``, once a record batch has been sent: the - reader would miss it. - """ - if not self._retain and self._sent: - raise ValueError( - f"A reader of {_named(self._stream)} must be opened before the first " - + "record batch is sent: this output channel does not retain what it " - + "sent (retain=False)." - ) - feed = _OutputFeed(self) - if not self._retain: - self._readers.append(feed) - return InputChannel(self._stream, feed) - - def result(self) -> StreamProtocol: - """Return the output as a stream, once the channel is closed. - - The concatenation of the record batches sent, in the order sent, with the - description and identity of ``stream`` (``stream_from_batches``); the same - object on every call. - - Raises: - RuntimeError: If the channel is not closed, failed, or does not retain. - """ - if self._error is not None: - raise RuntimeError( - f"The output of {_named(self._stream)} has no result: its producer " - + f"failed with {type(self._error).__name__}: {self._error}" - ) from self._error - if not self._retain: - raise RuntimeError( - f"The output of {_named(self._stream)} was not retained " - + "(retain=False), so it has no result stream." - ) - if not self._closed: - raise RuntimeError( - f"The output of {_named(self._stream)} is not closed yet; its result " - + "is a stream only once it is complete." - ) - if self._result is None: - self._result = stream_from_batches(self._stream, self._batches) - return self._result - - -def channel_from_stream(stream: StreamProtocol) -> InputChannel: - """Open an input channel on a complete stream. - - The channel delivers the stream's transport columns (``transport_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) - return repr(label) if label else repr(stream) - - -def _schema_mismatch(declared: pa.Schema, sent: pa.Schema) -> str | None: - """Say how a record batch's schema differs from a channel's, or ``None``. - - The two schemas agree when they have the same columns in the same order, each with - the same Arrow type and nullability. What a description does not say of a row is - not compared: a ``null`` column, which rows carry as ``large_string``, and whether - a system-tag or source-info field is nullable, which follows the values of the - complete table (``_flagged_by_values``). - """ - from orcapod.system_constants import constants - from orcapod.utils import arrow_utils - - if declared.names != sent.names: - return f"it has {sent.names}, the stream has {declared.names}" - for expected, column in zip(declared, sent): - expected_type = arrow_utils.normalize_to_large_types(expected.type) - if expected_type != arrow_utils.normalize_to_large_types(column.type): - return f"column {column.name!r} is {column.type}, the stream's is {expected.type}" - if expected.nullable != column.nullable and not column.name.startswith( - (constants.SYSTEM_TAG_PREFIX, constants.SOURCE_PREFIX) - ): - flags = {True: "nullable", False: "not nullable"} - return ( - f"column {column.name!r} is {flags[column.nullable]}, the stream's is " - + flags[expected.nullable] - ) - return None + """End the output with the producer's failure or cancellation.""" + ... diff --git a/src/orcapod/core/operators/batch.py b/src/orcapod/core/operators/batch.py index 7166d646b..3186ceaf2 100644 --- a/src/orcapod/core/operators/batch.py +++ b/src/orcapod/core/operators/batch.py @@ -8,9 +8,9 @@ from orcapod.core.operators.meta_columns import WithoutMetaWriter from orcapod.channels import ( - InputChannel, - OutputChannel, ReadableChannel, + RecordBatchInput, + RecordBatchOutput, WritableChannel, ) from orcapod.core.operators.base import UnaryOperator @@ -270,7 +270,7 @@ async def async_execute( await output.close() async def async_execute_batches( - self, inputs: Sequence[InputChannel], output: OutputChannel + self, inputs: Sequence[RecordBatchInput], output: RecordBatchOutput ) -> None: """Batch the rows of an input channel as they arrive. diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index 61cd6744b..cd0bb92e0 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -10,12 +10,10 @@ import pyarrow as pa from orcapod.channels import ( - InputChannel, - OutputChannel, ReadableChannel, + RecordBatchInput, + RecordBatchOutput, WritableChannel, - stream_from_batches, - transport_columns, ) from orcapod import contexts from orcapod.config import OrcapodConfig @@ -56,7 +54,9 @@ TagProtocol, TrackerManagerProtocol, ) +from orcapod.system_constants import constants from orcapod.types import ColumnConfig, ContentHash, Schema +from orcapod.utils import arrow_utils logger = logging.getLogger(__name__) @@ -794,7 +794,7 @@ async def async_execute( # ------------------------------------------------------------------ async def async_execute_batches( - self, inputs: Sequence[InputChannel], output: OutputChannel + self, inputs: Sequence[RecordBatchInput], output: RecordBatchOutput ) -> None: """Run this operator over input channels of Arrow record batches. @@ -839,7 +839,7 @@ async def _send_processed( self, batches: Sequence[pa.RecordBatch], stream: StreamProtocol, - output: OutputChannel, + output: RecordBatchOutput, ) -> None: """Apply this operator to some record batches of one input and send the result. @@ -856,7 +856,7 @@ async def _send_processed( ) @staticmethod - async def _send_result(result: StreamProtocol, output: OutputChannel) -> None: + async def _send_result(result: StreamProtocol, output: RecordBatchOutput) -> None: """Send a result stream's rows into ``output`` as its own record batches. Args: @@ -871,7 +871,7 @@ async def _send_result(result: StreamProtocol, output: OutputChannel) -> None: await output.send(batch) -async def _streams_of(inputs: Sequence[InputChannel]) -> list[StreamProtocol]: +async def _streams_of(inputs: Sequence[RecordBatchInput]) -> list[StreamProtocol]: """Read every input channel to its end, each as a stream, at the same time. Args: @@ -893,6 +893,151 @@ async def _streams_of(inputs: Sequence[InputChannel]) -> list[StreamProtocol]: raise +# --------------------------------------------------------------------------- +# Conversions between streams and Arrow record batches (ITL-1347) +# --------------------------------------------------------------------------- + + +def transport_columns( + table: pa.Table, keys: tuple[Sequence[str], Sequence[str]] +) -> pa.Table: + """Return ``table`` as the columns passed between nodes, for a channel. + + The transport columns of a stream are what a table built from its rows holds: user + tags, system tags, data and source info, in that order, with no data-context and no + meta (``__``) column, and ``null`` as ``large_string`` (a row's datagram stores a + ``null`` column so). The source info follows the stream's data keys, a data-tag's + first, as each row lists it. No value is changed. + + One property is left for the complete table: whether a source-info field is + nullable follows its tokens, so it cannot be decided on one record batch of many. + Here every source-info field is nullable, so all record batches of one channel have + one schema; ``stream_from_batches`` sets the flags over all of them. + + Args: + table: A stream's table with its system tags and source info + (``ZERO_ROW_INPUT_COLUMNS``), of any number of rows. + keys: The stream's tag keys and data keys (``stream.keys()``). + + Returns: + The transport columns, in row order. + """ + # TODO(ITL-1360): this is steps 1 to 4 of the row-built form of the design + # (docs/dev/specs/itl-1347-job-table-transport.md); stage 2 defines that form once, + # and this function then calls it. + tag_keys, data_keys = keys + names = table.column_names + system_tags = [n for n in names if n.startswith(constants.SYSTEM_TAG_PREFIX)] + source_info = [n for n in names if n.startswith(constants.SOURCE_PREFIX)] + # A row lists its source info in the order of its data columns. + by_data_key = [f"{constants.SOURCE_PREFIX}{name}" for name in data_keys] + source_info = [n for n in by_data_key if n in source_info] + [ + n + for n in source_info + if n not in by_data_key + and not n.removeprefix(constants.SOURCE_PREFIX).startswith( + constants.META_PREFIX + ) + ] + placed = {*tag_keys, *system_tags, *source_info, constants.CONTEXT_KEY} + data = [ + n + for n in names + if n not in placed + and not n.startswith((constants.META_PREFIX, constants.SOURCE_PREFIX)) + ] + kept = arrow_utils.normalize_table_to_large_types( + table.select([*tag_keys, *system_tags, *data, *source_info]) + ) + schema = pa.schema( + [ + column.with_nullable(True) + if column.name.startswith(constants.SOURCE_PREFIX) + else column + for column in kept.schema + ] + ) + return pa.Table.from_arrays(kept.columns, schema=schema) + + +def transport_schema(stream: StreamProtocol) -> pa.Schema | None: + """Return the schema ``stream``'s record batches have, from its description. + + Never computes, reads or polls a row: it is the schema of the stream's zero-row + input, as its record batches carry it (``transport_columns``). + + Args: + stream: The describing stream. + + Returns: + The schema, or ``None`` for a stream that cannot say its Arrow types without + rows (an unbound input slot, a source that has not polled yet). + """ + # TODO(ITL-1360): ``stream.arrow_schema()``, once every stream has it. + typed = StaticOutputOperatorPod._zero_row_input(stream) # pyright: ignore[reportPrivateUsage] # the zero-row form of an input + if typed is None: + return None + return transport_columns( + typed.as_table(columns=ZERO_ROW_INPUT_COLUMNS), stream.keys() + ).schema + + +def stream_from_batches( + stream: StreamProtocol, batches: Sequence[pa.RecordBatch] +) -> StreamProtocol: + """Return the Arrow record batches of ``stream``'s rows as a stream. + + 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 + applied to. The batches are put under one another in the order + given, each system-tag and source-info field is flagged nullable only when one of + its values is null (decided over the complete table, never per batch), and the + table is wrapped with ``stream``'s identity: its producer, upstreams, pipeline hash and data + context. With no batch it is ``stream``'s zero-row input, typed by its description + and never by rows. + + Args: + stream: The describing stream: the node or stream the rows are of. + batches: Its rows as transport columns (``transport_columns``), in order. + + Returns: + A complete, re-readable stream over the rows. + """ + if not batches: + return StaticOutputOperatorPod._materialize_upstream([], stream) # pyright: ignore[reportPrivateUsage] # the zero-row input of an operator + table = _flagged_by_values(pa.Table.from_batches(list(batches))) + return StaticOutputOperatorPod._as_upstream_stream( # pyright: ignore[reportPrivateUsage] # the identity of a successor's input + table, stream.keys()[0], stream_data_tags(stream), stream + ) + + +def _flagged_by_values(table: pa.Table) -> pa.Table: + """Flag each system-tag and source-info field nullable only when it holds a null. + + What a table built from rows has: a row states its system tags and its source-info + tokens as values, so those fields are non-nullable unless a value is missing. It is + decided over the complete table, never per record batch (two batches of one + channel would then have two schemas). The same arrays under the new flags. + + Args: + table: The complete table of a stream's transport columns. + + Returns: + The table with those fields' flags set by their values. + """ + by_values = (constants.SYSTEM_TAG_PREFIX, constants.SOURCE_PREFIX) + schema = pa.schema( + [ + column.with_nullable(table.column(i).null_count > 0) + if column.name.startswith(by_values) + else column + for i, column in enumerate(table.schema) + ] + ) + return pa.Table.from_arrays(table.columns, schema=schema) + + class _RowsOfStream(ArrowTableStream): """Rows standing in for the stream they came from, with its pipeline hash. diff --git a/src/orcapod/core/record_batch_channels.py b/src/orcapod/core/record_batch_channels.py new file mode 100644 index 000000000..0cf646761 --- /dev/null +++ b/src/orcapod/core/record_batch_channels.py @@ -0,0 +1,416 @@ +"""Channels of Arrow record batches (ITL-1347). + +``InputChannel`` and ``OutputChannel`` carry a stream's rows as Arrow record batches; they +implement ``RecordBatchInput`` and ``RecordBatchOutput`` of ``orcapod.channels``. 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``. +""" + +from __future__ import annotations + +import asyncio +from collections import deque +from collections.abc import AsyncIterator +from typing import TYPE_CHECKING, Any, Protocol + +import pyarrow as pa + +from orcapod.channels import ChannelClosed +from orcapod.core.operators.static_output_pod import ( + stream_from_batches, + transport_columns, + transport_schema, +) +from orcapod.core.streams.base import ZERO_ROW_INPUT_COLUMNS +from orcapod.errors import UpstreamFailedError +from orcapod.system_constants import constants +from orcapod.utils import arrow_utils + +if TYPE_CHECKING: + from orcapod.protocols.core_protocols import StreamProtocol + +SOURCE_BATCH_ROWS = 65_536 +"""The most rows of one Arrow record batch a complete stream is read in. + +Developer decision, November 22, 2026 (ITL-1347, question 6): a source sends record +batches of at most 65,536 rows; an operator sends its result's own record batches. +""" + +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: + self._stream = stream + self._batches: deque[pa.RecordBatch] | None = None + + async def next(self) -> pa.RecordBatch | None: + if self._batches is None: + # On the first read, not when the channel is opened: opening computes + # nothing. + table = transport_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: + self._batches = deque() + + +class _OutputFeed: + """One reader of an output channel, with its own position.""" + + def __init__(self, output: OutputChannel) -> None: + self._output = output + self.open = True + # With retained batches: this reader's position among them. Without: the + # batches sent and not yet read by this reader. + self.position = 0 + self.queue: deque[pa.RecordBatch] = deque() + + async def next(self) -> pa.RecordBatch | None: + output = self._output + while self.open: + if output._error is not None: # pyright: ignore[reportPrivateUsage] + raise output._upstream_failed() # pyright: ignore[reportPrivateUsage] + if output._retain: # pyright: ignore[reportPrivateUsage] + if self.position < len(output._batches): # pyright: ignore[reportPrivateUsage] + self.position += 1 + return output._batches[self.position - 1] # pyright: ignore[reportPrivateUsage] + elif self.queue: + batch = self.queue.popleft() + output._notify() # pyright: ignore[reportPrivateUsage] # room for the producer + return batch + if output._closed: # pyright: ignore[reportPrivateUsage] + return None + await output._changed.wait() # pyright: ignore[reportPrivateUsage] + return None + + def close(self) -> None: + self.open = False + self.queue.clear() + self._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: + self._stream = stream + self._feed = feed + self._received = 0 + self._ended = 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. + + Raises: + ChannelClosed: At the end, and after ``close``. + UpstreamFailedError: If the producer failed or was cancelled. + """ + if self._ended: + raise ChannelClosed() + batch = await self._feed.next() + if batch is None: + self._ended = True + raise ChannelClosed() + self._received += 1 + return batch + + def __aiter__(self) -> AsyncIterator[pa.RecordBatch]: + return self + + async def __anext__(self) -> pa.RecordBatch: + try: + return await self.receive() + except ChannelClosed: + raise StopAsyncIteration + + async def collect(self) -> list[pa.RecordBatch]: + """Read to the end and return every remaining record batch, in arrival order.""" + 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. + 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.""" + self._ended = True + self._feed.close() + + +class OutputChannel: + """The producer side of a node's async output, in Arrow record batches. + + The Arrow-record-batch form of ``WritableChannel``. Its ``stream`` is the producing + node, or the stream the output is of: the description of every record batch sent. + Each consumer reads through its own input channel (``open_reader``), which is the + fan-out. Once closed, ``result`` gives the output as an ordinary stream. + + Args: + stream: The describing stream. + retain: Keep every record batch sent, so that ``result`` can give the output + stream. Readers then read the kept batches at their own position, a reader + may be opened at any time, and ``send`` never waits. Without it, ``send`` + waits until every reader has room, so the slowest reader sets the pace, + and ``result`` raises. + buffer_size: Without ``retain``, how many record batches each reader queues + before ``send`` waits. + """ + + def __init__( + self, + stream: StreamProtocol, + *, + retain: bool = True, + buffer_size: int = BATCH_BUFFER_SIZE, + ) -> None: + if buffer_size < 1: + raise ValueError(f"buffer_size must be at least 1, got {buffer_size}") + self._stream = stream + self._retain = retain + self._buffer_size = buffer_size + self._batches: list[pa.RecordBatch] = [] + self._readers: list[_OutputFeed] = [] + self._sent = 0 + self._closed = False + self._error: BaseException | None = None + self._result: StreamProtocol | None = None + # The schema every record batch must have: the description's, or the first + # batch's when the stream cannot say its Arrow types without rows. + self._schema: pa.Schema | None = None + self._schema_known = False + self._changed = asyncio.Event() + + @property + def stream(self) -> StreamProtocol: + """The stream whose rows are written here: the description.""" + return self._stream + + def _notify(self) -> None: + """Wake everything waiting on this channel: readers and a waiting ``send``.""" + changed, self._changed = self._changed, asyncio.Event() + changed.set() + + def _upstream_failed(self) -> UpstreamFailedError: + error = self._error + assert error is not None + failure = UpstreamFailedError( + f"The input from {_named(self._stream)} did not finish: its producer " + + f"failed with {type(error).__name__}: {error}" + ) + failure.__cause__ = error + return failure + + def _check_schema(self, batch: pa.RecordBatch) -> None: + """Raise unless ``batch`` has the schema of this channel's record batches.""" + if not self._schema_known: + self._schema = transport_schema(self._stream) + self._schema_known = True + if self._schema is None: + self._schema = batch.schema + mismatch = _schema_mismatch(self._schema, batch.schema) + if mismatch is not None: + raise ValueError( + f"A record batch sent as {_named(self._stream)} does not have that " + + f"stream's columns: {mismatch}." + ) + + async def send(self, batch: pa.RecordBatch) -> None: + """Send one Arrow record batch of the stream's transport columns. + + Raises: + ChannelClosed: If the channel is closed or failed. + ValueError: If the batch's schema is not the stream's. + """ + if self._closed or self._error is not None: + raise ChannelClosed("Cannot send to a closed channel") + self._check_schema(batch) + self._sent += 1 + if self._retain: + self._batches.append(batch) + self._notify() + return + for reader in list(self._readers): + # The slowest reader sets the pace; one that closed is not waited for. + while reader.open and len(reader.queue) >= self._buffer_size: + await self._changed.wait() + if reader.open: + reader.queue.append(batch) + # At once, not after the last reader: this reader may be waiting for + # the batch while the send waits for another reader's room. + self._notify() + + async def close(self) -> None: + """Complete the output. A second close does nothing; never waits.""" + if not self._closed and self._error is None: + self._closed = True + self._notify() + + def fail(self, error: BaseException) -> None: + """End the output with the producer's failure or cancellation. + + Every reader's next read raises ``UpstreamFailedError`` (its cause is + ``error``), never a normal end. The failure is seen at once: record batches a + reader has not yet read are not delivered first, so no consumer acts on part of + a failed output. Does nothing on a channel already closed or failed. + + Args: + error: The producer's error. + """ + if not self._closed and self._error is None: + self._error = error + self._notify() + + def open_reader(self) -> InputChannel: + """Open an input channel for one consumer, with its own position. + + Raises: + ValueError: Without ``retain``, once a record batch has been sent: the + reader would miss it. + """ + if not self._retain and self._sent: + raise ValueError( + f"A reader of {_named(self._stream)} must be opened before the first " + + "record batch is sent: this output channel does not retain what it " + + "sent (retain=False)." + ) + feed = _OutputFeed(self) + if not self._retain: + self._readers.append(feed) + return InputChannel(self._stream, feed) + + def result(self) -> StreamProtocol: + """Return the output as a stream, once the channel is closed. + + The concatenation of the record batches sent, in the order sent, with the + description and identity of ``stream`` (``stream_from_batches``); the same + object on every call. + + Raises: + RuntimeError: If the channel is not closed, failed, or does not retain. + """ + if self._error is not None: + raise RuntimeError( + f"The output of {_named(self._stream)} has no result: its producer " + + f"failed with {type(self._error).__name__}: {self._error}" + ) from self._error + if not self._retain: + raise RuntimeError( + f"The output of {_named(self._stream)} was not retained " + + "(retain=False), so it has no result stream." + ) + if not self._closed: + raise RuntimeError( + f"The output of {_named(self._stream)} is not closed yet; its result " + + "is a stream only once it is complete." + ) + if self._result is None: + self._result = stream_from_batches(self._stream, self._batches) + return self._result + + +def channel_from_stream(stream: StreamProtocol) -> InputChannel: + """Open an input channel on a complete stream. + + The channel delivers the stream's transport columns (``transport_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) + return repr(label) if label else repr(stream) + + +def _schema_mismatch(declared: pa.Schema, sent: pa.Schema) -> str | None: + """Say how a record batch's schema differs from a channel's, or ``None``. + + The two schemas agree when they have the same columns in the same order, each with + the same Arrow type and nullability. What a description does not say of a row is + not compared: a ``null`` column, which rows carry as ``large_string``, and whether + a system-tag or source-info field is nullable, which follows the values of the + complete table (``_flagged_by_values``). + """ + if declared.names != sent.names: + return f"it has {sent.names}, the stream has {declared.names}" + for expected, column in zip(declared, sent): + expected_type = arrow_utils.normalize_to_large_types(expected.type) + if expected_type != arrow_utils.normalize_to_large_types(column.type): + return f"column {column.name!r} is {column.type}, the stream's is {expected.type}" + if expected.nullable != column.nullable and not column.name.startswith( + (constants.SYSTEM_TAG_PREFIX, constants.SOURCE_PREFIX) + ): + flags = {True: "nullable", False: "not nullable"} + return ( + f"column {column.name!r} is {flags[column.nullable]}, the stream's is " + + flags[expected.nullable] + ) + return None diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py index 73aecad3f..0f8a5cb33 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -14,7 +14,7 @@ from contextlib import contextmanager from contextvars import ContextVar from datetime import datetime -from typing import TYPE_CHECKING, Any, cast +from typing import Any, cast import pandas as pd import polars as pl @@ -37,9 +37,6 @@ from orcapod.types import ColumnConfig, Schema from orcapod.utils import arrow_utils -if TYPE_CHECKING: - from orcapod.channels import InputChannel - # TODO: consider using this instead of making copy of dicts # from types import MappingProxyType @@ -998,22 +995,6 @@ def iter_data( self, ) -> Iterator[tuple[TagProtocol, DataProtocol]]: ... - def open_channel(self) -> "InputChannel": - """Open an input channel on this stream, for async computation (ITL-1347). - - The channel delivers this stream's rows as Arrow record batches, 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: readable again, and by every other reader. Nothing is - computed until the channel is first read. - - Returns: - The input channel. - """ - from orcapod.channels import channel_from_stream - - return channel_from_stream(self) - async def async_iter_data( self, ) -> AsyncIterator[tuple[TagProtocol, DataProtocol]]: diff --git a/tests/test_channels/test_record_batch_channels.py b/tests/test_channels/test_record_batch_channels.py index b2f66a657..ca5b4a652 100644 --- a/tests/test_channels/test_record_batch_channels.py +++ b/tests/test_channels/test_record_batch_channels.py @@ -2,7 +2,7 @@ A stream is primary and owns the description; a channel is a separate, single-pass carrier of the stream's rows as Arrow record batches. An input channel is opened from a -complete stream (``stream.open_channel()``) or from an output channel +complete stream (``channel_from_stream``) 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". @@ -22,18 +22,24 @@ import pytest from orcapod.channels import ( + ChannelClosed, + ReadableChannel, + RecordBatchInput, + RecordBatchOutput, + WritableChannel, +) +from orcapod.core.operators import MapData, PolarsFilter, SelectDataColumns +from orcapod.core.operators.static_output_pod import ( + StaticOutputOperatorPod, + stream_from_batches, +) +from orcapod.core.record_batch_channels import ( BATCH_BUFFER_SIZE, SOURCE_BATCH_ROWS, - ChannelClosed, InputChannel, OutputChannel, - ReadableChannel, - WritableChannel, channel_from_stream, - stream_from_batches, ) -from orcapod.core.operators import MapData, PolarsFilter, SelectDataColumns -from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod from orcapod.core.streams import ArrowTableStream from orcapod.errors import UpstreamFailedError from orcapod.sources import ArrowTableSource @@ -87,7 +93,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 stream.open_channel().collect() + return await channel_from_stream(stream).collect() return pa.Table.from_batches(run(read)).to_batches(max_chunksize=rows) @@ -98,11 +104,12 @@ 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.""" stream = source() - channel = stream.open_channel() + channel = channel_from_stream(stream) assert isinstance(channel, InputChannel) assert isinstance(channel, ReadableChannel) - assert channel.stream is stream + as_protocol: RecordBatchInput = channel # what an operator reads (type-checked) + assert as_protocol.stream is stream delivered = run(channel.to_stream) assert same(delivered.as_table(columns=ALL), R(stream)) assert delivered.keys() == stream.keys() @@ -120,18 +127,18 @@ def test_opening_a_channel_computes_nothing() -> None: autospec=True, side_effect=ArrowTableSource.as_table, ) as read: - channel = stream.open_channel() + channel = channel_from_stream(stream) assert read.call_count == 0 _ = run(channel.receive) assert read.call_count == 1 def test_two_channels_on_one_stream_have_their_own_positions() -> None: - """``open_channel()`` twice: each reader gets every row, and the stream stays.""" + """Two channels opened on one stream: each reader gets every row, and the stream stays.""" stream = source() async def read() -> tuple[int, int, int]: - first, second = stream.open_channel(), channel_from_stream(stream) + first, second = channel_from_stream(stream), channel_from_stream(stream) one = await first.receive() rest = await second.collect() return one.num_rows, sum(b.num_rows for b in rest), len(await first.collect()) @@ -149,7 +156,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(stream.open_channel().collect)] + sizes = [batch.num_rows for batch in run(channel_from_stream(stream).collect)] assert sizes == [SOURCE_BATCH_ROWS, 10] @@ -157,7 +164,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 = source().open_channel() + channel = channel_from_stream(source()) first = await channel.collect() with pytest.raises(ChannelClosed): _ = await channel.receive() @@ -198,6 +205,10 @@ def test_result_is_the_batches_sent_in_order_as_the_nodes_stream(rows: int) -> N async def write() -> OutputChannel: output = OutputChannel(stream) assert isinstance(output, WritableChannel) + as_protocol: RecordBatchOutput = ( + output # what an operator writes (type-checked) + ) + assert as_protocol is output assert output.stream is stream for batch in batches: await output.send(batch) @@ -639,7 +650,7 @@ def test_an_operator_reads_its_input_to_the_end_and_closes_its_output() -> None: op = SelectDataColumns(["subject", "trial", "note"]) async def inputs() -> list[InputChannel]: - return [stream.open_channel()] + return [channel_from_stream(stream)] output = execute(op, [stream], inputs) assert same(output.result().as_table(columns=ALL), R(op(stream))) diff --git a/tests/test_core/operators/test_record_batch_execution.py b/tests/test_core/operators/test_record_batch_execution.py index 2de95ca57..29d962067 100644 --- a/tests/test_core/operators/test_record_batch_execution.py +++ b/tests/test_core/operators/test_record_batch_execution.py @@ -27,9 +27,13 @@ import pytest import orcapod.core.operators as operators -from orcapod.channels import InputChannel, OutputChannel, channel_from_stream from orcapod.core.operators import Batch from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod +from orcapod.core.record_batch_channels import ( + InputChannel, + OutputChannel, + channel_from_stream, +) from orcapod.protocols.core_protocols import StreamProtocol from tests.test_core.operators.test_async_sync_equivalence import ( AFTER_OPERATOR_CASES, From ef1d264c35d88eb63a51499f95831cca612050d5 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 02:49:33 -0800 Subject: [PATCH 06/12] refactor(channels): F from stage 2 (_row_built_columns, _flag_by_values, _output_stream); record-batch protocols in protocols/core_protocols, channels.py as on job-speed (ITL-1362) Co-Authored-By: Claude Opus 5.5 --- .zed/rules | 14 +- CLAUDE.md | 14 +- src/orcapod/channels.py | 78 +----- src/orcapod/core/operators/batch.py | 6 +- .../core/operators/static_output_pod.py | 260 +++++++++++------- src/orcapod/core/record_batch_channels.py | 11 +- .../core_protocols/record_batch_channels.py | 76 +++++ .../test_record_batch_channels.py | 6 +- 8 files changed, 272 insertions(+), 193 deletions(-) create mode 100644 src/orcapod/protocols/core_protocols/record_batch_channels.py diff --git a/.zed/rules b/.zed/rules index 866829ede..497e0b8c0 100644 --- a/.zed/rules +++ b/.zed/rules @@ -1306,13 +1306,13 @@ data. The rules: 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_columns, transport_schema); 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. + transport_schema, and F, _row_built_form); never build a stream from record batches + elsewhere. An operator's record-batch form (async_execute_batches, renamed async_execute + when wired) applies its one static_process body: per record batch when the class declares + ROW_BY_ROW = True (each output row comes from one input row), otherwise as a barrier over + the whole input (to_stream()); Batch with a size has its own form, grouping rows by arrival. + A new operator whose output rows each come from one input row declares ROW_BY_ROW; write no + other per-operator batch code. - The type converter keys synthesized struct classes by the large-normalized struct, so struct and struct are one Python type (a workaround, TODO(ITL-841)). diff --git a/CLAUDE.md b/CLAUDE.md index 3c0876c09..3016bdd42 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1353,13 +1353,13 @@ data. The rules: 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_columns`, `transport_schema`); 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. + (`stream_from_batches`, `transport_schema`, and F, `_row_built_form`); never build a stream + from record batches elsewhere. An operator's record-batch form (`async_execute_batches`, + renamed `async_execute` when wired) applies its one `static_process` body: per record batch + when the class declares `ROW_BY_ROW = True` (each output row comes from one input row), + otherwise as a barrier over the whole input (`to_stream()`); `Batch` with a size has its own + form, grouping rows by arrival. A new operator whose output rows each come from one input + row declares `ROW_BY_ROW`; write no other per-operator batch code. - The type converter keys synthesized struct classes by the large-normalized struct, so `struct` and `struct` are one Python type (a workaround, `TODO(ITL-841)`). diff --git a/src/orcapod/channels.py b/src/orcapod/channels.py index ac20150d9..8111912f4 100644 --- a/src/orcapod/channels.py +++ b/src/orcapod/channels.py @@ -2,13 +2,6 @@ Provides bounded async channels with close/done signaling, backpressure, and fan-out (broadcast) support. - -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 concrete channels are in -``orcapod.core.record_batch_channels``; this module imports nothing of Orcapod's core, so -every part of it may use these protocols. """ from __future__ import annotations @@ -16,12 +9,7 @@ import asyncio from collections.abc import AsyncIterator from dataclasses import dataclass, field -from typing import TYPE_CHECKING, Generic, Protocol, TypeVar, runtime_checkable - -if TYPE_CHECKING: - import pyarrow as pa - - from orcapod.protocols.core_protocols import StreamProtocol +from typing import Generic, Protocol, TypeVar, runtime_checkable T = TypeVar("T") T_co = TypeVar("T_co", covariant=True) @@ -310,67 +298,3 @@ async def close(self) -> None: reader._queue.put_nowait(_CLOSED) except asyncio.QueueFull: reader._closed = True - - -# --------------------------------------------------------------------------- -# Channels of Arrow record batches (ITL-1347) -# --------------------------------------------------------------------------- - - -class RecordBatchInput(Protocol): - """A single-pass reader of a stream's Arrow record batches. - - The Arrow-record-batch form of ``ReadableChannel``; ``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.""" - ... - - 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``; ``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/core/operators/batch.py b/src/orcapod/core/operators/batch.py index 3186ceaf2..876927ddc 100644 --- a/src/orcapod/core/operators/batch.py +++ b/src/orcapod/core/operators/batch.py @@ -7,10 +7,12 @@ import pyarrow as pa from orcapod.core.operators.meta_columns import WithoutMetaWriter -from orcapod.channels import ( - ReadableChannel, +from orcapod.protocols.core_protocols.record_batch_channels import ( RecordBatchInput, RecordBatchOutput, +) +from orcapod.channels import ( + ReadableChannel, WritableChannel, ) from orcapod.core.operators.base import UnaryOperator diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index cd0bb92e0..8c787e115 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -9,10 +9,12 @@ import pyarrow as pa -from orcapod.channels import ( - ReadableChannel, +from orcapod.protocols.core_protocols.record_batch_channels import ( RecordBatchInput, RecordBatchOutput, +) +from orcapod.channels import ( + ReadableChannel, WritableChannel, ) from orcapod import contexts @@ -56,7 +58,6 @@ ) from orcapod.system_constants import constants from orcapod.types import ColumnConfig, ContentHash, Schema -from orcapod.utils import arrow_utils logger = logging.getLogger(__name__) @@ -462,6 +463,144 @@ def _kept_output( return StaticOutputOperatorPod._materialize_to_stream(rows) return StaticOutputOperatorPod._zero_rows_in_row_order(result) + # TODO(ITL-1360): stage 2 defines F; this is its definition, copied unchanged from + # that branch until it is on eywalker/job-speed. + @staticmethod + def _row_built_columns( + table: pa.Table, keys: tuple[Sequence[str], Sequence[str]] + ) -> pa.Table: + """Return ``table``'s columns as ``_rows_to_table`` lays out the table's rows. + + Every step of F (``_row_built_form``) that each row decides on its own, so it + gives the same result on a whole table and on each slice of it: + + 1. The columns a row-built table holds: the user tags, the system tags, the data + columns that are not data-tags, and the source info of every data column (a + data-tag's included). ``table`` holds no context, meta or content-hash column + (``ZERO_ROW_INPUT_COLUMNS``). + 2. In row order: user tags in tag order, system tags in table order, then the data + columns and their source info, both in the order of the data keys. A row's + ``Data`` lists its source info in the order of its data keys, data-tags first + in tag order (``Data._ensure_source_info_table``), so a data-tag's source info + comes before the other data columns' even when the data-tag is not the first + column of ``table``. + 3. Normalized to the large types without keeping ``null``: each row's datagram + stores a ``null`` column as ``large_string`` (``Datagram._init_from_table``). + + Whether a system-tag or source-info field is nullable depends on its values over + the complete table (``_flag_by_values``), so it is not decided here. + + Args: + table: A table of user tags, system tags, data and source info. + keys: The tag keys and the data keys of the stream ``table`` belongs to + (``stream.keys()``). + + Returns: + The same arrays, selected and ordered, in their large types. + """ + from orcapod.system_constants import constants + from orcapod.utils import arrow_utils + + tag_keys, data_keys = keys + names = set(table.column_names) + tags = set(tag_keys) + system_tags = [ + n for n in table.column_names if n.startswith(constants.SYSTEM_TAG_PREFIX) + ] + data = [n for n in data_keys if n not in tags] + source_info = [ + f"{constants.SOURCE_PREFIX}{n}" + for n in data_keys + if f"{constants.SOURCE_PREFIX}{n}" in names + ] + return arrow_utils.normalize_table_to_large_types( + table.select([*tag_keys, *system_tags, *data, *source_info]) + ) + + @staticmethod + def _flag_by_values(table: pa.Table) -> pa.Table: + """Flag each system-tag and source-info field nullable only when it holds a null. + + The last step of F (``_row_built_form``), which needs the complete table. A table + built from rows takes its system tags and source-info tokens from each row's + values, so those fields are non-nullable unless a value is missing, whatever + flags the table the rows came from had (a join over inputs tied on pipeline hash + declares its system tags nullable). The table built from rows also carries no + schema metadata (``arrow_utils.hstack_tables``), so none is kept. + + Args: + table: A table of user tags, system tags, data and source info. + + Returns: + The same arrays under the new field flags, with no schema metadata. + """ + from orcapod.system_constants import constants + + prefixes = (constants.SYSTEM_TAG_PREFIX, constants.SOURCE_PREFIX) + fields = [ + field.with_nullable(table.column(i).null_count > 0) + if field.name.startswith(prefixes) + else field + for i, field in enumerate(table.schema) + ] + # Same arrays, new field flags: no cast, so no value or type can change. + return pa.Table.from_arrays(table.columns, schema=pa.schema(fields)) + + @staticmethod + def _row_built_form( + table: pa.Table, keys: tuple[Sequence[str], Sequence[str]] + ) -> pa.Table: + """Return ``table`` as ``_rows_to_table`` builds it from the table's own rows. + + F in the ITL-1347 spec: the same table, without making the rows. The columns, + their order and their types are decided row by row (``_row_built_columns``), the + system-tag and source-info field flags by their values over the whole table + (``_flag_by_values``). The equality with ``_rows_to_table`` is tested over every + operator, source kind and column role (ITL-1347, L0-L2). + + Args: + table: A table of user tags, system tags, data and source info, with rows. + keys: The tag keys and the data keys of the stream ``table`` belongs to + (``stream.keys()``). + + Returns: + The table ``_rows_to_table`` would build from its rows. + """ + return StaticOutputOperatorPod._flag_by_values( + StaticOutputOperatorPod._row_built_columns(table, keys) + ) + + @staticmethod + def _output_stream( + table: pa.Table, + keys: tuple[Sequence[str], Sequence[str]], + node: StreamProtocol, + ) -> StreamProtocol: + """Return the stream a node hands its successors, given the table of its rows. + + Exactly what ``_materialize_upstream`` builds from the node's rows: with rows, + ``_row_built_form`` of ``table`` as ``node``'s stream (``_as_upstream_stream``); + without, ``node``'s zero-row input. A node's ``execute`` returns it, and the sync + orchestrator gives it to every successor as it is (ITL-1347, stage 2). + + Args: + table: The node's rows: user tags, system tags, data and source info. + keys: The tag keys and the data keys of the stream the rows come from. + node: The node (or stream) whose output this is. + + Returns: + 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, + ) + @staticmethod def _flag_source_info_nullability(table: pa.Table) -> pa.Table: """Declare each ``_source_*`` field nullable only if some row's token is ``None``. @@ -863,7 +1002,7 @@ async def _send_result(result: StreamProtocol, output: RecordBatchOutput) -> Non result: An operator's result. output: The channel to send into; a result with no rows sends nothing. """ - table = transport_columns( + table = StaticOutputOperatorPod._row_built_columns( result.as_table(columns=ZERO_ROW_INPUT_COLUMNS), result.keys() ) for batch in table.to_batches(): @@ -898,73 +1037,11 @@ async def _streams_of(inputs: Sequence[RecordBatchInput]) -> list[StreamProtocol # --------------------------------------------------------------------------- -def transport_columns( - table: pa.Table, keys: tuple[Sequence[str], Sequence[str]] -) -> pa.Table: - """Return ``table`` as the columns passed between nodes, for a channel. - - The transport columns of a stream are what a table built from its rows holds: user - tags, system tags, data and source info, in that order, with no data-context and no - meta (``__``) column, and ``null`` as ``large_string`` (a row's datagram stores a - ``null`` column so). The source info follows the stream's data keys, a data-tag's - first, as each row lists it. No value is changed. - - One property is left for the complete table: whether a source-info field is - nullable follows its tokens, so it cannot be decided on one record batch of many. - Here every source-info field is nullable, so all record batches of one channel have - one schema; ``stream_from_batches`` sets the flags over all of them. - - Args: - table: A stream's table with its system tags and source info - (``ZERO_ROW_INPUT_COLUMNS``), of any number of rows. - keys: The stream's tag keys and data keys (``stream.keys()``). - - Returns: - The transport columns, in row order. - """ - # TODO(ITL-1360): this is steps 1 to 4 of the row-built form of the design - # (docs/dev/specs/itl-1347-job-table-transport.md); stage 2 defines that form once, - # and this function then calls it. - tag_keys, data_keys = keys - names = table.column_names - system_tags = [n for n in names if n.startswith(constants.SYSTEM_TAG_PREFIX)] - source_info = [n for n in names if n.startswith(constants.SOURCE_PREFIX)] - # A row lists its source info in the order of its data columns. - by_data_key = [f"{constants.SOURCE_PREFIX}{name}" for name in data_keys] - source_info = [n for n in by_data_key if n in source_info] + [ - n - for n in source_info - if n not in by_data_key - and not n.removeprefix(constants.SOURCE_PREFIX).startswith( - constants.META_PREFIX - ) - ] - placed = {*tag_keys, *system_tags, *source_info, constants.CONTEXT_KEY} - data = [ - n - for n in names - if n not in placed - and not n.startswith((constants.META_PREFIX, constants.SOURCE_PREFIX)) - ] - kept = arrow_utils.normalize_table_to_large_types( - table.select([*tag_keys, *system_tags, *data, *source_info]) - ) - schema = pa.schema( - [ - column.with_nullable(True) - if column.name.startswith(constants.SOURCE_PREFIX) - else column - for column in kept.schema - ] - ) - return pa.Table.from_arrays(kept.columns, schema=schema) - - def transport_schema(stream: StreamProtocol) -> pa.Schema | None: """Return the schema ``stream``'s record batches have, from its description. Never computes, reads or polls a row: it is the schema of the stream's zero-row - input, as its record batches carry it (``transport_columns``). + input, as its record batches carry it (``_row_built_columns``). Args: stream: The describing stream. @@ -977,7 +1054,7 @@ def transport_schema(stream: StreamProtocol) -> pa.Schema | None: typed = StaticOutputOperatorPod._zero_row_input(stream) # pyright: ignore[reportPrivateUsage] # the zero-row form of an input if typed is None: return None - return transport_columns( + return StaticOutputOperatorPod._row_built_columns( # pyright: ignore[reportPrivateUsage] # F, stage 2's typed.as_table(columns=ZERO_ROW_INPUT_COLUMNS), stream.keys() ).schema @@ -990,52 +1067,49 @@ 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 - applied to. The batches are put under one another in the order - given, each system-tag and source-info field is flagged nullable only when one of - its values is null (decided over the complete table, never per batch), and the - table is wrapped with ``stream``'s identity: its producer, upstreams, pipeline hash and data - context. With no batch it is ``stream``'s zero-row input, typed by its description - and never by rows. + 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 + flagged nullable only when one of its values is null (decided over the complete + table, never per batch), with ``stream``'s identity: its producer, upstreams, + pipeline hash and data context. With no batch it is ``stream``'s zero-row input, + typed by its description and never by rows. Args: stream: The describing stream: the node or stream the rows are of. - batches: Its rows as transport columns (``transport_columns``), in order. + batches: Its rows (``_row_built_columns``), in order. Returns: A complete, re-readable stream over the rows. """ if not batches: return StaticOutputOperatorPod._materialize_upstream([], stream) # pyright: ignore[reportPrivateUsage] # the zero-row input of an operator - table = _flagged_by_values(pa.Table.from_batches(list(batches))) - return StaticOutputOperatorPod._as_upstream_stream( # pyright: ignore[reportPrivateUsage] # the identity of a successor's input - table, stream.keys()[0], stream_data_tags(stream), stream - ) + 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 -def _flagged_by_values(table: pa.Table) -> pa.Table: - """Flag each system-tag and source-info field nullable only when it holds a null. +def _with_open_provenance_flags(batch: pa.RecordBatch) -> pa.RecordBatch: + """Flag every system-tag and source-info field of ``batch`` nullable. - What a table built from rows has: a row states its system tags and its source-info - tokens as values, so those fields are non-nullable unless a value is missing. It is - decided over the complete table, never per record batch (two batches of one - channel would then have two schemas). The same arrays under the new flags. + Record batches of one channel differ at most in these flags: each is built from its + own rows (``_row_built_columns`` leaves them, ``_flag_by_values`` sets them over a + complete table). Opened, they have one schema and can be put under one another; + the complete table's flags are then set by its values. The same arrays. Args: - table: The complete table of a stream's transport columns. + batch: A record batch of a stream's rows. Returns: - The table with those fields' flags set by their values. + The batch with those fields nullable. """ - by_values = (constants.SYSTEM_TAG_PREFIX, constants.SOURCE_PREFIX) + prefixes = (constants.SYSTEM_TAG_PREFIX, constants.SOURCE_PREFIX) schema = pa.schema( [ - column.with_nullable(table.column(i).null_count > 0) - if column.name.startswith(by_values) - else column - for i, column in enumerate(table.schema) + field.with_nullable(True) if field.name.startswith(prefixes) else field + for field in batch.schema ] ) - return pa.Table.from_arrays(table.columns, schema=schema) + return pa.RecordBatch.from_arrays(batch.columns, schema=schema) class _RowsOfStream(ArrowTableStream): diff --git a/src/orcapod/core/record_batch_channels.py b/src/orcapod/core/record_batch_channels.py index 0cf646761..36614bfe7 100644 --- a/src/orcapod/core/record_batch_channels.py +++ b/src/orcapod/core/record_batch_channels.py @@ -1,7 +1,8 @@ """Channels of Arrow record batches (ITL-1347). ``InputChannel`` and ``OutputChannel`` carry a stream's rows as Arrow record batches; they -implement ``RecordBatchInput`` and ``RecordBatchOutput`` of ``orcapod.channels``. The +implement ``RecordBatchInput`` and ``RecordBatchOutput`` +(``orcapod.protocols.core_protocols.record_batch_channels``). 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``); @@ -21,8 +22,8 @@ from orcapod.channels import ChannelClosed from orcapod.core.operators.static_output_pod import ( + StaticOutputOperatorPod, stream_from_batches, - transport_columns, transport_schema, ) from orcapod.core.streams.base import ZERO_ROW_INPUT_COLUMNS @@ -67,7 +68,7 @@ async def next(self) -> pa.RecordBatch | None: if self._batches is None: # On the first read, not when the channel is opened: opening computes # nothing. - table = transport_columns( + table = StaticOutputOperatorPod._row_built_columns( # pyright: ignore[reportPrivateUsage] # F, stage 2's self._stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS), self._stream.keys(), ) @@ -370,7 +371,7 @@ def result(self) -> StreamProtocol: def channel_from_stream(stream: StreamProtocol) -> InputChannel: """Open an input channel on a complete stream. - The channel delivers the stream's transport columns (``transport_columns``) as + 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. @@ -397,7 +398,7 @@ def _schema_mismatch(declared: pa.Schema, sent: pa.Schema) -> str | None: the same Arrow type and nullability. What a description does not say of a row is not compared: a ``null`` column, which rows carry as ``large_string``, and whether a system-tag or source-info field is nullable, which follows the values of the - complete table (``_flagged_by_values``). + complete table (``_flag_by_values``). """ if declared.names != sent.names: return f"it has {sent.names}, the stream has {declared.names}" diff --git a/src/orcapod/protocols/core_protocols/record_batch_channels.py b/src/orcapod/protocols/core_protocols/record_batch_channels.py new file mode 100644 index 000000000..5e24e926e --- /dev/null +++ b/src/orcapod/protocols/core_protocols/record_batch_channels.py @@ -0,0 +1,76 @@ +"""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.""" + ... + + 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 ca5b4a652..4feb7b7ed 100644 --- a/tests/test_channels/test_record_batch_channels.py +++ b/tests/test_channels/test_record_batch_channels.py @@ -21,11 +21,13 @@ import pyarrow as pa import pytest +from orcapod.protocols.core_protocols.record_batch_channels import ( + RecordBatchInput, + RecordBatchOutput, +) from orcapod.channels import ( ChannelClosed, ReadableChannel, - RecordBatchInput, - RecordBatchOutput, WritableChannel, ) from orcapod.core.operators import MapData, PolarsFilter, SelectDataColumns From b0acb7b47dfc6253b93f16061c7ab29d8118e88e Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 03:10:52 -0800 Subject: [PATCH 07/12] fix(channels): Codex round 1 on #483: in-flight send ends with the channel, strict send check, partial input never a stream, cancelled read closes, Batch takes differing provenance flags (ITL-1362) - send waiting for room raises at once on close (ChannelClosed) or fail (the failure) and publishes nothing more; a zero-row batch is checked and not kept - send takes exactly the description's types in their large variants, the field metadata of user fields, and only nulls where the description is null (transport_schema keeps the null type) - collect()/to_stream() of a reader closed before its producer completed raise; a cancelled receive() closes the reader; close() unregisters it - Batch opens provenance flags of arrived batches before concatenating (with_open_provenance_flags, as stream_from_batches) and holds no zero-row batch - tests: the job-sync oracle of barrier operators; AddTags -> Batch arrivals; F's provenance schema and raw meta columns as strict xfails, TODO(ITL-1360) Co-Authored-By: Claude Opus 5.5 --- .zed/rules | 25 +- CLAUDE.md | 25 +- src/orcapod/core/operators/batch.py | 7 +- .../core/operators/static_output_pod.py | 31 ++- src/orcapod/core/record_batch_channels.py | 127 +++++++++-- .../test_record_batch_channels.py | 211 ++++++++++++++++- .../operators/test_record_batch_execution.py | 214 +++++++++++++++++- 7 files changed, 585 insertions(+), 55 deletions(-) diff --git a/.zed/rules b/.zed/rules index 45177382b..6967e6d81 100644 --- a/.zed/rules +++ b/.zed/rules @@ -1301,18 +1301,19 @@ data. The rules: - Record-batch channels (ITL-1347, ITL-1362; not wired into nodes or orchestrators yet): orcapod.core.record_batch_channels.InputChannel / OutputChannel carry a stream's rows as Arrow record batches; operators see them only through the protocols RecordBatchInput / - RecordBatchOutput of orcapod.channels, which imports nothing of the core (keep it so: - 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. + 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. - 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 92dbed82c..7b781c65c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1348,18 +1348,19 @@ data. The rules: - Record-batch channels (ITL-1347, ITL-1362; not wired into nodes or orchestrators yet): `orcapod.core.record_batch_channels.InputChannel` / `OutputChannel` carry a stream's rows as Arrow record batches; operators see them only through the protocols `RecordBatchInput` / - `RecordBatchOutput` of `orcapod.channels`, which imports nothing of the core (keep it so: - 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. + `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. - 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/operators/batch.py b/src/orcapod/core/operators/batch.py index 876927ddc..5a9f750c6 100644 --- a/src/orcapod/core/operators/batch.py +++ b/src/orcapod/core/operators/batch.py @@ -16,6 +16,7 @@ WritableChannel, ) from orcapod.core.operators.base import UnaryOperator +from orcapod.core.operators.static_output_pod import with_open_provenance_flags from orcapod.core.data_tags import stream_data_tags from orcapod.core.streams import ArrowTableStream from orcapod.protocols.core_protocols import DataProtocol, StreamProtocol, TagProtocol @@ -295,7 +296,11 @@ async def async_execute_batches( waiting: list[pa.RecordBatch] = [] rows = 0 async for batch in channel: - waiting.append(batch) + if not batch.num_rows: + continue # nothing to batch, nothing to hold + # Arrived batches may differ in their provenance flags: open them so + # they concatenate (the flags are set again by the values). + waiting.append(with_open_provenance_flags(batch)) rows += batch.num_rows full = rows - rows % self.batch_size if not full: diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index 8c787e115..33f38b796 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -949,6 +949,12 @@ async def async_execute_batches( the sync call, so an input with no rows gives the typed zero-row result of the sync path, with no row to send. + The result is held to what a job's sync path gives: the operator over each + upstream rebuilt from its rows (``_materialize_upstream``: ``null`` as + ``large_string``, the columns in row order), not over the raw stream the rows + came from. A predicate that reads a ``null`` column's type or the column order + follows that form (documented behaviour, e5). + The output is closed when the operator is done. If it fails or is cancelled, the output fails instead, so no reader takes it for complete; every input is closed in either case. @@ -1041,7 +1047,9 @@ def transport_schema(stream: StreamProtocol) -> pa.Schema | None: """Return the schema ``stream``'s record batches have, from its description. Never computes, reads or polls a row: it is the schema of the stream's zero-row - input, as its record batches carry it (``_row_built_columns``). + input in the row-built form (``_row_built_columns``), except that a ``null`` type + is kept, as the description declares it (record batches carry it as + ``large_string``, holding only nulls). Args: stream: The describing stream. @@ -1054,9 +1062,20 @@ def transport_schema(stream: StreamProtocol) -> pa.Schema | None: typed = StaticOutputOperatorPod._zero_row_input(stream) # pyright: ignore[reportPrivateUsage] # the zero-row form of an input if typed is None: return None - return StaticOutputOperatorPod._row_built_columns( # pyright: ignore[reportPrivateUsage] # F, stage 2's - typed.as_table(columns=ZERO_ROW_INPUT_COLUMNS), stream.keys() - ).schema + from orcapod.utils import arrow_utils + + zero_rows = typed.as_table(columns=ZERO_ROW_INPUT_COLUMNS) + built = StaticOutputOperatorPod._row_built_columns(zero_rows, stream.keys()) # pyright: ignore[reportPrivateUsage] # F, stage 2's + return pa.schema( + [ + field.with_type( + arrow_utils.normalize_to_large_types( + zero_rows.schema.field(field.name).type, keep_null=True + ) + ) + for field in built.schema + ] + ) def stream_from_batches( @@ -1084,11 +1103,11 @@ 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]) + 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 -def _with_open_provenance_flags(batch: pa.RecordBatch) -> pa.RecordBatch: +def with_open_provenance_flags(batch: pa.RecordBatch) -> pa.RecordBatch: """Flag every system-tag and source-info field of ``batch`` nullable. Record batches of one channel differ at most in these flags: each is built from its diff --git a/src/orcapod/core/record_batch_channels.py b/src/orcapod/core/record_batch_channels.py index 36614bfe7..d0086107e 100644 --- a/src/orcapod/core/record_batch_channels.py +++ b/src/orcapod/core/record_batch_channels.py @@ -115,7 +115,11 @@ async def next(self) -> pa.RecordBatch | None: def close(self) -> None: self.open = False self.queue.clear() - self._output._notify() # pyright: ignore[reportPrivateUsage] # the producer stops waiting + output = self._output + readers = output._readers # pyright: ignore[reportPrivateUsage] + if self in readers: + readers.remove(self) # a send no longer walks it + output._notify() # pyright: ignore[reportPrivateUsage] # the producer stops waiting class InputChannel: @@ -136,6 +140,8 @@ def __init__(self, stream: StreamProtocol, feed: _BatchFeed) -> None: 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: @@ -145,13 +151,20 @@ def stream(self) -> StreamProtocol: 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``. UpstreamFailedError: If the producer failed or was cancelled. """ if self._ended: raise ChannelClosed() - batch = await self._feed.next() + try: + batch = await self._feed.next() + except asyncio.CancelledError: + await self.close() + raise if batch is None: self._ended = True raise ChannelClosed() @@ -168,8 +181,20 @@ async def __anext__(self) -> pa.RecordBatch: raise StopAsyncIteration async def collect(self) -> list[pa.RecordBatch]: - """Read to the end and return every remaining record batch, in arrival order.""" - return [batch async for batch in self] + """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. + """ + batches = [batch async for batch in self] + if self._closed: + raise ChannelClosed( + f"The input channel of {_named(self._stream)} was closed before its " + + "producer completed; it has no complete input to give." + ) + return batches async def to_stream(self) -> StreamProtocol: """Read to the end and return what the channel delivered, as a stream. @@ -181,6 +206,7 @@ async def to_stream(self) -> StreamProtocol: 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: @@ -193,6 +219,8 @@ async def to_stream(self) -> StreamProtocol: 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() @@ -260,14 +288,23 @@ def _upstream_failed(self) -> UpstreamFailedError: failure.__cause__ = error return failure + def _raise_if_ended(self) -> None: + """Raise what a send meets on an ended channel: closed, or failed.""" + if self._error is not None: + raise self._upstream_failed() + if self._closed: + raise ChannelClosed("Cannot send to a closed channel") + def _check_schema(self, batch: pa.RecordBatch) -> None: """Raise unless ``batch`` has the schema of this channel's record batches.""" if not self._schema_known: self._schema = transport_schema(self._stream) self._schema_known = True if self._schema is None: + # No description to check against: the first batch sets the schema, + # which must itself be in the large variants. self._schema = batch.schema - mismatch = _schema_mismatch(self._schema, batch.schema) + mismatch = _schema_mismatch(self._schema, batch) if mismatch is not None: raise ValueError( f"A record batch sent as {_named(self._stream)} does not have that " @@ -277,13 +314,20 @@ def _check_schema(self, batch: pa.RecordBatch) -> None: async def send(self, batch: pa.RecordBatch) -> None: """Send one Arrow record batch of the stream's transport columns. + A batch with no rows is checked and not kept. A send waiting for a reader's + room when the channel is closed or failed raises at once and publishes + nothing more. + Raises: - ChannelClosed: If the channel is closed or failed. + ChannelClosed: If the channel is closed. + UpstreamFailedError: If the channel failed (``fail``); its cause is the + producer's error. ValueError: If the batch's schema is not the stream's. """ - if self._closed or self._error is not None: - raise ChannelClosed("Cannot send to a closed channel") + self._raise_if_ended() self._check_schema(batch) + if not batch.num_rows: + return self._sent += 1 if self._retain: self._batches.append(batch) @@ -293,6 +337,7 @@ async def send(self, batch: pa.RecordBatch) -> None: # The slowest reader sets the pace; one that closed is not waited for. while reader.open and len(reader.queue) >= self._buffer_size: await self._changed.wait() + self._raise_if_ended() if reader.open: reader.queue.append(batch) # At once, not after the last reader: this reader may be waiting for @@ -391,27 +436,67 @@ def _named(stream: Any) -> str: # pyright: ignore[reportExplicitAny] # any str return repr(label) if label else repr(stream) -def _schema_mismatch(declared: pa.Schema, sent: pa.Schema) -> str | None: - """Say how a record batch's schema differs from a channel's, or ``None``. +def _schema_mismatch(declared: pa.Schema, batch: pa.RecordBatch) -> str | None: + """Say how a record batch's columns differ from a channel's, or ``None``. - The two schemas agree when they have the same columns in the same order, each with - the same Arrow type and nullability. What a description does not say of a row is - not compared: a ``null`` column, which rows carry as ``large_string``, and whether - a system-tag or source-info field is nullable, which follows the values of the - complete table (``_flag_by_values``). + The batch must have the description's columns in the same order, each with exactly + the description's type in its large variant (no other representation is taken and + converted: type strictness), the same nullability and the same field metadata. A + ``null`` type of the description (anywhere in a column's type) is carried as + ``large_string``, as a row's datagram stores it, and only null values are taken + there. Whether a system-tag or source-info field is nullable is not compared: it + follows the values of the complete table (``_flag_by_values``). """ + sent = batch.schema if declared.names != sent.names: return f"it has {sent.names}, the stream has {declared.names}" - for expected, column in zip(declared, sent): - expected_type = arrow_utils.normalize_to_large_types(expected.type) - if expected_type != arrow_utils.normalize_to_large_types(column.type): - return f"column {column.name!r} is {column.type}, the stream's is {expected.type}" - if expected.nullable != column.nullable and not column.name.startswith( - (constants.SYSTEM_TAG_PREFIX, constants.SOURCE_PREFIX) + provenance = (constants.SYSTEM_TAG_PREFIX, constants.SOURCE_PREFIX) + for index, (expected, column) in enumerate(zip(declared, sent)): + carried = arrow_utils.normalize_to_large_types(expected.type) + if column.type != carried: + return f"column {column.name!r} is {column.type}, the stream's is {carried}" + if carried != expected.type and not _holds_only_nulls( + batch.column(index), expected.type ): + return ( + f"column {column.name!r} holds values where the stream's type " + + f"{expected.type} holds only nulls" + ) + if column.name.startswith(provenance): + continue + if expected.nullable != column.nullable: flags = {True: "nullable", False: "not nullable"} return ( f"column {column.name!r} is {flags[column.nullable]}, the stream's is " + flags[expected.nullable] ) + if (expected.metadata or None) != (column.metadata or None): + return ( + f"column {column.name!r} has field metadata {column.metadata}, the " + + f"stream's is {expected.metadata}" + ) return None + + +def _holds_only_nulls(array: pa.Array[Any], declared: pa.DataType) -> bool: # pyright: ignore[reportExplicitAny] # any column + """Whether ``array`` is null wherever ``declared`` has the ``null`` type. + + Args: + array: A column as carried (``null`` as ``large_string``). + declared: The column's type in the description. + """ + if pa.types.is_null(declared): + return array.null_count == len(array) + if isinstance(declared, (pa.ListType, pa.LargeListType, pa.FixedSizeListType)): + return _holds_only_nulls(array.flatten(), declared.value_type) # pyright: ignore[reportAttributeAccessIssue, reportUnknownMemberType, reportUnknownArgumentType] + if isinstance(declared, pa.StructType): + return all( + _holds_only_nulls(array.field(i), declared.field(i).type) # pyright: ignore[reportAttributeAccessIssue, reportUnknownMemberType, reportUnknownArgumentType] + for i in range(declared.num_fields) + ) + if isinstance(declared, pa.MapType): + return _holds_only_nulls(array.keys, declared.key_type) and _holds_only_nulls( # pyright: ignore[reportAttributeAccessIssue, reportUnknownMemberType, reportUnknownArgumentType] + array.items, # pyright: ignore[reportAttributeAccessIssue, reportUnknownMemberType, reportUnknownArgumentType] + declared.item_type, + ) + return True diff --git a/tests/test_channels/test_record_batch_channels.py b/tests/test_channels/test_record_batch_channels.py index 4feb7b7ed..a4348b205 100644 --- a/tests/test_channels/test_record_batch_channels.py +++ b/tests/test_channels/test_record_batch_channels.py @@ -359,6 +359,214 @@ async def through() -> Any: assert table.schema.field("_source_x").nullable # one token is null +def test_a_batch_in_another_representation_is_refused() -> None: + """Type strictness at ``send``: exactly the description's types in their large + variants (``string`` for a ``large_string`` column is refused, never converted), + the description's field metadata, and only nulls where the description has + ``null``.""" + stream = source() + (batch,) = batches_of(stream) + note = batch.schema.get_field_index("note") + narrow = batch.set_column(note, "note", batch.column("note").cast(pa.string())) + tagged = pa.RecordBatch.from_arrays( + batch.columns, + schema=batch.schema.set( + note, batch.schema.field(note).with_metadata({"unit": "mV"}) + ), + ) + nulls = ArrowTableStream( + pa.table( + { + "k": pa.array([1, 2], pa.int64()), + "x": pa.array([1.5, 2.5], pa.float64()), + "unknown": pa.array([None, None], pa.null()), + } + ), + tag_columns=["k"], + ) + (null_batch,) = batches_of(nulls) + unknown = null_batch.schema.get_field_index("unknown") + filled = null_batch.set_column( + unknown, + null_batch.schema.field(unknown), + pa.array(["a value", None], pa.large_string()), + ) + + async def write() -> None: + output = OutputChannel(stream) + with pytest.raises(ValueError, match="column 'note' is string"): + await output.send(narrow) + with pytest.raises(ValueError, match="column 'note' has field metadata"): + await output.send(tagged) + await output.send(batch) + null_output = OutputChannel(nulls) + with pytest.raises(ValueError, match="'unknown' holds values"): + await null_output.send(filled) + await null_output.send(null_batch) + + run(write) + + +def test_a_batch_with_no_rows_is_checked_and_not_kept() -> None: + """A zero-row batch is not held, retained or queued, and no reader gets it.""" + stream = source(3) + (batch,) = batches_of(stream) + empty = batch.slice(0, 0) + + async def write() -> tuple[list[int], list[int], int]: + kept = OutputChannel(stream) + queued = OutputChannel(stream, retain=False, buffer_size=1) + reader = queued.open_reader() + for output in (kept, queued): + for _ in range(3): + await output.send(empty) # never waits, also with one slot + with pytest.raises(ValueError): + await output.send(empty.rename_columns(["x"] * empty.num_columns)) + await kept.send(batch) + await kept.close() + await queued.close() + late = kept.open_reader() + return ( + [b.num_rows for b in await late.collect()], + [b.num_rows for b in await reader.collect()], + kept.result().as_table().num_rows, + ) + + assert run(write) == ([3], [], 3) + + +@pytest.mark.parametrize("ending", ["close", "fail"]) +def test_a_waiting_send_ends_when_the_channel_ends(ending: str) -> None: + """A send waiting for a reader's room when the channel is closed or failed raises + at once (``ChannelClosed``, or the failure) and its batch is never delivered.""" + stream = source(2) + first, second = batches_of(stream, 1) + boom = OSError("disk gone") + + async def write() -> tuple[type[object], list[int]]: + output = OutputChannel(stream, retain=False, buffer_size=1) + reader = output.open_reader() + await output.send(first) # fills the one slot + waiting = asyncio.ensure_future(output.send(second)) + await asyncio.sleep(0) + assert not waiting.done() + if ending == "close": + await output.close() + else: + output.fail(boom) + raised = await asyncio.wait_for( + asyncio.gather(waiting, return_exceptions=True), 1 + ) + delivered: list[int] = [] + try: + async for batch in reader: + delivered.append(batch.num_rows) + except UpstreamFailedError: + pass + return type(raised[0]), delivered + + raised, delivered = run(write) + if ending == "close": + assert raised is ChannelClosed + assert delivered == [1] # the batch sent before the close, not the waiting one + else: + assert raised is UpstreamFailedError + assert delivered == [] # a failure is seen at once + + +@pytest.mark.parametrize("ending", ["close", "fail"]) +def test_a_send_scheduled_before_the_end_of_a_retained_output_publishes_nothing( + ending: str, +) -> None: + """Retained: a send that has not run when the channel ends raises, and the result + and every reader hold only what was sent before.""" + stream = source(2) + first, second = batches_of(stream, 1) + + async def write() -> tuple[type[object], list[int]]: + output = OutputChannel(stream) + await output.send(first) + scheduled = asyncio.ensure_future(output.send(second)) + if ending == "close": + await output.close() + else: + output.fail(OSError("disk gone")) + (raised,) = await asyncio.gather(scheduled, return_exceptions=True) + rows = [first.num_rows] + if ending == "close": + rows = [b.num_rows for b in await output.open_reader().collect()] + assert output.result().as_table().num_rows == 1 + return type(raised), rows + + raised, rows = run(write) + assert raised is (ChannelClosed if ending == "close" else UpstreamFailedError) + 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 + 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"): + output = OutputChannel(stream, retain=False, buffer_size=4) + reader = output.open_reader() + reading = asyncio.ensure_future(getattr(reader, read)()) + await output.send(first) + await asyncio.sleep(0) + await reader.close() + await output.send(second) + await output.close() + with pytest.raises(ChannelClosed, match="closed before its producer"): + _ = await reading + + run(write) + + +def test_a_cancelled_read_closes_the_reader_and_frees_the_producer() -> None: + """Cancelling a waiting ``receive()`` closes that reader: the producer is not held + by a consumer that stopped reading.""" + stream = source(3) + batches = batches_of(stream, 1) + + async def write() -> None: + output = OutputChannel(stream, retain=False, buffer_size=1) + reader = output.open_reader() + waiting = asyncio.ensure_future(reader.receive()) + await asyncio.sleep(0) + _ = waiting.cancel() + with pytest.raises(asyncio.CancelledError): + _ = await waiting + for batch in batches: # would wait forever on the abandoned reader + await asyncio.wait_for(output.send(batch), 1) + with pytest.raises(ChannelClosed): + _ = await reader.receive() + + run(write) + + +def test_a_closed_reader_is_unregistered() -> None: + """``close()`` removes the reader from its output channel: readers opened and + closed leave nothing for a send to walk.""" + stream = source(2) + batches = batches_of(stream, 1) + + async def write() -> int: + output = OutputChannel(stream, retain=False) + for _ in range(100): + await output.open_reader().close() + staying = output.open_reader() + for batch in batches: + await output.send(batch) + await output.close() + assert len(await staying.collect()) == 2 + return len(output._readers) # pyright: ignore[reportPrivateUsage] # registration is what is tested + + assert run(write) == 1 + + # --- Retained output: readers at their own position, send never waits ------------------- @@ -523,8 +731,9 @@ async def write() -> list[BaseException]: output.fail(boom) output.fail(RuntimeError("a second failure changes nothing")) await output.close() # nor does a close - with pytest.raises(ChannelClosed): + with pytest.raises(UpstreamFailedError) as refused: await output.send(batches[1]) + assert refused.value.__cause__ is boom with pytest.raises(RuntimeError, match="has no result"): _ = output.result() errors: list[BaseException] = [] diff --git a/tests/test_core/operators/test_record_batch_execution.py b/tests/test_core/operators/test_record_batch_execution.py index 29d962067..0b554e198 100644 --- a/tests/test_core/operators/test_record_batch_execution.py +++ b/tests/test_core/operators/test_record_batch_execution.py @@ -20,20 +20,22 @@ import asyncio import itertools import math -from collections.abc import Sequence +from collections.abc import Callable, Sequence from typing import Any +import polars as pl import pyarrow as pa import pytest import orcapod.core.operators as operators -from orcapod.core.operators import Batch +from orcapod.core.operators import AddTags, Batch, PolarsFilter, SelectDataColumns from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod from orcapod.core.record_batch_channels import ( InputChannel, OutputChannel, channel_from_stream, ) +from orcapod.core.streams import ArrowTableStream from orcapod.protocols.core_protocols import StreamProtocol from tests.test_core.operators.test_async_sync_equivalence import ( AFTER_OPERATOR_CASES, @@ -319,3 +321,211 @@ async def go() -> tuple[int, int]: return first.num_rows, sum(batch.num_rows for batch in rest) assert asyncio.run(go()) == (1, 1) + + +# --- The oracle of a barrier operator: what a job's sync path gives it ------------------ + + +def _outcome(make: Callable[[], StreamProtocol]) -> tuple[str, Any]: + """The rows a stream gives, or the kind of error that refuses it.""" + try: + return ("rows", make().as_table().to_pylist()) + except Exception as error: # noqa: BLE001 # the refusal is the outcome compared + return ("refused", type(error).__name__) + + +BARRIER_ORACLE_CASES: dict[ + str, tuple[Callable[[], StreamProtocol], Callable[[], StaticOutputOperatorPod]] +] = { + # A null column reaches an operator as large_string (a row's datagram stores it so). + "null_column": ( + lambda: ArrowTableStream( + pa.table( + { + "k": pa.array([1, 2, 3], pa.int64()), + "x": pa.array([None, None, None], pa.null()), + "y": pa.array([1, 2, 3], pa.int64()), + } + ), + tag_columns=["k"], + ), + lambda: PolarsFilter([(pl.col("x") + 1).is_null()]), + ), + # A predicate that selects by position reads the columns in row order. + "position_predicate": ( + lambda: ArrowTableStream( + pa.table( + { + "x": pa.array([2, -4], pa.int64()), + "k": pa.array([-1, 2], pa.int64()), + "z": pa.array([10, 20], pa.int64()), + "j": pa.array([5, 6], pa.int64()), + } + ), + tag_columns=["k", "j"], + ), + lambda: PolarsFilter([pl.first() > 0]), + ), +} + + +@pytest.mark.parametrize("label", list(BARRIER_ORACLE_CASES)) +def test_a_barrier_operator_sees_its_input_as_a_job_gives_it(label: str) -> None: + """The record-batch form is held to what a job's sync path gives an operator: the + upstream rebuilt from its rows (``_materialize_upstream``: ``null`` as + ``large_string``, the columns in row order), not the raw stream it came from. A + predicate that reads a ``null`` column's type or the column order follows that + form (documented behaviour, e5); in a job neither case reaches an operator: a + source refuses a ``null`` column, and a job refuses an expression that selects + columns by position.""" + make_stream, make_op = BARRIER_ORACLE_CASES[label] + stream = make_stream() + oracle = _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"): + assert ( + _outcome(lambda: run_on_channels(make_op(), [stream], LAYOUTS[layout])) + == oracle + ) + # The raw stream gives another outcome: the case tells the two oracles apart. + assert _outcome(lambda: make_op()(stream)) != oracle + + +# --- Arrivals from another producer ------------------------------------------------------- + + +def test_batch_takes_arrivals_whose_provenance_flags_differ() -> None: + """``AddTags`` feeding ``Batch(2)`` row by row: each arriving batch is built from its + own rows, so a source-info field is nullable in one (a null token) and not in the + next. ``Batch`` puts them together and gives the sync result.""" + raw = ArrowTableStream( + pa.table( + { + "k": pa.array([1, 2, 3, 4], pa.int64()), + "x": pa.array([1.5, 2.5, 3.5, 4.5], pa.float64()), + "_source_x": pa.array( + [None, "s::r1::x", "s::r2::x", None], pa.large_string() + ), + } + ), + tag_columns=["k"], + ) + expected = R(Batch(batch_size=2)(AddTags({"cohort": "A"})(raw))) + assert expected is not None + add, batch = AddTags({"cohort": "A"}), Batch(batch_size=2) + + async def go() -> tuple[StreamProtocol, set[bool]]: + tagged = add(raw) + middle = OutputChannel(tagged) + output = OutputChannel(batch(tagged)) + reader = middle.open_reader() + _ = await asyncio.wait_for( + asyncio.gather( + add.async_execute_batches([await _channel(raw, (1,))], middle), + batch.async_execute_batches([reader], output), + ), + TIMEOUT, + ) + flags = { + b.schema.field("_source_x").nullable + for b in await middle.open_reader().collect() + } + return output.result(), flags + + result, flags = asyncio.run(go()) + assert flags == {True, False} # the arrivals did differ + assert_same_table(result.as_table(columns=ALL), expected) + assert result.as_table(columns=ALL).to_pylist() == expected.to_pylist() + + +# --- The row-built form, F (stage 2, ITL-1360) ---------------------------------------------- + +SYSTEM_TAG = "_tag_source_id::abc" + + +@pytest.mark.xfail( + strict=True, + raises=AssertionError, + reason="TODO(ITL-1360): F (stage 2's _row_built_form) keeps system-tag field " + "metadata and a list's item field, where a table built from rows has neither", +) +def test_the_provenance_columns_have_the_row_built_schema() -> None: + """A raw stream whose system-tag field carries metadata and whose list-valued + source info has a non-nullable item named ``member``: the channel result's + provenance fields are those of the table built from the sync rows.""" + schema = pa.schema( + [ + pa.field("k", pa.int64()), + pa.field(SYSTEM_TAG, pa.large_string(), metadata={"m": "1"}), + pa.field("x", pa.int64()), + pa.field("z", pa.int64()), + pa.field("y", pa.int64()), + pa.field( + "_source_x", + pa.large_list(pa.field("member", pa.large_string(), nullable=False)), + ), + ] + ) + raw = ArrowTableStream( + pa.table( + [ + pa.array([1, 2], pa.int64()), + pa.array(["s", "s"], pa.large_string()), + pa.array([1, 2], pa.int64()), + pa.array([3, 4], pa.int64()), + pa.array([5, 6], pa.int64()), + pa.array([["a"], ["b"]], schema.field("_source_x").type), + ], + schema=schema, + ), + tag_columns=["k"], + ) + expected = R(SelectDataColumns(["x", "z"])(raw)) + assert expected is not None + for layout in ("one_batch", "one_row_per_batch"): + result = run_on_channels(SelectDataColumns(["x", "z"]), [raw], LAYOUTS[layout]) + assert_same_table(result.as_table(columns=ALL), expected) + + +@pytest.mark.xfail( + strict=True, + raises=(AssertionError, KeyError), + reason="TODO(ITL-1360): F (stage 2's _row_built_columns) carries a raw stream's " + "meta (__) columns and their source info as data (the data keys name a meta " + "column, which the zero-row table a description is read from lacks)", +) +def test_a_meta_column_does_not_travel() -> None: + """A raw stream with a meta column: neither it nor a source-info column of it is + in the record batches or in the stream rebuilt from them, as in the table built + from the stream's rows.""" + raw = ArrowTableStream( + pa.table( + { + "k": pa.array([1, 2], pa.int64()), + "x": pa.array([1, 2], pa.int64()), + "z": pa.array([3, 4], pa.int64()), + "__note": pa.array(["a", "b"], pa.large_string()), + } + ), + tag_columns=["k"], + ) + expected = R(raw) + assert expected is not None + + async def go() -> tuple[list[str], StreamProtocol]: + batches = await channel_from_stream(raw).collect() + output = OutputChannel(raw) + for batch in batches: + await output.send(batch) + await output.close() + return batches[0].schema.names, output.result() + + wire, rebuilt = asyncio.run(go()) + assert wire == expected.schema.names + assert rebuilt.as_table(columns=ALL).schema.names == expected.schema.names From a63bae5eae26adc64ea80515611fe51788b38f70 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 03:24:40 -0800 Subject: [PATCH 08/12] refactor(channels): stage 2's F verbatim (row_built_columns, row_built_names, row_built_provenance in streams/base.py; _flag_by_values, _row_built_form, _output_stream); F's two tests pass (ITL-1362) transport_schema follows stage 2's stream_arrow_schema recipe (still interim, TODO(ITL-1360)). row_built_provenance casts the schema metadata for the pyarrow stubs (the one line that differs from stage 2's b58decad, to be adopted there). Co-Authored-By: Claude Opus 5.5 --- .../core/operators/static_output_pod.py | 101 +++--------- src/orcapod/core/record_batch_channels.py | 7 +- src/orcapod/core/streams/base.py | 149 ++++++++++++++++++ .../operators/test_record_batch_execution.py | 15 +- 4 files changed, 178 insertions(+), 94 deletions(-) diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index 33f38b796..745b7b5b1 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -40,6 +40,7 @@ short_stream_repr, typed_zero_row_input, typed_zero_row_table, + row_built_columns, ) from orcapod.core.streams.view import ( STALE_NOTE, @@ -463,60 +464,6 @@ def _kept_output( return StaticOutputOperatorPod._materialize_to_stream(rows) return StaticOutputOperatorPod._zero_rows_in_row_order(result) - # TODO(ITL-1360): stage 2 defines F; this is its definition, copied unchanged from - # that branch until it is on eywalker/job-speed. - @staticmethod - def _row_built_columns( - table: pa.Table, keys: tuple[Sequence[str], Sequence[str]] - ) -> pa.Table: - """Return ``table``'s columns as ``_rows_to_table`` lays out the table's rows. - - Every step of F (``_row_built_form``) that each row decides on its own, so it - gives the same result on a whole table and on each slice of it: - - 1. The columns a row-built table holds: the user tags, the system tags, the data - columns that are not data-tags, and the source info of every data column (a - data-tag's included). ``table`` holds no context, meta or content-hash column - (``ZERO_ROW_INPUT_COLUMNS``). - 2. In row order: user tags in tag order, system tags in table order, then the data - columns and their source info, both in the order of the data keys. A row's - ``Data`` lists its source info in the order of its data keys, data-tags first - in tag order (``Data._ensure_source_info_table``), so a data-tag's source info - comes before the other data columns' even when the data-tag is not the first - column of ``table``. - 3. Normalized to the large types without keeping ``null``: each row's datagram - stores a ``null`` column as ``large_string`` (``Datagram._init_from_table``). - - Whether a system-tag or source-info field is nullable depends on its values over - the complete table (``_flag_by_values``), so it is not decided here. - - Args: - table: A table of user tags, system tags, data and source info. - keys: The tag keys and the data keys of the stream ``table`` belongs to - (``stream.keys()``). - - Returns: - The same arrays, selected and ordered, in their large types. - """ - from orcapod.system_constants import constants - from orcapod.utils import arrow_utils - - tag_keys, data_keys = keys - names = set(table.column_names) - tags = set(tag_keys) - system_tags = [ - n for n in table.column_names if n.startswith(constants.SYSTEM_TAG_PREFIX) - ] - data = [n for n in data_keys if n not in tags] - source_info = [ - f"{constants.SOURCE_PREFIX}{n}" - for n in data_keys - if f"{constants.SOURCE_PREFIX}{n}" in names - ] - return arrow_utils.normalize_table_to_large_types( - table.select([*tag_keys, *system_tags, *data, *source_info]) - ) - @staticmethod def _flag_by_values(table: pa.Table) -> pa.Table: """Flag each system-tag and source-info field nullable only when it holds a null. @@ -553,7 +500,7 @@ def _row_built_form( """Return ``table`` as ``_rows_to_table`` builds it from the table's own rows. F in the ITL-1347 spec: the same table, without making the rows. The columns, - their order and their types are decided row by row (``_row_built_columns``), the + their order and their types are decided row by row (``streams.base.row_built_columns``), the system-tag and source-info field flags by their values over the whole table (``_flag_by_values``). The equality with ``_rows_to_table`` is tested over every operator, source kind and column role (ITL-1347, L0-L2). @@ -566,9 +513,7 @@ def _row_built_form( Returns: The table ``_rows_to_table`` would build from its rows. """ - return StaticOutputOperatorPod._flag_by_values( - StaticOutputOperatorPod._row_built_columns(table, keys) - ) + return StaticOutputOperatorPod._flag_by_values(row_built_columns(table, keys)) @staticmethod def _output_stream( @@ -1008,7 +953,7 @@ async def _send_result(result: StreamProtocol, output: RecordBatchOutput) -> Non result: An operator's result. output: The channel to send into; a result with no rows sends nothing. """ - table = StaticOutputOperatorPod._row_built_columns( + table = row_built_columns( result.as_table(columns=ZERO_ROW_INPUT_COLUMNS), result.keys() ) for batch in table.to_batches(): @@ -1046,10 +991,12 @@ async def _streams_of(inputs: Sequence[RecordBatchInput]) -> list[StreamProtocol def transport_schema(stream: StreamProtocol) -> pa.Schema | None: """Return the schema ``stream``'s record batches have, from its description. - Never computes, reads or polls a row: it is the schema of the stream's zero-row - input in the row-built form (``_row_built_columns``), except that a ``null`` type - is kept, as the description declares it (record batches carry it as - ``large_string``, holding only nulls). + Never computes, reads or polls a row: the stream's zero-row input with the columns + of F in F's order (``row_built_names``) and its provenance fields as a row builds + them (``row_built_provenance``), as ``stream_arrow_schema`` of stage 2 gives it. A + ``null`` type is kept, as the description declares it (record batches carry it as + ``large_string``, holding only nulls). The flags of system-tag and source-info + fields are not part of it: they follow the values of the complete table. Args: stream: The describing stream. @@ -1059,23 +1006,25 @@ def transport_schema(stream: StreamProtocol) -> pa.Schema | None: rows (an unbound input slot, a source that has not polled yet). """ # TODO(ITL-1360): ``stream.arrow_schema()``, once every stream has it. + from orcapod.core.streams.base import row_built_names, row_built_provenance + from orcapod.utils import arrow_utils + typed = StaticOutputOperatorPod._zero_row_input(stream) # pyright: ignore[reportPrivateUsage] # the zero-row form of an input if typed is None: return None - from orcapod.utils import arrow_utils - zero_rows = typed.as_table(columns=ZERO_ROW_INPUT_COLUMNS) - built = StaticOutputOperatorPod._row_built_columns(zero_rows, stream.keys()) # pyright: ignore[reportPrivateUsage] # F, stage 2's - return pa.schema( - [ - field.with_type( - arrow_utils.normalize_to_large_types( - zero_rows.schema.field(field.name).type, keep_null=True + zero_rows = zero_rows.cast( + pa.schema( + [ + field.with_type( + arrow_utils.normalize_to_large_types(field.type, keep_null=True) ) - ) - for field in built.schema - ] + for field in zero_rows.schema + ] + ) ) + names = row_built_names(zero_rows.column_names, stream.keys()) + return row_built_provenance(zero_rows.select(names)).schema def stream_from_batches( @@ -1096,7 +1045,7 @@ def stream_from_batches( Args: stream: The describing stream: the node or stream the rows are of. - batches: Its rows (``_row_built_columns``), in order. + batches: Its rows (``row_built_columns``), in order. Returns: A complete, re-readable stream over the rows. @@ -1111,7 +1060,7 @@ def with_open_provenance_flags(batch: pa.RecordBatch) -> pa.RecordBatch: """Flag every system-tag and source-info field of ``batch`` nullable. Record batches of one channel differ at most in these flags: each is built from its - own rows (``_row_built_columns`` leaves them, ``_flag_by_values`` sets them over a + own rows (``row_built_columns`` leaves them, ``_flag_by_values`` sets them over a complete table). Opened, they have one schema and can be put under one another; the complete table's flags are then set by its values. The same arrays. diff --git a/src/orcapod/core/record_batch_channels.py b/src/orcapod/core/record_batch_channels.py index d0086107e..aa1ea88b4 100644 --- a/src/orcapod/core/record_batch_channels.py +++ b/src/orcapod/core/record_batch_channels.py @@ -22,11 +22,10 @@ from orcapod.channels import ChannelClosed from orcapod.core.operators.static_output_pod import ( - StaticOutputOperatorPod, stream_from_batches, transport_schema, ) -from orcapod.core.streams.base import ZERO_ROW_INPUT_COLUMNS +from orcapod.core.streams.base import ZERO_ROW_INPUT_COLUMNS, row_built_columns from orcapod.errors import UpstreamFailedError from orcapod.system_constants import constants from orcapod.utils import arrow_utils @@ -68,7 +67,7 @@ async def next(self) -> pa.RecordBatch | None: if self._batches is None: # On the first read, not when the channel is opened: opening computes # nothing. - table = StaticOutputOperatorPod._row_built_columns( # pyright: ignore[reportPrivateUsage] # F, stage 2's + table = row_built_columns( self._stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS), self._stream.keys(), ) @@ -416,7 +415,7 @@ def result(self) -> StreamProtocol: 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 + 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. diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py index 273d66f9b..f4c28d96a 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -34,6 +34,7 @@ StreamProtocol, TagProtocol, ) +from orcapod.system_constants import constants from orcapod.types import ColumnConfig, Schema from orcapod.utils import arrow_utils @@ -184,6 +185,154 @@ def typed_zero_row_input(stream: object) -> pa.Table | None: ) +def row_built_columns( + table: pa.Table, keys: tuple[Sequence[str], Sequence[str]] +) -> pa.Table: + """Return ``table``'s columns as a table built from its rows lays them out. + + Every step of F (``StaticOutputOperatorPod._row_built_form``) that each row decides on its own, so it + gives the same result on a whole table and on each slice of it: + + 1. The columns a row-built table holds: the user tags, the system tags, the data + columns that are not data-tags, and the source info of every data column (a + data-tag's included). ``table`` holds no context, meta or content-hash column + (``ZERO_ROW_INPUT_COLUMNS``). + 2. In row order: user tags in tag order, system tags in table order, then the data + columns and their source info, both in the order of the data keys. A row's + ``Data`` lists its source info in the order of its data keys, data-tags first + in tag order (``Data._ensure_source_info_table``), so a data-tag's source info + comes before the other data columns' even when the data-tag is not the first + column of ``table``. + 3. Normalized to the large types without keeping ``null``: each row's datagram + stores a ``null`` column as ``large_string`` (``Datagram._init_from_table``). + 4. The system-tag and source-info fields as a row builds them from its values + (``row_built_provenance``): no field metadata, and a source-info list of the + form its tokens give. + + Whether a system-tag or source-info field is nullable depends on its values over + the complete table (``StaticOutputOperatorPod._flag_by_values``), so it is not + decided here. + + Args: + table: A table of user tags, system tags, data and source info. + keys: The tag keys and the data keys of the stream ``table`` belongs to + (``stream.keys()``). + + Returns: + The same values, selected and ordered, in their large types. + """ + return row_built_provenance( + arrow_utils.normalize_table_to_large_types( + table.select(row_built_names(table.column_names, keys)) + ) + ) + + +def _source_info_value_type(kind: pa.DataType) -> pa.DataType: + """The Arrow type a row gives a source-info column of type ``kind``. + + A row's ``Data`` types its tokens from their Python values + (``arrow_utils.source_info_arrow_type``): a string as ``large_string``, a list as + ``large_list`` of its element's type, with the item field named ``item`` and + nullable. A type of any other kind is left as it is. + """ + if ( + pa.types.is_list(kind) + or pa.types.is_large_list(kind) + or pa.types.is_fixed_size_list(kind) + ): + return pa.large_list(_source_info_value_type(kind.value_type)) # pyright: ignore[reportAttributeAccessIssue, reportUnknownArgumentType, reportUnknownMemberType] # a list type has a value type + if ( + pa.types.is_string(kind) + or pa.types.is_large_string(kind) + or pa.types.is_null(kind) + ): + return pa.large_string() + return kind + + +def row_built_provenance(table: pa.Table) -> pa.Table: + """Give ``table``'s system-tag and source-info fields the form a row builds. + + A row rebuilds its system tags and its source info from their values, so their + fields carry no field metadata, and a source-info column has the type its tokens + give (``_source_info_value_type``): a list's item field named ``item`` and + nullable at every depth. The values are unchanged: a type that differs only in + its item fields is cast. The fields' nullability is left as it is + (``StaticOutputOperatorPod._flag_by_values`` decides it). Other fields are not + touched. + + Args: + table: A table of user tags, system tags, data and source info. + + Returns: + The same values under the rebuilt fields. + """ + fields: list[pa.Field[pa.DataType]] = [] + columns: list[Any] = [] + changed = False + for field, column in zip(table.schema, table.columns, strict=True): + if field.name.startswith(constants.SOURCE_PREFIX): + kind = _source_info_value_type(field.type) + if kind != field.type: + column = column.cast(kind) + new_field = pa.field(field.name, kind, nullable=field.nullable) + elif field.name.startswith(constants.SYSTEM_TAG_PREFIX): + new_field = field.remove_metadata() + else: + new_field = field + changed = changed or not new_field.equals(field, check_metadata=True) + fields.append(new_field) + columns.append(column) + if not changed: + return table + return pa.Table.from_arrays( + columns, + schema=pa.schema( + fields, cast("dict[bytes | str, bytes | str] | None", table.schema.metadata) + ), + ) + + +def row_built_names( + names: Sequence[str], keys: tuple[Sequence[str], Sequence[str]] +) -> list[str]: + """Return the columns of a table built from rows, in row order (F steps 1-2). + + The table built from rows is ``StaticOutputOperatorPod._rows_to_table``'s; this and + ``row_built_columns`` are module functions so that a stream applies them without + importing the operators (ITL-1347). + + The user tags in tag order, the system tags in the order of ``names``, the data + columns that are not data-tags or meta columns, then the source info of every + such data column and data-tag; data + and source info in the order of the data keys (a row's ``Data`` lists its source + info so, data-tags first in tag order: ``Data._ensure_source_info_table``). + + Args: + names: The column names of a table of user tags, system tags, data and + source info. + keys: The tag keys and the data keys of the stream the table belongs to. + + Returns: + The names a table built from rows holds, in its order. + """ + tag_keys, data_keys = keys + present = set(names) + tags = set(tag_keys) + system_tags = [n for n in names if n.startswith(constants.SYSTEM_TAG_PREFIX)] + # A meta (``__``) column is never data: a row's ``Data`` holds it apart, and no + # node passes it on (ITL-1080). + data_keys = [n for n in data_keys if not n.startswith(constants.META_PREFIX)] + data = [n for n in data_keys if n not in tags] + source_info = [ + f"{constants.SOURCE_PREFIX}{n}" + for n in data_keys + if f"{constants.SOURCE_PREFIX}{n}" in present + ] + return [*tag_keys, *system_tags, *data, *source_info] + + def typed_arrow_schemas( stream: object, *, own: bool = True ) -> tuple[pa.Schema, pa.Schema]: diff --git a/tests/test_core/operators/test_record_batch_execution.py b/tests/test_core/operators/test_record_batch_execution.py index 0b554e198..0fe878499 100644 --- a/tests/test_core/operators/test_record_batch_execution.py +++ b/tests/test_core/operators/test_record_batch_execution.py @@ -444,17 +444,11 @@ async def go() -> tuple[StreamProtocol, set[bool]]: assert result.as_table(columns=ALL).to_pylist() == expected.to_pylist() -# --- The row-built form, F (stage 2, ITL-1360) ---------------------------------------------- +# --- The row-built form, F (stage 2, ITL-1360) --------------------------------------------- SYSTEM_TAG = "_tag_source_id::abc" -@pytest.mark.xfail( - strict=True, - raises=AssertionError, - reason="TODO(ITL-1360): F (stage 2's _row_built_form) keeps system-tag field " - "metadata and a list's item field, where a table built from rows has neither", -) def test_the_provenance_columns_have_the_row_built_schema() -> None: """A raw stream whose system-tag field carries metadata and whose list-valued source info has a non-nullable item named ``member``: the channel result's @@ -493,13 +487,6 @@ def test_the_provenance_columns_have_the_row_built_schema() -> None: assert_same_table(result.as_table(columns=ALL), expected) -@pytest.mark.xfail( - strict=True, - raises=(AssertionError, KeyError), - reason="TODO(ITL-1360): F (stage 2's _row_built_columns) carries a raw stream's " - "meta (__) columns and their source info as data (the data keys name a meta " - "column, which the zero-row table a description is read from lacks)", -) def test_a_meta_column_does_not_travel() -> None: """A raw stream with a meta column: neither it nor a source-info column of it is in the record batches or in the stream rebuilt from them, as in the table built From 82b5af801a5277884aa2d8cef141117174febfc7 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 03:39:45 -0800 Subject: [PATCH 09/12] fix(channels): Codex round 2 on #483: a close during a send fails the channel, an early-closed input fails every loop, metadata at every depth, nulls on values sent, names without Arrow types (ITL-1362) - close() while a send waits for a reader's room fails the channel (the send raises ChannelClosed; readers' next read raises UpstreamFailedError caused by ChannelClosed): readers never complete normally with different inputs - an input reader closed before its producer completed raises ChannelClosed from receive() and from iteration, so no loop (row by row, Batch by arrival, barrier) takes it for the end; the operator fails its output - send compares user-field metadata at every depth; provenance fields carry none at any depth - the null-only rule reads the logical values of the slice sent (validity- and slice-aware; maps through their entries) - without Arrow types in the description, a batch whose names contradict the stream's keys is refused - tests: all of the above; F's two raw-stream edges as strict xfails (TODO(ITL-1360)) Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/record_batch_channels.py | 161 +++++++++++++---- .../test_record_batch_channels.py | 162 ++++++++++++++++-- .../operators/test_record_batch_execution.py | 117 +++++++++++++ 3 files changed, 393 insertions(+), 47 deletions(-) diff --git a/src/orcapod/core/record_batch_channels.py b/src/orcapod/core/record_batch_channels.py index aa1ea88b4..927e0a034 100644 --- a/src/orcapod/core/record_batch_channels.py +++ b/src/orcapod/core/record_batch_channels.py @@ -19,13 +19,18 @@ from typing import TYPE_CHECKING, Any, Protocol import pyarrow as pa +import pyarrow.compute as pc from orcapod.channels import ChannelClosed from orcapod.core.operators.static_output_pod import ( stream_from_batches, transport_schema, ) -from orcapod.core.streams.base import ZERO_ROW_INPUT_COLUMNS, row_built_columns +from orcapod.core.streams.base import ( + ZERO_ROW_INPUT_COLUMNS, + row_built_columns, + row_built_names, +) from orcapod.errors import UpstreamFailedError from orcapod.system_constants import constants from orcapod.utils import arrow_utils @@ -154,9 +159,14 @@ async def receive(self) -> pa.RecordBatch: a consumer that stops reading never holds its producer. Raises: - ChannelClosed: At the end, and after ``close``. + 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: @@ -165,6 +175,8 @@ async def receive(self) -> pa.RecordBatch: 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 @@ -177,8 +189,17 @@ async def __anext__(self) -> pa.RecordBatch: try: return await self.receive() except ChannelClosed: + if self._closed: + raise # closed before its producer completed: not the end raise StopAsyncIteration + 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. @@ -187,13 +208,7 @@ async def collect(self) -> list[pa.RecordBatch]: what was read is part of the input, never returned as all of it. UpstreamFailedError: If the producer failed or was cancelled. """ - batches = [batch async for batch in self] - if self._closed: - raise ChannelClosed( - f"The input channel of {_named(self._stream)} was closed before its " - + "producer completed; it has no complete input to give." - ) - return batches + 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. @@ -258,6 +273,8 @@ def __init__( self._batches: list[pa.RecordBatch] = [] self._readers: list[_OutputFeed] = [] self._sent = 0 + # Sends waiting for a reader's room (``retain=False`` only). + self._sending = 0 self._closed = False self._error: BaseException | None = None self._result: StreamProtocol | None = None @@ -289,6 +306,8 @@ def _upstream_failed(self) -> UpstreamFailedError: def _raise_if_ended(self) -> None: """Raise what a send meets on an ended channel: closed, or failed.""" + if isinstance(self._error, _ClosedDuringSend): + raise ChannelClosed(str(self._error)) if self._error is not None: raise self._upstream_failed() if self._closed: @@ -300,8 +319,15 @@ def _check_schema(self, batch: pa.RecordBatch) -> None: self._schema = transport_schema(self._stream) self._schema_known = True if self._schema is None: - # No description to check against: the first batch sets the schema, - # which must itself be in the large variants. + # No Arrow types in the description: the first batch sets them (they must + # be in the large variants), but the names are still the stream's. + names = batch.schema.names + if names != row_built_names(names, self._stream.keys()): + raise ValueError( + f"A record batch sent as {_named(self._stream)} does not have that " + + f"stream's columns: it has {names}, the stream's keys are " + + f"{self._stream.keys()}." + ) self._schema = batch.schema mismatch = _schema_mismatch(self._schema, batch) if mismatch is not None: @@ -332,22 +358,40 @@ async def send(self, batch: pa.RecordBatch) -> None: self._batches.append(batch) self._notify() return - for reader in list(self._readers): - # The slowest reader sets the pace; one that closed is not waited for. - while reader.open and len(reader.queue) >= self._buffer_size: - await self._changed.wait() - self._raise_if_ended() - if reader.open: - reader.queue.append(batch) - # At once, not after the last reader: this reader may be waiting for - # the batch while the send waits for another reader's room. - self._notify() + self._sending += 1 + try: + for reader in list(self._readers): + # The slowest reader sets the pace; one that closed is not waited for. + while reader.open and len(reader.queue) >= self._buffer_size: + await self._changed.wait() + self._raise_if_ended() + if reader.open: + reader.queue.append(batch) + # At once, not after the last reader: this reader may be waiting + # for the batch while the send waits for another reader's room. + self._notify() + finally: + self._sending -= 1 async def close(self) -> None: - """Complete the output. A second close does nothing; never waits.""" - if not self._closed and self._error is None: + """Complete the output. A second close does nothing; never waits. + + A close that comes while a send is waiting for a reader's room does not + complete the output: that send may have reached some readers and not others, + and readers never complete normally with different inputs. The channel fails + instead: the waiting send raises ``ChannelClosed``, and every reader's next + read raises ``UpstreamFailedError`` whose cause is a ``ChannelClosed``. + """ + if self._closed or self._error is not None: + return + if self._sending: + self._error = _ClosedDuringSend( + f"The output of {_named(self._stream)} was closed while a record " + + "batch was being sent to its readers." + ) + else: self._closed = True - self._notify() + self._notify() def fail(self, error: BaseException) -> None: """End the output with the producer's failure or cancellation. @@ -462,6 +506,11 @@ def _schema_mismatch(declared: pa.Schema, batch: pa.RecordBatch) -> str | None: + f"{expected.type} holds only nulls" ) if column.name.startswith(provenance): + # A row builds these from its values: no field metadata at any depth. + if column.metadata or not column.type.equals( + _without_metadata(column.type), check_metadata=True + ): + return f"column {column.name!r} carries field metadata" continue if expected.nullable != column.nullable: flags = {True: "nullable", False: "not nullable"} @@ -469,16 +518,40 @@ def _schema_mismatch(declared: pa.Schema, batch: pa.RecordBatch) -> str | None: f"column {column.name!r} is {flags[column.nullable]}, the stream's is " + flags[expected.nullable] ) - if (expected.metadata or None) != (column.metadata or None): + if (expected.metadata or None) != (column.metadata or None) or not ( + column.type.equals(carried, check_metadata=True) + ): return ( - f"column {column.name!r} has field metadata {column.metadata}, the " - + f"stream's is {expected.metadata}" + f"column {column.name!r} has field metadata {column.metadata} (or in " + + f"its type {column.type}), the stream's is {expected.metadata}" ) return None +def _without_metadata(kind: pa.DataType) -> pa.DataType: + """``kind`` with the field metadata of every nested field removed.""" + if isinstance(kind, pa.LargeListType): + return pa.large_list(_field_without_metadata(kind.value_field)) # pyright: ignore[reportUnknownArgumentType, reportUnknownMemberType] + if isinstance(kind, pa.ListType): + return pa.list_(_field_without_metadata(kind.value_field)) # pyright: ignore[reportUnknownArgumentType, reportUnknownMemberType] + if isinstance(kind, pa.FixedSizeListType): + return pa.list_(_field_without_metadata(kind.value_field), kind.list_size) # pyright: ignore[reportUnknownArgumentType, reportUnknownMemberType] + if isinstance(kind, pa.StructType): + return pa.struct( + [_field_without_metadata(kind.field(i)) for i in range(kind.num_fields)] + ) # pyright: ignore[reportUnknownArgumentType, reportUnknownMemberType] + return kind + + +def _field_without_metadata(field: pa.Field[Any]) -> pa.Field[Any]: # pyright: ignore[reportExplicitAny] # any field + return pa.field(field.name, _without_metadata(field.type), nullable=field.nullable) + + def _holds_only_nulls(array: pa.Array[Any], declared: pa.DataType) -> bool: # pyright: ignore[reportExplicitAny] # any column - """Whether ``array`` is null wherever ``declared`` has the ``null`` type. + """Whether ``array``'s values are null wherever ``declared`` has the ``null`` type. + + Judged on the logical values of ``array`` as sent: a slice's own rows only, and + nothing under a null list or struct (its children's buffers are not read). Args: array: A column as carried (``null`` as ``large_string``). @@ -486,16 +559,30 @@ def _holds_only_nulls(array: pa.Array[Any], declared: pa.DataType) -> bool: # p """ if pa.types.is_null(declared): return array.null_count == len(array) - if isinstance(declared, (pa.ListType, pa.LargeListType, pa.FixedSizeListType)): - return _holds_only_nulls(array.flatten(), declared.value_type) # pyright: ignore[reportAttributeAccessIssue, reportUnknownMemberType, reportUnknownArgumentType] + if isinstance( + declared, (pa.ListType, pa.LargeListType, pa.FixedSizeListType, pa.MapType) + ): + if isinstance(array.type, pa.MapType): + # A map's entries as a list of structs, which list_flatten reads. + entries = pa.struct([array.type.key_field, array.type.item_field]) # pyright: ignore[reportAttributeAccessIssue, reportUnknownMemberType, reportUnknownArgumentType] + array = array.cast(pa.large_list(entries)) # pyright: ignore[reportUnknownMemberType] + # The values of the non-null lists of the slice, in order. + values = pc.list_flatten(array) # pyright: ignore[reportUnknownMemberType, reportUnknownVariableType] + if isinstance(declared, pa.MapType): + return _holds_only_nulls( + values.field(0), + declared.key_type, # pyright: ignore[reportUnknownMemberType, reportUnknownArgumentType] + ) and _holds_only_nulls(values.field(1), declared.item_type) # pyright: ignore[reportUnknownMemberType, reportUnknownArgumentType] + return _holds_only_nulls(values, declared.value_type) # pyright: ignore[reportUnknownArgumentType] if isinstance(declared, pa.StructType): + # Each child with the struct's validity applied, for the slice's rows. + children = array.flatten() # pyright: ignore[reportAttributeAccessIssue, reportUnknownMemberType, reportUnknownVariableType] return all( - _holds_only_nulls(array.field(i), declared.field(i).type) # pyright: ignore[reportAttributeAccessIssue, reportUnknownMemberType, reportUnknownArgumentType] - for i in range(declared.num_fields) - ) - if isinstance(declared, pa.MapType): - return _holds_only_nulls(array.keys, declared.key_type) and _holds_only_nulls( # pyright: ignore[reportAttributeAccessIssue, reportUnknownMemberType, reportUnknownArgumentType] - array.items, # pyright: ignore[reportAttributeAccessIssue, reportUnknownMemberType, reportUnknownArgumentType] - declared.item_type, + _holds_only_nulls(child, declared.field(i).type) # pyright: ignore[reportUnknownArgumentType] + for i, child in enumerate(children) # pyright: ignore[reportUnknownArgumentType, reportUnknownVariableType] ) return True + + +class _ClosedDuringSend(ChannelClosed): + """The failure of an output channel closed while a send was in flight.""" diff --git a/tests/test_channels/test_record_batch_channels.py b/tests/test_channels/test_record_batch_channels.py index a4348b205..a117b6fca 100644 --- a/tests/test_channels/test_record_batch_channels.py +++ b/tests/test_channels/test_record_batch_channels.py @@ -34,12 +34,14 @@ from orcapod.core.operators.static_output_pod import ( StaticOutputOperatorPod, 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 import ArrowTableStream @@ -438,7 +440,9 @@ async def write() -> tuple[list[int], list[int], int]: @pytest.mark.parametrize("ending", ["close", "fail"]) def test_a_waiting_send_ends_when_the_channel_ends(ending: str) -> None: """A send waiting for a reader's room when the channel is closed or failed raises - at once (``ChannelClosed``, or the failure) and its batch is never delivered.""" + at once (``ChannelClosed``, or the failure) and its batch is never delivered. A + close during a send does not complete the channel: it fails, so the reader's next + read raises, with a ``ChannelClosed`` as the cause.""" stream = source(2) first, second = batches_of(stream, 1) boom = OSError("disk gone") @@ -458,20 +462,16 @@ async def write() -> tuple[type[object], list[int]]: asyncio.gather(waiting, return_exceptions=True), 1 ) delivered: list[int] = [] - try: + with pytest.raises(UpstreamFailedError) as failed: async for batch in reader: delivered.append(batch.num_rows) - except UpstreamFailedError: - pass + cause = failed.value.__cause__ + assert isinstance(cause, ChannelClosed if ending == "close" else OSError) return type(raised[0]), delivered raised, delivered = run(write) - if ending == "close": - assert raised is ChannelClosed - assert delivered == [1] # the batch sent before the close, not the waiting one - else: - assert raised is UpstreamFailedError - assert delivered == [] # a failure is seen at once + assert raised is (ChannelClosed if ending == "close" else UpstreamFailedError) + assert delivered == [] # a failure is seen at once @pytest.mark.parametrize("ending", ["close", "fail"]) @@ -567,6 +567,148 @@ async def write() -> int: assert run(write) == 1 +def test_a_close_during_a_send_that_reached_one_reader_fails_both() -> None: + """Two readers with one slot each: a send has queued its batch for the fast reader + and waits for the slow one when the channel is closed. The send raises + ``ChannelClosed``; neither reader completes normally (their inputs would differ): + each next read raises ``UpstreamFailedError`` caused by a ``ChannelClosed``.""" + stream = source(2) + first, second = batches_of(stream, 1) + + async def write() -> list[BaseException]: + output = OutputChannel(stream, retain=False, buffer_size=1) + fast, slow = output.open_reader(), output.open_reader() + await output.send(first) + _ = await fast.receive() + sending = asyncio.ensure_future(output.send(second)) + await asyncio.sleep(0) + assert not sending.done() # queued for fast, waiting for slow + await output.close() + with pytest.raises(ChannelClosed): + await sending + failures: list[BaseException] = [] + for reader in (fast, slow): + with pytest.raises(UpstreamFailedError) as failed: + _ = await reader.collect() + failures.append(failed.value) + with pytest.raises(RuntimeError, match="has no result"): + _ = output.result() + return failures + + for failure in run(write): + assert isinstance(failure.__cause__, ChannelClosed) + + +def test_metadata_is_compared_at_every_depth() -> None: + """A user field's nested field metadata must be the description's; a provenance + field (system tag, source info) carries none, as a row builds it.""" + stream = source() + (batch,) = batches_of(stream) + trace = batch.schema.get_field_index("trace") + trace_type = batch.schema.field(trace).type + tagged_item = pa.large_list(trace_type.value_field.with_metadata({"units": "b"})) + nested = batch.set_column( + trace, + batch.schema.field(trace).with_type(tagged_item), + batch.column(trace).cast(tagged_item), + ) + system_tag = next( + i for i, name in enumerate(batch.schema.names) if name.startswith("_tag") + ) + provenance = pa.RecordBatch.from_arrays( + batch.columns, + schema=batch.schema.set( + system_tag, batch.schema.field(system_tag).with_metadata({"m": "1"}) + ), + ) + + async def write() -> None: + output = OutputChannel(stream) + with pytest.raises(ValueError, match="column 'trace' has field metadata"): + await output.send(nested) + with pytest.raises(ValueError, match="carries field metadata"): + await output.send(provenance) + await output.send(batch) + + run(write) + + +def test_nulls_are_judged_on_the_values_sent() -> None: + """A struct row that is null may hold a value in its child's buffer, and a slice of + a map shares its backing array with rows outside it: neither is a value sent.""" + stream = ArrowTableStream( + pa.table( + { + "k": pa.array([1, 2], pa.int64()), + "s": pa.array( + [None, {"a": None}], pa.struct([pa.field("a", pa.null())]) + ), + } + ), + tag_columns=["k"], + ) + (batch,) = batches_of(stream) + index = batch.schema.get_field_index("s") + carried = batch.schema.field(index).type + masked = pa.StructArray.from_arrays( + [pa.array(["in the buffer", None], pa.large_string())], + fields=[carried.field(0)], + mask=pa.array([True, False]), + ) + assert masked.to_pylist() == [None, {"a": None}] + buffered = batch.set_column(index, batch.schema.field(index), masked) + + async def write() -> None: + output = OutputChannel(stream) + await output.send(buffered) + await output.close() + + run(write) + + # A map column declared map, sent as one row of a longer map + # array whose other row holds a value. + declared = pa.schema([pa.field("m", pa.map_(pa.large_string(), pa.null()))]) + whole = pa.array( + [[("a", None)], [("b", "a value")]], + pa.map_(pa.large_string(), pa.large_string()), + ) + sent = pa.RecordBatch.from_arrays([whole.slice(0, 1)], names=["m"]) + assert _schema_mismatch(declared, sent) is None + other = pa.RecordBatch.from_arrays([whole.slice(1, 1)], names=["m"]) + assert "holds values" in str(_schema_mismatch(declared, other)) + + +class _UntypedStream(ArrowTableStream): + """A stream that cannot say its Arrow types without rows.""" + + def _typed_zero_row_table(self) -> pa.Table | None: + return None + + +def test_without_arrow_types_the_names_are_still_the_streams() -> None: + """A stream with no typed zero-row table: the first record batch gives the Arrow + types, but a batch whose columns contradict the stream's keys is refused.""" + table = source().as_table(columns=ALL) + stream = _UntypedStream( + table, tag_columns=["subject", "trial"], data_tags=["trial"] + ) + assert transport_schema(stream) is None + (batch,) = batches_of(stream) + renamed = batch.rename_columns( + ["other" if name == "note" else name for name in batch.schema.names] + ) + + async def write() -> int: + output = OutputChannel(stream) + with pytest.raises(ValueError, match="the stream's keys are"): + await output.send(renamed) + await output.send(batch) + await output.close() + return output.result().as_table().num_rows + + assert run(write) == 7 + + # --- Retained output: readers at their own position, send never waits ------------------- diff --git a/tests/test_core/operators/test_record_batch_execution.py b/tests/test_core/operators/test_record_batch_execution.py index 0fe878499..98c835ace 100644 --- a/tests/test_core/operators/test_record_batch_execution.py +++ b/tests/test_core/operators/test_record_batch_execution.py @@ -35,7 +35,9 @@ OutputChannel, channel_from_stream, ) +from orcapod.channels import ChannelClosed from orcapod.core.streams import ArrowTableStream +from orcapod.errors import UpstreamFailedError from orcapod.protocols.core_protocols import StreamProtocol from tests.test_core.operators.test_async_sync_equivalence import ( AFTER_OPERATOR_CASES, @@ -516,3 +518,118 @@ async def go() -> tuple[list[str], StreamProtocol]: wire, rebuilt = asyncio.run(go()) assert wire == expected.schema.names assert rebuilt.as_table(columns=ALL).schema.names == expected.schema.names + + +# --- An input closed before its producer completed -------------------------------------- + + +@pytest.mark.parametrize( + "make_op", + [lambda: SelectDataColumns(["i8", "s"]), lambda: Batch(batch_size=1)], + ids=["row_by_row", "batch_by_arrival"], +) +def test_an_input_closed_early_fails_a_streaming_operator( + make_op: Callable[[], StaticOutputOperatorPod], +) -> None: + """A streaming loop takes an input reader closed before its producer completed for + a failure, never for the end of its input: the operator fails its output instead + of completing it with part of the rows.""" + source = source_a() + op = make_op() + + async def go() -> None: + rows = pa.Table.from_batches(await channel_from_stream(source).collect()) + first, second = _cut(rows, (1,))[:2] + feed = OutputChannel(source, retain=False, buffer_size=4) + reader = feed.open_reader() + output = OutputChannel(op(source)) + task = asyncio.ensure_future(op.async_execute_batches([reader], output)) + await feed.send(first) + await asyncio.sleep(0.01) + await reader.close() + await feed.send(second) + await feed.close() + with pytest.raises(ChannelClosed, match="closed before its producer"): + await asyncio.wait_for(task, TIMEOUT) + with pytest.raises(UpstreamFailedError): + _ = await output.open_reader().collect() + with pytest.raises(RuntimeError, match="has no result"): + _ = output.result() + + asyncio.run(go()) + + +# --- F on the edges of a raw stream's provenance (stage 2, ITL-1360) ---------------------- + + +def _job_sync(op: StaticOutputOperatorPod, stream: StreamProtocol) -> StreamProtocol: + """``op`` over ``stream`` as a job's sync path gives it its input.""" + return op( + StaticOutputOperatorPod._materialize_upstream( # pyright: ignore[reportPrivateUsage] # the job's sync input + list(stream.iter_data()), stream + ) + ) + + +def _schema_outcome(make: Callable[[], StreamProtocol]) -> tuple[str, Any]: + """The schema and rows of a stream's table, or the kind of error that refuses it.""" + try: + table = make().as_table(columns=ALL) + return ("table", (table.schema, table.to_pylist())) + except Exception as error: # noqa: BLE001 # the refusal is the outcome compared + return ("refused", type(error).__name__) + + +@pytest.mark.xfail( + strict=True, + raises=AssertionError, + reason="TODO(ITL-1360): F (stage 2's row_built_provenance) keeps both list levels " + "of an all-empty nested source-info column, where a row types each token [] as " + "large_list", +) +@pytest.mark.parametrize("layout", ["one_batch", "one_row_per_batch"]) +def test_empty_nested_source_info_lists_take_the_row_built_type(layout: str) -> None: + """Source info of type ``large_list>`` whose tokens are all + ``[]``: the channel result has the types the job's sync path builds from the + rows.""" + raw = ArrowTableStream( + pa.table( + { + "k": pa.array([1, 2], pa.int64()), + "x": pa.array([1, 2], pa.int64()), + "z": pa.array([3, 4], pa.int64()), + "_source_x": pa.array( + [[], []], pa.large_list(pa.large_list(pa.large_string())) + ), + } + ), + tag_columns=["k"], + ) + assert _schema_outcome( + lambda: run_on_channels(SelectDataColumns(["x"]), [raw], LAYOUTS[layout]) + ) == _schema_outcome(lambda: _job_sync(SelectDataColumns(["x"]), raw)) + + +@pytest.mark.xfail( + strict=True, + raises=AssertionError, + reason="TODO(ITL-1360): the job's sync path refuses (ArrowInvalid: two field flags) " + "a system-tag column with a string and a null, while F gives both rows", +) +def test_a_system_tag_with_a_null_among_strings_has_the_job_sync_outcome() -> None: + """A raw stream whose system-tag column holds a string and a null: the channel + result is the job's sync outcome, rows or refusal.""" + raw = ArrowTableStream( + pa.table( + { + "k": pa.array([1, 2], pa.int64()), + SYSTEM_TAG: pa.array(["s", None], pa.large_string()), + "x": pa.array([1, 2], pa.int64()), + "z": pa.array([3, 4], pa.int64()), + } + ), + tag_columns=["k"], + ) + assert _schema_outcome( + lambda: run_on_channels(SelectDataColumns(["x"]), [raw], None) + ) == _schema_outcome(lambda: _job_sync(SelectDataColumns(["x"]), raw)) From 0d502a6d46cf880012e4b4d9df8d69aee7c46850 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 03:42:55 -0800 Subject: [PATCH 10/12] fix(channels): types of the null check and its tests (ITL-1362) Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/record_batch_channels.py | 13 ++++++++----- tests/test_channels/test_record_batch_channels.py | 4 ++-- 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/src/orcapod/core/record_batch_channels.py b/src/orcapod/core/record_batch_channels.py index 927e0a034..6b4aabc7f 100644 --- a/src/orcapod/core/record_batch_channels.py +++ b/src/orcapod/core/record_batch_channels.py @@ -16,7 +16,7 @@ import asyncio from collections import deque from collections.abc import AsyncIterator -from typing import TYPE_CHECKING, Any, Protocol +from typing import TYPE_CHECKING, Any, Protocol, cast import pyarrow as pa import pyarrow.compute as pc @@ -569,10 +569,13 @@ def _holds_only_nulls(array: pa.Array[Any], declared: pa.DataType) -> bool: # p # The values of the non-null lists of the slice, in order. values = pc.list_flatten(array) # pyright: ignore[reportUnknownMemberType, reportUnknownVariableType] if isinstance(declared, pa.MapType): - return _holds_only_nulls( - values.field(0), - declared.key_type, # pyright: ignore[reportUnknownMemberType, reportUnknownArgumentType] - ) and _holds_only_nulls(values.field(1), declared.item_type) # pyright: ignore[reportUnknownMemberType, reportUnknownArgumentType] + keys, items = cast( + "pa.StructArray", cast(object, values) + ).flatten() # list_flatten of entries is a struct array + return _holds_only_nulls(keys, declared.key_type) and _holds_only_nulls( # pyright: ignore[reportUnknownMemberType, reportUnknownArgumentType] + items, + declared.item_type, # pyright: ignore[reportUnknownMemberType, reportUnknownArgumentType] + ) return _holds_only_nulls(values, declared.value_type) # pyright: ignore[reportUnknownArgumentType] if isinstance(declared, pa.StructType): # Each child with the struct's validity applied, for the slice's rows. diff --git a/tests/test_channels/test_record_batch_channels.py b/tests/test_channels/test_record_batch_channels.py index a117b6fca..0d72dbfd3 100644 --- a/tests/test_channels/test_record_batch_channels.py +++ b/tests/test_channels/test_record_batch_channels.py @@ -655,7 +655,7 @@ def test_nulls_are_judged_on_the_values_sent() -> None: fields=[carried.field(0)], mask=pa.array([True, False]), ) - assert masked.to_pylist() == [None, {"a": None}] + assert masked.to_pylist() == [None, {"a": None}] # pyright: ignore[reportAttributeAccessIssue] # the stubs omit it buffered = batch.set_column(index, batch.schema.field(index), masked) async def write() -> None: @@ -681,7 +681,7 @@ async def write() -> None: class _UntypedStream(ArrowTableStream): """A stream that cannot say its Arrow types without rows.""" - def _typed_zero_row_table(self) -> pa.Table | None: + def _typed_zero_row_table(self) -> pa.Table | None: # pyright: ignore[reportIncompatibleMethodOverride] # a kind that cannot type itself without rows return None From a2165d96efd74ab7e815b3f72d4a9b663dab13c3 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 03:45:45 -0800 Subject: [PATCH 11/12] test(channels): pin F's two documented exceptions instead of xfails; stage 2's _row_built_form docstring verbatim (ITL-1362) Co-Authored-By: Claude Opus 5.5 --- .../core/operators/static_output_pod.py | 18 ++++-- .../operators/test_record_batch_execution.py | 56 ++++++++++--------- 2 files changed, 44 insertions(+), 30 deletions(-) diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index 745b7b5b1..b429a1179 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -500,10 +500,20 @@ def _row_built_form( """Return ``table`` as ``_rows_to_table`` builds it from the table's own rows. F in the ITL-1347 spec: the same table, without making the rows. The columns, - their order and their types are decided row by row (``streams.base.row_built_columns``), the - system-tag and source-info field flags by their values over the whole table - (``_flag_by_values``). The equality with ``_rows_to_table`` is tested over every - operator, source kind and column role (ITL-1347, L0-L2). + their order and their types are decided row by row + (``streams.base.row_built_columns``), the system-tag and source-info field flags + by their values over the whole table (``_flag_by_values``). The equality with + ``_rows_to_table`` is tested over every operator, source kind and column role + (ITL-1347, L0-L2). + + Its domain: F equals ``_rows_to_table`` for every stream whose source-info tokens + are strings or non-empty lists of tokens, which is every stream a source or an + operator makes (a token list has one element per member of a batch, group or + merge). The one exception is a hand-built raw ``ArrowTableStream`` whose + source-info column is a list type holding only empty lists: a row types its + tokens from their values, so ``_rows_to_table`` loses the list levels the + empty lists do not show, while F keeps the column's type. Such a stream reaches + a job only when bound to a slot with a copied source-id and record-id pair. Args: table: A table of user tags, system tags, data and source info, with rows. diff --git a/tests/test_core/operators/test_record_batch_execution.py b/tests/test_core/operators/test_record_batch_execution.py index 98c835ace..96a56672e 100644 --- a/tests/test_core/operators/test_record_batch_execution.py +++ b/tests/test_core/operators/test_record_batch_execution.py @@ -580,18 +580,16 @@ def _schema_outcome(make: Callable[[], StreamProtocol]) -> tuple[str, Any]: return ("refused", type(error).__name__) -@pytest.mark.xfail( - strict=True, - raises=AssertionError, - reason="TODO(ITL-1360): F (stage 2's row_built_provenance) keeps both list levels " - "of an all-empty nested source-info column, where a row types each token [] as " - "large_list", -) @pytest.mark.parametrize("layout", ["one_batch", "one_row_per_batch"]) -def test_empty_nested_source_info_lists_take_the_row_built_type(layout: str) -> None: - """Source info of type ``large_list>`` whose tokens are all - ``[]``: the channel result has the types the job's sync path builds from the - rows.""" +def test_empty_source_info_lists_are_outside_the_row_built_forms_domain( + layout: str, +) -> None: + """Pins a documented exception of F (``_row_built_form``): F equals the table built + from rows for every stream whose source-info tokens are strings or non-empty + lists, which is every stream a source or an operator makes. A hand-built raw + stream whose source-info column is a nested list type holding only empty lists is + outside that domain: the channel keeps the column's two list levels, while the + job's sync path rebuilds the tokens from their values and gives one.""" raw = ArrowTableStream( pa.table( { @@ -605,20 +603,23 @@ def test_empty_nested_source_info_lists_take_the_row_built_type(layout: str) -> ), tag_columns=["k"], ) - assert _schema_outcome( - lambda: run_on_channels(SelectDataColumns(["x"]), [raw], LAYOUTS[layout]) - ) == _schema_outcome(lambda: _job_sync(SelectDataColumns(["x"]), raw)) + channel = run_on_channels(SelectDataColumns(["x"]), [raw], LAYOUTS[layout]) + job_sync = _job_sync(SelectDataColumns(["x"]), raw) + got = channel.as_table(columns=ALL) + rebuilt = job_sync.as_table(columns=ALL) + assert got.to_pylist() == rebuilt.to_pylist() # the same rows + assert got.schema.field("_source_x").type == pa.large_list( + pa.large_list(pa.large_string()) + ) + assert rebuilt.schema.field("_source_x").type == pa.large_list(pa.large_string()) -@pytest.mark.xfail( - strict=True, - raises=AssertionError, - reason="TODO(ITL-1360): the job's sync path refuses (ArrowInvalid: two field flags) " - "a system-tag column with a string and a null, while F gives both rows", -) -def test_a_system_tag_with_a_null_among_strings_has_the_job_sync_outcome() -> None: - """A raw stream whose system-tag column holds a string and a null: the channel - result is the job's sync outcome, rows or refusal.""" +def test_a_system_tag_with_a_null_is_refused_by_the_job_sync_path() -> None: + """Pins a stream no job can run: a raw stream whose system-tag column holds a string + and a null. The job's sync path refuses it (the rows' system-tag fields differ in + their flags), while the channel gives both rows; a job never sees such a stream, + because a source with a nullable system tag cannot be bound to a slot + (``SourceSpecMismatchError``).""" raw = ArrowTableStream( pa.table( { @@ -630,6 +631,9 @@ def test_a_system_tag_with_a_null_among_strings_has_the_job_sync_outcome() -> No ), tag_columns=["k"], ) - assert _schema_outcome( - lambda: run_on_channels(SelectDataColumns(["x"]), [raw], None) - ) == _schema_outcome(lambda: _job_sync(SelectDataColumns(["x"]), raw)) + assert _schema_outcome(lambda: _job_sync(SelectDataColumns(["x"]), raw)) == ( + "refused", + "ArrowInvalid", + ) + channel = run_on_channels(SelectDataColumns(["x"]), [raw], None) + assert channel.as_table(columns=ALL).column(SYSTEM_TAG).to_pylist() == ["s", None] From eef66a7c8b294115e2b23a080122df84f84ebd87 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 04:18:03 -0800 Subject: [PATCH 12/12] fix(channels): CodeRabbit round on #483: one send at a time, any abort of a partly delivered send fails the channel, schema set only by a batch that passes, the output closed in the protected block, every input closed (ITL-1362) - non-retained sends are serialized, so every reader gets one batch order - a send aborted after it reached one reader (close, fail, cancellation, any error) fails the channel; one aborted before any reader leaves it usable - an inferred schema is saved only after the batch passes the check - operators close their output inside the protected block and close every input even when one close fails (close_inputs) - RecordBatchInput.to_stream documents that it needs an unread channel - docstrings for the channel feeds, readers and helpers; the per-arrival test synchronizes on each input's result instead of sleeping and reading _sent - ITL-1365 (DropTagColumns' predicted tag order) pinned as a strict xfail Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/operators/batch.py | 12 +- .../core/operators/static_output_pod.py | 38 ++++- src/orcapod/core/record_batch_channels.py | 118 +++++++++++++--- .../core_protocols/record_batch_channels.py | 12 +- .../test_record_batch_channels.py | 132 ++++++++++++++++++ .../operators/test_record_batch_execution.py | 130 ++++++++++++++--- 6 files changed, 391 insertions(+), 51 deletions(-) diff --git a/src/orcapod/core/operators/batch.py b/src/orcapod/core/operators/batch.py index 5a9f750c6..78af8e8d1 100644 --- a/src/orcapod/core/operators/batch.py +++ b/src/orcapod/core/operators/batch.py @@ -16,7 +16,10 @@ WritableChannel, ) from orcapod.core.operators.base import UnaryOperator -from orcapod.core.operators.static_output_pod import with_open_provenance_flags +from orcapod.core.operators.static_output_pod import ( + close_inputs, + with_open_provenance_flags, +) from orcapod.core.data_tags import stream_data_tags from orcapod.core.streams import ArrowTableStream from orcapod.protocols.core_protocols import DataProtocol, StreamProtocol, TagProtocol @@ -315,13 +318,12 @@ async def async_execute_batches( # whether they make a last one. if rows: await self._send_processed(waiting, channel.stream, output) + await output.close() except BaseException as error: output.fail(error) + await close_inputs(inputs, error) raise - else: - await output.close() - finally: - await channel.close() + await close_inputs(inputs) def to_config(self) -> dict[str, Any]: """Serialize this Batch operator to a config dict. diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index b429a1179..6cdc6ab7e 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -926,14 +926,12 @@ async def async_execute_batches( else: streams = await _streams_of(inputs) await self._send_result(self.static_process(*streams), output) + await output.close() except BaseException as error: output.fail(error) + await close_inputs(inputs, error) raise - else: - await output.close() - finally: - for channel in inputs: - await channel.close() + await close_inputs(inputs) async def _send_processed( self, @@ -971,6 +969,36 @@ async def _send_result(result: StreamProtocol, output: RecordBatchOutput) -> Non await output.send(batch) +async def close_inputs( + inputs: Sequence[RecordBatchInput], error: BaseException | None = None +) -> None: + """Close every input channel of an operator, also when one close fails. + + Each input is closed on its own, so a failing close never leaves another input's + producer waiting. When the operator already failed (``error``), a failing close is + added to that error as a note and the operator's error stays the one raised; + otherwise the first failing close is raised once every input is closed. + + Args: + inputs: The operator's input channels. + error: The error the operator is failing with, if any. + + Raises: + Exception: The first error of a close, when ``error`` is ``None``. + """ + first: Exception | None = None + for channel in inputs: + try: + await channel.close() + except Exception as failure: # noqa: BLE001 # every input is closed first + if error is not None: + error.add_note(f"Closing an input channel also failed: {failure!r}") + elif first is None: + first = failure + if first is not None: + raise first + + async def _streams_of(inputs: Sequence[RecordBatchInput]) -> list[StreamProtocol]: """Read every input channel to its end, each as a stream, at the same time. diff --git a/src/orcapod/core/record_batch_channels.py b/src/orcapod/core/record_batch_channels.py index 6b4aabc7f..a6f5e57ab 100644 --- a/src/orcapod/core/record_batch_channels.py +++ b/src/orcapod/core/record_batch_channels.py @@ -65,10 +65,21 @@ 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. @@ -84,6 +95,7 @@ async def next(self) -> pa.RecordBatch | None: 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() @@ -91,6 +103,11 @@ class _OutputFeed: """One reader of an output channel, with its own position.""" def __init__(self, output: OutputChannel) -> None: + """Make a reader of ``output`` at the start of what it sends. + + Args: + output: The output channel read. + """ self._output = output self.open = True # With retained batches: this reader's position among them. Without: the @@ -99,6 +116,15 @@ def __init__(self, output: OutputChannel) -> None: self.queue: deque[pa.RecordBatch] = deque() async def next(self) -> pa.RecordBatch | None: + """Return this reader's next record batch, or ``None`` at the end. + + Waits while nothing is there for it. A failed output raises at once, with + batches still unread. Without ``retain``, taking a batch frees room in this + reader's queue and wakes a producer waiting for it. + + Raises: + UpstreamFailedError: If the output failed. + """ output = self._output while self.open: if output._error is not None: # pyright: ignore[reportPrivateUsage] @@ -117,6 +143,11 @@ async def next(self) -> pa.RecordBatch | None: return None def close(self) -> None: + """Stop reading and unregister from the output. + + The queued batches are dropped and a producer waiting for room in this + reader's queue is woken: it no longer waits for this reader. + """ self.open = False self.queue.clear() output = self._output @@ -140,6 +171,12 @@ class InputChannel: """ 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 @@ -183,9 +220,16 @@ async def receive(self) -> pa.RecordBatch: 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: @@ -265,6 +309,11 @@ def __init__( retain: bool = True, buffer_size: int = BATCH_BUFFER_SIZE, ) -> None: + """Make an output channel for ``stream``'s rows (the arguments: see the class). + + Raises: + ValueError: If ``buffer_size`` is less than 1. + """ if buffer_size < 1: raise ValueError(f"buffer_size must be at least 1, got {buffer_size}") self._stream = stream @@ -275,6 +324,7 @@ def __init__( self._sent = 0 # Sends waiting for a reader's room (``retain=False`` only). self._sending = 0 + self._send_lock = asyncio.Lock() self._closed = False self._error: BaseException | None = None self._result: StreamProtocol | None = None @@ -295,6 +345,7 @@ def _notify(self) -> None: changed.set() def _upstream_failed(self) -> UpstreamFailedError: + """The error a reader or a send meets on a failed output, caused by its cause.""" error = self._error assert error is not None failure = UpstreamFailedError( @@ -318,9 +369,11 @@ def _check_schema(self, batch: pa.RecordBatch) -> None: if not self._schema_known: self._schema = transport_schema(self._stream) self._schema_known = True - if self._schema is None: - # No Arrow types in the description: the first batch sets them (they must - # be in the large variants), but the names are still the stream's. + schema = self._schema + if schema is None: + # No Arrow types in the description: the first batch that passes sets them + # (they must be in the large variants), but the names are still the + # stream's. A refused batch sets nothing. names = batch.schema.names if names != row_built_names(names, self._stream.keys()): raise ValueError( @@ -328,20 +381,28 @@ def _check_schema(self, batch: pa.RecordBatch) -> None: + f"stream's columns: it has {names}, the stream's keys are " + f"{self._stream.keys()}." ) - self._schema = batch.schema - mismatch = _schema_mismatch(self._schema, batch) + schema = batch.schema + mismatch = _schema_mismatch(schema, batch) if mismatch is not None: raise ValueError( f"A record batch sent as {_named(self._stream)} does not have that " + f"stream's columns: {mismatch}." ) + self._schema = schema async def send(self, batch: pa.RecordBatch) -> None: """Send one Arrow record batch of the stream's transport columns. - A batch with no rows is checked and not kept. A send waiting for a reader's - room when the channel is closed or failed raises at once and publishes - nothing more. + A batch with no rows is checked and not kept. Without ``retain``, sends are + taken one at a time, so every reader gets the batches in one order. A send + waiting for a reader's room when the channel is closed or failed raises at + once and publishes nothing more. + + Any abort of a send that has reached one reader and not yet all of them (a + close, a failure, a cancellation, any error) fails the channel: readers never + complete normally with different inputs. Every reader's next read then raises + ``UpstreamFailedError``, caused by the abort (a ``ChannelClosed`` for a close). + A send aborted before it reached any reader leaves the channel as it was. Raises: ChannelClosed: If the channel is closed. @@ -358,20 +419,34 @@ async def send(self, batch: pa.RecordBatch) -> None: self._batches.append(batch) self._notify() return - self._sending += 1 - try: - for reader in list(self._readers): - # The slowest reader sets the pace; one that closed is not waited for. - while reader.open and len(reader.queue) >= self._buffer_size: - await self._changed.wait() - self._raise_if_ended() - if reader.open: - reader.queue.append(batch) - # At once, not after the last reader: this reader may be waiting - # for the batch while the send waits for another reader's room. + # One send at a time, so every reader gets the batches in one order. + async with self._send_lock: + self._raise_if_ended() + self._sending += 1 + delivered = False + try: + for reader in list(self._readers): + # The slowest reader sets the pace; one that closed is not waited + # for. + while reader.open and len(reader.queue) >= self._buffer_size: + await self._changed.wait() + self._raise_if_ended() + if reader.open: + reader.queue.append(batch) + delivered = True + # At once, not after the last reader: this reader may be + # waiting for the batch while the send waits for another + # reader's room. + self._notify() + except BaseException as error: + # A send that reached a reader and stops before the others (cancelled, + # or any error) fails the channel, as a close during it does. + if delivered and self._error is None: + self._error = error self._notify() - finally: - self._sending -= 1 + raise + finally: + self._sending -= 1 async def close(self) -> None: """Complete the output. A second close does nothing; never waits. @@ -544,6 +619,7 @@ def _without_metadata(kind: pa.DataType) -> pa.DataType: def _field_without_metadata(field: pa.Field[Any]) -> pa.Field[Any]: # pyright: ignore[reportExplicitAny] # any field + """``field`` with no field metadata, at its own level and below.""" return pa.field(field.name, _without_metadata(field.type), nullable=field.nullable) diff --git a/src/orcapod/protocols/core_protocols/record_batch_channels.py b/src/orcapod/protocols/core_protocols/record_batch_channels.py index 5e24e926e..27f34aa69 100644 --- a/src/orcapod/protocols/core_protocols/record_batch_channels.py +++ b/src/orcapod/protocols/core_protocols/record_batch_channels.py @@ -48,7 +48,17 @@ async def collect(self) -> list[pa.RecordBatch]: ... async def to_stream(self) -> StreamProtocol: - """Read to the end and return what the channel delivered, as a stream.""" + """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: diff --git a/tests/test_channels/test_record_batch_channels.py b/tests/test_channels/test_record_batch_channels.py index 0d72dbfd3..4c03cefd3 100644 --- a/tests/test_channels/test_record_batch_channels.py +++ b/tests/test_channels/test_record_batch_channels.py @@ -274,6 +274,8 @@ async def empty() -> tuple[Any, Any]: def test_send_after_close_is_refused_and_result_needs_a_closed_channel() -> None: + """A send after ``close()`` raises ``ChannelClosed``, and ``result()`` exists only + once the channel is closed.""" stream = source() (batch,) = batches_of(stream) @@ -709,6 +711,131 @@ async def write() -> int: assert run(write) == 7 +def test_a_refused_first_batch_sets_no_schema() -> None: + """Without Arrow types in the description, a refused first batch sets nothing: a + correct batch sent next is taken.""" + stream = _UntypedStream( + source().as_table(columns=ALL), + tag_columns=["subject", "trial"], + data_tags=["trial"], + ) + (batch,) = batches_of(stream) + note = batch.schema.get_field_index("note") + narrow = pa.RecordBatch.from_arrays( + [ + *batch.columns[:note], + batch.column(note).cast(pa.string()), + *batch.columns[note + 1 :], + ], + schema=batch.schema.set( + note, pa.field("note", pa.string(), metadata={"unit": "mV"}) + ), + ) + + async def write() -> int: + output = OutputChannel(stream) + with pytest.raises(ValueError, match="column 'note' is string"): + await output.send(narrow) + await output.send(batch) + await output.close() + return output.result().as_table().num_rows + + assert run(write) == 7 + + +def test_overlapping_sends_reach_every_reader_in_one_order() -> None: + """Two sends started while a reader is full: they are taken one at a time, so both + readers get the batches in one order. The first send queues its batch for the fast + reader and waits for room in the slow one; the second waits for the first; the + readers draining releases both.""" + stream = source(3) + first, second, third = batches_of(stream, 1) + + async def write() -> tuple[list[Any], list[Any]]: + output = OutputChannel(stream, retain=False, buffer_size=1) + fast, slow = output.open_reader(), output.open_reader() + await output.send(first) + _ = await fast.receive() + sending = [ + asyncio.ensure_future(output.send(second)), + asyncio.ensure_future(output.send(third)), + ] + await asyncio.sleep(0) + + async def trials(reader: InputChannel, start: list[Any]) -> list[Any]: + got: list[Any] = list(start) + async for batch in reader: + 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 + + fast_order, slow_order = run(write) + assert fast_order == slow_order == [0, 1, 2] + + +def test_a_cancelled_send_that_reached_one_reader_fails_both() -> None: + """A send cancelled after it queued its batch for the fast reader, while it waits + for the slow one, fails the channel: neither reader completes normally, each next + read raising ``UpstreamFailedError`` caused by the cancellation.""" + stream = source(2) + first, second = batches_of(stream, 1) + + async def write() -> list[BaseException | None]: + output = OutputChannel(stream, retain=False, buffer_size=1) + fast, slow = output.open_reader(), output.open_reader() + await output.send(first) + _ = await fast.receive() + sending = asyncio.ensure_future(output.send(second)) + await asyncio.sleep(0) # queued for fast, waiting for room in slow + _ = sending.cancel() + with pytest.raises(asyncio.CancelledError): + await sending + await output.close() + causes: list[BaseException | None] = [] + for reader in (fast, slow): + with pytest.raises(UpstreamFailedError) as failed: + _ = await reader.collect() + causes.append(failed.value.__cause__) + return causes + + for cause in run(write): + assert isinstance(cause, asyncio.CancelledError) + + +def test_a_send_cancelled_before_it_reached_a_reader_leaves_the_channel_usable() -> ( + None +): + """A send cancelled while it waits for the only reader's room delivered nothing: the + channel goes on and completes normally.""" + stream = source(3) + first, second, third = batches_of(stream, 1) + + async def write() -> list[Any]: + output = OutputChannel(stream, retain=False, buffer_size=1) + reader = output.open_reader() + await output.send(first) # fills the one slot + sending = asyncio.ensure_future(output.send(second)) + await asyncio.sleep(0) + _ = sending.cancel() + with pytest.raises(asyncio.CancelledError): + await sending + got = (await reader.receive()).column("trial").to_pylist() + await output.send(third) + await output.close() + for batch in await reader.collect(): + got.extend(batch.column("trial").to_pylist()) + return got + + assert run(write) == [0, 2] + + # --- Retained output: readers at their own position, send never waits ------------------- @@ -828,6 +955,8 @@ async def produce() -> None: def test_without_retain_a_late_reader_is_refused_and_there_is_no_result() -> None: + """Without ``retain``, a reader opened after the first send would miss it, so it is + refused, and the output has no result stream.""" stream = source() (batch,) = batches_of(stream) @@ -846,6 +975,7 @@ async def write() -> None: def test_a_buffer_must_hold_one_batch() -> None: + """``buffer_size`` below 1 is refused when the output channel is made.""" with pytest.raises(ValueError, match="buffer_size"): _ = OutputChannel(source(), retain=False, buffer_size=0) @@ -892,6 +1022,8 @@ async def write() -> list[BaseException]: def test_fail_after_close_changes_nothing() -> None: + """``fail()`` on a closed channel does nothing: its readers end normally and the + result is the batches sent.""" stream = source() batches = batches_of(stream, 3) diff --git a/tests/test_core/operators/test_record_batch_execution.py b/tests/test_core/operators/test_record_batch_execution.py index 96a56672e..c47c11a3c 100644 --- a/tests/test_core/operators/test_record_batch_execution.py +++ b/tests/test_core/operators/test_record_batch_execution.py @@ -29,7 +29,10 @@ import orcapod.core.operators as operators from orcapod.core.operators import AddTags, Batch, PolarsFilter, SelectDataColumns -from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod +from orcapod.core.operators.static_output_pod import ( + StaticOutputOperatorPod, + stream_from_batches, +) from orcapod.core.record_batch_channels import ( InputChannel, OutputChannel, @@ -249,38 +252,46 @@ def test_the_row_by_row_operators_are_exactly_these() -> None: ids=lambda case: case.label, ) def test_a_row_by_row_operator_sends_each_batch_as_it_arrives(case: Case) -> None: - """One result record batch per input record batch, before the next is read: with a - queue of one batch and no retained output, the operator can only go on when its - reader has taken the batch before.""" + """One result per input record batch, sent before the next input is read. Each + one-row input is sent and its result (the sync body over that row alone) is + received before the next row is sent or the input is closed; a row whose result + is empty sends nothing, which the end of the output shows. A barrier operator + sends nothing until its input ends, so it fails here.""" (source,) = case.make_sources() op = case.make_op() expected = R(case.make_op()(source)) assert expected is not None - async def go() -> tuple[list[int], pa.Table]: + async def go() -> list[pa.RecordBatch]: + rows = pa.Table.from_batches(await channel_from_stream(source).collect()) + inputs = _cut(rows, (1,)) + wanted = [ + case.make_op()(stream_from_batches(source, [batch])).as_table().num_rows + for batch in inputs + ] feed = OutputChannel(source, retain=False, buffer_size=1) reader = feed.open_reader() output = OutputChannel(op(source), retain=False, buffer_size=1) 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()) received: list[pa.RecordBatch] = [] - sizes: list[int] = [] - for batch in _cut(rows, (1,)): + for batch, rows_wanted in zip(inputs, wanted): await asyncio.wait_for(feed.send(batch), TIMEOUT) - await asyncio.sleep(0.001) - sizes.append(len(received)) - # Whatever this input row gave is there before the next row is sent. - while output._sent > len(received): # pyright: ignore[reportPrivateUsage] - received.append(await asyncio.wait_for(results.receive(), TIMEOUT)) + if rows_wanted: + # This row's result arrives before the next row is sent. + result = await asyncio.wait_for(results.receive(), TIMEOUT) + assert result.num_rows == rows_wanted + received.append(result) await feed.close() - received.extend(await asyncio.wait_for(results.collect(), TIMEOUT)) - await task - return sizes, pa.Table.from_batches(received) if received else rows.slice(0, 0) + assert await asyncio.wait_for(results.collect(), TIMEOUT) == [] + await asyncio.wait_for(task, TIMEOUT) + return received - _, table = asyncio.run(go()) - assert table.num_rows == expected.num_rows - assert table.to_pylist() == expected.to_pylist() + received = asyncio.run(go()) + table = pa.Table.from_batches(received) if received else None + assert (table.num_rows if table is not None else 0) == expected.num_rows + if table is not None: + assert table.to_pylist() == expected.to_pylist() @pytest.mark.parametrize("batch_size", [2, 3, 5]) @@ -637,3 +648,84 @@ def test_a_system_tag_with_a_null_is_refused_by_the_job_sync_path() -> None: ) channel = run_on_channels(SelectDataColumns(["x"]), [raw], None) assert channel.as_table(columns=ALL).column(SYSTEM_TAG).to_pylist() == ["s", None] + + +# --- Ending the output and closing the inputs ------------------------------------------------ + + +class _FailingClose(OutputChannel): + """An output channel whose ``close`` fails (an implementation that flushes).""" + + async def close(self) -> None: + raise OSError("flush failed") + + +def test_a_failing_close_of_the_output_fails_it() -> None: + """An operator whose ``output.close()`` raises fails the output, so its readers + never wait for an end that does not come.""" + source = source_a() + op = SelectDataColumns(["i8", "s"]) + + 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) + with pytest.raises(UpstreamFailedError): + _ = await asyncio.wait_for(results.collect(), TIMEOUT) + + asyncio.run(go()) + + +def test_every_input_is_closed_when_one_close_fails() -> None: + """A barrier operator over two inputs whose first close raises: the second input + is still closed, and the close error is raised once both are closed.""" + left, right = source_a(), source_a() + op = operators.SemiJoin() + + async def go() -> None: + first, second = channel_from_stream(left), channel_from_stream(right) + + async def failing_close() -> None: + raise OSError("cannot close") + + first.close = failing_close # a failing input + output = OutputChannel(op(left, right)) + with pytest.raises(OSError, match="cannot close"): + await op.async_execute_batches([first, second], output) + with pytest.raises(ChannelClosed): + _ = await second.receive() # closed + assert output.result().as_table().num_rows > 0 # the output completed first + + asyncio.run(go()) + + +# --- A prediction bug that refuses a valid result (ITL-1365) --------------------------------- + + +@pytest.mark.xfail( + strict=True, + raises=ValueError, + reason="ITL-1365: DropTagColumns predicts its tags in another order than its result " + "has them (pre-existing on main), so the result's batches do not match the " + "description and send() refuses them; the result should be sent", +) +def test_drop_tag_columns_over_three_tags_sends_its_result() -> None: + """Tags c, b, a with data-tags a and b; ``DropTagColumns(["a"])``: the channel + result is the table built from the sync rows.""" + stream = ArrowTableStream( + pa.table( + { + "a": pa.array([1, 2], pa.int64()), + "b": pa.array([3, 4], pa.int64()), + "c": pa.array([7, 8], pa.int64()), + "x": pa.array([5.0, 6.0], pa.float64()), + } + ), + tag_columns=["c", "b", "a"], + data_tags=["a", "b"], + ) + expected = R(operators.DropTagColumns(["a"])(stream)) + assert expected is not None + result = run_on_channels(operators.DropTagColumns(["a"]), [stream], None) + assert_same_table(result.as_table(columns=ALL), expected)