diff --git a/.zed/rules b/.zed/rules index f0496653a..6967e6d81 100644 --- a/.zed/rules +++ b/.zed/rules @@ -1298,6 +1298,22 @@ 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.core.record_batch_channels.InputChannel / OutputChannel carry a stream's rows as + Arrow record batches; operators see them only through the protocols RecordBatchInput / + RecordBatchOutput of protocols/core_protocols/record_batch_channels.py, which imports no + concrete core module (keep modules interacting through protocols: basedpyright counts local + and TYPE_CHECKING imports as import cycles). A channel owns no description: an input channel + refers to its stream (channel_from_stream(stream)), an output channel to the stream it + produces, and OutputChannel.result() closes it into that stream. The conversions are in one + place, core/operators/static_output_pod.py (stream_from_batches, transport_schema, and F, + _row_built_form); never build a stream from record batches elsewhere. An operator's + record-batch form (async_execute_batches, renamed async_execute when wired) applies its one + static_process body: per record batch when the class declares ROW_BY_ROW = True (each output + row comes from one input row), otherwise as a barrier over the whole input (to_stream()); + Batch with a size has its own form, grouping rows by arrival. A new operator whose output + rows each come from one input row declares ROW_BY_ROW; write no other per-operator batch + code. - 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 5a4c81c35..7b781c65c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1345,6 +1345,22 @@ 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.core.record_batch_channels.InputChannel` / `OutputChannel` carry a stream's rows as + Arrow record batches; operators see them only through the protocols `RecordBatchInput` / + `RecordBatchOutput` of `protocols/core_protocols/record_batch_channels.py`, which imports no + concrete core module (keep modules interacting through protocols: basedpyright counts local + and `TYPE_CHECKING` imports as import cycles). A channel owns no description: an input + channel refers to its stream (`channel_from_stream(stream)`), an output channel to the + stream it produces, and `OutputChannel.result()` closes it into that stream. The conversions + are in one place, `core/operators/static_output_pod.py` (`stream_from_batches`, + `transport_schema`, and F, `_row_built_form`); never build a stream from record batches + elsewhere. An operator's record-batch form (`async_execute_batches`, renamed `async_execute` + when wired) applies its one `static_process` body: per record batch when the class declares + `ROW_BY_ROW = True` (each output row comes from one input row), otherwise as a barrier over + the whole input (`to_stream()`); `Batch` with a size has its own form, grouping rows by + arrival. A new operator whose output rows each come from one input row declares + `ROW_BY_ROW`; write no other per-operator batch code. - 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/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..78af8e8d1 100644 --- a/src/orcapod/core/operators/batch.py +++ b/src/orcapod/core/operators/batch.py @@ -7,8 +7,19 @@ import pyarrow as pa from orcapod.core.operators.meta_columns import WithoutMetaWriter -from orcapod.channels import ReadableChannel, WritableChannel +from orcapod.protocols.core_protocols.record_batch_channels import ( + RecordBatchInput, + RecordBatchOutput, +) +from orcapod.channels import ( + ReadableChannel, + WritableChannel, +) from orcapod.core.operators.base import UnaryOperator +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 @@ -264,6 +275,56 @@ async def async_execute( finally: await output.close() + async def async_execute_batches( + self, inputs: Sequence[RecordBatchInput], output: RecordBatchOutput + ) -> 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: + 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: + 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) + await output.close() + except BaseException as error: + output.fail(error) + await close_inputs(inputs, error) + raise + 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/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..6cdc6ab7e 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.protocols.core_protocols.record_batch_channels import ( + RecordBatchInput, + RecordBatchOutput, +) +from orcapod.channels import ( + ReadableChannel, + WritableChannel, +) from orcapod import contexts from orcapod.config import OrcapodConfig from orcapod.contexts import DataContext @@ -33,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, @@ -49,6 +57,7 @@ TagProtocol, TrackerManagerProtocol, ) +from orcapod.system_constants import constants from orcapod.types import ColumnConfig, ContentHash, Schema logger = logging.getLogger(__name__) @@ -70,6 +79,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. @@ -445,6 +464,98 @@ def _kept_output( return StaticOutputOperatorPod._materialize_to_stream(rows) return StaticOutputOperatorPod._zero_rows_in_row_order(result) + @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 + (``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. + 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(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``. @@ -772,6 +883,240 @@ async def async_execute( finally: await output.close() + # ------------------------------------------------------------------ + # Async execution on Arrow record batches (ITL-1347) + # ------------------------------------------------------------------ + + async def async_execute_batches( + self, inputs: Sequence[RecordBatchInput], output: RecordBatchOutput + ) -> 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 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. + + 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) + await output.close() + except BaseException as error: + output.fail(error) + await close_inputs(inputs, error) + raise + await close_inputs(inputs) + + async def _send_processed( + self, + batches: Sequence[pa.RecordBatch], + stream: StreamProtocol, + output: RecordBatchOutput, + ) -> 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: RecordBatchOutput) -> 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 = row_built_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 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. + + 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 + + +# --------------------------------------------------------------------------- +# Conversions between streams and Arrow record batches (ITL-1347) +# --------------------------------------------------------------------------- + + +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: 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. + + 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.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 + zero_rows = typed.as_table(columns=ZERO_ROW_INPUT_COLUMNS) + zero_rows = zero_rows.cast( + pa.schema( + [ + field.with_type( + arrow_utils.normalize_to_large_types(field.type, keep_null=True) + ) + 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( + 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, 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 (``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 = 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: + """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 + 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: + batch: A record batch of a stream's rows. + + Returns: + The batch with those fields nullable. + """ + prefixes = (constants.SYSTEM_TAG_PREFIX, constants.SOURCE_PREFIX) + schema = pa.schema( + [ + field.with_nullable(True) if field.name.startswith(prefixes) else field + for field in batch.schema + ] + ) + return pa.RecordBatch.from_arrays(batch.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..a6f5e57ab --- /dev/null +++ b/src/orcapod/core/record_batch_channels.py @@ -0,0 +1,667 @@ +"""Channels of Arrow record batches (ITL-1347). + +``InputChannel`` and ``OutputChannel`` carry a stream's rows as Arrow record batches; they +implement ``RecordBatchInput`` and ``RecordBatchOutput`` +(``orcapod.protocols.core_protocols.record_batch_channels``). The +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, cast + +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, + row_built_names, +) +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: + """Make a feed of ``stream``'s rows; nothing is read until the first ``next``. + + Args: + stream: The complete stream to read. + """ + self._stream = stream + self._batches: deque[pa.RecordBatch] | None = None + + async def next(self) -> pa.RecordBatch | None: + """Return the stream's next record batch, or ``None`` at the end. + + The stream's table is read on the first call, not when the feed is made, in + the row-built form (``row_built_columns``) and cut into batches of at most + ``SOURCE_BATCH_ROWS`` rows; batches with no rows are skipped. + """ + if self._batches is None: + # On the first read, not when the channel is opened: opening computes + # nothing. + table = row_built_columns( + self._stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS), + self._stream.keys(), + ) + self._batches = deque( + batch + for batch in table.to_batches(max_chunksize=SOURCE_BATCH_ROWS) + if batch.num_rows + ) + return self._batches.popleft() if self._batches else None + + def close(self) -> None: + """Stop reading: the batches not read are dropped. No producer waits on it.""" + self._batches = deque() + + +class _OutputFeed: + """One reader of an output channel, with its own position.""" + + 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 + # 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: + """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] + 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: + """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 + 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: + """A single-pass, back-pressured reader of a stream's Arrow record batches. + + The Arrow-record-batch form of ``ReadableChannel``. The description of what it + delivers is its ``stream``, known before the first batch: the producing node, or + the stream it was opened from. A channel has no identity of its own and is read + once; to read again, go back to a stream (the one it was opened from, or the one + ``to_stream`` gives). + + Made by ``channel_from_stream`` or by ``OutputChannel.open_reader``, never + directly. + """ + + def __init__(self, stream: StreamProtocol, feed: _BatchFeed) -> None: + """Make an input channel; use ``channel_from_stream`` or ``open_reader``. + + Args: + stream: The stream whose rows the channel delivers: its description. + feed: Where the record batches come from. + """ + self._stream = stream + self._feed = feed + self._received = 0 + self._ended = False + # Closed by its consumer before the producer completed. + self._closed = False + + @property + def stream(self) -> StreamProtocol: + """The stream whose rows this channel delivers: the description.""" + return self._stream + + async def receive(self) -> pa.RecordBatch: + """Return the next Arrow record batch. + + A read that is cancelled while it waits closes the channel, as ``close`` does: + a consumer that stops reading never holds its producer. + + Raises: + ChannelClosed: At the end, and after ``close``. After a ``close`` that came + before the producer completed, the error says so, and iteration + (``async for``) raises it instead of ending: no consumer loop takes + part of an input for all of it. + UpstreamFailedError: If the producer failed or was cancelled. + """ + if self._closed: + raise self._closed_early() + if self._ended: + raise ChannelClosed() + try: + batch = await self._feed.next() + except asyncio.CancelledError: + await self.close() + raise + if batch is None: + if self._closed: # woken by its own early close + raise self._closed_early() + self._ended = True + raise ChannelClosed() + self._received += 1 + return batch + + def __aiter__(self) -> AsyncIterator[pa.RecordBatch]: + """Iterate over the remaining record batches, in arrival order.""" + return self + + async def __anext__(self) -> pa.RecordBatch: + """Return the next record batch; end the iteration at the producer's end. + + A channel closed before its producer completed does not end the iteration: + its ``ChannelClosed`` is raised, so a loop never takes part of an input for + all of it. + """ + try: + return await self.receive() + except ChannelClosed: + if self._closed: + raise # closed before its producer completed: not the end + raise StopAsyncIteration + + def _closed_early(self) -> ChannelClosed: + """The error of a read after a close that came before the producer completed.""" + return ChannelClosed( + f"The input channel of {_named(self._stream)} was closed before its " + + "producer completed; it has no complete input to give." + ) + + async def collect(self) -> list[pa.RecordBatch]: + """Read to the end and return every remaining record batch, in arrival order. + + Raises: + ChannelClosed: If the channel was closed before its producer completed: + what was read is part of the input, never returned as all of it. + UpstreamFailedError: If the producer failed or was cancelled. + """ + return [batch async for batch in self] + + async def to_stream(self) -> StreamProtocol: + """Read to the end and return what the channel delivered, as a stream. + + The stream holds the record batches in arrival order, with the identity of + ``stream`` (``stream_from_batches``). It is how an operator that needs all of + an input reads it. Called on a channel not read yet: a stream of part of an + input is never made. + + Raises: + RuntimeError: If a record batch has already been received. + ChannelClosed: If the channel was closed before its producer completed. + UpstreamFailedError: If the producer failed or was cancelled. + """ + if self._received: + raise RuntimeError( + "to_stream() gives everything an input channel delivers, as a stream; " + + f"{self._received} record batch(es) of this one have been received " + + "already." + ) + return stream_from_batches(self._stream, await self.collect()) + + async def close(self) -> None: + """Stop reading. The producer no longer waits for this reader.""" + if not self._ended: + self._closed = True + self._ended = True + self._feed.close() + + +class OutputChannel: + """The producer side of a node's async output, in Arrow record batches. + + 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: + """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 + self._retain = retain + self._buffer_size = buffer_size + 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._send_lock = asyncio.Lock() + 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: + """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( + 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 _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: + 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 + 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( + 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()}." + ) + 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. 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. + UpstreamFailedError: If the channel failed (``fail``); its cause is the + producer's error. + ValueError: If the batch's schema is not the stream's. + """ + self._raise_if_ended() + self._check_schema(batch) + if not batch.num_rows: + return + self._sent += 1 + if self._retain: + self._batches.append(batch) + self._notify() + return + # 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() + raise + finally: + self._sending -= 1 + + async def close(self) -> 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() + + 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 rows in the row-built form (``row_built_columns``) as + Arrow record batches of at most ``SOURCE_BATCH_ROWS`` rows. Several channels may be + opened on one stream, each with its own position; nothing is computed until the + first read, and nothing is queued, since the stream is complete. + + Args: + stream: The stream to read; it is the channel's description. + + Returns: + The input channel. + """ + return InputChannel(stream, _StreamFeed(stream)) + + +def _named(stream: Any) -> str: # pyright: ignore[reportExplicitAny] # any stream or node + """How an error names a stream: its label, or what it prints as.""" + label = getattr(stream, "label", None) + return repr(label) if label else repr(stream) + + +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 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}" + 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): + # 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"} + 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) or not ( + column.type.equals(carried, check_metadata=True) + ): + return ( + 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 + """``field`` with no field metadata, at its own level and below.""" + 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``'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``). + 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, 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): + 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. + children = array.flatten() # pyright: ignore[reportAttributeAccessIssue, reportUnknownMemberType, reportUnknownVariableType] + return all( + _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/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/src/orcapod/errors.py b/src/orcapod/errors.py index 7488bb0ba..b17ececdd 100644 --- a/src/orcapod/errors.py +++ b/src/orcapod/errors.py @@ -783,6 +783,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 RejoinDifferingColumnWarning(UserWarning): """``Rejoin`` dropped rows of one origin row because a shared column differed. 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..27f34aa69 --- /dev/null +++ b/src/orcapod/protocols/core_protocols/record_batch_channels.py @@ -0,0 +1,86 @@ +"""Protocols of the channels of Arrow record batches (ITL-1347). + +``RecordBatchInput`` and ``RecordBatchOutput`` are what an operator's record-batch form +reads and writes. The stream is primary and owns the description (keys, schemas, data +context, pipeline hash); a channel refers to its stream and restates nothing. The +implementations are in ``orcapod.core.record_batch_channels``. +""" + +from __future__ import annotations + +from collections.abc import AsyncIterator +from typing import TYPE_CHECKING, Protocol + +if TYPE_CHECKING: + import pyarrow as pa + + from orcapod.protocols.core_protocols.streams import StreamProtocol + + +class RecordBatchInput(Protocol): + """A single-pass reader of a stream's Arrow record batches. + + The Arrow-record-batch form of ``ReadableChannel`` (``orcapod.channels``); ``InputChannel`` of + ``orcapod.core.record_batch_channels`` is the implementation. Its description is + its ``stream``, known before the first batch. + """ + + @property + def stream(self) -> StreamProtocol: + """The stream whose rows this channel delivers: the description.""" + ... + + async def receive(self) -> pa.RecordBatch: + """Return the next Arrow record batch. + + Raises: + ChannelClosed: At the end, and after ``close``. + UpstreamFailedError: If the producer failed or was cancelled. + """ + ... + + def __aiter__(self) -> AsyncIterator[pa.RecordBatch]: + """Iterate over the remaining record batches, in arrival order.""" + ... + + async def collect(self) -> list[pa.RecordBatch]: + """Read to the end and return every remaining record batch, in arrival order.""" + ... + + async def to_stream(self) -> StreamProtocol: + """Read to the end and return what the channel delivered, as a stream. + + All of the input or nothing: it needs a channel not read yet. ``collect`` + drains the batches that remain; ``to_stream`` never makes a stream of part of + an input. + + Raises: + RuntimeError: If a record batch has already been received. + ChannelClosed: If the channel was closed before its producer completed. + UpstreamFailedError: If the producer failed or was cancelled. + """ + ... + + async def close(self) -> None: + """Stop reading. The producer no longer waits for this reader.""" + ... + + +class RecordBatchOutput(Protocol): + """The producer side of a stream's Arrow record batches. + + The Arrow-record-batch form of ``WritableChannel`` (``orcapod.channels``); ``OutputChannel`` of + ``orcapod.core.record_batch_channels`` is the implementation. + """ + + async def send(self, batch: pa.RecordBatch) -> None: + """Send one Arrow record batch of the stream's transport columns.""" + ... + + async def close(self) -> None: + """Complete the output.""" + ... + + def fail(self, error: BaseException) -> None: + """End the output with the producer's failure or cancellation.""" + ... diff --git a/tests/test_channels/test_record_batch_channels.py b/tests/test_channels/test_record_batch_channels.py new file mode 100644 index 000000000..4c03cefd3 --- /dev/null +++ b/tests/test_channels/test_record_batch_channels.py @@ -0,0 +1,1151 @@ +"""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 (``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". + +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.protocols.core_protocols.record_batch_channels import ( + RecordBatchInput, + RecordBatchOutput, +) +from orcapod.channels import ( + ChannelClosed, + ReadableChannel, + WritableChannel, +) +from orcapod.core.operators import MapData, PolarsFilter, SelectDataColumns +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 +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 bool( + 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 channel_from_stream(stream).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 = channel_from_stream(stream) + + assert isinstance(channel, InputChannel) + assert isinstance(channel, ReadableChannel) + as_protocol: RecordBatchInput = channel # what an operator reads (type-checked) + assert as_protocol.stream is stream + delivered = run(channel.to_stream) + assert same(delivered.as_table(columns=ALL), R(stream)) + assert delivered.keys() == stream.keys() + assert delivered.output_schema() == stream.output_schema() + assert delivered.data_context_key == stream.data_context_key + assert delivered.pipeline_hash() == stream.pipeline_hash() + + +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 = 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: + """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 = 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()) + + 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(channel_from_stream(stream).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 = channel_from_stream(source()) + 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) + 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) + 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: + """A send after ``close()`` raises ``ChannelClosed``, and ``result()`` exists only + once the channel is closed.""" + 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 + + +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. 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") + + 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] = [] + with pytest.raises(UpstreamFailedError) as failed: + async for batch in reader: + delivered.append(batch.num_rows) + cause = failed.value.__cause__ + assert isinstance(cause, ChannelClosed if ending == "close" else OSError) + return type(raised[0]), delivered + + raised, delivered = run(write) + assert raised is (ChannelClosed if ending == "close" else 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 + + +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}] # pyright: ignore[reportAttributeAccessIssue] # the stubs omit it + 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: # pyright: ignore[reportIncompatibleMethodOverride] # a kind that cannot type itself without rows + 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 + + +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 ------------------- + + +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[Any]]: + 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: + """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) + + 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: + """``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) + + +# --- 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(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] = [] + 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: + """``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) + + 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 [channel_from_stream(stream)] + + 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..c47c11a3c --- /dev/null +++ b/tests/test_core/operators/test_record_batch_execution.py @@ -0,0 +1,731 @@ +"""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 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 AddTags, Batch, PolarsFilter, SelectDataColumns +from orcapod.core.operators.static_output_pod import ( + StaticOutputOperatorPod, + stream_from_batches, +) +from orcapod.core.record_batch_channels import ( + InputChannel, + OutputChannel, + channel_from_stream, +) +from orcapod.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, + 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 channel_from_stream(stream).collect() + if sizes is None or not batches: + return channel_from_stream(stream) + 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() + # 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) + 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 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() -> 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)) + received: list[pa.RecordBatch] = [] + for batch, rows_wanted in zip(inputs, wanted): + await asyncio.wait_for(feed.send(batch), TIMEOUT) + if rows_wanted: + # This row's result arrives before the next row is sent. + result = await asyncio.wait_for(results.receive(), TIMEOUT) + assert result.num_rows == rows_wanted + received.append(result) + await feed.close() + assert await asyncio.wait_for(results.collect(), TIMEOUT) == [] + await asyncio.wait_for(task, TIMEOUT) + return received + + 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]) +@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 channel_from_stream(source).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) + + +# --- 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" + + +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) + + +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 + + +# --- 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.parametrize("layout", ["one_batch", "one_row_per_batch"]) +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( + { + "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"], + ) + 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()) + + +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( + { + "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: _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] + + +# --- 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)