From 752a5d93f34d5f1953cd992c7726e962e6621596 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 21 Nov 2026 22:09:54 -0800 Subject: [PATCH 01/86] perf(datagrams): build the rows of a table without normalizing each row again (ITL-1348) (#478) ArrowTableStream.iter_data built every row's Tag and Data from a one-row slice through the public constructors, which normalized the row to large types three times (tag, data, source info) and split its columns into groups again, although the stream's table is already normalized. Tag.rows_of(table) and Data.rows_of(table) prepare a table once for all of its rows (normalization, the split into data, meta, system-tag and source-info columns) and yield, for each row, the datagram the constructor builds from that row. Rows are read batch by batch as zero-copy slices, so the cost of a row does not depend on how the table is chunked (a table a job node builds from rows has one chunk per row). The constructors and the row path share the code that sets a datagram's state. 60,000-row source, list(iter_data()): 4.97 s -> 1.47 s. A fresh job of three operator nodes over two 30,000-row sources: 24.6 s -> 17.0 s. No hash, stored table or output changes. Co-authored-by: Edgar Y. Walker <> Co-authored-by: Claude Fable 5.2 --- changelog.d/ITL-1348.md | 14 + src/orcapod/core/datagrams/datagram.py | 171 ++++- src/orcapod/core/datagrams/tag_data.py | 139 +++- .../core/streams/arrow_table_stream.py | 47 +- .../test_core/datagrams/test_rows_of_table.py | 598 ++++++++++++++++++ 5 files changed, 911 insertions(+), 58 deletions(-) create mode 100644 changelog.d/ITL-1348.md create mode 100644 tests/test_core/datagrams/test_rows_of_table.py diff --git a/changelog.d/ITL-1348.md b/changelog.d/ITL-1348.md new file mode 100644 index 000000000..7db869fd6 --- /dev/null +++ b/changelog.d/ITL-1348.md @@ -0,0 +1,14 @@ +### Changed + +- **Rows of a stream are built without normalizing each one again** — `iter_data()` of a + stream over a table (every source, every operator result, every job node's rows) built + each row's `Tag` and `Data` from a one-row slice through their constructors, which + normalized the row's types three times (tag, data, source info) and split its columns into + groups again, although the stream's table is already normalized: 180,000 normalizations for + 60,000 rows. The table is now prepared once for all of its rows, however it is chunked (a + table a job node builds from rows has one chunk per row), by `Tag.rows_of(table)` and + `Data.rows_of(table)`, which yield for each row the datagram the constructor builds from + that row: the same values, system tags, source info, meta values, Arrow types and hashes. + Building the rows of a 60,000-row source takes 1.5 s instead of 5.0 s, and a job of three + operator nodes over two 30,000-row sources runs in 17.0 s instead of 24.6 s. No hash, + stored table or output changes. (ITL-1348) diff --git a/src/orcapod/core/datagrams/datagram.py b/src/orcapod/core/datagrams/datagram.py index 4f8cb8eb6..2ae640dc3 100644 --- a/src/orcapod/core/datagrams/datagram.py +++ b/src/orcapod/core/datagrams/datagram.py @@ -20,6 +20,7 @@ from __future__ import annotations +import itertools import logging import uuid from collections.abc import Collection, Iterator, Mapping @@ -48,6 +49,70 @@ logger = logging.getLogger(__name__) +def _data_and_meta_tables(table: pa.Table) -> tuple[pa.Table, pa.Table | None]: + """Split a normalized table into what a datagram holds as data and as meta. + + Args: + table: A table in the large types of a datagram + (``arrow_utils.normalize_table_to_large_types``), of any number of rows. + + Returns: + The table without its data-context and meta columns, and the table of its meta + columns, ``None`` when it has none. + + Raises: + ValueError: If no column is left as data. + """ + names = table.column_names + context_cols = [c for c in names if c == constants.CONTEXT_KEY] + meta_col_names = [c for c in names if c.startswith(constants.META_PREFIX)] + data_table = table.drop_columns(context_cols + meta_col_names) + if len(data_table.column_names) == 0: + raise ValueError("Data table must contain at least one data column.") + return data_table, table.select(meta_col_names) if meta_col_names else None + + +def _one_row_tables(*tables: pa.Table) -> Iterator[tuple[pa.Table, ...]]: + """Yield, for each row of tables of one length, the one-row table of each. + + The tables may be chunked in any way, each in its own: the rows are read batch by + batch (``Table.to_batches`` cuts at the chunk boundaries of every column), and a + row is a slice of its batch, so no value is copied and the cost of a row does not + grow with the number of chunks, as ``Table.slice(i, 1)`` on a table of many chunks + does (a table built from rows has one chunk per row). + + Args: + *tables: Tables with the same number of rows. + + Yields: + One tuple per row, in row order: the one-row table of each of ``tables``, with + that table's schema. + """ + schemas = [table.schema for table in tables] + bounds = list(itertools.accumulate((t.num_columns for t in tables), initial=0)) + arrays = [column for table in tables for column in table.columns] + side_by_side = pa.Table.from_arrays( + arrays, names=[str(i) for i in range(len(arrays))] + ) + row = 0 + for batch in side_by_side.to_batches(): + columns = batch.columns + parts = [ + pa.RecordBatch.from_arrays(columns[start:stop], schema=schema) + for start, stop, schema in zip(bounds, bounds[1:], schemas) + ] + for i in range(batch.num_rows): + yield tuple( + pa.Table.from_batches([part.slice(i, 1)]) + if part.num_columns + # A table with no column still has its rows; a batch made of none + # of them has not. + else table.slice(row, 1) + for part, table in zip(parts, tables) + ) + row += 1 + + def context_key_field() -> pa.Field[Any]: """The field of a datagram's data context column (``_context_key``).""" return pa.field(constants.CONTEXT_KEY, pa.large_string(), nullable=False) @@ -182,26 +247,41 @@ def _init_from_table( if constants.CONTEXT_KEY in table.column_names and data_context is None: data_context = table[constants.CONTEXT_KEY].to_pylist()[0] - context_cols = [c for c in table.column_names if c == constants.CONTEXT_KEY] + data_table, meta_table = _data_and_meta_tables(table) + self._init_from_row( + data_table, meta_table, meta_info, data_context, record_uuid + ) + def _init_from_row( + self, + data_table: pa.Table, + meta_table: pa.Table | None, + meta_info: Mapping[str, DataValue] | None, + data_context: str | contexts.DataContext | None, + record_uuid: uuid.UUID | None, + ) -> None: + """Set the state of a datagram held as Arrow, from one prepared row. + + The one place that state is set: ``_init_from_table`` prepares its row itself, + and ``_rows_of_table`` prepares all rows of a table at once (ITL-1348). + + Args: + data_table: The row's data columns, normalized, as + ``_data_and_meta_tables`` returns them. + meta_table: The row's meta columns, or ``None``. + meta_info: Meta values to add to those of ``meta_table``. + data_context: The row's data context. + record_uuid: The datagram's id, if it has one. + """ super().__init__(data_context=data_context) self._datagram_uuid = record_uuid - meta_col_names = [ - c for c in table.column_names if c.startswith(constants.META_PREFIX) - ] - self._data_table = table.drop_columns(context_cols + meta_col_names) + self._data_table = data_table self._data_dict = None self._data_python_schema = None # computed lazily self._data_arrow_schema = None # computed lazily - if len(self._data_table.column_names) == 0: - raise ValueError("Data table must contain at least one data column.") - # Build meta table - meta_table: "pa.Table | None" = ( - table.select(meta_col_names) if meta_col_names else None - ) if meta_info is not None: normalized_meta = { k @@ -244,6 +324,75 @@ def _init_from_table( self._meta_table = None self._context_table = None + @classmethod + def _rows_of_table( + cls, + table: pa.Table, + data_context: str | contexts.DataContext | None, + *, + apart_prefix: str | None = None, + beside: pa.Table | None = None, + ) -> Iterator[tuple[Self, pa.Table | None, pa.Table | None]]: + """Yield a datagram for each row of ``table``, prepared once for all rows. + + The datagram of row ``i`` has the state ``_init_from_table`` gives the one-row + table ``table.slice(i, 1)``. What that does to every row alike is done here + once for the whole table (ITL-1348): the normalization to the large types of a + datagram, and the split into data, meta and data-context columns. A row is + then a slice of each, however the table is chunked. + + Args: + table: The rows, of any Arrow types a datagram accepts. + data_context: The data context of every row; ``None`` reads each row's + own from the table's data-context column, if it has one. + apart_prefix: A prefix whose data columns the datagrams do not hold: a + subclass that keeps a column group of its own (a tag's system tags) + gets them beside each datagram instead. + beside: A table of the same rows that is no part of the datagrams (a + data's source info), to be read row by row with them. + + Yields: + The datagram, built without calling ``__init__``; the one-row table of + its columns named with ``apart_prefix`` (``None`` when there is none); + and the row of ``beside`` (``None`` when not given). + + Raises: + ValueError: If the table has rows and none of its columns is data. + """ + if table.num_rows == 0: + return + table = arrow_utils.normalize_table_to_large_types(table) + row_contexts: list[Any | None] | None = None + if constants.CONTEXT_KEY in table.column_names and data_context is None: + row_contexts = table[constants.CONTEXT_KEY].to_pylist() + data_table, meta_table = _data_and_meta_tables(table) + apart_table: pa.Table | None = None + if apart_prefix is not None: + apart = [c for c in data_table.column_names if c.startswith(apart_prefix)] + if apart: + apart_table = data_table.select(apart) + data_table = data_table.drop_columns(apart) + # The optional tables that are there, and where each is in a row's tuple. + optional = [meta_table, apart_table, beside] + places = list( + itertools.accumulate((t is not None for t in optional), initial=1) + ) + rows = _one_row_tables(data_table, *(t for t in optional if t is not None)) + for i, parts in enumerate(rows): + meta_row, apart_row, beside_row = ( + parts[place] if t is not None else None + for t, place in zip(optional, places) + ) + row = cls.__new__(cls) + row._init_from_row( + parts[0], + meta_row, + None, + data_context if row_contexts is None else row_contexts[i], + None, + ) + yield row, apart_row, beside_row + # ------------------------------------------------------------------ # Internal helpers (lazy loading) # ------------------------------------------------------------------ diff --git a/src/orcapod/core/datagrams/tag_data.py b/src/orcapod/core/datagrams/tag_data.py index 01e9b362c..808ae8b15 100644 --- a/src/orcapod/core/datagrams/tag_data.py +++ b/src/orcapod/core/datagrams/tag_data.py @@ -18,7 +18,7 @@ import logging import uuid -from collections.abc import Mapping, Sequence +from collections.abc import Iterator, Mapping, Sequence from typing import TYPE_CHECKING, Any, Self from orcapod import contexts @@ -136,15 +136,55 @@ def __init__( **kwargs, ) - self._system_tags: dict[str, DataValue] = { - **extracted_sys_tags, - **(system_tags or {}), - } + self._set_system_tags({**extracted_sys_tags, **(system_tags or {})}) + + def _set_system_tags(self, system_tags: dict[str, DataValue]) -> None: + """Hold ``system_tags`` as this tag's system tags.""" + self._system_tags: dict[str, DataValue] = system_tags self._system_tags_python_schema: Schema = infer_python_schema_from_pylist_data( [self._system_tags], default_type=str ) self._system_tags_table: "pa.Table | None" = None + @classmethod + def rows_of( + cls, + table: "pa.Table", + data_context: "str | contexts.DataContext | None" = None, + ) -> Iterator[Self]: + """Yield the tag of each row of ``table``, in row order. + + Row ``i`` gives the tag ``cls(table.slice(i, 1), data_context=data_context)`` + gives: the same user tags, system tags, meta values, Arrow types and hashes. + What the constructor does to every row alike is done once for the whole table + (ITL-1348): the normalization to the large types of a datagram and the split + of the columns into groups. Building the tags of a table row by row through the + constructor normalizes every row again. The table may be chunked in any way. + + Args: + table: The rows: user-tag and system-tag columns. + data_context: The data context of every tag; ``None`` reads each row's own + from the table's data-context column, or takes the default. + + Yields: + One tag per row. + + Raises: + ValueError: If the table has rows and no tag column. + """ + rows = cls._rows_of_table( + table, data_context, apart_prefix=constants.SYSTEM_TAG_PREFIX + ) + for tag, system_tag_row, _ in rows: + tag._set_system_tags( + tag._data_context.type_converter.arrow_table_to_python_dicts( + system_tag_row + )[0] + if system_tag_row is not None + else {} + ) + yield tag + # ------------------------------------------------------------------ # Internal helper # ------------------------------------------------------------------ @@ -323,12 +363,7 @@ def __init__( for k, v in source_info.items() } - data_table, prefixed_tables = arrow_utils.prepare_prefixed_columns( - data, - {constants.SOURCE_PREFIX: source_info}, - exclude_columns=[constants.CONTEXT_KEY], - exclude_prefixes=[constants.META_PREFIX], - ) + data_table, si_table = self._data_and_source_info_tables(data, source_info) super().__init__( data_table, meta_info=meta_info, @@ -336,14 +371,9 @@ def __init__( record_uuid=record_uuid, **kwargs, ) - si_table = prefixed_tables[constants.SOURCE_PREFIX] - if si_table.num_columns > 0 and si_table.num_rows > 0: - self._source_info: dict[str, SourceInfoValue] = { - k.removeprefix(constants.SOURCE_PREFIX): v - for k, v in si_table.to_pylist()[0].items() - } - else: - self._source_info = {} + self._source_info: dict[str, SourceInfoValue] = self._source_info_of_row( + si_table + ) else: # Dict path: extract source-info keys before calling super() data_only = { @@ -368,6 +398,77 @@ def __init__( self._source_info_table: "pa.Table | None" = None + @staticmethod + def _data_and_source_info_tables( + table: "pa.Table", source_info: "Mapping[str, SourceInfoValue]" + ) -> "tuple[pa.Table, pa.Table]": + """Split ``table`` into its data columns and the source info of each. + + Args: + table: Data, meta and source-info columns, of any number of rows. + source_info: Tokens to use instead of the table's, by data column name. + + Returns: + The table without its source-info columns, and a table with one + source-info column per data column (null where there is no token). + """ + data_table, prefixed_tables = arrow_utils.prepare_prefixed_columns( + table, + {constants.SOURCE_PREFIX: source_info}, + exclude_columns=[constants.CONTEXT_KEY], + exclude_prefixes=[constants.META_PREFIX], + ) + return data_table, prefixed_tables[constants.SOURCE_PREFIX] + + @staticmethod + def _source_info_of_row(si_table: "pa.Table") -> "dict[str, SourceInfoValue]": + """Return the tokens of a one-row source-info table, by data column name.""" + if si_table.num_columns > 0 and si_table.num_rows > 0: + return { + k.removeprefix(constants.SOURCE_PREFIX): v + for k, v in si_table.to_pylist()[0].items() + } + return {} + + @classmethod + def rows_of( + cls, + table: "pa.Table", + data_context: "str | contexts.DataContext | None" = None, + ) -> Iterator[Self]: + """Yield the data of each row of ``table``, in row order. + + Row ``i`` gives the data ``cls(table.slice(i, 1), data_context=data_context)`` + gives: the same values, source info, meta values, Arrow types and hashes. What + the constructor does to every row alike is done once for the whole table + (ITL-1348): the split into data and source-info columns and the normalization + to the large types of a datagram. Building the data of a table row by row + through the constructor splits and normalizes every row again. The table may + be chunked in any way. + + Args: + table: The rows: data, meta and source-info columns. + data_context: The data context of every row; ``None`` reads each row's own + from the table's data-context column, or takes the default. + + Yields: + One ``Data`` per row. + + Raises: + ValueError: If the table has rows and no data column. + """ + if table.num_rows == 0: + return + data_table, si_table = cls._data_and_source_info_tables(table, {}) + if data_table.num_columns == 0: + raise ValueError("Data table must contain at least one data column.") + rows = cls._rows_of_table(data_table, data_context, beside=si_table) + for data, _, source_info_row in rows: + assert source_info_row is not None + data._source_info = cls._source_info_of_row(source_info_row) + data._source_info_table = None + yield data + # ------------------------------------------------------------------ # Internal helper # ------------------------------------------------------------------ diff --git a/src/orcapod/core/streams/arrow_table_stream.py b/src/orcapod/core/streams/arrow_table_stream.py index ddac12f03..a07c32400 100644 --- a/src/orcapod/core/streams/arrow_table_stream.py +++ b/src/orcapod/core/streams/arrow_table_stream.py @@ -457,40 +457,31 @@ def iter_data(self) -> Iterator[tuple[TagProtocol, Data]]: source_columns = list(self._source_info_table.column_names) data_columns = list(self._data_columns) + source_columns - # The source-info table has its own chunk layout, so append its - # columns to the backing table and batch that once. - # ``Table.to_batches`` cuts at the union of the chunk boundaries of - # every column, so the tag, data and source-info columns of a batch - # always cover the same rows. Batching any of them separately and - # zipping the results drops or mis-pairs rows whenever they are - # chunked differently. - batching_table = self._table + # The source-info columns go beside the data columns they describe: the + # rows of this one table are read together, however each column is + # chunked (``rows_of`` reads batch by batch, cut at every column's chunk + # boundaries, so no row is dropped or paired with another's). + rows = self._table for name in source_columns: - batching_table = batching_table.append_column( + rows = rows.append_column( self._source_info_table.schema.field(name), self._source_info_table.column(name), ) - for batch in batching_table.to_batches(): - tag_batch = batch.select(tag_columns) - data_batch = batch.select(data_columns) - for i in range(batch.num_rows): - if tag_columns: - tag = Tag( - tag_batch.slice(i, 1), # type: ignore - data_context=self.data_context, - ) - else: - # A fresh empty tag per row, so rows never share one object. - tag = Tag({}) - - data = Data( - data_batch.slice(i, 1), # type: ignore - data_context=self.data_context, - ) + # The table is prepared once for all of its rows (ITL-1348): building + # ``Tag(row)`` and ``Data(row)`` from one-row slices normalized every row + # three times and split its columns again. + tags = ( + Tag.rows_of(rows.select(tag_columns), self.data_context) + if tag_columns + else None + ) + for data in Data.rows_of(rows.select(data_columns), self.data_context): + # A fresh empty tag per row, so rows never share one object. + tag = next(tags) if tags is not None else Tag({}) - yield tag, data + yield tag, data - cached_elements.append((tag, data)) + cached_elements.append((tag, data)) self._cached_elements = cached_elements else: yield from self._cached_elements diff --git a/tests/test_core/datagrams/test_rows_of_table.py b/tests/test_core/datagrams/test_rows_of_table.py new file mode 100644 index 000000000..354c1d2e9 --- /dev/null +++ b/tests/test_core/datagrams/test_rows_of_table.py @@ -0,0 +1,598 @@ +"""The rows of a table as ``Tag`` and ``Data``, prepared once per table (ITL-1348). + +``Tag.rows_of(table)`` and ``Data.rows_of(table)`` yield, for each row, the datagram the +constructor builds from the one-row table ``table.slice(i, 1)``. What the constructor does +to every row alike (the normalization to large types, the split of the columns into +groups) is done once per table, so building the rows of a 60,000-row stream no longer +normalizes 180,000 one-row tables. Nothing a row holds or reports may differ: these +tests compare every row with the constructor's, in what it holds and in every view. +""" + +from __future__ import annotations + +from collections.abc import Callable +from pathlib import Path +from typing import Any +from unittest import mock + +import pyarrow as pa +import pytest + +from orcapod import contexts +from orcapod.core.datagrams import Data, Tag +from orcapod.core.datagrams.datagram import Datagram +from orcapod.core.streams import ArrowTableStream +from orcapod.sources import ArrowTableSource, DictSource +from orcapod.system_constants import constants +from orcapod.types import ColumnConfig +from orcapod.utils import arrow_utils + +SYS = constants.SYSTEM_TAG_PREFIX +SRC = constants.SOURCE_PREFIX +META = constants.META_PREFIX +CONTEXT = constants.CONTEXT_KEY +EVERYTHING = ColumnConfig.all() + +# --- Comparing two datagrams ------------------------------------------------------------ + + +def _same_table(left: pa.Table | None, right: pa.Table | None) -> bool: + """Whether two tables have one schema (metadata included) and the same values.""" + if left is None or right is None: + return left is right + return left.schema.equals(right.schema, check_metadata=True) and ( + left.to_pylist() == right.to_pylist() + ) + + +def _assert_same_datagram(built: Datagram, expected: Datagram) -> None: + """Assert ``built`` holds and reports exactly what ``expected`` does.""" + assert type(built) is type(expected) + # What it holds: the same attributes, each with the same value. + held, wanted = vars(built), vars(expected) + assert sorted(held) == sorted(wanted) + for name, value in wanted.items(): + if isinstance(value, pa.Table) or isinstance(held[name], pa.Table): + assert _same_table(held[name], value), name + elif name == "_data_context": + assert held[name] is value + else: + assert held[name] == value, name + # What it reports, through every view. + assert built.data_context_key == expected.data_context_key + assert built.keys(columns=EVERYTHING) == expected.keys(columns=EVERYTHING) + assert built.schema(columns=EVERYTHING) == expected.schema(columns=EVERYTHING) + assert built.arrow_schema(columns=EVERYTHING).equals( + expected.arrow_schema(columns=EVERYTHING), check_metadata=True + ) + assert built.as_dict(columns=EVERYTHING) == expected.as_dict(columns=EVERYTHING) + assert _same_table( + built.as_table(columns=EVERYTHING), expected.as_table(columns=EVERYTHING) + ) + assert _same_table(built.as_table(), expected.as_table()) + assert built.get_meta_info() == expected.get_meta_info() + assert built.content_hash() == expected.content_hash() + if isinstance(expected, Tag): + assert isinstance(built, Tag) + assert built.system_tags() == expected.system_tags() + if isinstance(expected, Data): + assert isinstance(built, Data) + assert built.source_info() == expected.source_info() + + +def _assert_rows_match_the_constructor( + kind: type[Tag] | type[Data], table: pa.Table, data_context: Any = None +) -> None: + """Assert ``kind.rows_of(table)`` yields the constructor's datagram of every row.""" + rows = list(kind.rows_of(table, data_context)) + assert len(rows) == table.num_rows + for i, row in enumerate(rows): + _assert_same_datagram(row, kind(table.slice(i, 1), data_context=data_context)) + + +# --- Tables of tags --------------------------------------------------------------------- + + +def _user_and_system_tags() -> pa.Table: + """Two user tags and two system tags, small types, a null, one non-null field.""" + return pa.table( + { + "subject": pa.array(["m1", "m1", "m2"], pa.string()), + "trial": pa.array([1, 2, None], pa.int16()), + f"{SYS}source:abc": pa.array(["events", "events", "events"], pa.string()), + f"{SYS}record_id:abc": pa.array(["row_0", "row_1", "row_2"]), + }, + schema=pa.schema( + [ + pa.field("subject", pa.string(), nullable=False), + pa.field("trial", pa.int16(), metadata={"unit": "count"}), + pa.field(f"{SYS}source:abc", pa.string()), + pa.field(f"{SYS}record_id:abc", pa.string()), + ], + metadata={"origin": "a hand-built table"}, + ), + ) + + +def _reordered(table: pa.Table) -> pa.Table: + """The same table with its columns in the reverse order.""" + return table.select(list(reversed(table.column_names))) + + +def _in_two_chunks(table: pa.Table) -> pa.Table: + """The same rows, held in two chunks.""" + return pa.concat_tables([table.slice(0, 1), table.slice(1)]) + + +def _one_chunk_per_row(table: pa.Table) -> pa.Table: + """The same rows, one chunk each, as a table built from rows holds them.""" + return pa.concat_tables([table.slice(i, 1) for i in range(table.num_rows)]) + + +def _system_tags_only() -> pa.Table: + """No user tag: every column is a system tag.""" + return pa.table( + { + f"{SYS}source:abc": pa.array(["a", "b"], pa.large_string()), + f"{SYS}record_id:abc": pa.array(["row_0", None], pa.large_string()), + } + ) + + +def _user_tags_only() -> pa.Table: + """No system tag; a list tag, a binary tag and a tag with no values at all.""" + return pa.table( + { + "session": pa.array([["a", "b"], [], None], pa.list_(pa.string())), + "blob": pa.array([b"x", b"", None], pa.binary()), + "unknown": pa.array([None, None, None], pa.null()), + "day": pa.array([1, 2, 3], pa.date32()), + } + ) + + +def _tags_with_meta_and_context() -> pa.Table: + """Tags beside a meta column and each row's own data context.""" + key = contexts.get_default_context_key() + return pa.table( + { + "subject": pa.array(["m1", "m2"], pa.large_string()), + "trial": pa.array([1, 2], pa.int64()), + f"{META}note": pa.array(["first", None], pa.string()), + f"{SYS}source:abc": pa.array(["events", "events"], pa.large_string()), + CONTEXT: pa.array([key, key], pa.large_string()), + } + ) + + +TAG_TABLES: dict[str, Callable[[], pa.Table]] = { + "user_and_system_tags": _user_and_system_tags, + "user_and_system_tags_reordered": lambda: _reordered(_user_and_system_tags()), + "user_and_system_tags_in_two_chunks": lambda: _in_two_chunks( + _user_and_system_tags() + ), + "user_and_system_tags_one_chunk_per_row": lambda: _one_chunk_per_row( + _user_and_system_tags() + ), + "system_tags_only": _system_tags_only, + "system_tags_only_one_chunk_per_row": lambda: _one_chunk_per_row( + _system_tags_only() + ), + "user_tags_only": _user_tags_only, + "user_tags_only_reordered": lambda: _reordered(_user_tags_only()), + "tags_with_meta_and_context": _tags_with_meta_and_context, + "no_rows": lambda: _user_and_system_tags().slice(0, 0), +} + + +@pytest.mark.parametrize("name", list(TAG_TABLES)) +@pytest.mark.parametrize("given_context", [False, True]) +def test_tag_rows_are_the_constructors(name: str, given_context: bool) -> None: + """Each tag of ``Tag.rows_of`` is ``Tag(row)``, in every attribute and view.""" + context = contexts.resolve_context(None) if given_context else None + + _assert_rows_match_the_constructor(Tag, TAG_TABLES[name](), context) + + +# --- Tables of data --------------------------------------------------------------------- + + +def _data_with_some_source_info() -> pa.Table: + """Three data columns: one with a token, one with a list of tokens, one with none.""" + return pa.table( + { + "amplitude": pa.array([0.5, None, 2.5], pa.float32()), + "note": pa.array(["a", "b", None], pa.string()), + "trace": pa.array([[1.0], [], None], pa.list_(pa.float64())), + f"{SRC}amplitude": pa.array( + ["s::row_0::amplitude", "s::row_1::amplitude", None], pa.string() + ), + f"{SRC}trace": pa.array( + [["s::row_0::trace", "s::row_9::trace"], [], None], + pa.list_(pa.string()), + ), + }, + schema=pa.schema( + [ + pa.field("amplitude", pa.float32(), metadata={"unit": "mV"}), + pa.field("note", pa.string()), + pa.field("trace", pa.list_(pa.float64())), + pa.field(f"{SRC}amplitude", pa.string()), + pa.field(f"{SRC}trace", pa.list_(pa.string())), + ], + metadata={"origin": "a hand-built table"}, + ), + ) + + +def _data_with_meta_and_context() -> pa.Table: + """Data beside two meta columns, a source-info column and the data context.""" + key = contexts.get_default_context_key() + return pa.table( + { + "count": pa.array([1, 2], pa.int8()), + "label": pa.array(["x", "y"], pa.large_string()), + f"{META}pod_version": pa.array(["v1", "v1"], pa.string()), + f"{META}tries": pa.array([1, None], pa.int32()), + f"{SRC}count": pa.array(["s::row_0::count", "s::row_1::count"]), + f"{SRC}orphan": pa.array(["no such data column", "x"]), + CONTEXT: pa.array([key, key], pa.large_string()), + } + ) + + +def _data_of_types_normalization_changes() -> pa.Table: + """Columns a datagram stores in another type: ``null``, small strings, a struct.""" + return pa.table( + { + "unknown": pa.array([None, None], pa.null()), + "lists_of_unknown": pa.array([[None], []], pa.list_(pa.null())), + "pair": pa.array( + [{"name": "a", "size": 1}, None], + pa.struct( + [pa.field("name", pa.string()), pa.field("size", pa.int16())] + ), + ), + "raw": pa.array([b"\x00", b""], pa.binary()), + f"{SRC}unknown": pa.array([None, None], pa.null()), + }, + schema=pa.schema( + [ + pa.field("unknown", pa.null()), + pa.field("lists_of_unknown", pa.list_(pa.null())), + pa.field( + "pair", + pa.struct( + [pa.field("name", pa.string()), pa.field("size", pa.int16())] + ), + ), + pa.field("raw", pa.binary(), nullable=False), + pa.field(f"{SRC}unknown", pa.null()), + ] + ), + ) + + +DATA_TABLES: dict[str, Callable[[], pa.Table]] = { + "some_source_info": _data_with_some_source_info, + "some_source_info_reordered": lambda: _reordered(_data_with_some_source_info()), + "some_source_info_in_two_chunks": lambda: _in_two_chunks( + _data_with_some_source_info() + ), + "some_source_info_one_chunk_per_row": lambda: _one_chunk_per_row( + _data_with_some_source_info() + ), + "meta_and_context": _data_with_meta_and_context, + "meta_and_context_one_chunk_per_row": lambda: _one_chunk_per_row( + _data_with_meta_and_context() + ), + "meta_and_context_reordered": lambda: _reordered(_data_with_meta_and_context()), + "types_normalization_changes": _data_of_types_normalization_changes, + "no_rows": lambda: _data_with_some_source_info().slice(0, 0), +} + + +@pytest.mark.parametrize("name", list(DATA_TABLES)) +@pytest.mark.parametrize("given_context", [False, True]) +def test_data_rows_are_the_constructors(name: str, given_context: bool) -> None: + """Each data of ``Data.rows_of`` is ``Data(row)``, in every attribute and view.""" + context = contexts.resolve_context(None) if given_context else None + + _assert_rows_match_the_constructor(Data, DATA_TABLES[name](), context) + + +def test_rows_are_separate_objects() -> None: + """No two rows share a datagram or the mappings it holds.""" + tags = list(Tag.rows_of(_user_and_system_tags())) + datas = list(Data.rows_of(_data_with_meta_and_context())) + + for rows in (tags, datas): + assert len({id(row) for row in rows}) == len(rows) + assert tags[0]._system_tags is not tags[1]._system_tags + assert datas[0]._source_info is not datas[1]._source_info + assert datas[0]._meta is not datas[1]._meta + assert datas[0]._content_hash_cache is not datas[1]._content_hash_cache + + +def test_rows_are_built_as_they_are_asked_for() -> None: + """``rows_of`` is lazy: taking the first row builds no other.""" + with mock.patch.object( + Datagram, "_init_from_row", autospec=True, side_effect=Datagram._init_from_row + ) as built: + first = next(Tag.rows_of(_user_and_system_tags())) + + assert built.call_count == 1 + assert first["subject"] == "m1" + + +@pytest.mark.parametrize("kind", [Tag, Data]) +def test_a_table_with_rows_and_no_column_of_its_own_is_refused( + kind: type[Tag] | type[Data], +) -> None: + """Only meta or source-info columns: refused, as the constructor refuses the row.""" + table = pa.table( + {f"{META}note": ["a", "b"]} + if kind is Tag + else {f"{SRC}x": ["s::row_0::x", "s::row_1::x"]} + ) + + with pytest.raises(ValueError): + _ = kind(table.slice(0, 1)) + with pytest.raises(ValueError): + _ = list(kind.rows_of(table)) + + +# --- A stream's rows -------------------------------------------------------------------- + + +def _source_with_data_tags() -> Any: + """A source with two tags, one of them a data-tag, and three data columns.""" + return ArrowTableSource( + pa.table( + { + "subject": pa.array(["m1", "m1", "m2", "m2"], pa.string()), + "trial": pa.array([1, 2, 1, 2], pa.int16()), + "amplitude": pa.array([0.5, 1.5, None, 3.5], pa.float32()), + "note": pa.array(["a", None, "c", "d"], pa.string()), + "trace": pa.array( + [[1.0], [], None, [2.0, 3.0]], pa.list_(pa.float64()) + ), + } + ), + tag_columns=["subject", "trial"], + source_id="events", + ) + + +def _source_in_another_arrangement() -> Any: + """The same kind of source, tags last and in the other order, tag-only.""" + return ArrowTableSource( + pa.table( + { + "note": pa.array(["a", None, "c"], pa.large_string()), + "amplitude": pa.array([0.5, 1.5, None], pa.float64()), + "trial": pa.array([1, 2, 1], pa.int64()), + "subject": pa.array(["m1", "m1", "m2"], pa.large_string()), + } + ), + tag_columns=["trial", "subject"], + tag_only_columns=True, + record_id_columns=["subject", "trial"], + source_id="events", + ) + + +def _joined() -> Any: + """Two sources joined: two system-tag pairs, source info from both.""" + left = DictSource( + data=[{"k": i, "g": i % 2, "x": 10 * i} for i in range(4)], + tag_columns=["k", "g"], + tag_only_columns=True, + source_id="left", + ) + right = DictSource( + data=[{"k": i, "y": f"y{i}", "z": [i, i + 1]} for i in range(4)], + tag_columns=["k"], + tag_only_columns=True, + source_id="right", + ) + return left.join(right) + + +def _grouped() -> Any: + """A grouped stream: list-valued data and source info, folded system tags.""" + return _joined().group_by(["g"]) + + +def _raw_stream_without_tags() -> Any: + """A raw stream with no tag column, a meta column and a column with no values.""" + return ArrowTableStream( + pa.table( + { + "x": pa.array([1, 2, 3], pa.int32()), + "label": pa.array(["a", "b", None], pa.string()), + "unknown": pa.array([None, None, None], pa.null()), + f"{META}note": pa.array(["n1", None, "n3"], pa.string()), + } + ) + ) + + +def _raw_stream_in_two_chunks() -> Any: + """A raw stream whose table is held in two chunks, with given source info.""" + table = pa.concat_tables( + [ + pa.table({"k": ["a", "b"], "t": [1, 2], "x": [1.0, 2.0], "y": ["p", "q"]}), + pa.table({"k": ["c"], "t": [3], "x": [3.0], "y": ["r"]}), + ] + ) + return ArrowTableStream( + table, tag_columns=["k", "t"], source_info={"x": "given::token::x"} + ) + + +STREAMS: dict[str, Callable[[], Any]] = { + "source_with_data_tags": _source_with_data_tags, + "source_in_another_arrangement": _source_in_another_arrangement, + "joined": _joined, + "grouped": _grouped, + "raw_stream_without_tags": _raw_stream_without_tags, + "raw_stream_in_two_chunks": _raw_stream_in_two_chunks, +} + + +def _rows_through_the_constructors(stream: Any) -> list[tuple[Tag, Data]]: + """The rows of ``stream`` as ``iter_data`` built them before ITL-1348. + + Each row's tag and data are built by the public constructors from one-row tables + of the stream's own table: its tags and system tags, and its data columns with + their source info. + """ + table = stream.as_table(columns={"system_tags": True, "source": True, "meta": True}) + tag_keys, data_keys = stream.keys(columns={"system_tags": True, "meta": True}) + source_keys = [c for c in table.column_names if c.startswith(SRC)] + context = stream.data_context + rows: list[tuple[Tag, Data]] = [] + for i in range(table.num_rows): + row = table.slice(i, 1) + tag = ( + Tag(row.select(list(tag_keys)), data_context=context) + if tag_keys + else Tag({}) + ) + data = Data(row.select([*data_keys, *source_keys]), data_context=context) + rows.append((tag, data)) + return rows + + +@pytest.mark.parametrize("name", list(STREAMS)) +def test_a_streams_rows_are_the_constructors(name: str) -> None: + """``iter_data`` yields, for every row, the tag and data the constructors build.""" + stream = STREAMS[name]() + expected = _rows_through_the_constructors(stream) + + rows = list(stream.iter_data()) + + assert len(rows) == len(expected) > 0 + for (tag, data), (expected_tag, expected_data) in zip(rows, expected): + if stream.keys(columns={"system_tags": True})[0]: + _assert_same_datagram(tag, expected_tag) + else: + # No tag column: the empty tag, which has no table to compare. + assert tag.as_dict(columns=EVERYTHING) == expected_tag.as_dict( + columns=EVERYTHING + ) + assert tag.system_tags() == {} + _assert_same_datagram(data, expected_data) + + +@pytest.mark.parametrize( + "name", [name for name in STREAMS if name != "raw_stream_without_tags"] +) +def test_a_streams_rows_rebuild_its_table(name: str) -> None: + """The rows' own tables, put side by side, are the stream's table. + + Not for the raw stream with a meta column: a row's data holds that column as meta, + the stream as a column like any other. + """ + stream = STREAMS[name]() + columns = {"system_tags": True, "source": True} + table = stream.as_table(columns=columns) + + rebuilt = pa.concat_tables( + [ + arrow_utils.hstack_tables( + tag.as_table(columns=columns), + data.as_table(columns=columns).drop_columns( + [k for k in data.keys() if k in tag.keys()] + ), + ) + for tag, data in stream.iter_data() + ] + ) + + assert sorted(rebuilt.column_names) == sorted(table.column_names) + assert rebuilt.select(table.column_names).to_pylist() == table.to_pylist() + + +# --- The cost: nothing is prepared per row --------------------------------------------- + + +def _many_rows(n: int, one_chunk_per_row: bool) -> Any: + """A stream of ``n`` rows over a table of one chunk, or of one chunk per row.""" + table = pa.table( + { + "subject": [f"m{i % 3}" for i in range(n)], + "trial": list(range(n)), + "amplitude": [0.5 * i for i in range(n)], + "note": [f"n{i}" for i in range(n)], + } + ) + return ArrowTableSource( + _one_chunk_per_row(table) if one_chunk_per_row else table, + tag_columns=["subject", "trial"], + tag_only_columns=True, + source_id="events", + ) + + +@pytest.mark.parametrize("one_chunk_per_row", [False, True]) +@pytest.mark.parametrize( + "prepared_per_table", + ["normalize_schema_to_large_types", "prepare_prefixed_columns"], +) +def test_iterating_rows_prepares_nothing_per_row( + prepared_per_table: str, one_chunk_per_row: bool +) -> None: + """Ten times the rows cost not one more call of what is done once per table. + + Also for a table of one chunk per row, which is what a table built from rows (a + job node's output) is. + """ + + def calls(n: int) -> int: + stream = _many_rows(n, one_chunk_per_row) + _ = stream.as_table() + with mock.patch.object( + arrow_utils, + prepared_per_table, + side_effect=getattr(arrow_utils, prepared_per_table), + ) as counted: + assert len(list(stream.iter_data())) == n + return counted.call_count + + assert calls(50) == calls(5) + + +def test_rows_of_a_table_built_from_rows_are_the_constructors() -> None: + """A stream rebuilt from its own rows (one chunk per row) yields the same rows.""" + stream = _joined() + table = pa.concat_tables( + [ + arrow_utils.hstack_tables( + tag.as_table(columns={"system_tags": True}), + data.as_table(columns={"source": True}), + ) + for tag, data in stream.iter_data() + ] + ) + assert table.column("x").num_chunks == table.num_rows > 1 + rebuilt: Any = ArrowTableStream(table, tag_columns=["k", "g"]) + + rows = list(rebuilt.iter_data()) + + for (tag, data), (expected_tag, expected_data) in zip( + rows, _rows_through_the_constructors(rebuilt), strict=True + ): + _assert_same_datagram(tag, expected_tag) + _assert_same_datagram(data, expected_data) + + +def test_iterating_rows_twice_gives_the_same_objects(tmp_path: Path) -> None: + """A stream keeps the rows it built: a second pass yields those objects.""" + stream = _source_with_data_tags() + + first = list(stream.iter_data()) + second = list(stream.iter_data()) + + assert all(a[0] is b[0] and a[1] is b[1] for a, b in zip(first, second)) From 9f7f1c117e0b52d29ff4e7f1775d186a199f1d40 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 21 Nov 2026 22:52:54 -0800 Subject: [PATCH 02/86] perf(pipeline): count a held node's rows from what it holds, not by building them (ITL-1351) (#476) * perf(pipeline): count a held node's rows from what it holds, not by building them (ITL-1351) plan_run counted every held node's rows for the run summary with sum(1 for _ in node.iter_data()). For an operator node that builds a (Tag, Data) pair per row of its output only to count it: in a run where every node is held, nearly all the time (5.6 of 5.7 s on a workshop-scale job). RunHoldingNode gains held_row_count(), the count iter_data would give, from what each kind holds: an operator node its current output's table row count, a function node its run's inputs that have an output (from the entry counts it keeps), a side-effect node its held rows. plan_run uses it. Counts and summaries are unchanged; no hash, stored layout or output changes. The tests compare the new counts with iterating the rows for every held node kind (operator, function, side effect), after a full and a load-only run, on both orchestrators, and check that a fully held run builds no Data (which fails on the old count). Co-Authored-By: Claude Opus 5.5 * test(pipeline): fill the held rows on the orchestrator under test (ITL-1351) CodeRabbit on #476: the preparation runs used the default (sync) orchestrator, so the async case never counted rows the async orchestrator had produced. Both preparation runs now use the orchestrator the case is about. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Edgar Y. Walker <> Co-authored-by: Claude Opus 5.5 --- changelog.d/ITL-1351.md | 9 ++ src/orcapod/core/nodes/function_node.py | 33 ++++- src/orcapod/core/nodes/operator_node.py | 12 ++ src/orcapod/core/nodes/staleness.py | 13 ++ src/orcapod/pipeline/node_run.py | 4 +- src/orcapod/side_effects.py | 8 ++ tests/test_pipeline/test_held_row_count.py | 154 +++++++++++++++++++++ 7 files changed, 231 insertions(+), 2 deletions(-) create mode 100644 changelog.d/ITL-1351.md create mode 100644 tests/test_pipeline/test_held_row_count.py diff --git a/changelog.d/ITL-1351.md b/changelog.d/ITL-1351.md new file mode 100644 index 000000000..a003ecc38 --- /dev/null +++ b/changelog.d/ITL-1351.md @@ -0,0 +1,9 @@ +### Changed + +- A run counts the rows of the nodes it holds without building them (ITL-1351). The run + summary's count of a held node's rows (`plan_run`) iterated the node's rows, which built + a `(Tag, Data)` pair per row of an operator's output only to count it; a run in which + every node holds a current run spent most of its time there. Each kind of job node that + holds a run now counts what it holds (`held_row_count`: an operator node its output + table's row count, a function node its run's inputs with an output, a side-effect node + its held rows), with the same counts and summaries as before. diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 117eb50b9..adccd23b4 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -3955,6 +3955,38 @@ def iter_data(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: changed since its run) yields nothing (ITL-1095); ``as_source()`` reads every row stored for it. + Raises: + RuntimeError: If ``load_status`` is UNAVAILABLE. + """ + self._prepare_held_read() + yield from self._held_pairs() + + def held_row_count(self) -> int: + """The number of rows ``iter_data`` yields now, counted from the run's inputs. + + The same count as ``iter_data`` (one row per input of the run that has an + output), without going through the rows (ITL-1351). + + Returns: + The row count. + + Raises: + RuntimeError: If ``load_status`` is UNAVAILABLE. + """ + self._prepare_held_read() + counts = self._run_entry_counts + if counts is None: + return 0 + return sum( + counts.get(entry_id, 0) + for entry_id, (_, data) in self._cached_output_datas.items() + if data is not None + ) + + def _prepare_held_read(self) -> None: + """What every read of the held rows does first: refuse a node with no database + to read, and drop rows that went stale. + Raises: RuntimeError: If ``load_status`` is UNAVAILABLE. """ @@ -3966,7 +3998,6 @@ def iter_data(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: # A CACHE_ONLY node has no live input to be stale against. if status != LoadStatus.CACHE_ONLY and self.is_stale: self.clear_cache() - yield from self._held_pairs() def run(self, *, load_only: bool = False) -> StreamView: """Run the node as a job run would, and return a ``StreamView`` of its rows. diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index 12a19d954..2f725683a 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -1927,6 +1927,18 @@ def _current_output(self) -> StreamProtocol | None: return None return self._cached_output_stream + def held_row_count(self) -> int: + """The number of rows of the node's current run, from its output table. + + The same count as ``iter_data`` (0 when the node holds no run), without building + a ``(Tag, Data)`` pair per row (ITL-1351). + + Returns: + The row count. + """ + current = self._current_output() + return 0 if current is None else current.as_table().num_rows + def iter_data(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: """Return an iterator over the (tag, data) rows of the node's current run. diff --git a/src/orcapod/core/nodes/staleness.py b/src/orcapod/core/nodes/staleness.py index 8ae8162a8..b7a140a61 100644 --- a/src/orcapod/core/nodes/staleness.py +++ b/src/orcapod/core/nodes/staleness.py @@ -73,6 +73,19 @@ def _holds_run(self, *, load_only: bool) -> bool: """Whether the node holds the rows of a completed run good for such a run.""" raise NotImplementedError + def held_row_count(self) -> int: + """The number of rows ``iter_data`` yields now, counted without building them. + + A run's summary counts the rows of every node it holds (``plan_run``). + Iterating them would build a ``(Tag, Data)`` pair per row of an operator's + output (ITL-1351); each kind counts what it holds instead, with the same + result as ``sum(1 for _ in node.iter_data())``. + + Returns: + The row count. + """ + raise NotImplementedError + def _job_upstreams(node: Any) -> list[RunHoldingNode]: """The direct upstreams of ``node`` that are job nodes holding run rows.""" diff --git a/src/orcapod/pipeline/node_run.py b/src/orcapod/pipeline/node_run.py index 4252ce854..c1a031c90 100644 --- a/src/orcapod/pipeline/node_run.py +++ b/src/orcapod/pipeline/node_run.py @@ -343,7 +343,9 @@ def is_source(node: Any) -> bool: for node in included if not any(node is r for r in to_run) and not is_source(node) } - held_counts = {node: sum(1 for _ in node.iter_data()) for node in current} + # Counted from what each node holds: iterating an operator's rows would build a + # (Tag, Data) pair per row only to count them (ITL-1351). + held_counts = {node: node.held_row_count() for node in current} return RunPlan(dag, held_rows, to_run, held_counts) diff --git a/src/orcapod/side_effects.py b/src/orcapod/side_effects.py index 20087e938..9cb769522 100644 --- a/src/orcapod/side_effects.py +++ b/src/orcapod/side_effects.py @@ -1335,6 +1335,14 @@ def iter_data(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: """ yield from self._current_rows() or () + def held_row_count(self) -> int: + """The number of rows the last run of this node passed on (``iter_data``'s count). + + Returns: + The row count; 0 with no rows from a completed run, as ``iter_data``. + """ + return len(self._current_rows() or ()) + @override def head( self, diff --git a/tests/test_pipeline/test_held_row_count.py b/tests/test_pipeline/test_held_row_count.py new file mode 100644 index 000000000..5c43bd3e1 --- /dev/null +++ b/tests/test_pipeline/test_held_row_count.py @@ -0,0 +1,154 @@ +"""A run counts the rows of the nodes it holds without building them (ITL-1351). + +``plan_run`` gives the run summary every held node's row count. It used to iterate the +node's rows, which builds a ``(Tag, Data)`` pair per row of an operator's output only to +count it. Each kind of held node now counts what it holds (``held_row_count``); the +counts, and so the summaries, must be those of iterating the rows, for every kind of node +that holds a run (operator, function, side effect), after a full and a load-only run, on +the sync and the async orchestrator. +""" + +from __future__ import annotations + +from typing import Any + +import pyarrow as pa +import pytest + +import orcapod.pipeline.job as job_module +from orcapod import PipelineJob, function_pod +from orcapod.core.datagrams import tag_data +from orcapod.core.nodes import FunctionJobNode, OperatorJobNode +from orcapod.databases import InMemoryArrowDatabase +from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator +from orcapod.side_effects import SideEffectJobNode, SideEffectPod, side_effect_pod +from orcapod.sources import ArrowTableSource + +ORCHESTRATORS = {"sync": SyncPipelineOrchestrator, "async": AsyncPipelineOrchestrator} +# The kinds of job node that hold a run (``RunHoldingNode``). +HOLDING = (OperatorJobNode, FunctionJobNode, SideEffectJobNode) + + +@function_pod(output_keys="y") +def scaled(x: int, w: float) -> float: + """Return ``x * w``.""" + return x * w + + +@function_pod(output_keys="total") +def summed(x: list[int]) -> int: + """Return the sum of a group's values.""" + return sum(x) + + +def _note(x: int, ctx: Any) -> None: # pyright: ignore[reportExplicitAny] # the invocation context + """A side effect that does nothing.""" + + +def _source() -> ArrowTableSource: + """Two tags (``g``, ``k``) and two data columns (``x``, ``w``, one null ``w``).""" + table = pa.table( + { + "k": pa.array([f"r{i}" for i in range(8)], pa.large_string()), + "x": pa.array(range(8), pa.int64()), + "g": pa.array([i % 3 for i in range(8)], pa.int64()), + "w": pa.array([0.5, 1.5, None, 2.5, 3.5, 4.5, 5.5, 6.5], pa.float64()), + }, + schema=pa.schema( + [ + pa.field("k", pa.large_string(), nullable=False), + pa.field("x", pa.int64(), nullable=False), + pa.field("g", pa.int64(), nullable=False), + pa.field("w", pa.float64()), + ] + ), + ) + return ArrowTableSource( + table, tag_columns=["g", "k"], tag_only_columns=True, source_id="held" + ) + + +def _job(db: Any) -> PipelineJob: # pyright: ignore[reportExplicitAny] # a database + """Operators (drop_nulls, select, group_by), function pods and a side effect.""" + tap = side_effect_pod(_note) + assert isinstance(tap, SideEffectPod) + job = PipelineJob(name="held", database=db) + with job: + kept: Any = _source().drop_nulls(["w"], label="kept") # pyright: ignore[reportExplicitAny] + scaled.pod(kept, label="scaled") + tap.process(kept.select_data_columns(["x"], label="xs"), label="tapped") + summed.pod( + kept.select_data_columns(["x"]).group_by("g", label="grouped"), label="sums" + ) + return job + + +def _iterated(job: PipelineJob) -> dict[str, int]: + """Every held node's row count by iterating its rows (the old count).""" + return { + label: sum(1 for _ in node.iter_data()) + for label, node in job.nodes.items() + if isinstance(node, HOLDING) + } + + +@pytest.mark.parametrize("orchestrator", sorted(ORCHESTRATORS)) +@pytest.mark.parametrize("load_only", [False, True], ids=["full", "load_only"]) +def test_a_held_run_counts_every_held_node_as_its_rows_and_builds_none( + orchestrator: str, load_only: bool, monkeypatch: pytest.MonkeyPatch +) -> None: + db = InMemoryArrowDatabase() + # The held rows come from runs on the orchestrator under test (CodeRabbit, #476). + _job(db).run(orchestrator=ORCHESTRATORS[orchestrator]()) + job = _job(db) + job.run(orchestrator=ORCHESTRATORS[orchestrator](), load_only=load_only) + + plans: list[Any] = [] # pyright: ignore[reportExplicitAny] # RunPlan + plan_run = job_module.plan_run + + def spying(*args: Any, **kwargs: Any) -> Any: # pyright: ignore[reportExplicitAny] + plans.append(plan_run(*args, **kwargs)) + return plans[-1] + + built: list[int] = [] + data_init = tag_data.Data.__init__ + + def counting(self: Any, *args: Any, **kwargs: Any) -> None: # pyright: ignore[reportExplicitAny] + built.append(1) + data_init(self, *args, **kwargs) + + monkeypatch.setattr(job_module, "plan_run", spying) + monkeypatch.setattr(tag_data.Data, "__init__", counting) + summary = job.run(orchestrator=ORCHESTRATORS[orchestrator](), load_only=load_only) + monkeypatch.undo() + + # Every node held: nothing ran, and counting the held rows built no datagram. + assert repr(summary).splitlines()[0].endswith("every node holds a current run.") + assert built == [] + (plan,) = plans + counts = {node.label: count for node, count in plan.held_counts.items()} + expected = _iterated(job) + assert counts == expected + # Two equal selects over one input are one node, so its label is the default one. + assert {"kept", "scaled", "tapped", "grouped", "sums"} <= set(counts) + assert len(counts) == len(expected) == 6 + assert expected["kept"] == 7 and expected["grouped"] == 3 + for label in ("scaled", "sums"): + assert summary.nodes[label].held == expected[label] + + +def test_a_node_counts_its_rows_as_iterating_them_does_before_and_after_a_run() -> None: + job = _job(InMemoryArrowDatabase()) + held = [n for n in job.nodes.values() if isinstance(n, HOLDING)] + assert {type(n).__name__ for n in held} == { + "OperatorJobNode", + "FunctionJobNode", + "SideEffectJobNode", + } + assert all(n.held_row_count() == 0 == sum(1 for _ in n.iter_data()) for n in held) + job.run() + for node in held: + assert node.held_row_count() == sum(1 for _ in node.iter_data()), node.label + for node in held: + node.clear_cache() + assert node.held_row_count() == 0 == sum(1 for _ in node.iter_data()) From 0e15d0dbe38c7bd15c36c55d8a9964857d836902 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 21 Nov 2026 23:12:07 -0800 Subject: [PATCH 03/86] perf: import modules that import orcapod loads directly, not through LazyModule (ITL-1349) (#477) Every attribute read through a LazyModule is a __getattr__ call: 42.9 million in one warm workshop-scale job.run(), 88 per row of a source's iter_data(). pyarrow, pyarrow.compute, pyarrow.ipc, polars, numpy, pandas and asyncio are loaded by `import orcapod` anyway, so they are now imported directly and import time does not change. LazyModule stays for modules a plain `import orcapod` never loads (networkx, deltalake, pyarrow.fs, pyarrow.dataset, git) and the optional extras (psycopg, ray, spiral). Bindings no code read are dropped; polars._typing is typing-only. tests/test_utils/test_lazy_module_use.py keeps it that way; CLAUDE.md and .zed/rules state the rule. Co-authored-by: Edgar Y. Walker <> Co-authored-by: Claude Opus 5.5 --- .zed/rules | 10 ++- CLAUDE.md | 13 +++- changelog.d/ITL-1349.md | 3 + src/orcapod/contexts/stored.py | 13 +--- src/orcapod/core/data_function.py | 7 +- src/orcapod/core/data_tags.py | 8 +- src/orcapod/core/datagrams/datagram.py | 9 +-- src/orcapod/core/datagrams/tag_data.py | 7 +- src/orcapod/core/function_pod.py | 8 +- src/orcapod/core/nodes/function_node.py | 13 +--- src/orcapod/core/nodes/operator_node.py | 10 +-- src/orcapod/core/nodes/source_node.py | 7 +- src/orcapod/core/operators/add_tags.py | 7 +- src/orcapod/core/operators/arrow_keys.py | 17 ++--- src/orcapod/core/operators/batch.py | 13 +--- .../core/operators/column_selection.py | 8 +- src/orcapod/core/operators/drop_nulls.py | 13 +--- src/orcapod/core/operators/filters.py | 10 +-- src/orcapod/core/operators/group_by.py | 17 ++--- src/orcapod/core/operators/index.py | 10 +-- src/orcapod/core/operators/join.py | 13 +--- src/orcapod/core/operators/mappers.py | 8 +- src/orcapod/core/operators/match_keys.py | 9 +-- src/orcapod/core/operators/merge_join.py | 13 +--- src/orcapod/core/operators/meta_columns.py | 9 +-- src/orcapod/core/operators/pick.py | 10 +-- src/orcapod/core/operators/rejoin.py | 12 +-- src/orcapod/core/operators/semijoin.py | 15 +--- .../core/operators/static_output_pod.py | 7 +- src/orcapod/core/result_cache.py | 7 +- src/orcapod/core/sources/cached_source.py | 5 +- src/orcapod/core/sources/csv_source.py | 10 +-- src/orcapod/core/sources/data_frame_source.py | 9 +-- src/orcapod/core/sources/db_table_source.py | 6 +- .../core/sources/delta_table_source.py | 3 +- src/orcapod/core/sources/derived_source.py | 7 +- src/orcapod/core/sources/dict_source.py | 10 +-- src/orcapod/core/sources/polling_source.py | 9 +-- src/orcapod/core/sources/reload.py | 20 ++--- .../core/sources/spiraldb_table_source.py | 8 +- src/orcapod/core/sources/stream_builder.py | 7 +- .../core/streams/arrow_table_stream.py | 11 +-- src/orcapod/core/streams/base.py | 17 ++--- src/orcapod/core/streams/view.py | 15 +--- src/orcapod/databases/_row_index.py | 12 +-- .../databases/connector_arrow_database.py | 13 +--- src/orcapod/databases/delta_arrow_types.py | 10 +-- src/orcapod/databases/delta_lake_databases.py | 10 +-- src/orcapod/databases/delta_statistics.py | 9 +-- src/orcapod/databases/in_memory_databases.py | 9 +-- src/orcapod/databases/noop_database.py | 9 +-- src/orcapod/databases/postgresql_connector.py | 4 +- src/orcapod/databases/spiraldb_connector.py | 4 +- src/orcapod/databases/spiraldb_nullability.py | 10 +-- src/orcapod/databases/sqlite_connector.py | 11 +-- .../execution_engines/ray_execution_engine.py | 8 +- src/orcapod/hashing/arrow_utils.py | 9 +-- .../hashing/semantic_hashing/polars_expr.py | 10 +-- src/orcapod/hashing/visitors.py | 6 +- src/orcapod/logical_types/canonical_form.py | 10 +-- src/orcapod/logical_types/ignore_list.py | 10 +-- .../list_logical_type_factory.py | 9 +-- src/orcapod/logical_types/registry.py | 13 +--- .../logical_types/user_class_logical_type.py | 10 +-- .../semantic_types/precomputed_converters.py | 8 +- .../semantic_types/universal_converter.py | 6 +- src/orcapod/side_effects.py | 5 +- src/orcapod/types/__init__.py | 7 +- src/orcapod/utils/arrow_utils.py | 6 +- src/orcapod/utils/polars_data_utils.py | 9 +-- src/orcapod/utils/schema_utils.py | 14 +--- tests/test_utils/test_lazy_module_use.py | 74 +++++++++++++++++++ 72 files changed, 274 insertions(+), 484 deletions(-) create mode 100644 changelog.d/ITL-1349.md create mode 100644 tests/test_utils/test_lazy_module_use.py diff --git a/.zed/rules b/.zed/rules index 74bb0a724..0ca1db43b 100644 --- a/.zed/rules +++ b/.zed/rules @@ -758,7 +758,7 @@ src/orcapod/ arrow_data_utils.py — System tag manipulation, source info, column helpers arrow_utils.py — Arrow table utilities schema_utils.py — Schema extraction, union, intersection, compatibility - lazy_module.py — LazyModule for deferred heavy imports + lazy_module.py — LazyModule for modules `import orcapod` does not load tests/ test_core/ @@ -1078,8 +1078,12 @@ generation of hashing; rows of the current data context are the current entries. ### Key patterns -- LazyModule("pyarrow") — deferred import for heavy deps. Used in - if TYPE_CHECKING: / else: blocks. +- Imports: a module that `import orcapod` loads anyway (pyarrow, pyarrow.compute, polars, + numpy, pandas, asyncio) is imported directly (ITL-1349: every LazyModule attribute read is + a __getattr__ call, 42.9 million in one warm job.run()). LazyModule (if TYPE_CHECKING: / + else: blocks) only for a module `import orcapod` never loads (networkx, deltalake, + pyarrow.fs, pyarrow.dataset, git) and the optional extras (psycopg, ray, spiral); + tests/test_utils/test_lazy_module_use.py checks it. - Argument symmetry — operators return frozenset (commutative) or tuple (ordered). - StaticOutputPod.process() → DynamicPodStream — wraps static_process() with staleness detection and automatic recomputation. diff --git a/CLAUDE.md b/CLAUDE.md index a60459f2e..18c5d6f25 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -770,7 +770,7 @@ src/orcapod/ ├── arrow_data_utils.py # System tag manipulation, source info, column helpers ├── arrow_utils.py # Arrow table utilities ├── schema_utils.py # Schema extraction, union, intersection, compatibility - └── lazy_module.py # LazyModule for deferred heavy imports + └── lazy_module.py # LazyModule for modules `import orcapod` does not load tests/ ├── test_core/ @@ -1120,8 +1120,15 @@ and `as_table()` methods. `all_info=True` sets everything to True. ### Key patterns -- **`LazyModule("pyarrow")`** — deferred import for heavy deps (pyarrow, polars). Used in - `if TYPE_CHECKING:` / `else:` blocks at module level. +- **Imports: direct, or `LazyModule` only for a module `import orcapod` does not load** + (developer, November 22, 2026, ITL-1349). Every attribute read through a `LazyModule` is + a `__getattr__` call (42.9 million in one warm workshop-scale `job.run()`), so a module + that `import orcapod` loads anyway (pyarrow, `pyarrow.compute`, polars, numpy, pandas, + asyncio) is imported directly: `import pyarrow as pa`. `LazyModule` (in an + `if TYPE_CHECKING:` / `else:` block at module level) stays only for a module a plain + `import orcapod` never loads (networkx, deltalake, `pyarrow.fs`, `pyarrow.dataset`, git) + and for the optional extras (psycopg, ray, spiral). + `tests/test_utils/test_lazy_module_use.py` checks it. - **Argument symmetry** — each operator declares `argument_symmetry(streams)` returning `frozenset` (commutative) or `tuple` (ordered). Determines how upstream hashes combine. - **`StaticOutputPod.process()` → `DynamicPodStream`** — wraps `static_process()` output diff --git a/changelog.d/ITL-1349.md b/changelog.d/ITL-1349.md new file mode 100644 index 000000000..4badc89a6 --- /dev/null +++ b/changelog.d/ITL-1349.md @@ -0,0 +1,3 @@ +### Changed + +- **Less overhead per row.** Orcapod imports pyarrow, `pyarrow.compute`, polars, numpy and pandas directly instead of through a lazy module wrapper, which cost a Python call on every attribute access (millions in one job run). `import orcapod` already loaded these modules, so import time does not change. Modules that `import orcapod` does not load (networkx, deltalake, the optional database clients) stay deferred. Results, hashes and stored tables are unchanged. (ITL-1349) diff --git a/src/orcapod/contexts/stored.py b/src/orcapod/contexts/stored.py index 605c04c92..353c90121 100644 --- a/src/orcapod/contexts/stored.py +++ b/src/orcapod/contexts/stored.py @@ -32,7 +32,10 @@ import warnings from collections.abc import Collection from dataclasses import dataclass, field -from typing import TYPE_CHECKING, Any, NamedTuple, Protocol, cast +from typing import Any, NamedTuple, Protocol, cast + +import pyarrow as pa +import pyarrow.compute as pc from orcapod.errors import ( InputValidationError, @@ -49,14 +52,6 @@ TRACKING_DB_SCHEMA_VERSION, constants, ) -from orcapod.utils.lazy_module import LazyModule - -if TYPE_CHECKING: - import pyarrow as pa - import pyarrow.compute as pc -else: - pa = LazyModule("pyarrow") - pc = LazyModule("pyarrow.compute") logger = logging.getLogger(__name__) diff --git a/src/orcapod/core/data_function.py b/src/orcapod/core/data_function.py index 6fc71c3dc..fc124c478 100644 --- a/src/orcapod/core/data_function.py +++ b/src/orcapod/core/data_function.py @@ -13,6 +13,7 @@ import typing from typing import TYPE_CHECKING, Any, ClassVar, Generic, Literal, TypeVar +import pyarrow as pa from uuid_utils import uuid7 from orcapod.config import OrcapodConfig @@ -46,7 +47,6 @@ from orcapod.utils import schema_utils from orcapod.utils.canonical_type_names import stabilize_type_names from orcapod.utils.git_utils import get_git_info_for_python_object -from orcapod.utils.lazy_module import LazyModule from orcapod.utils.tensor_conversions import describe, tensor_conversions, warn_once from orcapod.protocols.observability_protocols import DataExecutionLoggerProtocol @@ -55,11 +55,6 @@ from orcapod.logical_types.protocols import ( TypeConverterProtocol as LogicalTypeConverterProtocol, ) - import pyarrow as pa - import pyarrow.compute as pc -else: - pa = LazyModule("pyarrow") - pc = LazyModule("pyarrow.compute") module_logger = logging.getLogger(__name__) diff --git a/src/orcapod/core/data_tags.py b/src/orcapod/core/data_tags.py index 7249f1c01..7435790bb 100644 --- a/src/orcapod/core/data_tags.py +++ b/src/orcapod/core/data_tags.py @@ -35,17 +35,13 @@ from contextvars import ContextVar from typing import TYPE_CHECKING, Any, Literal +import pyarrow as pa + from orcapod.errors import InputValidationError from orcapod.types import Schema, SourceInfoValue -from orcapod.utils.lazy_module import LazyModule - if TYPE_CHECKING: - import pyarrow as pa - from orcapod.protocols.core_protocols import DataProtocol, TagProtocol -else: - pa = LazyModule("pyarrow") # Diagnostic emitted when a structural operator materializes a data-tag (section 7.4). # ``"warn"`` emits a ``DataTagMaterializationWarning``; ``"silent"`` emits nothing. The diff --git a/src/orcapod/core/datagrams/datagram.py b/src/orcapod/core/datagrams/datagram.py index 2ae640dc3..23acd12ac 100644 --- a/src/orcapod/core/datagrams/datagram.py +++ b/src/orcapod/core/datagrams/datagram.py @@ -24,8 +24,9 @@ import logging import uuid from collections.abc import Collection, Iterator, Mapping -from typing import TYPE_CHECKING, Any, Self, cast +from typing import Any, Self, cast +import pyarrow as pa from uuid_utils import uuid7 from orcapod.hashing.orcapod_table import OrcapodTable @@ -39,12 +40,6 @@ from orcapod.system_constants import constants from orcapod.types import ColumnConfig, DataType, DataValue, Schema, SchemaLike from orcapod.utils import arrow_utils -from orcapod.utils.lazy_module import LazyModule - -if TYPE_CHECKING: - import pyarrow as pa -else: - pa = LazyModule("pyarrow") logger = logging.getLogger(__name__) diff --git a/src/orcapod/core/datagrams/tag_data.py b/src/orcapod/core/datagrams/tag_data.py index 808ae8b15..8bdf566bd 100644 --- a/src/orcapod/core/datagrams/tag_data.py +++ b/src/orcapod/core/datagrams/tag_data.py @@ -21,6 +21,8 @@ from collections.abc import Iterator, Mapping, Sequence from typing import TYPE_CHECKING, Any, Self +import pyarrow as pa + from orcapod import contexts from orcapod.core.datagrams.datagram import Datagram, context_key_field from orcapod.semantic_types import infer_python_schema_from_pylist_data @@ -35,14 +37,9 @@ SourceInfoValue, ) from orcapod.utils import arrow_utils -from orcapod.utils.lazy_module import LazyModule if TYPE_CHECKING: - import pyarrow as pa - from orcapod.protocols.core_protocols import DataProtocol -else: - pa = LazyModule("pyarrow") logger = logging.getLogger(__name__) diff --git a/src/orcapod/core/function_pod.py b/src/orcapod/core/function_pod.py index 039b45b06..8a24c3b49 100644 --- a/src/orcapod/core/function_pod.py +++ b/src/orcapod/core/function_pod.py @@ -9,6 +9,8 @@ from functools import update_wrapper, wraps from typing import TYPE_CHECKING, Any, Literal, Protocol, cast +import pyarrow as pa + from orcapod import contexts from orcapod.channels import ReadableChannel, WritableChannel from orcapod.config import OrcapodConfig @@ -59,7 +61,6 @@ resolve_concurrency, ) from orcapod.utils import arrow_utils, schema_utils -from orcapod.utils.lazy_module import LazyModule from datetime import datetime, timezone @@ -75,12 +76,7 @@ logger = logging.getLogger(__name__) if TYPE_CHECKING: - import polars as pl - import pyarrow as pa from orcapod.protocols.observability_protocols import ExecutionObserverProtocol -else: - pa = LazyModule("pyarrow") - pl = LazyModule("polars") def _executor_supports_concurrent( diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index adccd23b4..6b8ee6a3a 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -25,7 +25,10 @@ from abc import abstractmethod from collections import Counter from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence -from typing import TYPE_CHECKING, Any, Literal, NamedTuple, cast +from typing import Any, Literal, NamedTuple, cast + +import polars as pl +import pyarrow as pa from orcapod import contexts from orcapod.core.function_pod import ( @@ -116,17 +119,9 @@ Schema, ) from orcapod.utils import arrow_utils, schema_utils -from orcapod.utils.lazy_module import LazyModule logger = logging.getLogger(__name__) -if TYPE_CHECKING: - import polars as pl - import pyarrow as pa -else: - pa = LazyModule("pyarrow") - pl = LazyModule("polars") - # Pipeline entry ID column name used when fetching records from the pipeline # database. Always present in the table returned by _fetch_joined_records. _PIPELINE_ENTRY_ID_COL = "__pipeline_entry_id" diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index 2f725683a..d66d479c6 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -24,6 +24,9 @@ from collections.abc import Collection, Iterator, Mapping, Sequence from typing import TYPE_CHECKING, Any, Literal, cast +import pyarrow as pa +import pyarrow.compute as pc + from orcapod import contexts from orcapod.core.data_tags import ( mark_data_tags, @@ -82,18 +85,11 @@ from orcapod.system_constants import OPERATOR_DB_SCHEMA_VERSION, constants from orcapod.types import CacheMode, ColumnConfig, ContentHash, Schema from orcapod.utils import arrow_utils -from orcapod.utils.lazy_module import LazyModule logger = logging.getLogger(__name__) if TYPE_CHECKING: - import pyarrow as pa - import pyarrow.compute as pc - from orcapod.protocols.observability_protocols import ExecutionObserverProtocol -else: - pa = LazyModule("pyarrow") - pc = LazyModule("pyarrow.compute") async def _discard(channel: ReadableChannel[Any]) -> None: diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index 8c8528b05..b522c117f 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -17,6 +17,8 @@ from datetime import datetime from typing import TYPE_CHECKING, Any +import pyarrow as pa + from orcapod import contexts from orcapod.config import OrcapodConfig from orcapod.core.base import TraceableBase @@ -46,7 +48,6 @@ from orcapod.types import ColumnConfig, ContentHash, Schema from orcapod.utils import arrow_utils from orcapod.utils.arrow_utils import system_tag_column_names -from orcapod.utils.lazy_module import LazyModule from orcapod.utils.schema_utils import ( arrow_schema_identity, compute_source_schema_hash, @@ -54,13 +55,9 @@ ) if TYPE_CHECKING: - import pyarrow as pa - from orcapod.channels import WritableChannel from orcapod.protocols.core_protocols import StreamProtocol from orcapod.protocols.observability_protocols import ExecutionObserverProtocol -else: - pa = LazyModule("pyarrow") logger = logging.getLogger(__name__) diff --git a/src/orcapod/core/operators/add_tags.py b/src/orcapod/core/operators/add_tags.py index 7b1ae1801..befd84f56 100644 --- a/src/orcapod/core/operators/add_tags.py +++ b/src/orcapod/core/operators/add_tags.py @@ -7,6 +7,8 @@ from types import MappingProxyType from typing import TYPE_CHECKING, Any, ClassVar +import pyarrow as pa + from orcapod.channels import ReadableChannel, WritableChannel from orcapod.core.data_tags import stream_data_tags from orcapod.core.datagrams import Tag @@ -19,14 +21,9 @@ from orcapod.system_constants import constants from orcapod.types import ColumnConfig, ContentHash, Schema from orcapod.utils import schema_utils -from orcapod.utils.lazy_module import LazyModule if TYPE_CHECKING: - import pyarrow as pa - from orcapod.protocols.semantic_types_protocols import TypeConverterProtocol -else: - pa = LazyModule("pyarrow") TagConstant = bool | int | float | str | bytes """A value ``AddTags`` accepts: its exact Python type is the tag's declared type.""" diff --git a/src/orcapod/core/operators/arrow_keys.py b/src/orcapod/core/operators/arrow_keys.py index 859027a15..5ecdacba3 100644 --- a/src/orcapod/core/operators/arrow_keys.py +++ b/src/orcapod/core/operators/arrow_keys.py @@ -32,18 +32,11 @@ from __future__ import annotations from collections.abc import Sequence -from typing import TYPE_CHECKING, Any, cast - -from orcapod.utils.lazy_module import LazyModule - -if TYPE_CHECKING: - import numpy as np - import polars as pl - import pyarrow as pa -else: - np = LazyModule("numpy") - pl = LazyModule("polars") - pa = LazyModule("pyarrow") +from typing import Any, cast + +import numpy as np +import polars as pl +import pyarrow as pa def is_list_kind(arrow_type: "pa.DataType") -> bool: diff --git a/src/orcapod/core/operators/batch.py b/src/orcapod/core/operators/batch.py index 879229f58..e4c19d279 100644 --- a/src/orcapod/core/operators/batch.py +++ b/src/orcapod/core/operators/batch.py @@ -1,7 +1,10 @@ from __future__ import annotations from collections.abc import Sequence -from typing import Any, ClassVar, TYPE_CHECKING, cast +from typing import Any, ClassVar, cast + +import numpy as np +import pyarrow as pa from orcapod.core.operators.meta_columns import WithoutMetaWriter from orcapod.channels import ReadableChannel, WritableChannel @@ -12,14 +15,6 @@ from orcapod.system_constants import constants from orcapod.types import ColumnConfig, ContentHash from orcapod.utils import arrow_utils -from orcapod.utils.lazy_module import LazyModule - -if TYPE_CHECKING: - import numpy as np - import pyarrow as pa -else: - np = LazyModule("numpy") - pa = LazyModule("pyarrow") from orcapod.types import Schema diff --git a/src/orcapod/core/operators/column_selection.py b/src/orcapod/core/operators/column_selection.py index 1e91993a2..3e59a5458 100644 --- a/src/orcapod/core/operators/column_selection.py +++ b/src/orcapod/core/operators/column_selection.py @@ -1,7 +1,7 @@ import logging from abc import ABC, abstractmethod from collections.abc import Collection, Sequence -from typing import TYPE_CHECKING, Any, ClassVar +from typing import Any, ClassVar from orcapod.core.operators.meta_columns import WithoutMetaWriter from orcapod.channels import ReadableChannel, WritableChannel @@ -12,14 +12,8 @@ from orcapod.protocols.core_protocols import DataProtocol, StreamProtocol, TagProtocol from orcapod.system_constants import constants from orcapod.types import ColumnConfig, ContentHash, Schema -from orcapod.utils.lazy_module import LazyModule from orcapod.utils.schema_utils import column_names -if TYPE_CHECKING: - import pyarrow as pa -else: - pa = LazyModule("pyarrow") - logger = logging.getLogger(__name__) diff --git a/src/orcapod/core/operators/drop_nulls.py b/src/orcapod/core/operators/drop_nulls.py index 41a972dba..6e1fc0a81 100644 --- a/src/orcapod/core/operators/drop_nulls.py +++ b/src/orcapod/core/operators/drop_nulls.py @@ -5,7 +5,10 @@ import types import typing from collections.abc import Collection, Sequence -from typing import Any, ClassVar, TYPE_CHECKING +from typing import Any, ClassVar + +import pyarrow as pa +import pyarrow.compute as pc from orcapod.core.data_tags import stream_data_tags from orcapod.core.operators.meta_columns import WithoutMetaWriter @@ -18,16 +21,8 @@ from orcapod.system_constants import constants from orcapod.types import ColumnConfig, ContentHash, DataType, Schema from orcapod.utils import arrow_utils -from orcapod.utils.lazy_module import LazyModule from orcapod.utils.schema_utils import column_names -if TYPE_CHECKING: - import pyarrow as pa - import pyarrow.compute as pc -else: - pa = LazyModule("pyarrow") - pc = LazyModule("pyarrow.compute") - def _without_none(python_type: DataType) -> DataType: """Return ``python_type`` with ``None`` removed from a union. diff --git a/src/orcapod/core/operators/filters.py b/src/orcapod/core/operators/filters.py index 1a3a7f23a..73e34bef7 100644 --- a/src/orcapod/core/operators/filters.py +++ b/src/orcapod/core/operators/filters.py @@ -2,23 +2,19 @@ from collections.abc import Collection, Iterable, Mapping from typing import Any, ClassVar, TYPE_CHECKING, TypeAlias +import polars as pl +import pyarrow as pa + from orcapod.core.data_tags import stream_data_tags from orcapod.core.operators.base import UnaryOperator from orcapod.core.streams import ArrowTableStream from orcapod.protocols.core_protocols import StreamProtocol from orcapod.types import ColumnConfig, Schema from orcapod.utils import arrow_utils -from orcapod.utils.lazy_module import LazyModule if TYPE_CHECKING: import numpy as np - import polars as pl import polars._typing as pl_type - import pyarrow as pa -else: - pa = LazyModule("pyarrow") - pl = LazyModule("polars") - pl_type = LazyModule("polars._typing") logger = logging.getLogger(__name__) diff --git a/src/orcapod/core/operators/group_by.py b/src/orcapod/core/operators/group_by.py index 63b5ccf33..b78a0553c 100644 --- a/src/orcapod/core/operators/group_by.py +++ b/src/orcapod/core/operators/group_by.py @@ -3,7 +3,11 @@ from __future__ import annotations from collections.abc import Collection, Mapping, Sequence, Set -from typing import Any, ClassVar, TYPE_CHECKING, cast, get_origin +from typing import Any, ClassVar, cast, get_origin + +import numpy as np +import polars as pl +import pyarrow as pa from orcapod.core.operators.arrow_keys import ( is_list_kind, @@ -21,19 +25,8 @@ from orcapod.system_constants import constants from orcapod.types import ColumnConfig, Schema from orcapod.utils import arrow_utils -from orcapod.utils.lazy_module import LazyModule from orcapod.utils.schema_utils import column_names -if TYPE_CHECKING: - import numpy as np - import polars as pl - import pyarrow as pa -else: - np = LazyModule("numpy") - pl = LazyModule("polars") - pa = LazyModule("pyarrow") - - # GroupBy decides which rows form a group, and in what order, with Polars, and builds # its output from the input's Arrow arrays (ITL-1250): no value passes through Python, # so two keys are one group only when Polars finds them equal (all NaN equal, 0.0 equal diff --git a/src/orcapod/core/operators/index.py b/src/orcapod/core/operators/index.py index 7b2913c82..ac988abe3 100644 --- a/src/orcapod/core/operators/index.py +++ b/src/orcapod/core/operators/index.py @@ -5,7 +5,9 @@ import logging import typing from collections.abc import Sequence -from typing import Any, ClassVar, TYPE_CHECKING, cast +from typing import Any, ClassVar, cast + +import pyarrow as pa from orcapod.core.data_tags import stream_data_tags from orcapod.core.operators.meta_columns import WithoutMetaWriter @@ -17,12 +19,6 @@ from orcapod.protocols.core_protocols import DataProtocol, StreamProtocol, TagProtocol from orcapod.types import ColumnConfig, ContentHash, Schema, SourceInfoValue from orcapod.utils import arrow_utils, schema_utils -from orcapod.utils.lazy_module import LazyModule - -if TYPE_CHECKING: - import pyarrow as pa -else: - pa = LazyModule("pyarrow") logger = logging.getLogger(__name__) diff --git a/src/orcapod/core/operators/join.py b/src/orcapod/core/operators/join.py index c48254a88..0f8afc2d6 100644 --- a/src/orcapod/core/operators/join.py +++ b/src/orcapod/core/operators/join.py @@ -3,7 +3,9 @@ import itertools import json from collections.abc import Callable, Collection, Mapping, Sequence -from typing import Any, ClassVar, TYPE_CHECKING +from typing import Any, ClassVar + +import pyarrow as pa from orcapod.core.operators.meta_columns import ( WithoutMetaWriter, @@ -42,15 +44,6 @@ from orcapod.system_constants import constants from orcapod.types import ColumnConfig, ContentHash, DataValue, Schema from orcapod.utils import arrow_utils, schema_utils -from orcapod.utils.lazy_module import LazyModule - -if TYPE_CHECKING: - import polars as pl - import pyarrow as pa -else: - pa = LazyModule("pyarrow") - pl = LazyModule("polars") - # The row-number columns of the frames Polars joins (``_inner_join``); a tag, so a # key, never starts with the meta prefix ``__``. diff --git a/src/orcapod/core/operators/mappers.py b/src/orcapod/core/operators/mappers.py index c4c7e4ee9..b27aae340 100644 --- a/src/orcapod/core/operators/mappers.py +++ b/src/orcapod/core/operators/mappers.py @@ -1,5 +1,5 @@ from collections.abc import Collection, Mapping, Sequence -from typing import TYPE_CHECKING, Any, ClassVar +from typing import Any, ClassVar from orcapod.core.operators.meta_columns import WithoutMetaWriter from orcapod.channels import ReadableChannel, WritableChannel @@ -15,12 +15,6 @@ from orcapod.system_constants import constants from orcapod.types import ColumnConfig, ContentHash, Schema from orcapod.utils import schema_utils -from orcapod.utils.lazy_module import LazyModule - -if TYPE_CHECKING: - import pyarrow as pa -else: - pa = LazyModule("pyarrow") def _with_other_group_note( diff --git a/src/orcapod/core/operators/match_keys.py b/src/orcapod/core/operators/match_keys.py index 42e9ae1c2..c8da718fa 100644 --- a/src/orcapod/core/operators/match_keys.py +++ b/src/orcapod/core/operators/match_keys.py @@ -22,14 +22,9 @@ from __future__ import annotations import math -from typing import TYPE_CHECKING, Any +from typing import Any -from orcapod.utils.lazy_module import LazyModule - -if TYPE_CHECKING: - import pyarrow as pa -else: - pa = LazyModule("pyarrow") +import pyarrow as pa # The frozen form of a NaN value: equal to itself, as NaN is in Polars. _NAN = object() diff --git a/src/orcapod/core/operators/merge_join.py b/src/orcapod/core/operators/merge_join.py index 616b135de..b4d926c3d 100644 --- a/src/orcapod/core/operators/merge_join.py +++ b/src/orcapod/core/operators/merge_join.py @@ -1,4 +1,7 @@ -from typing import Any, ClassVar, TYPE_CHECKING, cast +from typing import Any, ClassVar, cast + +import numpy as np +import pyarrow as pa from orcapod.core.operators.base import ( BinaryOperator, @@ -26,14 +29,6 @@ from orcapod.system_constants import constants from orcapod.types import ColumnConfig, Schema from orcapod.utils import arrow_utils, schema_utils -from orcapod.utils.lazy_module import LazyModule - -if TYPE_CHECKING: - import numpy as np - import pyarrow as pa -else: - np = LazyModule("numpy") - pa = LazyModule("pyarrow") def _output_types( diff --git a/src/orcapod/core/operators/meta_columns.py b/src/orcapod/core/operators/meta_columns.py index 8ca65947f..674d55e46 100644 --- a/src/orcapod/core/operators/meta_columns.py +++ b/src/orcapod/core/operators/meta_columns.py @@ -14,7 +14,8 @@ from __future__ import annotations from collections.abc import Collection, Sequence -from typing import TYPE_CHECKING + +import pyarrow as pa from orcapod.channels import WritableChannel from orcapod.core.data_tags import stream_data_tags, with_data_tags_first @@ -22,12 +23,6 @@ from orcapod.protocols.core_protocols import DataProtocol, StreamProtocol, TagProtocol from orcapod.system_constants import constants from orcapod.types import Schema -from orcapod.utils.lazy_module import LazyModule - -if TYPE_CHECKING: - import pyarrow as pa -else: - pa = LazyModule("pyarrow") _META_SOURCE_PREFIX = f"{constants.SOURCE_PREFIX}{constants.META_PREFIX}" diff --git a/src/orcapod/core/operators/pick.py b/src/orcapod/core/operators/pick.py index 6b3d28e0a..e6d648659 100644 --- a/src/orcapod/core/operators/pick.py +++ b/src/orcapod/core/operators/pick.py @@ -5,7 +5,9 @@ import logging import typing from collections.abc import Sequence -from typing import Any, ClassVar, TYPE_CHECKING, cast +from typing import Any, ClassVar, cast + +import pyarrow as pa from orcapod.core.data_tags import stream_data_tags from orcapod.core.operators.meta_columns import WithoutMetaWriter @@ -17,12 +19,6 @@ from orcapod.protocols.core_protocols import DataProtocol, StreamProtocol, TagProtocol from orcapod.types import ColumnConfig, ContentHash, Schema from orcapod.utils import arrow_utils, schema_utils -from orcapod.utils.lazy_module import LazyModule - -if TYPE_CHECKING: - import pyarrow as pa -else: - pa = LazyModule("pyarrow") logger = logging.getLogger(__name__) diff --git a/src/orcapod/core/operators/rejoin.py b/src/orcapod/core/operators/rejoin.py index f4911d843..37e78a829 100644 --- a/src/orcapod/core/operators/rejoin.py +++ b/src/orcapod/core/operators/rejoin.py @@ -15,7 +15,9 @@ from __future__ import annotations from collections.abc import Collection, Sequence -from typing import TYPE_CHECKING, Any, ClassVar +from typing import Any, ClassVar + +import pyarrow as pa from orcapod.channels import ReadableChannel, WritableChannel from orcapod.core.data_tags import data_tag_names, data_tags_first @@ -40,14 +42,6 @@ from orcapod.system_constants import constants from orcapod.types import ColumnConfig, ContentHash, Schema from orcapod.utils import arrow_utils, schema_utils -from orcapod.utils.lazy_module import LazyModule - -if TYPE_CHECKING: - import polars as pl - import pyarrow as pa -else: - pa = LazyModule("pyarrow") - pl = LazyModule("polars") # Row-number columns of the frames Polars matches; never a key (keys are system tags). _LEFT_ROW = "__rejoin_left_row" diff --git a/src/orcapod/core/operators/semijoin.py b/src/orcapod/core/operators/semijoin.py index 26dc27734..5bc03d11d 100644 --- a/src/orcapod/core/operators/semijoin.py +++ b/src/orcapod/core/operators/semijoin.py @@ -3,7 +3,10 @@ import warnings from collections import deque from collections.abc import AsyncGenerator, AsyncIterator, Collection, Sequence -from typing import TYPE_CHECKING, Any, ClassVar, final +from typing import Any, ClassVar, final + +import pyarrow as pa +import pyarrow.compute as pc from orcapod.channels import ChannelClosed, ReadableChannel, WritableChannel from orcapod.core.operators.meta_columns import WithoutMetaWriter @@ -22,18 +25,8 @@ from orcapod.system_constants import constants from orcapod.types import ColumnConfig, ContentHash, Schema from orcapod.utils import arrow_utils, schema_utils -from orcapod.utils.lazy_module import LazyModule from orcapod.utils.warning_utils import outside_orcapod_stacklevel -if TYPE_CHECKING: - import polars as pl - import pyarrow as pa - import pyarrow.compute as pc -else: - pa = LazyModule("pyarrow") - pc = LazyModule("pyarrow.compute") - pl = LazyModule("polars") - # The row-number column of the left frame Polars matches; a tag, so a key, never # starts with the meta prefix ``__``. _LEFT_ROW = "__semi_join_left_row" diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index dbc7b13d3..a669ecf9b 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -7,6 +7,8 @@ from datetime import datetime, timezone from typing import TYPE_CHECKING, Any, ClassVar, cast +import pyarrow as pa + from orcapod.channels import ReadableChannel, WritableChannel from orcapod import contexts from orcapod.config import OrcapodConfig @@ -48,16 +50,11 @@ TrackerManagerProtocol, ) from orcapod.types import ColumnConfig, ContentHash, Schema -from orcapod.utils.lazy_module import LazyModule logger = logging.getLogger(__name__) if TYPE_CHECKING: - import pyarrow as pa - from orcapod.protocols.hashing_protocols import SemanticHasherProtocol -else: - pa = LazyModule("pyarrow") class StaticOutputOperatorPod(TraceableBase): diff --git a/src/orcapod/core/result_cache.py b/src/orcapod/core/result_cache.py index a3f544315..faf746112 100644 --- a/src/orcapod/core/result_cache.py +++ b/src/orcapod/core/result_cache.py @@ -12,6 +12,8 @@ from datetime import datetime, timezone from typing import TYPE_CHECKING, Any +import pyarrow as pa + from orcapod.core.data_function_types import StoredColumn from orcapod.errors import OrcapodDatabaseReadError, OrcapodDatabaseWriteError from orcapod.hashing.arrow_hashers import ARROW_HASH_LABEL @@ -30,14 +32,9 @@ RESULT_DB_SCHEMA_VERSION, constants, ) -from orcapod.utils.lazy_module import LazyModule if TYPE_CHECKING: - import pyarrow as pa - from orcapod.protocols.core_protocols.datagrams import DatagramProtocol -else: - pa = LazyModule("pyarrow") logger = logging.getLogger(__name__) diff --git a/src/orcapod/core/sources/cached_source.py b/src/orcapod/core/sources/cached_source.py index 4be081849..308a24fb6 100644 --- a/src/orcapod/core/sources/cached_source.py +++ b/src/orcapod/core/sources/cached_source.py @@ -6,6 +6,7 @@ from collections.abc import Iterator from typing import Any, ClassVar, TYPE_CHECKING +import pyarrow as pa from typing_extensions import override from orcapod import contexts @@ -40,13 +41,9 @@ from orcapod.system_constants import SOURCE_DB_SCHEMA_VERSION, constants from orcapod.types import ColumnConfig, Schema from orcapod.utils import schema_utils -from orcapod.utils.lazy_module import LazyModule if TYPE_CHECKING: - import pyarrow as pa from orcapod.protocols.database_protocols import DatabaseRegistryProtocol -else: - pa = LazyModule("pyarrow") logger = logging.getLogger(__name__) diff --git a/src/orcapod/core/sources/csv_source.py b/src/orcapod/core/sources/csv_source.py index 6fbfb841a..cd780ab1e 100644 --- a/src/orcapod/core/sources/csv_source.py +++ b/src/orcapod/core/sources/csv_source.py @@ -5,8 +5,9 @@ import os import re from collections.abc import Collection -from typing import Any, ClassVar, TYPE_CHECKING +from typing import Any, ClassVar +import pyarrow as pa from typing_extensions import override from orcapod.core.sources.base import RootSource, saved_tag_only_columns @@ -20,13 +21,6 @@ ) from orcapod.utils import arrow_utils from orcapod.utils.schema_utils import _normalize_column_list -from orcapod.utils.lazy_module import LazyModule - -if TYPE_CHECKING: - import pyarrow as pa -else: - pa = LazyModule("pyarrow") - _INFINITY = re.compile(r"\s*[+-]?inf(inity)?\s*", re.IGNORECASE) """The texts pyarrow's CSV reader reads as an infinity: ``inf`` or ``infinity``, any diff --git a/src/orcapod/core/sources/data_frame_source.py b/src/orcapod/core/sources/data_frame_source.py index d89ee808d..5db583ec2 100644 --- a/src/orcapod/core/sources/data_frame_source.py +++ b/src/orcapod/core/sources/data_frame_source.py @@ -4,6 +4,9 @@ from collections.abc import Collection from typing import TYPE_CHECKING, Any, ClassVar +import polars as pl +import pyarrow as pa + from orcapod.core.sources.base import RootSource from orcapod.core.data_tags import TagOnlyColumns, source_data_tags from orcapod.core.sources.stream_builder import SourceStreamBuilder @@ -12,15 +15,9 @@ ) from orcapod.utils import arrow_utils, polars_data_utils from orcapod.utils.schema_utils import _normalize_column_list -from orcapod.utils.lazy_module import LazyModule if TYPE_CHECKING: - import polars as pl - import pyarrow as pa from polars._typing import FrameInitTypes -else: - pl = LazyModule("polars") - pa = LazyModule("pyarrow") logger = logging.getLogger(__name__) diff --git a/src/orcapod/core/sources/db_table_source.py b/src/orcapod/core/sources/db_table_source.py index 437b2aedc..decdc09ea 100644 --- a/src/orcapod/core/sources/db_table_source.py +++ b/src/orcapod/core/sources/db_table_source.py @@ -18,6 +18,7 @@ from contextlib import contextmanager from typing import Any, ClassVar, TYPE_CHECKING +import pyarrow as pa from typing_extensions import override from orcapod.core.sources.base import RootSource @@ -30,17 +31,12 @@ SourceStreamResult, ) from orcapod.utils import arrow_utils -from orcapod.utils.lazy_module import LazyModule from orcapod.utils.schema_utils import _normalize_column_list if TYPE_CHECKING: - import pyarrow as pa - from orcapod import contexts from orcapod.config import OrcapodConfig from orcapod.protocols.db_connector_protocol import DBConnectorProtocol -else: - pa = LazyModule("pyarrow") class DBTableSource(RootSource): diff --git a/src/orcapod/core/sources/delta_table_source.py b/src/orcapod/core/sources/delta_table_source.py index 6bfad9f78..ae623bdec 100644 --- a/src/orcapod/core/sources/delta_table_source.py +++ b/src/orcapod/core/sources/delta_table_source.py @@ -6,6 +6,7 @@ from pathlib import Path from typing import Any, ClassVar, TYPE_CHECKING +import pyarrow as pa from typing_extensions import override from orcapod.core.sources.base import RootSource, saved_tag_only_columns @@ -23,10 +24,8 @@ from orcapod.utils.schema_utils import _normalize_column_list if TYPE_CHECKING: - import pyarrow as pa import deltalake else: - pa = LazyModule("pyarrow") deltalake = LazyModule("deltalake") diff --git a/src/orcapod/core/sources/derived_source.py b/src/orcapod/core/sources/derived_source.py index 5b06672d2..1a7a58a93 100644 --- a/src/orcapod/core/sources/derived_source.py +++ b/src/orcapod/core/sources/derived_source.py @@ -5,6 +5,8 @@ from datetime import datetime from typing import TYPE_CHECKING, Any, ClassVar +import pyarrow as pa + from orcapod.core.data_tags import ( stored_data_tags, stream_data_tags, @@ -35,16 +37,11 @@ from orcapod.system_constants import constants from orcapod.types import ColumnConfig, Schema from orcapod.utils import schema_utils -from orcapod.utils.lazy_module import LazyModule from orcapod.utils.provisional import provisional_class_name if TYPE_CHECKING: - import pyarrow as pa - from orcapod.core.nodes.function_node import FunctionJobNode from orcapod.core.nodes.operator_node import OperatorJobNode -else: - pa = LazyModule("pyarrow") def validate_tags_as_data( diff --git a/src/orcapod/core/sources/dict_source.py b/src/orcapod/core/sources/dict_source.py index 234c9d6b2..bb99e1f9c 100644 --- a/src/orcapod/core/sources/dict_source.py +++ b/src/orcapod/core/sources/dict_source.py @@ -1,7 +1,9 @@ from __future__ import annotations from collections.abc import Collection, Mapping -from typing import TYPE_CHECKING, Any, ClassVar +from typing import Any, ClassVar + +import pyarrow as pa from orcapod.core.sources.base import RootSource from orcapod.core.data_tags import TagOnlyColumns, source_data_tags @@ -12,14 +14,8 @@ from orcapod.types import DataValue, SchemaLike from orcapod.utils import arrow_utils from orcapod.utils.schema_utils import _normalize_column_list -from orcapod.utils.lazy_module import LazyModule from orcapod.utils.tensor_conversions import warn_source_tensor_conversions -if TYPE_CHECKING: - import pyarrow as pa -else: - pa = LazyModule("pyarrow") - class DictSource(RootSource): """A source backed by a collection of Python dictionaries. diff --git a/src/orcapod/core/sources/polling_source.py b/src/orcapod/core/sources/polling_source.py index 03d51bc42..b215460c1 100644 --- a/src/orcapod/core/sources/polling_source.py +++ b/src/orcapod/core/sources/polling_source.py @@ -18,6 +18,8 @@ from math import floor from typing import Any, ClassVar, Generic, TYPE_CHECKING, TypeVar, cast +import polars as pl +import pyarrow as pa from typing_extensions import override from orcapod.core.sources.base import RootSource @@ -45,7 +47,6 @@ from orcapod.types import ColumnConfig, Cursor, PollingConfig, Schema from orcapod.utils import arrow_utils, polars_data_utils from orcapod.utils.arrow_utils import system_tag_column_names -from orcapod.utils.lazy_module import LazyModule from orcapod.utils.schema_utils import ( _normalize_column_list, compute_source_schema_hash, @@ -53,18 +54,12 @@ ) if TYPE_CHECKING: - import polars as pl - import pyarrow as pa from polars._typing import FrameInitTypes from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.protocols.core_protocols.sources import DynamicSourceProtocol from orcapod.types import Schema -else: - pa = LazyModule("pyarrow") - pl = LazyModule("polars") - T = TypeVar("T") logger = logging.getLogger(__name__) diff --git a/src/orcapod/core/sources/reload.py b/src/orcapod/core/sources/reload.py index ce700aa62..3a2b12d2b 100644 --- a/src/orcapod/core/sources/reload.py +++ b/src/orcapod/core/sources/reload.py @@ -9,20 +9,12 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Any - -from orcapod.utils.lazy_module import LazyModule - -if TYPE_CHECKING: - import polars as pl - import pyarrow as pa - import pyarrow.compute as pc - import pyarrow.ipc as pa_ipc -else: - pa = LazyModule("pyarrow") - pc = LazyModule("pyarrow.compute") - pa_ipc = LazyModule("pyarrow.ipc") - pl = LazyModule("polars") +from typing import Any + +import polars as pl +import pyarrow as pa +import pyarrow.compute as pc +import pyarrow.ipc as pa_ipc def keep_nullable_columns(read: pa.Table, held: pa.Schema) -> pa.Table: diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index 57dfe86d8..57d1325f9 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -45,6 +45,7 @@ from contextlib import contextmanager from typing import Any, ClassVar, NamedTuple, TYPE_CHECKING +import pyarrow as pa from typing_extensions import override from orcapod.core.sources.base import RootSource, saved_tag_only_columns @@ -65,19 +66,12 @@ from orcapod.errors import InputValidationError, RowIdentifierError, SourceTooLargeError from orcapod.types import ColumnConfig, Condition from orcapod.utils import arrow_utils -from orcapod.utils.lazy_module import LazyModule from orcapod.utils.schema_utils import _normalize_column_list if TYPE_CHECKING: - import polars as pl - import pyarrow as pa - from orcapod import contexts from orcapod.config import OrcapodConfig from orcapod.protocols.core_protocols import DataProtocol, TagProtocol -else: - pa = LazyModule("pyarrow") - pl = LazyModule("polars") DEFAULT_MAX_ROWS = 100_000 DEFAULT_BATCH_ROWS = 8_192 diff --git a/src/orcapod/core/sources/stream_builder.py b/src/orcapod/core/sources/stream_builder.py index 95f2e2ca4..4f66de5e8 100644 --- a/src/orcapod/core/sources/stream_builder.py +++ b/src/orcapod/core/sources/stream_builder.py @@ -14,6 +14,8 @@ from dataclasses import dataclass from typing import TYPE_CHECKING, Any, cast +import pyarrow as pa + from orcapod.core.sources.source_ids import hash_source_id from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.errors import RowIdentifierError @@ -22,16 +24,11 @@ from orcapod.types import ContentHash from orcapod.utils import arrow_utils, schema_utils from orcapod.utils.schema_utils import compute_source_schema_hash -from orcapod.utils.lazy_module import LazyModule if TYPE_CHECKING: - import pyarrow as pa - from orcapod.config import OrcapodConfig from orcapod.contexts import DataContext from orcapod.protocols.hashing_protocols import ArrowHasherProtocol -else: - pa = LazyModule("pyarrow") def normalize_record_id_columns( diff --git a/src/orcapod/core/streams/arrow_table_stream.py b/src/orcapod/core/streams/arrow_table_stream.py index a07c32400..9d171d8c3 100644 --- a/src/orcapod/core/streams/arrow_table_stream.py +++ b/src/orcapod/core/streams/arrow_table_stream.py @@ -3,7 +3,9 @@ import itertools import logging from collections.abc import Collection, Iterator -from typing import TYPE_CHECKING, Any +from typing import Any + +import pyarrow as pa from orcapod.hashing.orcapod_table import OrcapodTable from orcapod import contexts @@ -19,13 +21,6 @@ from orcapod.system_constants import constants from orcapod.types import ColumnConfig, Schema, SourceInfoValue from orcapod.utils import arrow_utils, schema_utils -from orcapod.utils.lazy_module import LazyModule - -if TYPE_CHECKING: - import pyarrow as pa -else: - pa = LazyModule("pyarrow") - logger = logging.getLogger(__name__) diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py index f5dbc5e61..0f8a5cb33 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -14,7 +14,11 @@ from contextlib import contextmanager from contextvars import ContextVar from datetime import datetime -from typing import TYPE_CHECKING, Any, cast +from typing import Any, cast + +import pandas as pd +import polars as pl +import pyarrow as pa from orcapod.core.base import TraceableBase from orcapod.core.streams.view import ( @@ -32,17 +36,6 @@ ) from orcapod.types import ColumnConfig, Schema from orcapod.utils import arrow_utils -from orcapod.utils.lazy_module import LazyModule - -if TYPE_CHECKING: - import pandas as pd - import polars as pl - import pyarrow as pa -else: - pa = LazyModule("pyarrow") - pl = LazyModule("polars") - pd = LazyModule("pandas") - # TODO: consider using this instead of making copy of dicts # from types import MappingProxyType diff --git a/src/orcapod/core/streams/view.py b/src/orcapod/core/streams/view.py index cde4ba5ee..699de9401 100644 --- a/src/orcapod/core/streams/view.py +++ b/src/orcapod/core/streams/view.py @@ -24,21 +24,14 @@ from dataclasses import dataclass from enum import Enum from html.parser import HTMLParser -from typing import TYPE_CHECKING, Any, cast +from typing import Any, cast +import polars as pl +import pyarrow as pa +import pyarrow.compute as pc from typing_extensions import override from orcapod.system_constants import constants -from orcapod.utils.lazy_module import LazyModule - -if TYPE_CHECKING: - import polars as pl - import pyarrow as pa - import pyarrow.compute as pc -else: - pa = LazyModule("pyarrow") - pc = LazyModule("pyarrow.compute") - pl = LazyModule("polars") class ViewStatus(str, Enum): diff --git a/src/orcapod/databases/_row_index.py b/src/orcapod/databases/_row_index.py index a8223514d..68904182a 100644 --- a/src/orcapod/databases/_row_index.py +++ b/src/orcapod/databases/_row_index.py @@ -10,16 +10,10 @@ from collections.abc import Sequence from dataclasses import dataclass, field -from typing import TYPE_CHECKING, Any +from typing import Any -from orcapod.utils.lazy_module import LazyModule - -if TYPE_CHECKING: - import pyarrow as pa - import pyarrow.compute as pc -else: - pa = LazyModule("pyarrow") - pc = LazyModule("pyarrow.compute") +import pyarrow as pa +import pyarrow.compute as pc @dataclass diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index 205a108ac..ba3ef3297 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -21,7 +21,10 @@ import re from collections import defaultdict from collections.abc import Collection, Mapping -from typing import TYPE_CHECKING, Any, cast +from typing import Any, cast + +import pyarrow as pa +import pyarrow.compute as pc from orcapod.databases.utils import coerce_record_id from orcapod.errors import UnstorableColumnError, UnstorableTableNameError @@ -31,14 +34,6 @@ normalize_to_large_types, ) from orcapod.protocols.db_connector_protocol import ColumnInfo, DBConnectorProtocol -from orcapod.utils.lazy_module import LazyModule - -if TYPE_CHECKING: - import pyarrow as pa - import pyarrow.compute as pc -else: - pa = LazyModule("pyarrow") - pc = LazyModule("pyarrow.compute") def _arrow_schema_to_column_infos(schema: pa.Schema) -> list[ColumnInfo]: diff --git a/src/orcapod/databases/delta_arrow_types.py b/src/orcapod/databases/delta_arrow_types.py index 144bedf8e..a56fbaf0f 100644 --- a/src/orcapod/databases/delta_arrow_types.py +++ b/src/orcapod/databases/delta_arrow_types.py @@ -30,15 +30,11 @@ import base64 from collections.abc import Collection, Mapping -from typing import TYPE_CHECKING, Any +from typing import Any -from orcapod.utils import arrow_utils -from orcapod.utils.lazy_module import LazyModule +import pyarrow as pa -if TYPE_CHECKING: - import pyarrow as pa -else: - pa = LazyModule("pyarrow") +from orcapod.utils import arrow_utils # Field metadata key holding a column's original Arrow type. ARROW_TYPE_KEY = b"orcapod:arrow_type" diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index 8399c3dd9..44ada6e40 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -9,6 +9,10 @@ from pathlib import Path from typing import TYPE_CHECKING, Any, Literal, cast +import polars as pl +import pyarrow as pa +import pyarrow.compute as pc + from orcapod.databases._row_index import ( KeyIndex, compact_tail, @@ -40,17 +44,11 @@ if TYPE_CHECKING: import deltalake - import polars as pl - import pyarrow as pa - import pyarrow.compute as pc import pyarrow.dataset as pa_ds import pyarrow.fs as pa_fs from upath import UPath else: deltalake = LazyModule("deltalake") - pa = LazyModule("pyarrow") - pl = LazyModule("polars") - pc = LazyModule("pyarrow.compute") pa_ds = LazyModule("pyarrow.dataset") # Module-level logger diff --git a/src/orcapod/databases/delta_statistics.py b/src/orcapod/databases/delta_statistics.py index f713cc7de..a5b81a0c9 100644 --- a/src/orcapod/databases/delta_statistics.py +++ b/src/orcapod/databases/delta_statistics.py @@ -46,14 +46,7 @@ from __future__ import annotations -from typing import TYPE_CHECKING - -from orcapod.utils.lazy_module import LazyModule - -if TYPE_CHECKING: - import pyarrow as pa -else: - pa = LazyModule("pyarrow") +import pyarrow as pa STATS_COLUMNS_PROPERTY = "delta.dataSkippingStatsColumns" NUM_INDEXED_COLUMNS_PROPERTY = "delta.dataSkippingNumIndexedCols" diff --git a/src/orcapod/databases/in_memory_databases.py b/src/orcapod/databases/in_memory_databases.py index 7857c96fd..1f1a73602 100644 --- a/src/orcapod/databases/in_memory_databases.py +++ b/src/orcapod/databases/in_memory_databases.py @@ -5,17 +5,14 @@ from collections.abc import Collection, Mapping from typing import TYPE_CHECKING, Any, cast +import pyarrow as pa +import pyarrow.compute as pc + from orcapod.databases._row_index import KeyIndex, compact_tail, matching_rows from orcapod.databases.utils import coerce_record_id -from orcapod.utils.lazy_module import LazyModule if TYPE_CHECKING: - import pyarrow as pa - import pyarrow.compute as pc from orcapod.pipeline.serialization import DatabaseRegistry -else: - pa = LazyModule("pyarrow") - pc = LazyModule("pyarrow.compute") logger = logging.getLogger(__name__) diff --git a/src/orcapod/databases/noop_database.py b/src/orcapod/databases/noop_database.py index 27c1bf9b6..88012d2dd 100644 --- a/src/orcapod/databases/noop_database.py +++ b/src/orcapod/databases/noop_database.py @@ -1,14 +1,9 @@ from __future__ import annotations from collections.abc import Collection, Mapping -from typing import TYPE_CHECKING, Any +from typing import Any -from orcapod.utils.lazy_module import LazyModule - -if TYPE_CHECKING: - import pyarrow as pa -else: - pa = LazyModule("pyarrow") +import pyarrow as pa class NoOpArrowDatabase: diff --git a/src/orcapod/databases/postgresql_connector.py b/src/orcapod/databases/postgresql_connector.py index cd59c4dc4..f834bb3c6 100644 --- a/src/orcapod/databases/postgresql_connector.py +++ b/src/orcapod/databases/postgresql_connector.py @@ -22,16 +22,16 @@ from collections.abc import Iterator from typing import TYPE_CHECKING, Any +import pyarrow as pa + from orcapod.errors import UnstorableTableNameError from orcapod.types import ColumnInfo from orcapod.utils.lazy_module import LazyModule if TYPE_CHECKING: import psycopg - import pyarrow as pa else: psycopg = LazyModule("psycopg") - pa = LazyModule("pyarrow") logger = logging.getLogger(__name__) diff --git a/src/orcapod/databases/spiraldb_connector.py b/src/orcapod/databases/spiraldb_connector.py index cd0679ef6..d3b67dae8 100644 --- a/src/orcapod/databases/spiraldb_connector.py +++ b/src/orcapod/databases/spiraldb_connector.py @@ -26,6 +26,8 @@ from contextlib import contextmanager from typing import TYPE_CHECKING, Any +import pyarrow as pa + from orcapod.databases.spiraldb_nullability import ( apply_nullability_record, check_no_nulls, @@ -46,12 +48,10 @@ from orcapod.utils import arrow_utils if TYPE_CHECKING: - import pyarrow as pa import spiral as sp else: from orcapod.utils.lazy_module import LazyModule - pa = LazyModule("pyarrow") sp = LazyModule("spiral") logger = logging.getLogger(__name__) diff --git a/src/orcapod/databases/spiraldb_nullability.py b/src/orcapod/databases/spiraldb_nullability.py index 8f6b4592c..161744861 100644 --- a/src/orcapod/databases/spiraldb_nullability.py +++ b/src/orcapod/databases/spiraldb_nullability.py @@ -31,15 +31,11 @@ import hashlib import json from collections.abc import Iterable, Mapping -from typing import TYPE_CHECKING, Any, Protocol +from typing import Any, Protocol -from orcapod.errors import NullabilityRecordError, NullInNonNullableColumnError -from orcapod.utils.lazy_module import LazyModule +import pyarrow as pa -if TYPE_CHECKING: - import pyarrow as pa -else: - pa = LazyModule("pyarrow") +from orcapod.errors import NullabilityRecordError, NullInNonNullableColumnError RECORD_KEY = "__orcapod_nullability__" _FORMAT = "orcapod.nullability" diff --git a/src/orcapod/databases/sqlite_connector.py b/src/orcapod/databases/sqlite_connector.py index d3d20d491..5c0e5956e 100644 --- a/src/orcapod/databases/sqlite_connector.py +++ b/src/orcapod/databases/sqlite_connector.py @@ -19,16 +19,11 @@ import sqlite3 import threading from collections.abc import Iterator -from typing import TYPE_CHECKING, Any +from typing import Any -from orcapod.types import ColumnInfo - -if TYPE_CHECKING: - import pyarrow as pa -else: - from orcapod.utils.lazy_module import LazyModule +import pyarrow as pa - pa = LazyModule("pyarrow") +from orcapod.types import ColumnInfo logger = logging.getLogger(__name__) diff --git a/src/orcapod/execution_engines/ray_execution_engine.py b/src/orcapod/execution_engines/ray_execution_engine.py index b36de8430..e7c25b4e5 100644 --- a/src/orcapod/execution_engines/ray_execution_engine.py +++ b/src/orcapod/execution_engines/ray_execution_engine.py @@ -1,13 +1,13 @@ -from orcapod.utils.lazy_module import LazyModule -from typing import TYPE_CHECKING, Any, TypeVar +import asyncio import logging from collections.abc import Callable +from typing import TYPE_CHECKING, Any, TypeVar + +from orcapod.utils.lazy_module import LazyModule if TYPE_CHECKING: - import asyncio import ray else: - asyncio = LazyModule("asyncio") ray = LazyModule("ray") logger = logging.getLogger(__name__) diff --git a/src/orcapod/hashing/arrow_utils.py b/src/orcapod/hashing/arrow_utils.py index 364703167..e113ddb0c 100644 --- a/src/orcapod/hashing/arrow_utils.py +++ b/src/orcapod/hashing/arrow_utils.py @@ -4,14 +4,9 @@ import hashlib import json from decimal import Decimal -from typing import TYPE_CHECKING, Any +from typing import Any -from orcapod.utils.lazy_module import LazyModule - -if TYPE_CHECKING: - import pyarrow as pa -else: - pa = LazyModule("pyarrow") +import pyarrow as pa def serialize_pyarrow_table_schema(table: "pa.Table") -> str: diff --git a/src/orcapod/hashing/semantic_hashing/polars_expr.py b/src/orcapod/hashing/semantic_hashing/polars_expr.py index 244a53cf8..a37ae2e66 100644 --- a/src/orcapod/hashing/semantic_hashing/polars_expr.py +++ b/src/orcapod/hashing/semantic_hashing/polars_expr.py @@ -65,15 +65,11 @@ import json import math import struct -from typing import TYPE_CHECKING, Any +from typing import Any -from orcapod.types import ContentHash -from orcapod.utils.lazy_module import LazyModule +import polars as pl -if TYPE_CHECKING: - import polars as pl -else: - pl = LazyModule("polars") +from orcapod.types import ContentHash POLARS_EXPR_HASH_LABEL = "polars_expr_v1" diff --git a/src/orcapod/hashing/visitors.py b/src/orcapod/hashing/visitors.py index 1303cbd61..07c44fea9 100644 --- a/src/orcapod/hashing/visitors.py +++ b/src/orcapod/hashing/visitors.py @@ -9,16 +9,14 @@ import typing from typing import TYPE_CHECKING, Any +import pyarrow as pa + from orcapod.logical_types.identifier import arrow_type_identifier from orcapod.logical_types.ignore_list import IgnoreListHandler, parse_ignore_metadata -from orcapod.utils.lazy_module import LazyModule if TYPE_CHECKING: - import pyarrow as pa from orcapod.semantic_types.universal_converter import UniversalTypeConverter from orcapod.protocols.hashing_protocols import SemanticHasherProtocol -else: - pa = LazyModule("pyarrow") class ArrowTypeDataVisitor(ABC): diff --git a/src/orcapod/logical_types/canonical_form.py b/src/orcapod/logical_types/canonical_form.py index e73fa8335..ebf299578 100644 --- a/src/orcapod/logical_types/canonical_form.py +++ b/src/orcapod/logical_types/canonical_form.py @@ -27,15 +27,11 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Any, cast +from typing import Any, cast -from orcapod.logical_types.identifier import LogicalTypeIdentifierError -from orcapod.utils.lazy_module import LazyModule +import pyarrow as pa -if TYPE_CHECKING: - import pyarrow as pa -else: - pa = LazyModule("pyarrow") +from orcapod.logical_types.identifier import LogicalTypeIdentifierError EXTENSION_NAME_KEY = b"ARROW:extension:name" EXTENSION_METADATA_KEY = b"ARROW:extension:metadata" diff --git a/src/orcapod/logical_types/ignore_list.py b/src/orcapod/logical_types/ignore_list.py index 1a4d0396b..acb5d3e6d 100644 --- a/src/orcapod/logical_types/ignore_list.py +++ b/src/orcapod/logical_types/ignore_list.py @@ -35,22 +35,18 @@ from collections.abc import Callable, Collection, Iterable from typing import TYPE_CHECKING, Any, ClassVar, cast +import polars as pl +import pyarrow as pa + from orcapod.logical_types.base_logical_type import BaseLogicalType from orcapod.logical_types.identifier import ( LogicalTypeIdentifier, LogicalTypeIdentifierError, ) from orcapod.types import ContentHash -from orcapod.utils.lazy_module import LazyModule if TYPE_CHECKING: - import polars as pl - import pyarrow as pa - from orcapod.protocols.hashing_protocols import SemanticHasherProtocol -else: - pa = LazyModule("pyarrow") - pl = LazyModule("polars") _OPTION_NAME = re.compile(r"[a-z][a-z0-9_]*") diff --git a/src/orcapod/logical_types/list_logical_type_factory.py b/src/orcapod/logical_types/list_logical_type_factory.py index 4a453ca15..accb1f88a 100644 --- a/src/orcapod/logical_types/list_logical_type_factory.py +++ b/src/orcapod/logical_types/list_logical_type_factory.py @@ -54,23 +54,20 @@ from dataclasses import dataclass from typing import TYPE_CHECKING, Any +import polars as pl +import pyarrow as pa + from orcapod.logical_types.base_logical_type import BaseLogicalType from orcapod.logical_types.registry import ( make_arrow_extension_type, make_polars_extension_type, ) -from orcapod.utils.lazy_module import LazyModule if TYPE_CHECKING: - import polars as pl - import pyarrow as pa from orcapod.logical_types.protocols import ( LogicalTypeProtocol, TypeConverterProtocol, ) -else: - pa = LazyModule("pyarrow") - pl = LazyModule("polars") logger = logging.getLogger(__name__) diff --git a/src/orcapod/logical_types/registry.py b/src/orcapod/logical_types/registry.py index 7d4aa1173..26346f02d 100644 --- a/src/orcapod/logical_types/registry.py +++ b/src/orcapod/logical_types/registry.py @@ -9,7 +9,10 @@ import logging import re import threading -from typing import TYPE_CHECKING, Any, Iterable +from typing import Any, Iterable + +import polars as pl +import pyarrow as pa from orcapod.errors import MissingOptionalDependencyError from orcapod.logical_types.identifier import LogicalTypeIdentifierError @@ -20,14 +23,6 @@ LogicalTypeFactoryProtocol, ) from orcapod.utils.deferred_types import load_object, module_available, qualified_name -from orcapod.utils.lazy_module import LazyModule - -if TYPE_CHECKING: - import polars as pl - import pyarrow as pa -else: - pa = LazyModule("pyarrow") - pl = LazyModule("polars") logger = logging.getLogger(__name__) diff --git a/src/orcapod/logical_types/user_class_logical_type.py b/src/orcapod/logical_types/user_class_logical_type.py index 6301157c0..7f9578b3b 100644 --- a/src/orcapod/logical_types/user_class_logical_type.py +++ b/src/orcapod/logical_types/user_class_logical_type.py @@ -22,6 +22,9 @@ import logging from typing import TYPE_CHECKING, Any +import polars as pl +import pyarrow as pa + from orcapod.errors import RecursiveTypeError, TypeIdentityError import orcapod.logical_types.user_class_identity as uci from orcapod.logical_types.base_logical_type import BaseLogicalType @@ -36,16 +39,9 @@ make_arrow_extension_type, make_polars_extension_type, ) -from orcapod.utils.lazy_module import LazyModule if TYPE_CHECKING: - import polars as pl - import pyarrow as pa - from orcapod.logical_types.protocols import TypeConverterProtocol -else: - pa = LazyModule("pyarrow") - pl = LazyModule("polars") logger = logging.getLogger(__name__) diff --git a/src/orcapod/semantic_types/precomputed_converters.py b/src/orcapod/semantic_types/precomputed_converters.py index 95e792a43..3e56bc801 100644 --- a/src/orcapod/semantic_types/precomputed_converters.py +++ b/src/orcapod/semantic_types/precomputed_converters.py @@ -8,19 +8,13 @@ from __future__ import annotations -from typing import Any, TYPE_CHECKING +from typing import Any from collections.abc import Callable import pyarrow as pa -from orcapod.utils.lazy_module import LazyModule from orcapod.semantic_types.universal_converter import UniversalTypeConverter -if TYPE_CHECKING: - import pyarrow as pa -else: - pa = LazyModule("pyarrow") - class SemanticSchemaConverter: def __init__( diff --git a/src/orcapod/semantic_types/universal_converter.py b/src/orcapod/semantic_types/universal_converter.py index 605c421c7..678270275 100644 --- a/src/orcapod/semantic_types/universal_converter.py +++ b/src/orcapod/semantic_types/universal_converter.py @@ -22,6 +22,8 @@ # Handle generic types from typing import TYPE_CHECKING, Any, TypedDict, get_args, get_origin +import pyarrow as pa + from orcapod.contexts import DataContext, resolve_context from orcapod.errors import ( CanonicalOrderError, @@ -49,17 +51,13 @@ from orcapod.semantic_types.type_inference import infer_python_schema_from_pylist_data from orcapod.types import DataType, Schema, SchemaLike from orcapod.utils import arrow_utils -from orcapod.utils.lazy_module import LazyModule if TYPE_CHECKING: - import pyarrow as pa from orcapod.logical_types.registry import LogicalTypeRegistry from orcapod.logical_types.protocols import ( LogicalTypeFactoryProtocol, LogicalTypeProtocol, ) -else: - pa = LazyModule("pyarrow") logger = logging.getLogger(__name__) diff --git a/src/orcapod/side_effects.py b/src/orcapod/side_effects.py index 9cb769522..de75192ef 100644 --- a/src/orcapod/side_effects.py +++ b/src/orcapod/side_effects.py @@ -15,6 +15,7 @@ from collections.abc import Callable, Collection, Iterator, Sequence from typing import TYPE_CHECKING, Any, Literal +import pyarrow as pa from typing_extensions import override from orcapod.core.base import TraceableBase @@ -59,10 +60,8 @@ from orcapod.types import ColumnConfig from orcapod.utils import arrow_utils from orcapod.utils.database_errors import flush_best_effort -from orcapod.utils.lazy_module import LazyModule if TYPE_CHECKING: - import pyarrow as pa from orcapod.channels import ReadableChannel, WritableChannel from orcapod.protocols.core_protocols import ( DataProtocol, @@ -74,8 +73,6 @@ from orcapod.protocols.observability_protocols import ExecutionObserverProtocol from orcapod.contexts import DataContext from orcapod.types import ContentHash, Schema -else: - pa = LazyModule("pyarrow") logger = logging.getLogger(__name__) diff --git a/src/orcapod/types/__init__.py b/src/orcapod/types/__init__.py index 51e4e0b82..c54a0c3e1 100644 --- a/src/orcapod/types/__init__.py +++ b/src/orcapod/types/__init__.py @@ -23,19 +23,14 @@ from types import UnionType from typing import TYPE_CHECKING, Any, Generic, Self, TypeAlias, TypeVar +import pyarrow as pa from typing_extensions import override # Re-exported: ``Condition`` is defined in its own module (ITL-1218). from orcapod.types.condition import Condition as Condition if TYPE_CHECKING: - import pyarrow as pa - from orcapod.protocols.core_protocols import DataFunctionExecutorProtocol -else: - from orcapod.utils.lazy_module import LazyModule - - pa = LazyModule("pyarrow") logger = logging.getLogger(__name__) diff --git a/src/orcapod/utils/arrow_utils.py b/src/orcapod/utils/arrow_utils.py index 2021a2ec1..f82a694b6 100644 --- a/src/orcapod/utils/arrow_utils.py +++ b/src/orcapod/utils/arrow_utils.py @@ -6,15 +6,13 @@ from collections.abc import Callable, Mapping, Collection, Sequence from typing import Any, TYPE_CHECKING, cast +import pyarrow as pa + from orcapod.system_constants import constants from orcapod.types import ColumnConfig, SourceInfoValue -from orcapod.utils.lazy_module import LazyModule if TYPE_CHECKING: - import pyarrow as pa from orcapod.protocols.semantic_types_protocols import TypeConverterProtocol -else: - pa = LazyModule("pyarrow") def make_empty_table( diff --git a/src/orcapod/utils/polars_data_utils.py b/src/orcapod/utils/polars_data_utils.py index 443614ed7..f8d1d10cb 100644 --- a/src/orcapod/utils/polars_data_utils.py +++ b/src/orcapod/utils/polars_data_utils.py @@ -2,15 +2,10 @@ from __future__ import annotations from collections.abc import Collection -from typing import TYPE_CHECKING -from orcapod.system_constants import constants -from orcapod.utils.lazy_module import LazyModule +import polars as pl -if TYPE_CHECKING: - import polars as pl -else: - pl = LazyModule("polars") +from orcapod.system_constants import constants def drop_columns_with_prefix( diff --git a/src/orcapod/utils/schema_utils.py b/src/orcapod/utils/schema_utils.py index 7a3f4b43c..f0322d3f2 100644 --- a/src/orcapod/utils/schema_utils.py +++ b/src/orcapod/utils/schema_utils.py @@ -5,21 +5,13 @@ import sys from collections.abc import Callable, Collection, Iterable, Mapping, Sequence from types import UnionType -from typing import TYPE_CHECKING, Any, Union, get_args, get_origin, get_type_hints +from typing import Any, Union, get_args, get_origin, get_type_hints + +import pyarrow as pa from orcapod.errors import InputValidationError from orcapod.types import ContentHash, Schema, SchemaLike -if TYPE_CHECKING: - import pyarrow as pa -else: - from orcapod.utils.lazy_module import LazyModule - - pa = LazyModule("pyarrow") - -if TYPE_CHECKING: - import pyarrow as pa - logger = logging.getLogger(__name__) diff --git a/tests/test_utils/test_lazy_module_use.py b/tests/test_utils/test_lazy_module_use.py new file mode 100644 index 000000000..a417695d8 --- /dev/null +++ b/tests/test_utils/test_lazy_module_use.py @@ -0,0 +1,74 @@ +"""A ``LazyModule`` defers only a module that ``import orcapod`` does not load (ITL-1349). + +Every attribute read through a ``LazyModule`` is a ``__getattr__`` call. On a module that +``import orcapod`` loads anyway (pyarrow, polars, numpy, pandas, asyncio) the wrapper defers +nothing and costs a call per attribute: 42.9 million of them in one warm workshop-scale +``job.run()``. Such a module is imported directly; the wrapper is kept for modules a plain +``import orcapod`` never loads (networkx, deltalake) and for the optional extras. +""" + +from __future__ import annotations + +import ast +import json +import subprocess +import sys +from pathlib import Path + +import orcapod + +SOURCE_ROOT = Path(orcapod.__file__).parent + +# Modules of the optional extras (``orcapod[postgresql]``, ``[ray]``, ``[spiraldb]``): +# ``import orcapod`` loads psycopg when it is installed, but the library must import +# without them, so they stay wrapped. +OPTIONAL_EXTRAS = frozenset({"psycopg", "ray", "spiral"}) + + +def _lazy_modules() -> dict[str, list[str]]: + """Every module name given to ``LazyModule`` in the library, with where it is.""" + found: dict[str, list[str]] = {} + for path in sorted(SOURCE_ROOT.rglob("*.py")): + if path.name == "lazy_module.py": + continue + for node in ast.walk(ast.parse(path.read_text(), filename=str(path))): + if ( + isinstance(node, ast.Call) + and isinstance(node.func, ast.Name) + and node.func.id == "LazyModule" + ): + assert node.args and isinstance(node.args[0], ast.Constant), ( + f"{path}:{node.lineno}: LazyModule takes a literal module name" + ) + where = f"{path.relative_to(SOURCE_ROOT)}:{node.lineno}" + found.setdefault(str(node.args[0].value), []).append(where) + return found + + +def _loaded_by_import_orcapod() -> set[str]: + """The modules a fresh interpreter holds after ``import orcapod``.""" + script = "import json, sys; import orcapod; print(json.dumps(sorted(sys.modules)))" + result = subprocess.run( + [sys.executable, "-c", script], capture_output=True, text=True, check=True + ) + return set(json.loads(result.stdout.splitlines()[-1])) + + +def test_no_lazy_module_wraps_a_module_import_orcapod_loads() -> None: + lazy = _lazy_modules() + loaded = _loaded_by_import_orcapod() + wrapped_but_loaded = { + name: lazy[name] + for name in sorted(lazy) + if name in loaded and name not in OPTIONAL_EXTRAS + } + assert not wrapped_but_loaded, ( + "import these directly, `import orcapod` loads them anyway: " + f"{wrapped_but_loaded}" + ) + + +def test_the_scan_finds_the_lazy_modules_that_remain() -> None: + # Guards the scan itself: a refactor that hid every call from it would pass the + # test above vacuously. + assert "networkx" in _lazy_modules() From 522f6428581be38388dc761b5afb0c89e1b0633b Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" <> Date: Sun, 22 Nov 2026 00:36:23 -0800 Subject: [PATCH 04/86] perf(pipeline): an operator node hands the table it kept to the nodes after it (ITL-1347 stage 1) Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1347.md | 11 ++ src/orcapod/core/nodes/operator_node.py | 9 +- .../core/operators/static_output_pod.py | 80 +++++++- .../test_operator_kept_table_reuse.py | 181 ++++++++++++++++++ 4 files changed, 275 insertions(+), 6 deletions(-) create mode 100644 changelog.d/ITL-1347.md create mode 100644 tests/test_pipeline/test_operator_kept_table_reuse.py diff --git a/changelog.d/ITL-1347.md b/changelog.d/ITL-1347.md new file mode 100644 index 000000000..1396fe682 --- /dev/null +++ b/changelog.d/ITL-1347.md @@ -0,0 +1,11 @@ +### Changed + +- **A job run hands an operator node's kept table to the nodes after it** — an operator node + in a job keeps its run's output as a table built from its rows, and the sync orchestrator + then built the same table again from the same rows for each node that reads it. The node + now returns its rows carrying the table it built (`RowsWithTable`), and the orchestrator + wraps that table for each successor (`_materialize_upstream`). The table is built once + instead of once per successor plus once to keep. Every successor's input is the same: + columns, types, row order, system tags, source info, pipeline and content hashes. No hash, + stored table or output changes. First stage of the table transport between job nodes + (`docs/dev/specs/itl-1347-job-table-transport.md`). (ITL-1347) diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index d66d479c6..e51c19e50 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -1695,9 +1695,12 @@ def execute( # Materialize output = list(result_stream.iter_data()) - # Cache, in row order with or without rows (ITL-1131, ITL-1133) - self._cached_output_stream = StaticOutputOperatorPod._kept_output( - result_stream, output + # Cache, in row order with or without rows (ITL-1131, ITL-1133). The rows + # returned carry the table the kept stream is built over, so the sync + # orchestrator gives it to each successor without building it again + # (ITL-1347, stage 1). + self._cached_output_stream, output = ( + StaticOutputOperatorPod._kept_output_with_rows(result_stream, output) ) self._update_modified_time() diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index a669ecf9b..d0750405e 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -441,9 +441,35 @@ def _kept_output( Returns: A stream over the rows, in row order. """ + return StaticOutputOperatorPod._kept_output_with_rows(result, rows)[0] + + @staticmethod + def _kept_output_with_rows( + result: StreamProtocol, + rows: Sequence[tuple[TagProtocol, DataProtocol]], + ) -> tuple[StreamProtocol, list[tuple[TagProtocol, DataProtocol]]]: + """Return what ``_kept_output`` returns, and ``rows`` with the table built from them. + + With rows, the second value is a ``RowsWithTable``: the same rows, carrying the + table ``_rows_to_table(rows)`` the kept stream is built over. An operator node's + ``execute`` returns it, so the sync orchestrator gives each successor that table + (``_materialize_upstream``) instead of building it from the rows again (ITL-1347, + stage 1). Without rows, the rows are returned as a plain list. + + Args: + result: The operator's result of the run. + rows: ``result``'s rows, in order. + + Returns: + The kept stream, and the rows. + """ if rows: - return StaticOutputOperatorPod._materialize_to_stream(rows) - return StaticOutputOperatorPod._zero_rows_in_row_order(result) + row_table = StaticOutputOperatorPod._rows_to_table(rows) + return ( + StaticOutputOperatorPod._stream_over_row_table(row_table), + RowsWithTable(rows, row_table), + ) + return StaticOutputOperatorPod._zero_rows_in_row_order(result), list(rows) @staticmethod def _flag_source_info_nullability(table: pa.Table) -> pa.Table: @@ -558,7 +584,23 @@ def _materialize_to_stream( Raises: ValueError: If ``rows`` is empty. """ - table, tag_keys, data_tags = StaticOutputOperatorPod._rows_to_table(rows) + return StaticOutputOperatorPod._stream_over_row_table( + StaticOutputOperatorPod._rows_to_table(rows) + ) + + @staticmethod + def _stream_over_row_table( + row_table: tuple[pa.Table, tuple[str, ...], tuple[str, ...]], + ) -> StreamProtocol: + """The stream ``_materialize_to_stream`` builds, over ``_rows_to_table``'s result. + + Args: + row_table: The table, user tag keys and data-tags ``_rows_to_table`` returns. + + Returns: + A stream over the table's rows, in order. + """ + table, tag_keys, data_tags = row_table # No ``source_info`` argument: the table's own ``_source_*`` columns # pass through, one value per row. return ArrowTableStream(table, tag_columns=tag_keys, data_tags=data_tags) @@ -596,6 +638,13 @@ def _materialize_upstream( """ from orcapod.utils import arrow_utils + if rows and not zero_rows and isinstance(rows, RowsWithTable): + # The rows' own table, built once by the node that returned them: the + # same ``_rows_to_table(rows)`` as below, not built again (ITL-1347). + table, tag_keys, data_tags = rows.row_table + return StaticOutputOperatorPod._as_upstream_stream( + table, tag_keys, data_tags, upstream + ) if rows: table, tag_keys, data_tags = StaticOutputOperatorPod._rows_to_table(rows) if zero_rows: @@ -773,6 +822,31 @@ async def async_execute( await output.close() +class RowsWithTable(list[tuple[TagProtocol, DataProtocol]]): + """Rows of an operator node's run, carrying the table built from them. + + ``row_table`` is ``StaticOutputOperatorPod._rows_to_table`` of exactly these rows: the + table, the user tag keys and the data-tags. An operator node builds it once for the + output it keeps and returns its rows in this form, so whoever rebuilds the rows as a + stream (``_materialize_upstream``) takes the table instead of building it again + (ITL-1347, stage 1). It is a list in every other respect. + + Args: + rows: The rows, in order. + row_table: ``_rows_to_table(rows)``. + """ + + __slots__ = ("row_table",) + + def __init__( + self, + rows: Sequence[tuple[TagProtocol, DataProtocol]], + row_table: tuple[pa.Table, tuple[str, ...], tuple[str, ...]], + ) -> None: + super().__init__(rows) + self.row_table = row_table + + class _RowsOfStream(ArrowTableStream): """Rows standing in for the stream they came from, with its pipeline hash. diff --git a/tests/test_pipeline/test_operator_kept_table_reuse.py b/tests/test_pipeline/test_operator_kept_table_reuse.py new file mode 100644 index 000000000..ea0e46eed --- /dev/null +++ b/tests/test_pipeline/test_operator_kept_table_reuse.py @@ -0,0 +1,181 @@ +"""ITL-1347 stage 1: a successor's input reuses the table its operator node kept. + +An operator node's ``execute`` returns its rows as ``RowsWithTable``, carrying the table +``_rows_to_table`` built for the output the node keeps. The sync orchestrator rebuilds a +successor's input with ``_materialize_upstream``, which now takes that table instead of +building it from the rows again. The governing rule of the spec +(``docs/dev/specs/itl-1347-job-table-transport.md``) is that nothing a run shows may change. +So every successor's input must equal, byte for byte and in identity, the input built from +the same rows as a plain list (the path before stage 1). The test checks that on every +edge of a job that uses every operator kind, over several tag orders, table layouts and tag +roles. These tests are about the orchestrator's internal hand-off, so they wrap it. +""" + +from __future__ import annotations + +import warnings +from collections.abc import Iterator +from typing import Any + +import pytest + +from orcapod import PipelineJob, function_pod +from orcapod.core.operators.static_output_pod import ( + RowsWithTable, + StaticOutputOperatorPod, +) +from orcapod.databases import InMemoryArrowDatabase +from orcapod.errors import ProvisionalHashWarning +from orcapod.operators import MergeJoin, Rejoin +from orcapod.pipeline import SyncPipelineOrchestrator +from tests.test_core.operators.several_items import ( + MAIN, + P, + Q, + Arrangement, + arrangements, + make_source, +) + +ALL_COLUMNS = { + "meta": True, + "source": True, + "system_tags": True, + "context": True, + "content_hash": True, +} + + +@function_pod(output_keys="d1_doubled") +def doubled(d1: int) -> int: + return 2 * d1 + + +def build_job(arrangement: Arrangement) -> Any: + """A job in which every operator kind feeds a successor.""" + main = make_source(MAIN, arrangement) + partner_p = make_source(P) + partner_q = make_source(Q) + job = PipelineJob(name="kept_table_reuse", database=InMemoryArrowDatabase()) + with job: + joined = main.join(partner_p, label="joined") + mapped = joined.map_data({"p1": "p1_renamed"}, label="mapped") + no_nulls = mapped.drop_nulls(["d2"], label="no_nulls") + no_nulls.select_data_columns(["d1", "p1_renamed"], label="after_no_nulls") + grouped = main.group_by(["t1"], label="grouped") + grouped.select_data_columns(["d1"], label="after_grouped") + batched = main.select_data_columns(["d1"]).batch(batch_size=2, label="batched") + batched.select_data_columns(["d1"], label="after_batched") + tagged = main.add_tags(k=1, label="tagged") + doubled.pod(tagged.select_data_columns(["d1"]), label="doubled") + semi = main.semi_join(partner_q, label="semi") + semi.select_data_columns(["d3"], label="after_semi") + merged = MergeJoin()( + main.select_data_columns(["d1"]), + partner_p.map_data({"p1": "d1"}).select_data_columns(["d1"]), + ) + merged.select_data_columns(["d1"], label="after_merged") + rejoined = Rejoin()( + main.select_data_columns(["d1"]), main.select_data_columns(["d3"]) + ) + rejoined.select_data_columns(["d1"], label="after_rejoined") + nothing = main.polars_filter(d1=999, label="nothing") + nothing.select_data_columns(["d1"], label="after_nothing") + return job + + +def _identity(stream: Any) -> tuple[Any, ...]: + return ( + type(stream), + stream.producer, + tuple(id(u) for u in stream.upstreams), + stream.pipeline_hash(), + stream.content_hash(), + stream.keys(), + stream.output_schema(), + stream.data_context_key, + ) + + +@pytest.fixture +def recorded_edges(monkeypatch: pytest.MonkeyPatch) -> Iterator[list[str]]: + """Wrap the orchestrator's input rebuild; check each input against the old path.""" + original = SyncPipelineOrchestrator._materialize_as_stream + reused: list[str] = [] + + def checked(buf: Any, upstream_node: Any) -> Any: + built = original(buf, upstream_node) + plain = StaticOutputOperatorPod._materialize_upstream( # pyright: ignore[reportPrivateUsage] # the path before stage 1 + list(buf), upstream_node + ) + assert _identity(built) == _identity(plain) + built_table = built.as_table(columns=ALL_COLUMNS).combine_chunks() + plain_table = plain.as_table(columns=ALL_COLUMNS).combine_chunks() + assert built_table.schema.equals(plain_table.schema, check_metadata=True) + assert built_table.equals(plain_table, check_metadata=True) + if isinstance(buf, RowsWithTable): + reused.append(upstream_node.label) + return built + + monkeypatch.setattr( + SyncPipelineOrchestrator, "_materialize_as_stream", staticmethod(checked) + ) + yield reused + + +@pytest.mark.parametrize("arrangement", arrangements(MAIN), ids=lambda a: a.id) +def test_every_successor_input_equals_the_rebuilt_one( + arrangement: Arrangement, recorded_edges: list[str] +) -> None: + with warnings.catch_warnings(): + warnings.simplefilter("ignore", ProvisionalHashWarning) + job = build_job(arrangement) + job.run() + # Every operator node with rows handed its kept table on; the one with no rows + # (``nothing``) took the plain path, which gives its zero-row input as before. + assert { + "joined", + "mapped", + "no_nulls", + "grouped", + "batched", + "tagged", + "semi", + } <= set(recorded_edges) + assert "nothing" not in recorded_edges + + +def test_a_held_operator_node_takes_the_plain_path( + recorded_edges: list[str], +) -> None: + """A second run holds every node: buffers are plain lists, inputs as before.""" + with warnings.catch_warnings(): + warnings.simplefilter("ignore", ProvisionalHashWarning) + job = build_job(arrangements(MAIN)[0]) + job.run() + recorded_edges.clear() + # Clear one function node so the second run has something to run, fed by a + # held operator node. + job.nodes["doubled"].clear_cache() + job.run() + assert recorded_edges == [] + + +def test_execute_returns_rows_equal_to_the_plain_list() -> None: + """The rows an operator node returns compare equal to the plain list of its rows.""" + with warnings.catch_warnings(): + warnings.simplefilter("ignore", ProvisionalHashWarning) + job = build_job(arrangements(MAIN)[0]) + job.run() + node = job.nodes["joined"] + upstreams = [ + StaticOutputOperatorPod._materialize_upstream(list(u.iter_data()), u) # pyright: ignore[reportPrivateUsage] # the orchestrator's input form + for u in node.upstreams + ] + rows = node.execute(*upstreams) + assert isinstance(rows, RowsWithTable) + assert rows == list(rows) + table, tag_keys, data_tags = rows.row_table + assert table.num_rows == len(rows) + assert tag_keys == node.keys()[0] + assert isinstance(data_tags, tuple) From de98e05906e3215c2e07e832065dec1e2f381e02 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 01:03:54 -0800 Subject: [PATCH 05/86] docs(dev): spec, job nodes pass streams of Arrow data; channels opened from and closed into streams (ITL-1347, ITL-858) (#475) * docs(dev): spec, job nodes pass tables and record batches, not rows (ITL-1347) Design only: the unit moving between job nodes, sync and async, is a table or record batch; rows exist only where a user function is called; observers and the error policy stay per row; how ITL-845, ITL-1122, async equals sync and ITL-1133 hold; byte-identity proof and a staged plan. Co-Authored-By: Claude Opus 5.5 * docs(dev): record the developer's decisions on the ITL-1347 spec questions Co-Authored-By: Claude Opus 5.5 * docs(dev): ITL-1347 spec folds in the ITL-858 input object; protocol change and call sites Co-Authored-By: Claude Opus 5.5 * docs(dev): ITL-1347 spec, second revision: the stream is the unit and can act as a channel; Arrow terminology Co-Authored-By: Claude Opus 5.5 * docs(dev): ITL-1347 spec, the stream is primary; input and output channels are separate, convertible structures Co-Authored-By: Claude Opus 5.5 * docs(dev): ITL-1347 spec, today vs proposed, alternatives considered, risks and unknowns Co-Authored-By: Claude Opus 5.5 * docs(dev): ITL-1347 spec, barrier vs streaming operators, streaming Join and Rejoin, the order rule Co-Authored-By: Claude Opus 5.5 * docs(dev): ITL-1347 spec, the governing rule, every difference from main, the differential as every stage's gate Co-Authored-By: Claude Opus 5.5 * docs(dev): ITL-1347 spec, the developer's order decisions: async keeps arrival order, Batch streams, async compared as sets Co-Authored-By: Claude Opus 5.5 * docs(dev): ITL-1347 spec, streaming Rejoin under ITL-1355's rule; question 9 resolved Co-Authored-By: Claude Opus 5.5 * docs(dev): ITL-1347 spec approved: record the developer's decisions; log ITL-1357 and ITL-1358 Co-Authored-By: Claude Opus 5.5 * docs(dev): ITL-1347 spec: multiset comparisons, arrival-dependent descendants, e7 narrowed, e8 async side-effect meta, ITL-1357 first finding Co-Authored-By: Claude Opus 5.5 * docs(dev): ITL-1347 spec: arrival-dependent nodes checked against a sync recomputation over their own recorded arrivals Co-Authored-By: Claude Opus 5.5 * docs(dev): ITL-1347 spec: arrival-dependent set from either async run, edge conservation; e8 approved Co-Authored-By: Claude Opus 5.5 * docs(dev): ITL-1347 spec: arrival-dependent nodes recomputed by pinned main's operator; the gate's statement is complete Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Edgar Y. Walker <> Co-authored-by: Claude Opus 5.5 --- docs/dev/design_issues/ITL-1357-JRO1.md | 23 + docs/dev/design_issues/ITL-1358-VST1.md | 27 + .../dev/specs/itl-1347-job-table-transport.md | 1295 +++++++++++++++++ 3 files changed, 1345 insertions(+) create mode 100644 docs/dev/design_issues/ITL-1357-JRO1.md create mode 100644 docs/dev/design_issues/ITL-1358-VST1.md create mode 100644 docs/dev/specs/itl-1347-job-table-transport.md diff --git a/docs/dev/design_issues/ITL-1357-JRO1.md b/docs/dev/design_issues/ITL-1357-JRO1.md new file mode 100644 index 000000000..a74ce2262 --- /dev/null +++ b/docs/dev/design_issues/ITL-1357-JRO1.md @@ -0,0 +1,23 @@ +## `src/orcapod/core/operators/` — join row order + +### JRO1 — Sync `Join`, `MergeJoin` and `Rejoin` take their row order from Polars' unspecified inner-join order +**Status:** open +**Severity:** low +**Issue:** ITL-1357 + +The sync paths of `Join` (`join._inner_join`, `join.py:94`, which `MergeJoin` shares) and +`Rejoin` (`_rejoin_pair`, `rejoin.py:376`) pair rows with a Polars inner join on a key frame +of prepared keys and row numbers, without `maintain_order`, then take every value from the +Arrow inputs by row number. Polars does not guarantee the row order of such a join, so a +Polars upgrade or a different thread count could reorder a join node's rows, and its stored +operator table, on the sync path. Values and hashes would not move: hashes are per row. +`SemiJoin` already sets `maintain_order="left"` (`semijoin.py:242`). + +The developer has said row order is not critical (2026-11-22), so this is low priority. +Found while writing the ITL-1347 spec (`docs/dev/specs/itl-1347-job-table-transport.md`, +question 10). + +What to do: measure whether `maintain_order="left_right"` gives exactly today's row order on +the test suite and on the ITL-1347 differential, at one Polars thread and at the default +(stage 0 of ITL-1347 reports it). If it does, set it explicitly in every key-frame join. If +it does not, report the differences for a decision: a change of stored row order needs one. diff --git a/docs/dev/design_issues/ITL-1358-VST1.md b/docs/dev/design_issues/ITL-1358-VST1.md new file mode 100644 index 000000000..d6a70952e --- /dev/null +++ b/docs/dev/design_issues/ITL-1358-VST1.md @@ -0,0 +1,27 @@ +## `src/orcapod/core/operators/` — Async execution + +### VST1 — Operators keep state written at validation: one operator object on two streams can use the other stream's values +**Status:** open +**Severity:** medium +**Issue:** ITL-1358 + +Some operators store values computed while validating an input on the operator object +itself and read them later on the async path, where no stream is at hand: + +- `SemiJoin._validated_common_keys` (`semijoin.py:287`, read at `:306` and `:381`); +- `Index._element_arrow_type_fallback` (`index.py:82`, `:126`). + +One operator object applied to two streams can then use the shared keys or the fallback +type of the stream validated last (ITL-858 inventory, section 1.2). Found again while +writing the ITL-1347 spec (`docs/dev/specs/itl-1347-job-table-transport.md`, difference e6). +It is not yet confirmed by a reproducer. + +What to do: + +- Write a reproducer: one `SemiJoin` instance validated on stream B, then run async over + stream A with other shared tag keys; likewise for `Index`. It fails on `main` if the bug is + real. +- Inventory every operator that writes instance state during validation. +- Derive such values from each input's description when they are used, with no state + written at validation. Stage 5 of ITL-1347 does this as part of reading descriptions; the + reproducers then pass, and sync results are unchanged. diff --git a/docs/dev/specs/itl-1347-job-table-transport.md b/docs/dev/specs/itl-1347-job-table-transport.md new file mode 100644 index 000000000..ce0097d17 --- /dev/null +++ b/docs/dev/specs/itl-1347-job-table-transport.md @@ -0,0 +1,1295 @@ +# Job nodes pass streams of Arrow data, not rows (ITL-1347, with ITL-858) + +Status: approved by the developer (2026-11-22). No code changes with it. Written against +`origin/main` 8c6fc4f5 (2026-11-22); the work lands on the integration branch +`eywalker/job-speed`. Every stage is tracked under ITL-1347, one PR per stage against `eywalker/job-speed`. + +Revisions, all on 2026-11-22: +- The ITL-858 input object was folded in, with the protocol change and its call sites. +- Second revision: the developer's terminology ("Arrow table", "Arrow record batch"), and + streams with channels. +- The developer's clarification: the stream is primary and owns the description. Channels + are separate structures, opened from a stream and closed into one. +- Third revision: the governing rule (results identical to `main`), every difference from + `main` listed with its bug, and the differential as every stage's gate. +- Fourth revision, the developer's decisions on order: row order is not critical within a + stream or channel. Async runs keep arrival order, as on `main`; `Batch` grouping by + arrival is accepted; column order is not a goal. The order rule of the third revision is + dropped. +- Fifth revision: `Rejoin`'s new rule (ITL-1355) resolves question 9. `Rejoin` matches on + every shared column, never refuses on data, and drops unmatched rows. + +Terms used throughout: +- **Arrow table**: a `pyarrow.Table`. +- **Arrow record batch**: a `pyarrow.RecordBatch`. +- **Stream**: an Orcapod stream (`StreamProtocol`). +- **Channel**: an async, single-pass carrier of Arrow record batches. + +## The governing rule + +Developer, 2026-11-22: "We must ensure, above all, that all computations results are +identical to as before unless explicit bug/incorrectness in computation is discovered." + +- **Sync path.** Every observable result of the branch equals pinned `main`, byte for + byte: + - values, types, nullability and column order; + - the row order of every kept, stored and returned Arrow table; + - content and pipeline hashes, record ids; + - stored paths and stored rows; + - error types and messages. +- **Async path.** It equals the sync path as a multiset of rows (unordered, each row counted + as often as it occurs), with columns matched by name. + Row order is not compared: the developer, 2026-11-22, "generally order of rows shouldn't be + considered critical". The async path also equals `main`'s async path as a multiset of rows. +- **The only allowed difference** is one that fixes a named bug in `main`. Each is listed in + "Every difference from `main`" below, with its reproducer, and approved by the developer + one by one. +- **Speed work never changes a result as a side effect.** Every section of this spec is + subordinate to this rule. +- **No row below changes a sync-path result of `main`.** Every difference is on the async + path or the failure path. + +## The rule + +Developer, 2026-11-22: Orcapod was always meant to keep data as Arrow (or Polars) tables as +long as possible and to avoid converting rows to objects and back. This spec makes that the +rule for the job layer as a whole. + +- **The stream is the primary concept, and it owns the description**: schemas, Arrow schema, + keys, data context and pipeline hash. Sync code receives streams and produces streams. +- **Channels serve async computation, as separate structures.** + - A stream can open an **input channel** for downstream async compute: a single-pass, + back-pressured reader of Arrow record batches that refers to its stream for the + description. + - A node's async output is written into an **output channel**. When its producer closes + it, it yields an ordinary stream backed by an Arrow table, with the same description. + - The conversions between streams and channels are defined in one place. + + The developer, 2026-11-22: "I don't think data structure wise a truly synchronous + table/list must equal the async channel but given how closely related they are, I was + thinking they ought to be consolidatable." +- **A row exists only where a user's function is called**: a function pod's function, or a + side effect's delivery. Even there, the node reads its input as Arrow data and writes its + results as Arrow data. +- **Observers and the error policy stay per row.** They are told about each row, and a + failing row is skipped or raised, as today. The transport underneath is not rows. + +## Why the job layer is per-row today + +From the ITL-1347 comment: + +- **March 2026, PLT-922 (the orchestrators).** The node execution protocol was defined per + row: + - `execute()` returns `list[tuple[Tag, Data]]`, and `async_execute` reads and writes + channels of `(Tag, Data)`. + - The sync orchestrator keeps a buffer of row tuples per node and rebuilds a stream for + each successor (`_materialize_as_stream`). + - Every operator node turns its result's Arrow table back into rows. + + This served per-row async streaming, concurrent function calls, per-row observer hooks + and the per-row error policy. Plain streams never adopted it. +- **November 2026: correctness fixes kept the row protocol and made each row costlier.** + - ITL-845: `_rows_to_table` keeps each row's source info. + - ITL-1122: large-type normalization at stream construction, paid three times per row + datagram. + - The rule that async output rows equal the sync rows. +- **Channels carry rows and nothing else (ITL-858).** So async operators rediscover from + rows what the sync path is told. Where rows cannot answer, the two paths diverged: + - key types on an empty input (ITL-856); + - column order (ITL-854, ITL-1249); + - data context (ITL-844, ITL-951); + - zero-row results (ITL-865, ITL-912); + - system-tag names after a non-source input (ITL-906). + +## What it costs + +The ITL-1345 profile (workshop-scale notebook on 0.4.0rc1, local Delta copy, no network): + +| Measure | Value | +|---|---| +| Same pipeline as plain streams | 1.9 s | +| As a `PipelineJob`, warm / cold `job.run()` | 44.7 s / 46.8 s, identical rows | +| Warm run: building a `(Tag, Data)` datagram per row passed between job nodes | ~58% (~26 s) | +| Warm run: rebuilding Arrow tables from those rows (`_rows_to_table`, `_materialize_as_stream`) | ~32% (~14 s) | +| Warm run: operator compute / reads / all hashing | ~8% / ~1% / ~0.3% | +| `Data.__init__` calls; `normalize_schema_to_large_types` calls | 121,139; 363,466 (three per row) | +| One source of 63,349 rows: `as_table()` / `list(iter_data())` | 0.29 s / 9.1 s | + +About 90% of a warm run converts Arrow tables into rows and back. + +### Where rows are made and unmade today + +Sync orchestrator (`SyncPipelineOrchestrator.run`): + +1. **Source job node**: `list(self.iter_data())`, one datagram per row. A narrower source + given in the declared form gets a second one (`_declared_row`). +2. **Every edge** (`_materialize_as_stream` → `_materialize_upstream`): the successor's input + is `R(rows)`, wrapped as the predecessor's stream (`_as_upstream_stream`). A node with *k* + successors is rebuilt *k* times. +3. **Operator job node**: the operator computes an Arrow table, then + `list(result.iter_data())` makes rows of it, and `_kept_output` makes an Arrow table of + them again. +4. **Function job node**: iterates its input's rows; loads stored hits as one datagram per + stored row; builds each result as a `Data`. +5. **Side-effect job node**: iterates its input's rows and passes them on. +6. **Held nodes** (`plan_run`): `list(node.iter_data())`, and a second pass to count. + +The async orchestrator does the same with channels of rows. Barrier operators rebuild +inputs with `R` (`_materialize_input_stream`), and operator nodes rebuild their output with +`R` (`_materialize_to_stream`). + +## Definitions + +- **R(rows)**: `StaticOutputOperatorPod._rows_to_table(rows)`, the Arrow table today's code + builds from rows. It is the oracle of the proofs below. +- **Row-built form F**: the one function that turns a node's Arrow table into `R` of that + table's rows, without making the rows. In order: + 1. Drop the context, meta (`__`) and `_content_hash` columns. A row's `Data.as_table` + leaves them out, and no operator carries meta columns (ITL-1080). + 2. Drop the data-side copy of each data-tag. + 3. Map `null` to `large_string`, as a datagram's normalization does today + (`Datagram._init_from_table`; whether it should is ITL-1319's decision). + 4. Place the columns in row order: user tags, system tags, data, source info + (`_in_row_order`, ITL-1131). + 5. On a complete Arrow table only, never on one Arrow record batch: flag each source-info + field nullable only when a token is null (`_flag_source_info_nullability`). +- **Transport columns**: the columns passed between nodes. They are the columns of F: user + tags, system tags, data and source info, in row order, with no context and no meta column. + +## The design: the stream is primary; channels are opened from it and closed into it + +### The stream owns the description + +A stream's description is its existing members plus one new one, `arrow_schema()`: + +| Member | Today | What it answers | +|---|---|---| +| `keys()`, `output_schema()` | on `StreamProtocol` | names and Python types, in key order | +| `data_context_key` | on every stream (`hashing_protocols.py:19`) | the stream's data context | +| `pipeline_hash()`, `content_hash()` | on `StreamProtocol` | as today | +| `producer`, `upstreams` | on `StreamProtocol` | as today | +| data-tags | `stream_data_tags(stream)`, from `keys()` | unchanged; no new member | +| **`arrow_schema()`** (new) | – | the Arrow schema of the transport columns: types, nullability and field metadata of the rows, in row order. It tells which system-tag and source-info columns are present, and that no meta column is | + +None of these reads, computes or polls a row. A job node is a stream today, so a node owns +its own description, also while it runs. + +**Where `arrow_schema()` comes from now.** From `typed_zero_row_table` +(`core/streams/base.py:116`, ITL-912), put through F's steps 1, 2 and 4 and normalized to +large types as `typed_zero_row_input` does. That is exactly the schema of today's zero-row +input (`_zero_row_input`) without its context column. + +- A source answers from the Arrow table or schema it holds. +- An operator node applies its operator to its inputs' zero-row Arrow tables, which + processes no data. +- A function node answers with its input's tags and declared outputs + (`function_zero_row_table`). +- A loaded node answers from the Arrow type texts its saved file holds (ITL-640). + +A stream that cannot type itself without rows answers from its Python schema, through the +data context's converter. These are an unbound slot, and a `PollingSource` never polled +(ITL-1089). Such a stream says so through `arrow_types_declared` (a `StreamBase` property). +A run checks its sources first (ITL-1102), which polls them. + +**ITL-1307 later.** When `Schema` carries its Arrow schema, `arrow_schema()` reads the two +schemas plus the system-tag and source-info fields, in one place (`StreamBase`). + +Two exceptions keep today's bytes: +- **Source-info nullability** is decided by a complete Arrow table's values (F step 5). + `arrow_schema()` states those fields nullable (question 5). +- **`null` columns.** Rows carry `large_string`, and a zero-row Arrow table carries `null`, as + today (ITL-1319). + +### Sync: streams in, a stream out + +A node's `execute` receives streams and returns its **output stream**: +`_as_upstream_stream(F(node's Arrow table), node)`. + +- It takes the node's producer, upstreams, pipeline hash and data context. For a node + without a producer it is a `_RowsOfStream`. +- With no rows, it is today's zero-row input (`_zero_row_input(node)`). +- That is exactly what each successor receives today, so a successor's input is unchanged by + construction. + +The orchestrator passes each output stream to its successors as it is, and a fan-out passes +the same stream to every successor. A stream on the sync path is always complete: +`as_table()`, `iter_data()` and `head()` behave as for any `ArrowTableStream`. + +### Async: input channels opened from streams, output channels closed into streams + +Two separate structures, in `src/orcapod/channels.py`. They consolidate with the existing +generic channel protocols: an input channel is a `ReadableChannel[pa.RecordBatch]`, and an +output channel a `WritableChannel[pa.RecordBatch]`. + +```python +class InputChannel(ReadableChannel[pa.RecordBatch], Protocol): + """A single-pass, back-pressured reader of a stream's Arrow record batches.""" + + @property + def stream(self) -> StreamProtocol: ... # the description; never restated here + async def receive(self) -> pa.RecordBatch: ... # raises ChannelClosed at the end + def __aiter__(self) -> AsyncIterator[pa.RecordBatch]: ... + async def collect(self) -> list[pa.RecordBatch]: ... # as every ReadableChannel + async def to_stream(self) -> StreamProtocol: ... # reads to the end: what it delivered, as a stream + async def close(self) -> None: ... # stop reading; the producer stops waiting + + +class OutputChannel(WritableChannel[pa.RecordBatch], Protocol): + """The producer side of a node's async output.""" + + @property + def stream(self) -> StreamProtocol: ... # the producing node: the description + async def send(self, batch: pa.RecordBatch) -> None: ... + async def close(self) -> None: ... + def fail(self, error: BaseException) -> None: ... + def open_reader(self) -> InputChannel: ... # one per consumer, before the first send + def result(self) -> StreamProtocol: ... # after close: the node's output stream +``` + +- **Opening an input channel from a stream.** `stream.open_channel()` is new on + `StreamProtocol` and implemented once in `StreamBase`. It returns an `InputChannel` that + delivers that complete stream's transport columns, as its Arrow table's record batches. + Several channels can be opened on one stream, each with its own position. A held node's + output stream feeds async successors this way. +- **The producer side.** The orchestrator makes one `OutputChannel` per node that runs, + before any task starts: `OutputChannel(node, retain=..., buffer_size=...)`. The node writes + Arrow record batches into it. Each successor gets `output.open_reader()`, an `InputChannel` + whose `stream` is the producing node, so its description is known before the first batch. +- **Closing into a stream.** After `close()`, `output.result()` is the node's output stream: + an ordinary stream backed by an Arrow table, with the node's description and identity. It + is the same object the sync path would return. `input_channel.to_stream()` gives the same + kind of stream from what the channel delivered. +- **Checks.** `send` checks each Arrow record batch's schema against `stream.arrow_schema()` + (with the two exceptions above), once per batch and always on (ITL-858 decision 4). + +### What lives where + +| Member | Stream | Input channel | Output channel | +|---|---|---|---| +| keys, schemas, Arrow schema, data context, pipeline hash, content hash, producer, upstreams | yes; owned here | no; read through `channel.stream` | no; read through `channel.stream` | +| `as_table()`, `iter_data()`, `head()`, re-reading | yes | no | no | +| `open_channel()` | yes | – | – | +| `receive()`, `async for`, `collect()`, `to_stream()`, `close()` | no | yes, single pass | no | +| `send()`, `close()`, `fail()`, `open_reader()`, `result()` | no | no | yes | +| modified time, staleness | yes (a node's, as today) | no | no | + +### The conversions, in one place + +`src/orcapod/channels.py` holds every conversion between streams and channels: + +| Conversion | Function | Used by | +|---|---|---| +| stream → input channel | `channel_from_stream(stream, buffer_size)`, called by `StreamBase.open_channel()` | held nodes feeding async successors; tests; any async consumer of a complete stream | +| output channel → stream | `stream_from_batches(stream, batches)`, called by `OutputChannel.result()` | every node's async output | +| input channel → stream | `stream_from_batches(channel.stream, batches)`, called by `InputChannel.to_stream()`: the batches it delivered, in arrival order | barrier operators; operators that need all of an input | + +`stream_from_batches` is the only place a stream is made from Arrow record batches. It +concatenates them, applies F step 5, and wraps the result as `_as_upstream_stream` does for +the describing stream. With no batch, it is the describing stream's zero-row input. + +### One operator body for both paths + +An operator reads its description from its inputs' streams: on the sync path the stream +itself, on the async path `channel.stream`. So validation, canonical input order, key-type +checks and zero-row results are one implementation. For example, +`validate_inputs(*(c.stream for c in channels))` is the sync call. + +- **A barrier operator, async**: + `streams = await asyncio.gather(*(c.to_stream() for c in channels))`, then + `static_process(*streams)` (the sync call), then it writes the result's Arrow record + batches. +- **A per-row operator** (select, map, `AddTags`, `DropNulls`, `Index`, `Pick`) has one rule, + `_apply(arrow_table, stream)`. Sync applies it to `stream.as_table()`. Async applies it to + each Arrow record batch, with `channel.stream` as the description. +- **`Join`, `MergeJoin`, `Rejoin` and `SemiJoin`, async**: check key types from + `channel.stream.arrow_schema()` before the first batch (ITL-856), order inputs with the + sync method, and stream as below. + +### Barrier or streaming: every operator + +The developer, 2026-11-22: `Join` and `Rejoin` must not be barrier operators; both can run +fully async on Arrow record batches. The test for each operator: can each output row be +decided from the input rows seen so far? If so, the operator streams. If it needs all of an +input, it is a barrier. Row order within a stream or channel is not critical (developer, +2026-11-22), so an operator whose groups follow arrival (`Batch`) keeps `main`'s form. + +| Operator | Async form | Why | +|---|---|---| +| `SelectTagColumns`, `SelectDataColumns`, `DropTagColumns`, `DropDataColumns`, `SelectColumns`, `DropColumns`, `MapTags`, `MapData`, `MapColumns`, `AddTags`, `DropNulls`, `Index`, `Pick` | streaming, per Arrow record batch | each output row comes from one input row, and its content does not depend on other rows | +| `Join` | streaming: a symmetric hash join | an output row is a pair of matching rows; it can be emitted as soon as both have arrived | +| `MergeJoin` | streaming, as `Join` | the same inner join (`join._inner_join`). Each matched pair's lists are built from that pair alone, in argument order | +| `Rejoin` | streaming: a symmetric match on every shared column (ITL-1355), with matched rows removed from both sides | an output row is the set of one origin row's rows from every input; each row matches at most once | +| `SemiJoin` | streaming on the left. A left row is emitted as soon as its key is among the right rows seen so far; undecided left rows wait for the right input to close | whether a left row is kept depends on the whole right input only when no match has been seen yet | +| `GroupBy` | barrier | a group needs all its members. Its output does not depend on input order (members are ordered by tags, record id and source id; groups by key) | +| `Batch` | streaming, per group of `batch_size` arrivals, as on `main`; a barrier for `batch_size=0` | groups consecutive arrivals. When the input arrives in another order than on sync, its groups differ from sync: accepted by the developer ("This difference is totally fine in Batch for sync and async") | +| `PolarsFilter` | barrier over arrival order, as on `main` | a predicate may be a window or whole-table expression (`pl.col(...).rank()`), so a row cannot be decided alone. Such a predicate over an input that arrived out of order selects other rows than sync: the same class as `Batch`, kept as `main` | +| one-input `Join` / `Rejoin` | pass-through | as today | + +On `main`: +- `Join`'s async path already streams: a symmetric hash join, row by row + (`join.py:669`, `_binary_streaming_join`), with N inputs as a staggered chain in canonical + order. +- `Rejoin` is a barrier (`rejoin.py:416` delegates to the default). +- `Batch` streams per batch over arrival order, and is a barrier for `batch_size=0` + (`batch.py:211`). + +The change: `Rejoin` and `MergeJoin` stream. `Batch` and `PolarsFilter` keep `main`'s async +form. + +#### Streaming `Join` and `MergeJoin` + +- **Hash tables.** Each input keeps an accumulating Arrow table of its rows and a key frame + of its prepared keys (`arrow_keys.polars_ready`, as the sync join prepares them). The key + frame holds the shared tag keys and row numbers only. +- **Probing.** When an Arrow record batch arrives on one input, its key frame is joined + (Polars, keys and row numbers only, as `_inner_join` does) with the other input's + accumulated key frame. The matches are emitted at once, every value taken from the two + Arrow tables by row number (`take`), so values are the inputs', bit for bit. The batch is + then appended to its own side. +- **Matching is vectorized**, one join per arriving batch, never per row. Each pair is + emitted exactly once: by whichever of its two rows arrives second. +- **N inputs**: a staggered chain of binary joins in canonical order, as today. Each link is + an `OutputChannel` whose `stream` is that pair's `zero_row_result`. +- **System-tag renaming** uses each input's `stream.pipeline_hash()` and position, as the + sync path does. +- **`MergeJoin`** builds each emitted pair's merged lists from the pair's two rows + (`aggregated_list_array` over the taken values), in argument order. + +#### Streaming `Rejoin` + +It follows `Rejoin`'s rule as ITL-1355 sets it on `main` (developer, 2026-11-22). That +change lands on `main` separately, before stage 5: +- system tags are assumed unique by construction (ITL-1356 makes record ids unique at the + source); +- `Rejoin` is an inner join on every column its inputs share: the system-tag columns, shared + user tags, the data context, and a shared data-tag's source info; +- equality is `Join`'s: NaN equals NaN, and `-0.0` equals `0.0`. The output keeps the first + input's bits; +- each row matches at most once; +- a row that matches nothing is dropped. A differing shared value is a non-match, never an + error. + +How it streams: + +- **Remaining sets.** Each input keeps an Arrow table of its rows not yet matched, with a key + frame of its shared columns (sorted names, `arrow_keys.polars_ready`). Unlike `Join`, + which holds every row of both sides, a matched row is removed from its remaining set, so + the memory held is the unmatched rows only. Removal is a mask over row numbers; the table + is compacted when the removed share passes a threshold, so a batch never copies the whole + table. +- **Matching an arriving Arrow record batch**, vectorized and never per row: + 1. The batch's key frame is joined (Polars, keys and row numbers only) with the other + side's remaining key frame **on every shared column**. That gives the matches under + `Join`'s equality. + 2. Each matched pair is emitted, built as `_rejoin_pair` builds it (the first input's copy + of each shared column, every value taken by row number), and both rows leave their + remaining sets. + 3. The batch's unmatched rows join their side's remaining set. +- **The warning, per batch.** A second join of the same batch, on the system-tag columns + only, against the other side's remaining rows finds the pairs that match on system tags. + Pairs found by this join but not by the first one matched on system tags and differed on + another shared column. For each shared column outside the system tags, one vectorized + comparison over those pairs, with `Join`'s equality on the prepared keys, names the + columns that differed. The operator issues its warning once per operator and set of + columns, as ITL-1355 specifies (after the pattern of `SemiJoinIgnoredColumnWarning`). + These rows are non-matches: they stay in their remaining sets. +- **Early release.** When one input closes, the other input's remaining rows can never match + anymore (nothing will arrive to match them), so they are dropped at once. From then on, an + arriving row from the open input either matches the closed input's remaining rows or is + dropped at once. So after one input closes, only the closed input's unmatched rows are + held, and that set only shrinks. When both inputs close, whatever is left is dropped. +- **A differing data context.** The data context is per stream. In a job, every row of an + edge carries its producing node's context. So inputs whose descriptions name different + contexts can match nothing. The operator knows this before the first batch: it reads every + input to its end (ITL-1075-AH1), emits nothing, and warns once, as the rule's non-match. +- **Checks: description-only, before the first batch.** These are the same system-tag names + on every input (`_require_same_system_tags`), the shared tags' Arrow types + (`require_shared_arrow_type`, `require_matchable_key`), and disjoint data columns. + `Rejoin` raises on nothing else, so it never refuses after rows have flowed. +- **N inputs** chain pairwise in canonical order, as the sync `static_process` does. Each + link applies the same rule. +- **Duplicates.** If system tags are not unique after all (a source with non-unique + `record_id_columns`), "match once" pairs duplicates in arrival order, which can differ + between sync and async (risks; ITL-1356 removes the case). + +### Row order + +The developer, 2026-11-22: "For async absolutely fine that rows are stored in arrival order +-- generally order of rows shouldn't be considered critical", and "row orders are also not +critical within stream/channel". + +- **Sync path**: every row order stays exactly as on `main`. Nothing in the design needs to + change it, and keeping it keeps the differential against `main` exact. +- **Async path**: rows in flight, and what a node keeps, stores and gives as `result()`, + are in arrival order, as on `main` (`operator_node.py:2231` keeps arrival order today). + There is no recompute at close, and nothing is retained only for ordering. Retention + follows `main`'s rules (`materialize_results` included). +- `OutputChannel.result()` is the concatenation of the Arrow record batches the node sent, + in the order sent. +- `InputChannel.to_stream()` reads its channel to the end and returns the concatenation of + the batches it delivered, in arrival order, as a stream with the producer's description + and identity (`stream_from_batches`). +- Async results are compared with sync as a multiset of rows (row order ignored, duplicates + counted), with columns matched by name. + +### The hard semantics + +| Question | Rule | +|---|---| +| **Re-reading** | A channel is single-pass. To re-read, go back to a stream: the complete stream the channel was opened from, or the stream `result()` / `to_stream()` gives. A stream is always re-readable. | +| **When batches are retained** | An `OutputChannel` made with `retain=True` keeps every Arrow record batch it was sent, so that `result()` can give the output stream. Retained: every operator, function and side-effect node, which keep their output today; the result stream becomes that kept output, so nothing is held twice. Also retained: every node when `materialize_results=True` (the default), because `node_outputs` holds each output. Not retained (`retain=False`): only a source's output when `materialize_results=False`. Its `result()` then raises, and memory is bounded by the readers' queues. | +| **Memory bound** | Each input channel queues at most `buffer_size` Arrow record batches. With `retain=True` the output channel holds the node's whole output, which today's code already holds. A barrier operator's `to_stream()` holds its whole input, as today. | +| **Several readers (fan-out)** | One input channel per consumer, each with its own position: `open_reader()` on an output channel, or `open_channel()` on a stream. With `retain=False`, `send` waits until every reader's queue has room, so the slowest reader sets the pace, as today's `BroadcastChannel` does. With `retain=True`, readers read the retained list at their own position, and `send` never waits. | +| **Reading to the end (ITL-1075-AH1)** | Every input channel is read to its end or closed; `close()` unregisters it. As today, REPLAY reads and discards its inputs while it sends, and `SemiJoin` reads its left input while it collects its right one. The ITL-1075 deadlock tests run with one-row batches as well as full ones. | +| **Late readers** | `open_reader()` after the first `send` replays the retained batches and continues when `retain=True`. Otherwise it is refused (`ValueError`). The orchestrator opens every reader before any task starts. `open_channel()` on a stream works at any time. | +| **Sync reads while a node runs** | There is no open stream: a node's output stream exists only once its output channel closes. Reading the node itself (`as_table()`, `iter_data()`, `head()`, the preview) follows today's rule for a job node whose run has not completed: zero rows typed by its schema, status `not_computed`, never computing and never waiting (ITL-1095, ITL-991). Nothing blocks, and nothing new raises. | +| **Identity** | A channel has no identity. Its `stream` does: the producing node, or the stream it was opened from. `result()` and `to_stream()` give streams with exactly today's successor-input identity (`_as_upstream_stream`). Nothing about the transport enters a hash: not `retain`, not the buffer size, not batch boundaries, not the reader. | +| **Producer failure** | The producing node's `finally` calls `output.fail(error)`, where it closes its output today. Every reader's next read raises `UpstreamFailedError` naming the node, never a normal end, so a barrier operator never computes over a partial input. The run raises the producer's own error, as today: the failure selection (`async_orchestrator.py:708` `_single_failure`, `:742` `_single_database_error`) skips `UpstreamFailedError`. | +| **Cancellation** | A cancelled producer fails its output channel with the cancellation. A cancelled reader closes its input channel. | +| **Close** | `close()` after the last `send` completes the output. A second `close()` does nothing, and `send` after `close` raises. A zero-row output is a close with no batch: `result()` is the zero-row stream typed by `stream.arrow_schema()`, never by rows. | + +## Today vs proposed + +Each concern, with where it lives today on `origin/main` 8c6fc4f5. + +| Concern | Today | Proposed | +|---|---|---| +| **Data unit** | Rows: `list[tuple[Tag, Data]]` per node (node protocols `node_protocols.py:45`–`:175`; the sync buffers, `sync_orchestrator.py:101`–`:141`); async channels of rows | A stream (sync). Arrow record batches through channels (async) | +| **Description** | Sync: the stream's members, with Arrow types from `typed_zero_row_table` (`core/streams/base.py:116`). Async: only `input_pipeline_hashes` (`static_output_pod.py:728`, `base.py:207`, `:321`); everything else is read from rows | The stream's members plus `arrow_schema()`, on both paths. Async reads it through `channel.stream` | +| **Sync input** | Rebuilt from the predecessor's rows for each successor: `_materialize_as_stream` (`sync_orchestrator.py:206`) → `_materialize_upstream` (`static_output_pod.py:570`) → `_rows_to_table` (`:304`) | The predecessor's output stream, passed as it is | +| **Sync output** | A row list: a source's `list(self.iter_data())` (`source_node.py:1191`); an operator's `list(result.iter_data())` plus `_kept_output` (`operator_node.py:1647`, `static_output_pod.py:428`); a function node's appended pairs (`function_node.py:2485`) | The node's output stream, `_as_upstream_stream(F(Arrow table), node)` | +| **Async input** | A row `ReadableChannel` per edge (`async_orchestrator.py:230`–`:250`, `:294`, `:320`, `:340`) | An `InputChannel` opened from the predecessor's `OutputChannel`, or from a held predecessor's stream | +| **Async output** | A row `WritableChannel`. An operator node forwards through an intermediate channel and collects every row (`operator_node.py:2218`, `:2231`), then rebuilds them (`_materialize_to_stream`, `static_output_pod.py:543`) | An `OutputChannel`; `result()` after close is the output stream | +| **Fan-out** | Sync: one rebuild per successor (`sync_orchestrator.py:110`, `:123`). Async: `BroadcastChannel` (`async_orchestrator.py:239`, `channels.py:247`) | Sync: the same stream for every successor. Async: one reader per successor on one `OutputChannel` | +| **Held nodes** | `list(node.iter_data())`, then a second pass to count (`node_run.py:341`–`:346`). Async: `_send_held` re-sends the rows (`async_orchestrator.py:651`), and `_drain` reads inputs (`:645`) | The held node's output stream. Async successors open channels on it. Counts are read without rows | +| **Observers** | Per-row hooks with the row's datagrams (`function_node.py:2579` `on_data_start`, `:2606`/`:2614` `on_data_crash`; side effects per row, `side_effects.py:403`) | The same hooks and order, with `RowView`s that build a datagram only when read | +| **Error policy** | Per row in the function node's loop (`function_node.py:2628` `fail_fast`; a failed row is not appended) and per delivery | Per call, as today; a failed row is left out by mask | +| **Zero rows** | Sync: `_zero_row_input` (`static_output_pod.py:476`). Async: an operator node records rows through `_InputTap` (`operator_node.py:109`) to rebuild empty inputs (`:2275`); barrier operators emit nothing (ITL-865 narrow fix) | Sync: the same zero-row stream. Async: `to_stream()` of an empty channel gives that same stream, typed by `arrow_schema()` | +| **Async row order** | Rows flow in arrival order. `Join` streams in match order (`join.py:669`), and `Rejoin` is a barrier (`rejoin.py:416`). The async operator node keeps and stores rows in arrival order (`operator_node.py:2231`), so they equal sync only as a multiset, in a scheduling-dependent order | As on `main`: arrival or match order, in flight and in what a node keeps and stores (multiset-equal to sync; accepted by the developer). `Join`, `MergeJoin`, `Rejoin` and `SemiJoin` stream; `Batch` streams by arrival as on `main`; `GroupBy` and `PolarsFilter` are barriers | +| **Identity** | The successor's input takes the predecessor's identity: `_as_upstream_stream` (`static_output_pod.py:634`), or `_RowsOfStream` without a producer (`:779`). An async barrier rebuild takes `input_pipeline_hashes` (`_materialize_input_stream`, `:689`) | Output streams are built by the same `_as_upstream_stream`. Channels have no identity | +| **Memory** | Row objects held in several places: the sync buffers (`sync_orchestrator.py:101`), `_CollectingWriter` (`async_orchestrator.py:799`), an operator node's `collected` list plus its kept stream (`operator_node.py:2231`), a function node's `_cached_output_datas` (`function_node.py:1430`), a side effect's `_held_rows` (`side_effects.py:1103`). Channel buffer: 64 rows | Arrow tables in the same places. A retained output channel's result is the node's kept output, not a second copy. Input channel buffer: `buffer_size` Arrow record batches | + +## Alternatives considered + +| | Stream primary, separate channels (proposed) | (a) Two protocols, `TableInput` + `BatchInput` (first revision) | (b) One class that is both (second revision) | +|---|---|---|---| +| Where the description lives | on the stream only; a channel refers to it | a separate `StreamDescription` that both protocols repeat | on the one class | +| What sync code receives | streams | `TableInput` (a stream) | streams | +| What async code receives | input channels, each referring to its stream | `BatchInput` | streams in a "channel-fed" state | +| States a stream can be in | complete only | complete only | open, complete, consumed, failed | +| Sync read of data still being produced | impossible: no stream exists yet, and the node reads as not run | impossible by type | possible to attempt; must raise | +| Re-reading | go back to the stream | `materialize()` | the same object, if retained | +| Conversions | three, in `channels.py` | `materialize()` only | inside the one class | +| Fits the existing channel protocols | yes: `ReadableChannel` / `WritableChannel` of Arrow record batches | no: a new protocol | no | +| Complexity | two small classes, plus `open_channel()` and `arrow_schema()` on streams | two protocols plus a description protocol | one class with four states, and five members on `StreamProtocol` | +| Operator written once | yes: the description is always a stream (`channel.stream`) | yes, through the description protocol | yes | + +The proposed form keeps what the second revision gained: +- one description; +- the sync operator code reused on the async path; +- a node's output as an ordinary stream. + +It also removes the second revision's open and consumed stream states, and their raising +sync reads. Nothing blocks it. + +The four alternatives, each with what it gains, what it costs, and why it was not chosen: + +| Alternative | Gains | Costs | Why not chosen | +|---|---|---|---| +| **(a) Two protocols** (`TableInput`, a stream; `BatchInput`, explicitly not one; a shared `StreamDescription`) | The split is visible in the types. An async input cannot be read synchronously by mistake | A third protocol repeats what a stream already answers. Operators are written against the description protocol rather than streams. A `NodeTable` wrapper is needed for outputs | The developer prefers the stream as the primary concept that owns the description. The proposed form keeps (a)'s safety, since no open stream exists, with one fewer type | +| **(b) One class that is both** (a stream that is fed by and read as a channel) | One type for everything. Sync code runs on async data once it is complete | Four states (open, complete, consumed, failed) on one class. Sync reads must raise on an open stream. Five new members on `StreamProtocol`. It blurs the line between an Arrow table and a queue, the hazard ITL-858 named | The developer: "I don't think data structure wise a truly synchronous table/list must equal the async channel". The proposed form gives the same reuse with separate, convertible structures | +| **(c) Rows with cheaper datagrams only** (ITL-1348-style: no per-row normalization or `prepare_prefixed_columns`, rows built through a trusted path) | The smallest change, with no protocol change and byte identity easy to keep. ITL-1348 estimates about 10 s of the 45 s (the normalizations and `prepare_prefixed_columns`). It is in progress now | 121,139 datagrams are still built, `R` still concatenates one-row Arrow tables on every edge, and fan-out still rebuilds per successor. Its ceiling is the normalization share, not the ~40 s conversion share. The ITL-858 divergences stay, because channels still carry only rows | Not a replacement but a complement. It lands first and keeps paying wherever rows remain: function-node misses, observers that read a `RowView`, side-effect deliveries. It cannot bring a job near the plain-stream floor (1.9 s) | +| **(d) Polars-backed nodes** (nodes pass Polars data frames or lazy frames; operators fused into Polars plans) | Fused, multithreaded operator plans and fast joins and group-bys. Lazy evaluation could skip work | Orcapod's type rules require values bit for bit and Arrow types as given. Polars round trips lose them: `date64` comes back at midnight, `decimal256` panics, and extension (logical) types, `float16` and large-versus-non-large layouts do not survive. The operators were moved off carrying columns through Polars for this reason (ITL-1284, ITL-1281). Hashes are computed over Arrow tables, so every node would convert back | It conflicts with the type-strict, bit-for-bit rules, and it targets the ~8% operator compute rather than the ~90% conversions. It stays future work, only where an operator already works in Polars | + +## Every difference from `main` + +Every observable difference this design introduces, on any path. A row is allowed only +with the developer's approval, given row by row. Each row gets its own test: it fails on +`main`, passes on the branch, and is the only thing the differential excludes for that +row, by name. The developer has accepted some behaviours of `main` that are not listed as +rows; they are kept as `main` has them, and documented below. + +**No row changes a sync-path result.** On the sync path the branch equals `main` byte for +byte. Stages 1–4 hold this by construction and by L0–L5, and a lemma that fails stops its +stage. + +| # | What differs | On `main` today | On the branch | Why `main` is wrong (bug, reproducer) | Approval needed | +|---|---|---|---|---|---| +| e1 | Async `Join` / `SemiJoin` with an empty input and disagreeing key types | Returns nothing (no row is there to read a type from) | Raises the sync path's `InputValidationError`, from the descriptions, before the first batch | **ITL-856.** Reproducer: a zero-row source with an `int16` key joined, async, with a source whose key is `int32` | approved (developer, 2026-11-22) | +| e2 | An async input row of another data context | The async function node answers it from the cache (the ITL-858 inventory) | A whole-input error before the first batch, as on sync | **ITL-951** (its comment; ITL-858 decision 9). Reproducer: an async function node fed a stream of another data context, with its result stored | approved (developer, 2026-11-22) | +| e3 | Function calls and stored rows for duplicate inputs, async; `RunSummary` computed counts | About 3× more calls than sync, and more stored rows (4,188 against 4,060 in ITL-1062's measurement) | Misses are deduplicated by base entry id, so calls, stored rows and counts equal sync | **ITL-1062.** Reproducer: ITL-1062's workshop-shaped pipeline with repeated input data, async | approved (developer, 2026-11-22) | +| e6 | Async values that depend on an earlier validation of the same operator object | `SemiJoin._validated_common_keys` and `Index._element_arrow_type_fallback` hold the last validation's values (ITL-858, section 1.2). One operator object applied to two streams can use the other stream's keys or fallback type | Read from each input's description, with no state | The ITL-858 finding; filed as ITL-1358. Reproducer: one `SemiJoin` instance validated on stream B, then run async over stream A with other keys. To be confirmed in stage 5 | ITL-1358 (filed); fixed with stage 5 once a reproducer confirms it | +| e7 | What a consumer does after its producer failed (async, failure path) | The producer closes its output in `finally`, so a consumer sees a normal end and may finish, and a `LOG` operator node may store, a partial result before the task group cancels it | Readers raise `UpstreamFailedError` at the failure point instead of seeing a normal end, so no consumer finishes, or stores its result, as if its input were complete. Batches a consumer processed before the failure are still processed, and a streaming node may already have passed them on or a function node stored results for them, as on `main`; there is no rollback. A barrier operator never computes over a partial input. The run raises the producer's own error, as today | A candidate race, to be confirmed with a reproducer in stage 5: a `fail_fast` function node raising on row 3 of 6, feeding a `Select` node in `LOG` mode; check the operator cache after the failed run. If `main` never stores in practice, this row is no difference | filed by the developer only once a test reproduces it | +| e8 | Meta columns of an async side-effect node's rows | An async side-effect node passes on and holds the rows it receives as they are, so a computed row keeps its `__computed` meta column (from the cached function pod), and the node's `as_table(all_info=True)` shows it. On sync, its input is rebuilt from rows (`_rows_to_table` drops meta), so the column is absent | Async drops input meta columns as sync does. With table transport this follows from the transport columns, which hold no meta column | A `main` bug: the async and sync paths give the node different columns. Found by the stage 0 harness on `job-speed` 0e15d0db, which does not change side-effect nodes; the stage 0 differential checks it on pinned `main`. Reproducer: a function node (with a result store) feeding a `tap_pod`, async against sync, comparing the side-effect node's `as_table(all_info=True)` columns | approved (developer, 2026-11-22) | + +**Resolved: refusals after rows have flowed (was c, question 9).** The developer's `Rejoin` +rule (ITL-1355) removes every data-dependent refusal from `Rejoin`: it checks only what its +inputs' descriptions show, before the first batch, so the streaming form never refuses after +rows have flowed. The fallback is gone. `Join`'s refusals were already schema-level. + +**A behaviour change on `main`, not made by this design: ITL-1355.** It is decided by the +developer and lands on `main` separately (its own PR), before stage 5. Inputs `main`'s +`Rejoin` refused now give fewer rows plus a warning: +- duplicate origin rows; +- a null system tag; +- rows of different data contexts; +- shared values that differ. + +`Rejoin` is provisional (`PROVISIONAL_OPERATORS`), and no golden value moves. Every stage +pins the `main` it is compared with, which includes ITL-1355 once it has landed. + +**Accepted by the developer, kept as `main`** (2026-11-22). These are not differences the +branch introduces: the branch keeps `main`'s behaviour, and they are documented here. +- **Async row order (was a).** Kept, stored and returned tables of an async run are in + arrival order, multiset-equal to sync. This covers operator caches, `node_outputs`, the + function-node stored tables and the side-effect log, all written as rows complete. + Developer: "For async absolutely fine that rows are stored in arrival order". This settles + question 11. +- **`Batch` grouping by arrival (was b).** When `Batch`'s input arrives in another order than + on sync (behind a concurrent function node, or a streaming join), its groups differ from + sync, and so do its values, its `batch_v1:` folds and everything downstream. For example, + rows `t = 0..5` through a function node sleeping `(5 - t) × 10 ms` give batches + {5,4}, {3,2}, {1,0} against sync's {0,1}, {2,3}, {4,5}. Developer: "This difference is + totally fine in Batch for sync and async". +- **An order-dependent `PolarsFilter` predicate over arrival order (was e5).** It is the same + class as `Batch`: a window or cumulative predicate (`rank`, `cum_sum`) over an input that + arrived out of order selects other rows than sync. Accepted by the developer + (2026-11-22), like `Batch`: `main`'s behaviour is kept and documented in the + `PolarsFilter` docstring and the concepts page, with no fix. +- **Async column order (was e4, ITL-1249).** Developer: "generally how column order comes out + is not as critical". The branch may keep or fix the async column order of + `ASYNC_ORDER_XFAIL` (`tests/test_core/operators/test_several_items.py:211`); it is neither + a goal nor a gate. The async comparison matches columns by name. + +**Checked, no difference found:** +- **The sync path**, at every stage, by construction and L0–L5. +- **Error types and messages**: `Join`'s schema-level checks keep their messages, asserted + in L6. +- **Observer events**: the same events in the same order and count. Function and side-effect + nodes are per row as today; operators and sources call node hooks only. +- **`RunSummary`**: identical on sync; on async it differs only under e3. +- **`head()` and the preview**: identical on sync. On async they show arrival order, as on + `main`. +- **Warnings**: issued from the same validation calls. +- **Async `Join` key matching**: `main` matches through `_match_key` / `frozen_scalar`, + which is meant to compare as the sync join does. The branch uses the sync join's prepared + keys. L6's corpus includes NaN, `0.0` / `-0.0` and `time64[ns]` keys, so a difference here + would show up and be added as a row. + +**Not part of this design:** +- **Polars' join order.** The sync joins take their row order from Polars' inner join without + `maintain_order` (risks). Making it explicit is allowed only if stage 0 shows that + `maintain_order="left_right"` gives exactly today's order on every test and in the + differential. Otherwise it is a result change that needs its own decision. +- **One canonical stored order** (for example, by record id). It would change today's + stored row order, so it is out of scope under the governing rule. +- **Sync order for async results** (the third revision's order rule), dropped by the + developer's decision on row order. + +## Protocol change + +All of these land on `eywalker/job-speed`, which reaches `main` as one merge (decision 7). + +### `StreamProtocol` (`src/orcapod/protocols/core_protocols/streams.py:81`) + +Two new members: +- `arrow_schema() -> pa.Schema`; +- `open_channel(*, buffer_size: int = 8) -> InputChannel`. + +`StreamBase` implements both for every existing stream kind. A class that implements +`StreamProtocol` without `StreamBase` must add them (the release note says so). + +### Node protocols (`src/orcapod/protocols/node_protocols.py`) + +| Protocol | Before | After | +|---|---|---| +| `SourceNodeProtocol.execute` (:45) | `execute(self, *, observer=None) -> list[tuple[TagProtocol, DataProtocol]]` | `execute(self, *, observer: ExecutionObserverProtocol \| None = None) -> StreamProtocol` | +| `SourceNodeProtocol.async_execute` (:51) | `async_execute(self, output: WritableChannel[tuple[Tag, Data]], *, observer=None) -> None` | `async_execute(self, output: OutputChannel, *, observer=None) -> None` | +| `FunctionNodeProtocol.execute` (:84) | `execute(self, input_stream: StreamProtocol, *, observer, error_policy, run_id, load_only) -> list[tuple[Tag, Data]]` | `execute(self, input_stream: StreamProtocol, *, observer=None, error_policy: Literal["continue", "fail_fast"] = "continue", run_id: str \| None = None, load_only: bool = False) -> StreamProtocol` | +| `FunctionNodeProtocol.async_execute` (:94) | `async_execute(self, input_channel: ReadableChannel[tuple[Tag, Data]], output: WritableChannel[...], *, ...) -> None` | `async_execute(self, input_channel: InputChannel, output: OutputChannel, *, observer=None, error_policy="continue", run_id=None, load_only=False) -> None` | +| `OperatorNodeProtocol.execute` (:127) | `execute(self, *input_streams: StreamProtocol, observer=None, load_only=False) -> list[tuple[Tag, Data]]` | `execute(self, *input_streams: StreamProtocol, observer=None, load_only: bool = False) -> StreamProtocol` | +| `OperatorNodeProtocol.async_execute` (:134) | `async_execute(self, inputs: Sequence[ReadableChannel[...]], output: WritableChannel[...], *, observer, load_only) -> None` | `async_execute(self, inputs: Sequence[InputChannel], output: OutputChannel, *, observer=None, load_only=False) -> None` | +| `SideEffectNodeProtocol.execute` (:158) | `execute(self, input_stream: StreamProtocol, *, observer, run_id, load_only) -> list[tuple[Tag, Data]]` | `execute(self, input_stream: StreamProtocol, *, observer=None, run_id=None, load_only=False) -> StreamProtocol` | +| `SideEffectNodeProtocol.async_execute` (:167) | `async_execute(self, inputs: Sequence[ReadableChannel[...]], output: WritableChannel[...], *, observer, run_id, load_only) -> None` | `async_execute(self, input_channel: InputChannel, output: OutputChannel, *, observer=None, run_id=None, load_only=False) -> None` (one input, as it always had) | + +Sync takes streams and returns a stream. Async takes input channels opened from streams, +and an output channel. The sync input type does not change, so every `execute(stream)` call +in the tests keeps its argument. + +**Implemented by:** +- `SourceNodeBase` (`core/nodes/source_node.py:1191`, `:1216`); +- `FunctionJobNode` (`core/nodes/function_node.py:2485`, `:4130`); +- `OperatorJobNode` (`core/nodes/operator_node.py:1647`, `:2133`); +- `SideEffectJobNode` (`side_effects.py:1224`, `:1455`); +- `LoadedSideEffectJobNode` (`pipeline/loaded_side_effects.py:259`, `:289`). + +**Called by:** the two orchestrators, `FunctionJobNode.run`, `SideEffectJobNode._run_alone` +and the loaded side-effect node. + +### Operator and function pod `async_execute` + +| | Before | After | +|---|---|---| +| `StaticOutputOperatorPod.async_execute` (`static_output_pod.py:728`) and every override | `async_execute(self, inputs: Sequence[ReadableChannel[tuple[Tag, Data]]], output: WritableChannel[tuple[Tag, Data]], *, input_pipeline_hashes: Sequence[ContentHash]) -> None` | `async_execute(self, inputs: Sequence[InputChannel], output: OutputChannel) -> None` | +| `FunctionPod.async_execute` (`function_pod.py:660`) | `async_execute(self, inputs: Sequence[ReadableChannel[...]], output: WritableChannel[...], pipeline_config=None, *, observer, error_policy, run_id) -> None` | `async_execute(self, inputs: Sequence[InputChannel], output: OutputChannel, pipeline_config: PipelineConfig \| None = None, *, observer=None, error_policy="continue", run_id=None) -> None` | + +`input_pipeline_hashes` disappears: an operator reads `inputs[i].stream.pipeline_hash()`. +That removes 65 uses in 13 source files and 84 lines in 17 test files. + +**Implemented by:** +- the barrier default (`static_output_pod.py:728`); +- `UnaryOperator` (`base.py:202`) and `BinaryOperator` (`base.py:316`); +- `FunctionPod` (`function_pod.py:660`); +- the 16 overrides: + - `add_tags.py:336`, `drop_nulls.py:322`, `batch.py:211`, `semijoin.py:308`, + `join.py:669`, `index.py:448`, `pick.py:444`, `rejoin.py:416`; + - `column_selection.py:152`, `:305`, `:444`, `:598`, `:825`; + - `mappers.py:263`, `:538`, `:825`. + +**Called by:** `OperatorJobNode.async_execute` (`operator_node.py:2244`), `Rejoin` +(`rejoin.py:428`), the function node (`function_node.py:4467`, `:4485`), and tests. + +**Validation state goes**, since the description is always at hand: +`SemiJoin._validated_common_keys` (`semijoin.py:287`, `:306`, `:381`) and +`Index._element_arrow_type_fallback` (`index.py:82`, `:126`). + +### Channels (`src/orcapod/channels.py`) + +| Class | Before | After | +|---|---|---| +| `ReadableChannel[T]` (:46), `WritableChannel[T]` (:63) | protocols in every node, operator and pod signature, with `T = tuple[Tag, Data]` | unchanged generic protocols. `InputChannel` and `OutputChannel` are their Arrow-record-batch forms. Queues inside a node (a function node's row queue to its pod) use them with rows | +| `Channel[T]` (:172) | the edge for one successor | unchanged generic bounded queue: the queue of each `InputChannel`, and of queues inside nodes | +| `BroadcastChannel[T]` (:247) | the edge for fan-out | removed: an `OutputChannel` with several readers is the fan-out. It has no other user | +| `ChannelClosed` (:36) | raised by `receive` on a closed, drained channel | unchanged; also raised by `InputChannel.receive` | +| **new** `InputChannel`, `OutputChannel` | – | defined above; the conversions (`channel_from_stream`, `stream_from_batches`) live beside them | +| **new** error | – | `UpstreamFailedError`, in `orcapod.errors` | + +### Results and orchestrators + +| | Before | After | +|---|---|---| +| `OrchestratorResult.node_outputs` (`result.py:21`) | `dict[Any, list[tuple[Tag, Data]]]` | `dict[Any, StreamProtocol]`: each node's output stream, backed by an Arrow table. This refines developer decision 1 (question 8) | +| `SyncPipelineOrchestrator.run(..., held_rows=...)` (`sync_orchestrator.py:58`) | `held_rows: Mapping[Any, list[tuple[Tag, Data]]] \| None` | `held: Mapping[Any, StreamProtocol] \| None` | +| `AsyncPipelineOrchestrator.run` / `run_async` / `_run_async` (`async_orchestrator.py:77`, `:158`, `:196`) | `held_rows: ...` | `held: Mapping[Any, StreamProtocol] \| None` | +| `RunPlan.held_rows` (`node_run.py:267`) | `dict[Any, list[Any]]` | `held: dict[Any, StreamProtocol]` | + +Not changed: `FunctionJobNode.execute_data(tag, data)` (`function_node.py:2464`), a per-row +entry point that no orchestrator uses (33 test lines in 10 files). The executors' +`async_execute_callable` is also unchanged. + +## Call sites + +Every call site on `origin/main` 8c6fc4f5, and what it becomes. + +### Sync orchestrator (`src/orcapod/pipeline/sync_orchestrator.py`) + +| Line | Today | Becomes | +|---|---|---| +| :58–66 | `run(..., held_rows=...)` | `run(..., held=...)` | +| :104 | `buffers[node] = list(held[node])` | `outputs[node] = held[node]` (the held node's output stream) | +| :106 | `node.execute(observer=...)` (source) | same call; returns the output stream | +| :108–119 | `_gather_upstream`, `_materialize_as_stream(buf, upstream)`, `node.execute(input_stream, ...)` | `node.execute(outputs[pred], ...)` | +| :121–128 | `_gather_upstream_multi`, one `_materialize_as_stream` per input, `node.execute(*input_streams, ...)` | inputs in the same order (`node.upstreams`); `node.execute(*(outputs[p] for p in ordered), ...)` | +| :130–141 | as :108 (side-effect node) | as :108 | +| :173, :187 | `_gather_upstream*` return row buffers | return output streams; order logic unchanged | +| :206 | `_materialize_as_stream` | removed: each output stream already is the successor's input | +| :225 | `_gc_buffers` | unchanged logic over `outputs` | +| :155 | `OrchestratorResult(node_outputs=buffers)` | `OrchestratorResult(node_outputs=outputs)` | + +### Async orchestrator (`src/orcapod/pipeline/async_orchestrator.py`) + +| Line | Today | Becomes | +|---|---|---| +| :77, :158, :196 | `held_rows=` | `held=` | +| :230–250 | `Channel` per single edge, `BroadcastChannel` + `add_reader()` for fan-out, a sink `Channel` per terminal node | one `OutputChannel(node, retain=..., buffer_size=...)` per node that runs; one `open_reader()` per successor. A terminal node's output channel has no reader | +| :258–265, :799 | `_CollectingWriter` copies every row | removed: `node_outputs` holds each `output.result()` | +| :267–275, :645, :651 | held node: `_drain` each input, `_send_held(rows, writer)` | a held node's output stream opens one input channel per async successor (`held[node].open_channel()`). `_drain` and `_send_held` are removed, since the plan gives a held node no input edge | +| :281 | `node.async_execute(writer, ...)` (source) | `node.async_execute(output, ...)` | +| :294 | `node.async_execute(input_reader, writer, ...)` (function) | `node.async_execute(reader_for(pred, node), output, ...)` | +| :320 | `node.async_execute(input_readers, writer, ...)` (operator; ordered by `node.upstreams`) | `node.async_execute([reader_for(p, node) for p in ordered], output, ...)` | +| :340 | `node.async_execute([input_reader], writer, ...)` (side effect) | `node.async_execute(reader_for(pred, node), output, ...)` | +| :708, :742 (`_single_failure`, `_single_database_error`) | pick the error the run raises | unchanged, but skip `UpstreamFailedError` | + +`reader_for(pred, node)` is the reader opened for that edge before tasks start: from the +predecessor's output channel, or from a held predecessor's stream. + +### Nodes, operators and pods + +| Site | Today | Becomes | +|---|---|---| +| `source_node.py:1191` `execute` | `list(self.iter_data())` | the output stream over `F(declared(bound.as_table(all columns)))` | +| `source_node.py:1216` `async_execute` | sends each row of `async_iter_data()` | sends that Arrow table's record batches, or one batch per poll for a `PollingSource` | +| `operator_node.py:1647` `execute` | `process`, `list(result.iter_data())`, `_kept_output` | `process`; the kept output and return value is `_as_upstream_stream(F(result.as_table(...)), self)` | +| `operator_node.py:2133` `async_execute` | `intermediate` row `Channel` (:2218), `collected`, `_materialize_to_stream` | passes its input channels and its output channel to the operator. After close, its kept output is `output.result()`, stored in `LOG` mode | +| `operator_node.py:2241–2250` | `hashes = [...]`; `operator.async_execute(taps, intermediate.writer, input_pipeline_hashes=hashes)` | `operator.async_execute(inputs, output)` | +| `operator_node.py:109` `_InputTap`, `:2275` `_materialize_upstream(..., zero_rows=True)` | taps record rows to rebuild empty inputs | removed: an empty input's `to_stream()` is its zero-row stream | +| `function_node.py:2485` `execute`, `:2008` `_execute_load_only` | iterate `input_stream.iter_data()` | read `input_stream.as_table()`: entry ids from slices, hits from the stored Arrow table, calls on misses; return the output stream | +| `function_node.py:4130` `async_execute` | three stages over row channels | reads Arrow record batches from its input channel. Hits are sent as batches; misses go row by row to the pod's row executor; results are sent as batches | +| `function_node.py:4259`, `:4262` | `compute_channel`, `result_channel`: row `Channel`s to and from the pod | kept as row queues inside the node, since rows exist only for misses | +| `function_node.py:4467`, `:4485` | `execution_pod.async_execute([compute_channel.reader], result_channel.writer, ...)` | the pod's per-row executor: today's semaphore and hooks, split out so the node and the pod's own `async_execute` share it | +| `function_node.py:4055` `FunctionJobNode.run` | `_ = self.execute(self._input_stream, observer=counter, ...)` | unchanged call; returns a stream | +| `side_effects.py:1224`, `:1455` | iterate and pass on rows | rows for delivery only; the output is the input's Arrow data masked to the rows passed on | +| `side_effects.py:1428` `_run_alone` | `self.execute(self._input_stream, ...)` | unchanged call | +| `loaded_side_effects.py:284`, `:319` | `super().execute(...)`, `super().async_execute(...)` | same forwarding, new signatures | +| `rejoin.py:428` | `StaticOutputOperatorPod.async_execute(self, inputs, output, input_pipeline_hashes=...)` | `StaticOutputOperatorPod.async_execute(self, inputs, output)` | +| `join.py:815`, `:834` | row `Channel` chain inside an N-ary join | an `OutputChannel` per intermediate pair, its `stream` the pair's `zero_row_result`; the next step reads its reader | +| `static_output_pod.py:689`, `:543`, `:570` (`_materialize_input_stream`, `_materialize_to_stream`, `_materialize_upstream`) | rebuild rows into streams | removed: `to_stream()`, `result()` and the output streams replace them | +| `static_output_pod.py:304` `_rows_to_table` | used on every edge | moves to the tests as the oracle `R`, once nothing in the library uses it | + +### Plan and held nodes + +| Site | Today | Becomes | +|---|---|---| +| `node_run.py:341–345` | `held_rows = {node: list(node.iter_data()) ...}` | `held = {node: node.output_stream() ...}`. That is an operator's kept stream, a function node's held rows as a stream in cache order (developer decision 3), or a side effect's held stream | +| `node_run.py:346` | `held_counts = {node: sum(1 for _ in node.iter_data()) ...}` | `held[node].as_table().num_rows`, or a function node's run entry counts | +| `node_run.py:432`, `job.py:1000`, `job.py:1071` | `held_rows=plan.held_rows` | `held=plan.held` | +| `run_summary.py:532` | reads held counts | unchanged | + +### Tests that call these directly + +Counted on `origin/main`, by file, excluding database cursors' own `execute`: + +| What | Files | Lines | Largest | Change | +|---|---|---|---|---| +| node `.execute(` | 18 | 88 | `test_ephemeral_result.py` 32, `test_side_effect_pod.py` 13, `test_node_execute.py` 8, `test_node_protocols.py` 7 | arguments unchanged; a test that reads the returned list reads `iter_data()` of the returned stream | +| `.async_execute(` | 42 | 171 | `test_native_async_operators.py` 39, `test_node_async_execute.py` 26, `test_async_execute.py` 23 | inputs become `stream.open_channel()`; the output is an `OutputChannel` whose `result()` the test reads | +| `Channel(` | 42 | 329 | `test_native_async_operators.py` 95, `test_node_async_execute.py` 51, `test_async_execute.py` 48 | a helper (`tests/stream_helpers.py`) opens a channel on a stream and reads an output channel's result | +| `input_pipeline_hashes` | 17 | 84 | `test_native_async_operators.py` 42 | removed | +| `node_outputs` | 4 | 5 | `test_core/alignment/records.py` 2 | read the stream | + +## Each node kind + +### Source job node + +- **Sync**: returns the output stream over `F(declared(bound.as_table(all columns)))`. + `declared` is `_DeclaredForm.apply`, which already serves a whole Arrow table. +- **Async**: sends that Arrow table's record batches, or one batch per poll for a + `PollingSource`, which keeps streaming. +- A `PollingSource` polls as often as today, and a run checks its sources first (ITL-1102). + +### Operator job node + +- **Sync**: `process(*input_streams)`. The kept output, which is also the return value, is + `_as_upstream_stream(F(result.as_table(...)), self)`. + - `_store_output_stream` stores the same Arrow table. + - REPLAY returns the stored stream in that form. + - A result with no rows keeps `_zero_rows_in_row_order` (ITL-1131). +- **Async**: the operator writes into the node's output channel (barrier or streaming, per + the table above). + - At close, the node keeps `output.result()`, in arrival order as on `main`, and stores + it in `LOG` mode. + - REPLAY sends the stored Arrow table's batches and drains its inputs. + - A run with no rows closes with no batch. +- Operators have no per-row error policy: a failure fails the node, as today. + +### Function job node + +The function is still called once per row. Everything around the call is Arrow data. + +1. **Input as Arrow data.** For each input row, the node computes the base entry id from that + row's slice of the Arrow table or record batch: the tag side with system tags, plus the + input data hash. This is the same one-row preimage `_build_record_id_preimage` builds + today, still per row (hashing is ~0.3% of the run). No datagram is made. +2. **Lookup as an Arrow table.** `get_cached_results` finds the same entries. The loader keeps + the stored joined Arrow table and a map from base entry id to row, and hits are taken + from it by row index. +3. **The call.** For each miss: + - The parameters' values come from the input Arrow data. They are converted to Python + once per column per Arrow table or record batch, through the data context's type + converter: the conversion `Data` applies per row today. + - The call keeps today's logger, invocation context, error policy, commit cadence + (`commit_every_rows`, `_row_processed`) and database error handling. + - Misses that share a base entry id are called once and the result reused, as the sync + path's in-run lookup does today and as ITL-1062 asks of the async path. +4. **Results as Arrow data.** + - Returned values are collected per output column and converted to Arrow once, under the + declared output Arrow schema. + - The per-row items stay per row: the output data hash, the source-info tokens and the + datagram id (`uuid7`, stored as `__data_id`). + - Pipeline records and result rows are written as Arrow tables per commit window, with + today's rows, columns and values. Rows written before a failure stay written. +5. **Output.** In input order, assembled from hit rows and computed rows by row index: + - a `None` result or a failed row gives no row; + - two equal inputs give two rows; + - the column order is the first output row's (developer decision 2). + + On the async path, rows keep today's order: stored hits first, then computed rows as + they finish. That is also the order of `result()`, as on `main`. The node's own reads + keep cache order on both paths (developer decision 3). +6. **Load-only**: the hits-only case, with the same `not_stored` count. +7. **The node's own reads** come from its kept stream, in cache order (developer decision 3). +8. **Stored values decoded as a class (ITL-881).** A `TypeIdentityError` must stop the run at + the same point as today. Stage 3 first establishes where it is raised today. If at + datagram construction, the node checks each user-class column of the stored Arrow table + once, before it passes a row on. +9. **`EmptyData` inputs (ITL-605).** Stage 3 first establishes how such a row crosses an edge + today, and keeps that behaviour. The stream carries those rows' cached content hashes + beside its Arrow data, never as a column. ITL-605's materialization thunks later use the + same record. + +### Side-effect job node + +- Delivery calls the user's function with one row's values, taken from the Arrow data. +- The output is the input's Arrow data, masked to the rows passed on. +- A load-only run passes its input on unchanged. + +## Per-row concerns without a row transport + +### Observers + +The protocol keeps its per-row hooks and its event order. A hook now receives a **row +view**: one internal class, `RowView`, that satisfies `TagProtocol` or `DataProtocol` over an +Arrow table or record batch and a row index. It builds the datagram only when it is first +read. + +- `RunCountingObserver` reads only the label and the `cached` flag, so it makes no row. +- The status and logging observers read tag values, so they make the tag datagram of the + rows they report. +- A user's observer gets what it gets today. + +Event order stays as today: +- sync: input order; +- async: stored hits first, then rows as they finish. + +The async function node matches a row's input by row index, instead of by a +`_TAG_NODE_INPUT_REF` meta column. + +**ITL-1220 (attachments, future).** A stream lists its attachments, since the stream owns +the description. They run over row views of each Arrow table or record batch, in row order, +where observers are told. A "halt" signal maps onto failing the output channel and +cancelling the run's task group. + +### Error policy + +A row can fail only in a user's function or a delivery, both per row. The node wraps each +call: +- `continue`: the failed row is left out by mask, counted, and reported through + `on_data_crash` with its row view; +- `fail_fast`: the node raises at once; +- database errors and `TypeIdentityError` stop the run whatever the policy. + +## How each rule holds + +- **ITL-845, each row keeps its own source info.** + - Streams and Arrow record batches keep the `_source_*` values row by row, and F touches no + value. List-valued tokens after `Batch`, `GroupBy` or `MergeJoin` are kept too. + - Source-info nullability is set once per complete Arrow table: a sync output, and + `stream_from_batches` (`result()`, `to_stream()`). + - It is never set per Arrow record batch, because two batches of one channel would then + have two schemas. +- **ITL-1122, large types.** + - An Arrow table is normalized once, where it becomes a stream. + - Streams and channels pass Arrow data on by selecting, slicing or `take`, which keep + types. + - Function results are converted under the declared output schema, which is large. + - Nothing is normalized per row or twice. F step 3 keeps the one observable effect of + today's per-row normalization. +- **Async equals sync.** + - An operator reads its description from a stream on both paths, and a barrier operator + runs `static_process` on streams on both. + - Validation, input order, key checks and zero-row results are one implementation. + - Async results equal the sync rows as a multiset, with columns matched by name; row order is + not compared (developer, 2026-11-22). + - `test_async_sync_equivalence` stays the check, with the standing guards below. +- **ITL-1133 and ITL-1131, one column order.** + - F places every stream's transport columns in row order, and `arrow_schema()` is in the + same order. + - An operator node keeps and stores `F` of its result, sync and async. +- **Row order.** Each node passes on its rows in the order its successors receive them today: + - a source: its Arrow table's order; + - an operator: its result's order; + - a function node (sync): input order; + - a held function node: cache order; + - a side-effect node: delivery order; + - async: arrival or match order, in flight and in what a node keeps and stores, as on + `main` (accepted by the developer). +- **Staleness.** + - Every node calls `_update_modified_time` at the same points and in the same order. + - A channel has no modified time; its stream does. + - The ITL-1095 and ITL-1121 tests run at each stage. +- **Run summary.** The counts come from: + - the counting observer, which still sees one event per row; + - `last_run_not_stored`; + - held counts, read without rows. + +## What this closes (ITL-858) + +| Case | Status on main | Closed by | Stage | +|---|---|---|---| +| Key types on an empty input, `Join` / `SemiJoin` (ITL-856) | open | checks from `channel.stream.arrow_schema()` before the first batch | 5 | +| Async column order (`ASYNC_ORDER_XFAIL`, ITL-1249, `tests/test_core/operators/test_several_items.py:211`) | strict xfail | not a goal or a gate (developer: column order is not critical). It may pass as a side effect; if so, the xfail is removed | – | +| Data context of an async input (ITL-844) | open | `channel.stream.data_context_key` | 5 | +| A row of another data context (ITL-951) | sync: whole-input error; async: answered from the cache | whole-input error before the first batch (ITL-858 decision 9) | 5 | +| Zero-row results, async (ITL-865) | narrow fix | `to_stream()` of an empty input is the typed zero-row stream | 5 | +| System-tag names after a non-source input, async (ITL-906) | narrow fix through `input_pipeline_hashes` | each input's `stream.pipeline_hash()` | 5 | +| Zero-row read-back types (ITL-912) | fixed (`typed_zero_row_table`) | the same derivation, now `arrow_schema()` | 2b, 5 | +| Operator state written at validation (`SemiJoin`, `Index`) | present | read from the input's stream | 5 | +| Duplicate function calls on async (ITL-1062) | open | misses deduplicated by base entry id | 5 | +| A loaded node's description (ITL-858 decision 7) | – | saved Arrow type texts (ITL-640) | 2a | + +Standing guards: +- **Declared against materialized** (stage 2a, before anything depends on it): + `stream.arrow_schema()` equals the materialized Arrow table's schema, with the two stated + exceptions. This holds for every operator, source kind and function node, sync and async. +- **In `test_async_sync_equivalence.py` (stage 5)**: one registry of every operator class + with an `async_execute`. The test fails when a class is missing from it. +- **Four input shapes per case**: rows; zero rows on every input; zero rows on one input; + inputs from an operator instead of a root source. +- **Batch layouts**: one Arrow record batch, one row per batch, and mixed sizes. + +## What must stay byte-identical, and how it is proven + +This section applies the governing rule. Everything below holds on the sync path against +pinned `main`, byte for byte. On the async path it holds against the branch's sync path as a +multiset of rows, with columns matched by name. The rows of "Every difference from `main`" are +the only exceptions, each by name. + +### Must not change + +1. **Every hash.** `generate_golden_hashes.py --check` matches. Per node, this covers: + - content hash and pipeline hash; + - record ids; + - base and pipeline entry ids; + - output data hashes; + - source-info tokens; + - system-tag column names and values; + - folded values (`batch_v1:` / `group_v1:`). + + Nothing about the transport enters a hash (ITL-858 decision 3). +2. **Every stored table**: the function pipeline and result tables, the operator cache + (`odb_v1`), the side-effect log (`tdb_v1`) and the cached source (`sdb_v1`). For each: + path, column names and order, types, nullability, field metadata, values, and the row + order written. +3. **Every output a user reads.** For every node: `as_table(all_info=True)`, the `iter_data()` + rows, the `head()` and `run()` views with their status and notes, and `as_source()` / + `DerivedSource`. +4. **Every successor's input**: the Arrow data each operator, function node and side-effect + node receives. Columns, order, types, nullability, metadata, values and row order. +5. **Run behaviour.** + - `RunSummary` and `NodeRunSummary.held`. + - The warnings issued. + - Every error raised, at the point it is raised today. + - The observer event sequence, and the values an observer reads. + - What logging capture records. + - Which nodes a second run holds. + +Not covered: +- Arrow chunk and record-batch boundaries, datagram object identity, and timing. +- By design, the changed signatures, which are the breaking change. + +### Proof + +1. **Equality tests**, kept permanently (`tests/test_pipeline/test_stream_transport_equivalence.py`). + `R` and `ArrowTableStream.iter_data` are the oracle. Each comparison is + `Table.equals(check_metadata=True)` plus field-by-field schema equality, on combined + chunks. + - **L0 (idempotence)**: an output stream `S` gives `R(rows of S) == S.as_table()` on the + transport columns. + - **L1 (operators)**: an operator node's output equals `R(list(result.iter_data()))`, for + every exported operator and for REPLAY. + - **L2 (sources)**: for each source kind bound to a slot, with and without a declared + form, the output equals `R(list(node.iter_data()))`. The kinds are in-memory, CSV, + Delta, SQLite, `CachedSource`, `DerivedSource`, `PollingSource` (counting polls) and + SpiralDB through its fakes. PostgreSQL runs in its own job. + - **L3 (entry ids)**: per input row, the id from the Arrow slice equals + `compute_base_entry_id(tag, data)`, also for a stream outside a job. + - **L4 (function node)**: + - the values given to the function equal today's `function_input(...).as_dict()` + values (`==`, same types); + - the results equal `R` of today's result datagrams; + - the output equals `R` of today's output rows, both with the first row a hit and with + it a miss. + - **L5 (held)**: a held node's output stream and count equal today's. + - **L6 (async)**: for every node kind and every operator (streaming and barrier), + `output.result()` equals the sync output stream's Arrow table as a multiset of rows, with + columns matched by name. It runs with the three batch layouts and with a predecessor + that streams in match order. It also covers `Join`'s schema-level refusals (the same + error type and message as sync) and ITL-1355's non-match cases under streaming: + - a shared tag that differs; + - NaN and `-0.0` / `0.0` in a shared column (they match; the first input's bits are + kept); + - inputs of different data contexts; + - rows held until close, and released early once one input closes. + + Each is compared with sync as a multiset, and the warning is checked to be issued once per + operator and set of columns. + `Batch` and order-dependent `PolarsFilter` predicates behind an out-of-order input, and + their descendants, are checked instead by per-node consistency over their recorded + arrivals (see the differential), as the developer accepted. + - **L7 (descriptions)**: the declared-against-materialized guard. + - **L8 (channels)**: unit tests of `InputChannel`, `OutputChannel` and the conversions, + one per row of the semantics table: + - retain on and off; + - late readers; + - fan-out with a slow reader; + - a reader that closes early; + - reading a node while it runs (zero rows, `not_computed`, no wait); + - identity of `result()` and `to_stream()`, with and without a producer; + - producer failure and cancellation (readers raise `UpstreamFailedError`, and the run + raises the producer's error); + - double close; + - zero rows; + - `open_channel()` twice on one stream. + + The corpus is the several-items family (`tests/test_core/operators/several_items.py`). + It adds: + - logical types and user classes; + - `null`-typed, list, struct and nullable columns; + - zero, one and many rows; + - duplicate inputs; + - a function returning `None`; + - ephemeral `EmptyData`; + - failed rows under both policies; + - a loaded node; + - a stream outside the job; + - fan-out; + - a null source-info token. +2. **Existing suites**, run targeted as each stage lands: + - `test_async_sync_equivalence`, `test_order_invariance`; + - the operator, function and side-effect node tests; + - `test_pipeline_job` and the observer tests; + - the ITL-1131/ITL-1133 column-order tests; + - the ITL-1095/ITL-1121 staleness and load-only tests; + - the ITL-1075 deadlock tests; + - the run summary tests; + - the golden check. +3. **End-to-end differential: the acceptance gate of every stage**, stage 1 included. A + script in `docs/dev/scripts/itl_1347/` builds fixture pipelines from + `docs/tutorial/workshop_data.py`, the corpus, and the arrival-order graphs below. Each + pipeline runs cold, warm, held and load-only, on both orchestrators. + - **Sync on the branch against sync on pinned `main`**: byte for byte, with no exception. + - **Async on the branch against sync on the branch**: equal as multisets of rows (row + order ignored, duplicates counted), with columns matched by name. The rows of "Every + difference from `main`" are excluded, each by name only. + - **Async on the branch against async on `main`**: equal as multisets. Every difference + beyond that must be a listed row. + - **Arrival-dependent results and everything downstream of them.** An accepted + arrival-dependent node is a `Batch`, or a `PolarsFilter` with an order-dependent + predicate, whose input arrives in another order than on sync in **either** async run: + the branch's or `main`'s. Its rows legitimately + differ from sync, and so do the rows of every node downstream of it. The differential + determines that set mechanically, from the job's graph: the arrival-dependent node and + all its descendants. That set, and nothing else, is excluded from the row comparison + against sync and against `main`'s async run. Instead, every node in the set is checked, + in each async run separately (the branch's and `main`'s), against a sync recomputation + over exactly the inputs it received in that run: + - **recorded arrivals**: the differential records, for each node in the set, the rows of + each of its inputs in the order the node received them on the async path (it wraps + the node's input channels; the library is not changed); + - **per-node consistency**: the node is computed again on the sync path of pinned + `main` (not the branch's), over those inputs as Arrow tables in that recorded order. + Its async output must equal that recomputation as a multiset of rows, apart from the + named differences. Using `main`'s operator catches a branch defect that shows only on + an arrival order the sync run never produces. For a `Batch` this fixes the groups to the + consecutive `batch_size` segments of its own arrival sequence, with their boundaries + and member order (lists are compared in order). Interleaved groups such as [A, C] and + [B, D] from arrivals A, B, C, D fail. For an order-dependent `PolarsFilter` it fixes + the kept rows to exactly those the predicate selects over the arrival sequence: no + selected row missing, none extra; + - **every arrival-dependent descendant too**: a later `Batch` or order-dependent + `PolarsFilter` in the set (for example behind a concurrent function node fed by the + first `Batch`) is checked against its own recorded arrivals in the same way, never + against an order the sync recomputation would choose. Each node's check uses only + its own recorded inputs, so a valid arrival order anywhere in the set passes; + - **edge conservation**: for every edge into or inside the set, the node's recorded input + rows equal its producer's output rows in the same run, as a multiset with + multiplicity. So a row lost or duplicated between two excluded nodes fails, even + though each node agrees with its own recomputation; + - **everything outside the set** is compared as usual. + + This is the complete statement of the gate. The stage 0 harness (`docs/dev/scripts/itl_1347/`) + implements the comparisons stages 1–4 need; stage 5 adds the recorded-arrival checks + above (its README lists them). + + A difference anywhere else fails the gate. + - **What it dumps and compares**: every stored table (Arrow IPC, with Delta version + counts and per-version row sets), every node's `as_table(all_info=True)`, the + `RunSummary`, the errors raised (type and message), the warnings, and a recording + observer's events with the values it read. + - **Polars threads**: it runs twice, with Polars at one thread (`POLARS_MAX_THREADS=1`, + set before import, in a subprocess) and at the default. + - **A stage merges only when its differential output is clean.** That output goes on the + stage's PR. +4. **Async graphs where arrival order differs from sync order.** The equivalence tests feed + operators from sources only, so arrival order always equals sync order there, and + `Batch`'s grouping by arrival went unseen. New cases (L6, and the differential) put a concurrent function + node in front of the operator under test. The function's delay is set per row (it sleeps + longer for earlier rows), and the order is forced by awaiting per-row events in a + scripted order, so the run is deterministic. The function node feeds: + - `Batch` (`batch_size=2` and `0`); + - `Join` and `MergeJoin` (the function node on one side); + - `GroupBy`; + - `PolarsFilter` with an order-dependent predicate; + - `Rejoin` of two branches of one source, one branch through the function node; + - a `Select` operator node in `LOG` mode, so its stored table is checked. + + Each case asserts the rows equal sync as a multiset. `Batch` and the order-dependent + `PolarsFilter`, and their descendants, are checked as above: per-node consistency over + recorded arrivals. The same holds against `main`'s async run. The `Rejoin` + case runs ITL-1355's non-match cases with the late branch behind the function node: + - a differing shared value; + - NaN and `-0.0` / `0.0` in a shared column; + - a different data context. + + It compares with sync as a multiset, and checks the warning once. + +## Migration and staging + +### On the integration branch + +The work lands on `eywalker/job-speed`, which the developer merges into `main` as one PR. +So each signature changes directly in the stage that needs it, with no thin forms of old +signatures kept between stages (CLAUDE.md: no compatibility shims). `main` still sees one +breaking change, at the branch merge (decision 7). + +### Stages, with the ITL-858 work merged in + +The savings below are estimates from the profile's shares; stage 0 replaces them with +measurements before stage 1 merges. The profile's unit costs: +- about 26 s of datagram building over 121,139 rows (about **0.21 ms per row**); +- about 14 s of rebuilding. + +| Stage | What | ITL-858 part | Proof | Expected saving, warm sync run of 44.7 s | +|---|---|---|---|---| +| 0 | Measurement only: datagrams per node kind, `R` calls and time by caller, edges per node, on a tutorial-data pipeline of the workshop's shape | declared against materialized Arrow schema, measured for every operator and source | – | 0 s | +| 1 | **First small step**: the sync orchestrator reuses an operator node's kept Arrow table, already `R` of exactly the rows it passes on, for each successor (held operator nodes included). Held counts are read without rows. No signature changes | – | by construction; one test per edge | about **4–8 s** | +| 2a | Sources, sync: `arrow_schema()` on `StreamBase`; each node's `execute` returns its output stream; held nodes give their output stream; `node_outputs` holds streams; sources return `F` of their Arrow table | `arrow_schema()` on every stream; the declared-against-materialized guard; loaded nodes describe themselves | L0, L2, L5, L7 | with 2b, about **14–20 s** | +| 2b | Operators, sync: kept output and return value `F(result.as_table())`, and REPLAY likewise | – | L0, L1, L5 | (with 2a) | +| 3 | Function nodes, sync: input from the input stream's Arrow table; entry ids from slices; hits from the stored Arrow table; calls on values from Arrow data; results per column; row views for observers; own reads from the kept stream | – | L3, L4, differential | about **8–14 s** | +| 4 | Side-effect nodes, sync: masked pass-through, load-only pass-through, held stream | – | L0, differential | small | +| 5 | Async: `InputChannel`, `OutputChannel`, the conversions and `open_channel()`; every `async_execute` on input channels and an output channel; barrier operators (`GroupBy`, `PolarsFilter`, `Batch(0)`) by `to_stream()`; streaming `Join`, `MergeJoin`, `Rejoin` (ITL-1355's rule: match on every shared column, matched rows removed, early release, the warning per batch) and `SemiJoin` (vectorized symmetric hash joins); `Batch` streaming by arrival as on `main`; key checks before the first batch; per-row operators per Arrow record batch; validation state, `input_pipeline_hashes` and `BroadcastChannel` removed; function node async with dedup | ITL-856, ITL-844/951 async, ITL-865/906 general form, ITL-1062; standing guards | L6, L7, L8, `test_async_sync_equivalence`, differential | the same order of gain for async runs | + +The ranges overlap: +- the bound for stages 1–4 is the ~40 s (~90%) the profile puts on conversions; +- the floor is the plain-stream time (1.9 s) plus the lookups and writes a job adds; +- a warm sync `job.run()` of about 3–6 s is the target after stage 3. + +The `LazyModule` cost (42.9 million `__getattr__` calls; 45.1 s → 40.7 s in the profile's +experiment) is a separate fix in this round. + +Each stage is one issue and one PR against `eywalker/job-speed`, with: +- its equality tests; +- the targeted suites; +- the golden check; +- the differential, which is its acceptance gate. + +The differential must come out clean: sync identical to pinned `main`, and async identical to +the branch's sync run except the named rows. A stage that introduces a difference not listed +in "Every difference from `main`" does not merge. The difference is either removed, or added +as a row with its bug and reproducer, for the developer's approval. + +Benchmarks follow the round's rules. + +### Release note (for the merge into `main`) + +In `changelog.d/.md`, under `### Breaking changes and migration`: + +> #### Job nodes and operators exchange streams and channels of Arrow data, not rows +> +> Code that drives nodes or operators directly changes. These stay unchanged: pipelines, +> jobs, `job.run()`, `run_async()`, sources, operators used in pipelines, and every stored +> table and hash. +> +> - A node's `execute()` returns its output stream, not a list of `(Tag, Data)` pairs. Read +> rows with `iter_data()`, or the Arrow table with `as_table()`. +> - `async_execute()` of nodes, operators and function pods takes input channels and an +> output channel (`orcapod.channels.InputChannel`, `OutputChannel`) carrying Arrow record +> batches, instead of row channels. +> - Open an input channel on a stream with `stream.open_channel()`; its description is +> `channel.stream`. +> - An output channel's `result()` is the output stream, once closed. +> - `BroadcastChannel` is removed. An `OutputChannel` with several readers replaces it. +> - The `input_pipeline_hashes` argument of operators' `async_execute()` is removed: each +> input's stream states its own `pipeline_hash()`. +> - A side-effect node's `async_execute()` takes one input channel, not a list of one. +> - `OrchestratorResult.node_outputs` maps each node to its output stream. +> - The orchestrators' `held_rows=` argument is now `held=`, and takes streams. +> - `StreamProtocol` has two new members, `arrow_schema()` and `open_channel()`. +> `StreamBase` provides them. A class that implements the protocol without `StreamBase` +> must add them. + +## Risks and unknowns + +| Risk | What could go wrong | Mitigation | How we would detect it | +|---|---|---|---| +| **Memory with retained output** | `retain=True` is the default (`materialize_results=True`), so whole outputs are held as Arrow tables. During the transition a node could hold both its old rows and its new Arrow table. A large source, fully retained, could exceed today's footprint | A retained output channel's `result()` is the node's kept output: one copy, enforced by a test that they are the same object. Sources retain only when `materialize_results=True`. Arrow tables are far smaller than datagram objects | Stage 0 records peak RSS (`resource.getrusage`) for the baseline; every stage's benchmark reports it before and after | +| **Back-pressure and deadlock cycles** | Channels now count Arrow record batches. Diamonds, `SemiJoin` over one source, `Join`'s internal chain and slow fan-out readers could block a producer, as ITL-1075 did with rows | The read-to-the-end rule and `close()` on input channels. `retain=True` on node outputs means `send` never waits. REPLAY and `SemiJoin` keep reading their inputs | The ITL-1075 deadlock tests, run with one-row batches and `buffer_size=1`, plus a diamond and fan-out matrix under a pytest timeout (L8) | +| **Error propagation** | `UpstreamFailedError` could become the error a run raises instead of the producer's own. A consumer could take a producer's failure as a normal end and store a partial result | `fail()` in the producer's `finally`. The failure selection skips `UpstreamFailedError`. `LOG` stores only after a complete run | L8, and the existing error tests (`test_async_error_policy.py`, `test_store_write_failure.py`), asserting the raised type and message equal `main`'s. The differential's failing-row cases | +| **Async ordering** | Arrow record batches change the granularity of what async nodes see, so arrival order can differ from `main`'s. `Batch` groups by arrival, so with record batches its groups may differ from `main`'s async groups too | Accepted by the developer (row order is not critical; `Batch` grouping by arrival is fine). Every other result is order-independent and compared as a multiset | L6 and the arrival-order graphs (as multisets; `Batch` and its descendants by per-node consistency over recorded arrivals) | +| **Observer `RowView` cost and fidelity** | With a status or logging observer attached, every row's tag datagram is built again, so part of the cost returns. A lazy view could also differ from a real datagram (`isinstance`, equality, `as_dict()` values, pickling in a logger) | A `RowView` builds the real datagram on first access and then delegates every call to it. ITL-1348 makes that construction cheaper | The differential's recording observer compares every value it reads. A benchmark row "warm run with a status observer" shows the remaining cost | +| **Test migration size** | Stage 5 touches 42 files with 171 `async_execute` lines, 329 `Channel(` lines and 84 `input_pipeline_hashes` lines, and stage 2a touches 18 files with 88 `execute` calls. A large diff is hard to review, and a test could be weakened by accident | A shared helper (`tests/stream_helpers.py`). Plumbing changes go in their own commit, before any behaviour change. Assertions are not edited, only how inputs are fed and outputs read | A per-file count of `assert` statements before and after, reported on the PR. The coordinator's full-suite run and CodeRabbit | +| **Estimates that stage 0 may disprove** | The savings come from profile shares that overlap. The datagram cost may sit mostly in function nodes' stored-hit loading, or in observers, rather than on edges. Stage 1's 4–8 s may be less | Stage 0 measures the split per node kind and per caller before stage 1 merges. If a stage's measured share differs from its estimate by more than half, the plan is revisited with the developer | Stage 0's numbers against the stage table. Each stage's before-and-after benchmark (best of 3, with the load average) | +| **Byte-identity drift in edge cases** | `null` columns, source-info flags, the function node's first-row column order, `EmptyData` rows, and the point where `TypeIdentityError` is raised | F's explicit steps. The stage 3 investigations named in "Function job node". No golden file is regenerated | L0–L7, the golden check, and the differential (stored tables byte for byte) | +| **Memory of a streaming join's held inputs** | A streaming `Join` or `MergeJoin` holds every row of both inputs in its hash tables until they close, as `main`'s streaming `Join` does with rows | The hash tables hold Arrow tables and key frames, not datagrams, so they are smaller than `main`'s row buffers | Peak RSS of async runs against `main`'s async run, in stage 0 and stage 5 | +| **Held unmatched rows (`Rejoin`)** | A streaming `Rejoin` holds every unmatched row until it can rule out a match (developer: "unmatched rows will remain in 'to-be matched' in memory all the way until the operator channel closes"). Branches that drop or delay many rows keep them held longer | Matched rows leave both remaining sets at once. When one input closes, the other input's remaining rows are dropped, and the held set then only shrinks. Removal is a mask, with periodic compaction | Peak RSS in stage 5's async benchmark, with a branch that filters most rows out; a test that the held count falls to the closed side's unmatched rows when one input closes | +| **Non-unique system tags (`Rejoin`)** | With duplicate record ids, "match once" pairs duplicates in arrival order, which can differ between sync and async, so the rows differ even as multisets | Out of the design's scope: ITL-1356 makes record ids unique at the source. The equivalence tests use unique record ids, as the rule assumes | A test documents the duplicate case and is excluded, by name, from the set comparison | +| **Sync join order is Polars' unspecified order** (found while writing this) | The sync `Join`, `MergeJoin` and `Rejoin` take their row order from Polars' inner join without `maintain_order` (`join.py:94`, `rejoin.py`). Polars does not guarantee that order, so a Polars upgrade or thread count could reorder the stored rows of a join node on the sync path too. Hashes would not move; stored row order would | Not changed by this design. Making it explicit (`maintain_order="left_right"`) is a separate decision, because it could change today's stored row order (question 10) | Stage 0 compares the current order with `left_right` order over the corpus. The differential runs with the Polars thread count at 1 and at the default | +| **Hidden consumers of row lists** | Code outside the orchestrators reads `node_outputs` or held rows as lists: tests, alignment helpers, user code | The inventory in "Call sites", and the release note | The full suite, and the grep inventory re-run at each stage | + +## Developer decisions (2026-11-22) + +1. **`OrchestratorResult.node_outputs` holds each node's output.** With `NodeTable` gone, it + holds each node's output stream, backed by an Arrow table; `stream.as_table()` gives the + Arrow table. The developer confirms this refinement (question 8). +2. **A function node's first-row column order is kept exactly.** Every stage reproduces it + (L4). Giving it one order is future work, ITL-1353. +3. **A function node's own reads keep cache order for now.** +4. **Stages run in order 0 → 1 → 2 → 3 → 4 → 5.** Stage 2 is split into 2a (sources) and 2b + (operators), which can go to two workers in parallel. + +Also from the developer: +- Async execution handles an object that wraps the channel and carries the stream's + information. +- The protocol change is spelled out in detail. +- The data is named "Arrow table" and "Arrow record batch". +- The stream is primary and owns the description. A stream opens input channels for async + compute, and an output channel closes into an ordinary stream. These are separate, + consolidatable structures, with the conversions in one place (this design). +- Results are identical to `main` unless a named bug is fixed (the governing rule). +- Row order is not critical within a stream or channel. Async runs keep and store arrival + order, as on `main`, and `Batch` grouping by arrival is fine on sync and async. Column order + is not critical either: the async column order (ITL-1249) is not a goal. + +Answers to the spec's questions (developer, 2026-11-22, approving the spec as a whole): + +5. **Source-info nullability stays decided by a complete Arrow table's values.** It is the + one column property `arrow_schema()` does not declare, so stored field flags and the + operator node's record hashes stay as they are. +6. **Batch and buffer sizes**: + - a source sends Arrow record batches of at most 65,536 rows; + - an operator sends its result's own record batches; + - an input channel queues 8 batches. +7. **Signatures change directly in each stage** on `eywalker/job-speed`, with no thin forms + of the old ones. `main` sees one breaking change, at the branch merge. +8. **`node_outputs` holds each node's output stream** (refining decision 1). +9. **Resolved by ITL-1355.** `Rejoin` matches on every shared column with `Join`'s equality, + never refuses on data, and drops unmatched rows. It lands on `main` separately; stage 5's + streaming `Rejoin` builds on it. ITL-1356 makes record ids unique at the source. +10. **Polars' join order** is filed as ITL-1357, low priority, with a design-issue entry + (`docs/dev/design_issues/ITL-1357-JRO1.md`). It is not part of this design. Stage 0 + measures `maintain_order="left_right"` against today's order, as a report only. A first + check already shows that Polars' default order differs from `left_right` in a `MergeJoin` + case (`join._inner_join`). So `left_right` does not reproduce today's order, and making + the order explicit would be a result change for its own decision (report only). +11. **Async write order** keeps `main`'s completion order (row order is not critical). +12. **Bugs found while writing this:** + - e6 is filed as ITL-1358, with a design-issue entry + (`docs/dev/design_issues/ITL-1358-VST1.md`); + - e7 is filed only once a test reproduces it; the developer files it; + - e5 is accepted as documented behaviour, like `Batch`, with no fix. + +**Differences approved as bug fixes**: e1 (ITL-856), e2 (ITL-951), e3 (ITL-1062) and e8 (the +async side-effect node drops the `__computed` meta column, as sync does). + +**Each stage merges** into `eywalker/job-speed` only after the comparison against `main` +shows no change in any sync result. The coordinator verifies and merges. + +## Future work (not designed here) + +- One output column order for a function node, whatever its first row (ITL-1353). +- Source-info nullability declared by `arrow_schema()` (question 5). +- A `null` column through the job layer (ITL-1319). +- `Schema` carrying its Arrow schema (ITL-1307), which `arrow_schema()` then reads. +- Attachments on streams (ITL-1220) and materialization thunks (ITL-605), placed above. +- Batching the side-effect completion lookup (one `get_record_by_id` per row today). +- Polars data frames as a stream's backing, where an operator works in Polars. From edb4148c632bf4d17d6aeb6551128a56b44fc251 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 01:06:33 -0800 Subject: [PATCH 06/86] perf(spiraldb): a source looks its table up once to build and once per check (ITL-1350) (#479) * perf(spiraldb): a source looks its table up once to build and once per check (ITL-1350) Every lookup of a SpiralDB table by name is a round trip. A SpiralDBTableSource looked its table up for each item it needed: four times to build (key, id, schema, version) and three times per new-data check (id, schema, version). SpiralDBConnector.lookup_table returns a SpiralDBTable: the table looked up once, with its id and key columns, and its schema and version read when asked. The source builds and checks from one handle, calling them in the same order and under the same conditions as before (no version read when asof is given; the check compares the id before reading the schema), so what it decides, and every error, is unchanged. A check looks the table up afresh each time, so a table dropped and created again is still found. The connector's getters go through the handle, still one lookup per call; no cache is kept beyond a call. Counted on the repository's pyspiral fake: lookups to build 4 -> 1 (3 -> 1 with asof), per check 3 -> 1; every other call unchanged. A test that faked a keyless table by patching get_pk_columns now patches the handle's key_columns. Co-Authored-By: Claude Opus 5.5 * test(spiraldb): the lookup counts over several keys, data columns, arrangements and roles (ITL-1350) CodeRabbit on #479: the fixture had one key column and one layout. It now builds the table with two key columns and two data columns in two arrangements (key order and column layout), and the tests build the source in both tag roles (plain tags, data-tags), read it through the public sync and async paths, and keep every lookup-count assertion. Co-Authored-By: Claude Opus 5.5 * test(spiraldb): expected rows written out; the arrangements compared (ITL-1350) CodeRabbit on #479: the reads were compared with each other only. The rows are now compared with expected rows written out independently, and a test builds both arrangements as two tables: same rows, same pipeline hash (a schema, no column order), different content hashes (two table ids, and the key order is part of each row's record id). Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Edgar Y. Walker <> Co-authored-by: Claude Opus 5.5 --- changelog.d/ITL-1350.md | 11 + .../core/sources/spiraldb_table_source.py | 23 +- src/orcapod/databases/spiraldb_connector.py | 80 +++++- .../sources/test_spiraldb_lookups.py | 232 ++++++++++++++++++ .../sources/test_spiraldb_table_source.py | 8 +- 5 files changed, 328 insertions(+), 26 deletions(-) create mode 100644 changelog.d/ITL-1350.md create mode 100644 tests/test_core/sources/test_spiraldb_lookups.py diff --git a/changelog.d/ITL-1350.md b/changelog.d/ITL-1350.md new file mode 100644 index 000000000..964573c20 --- /dev/null +++ b/changelog.d/ITL-1350.md @@ -0,0 +1,11 @@ +### Changed + +- A `SpiralDBTableSource` looks its table up once when it is built and once per new-data + check (ITL-1350). Every lookup of a table by name is a round trip to SpiralDB; the + source used to look the table up for each item it needed (key, id, schema and + version: four lookups to build, three per check). `SpiralDBConnector.lookup_table` + returns the table once, with its id and key columns, and reads its schema and version + when asked, in the same order and under the same conditions as before, so a check + still finds a table dropped and created again since. Measured on a live project: + building a source about 1.5 s -> 0.9 s, a check about 1.2 s -> 0.8 s. The connector's + other methods are unchanged. diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index 57d1325f9..8b022ff87 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -443,7 +443,9 @@ def __init__( raise ValueError( f"{location}: Table {table_name!r} not found in database." ) - primary_key = tuple(connector.get_pk_columns(table_name)) + # One lookup for the key, id, schema and version (ITL-1350). + table = connector.lookup_table(table_name) + primary_key = tuple(table.key_columns) self._key_columns: tuple[str, ...] = ( given_key if given_key is not None else primary_key ) @@ -453,15 +455,11 @@ def __init__( "its rows cannot be identified: name key columns with " "record_id_columns=[...]." ) - self._table_id = connector.get_spiral_table_id(table_name) - schema = connector.get_arrow_schema(table_name) + self._table_id = table.table_id + schema = table.arrow_schema() # One version for every read of this source object. A given version is # used as it is; a table that was never written has no version to pin. - self._asof = ( - asof - if asof is not None - else (connector.get_table_version(table_name) or None) - ) + self._asof = asof if asof is not None else (table.version() or None) # The default tags are the primary key, whatever identifies the rows. resolved_tags = ( @@ -790,7 +788,10 @@ def check_for_new_data(self) -> bool: if self._given_asof is not None: return False with self._connector() as connector: - table_id = connector.get_spiral_table_id(self._table_name) + # One lookup per check (ITL-1350): a table dropped and created again since + # is found by this lookup, and its schema and version come from it. + table = connector.lookup_table(self._table_name) + table_id = table.table_id if table_id != self._table_id: raise ValueError( f"SpiralDB table {self._qualified!r} is now another table (id " @@ -798,7 +799,7 @@ def check_for_new_data(self) -> bool: "dropped and created again. Build the source again to read it." ) schema = arrow_utils.drop_system_columns( - connector.get_arrow_schema(self._table_name).empty_table() + table.arrow_schema().empty_table() ).schema if not schema.equals(self._table_schema, check_metadata=True): raise ValueError( @@ -806,7 +807,7 @@ def check_for_new_data(self) -> bool: f"{_schema_difference(schema, self._table_schema)}. Build the " "source again to read it as it is now." ) - version = connector.get_table_version(self._table_name) or None + version = table.version() or None if version is None or (self._asof is not None and version <= self._asof): return False self._asof = version diff --git a/src/orcapod/databases/spiraldb_connector.py b/src/orcapod/databases/spiraldb_connector.py index d3b67dae8..963b78240 100644 --- a/src/orcapod/databases/spiraldb_connector.py +++ b/src/orcapod/databases/spiraldb_connector.py @@ -396,6 +396,55 @@ def _holds_zone_aware_timestamp(arrow_type: pa.DataType) -> bool: ) +class SpiralDBTable: + """One SpiralDB table, looked up once (``SpiralDBConnector.lookup_table``). + + Every lookup of a table by name is a round trip to SpiralDB, and so is each item of + metadata. A caller that needs several items of one table (a source's id, key, schema + and version when it is built, and each run's check) takes them from one handle + instead of looking the table up for each (ITL-1350). The id and the key columns come + with the lookup; the schema and the version are read when asked, in the caller's + order, from the table the lookup found. The handle reads the table as it was when + looked up: look it up again to see a table dropped and created again since. + """ + + def __init__( + self, connector: SpiralDBConnector, table: Any, table_name: str + ) -> None: + """Wrap the pyspiral ``table`` that ``connector`` looked up as ``table_name``.""" + self._connector = connector + self._table = table + self._table_name = table_name + + @property + def table_id(self) -> str: + """SpiralDB's own id of the table (no round trip).""" + return str(self._table.table_id) + + @property + def key_columns(self) -> list[str]: + """The primary-key column names in declaration order (no round trip).""" + return list(self._table.key_schema.names) + + def arrow_schema(self) -> pa.Schema: + """The schema of the batches ``scan_batches`` yields (``get_arrow_schema``). + + Raises: + NullabilityRecordError: If the table's nullability record cannot be read or + names a column the table does not have. + """ + import pyarrow as _pa # noqa: PLC0415 + + declared = self._table.schema().to_arrow() + empty = _pa.RecordBatch.from_pylist([], schema=declared) + preparer = self._connector._batch_preparer(self._table, self._table_name) # pyright: ignore[reportPrivateUsage] # the connector's own preparer + return preparer(empty).schema + + def version(self) -> int: + """The table's current version (``get_table_version``).""" + return int(self._table.last_modified_at()) + + class SpiralDBConnector: """DBConnectorProtocol implementation backed by SpiralDB (pyspiral). @@ -452,6 +501,20 @@ def get_table_names(self) -> list[str]: resources = self._project.list_tables() return sorted(r.table for r in resources if r.dataset == self._dataset) + def lookup_table(self, table_name: str) -> SpiralDBTable: + """Look the table up once, for several items of its metadata (ITL-1350). + + Args: + table_name: Plain table name (no dataset prefix). + + Returns: + The table: its id and key columns, and its schema and version when asked. + """ + self._require_open() + return SpiralDBTable( + self, self._project.table(self._table_id(table_name)), table_name + ) + def get_pk_columns(self, table_name: str) -> list[str]: """Return primary-key column names in declaration order. @@ -461,8 +524,7 @@ def get_pk_columns(self, table_name: str) -> list[str]: Returns: List of PK column names; empty list if the table has no key schema. """ - self._require_open() - return list(self._project.table(self._table_id(table_name)).key_schema.names) + return self.lookup_table(table_name).key_columns def get_column_info(self, table_name: str) -> list[ColumnInfo]: """Return column metadata with Arrow types. @@ -694,13 +756,7 @@ def get_arrow_schema(self, table_name: str) -> pa.Schema: NullabilityRecordError: If the table's nullability record cannot be read or names a column the table does not have. """ - import pyarrow as _pa # noqa: PLC0415 - - self._require_open() - tbl = self._project.table(self._table_id(table_name)) - declared = tbl.schema().to_arrow() - empty = _pa.RecordBatch.from_pylist([], schema=declared) - return self._batch_preparer(tbl, table_name)(empty).schema + return self.lookup_table(table_name).arrow_schema() def get_spiral_table_id(self, table_name: str) -> str: """Return SpiralDB's own id of the table (for example ``table_W7C01nkLTmEJ``). @@ -714,8 +770,7 @@ def get_spiral_table_id(self, table_name: str) -> str: Returns: The table id. """ - self._require_open() - return str(self._project.table(self._table_id(table_name)).table_id) + return self.lookup_table(table_name).table_id def get_table_version(self, table_name: str) -> int: """Return the table's current version, usable as ``asof`` in ``scan_batches``. @@ -727,8 +782,7 @@ def get_table_version(self, table_name: str) -> int: The time of the table's last change, in microseconds; ``0`` for a table that was never written. """ - self._require_open() - return int(self._project.table(self._table_id(table_name)).last_modified_at()) + return self.lookup_table(table_name).version() def get_row_count_estimate(self, table_name: str, asof: int | None = None) -> int: """Return the table's row count as SpiralDB's manifests record it, without scanning. diff --git a/tests/test_core/sources/test_spiraldb_lookups.py b/tests/test_core/sources/test_spiraldb_lookups.py new file mode 100644 index 000000000..314cfdaad --- /dev/null +++ b/tests/test_core/sources/test_spiraldb_lookups.py @@ -0,0 +1,232 @@ +"""A SpiralDB source looks its table up once to build and once per check (ITL-1350). + +Every lookup of a table by name is a round trip to SpiralDB (0.2-0.9 s each in a +workshop-scale profile). A source used to look the table up for each item it needs: four +times to build (key, id, schema, version), three times per new-data check (id, schema, +version). It now takes them from one lookup (``SpiralDBConnector.lookup_table``). The +calls are counted on the repository's pyspiral fake; what the source decides is unchanged. +""" + +from __future__ import annotations + +import asyncio +import collections +from collections.abc import Callable, Iterator +from pathlib import Path +from typing import Any + +import pyarrow as pa +import pytest + +from orcapod.databases import SpiralDBConnector, write_nullability_record +from orcapod.sources import SpiralDBTableSource +from tests.test_databases import fake_pyspiral + +_PROJECT = "lookups" +# Two key columns (tags) and two data columns, in two arrangements: the key order of the +# table and the column layout of its rows (CodeRabbit on #479, the several-items rule). +ARRANGEMENTS: dict[str, tuple[list[str], list[str]]] = { + # name: (key columns in key order, column layout) + "keys_first": (["subject", "k"], ["subject", "k", "x", "y"]), + "reversed": (["k", "subject"], ["y", "x", "k", "subject"]), +} +# The source's tag roles: every key a plain tag, or every key a data-tag (the default). +ROLES: dict[str, bool | tuple[str, ...]] = {"plain": True, "data_tags": ()} +_FIELDS = { + "subject": pa.field("subject", pa.large_string(), nullable=False), + "k": pa.field("k", pa.int64(), nullable=False), + "x": pa.field("x", pa.int64(), nullable=False), + "y": pa.field("y", pa.large_string(), nullable=True), +} +COUNTED = { + (fake_pyspiral.FakeProject, "table"): "lookup", + (fake_pyspiral.FakeProject, "list_tables"): "list_tables", + (fake_pyspiral.FakeTable, "schema"): "schema", + (fake_pyspiral.FakeTable, "last_modified_at"): "version", + (fake_pyspiral.FakeTable, "get_metadata"): "metadata", +} + + +def _schema(layout: list[str]) -> pa.Schema: + return pa.schema([_FIELDS[name] for name in layout]) + + +def _keys(keys: list[str]) -> pa.Schema: + return pa.schema([_FIELDS[name] for name in keys]) + + +def _rows(layout: list[str], ks: list[int]) -> pa.Table: + values = { + "subject": [f"s{k % 2}" for k in ks], + "k": ks, + "x": [10 * k for k in ks], + "y": [f"v{k}" for k in ks], + } + return pa.table({name: values[name] for name in layout}, schema=_schema(layout)) + + +@pytest.fixture(params=sorted(ARRANGEMENTS)) +def calls( + request: pytest.FixtureRequest, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> Iterator[collections.Counter[str]]: + """A fake project with table ``default.t`` in one arrangement; counts the pyspiral + calls made on it.""" + keys, layout = ARRANGEMENTS[request.param] + counts: collections.Counter[str] = collections.Counter() + for (cls, name), label in COUNTED.items(): + original: Callable[..., Any] = getattr(cls, name) # pyright: ignore[reportExplicitAny] # the fake's method + + def wrapper( + *args: Any, # pyright: ignore[reportExplicitAny] # passed through + _original: Callable[..., Any] = original, # pyright: ignore[reportExplicitAny] + _label: str = label, + **kwargs: Any, # pyright: ignore[reportExplicitAny] + ) -> Any: # pyright: ignore[reportExplicitAny] + counts[_label] += 1 + return _original(*args, **kwargs) + + monkeypatch.setattr(cls, name, wrapper) + with fake_pyspiral.install(tmp_path / "spiral"): + project = fake_pyspiral.FakeSpiral().project(_PROJECT) + table = project.create_table("default.t", key_schema=_keys(keys)) + table.write(_rows(layout, [0, 1, 2])) + write_nullability_record(table, _schema(layout)) + _ARRANGED["keys"], _ARRANGED["layout"] = keys, layout + counts.clear() + yield counts + + +# The arrangement the current ``calls`` fixture built (for the recreation test). +_ARRANGED: dict[str, list[str]] = {} + + +def _source(role: str, **kwargs: Any) -> SpiralDBTableSource: # pyright: ignore[reportExplicitAny] # options + return SpiralDBTableSource( + project_id=_PROJECT, table_name="t", tag_only_columns=ROLES[role], **kwargs + ) + + +def _sync_and_async_rows(source: SpiralDBTableSource) -> tuple[list[Any], list[Any]]: # pyright: ignore[reportExplicitAny] # rows + """Every row through the public sync and async reads, tags and data merged.""" + + def merged(tag: Any, data: Any) -> tuple[tuple[str, Any], ...]: # pyright: ignore[reportExplicitAny] + return tuple(sorted({**tag.as_dict(), **data.as_dict()}.items())) + + async def collect() -> list[Any]: # pyright: ignore[reportExplicitAny] + return [merged(t, d) async for t, d in source.async_iter_data()] + + sync = [merged(t, d) for t, d in source.iter_data()] + return sync, asyncio.run(collect()) + + +def _expected_rows(ks: list[int]) -> list[Any]: # pyright: ignore[reportExplicitAny] # rows + """The rows of ``_rows(..., ks)``, written out independently, tags and data merged.""" + return sorted( + tuple( + sorted({"subject": f"s{k % 2}", "k": k, "x": 10 * k, "y": f"v{k}"}.items()) + ) + for k in ks + ) + + +@pytest.mark.parametrize("role", sorted(ROLES)) +def test_a_source_looks_its_table_up_once_to_build( + calls: collections.Counter[str], role: str +) -> None: + source = _source(role) + # Before ITL-1350: 4 lookups (key, id, schema, version). + assert calls == { + "list_tables": 1, + "lookup": 1, + "schema": 1, + "metadata": 1, + "version": 1, + } + # Its reads are those of every source: the key order, layout and role it has. + tags, data = source.keys() + assert set(tags) == {"subject", "k"} + assert {"x", "y"} <= set(data) + assert (set(tags) <= set(data)) == (role == "data_tags") + sync, async_ = _sync_and_async_rows(source) + assert sorted(sync) == sorted(async_) == _expected_rows([0, 1, 2]) + + +@pytest.mark.parametrize("role", sorted(ROLES)) +def test_a_source_with_a_given_version_reads_no_version( + calls: collections.Counter[str], role: str +) -> None: + _source(role, asof=1) + # Before ITL-1350: 3 lookups (key, id, schema). + assert calls == {"list_tables": 1, "lookup": 1, "schema": 1, "metadata": 1} + + +@pytest.mark.parametrize("role", sorted(ROLES)) +def test_each_check_looks_the_table_up_once( + calls: collections.Counter[str], role: str +) -> None: + source = _source(role) + for _ in range(2): + calls.clear() + assert source.check_for_new_data() is False + # Before ITL-1350: 3 lookups (id, schema, version). + assert calls == {"lookup": 1, "schema": 1, "metadata": 1, "version": 1} + sync, async_ = _sync_and_async_rows(source) + assert sorted(sync) == sorted(async_) == _expected_rows([0, 1, 2]) + + +@pytest.mark.parametrize("role", sorted(ROLES)) +def test_a_check_still_finds_a_table_created_again( + calls: collections.Counter[str], role: str +) -> None: + source = _source(role) + keys, layout = _ARRANGED["keys"], _ARRANGED["layout"] + project = fake_pyspiral.FakeSpiral().project(_PROJECT) + project.drop_table("default.t") + again = project.create_table("default.t", key_schema=_keys(keys)) + again.write(_rows(layout, [0, 1, 2, 3])) + write_nullability_record(again, _schema(layout)) + calls.clear() + with pytest.raises(ValueError, match="dropped and created again"): + source.check_for_new_data() + # Refused on the id, before the new table's schema or version is read. + assert calls == {"lookup": 1} + + +def test_the_connector_getters_answer_as_the_handle_does( + calls: collections.Counter[str], +) -> None: + with SpiralDBConnector(project_id=_PROJECT) as connector: + table = connector.lookup_table("t") + # The key columns in the table's key order. + assert connector.get_pk_columns("t") == table.key_columns == _ARRANGED["keys"] + assert connector.get_spiral_table_id("t") == table.table_id + assert connector.get_arrow_schema("t").equals( + table.arrow_schema(), check_metadata=True + ) + assert table.arrow_schema().names == _ARRANGED["layout"] + assert connector.get_table_version("t") == table.version() + + +@pytest.mark.parametrize("role", sorted(ROLES)) +def test_the_arrangements_give_the_same_rows_and_pipeline_hash( + tmp_path: Path, role: str +) -> None: + """Two tables holding the same rows in the two arrangements: the same rows and the + same pipeline hash (a schema, in no column order); different content hashes, since + they are two tables (two table ids) and the key order is part of a row's record id.""" + with fake_pyspiral.install(tmp_path / "spiral"): + project = fake_pyspiral.FakeSpiral().project(_PROJECT) + sources = {} + for name, (keys, layout) in ARRANGEMENTS.items(): + table = project.create_table(f"default.{name}", key_schema=_keys(keys)) + table.write(_rows(layout, [0, 1, 2])) + write_nullability_record(table, _schema(layout)) + sources[name] = SpiralDBTableSource( + project_id=_PROJECT, table_name=name, tag_only_columns=ROLES[role] + ) + first, second = sources.values() + for source in (first, second): + sync, async_ = _sync_and_async_rows(source) + assert sorted(sync) == sorted(async_) == _expected_rows([0, 1, 2]) + assert first.pipeline_hash() == second.pipeline_hash() + assert first.content_hash() != second.content_hash() diff --git a/tests/test_core/sources/test_spiraldb_table_source.py b/tests/test_core/sources/test_spiraldb_table_source.py index 8dad21588..9bcca9bbf 100644 --- a/tests/test_core/sources/test_spiraldb_table_source.py +++ b/tests/test_core/sources/test_spiraldb_table_source.py @@ -24,13 +24,14 @@ from collections.abc import Generator from pathlib import Path from typing import Any, cast -from unittest.mock import patch +from unittest.mock import PropertyMock, patch import pyarrow as pa import pytest from orcapod.core.sources import SpiralDBTableSource from orcapod.databases import SpiralDBConnector +from orcapod.databases.spiraldb_connector import SpiralDBTable from tests.test_databases import fake_pyspiral _TABLE_NAME = "spike_data" @@ -228,7 +229,10 @@ def test_missing_table_raises_value_error(self): def test_a_table_without_a_key_schema_raises(self, tag_columns): """Rows are identified by their primary key, so a key schema is required.""" _make_table() - with patch.object(SpiralDBConnector, "get_pk_columns", return_value=[]): + # The source reads the key from its one lookup of the table (ITL-1350). + with patch.object( + SpiralDBTable, "key_columns", new_callable=PropertyMock, return_value=[] + ): with pytest.raises(ValueError, match="no primary key"): SpiralDBTableSource( _PROJECT_ID, From 3fdcf960c49a17fc9cc1970d379d232df0d4ef3a Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 01:34:23 -0800 Subject: [PATCH 07/86] docs(dev): ITL-1347 stage 0: measurements and the differential harness (#481) * docs(dev): ITL-1347 stage 0 harness: counters, fixtures, dump, compare, differential driver, join-order plugin Co-Authored-By: Claude Opus 5.5 * docs(dev): ITL-1347 stage 0 measurements; harness compares floats by bits, events per node, counts trusted rows Co-Authored-By: Claude Opus 5.5 * docs(dev): ITL-1347 harness README: the recorded-arrival checks stage 5 adds Co-Authored-By: Claude Opus 5.5 * docs(dev): ITL-1347 harness: node errors compared, volatile validity and float bits in multisets, gate exit status, compare-only keeps the report Co-Authored-By: Claude Opus 5.5 * docs(dev): ITL-1347 harness: a comparison that cannot complete fails the gate (compare.py exits 3 on differences) Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Edgar Y. Walker <> Co-authored-by: Claude Opus 5.5 --- docs/dev/scripts/itl_1347/README.md | 53 ++++ docs/dev/scripts/itl_1347/compare.py | 252 ++++++++++++++++++ docs/dev/scripts/itl_1347/differential.py | 236 ++++++++++++++++ docs/dev/scripts/itl_1347/dump.py | 214 +++++++++++++++ docs/dev/scripts/itl_1347/fixtures.py | 172 ++++++++++++ docs/dev/scripts/itl_1347/instrument.py | 199 ++++++++++++++ .../dev/scripts/itl_1347/join_order_plugin.py | 71 +++++ docs/dev/specs/itl-1347/stage-0.md | 127 +++++++++ 8 files changed, 1324 insertions(+) create mode 100644 docs/dev/scripts/itl_1347/README.md create mode 100644 docs/dev/scripts/itl_1347/compare.py create mode 100644 docs/dev/scripts/itl_1347/differential.py create mode 100644 docs/dev/scripts/itl_1347/dump.py create mode 100644 docs/dev/scripts/itl_1347/fixtures.py create mode 100644 docs/dev/scripts/itl_1347/instrument.py create mode 100644 docs/dev/scripts/itl_1347/join_order_plugin.py create mode 100644 docs/dev/specs/itl-1347/stage-0.md diff --git a/docs/dev/scripts/itl_1347/README.md b/docs/dev/scripts/itl_1347/README.md new file mode 100644 index 000000000..03843795d --- /dev/null +++ b/docs/dev/scripts/itl_1347/README.md @@ -0,0 +1,53 @@ +# ITL-1347 measurement and differential harness + +Scripts for the stages of `docs/dev/specs/itl-1347-job-table-transport.md`. None of them +changes the library. They use only the public API, except where `instrument.py` wraps +internals for the duration of a block. + +| Script | What it does | +|---|---| +| `instrument.py` | `counting()`: datagrams made, by node kind and class; `_rows_to_table` calls, rows and seconds, by caller; node `execute` / `async_execute` calls and inclusive seconds. `edges_per_node(job)`. | +| `fixtures.py` | Fixture jobs on the tutorial dataset: `tutorial` (the tutorial's pipeline) and `spikes` (one row per spike, every operator kind once, a side effect). `ITL1347_SPIKES_MAX` limits the spike rows for a quick check. | +| `dump.py` | Runs one fixture in one mode (`cold`, `warm`, `held`, `load_only`) on one orchestrator, and dumps the run summary, the warnings, a recording observer's events, every node's `as_table(all_info=True)`, every stored table and its Delta version count, peak RSS and wall time. | +| `compare.py` | Compares two dumps: `--mode exact` (byte for byte, row order included) or `--mode set` (rows as a multiset, columns by name). Floats are compared by their bits (Arrow's `equals` holds NaN unequal to itself). `--calibrate` finds the volatile columns (values a run makes afresh: a `uuid7` datagram id, a write time, the source-info tokens that embed them) from two dumps of the same checkout. Those, and `__pf_var_git_hash` (the checkout's git state), are the only columns left out. Observer events are compared node by node, because `main` starts independent nodes in an order that varies between runs. | +| `differential.py` | Runs the whole differential: every fixture, mode, orchestrator and Polars thread count, under two interpreters, then the three comparisons. `--compare-only` redoes the comparisons on existing dumps. | +| `join_order_plugin.py` | A pytest plugin (ITL-1357, report only): every Polars inner join without `maintain_order` is recomputed with `maintain_order="left_right"` and the row orders are compared. | + +## The differential (each stage's gate) + +1. Build one environment per Orcapod under test, from a built wheel: pinned `main` and the + stage branch. `uv run --with ` can reuse a cached build of the same version + string, so install each wheel into its own environment and check the version and file + it imports before measuring. +2. For each fixture, mode, orchestrator and Polars thread count (`POLARS_MAX_THREADS=1` and + the default), run `dump.py` with each environment's interpreter, in its own work + directory. A `warm` or `load_only` dump runs in the work directory a `cold` dump left. +3. Calibrate the volatile columns from two dumps of the same environment. +4. Compare: + - sync on the branch against sync on `main`, `--mode exact`; + - async on the branch against sync on the branch, `--mode set`; + - async on the branch against async on `main`, `--mode set`. + + Only the differences the spec lists by name may remain. + +Outputs are raw records: keep them outside the repository. + +## What stage 5 adds to the differential + +The spec's gate (section "Proof", item 3) is complete. This harness implements what stages +1–4 need: sync against pinned `main` byte for byte, async against sync and against `main`'s +async as multisets. Stage 5, where `Batch` and order-dependent `PolarsFilter` see arrival +orders the sync run never produces, adds the recorded-arrival checks: + +1. **The arrival-dependent set**: every `Batch`, or `PolarsFilter` with an order-dependent + predicate, whose input arrived in another order than on sync in either async run (the + branch's or `main`'s), together with all its descendants in the job's graph. +2. **Recorded arrivals**: for each node in the set, the rows of each input in the order the + node received them. Record them by wrapping the node's input channels, with no library + change. +3. **Per-node consistency**: recompute the node with pinned `main`'s operator, on the sync + path, over those recorded inputs in that order. The node's async output must equal the + recomputation as a multiset, apart from the spec's named differences. +4. **Edge conservation**: on every edge into or inside the set, the recorded input rows + equal the producer's output rows in the same run, as a multiset with multiplicity. +5. **Everything outside the set** is compared as above. diff --git a/docs/dev/scripts/itl_1347/compare.py b/docs/dev/scripts/itl_1347/compare.py new file mode 100644 index 000000000..6ac088422 --- /dev/null +++ b/docs/dev/scripts/itl_1347/compare.py @@ -0,0 +1,252 @@ +"""ITL-1347 differential, the comparison: two dumps of ``dump.py``, exactly or as sets. + + uv run python compare.py --mode exact|set [--volatile volatile.json] + uv run python compare.py --calibrate volatile.json + +- ``exact`` (sync branch against sync pinned ``main``): every node table and stored table is + equal byte for byte (``Table.equals(check_metadata=True)`` on combined chunks, schemas + field by field), the row order included. The same holds for the run summary, the errors, + the warnings, the observer events and the Delta version counts. Only the volatile columns + are left out of the value comparison. Their schema and null pattern are still compared. +- ``set`` (async against sync): the same, except that rows are compared as a multiset, with + columns matched by name; observer events are compared as a multiset too. +- ``--calibrate``: compares two dumps of the **same** checkout and writes the columns whose + values differ between them (identifiers and timestamps a run makes, such as a ``uuid7`` + datagram id or a write time) to ``volatile.json``. Only those columns are ever left out. + +Exit status 0 when equal, 3 when the comparison completed and found differences (every +difference is printed). Any other status (Python's 1 on an uncaught error) means the +comparison could not complete. +""" + +from __future__ import annotations + +import argparse +import json +import sys +from pathlib import Path +from typing import Any + +import pyarrow as pa + + +def _read(path: Path) -> pa.Table: + with pa.memory_map(str(path), "r") as source: + return pa.ipc.open_file(source).read_all().combine_chunks() + + +# Columns whose value depends on the environment, not on the code under test: the git +# state of the file a function is defined in (``-dirty``, ``-untracked``), which changes +# whenever a file is added to the checkout during a run. Left out like volatile columns. +ENVIRONMENT_COLUMNS = frozenset({"__pf_var_git_hash"}) + + +# The exit status of a completed comparison that found differences. It is distinct from +# Python's 1 for an uncaught error, so a caller can tell the two apart. +DIFFERENCES_FOUND = 3 + + +def _events_by_node(events: list[Any]) -> dict[str, list[str]]: + """Each node's events, in order; run-level events under ``""``. + + The order in which ``main`` starts independent nodes (two sources, say) varies from one + process to the next, so only each node's own sequence of events is a result. + """ + grouped: dict[str, list[str]] = {} + for event in events: + label = event[1] if len(event) > 1 else "" + grouped.setdefault(label, []).append(json.dumps(event)) + return grouped + + +def _tables(dump: Path) -> dict[str, pa.Table]: + manifest = json.loads((dump / "manifest.json").read_text()) + found: dict[str, pa.Table] = {} + for group in ("nodes", "stored"): + for name, entry in manifest[group].items(): + if "file" in entry: + found[f"{group}:{name}"] = _read(dump / entry["file"]) + return found + + +def _schema_differences(key: str, a: pa.Table, b: pa.Table) -> list[str]: + if a.schema.equals(b.schema, check_metadata=True): + return [] + lines = [f"{key}: schemas differ"] + for name in sorted(set(a.column_names) | set(b.column_names)): + if name not in a.column_names or name not in b.column_names: + lines.append(f" column {name!r} only in one side") + continue + fa, fb = a.schema.field(name), b.schema.field(name) + if not fa.equals(fb, check_metadata=True): + lines.append(f" {name!r}: {fa} != {fb}") + if a.column_names != b.column_names: + lines.append(f" column order: {a.column_names} != {b.column_names}") + return lines + + +_FLOAT_BITS = {16: pa.uint16(), 32: pa.uint32(), 64: pa.uint64()} + + +def _bits(array: Any) -> Any: + """``array`` with every float as its integer bits, so equality is bit for bit. + + Arrow's ``equals`` holds NaN unequal to itself; two tables with the same NaN bits must + compare equal, and ``0.0`` must stay distinct from ``-0.0``. Lists, fixed-size lists + and structs are rebuilt over their converted children, keeping their validity. + """ + kind = array.type + if pa.types.is_floating(kind): + return array.view(_FLOAT_BITS[kind.bit_width]) + if pa.types.is_list(kind) or pa.types.is_large_list(kind): + cls = pa.LargeListArray if pa.types.is_large_list(kind) else pa.ListArray + return cls.from_arrays(array.offsets, _bits(array.values), mask=array.is_null()) + if pa.types.is_fixed_size_list(kind): + return pa.FixedSizeListArray.from_arrays( + _bits(array.values), kind.list_size, mask=array.is_null() + ) + if pa.types.is_struct(kind): + children = [_bits(array.field(i)) for i in range(kind.num_fields)] + return pa.StructArray.from_arrays( + children, + fields=[ + kind.field(i).with_type(child.type) for i, child in enumerate(children) + ], + mask=array.is_null(), + ) + return array + + +def _bitwise(table: pa.Table) -> pa.Table: + """``table`` with every column through ``_bits`` (names kept).""" + columns = [_bits(column.combine_chunks()) for column in table.columns] + return pa.Table.from_arrays(columns, names=table.column_names) + + +def _without(table: pa.Table, volatile: set[str]) -> pa.Table: + return table.drop_columns([c for c in table.column_names if c in volatile]) + + +def _rows_as_multiset(table: pa.Table) -> list[str]: + """The rows as a sorted list of their serialized values, duplicates kept. + + Floats are taken by their bits (``_bitwise``), so NaN payloads stay distinct. + """ + table = _bitwise(table) + names = sorted(table.column_names) + return sorted( + json.dumps([repr(row[n]) for n in names]) + for row in table.select(names).to_pylist() + ) + + +def compare( + a: Path, b: Path, mode: str, volatile_by_table: dict[str, list[str]] +) -> list[str]: + """Every difference between dumps ``a`` and ``b``.""" + problems: list[str] = [] + ma = json.loads((a / "manifest.json").read_text()) + mb = json.loads((b / "manifest.json").read_text()) + for field in ("error", "summary", "warnings"): + if ma[field] != mb[field]: + problems.append(f"{field}: {ma[field]!r} != {mb[field]!r}") + events_a: Any = _events_by_node(ma["events"]) + events_b: Any = _events_by_node(mb["events"]) + if mode == "set": + events_a = sorted(json.dumps(e) for e in ma["events"]) + events_b = sorted(json.dumps(e) for e in mb["events"]) + if events_a != events_b: + problems.append("observer events differ") + for group in ("nodes", "stored"): + only = sorted(set(ma[group]) ^ set(mb[group])) + if only: + problems.append(f"{group}: only in one dump: {only}") + for name in sorted(set(ma["nodes"]) & set(mb["nodes"])): + ea, eb = ma["nodes"][name].get("error"), mb["nodes"][name].get("error") + if ea != eb: + problems.append(f"nodes:{name}: as_table error {ea!r} != {eb!r}") + for name in sorted(set(ma["stored"]) | set(mb["stored"])): + va = ma["stored"].get(name, {}).get("versions") + vb = mb["stored"].get(name, {}).get("versions") + if va != vb: + problems.append(f"stored:{name}: Delta versions {va} != {vb}") + ta, tb = _tables(a), _tables(b) + for key in sorted(set(ta) | set(tb)): + if key not in ta or key not in tb: + problems.append(f"{key}: only in one dump") + continue + x, y = ta[key], tb[key] + volatile = set(volatile_by_table.get(key, [])) | ENVIRONMENT_COLUMNS + if mode == "exact": + problems += _schema_differences(key, x, y) + else: + x, y = x.select(sorted(x.column_names)), y.select(sorted(y.column_names)) + problems += _schema_differences(key, x, y) + if x.num_rows != y.num_rows: + problems.append(f"{key}: {x.num_rows} rows != {y.num_rows} rows") + continue + for name in volatile & set(x.column_names) & set(y.column_names): + if mode == "exact" and not x.column(name).is_null().equals( + y.column(name).is_null() + ): + problems.append(f"{key}: null pattern of volatile {name!r} differs") + if mode == "set": + # Keep each volatile column's validity with its row, then drop its values. + for name in sorted(volatile & set(x.column_names) & set(y.column_names)): + x = x.append_column(f"__valid__{name}", x.column(name).is_valid()) + y = y.append_column(f"__valid__{name}", y.column(name).is_valid()) + xs, ys = _without(x, volatile), _without(y, volatile) + if mode == "exact": + if not _bitwise(xs).equals(_bitwise(ys)): + problems.append(f"{key}: values differ") + elif _rows_as_multiset(xs) != _rows_as_multiset(ys): + problems.append(f"{key}: rows differ as sets") + return problems + + +def calibrate(a: Path, b: Path) -> dict[str, list[str]]: + """The columns whose values differ between two dumps of the same checkout.""" + volatile: dict[str, list[str]] = {} + ta, tb = _tables(a), _tables(b) + for key in sorted(set(ta) & set(tb)): + x, y = ta[key], tb[key] + if x.num_rows != y.num_rows: + continue + names = [n for n in x.column_names if n in y.column_names] + differing = [ + n + for n in names + if not _bits(x.column(n).combine_chunks()).equals( + _bits(y.column(n).combine_chunks()) + ) + ] + if differing: + volatile[key] = differing + return volatile + + +def main(argv: list[str]) -> int: + parser = argparse.ArgumentParser() + parser.add_argument("a", type=Path) + parser.add_argument("b", type=Path) + parser.add_argument("--mode", choices=("exact", "set"), default="exact") + parser.add_argument("--volatile", type=Path) + parser.add_argument("--calibrate", type=Path) + args = parser.parse_args(argv) + if args.calibrate is not None: + found = calibrate(args.a, args.b) + args.calibrate.write_text(json.dumps(found, indent=1, sort_keys=True)) + print(json.dumps(found, indent=1, sort_keys=True)) + return 0 + volatile: dict[str, Any] = ( + json.loads(args.volatile.read_text()) if args.volatile is not None else {} + ) + problems = compare(args.a, args.b, args.mode, volatile) + for line in problems: + print(line) + print("EQUAL" if not problems else f"{len(problems)} DIFFERENCES") + return 0 if not problems else DIFFERENCES_FOUND + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/docs/dev/scripts/itl_1347/differential.py b/docs/dev/scripts/itl_1347/differential.py new file mode 100644 index 000000000..947553156 --- /dev/null +++ b/docs/dev/scripts/itl_1347/differential.py @@ -0,0 +1,236 @@ +"""ITL-1347 differential driver: every fixture, mode, orchestrator and thread count, two Orcapods. + + python differential.py OUT --base --branch + [--fixtures tutorial,spikes] [--threads 1,default] + +``--base`` and ``--branch`` are the interpreters of two environments, each with one Orcapod +installed from a built wheel (pinned ``main`` and the stage branch). Every dump runs in its +own process, one after another. For each fixture: + +1. two ``cold`` sync dumps with the base interpreter calibrate the volatile columns + (``compare.py --calibrate``); +2. for each interpreter, orchestrator (``sync``, ``async``) and Polars thread count: a + ``cold`` dump, then ``warm`` and ``load_only`` dumps over the store it left, and a + ``held`` dump over a new store; +3. comparisons: + - branch sync against base sync, ``exact``; + - branch async against branch sync, ``set``; + - branch async against base async, ``set``. + +Writes ``OUT/report.json`` (every comparison with its differences; ``--compare-only`` +writes ``OUT/report_compare_only.json`` and leaves ``report.json`` as it is) and prints a +summary. The exit status is the gate: 1 if a dump process failed or a comparison could not +complete (its stderr is kept in the report), 2 if sync on the branch differs from sync on +base, else 0. Completed async differences are printed for review against the spec's +named differences and do not set the status. +""" + +from __future__ import annotations + +import argparse +import json +import os +import subprocess +import sys +import time +from pathlib import Path +from typing import Any + +HERE = Path(__file__).resolve().parent +MODES = ("cold", "warm", "load_only", "held") + + +def _dump( + python: str, + fixture: str, + mode: str, + orchestrator: str, + threads: str, + workdir: Path, + out: Path, +) -> dict[str, Any]: + env = dict(os.environ) + if threads == "default": + env.pop("POLARS_MAX_THREADS", None) + else: + env["POLARS_MAX_THREADS"] = threads + start = time.perf_counter() + done = subprocess.run( + [ + python, + str(HERE / "dump.py"), + fixture, + mode, + orchestrator, + str(workdir), + str(out), + ], + env=env, + capture_output=True, + text=True, + check=False, + ) + return { + "dump": str(out), + "returncode": done.returncode, + "stderr_tail": done.stderr[-2000:] if done.returncode else "", + "seconds": round(time.perf_counter() - start, 2), + } + + +def _compare(a: Path, b: Path, mode: str, volatile: Path) -> dict[str, Any]: + done = subprocess.run( + [ + sys.executable, + str(HERE / "compare.py"), + str(a), + str(b), + "--mode", + mode, + "--volatile", + str(volatile), + ], + capture_output=True, + text=True, + check=False, + ) + # compare.py exits 0 (equal) or 3 (completed, with differences); anything else means + # the comparison could not complete, and its stderr is kept. + completed = done.returncode in (0, 3) + return { + "a": str(a), + "b": str(b), + "mode": mode, + "completed": completed, + "stderr_tail": "" if completed else done.stderr[-2000:], + "equal": done.returncode == 0, + "output": done.stdout.splitlines()[-40:], + } + + +def main(argv: list[str]) -> int: + parser = argparse.ArgumentParser() + parser.add_argument("out", type=Path) + parser.add_argument("--base", required=True) + parser.add_argument("--branch", required=True) + parser.add_argument("--fixtures", default="tutorial,spikes") + parser.add_argument("--threads", default="1,default") + parser.add_argument( + "--compare-only", + action="store_true", + help="redo the comparisons on the dumps already in OUT; run nothing", + ) + args = parser.parse_args(argv) + out: Path = args.out + out.mkdir(parents=True, exist_ok=args.compare_only) + pythons = {"base": args.base, "branch": args.branch} + + def dump_fn(*dump_args: Any) -> dict[str, Any]: + if args.compare_only: + return {"dump": str(dump_args[-1]), "returncode": 0, "skipped": True} + return _dump(*dump_args) + + report: dict[str, Any] = {"runs": [], "comparisons": [], "load": []} + for fixture in args.fixtures.split(","): + calib = [out / fixture / f"calibrate_{i}" for i in (1, 2)] + for i, dump in enumerate(calib, start=1): + report["runs"].append( + dump_fn( + pythons["base"], + fixture, + "cold", + "sync", + "default", + out / fixture / f"calibrate_work_{i}", + dump, + ) + ) + volatile = out / fixture / "volatile.json" + subprocess.run( + [ + sys.executable, + str(HERE / "compare.py"), + str(calib[0]), + str(calib[1]), + "--calibrate", + str(volatile), + ], + capture_output=True, + check=True, + ) + for threads in args.threads.split(","): + for side, python in pythons.items(): + for orchestrator in ("sync", "async"): + tag = f"{side}_{orchestrator}_t{threads}" + work = out / fixture / f"work_{tag}" + held_work = out / fixture / f"work_{tag}_held" + for mode in MODES: + report["load"].append(os.getloadavg()[0]) + report["runs"].append( + dump_fn( + python, + fixture, + mode, + orchestrator, + threads, + held_work if mode == "held" else work, + out / fixture / f"{tag}_{mode}", + ) + ) + for mode in MODES: + + def d(side: str, orchestrator: str) -> Path: + return out / fixture / f"{side}_{orchestrator}_t{threads}_{mode}" + + report["comparisons"] += [ + { + "fixture": fixture, + "threads": threads, + "check": f"sync branch vs base, {mode}", + } + | _compare( + d("base", "sync"), d("branch", "sync"), "exact", volatile + ), + { + "fixture": fixture, + "threads": threads, + "check": f"async vs sync, branch, {mode}", + } + | _compare( + d("branch", "sync"), d("branch", "async"), "set", volatile + ), + { + "fixture": fixture, + "threads": threads, + "check": f"async branch vs base, {mode}", + } + | _compare( + d("base", "async"), d("branch", "async"), "set", volatile + ), + ] + report_name = "report_compare_only.json" if args.compare_only else "report.json" + (out / report_name).write_text(json.dumps(report, indent=1)) + failed_runs = [r for r in report["runs"] if r["returncode"] != 0] + incomplete = [c for c in report["comparisons"] if not c["completed"]] + for c in report["comparisons"]: + status = ( + "EQUAL" if c["equal"] else "DIFFERENT" if c["completed"] else "INCOMPLETE" + ) + print(f"{status:9} {c['fixture']:8} t={c['threads']:7} {c['check']}") + print(f"{len(failed_runs)} dump processes failed") + print(f"{len(incomplete)} comparisons could not complete") + # The exit status is the gate. A failed dump or a comparison that could not complete + # makes the run incomplete (1). A sync difference against main fails the governing + # rule (2). Completed async differences are printed for review against the spec's + # named differences, and do not set it. + if failed_runs or incomplete: + return 1 + if any( + not c["equal"] and c["check"].startswith("sync") for c in report["comparisons"] + ): + return 2 + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/docs/dev/scripts/itl_1347/dump.py b/docs/dev/scripts/itl_1347/dump.py new file mode 100644 index 000000000..e510310a0 --- /dev/null +++ b/docs/dev/scripts/itl_1347/dump.py @@ -0,0 +1,214 @@ +"""ITL-1347 differential, one side: run a fixture job and dump everything it shows. + +Run it with the interpreter of the checkout under test (pinned ``main`` or a stage branch); +the script uses only the public API: + + cd && uv run python + +- ``fixture``: a name in ``fixtures.FIXTURES``. +- ``mode``: ``cold`` (fresh store, one run), ``warm`` (a fresh process over the store a + ``cold`` run left in ``workdir``, one run), ``held`` (two runs in one process over a fresh + store; the second is dumped), ``load_only`` (a fresh process over the store a ``cold`` + run left, ``run(load_only=True)``). +- ``orchestrator``: ``sync`` or ``async``. +- ``workdir``: holds the dataset (``data/``) and the Delta store (``store/``). +- ``out``: an empty directory for the dump. + +The dump: ``manifest.json`` (the run summary, the warnings, the recording observer's events, +each node's table status, the stored tables with their Delta version counts, peak RSS and +wall time) and one Arrow IPC file per node table (``as_table(all_info=True)``) and per stored +table. ``compare.py`` compares two dumps. +""" + +from __future__ import annotations + +import dataclasses +import json +import os +import resource +import sys +import time +import warnings +from pathlib import Path +from typing import Any + +import pyarrow as pa + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +sys.path.insert(0, str(Path(__file__).resolve().parents[3] / "tutorial")) + + +def _jsonable(given: object) -> Any: + """A JSON-ready form of ``given``: plain data kept, anything else as its repr.""" + value: Any = given + if value is None or isinstance(value, (bool, int, float, str)): + return value + if isinstance(value, (list, tuple)): + return [_jsonable(v) for v in value] + if isinstance(value, dict): + return {str(k): _jsonable(v) for k, v in value.items()} + items = getattr(value, "items", None) + if callable(items): + pairs: Any = items() + return {str(k): _jsonable(v) for k, v in pairs} + if dataclasses.is_dataclass(value) and not isinstance(value, type): + fields = dataclasses.fields(value) + return {f.name: _jsonable(getattr(given, f.name)) for f in fields} + if hasattr(value, "__dict__") and not isinstance(value, type): + return {k: _jsonable(v) for k, v in sorted(vars(value).items()) if k[:1] != "_"} + return repr(value) + + +class RecordingObserver: + """An observer that records every event, with the tag values it was given.""" + + def __init__(self) -> None: + self.events: list[list[Any]] = [] + + def contextualize(self, *identity_path: str) -> RecordingObserver: + return self + + def on_run_start(self, run_id: str, pipeline_uri: str = "") -> None: + self.events.append(["run_start"]) + + def on_run_end(self, run_id: str) -> None: + self.events.append(["run_end"]) + + def on_node_start( + self, node_label: str, node_hash: str, tag_schema: Any = None + ) -> None: + self.events.append(["node_start", node_label, node_hash]) + + def on_node_end(self, node_label: str, node_hash: str) -> None: + self.events.append(["node_end", node_label, node_hash]) + + def on_data_start(self, node_label: str, tag: Any, data: Any) -> None: + self.events.append(["data_start", node_label, _jsonable(tag.as_dict())]) + + def on_data_end( + self, + node_label: str, + tag: Any, + input_data: Any, + output_data: Any, + cached: bool, + ) -> None: + out = None if output_data is None else _jsonable(output_data.as_dict()) + self.events.append( + ["data_end", node_label, _jsonable(tag.as_dict()), out, cached] + ) + + def on_data_crash(self, node_label: str, tag: Any, data: Any, error: Any) -> None: + self.events.append( + ["data_crash", node_label, _jsonable(tag.as_dict()), type(error).__name__] + ) + + def create_data_logger(self, tag: Any, data: Any) -> Any: + from orcapod.pipeline.observer import NoOpObserver + + return NoOpObserver().create_data_logger(tag, data) + + +def _write_ipc(table: pa.Table, path: Path) -> None: + with ( + pa.OSFile(str(path), "wb") as sink, + pa.ipc.new_file(sink, table.schema) as writer, + ): + writer.write_table(table) + + +def _stored_tables(store: Path) -> dict[str, tuple[pa.Table, int]]: + """Every Delta table under ``store``: its rows and its number of versions.""" + from deltalake import DeltaTable + + found: dict[str, tuple[pa.Table, int]] = {} + for dirpath, dirnames, _ in os.walk(store): + if "_delta_log" in dirnames: + log = Path(dirpath) / "_delta_log" + versions = len([f for f in os.listdir(log) if f.endswith(".json")]) + table = DeltaTable(dirpath).to_pyarrow_table() + found[os.path.relpath(dirpath, store)] = (table, versions) + dirnames.clear() + return found + + +def main(argv: list[str]) -> int: + fixture, mode, orchestrator, workdir_arg, out_arg = argv + import importlib + + fixtures_module: Any = importlib.import_module("fixtures") + workshop_data: Any = importlib.import_module("workshop_data") + FIXTURES = fixtures_module.FIXTURES + make_dataset = workshop_data.make_dataset + + from orcapod.databases import DeltaTableDatabase + from orcapod.pipeline import AsyncPipelineOrchestrator + + workdir = Path(workdir_arg) + out = Path(out_arg) + out.mkdir(parents=True, exist_ok=False) + data_dir = make_dataset(workdir / "data") + store = workdir / "store" + database = DeltaTableDatabase(store) + job = FIXTURES[fixture](data_dir, database) + run_kwargs: dict[str, Any] = {} + if orchestrator == "async": + run_kwargs["orchestrator"] = AsyncPipelineOrchestrator() + + observer = RecordingObserver() + error: str | None = None + summary: Any = None + started = time.perf_counter() + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + try: + if mode == "held": + job.run(**run_kwargs) + observer.events.clear() + summary = job.run( + observer=observer, load_only=(mode == "load_only"), **run_kwargs + ) + except Exception as exc: # recorded: an error is a result too + error = f"{type(exc).__name__}: {exc}" + seconds = time.perf_counter() - started + + nodes: dict[str, Any] = {} + for label in sorted(job.nodes): + node = job.nodes[label] + try: + table = node.as_table(all_info=True) + except Exception as exc: + nodes[label] = {"error": f"{type(exc).__name__}: {exc}"} + continue + name = f"node_{len(nodes):03d}.arrow" + _write_ipc(table, out / name) + nodes[label] = {"file": name, "rows": table.num_rows} + + stored: dict[str, Any] = {} + for index, (path, (table, versions)) in enumerate( + sorted(_stored_tables(store).items()) + ): + name = f"stored_{index:03d}.arrow" + _write_ipc(table, out / name) + stored[path] = {"file": name, "rows": table.num_rows, "versions": versions} + + manifest = { + "fixture": fixture, + "mode": mode, + "orchestrator": orchestrator, + "polars_max_threads": os.environ.get("POLARS_MAX_THREADS", "default"), + "error": error, + "summary": _jsonable(summary), + "warnings": sorted({f"{w.category.__name__}: {w.message}" for w in caught}), + "events": observer.events, + "nodes": nodes, + "stored": stored, + "seconds": round(seconds, 3), + "peak_rss_bytes": resource.getrusage(resource.RUSAGE_SELF).ru_maxrss, + } + (out / "manifest.json").write_text(json.dumps(manifest, indent=1, sort_keys=True)) + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/docs/dev/scripts/itl_1347/fixtures.py b/docs/dev/scripts/itl_1347/fixtures.py new file mode 100644 index 000000000..4af2601dd --- /dev/null +++ b/docs/dev/scripts/itl_1347/fixtures.py @@ -0,0 +1,172 @@ +"""ITL-1347 fixture pipelines, built on the tutorial dataset (``docs/tutorial/workshop_data.py``). + +Every fixture is a function ``build(data_dir, database) -> PipelineJob`` that records a job +over the dataset written by ``make_dataset(data_dir)``. The fixtures use only the public +API, so the same file builds the same job on pinned ``main`` and on a stage branch: the +differential (``dump.py``, ``compare.py``) runs it under both checkouts. + +- ``tutorial``: the pipeline of ``docs/tutorial/05-pipeline-job.md`` (two sources, a join, + a function pod per unit, a group-by, a function pod per session). +- ``spikes``: the workshop's shape at a larger scale. Every spike of the dataset is one row + (tens of thousands), joined to its unit, binned by a function pod per spike, grouped per + unit and counted by a second function pod, with ``Batch``, ``MergeJoin``, ``SemiJoin``, + ``PolarsFilter``, ``AddTags``, ``DropNulls``, ``MapData`` and ``Rejoin`` beside it, and a + side effect at the end. Every operator of the stage-5 classification appears once. +""" + +from __future__ import annotations + +import csv +import os +from collections.abc import Callable +from pathlib import Path +from typing import Any + +import pyarrow as pa + + +def _tutorial_sources(data_dir: Path) -> tuple[Any, Any]: + from orcapod.sources import CSVSource + + sessions = CSVSource( + str(data_dir / "sessions.csv"), + tag_columns=["subject_id", "session"], + tag_only_columns=True, + source_id="sessions", + ) + units = CSVSource( + str(data_dir / "units.csv"), + tag_columns=["subject_id", "session", "probe", "unit"], + tag_only_columns=True, + source_id="units", + ) + return sessions, units + + +def build_tutorial(data_dir: Path, database: Any) -> Any: + """The tutorial's pipeline job (``05-pipeline-job.md``).""" + from orcapod import PipelineJob, function_pod + + sessions, units = _tutorial_sources(data_dir) + + @function_pod(output_keys="rate_hz") + def firing_rate(n_spikes: int, duration_s: float) -> float: + return n_spikes / duration_s + + @function_pod(output_keys="mean_rate_hz") + def mean_rate(rate_hz: list[float]) -> float: + return sum(rate_hz) / len(rate_hz) + + job = PipelineJob(name="itl1347_tutorial", database=database) + with job: + rates: Any = firing_rate.pod( + units.select_data_columns(["n_spikes"]), + sessions.select_data_columns(["duration_s"]), + label="rates", + ) + mean_rate.pod( + rates.group_by(["subject_id", "session"]).select_data_columns(["rate_hz"]), + label="session_means", + ) + return job + + +def spikes_table(data_dir: Path) -> pa.Table: + """Every spike of the dataset as one row, in a fixed order (file name, then line). + + ``ITL1347_SPIKES_MAX`` keeps only the first rows, for a quick check of the harness. + """ + columns: dict[str, list[Any]] = { + "subject_id": [], + "session": [], + "probe": [], + "spike": [], + "unit": [], + "time_s": [], + } + for session_dir in sorted((data_dir / "sessions").iterdir()): + subject_id, session = session_dir.name.rsplit("_", 1) + for path in sorted(session_dir.glob("spikes_*.csv")): + probe = path.stem.removeprefix("spikes_") + with path.open(newline="", encoding="utf-8") as handle: + for index, row in enumerate(csv.DictReader(handle)): + columns["subject_id"].append(subject_id) + columns["session"].append(session) + columns["probe"].append(probe) + columns["spike"].append(index) + columns["unit"].append(int(row["unit"])) + columns["time_s"].append(float(row["time_s"])) + limit = os.environ.get("ITL1347_SPIKES_MAX") + if limit is not None: + columns = {name: values[: int(limit)] for name, values in columns.items()} + types = { + "subject_id": pa.large_string(), + "session": pa.large_string(), + "probe": pa.large_string(), + "spike": pa.int64(), + "unit": pa.int64(), + "time_s": pa.float64(), + } + schema = pa.schema([pa.field(name, t, nullable=False) for name, t in types.items()]) + return pa.Table.from_arrays( + [pa.array(columns[name], types[name]) for name in types], schema=schema + ) + + +def build_spikes(data_dir: Path, database: Any) -> Any: + """The workshop's shape at scale: one row per spike, every operator kind once.""" + from orcapod import InvocationContext, PipelineJob, function_pod, tap_pod + from orcapod.operators import MergeJoin, Rejoin + from orcapod.sources import ArrowTableSource + + sessions, units = _tutorial_sources(data_dir) + spikes = ArrowTableSource( + spikes_table(data_dir), + tag_columns=["subject_id", "session", "probe", "unit", "spike"], + tag_only_columns=True, + source_id="spikes", + ) + + @function_pod(output_keys="bin") + def time_bin(time_s: float) -> int: + return int(time_s // 10.0) + + @function_pod(output_keys="n_bins") + def bins_hit(bin: list[int]) -> int: + return len(set(bin)) + + @tap_pod + def report_fn(n_bins: int, ctx: InvocationContext) -> None: + return None + + job = PipelineJob(name="itl1347_spikes", database=database) + with job: + located = spikes.join(units.select_data_columns(["region"]), label="located") + binned: Any = time_bin.pod( + located.select_data_columns(["time_s"]), label="binned" + ) + per_unit = binned.group_by(["subject_id", "session", "probe", "unit"]) + counted: Any = bins_hit.pod( + per_unit.select_data_columns(["bin"]), label="counted" + ) + report: Any = report_fn + report(counted, label="report") + long_sessions = sessions.polars_filter(duration_s=120.0, label="long_sessions") + units.semi_join(long_sessions, label="units_in_long_sessions") + units.select_data_columns(["n_spikes"]).batch(batch_size=4, label="batched") + merged = MergeJoin()( + units.select_data_columns(["n_spikes"]), + counted.map_data({"n_bins": "n_spikes"}), + ) + merged.add_tags(study="itl1347", label="tagged").drop_nulls(label="no_nulls") + Rejoin()( + units.select_data_columns(["region"]), + units.select_data_columns(["depth_um"]), + ) + return job + + +FIXTURES: dict[str, Callable[[Path, Any], Any]] = { + "tutorial": build_tutorial, + "spikes": build_spikes, +} diff --git a/docs/dev/scripts/itl_1347/instrument.py b/docs/dev/scripts/itl_1347/instrument.py new file mode 100644 index 000000000..6d280961f --- /dev/null +++ b/docs/dev/scripts/itl_1347/instrument.py @@ -0,0 +1,199 @@ +"""ITL-1347 stage 0: count where a job run makes and unmakes rows. + +Wraps, for the duration of a ``with counting():`` block and nowhere else: + +- ``Datagram.__init__`` (every ``Tag`` and ``Data``), counted by class and by the node kind + whose ``execute`` / ``async_execute`` is running (``edge`` when none is: the orchestrator + rebuilding a successor's input, or the run plan); +- ``StaticOutputOperatorPod._rows_to_table`` (``R`` in the spec), counted and timed by its + caller (``_kept_output``/``_materialize_to_stream``, ``_materialize_upstream``, + ``_materialize_input_stream``); +- each node kind's ``execute`` and ``async_execute``, timed inclusively. + +Nothing in the library changes; the wrappers are removed when the block ends. The counts +are what the spec's stage table needs to replace its estimates (rows made per node kind, +rebuilds per caller, edges per node). +""" + +from __future__ import annotations + +import contextlib +import contextvars +import functools +import sys +import time +from collections import Counter, defaultdict +from collections.abc import Callable, Iterator +from typing import Any + +_NODE_KIND: contextvars.ContextVar[str] = contextvars.ContextVar( + "itl1347_node_kind", default="edge" +) + + +class Counts: + """What one counted block saw.""" + + def __init__(self) -> None: + self.datagrams: Counter[tuple[str, str]] = Counter() + self.rows_to_table_calls: Counter[str] = Counter() + self.rows_to_table_rows: Counter[str] = Counter() + self.rows_to_table_seconds: defaultdict[str, float] = defaultdict(float) + self.execute_calls: Counter[str] = Counter() + self.execute_seconds: defaultdict[str, float] = defaultdict(float) + + def as_dict(self) -> dict[str, Any]: + """The counts as plain JSON-ready data.""" + return { + "datagrams_by_node_kind_and_class": { + f"{kind}/{cls}": n for (kind, cls), n in sorted(self.datagrams.items()) + }, + "datagrams_total": sum(self.datagrams.values()), + "rows_to_table_by_caller": { + caller: { + "calls": self.rows_to_table_calls[caller], + "rows": self.rows_to_table_rows[caller], + "seconds": round(self.rows_to_table_seconds[caller], 4), + } + for caller in sorted(self.rows_to_table_calls) + }, + "execute_by_node_kind": { + kind: { + "calls": self.execute_calls[kind], + "seconds_inclusive": round(self.execute_seconds[kind], 4), + } + for kind in sorted(self.execute_calls) + }, + } + + +def _patch(owner: Any, name: str, make: Callable[[Any], Any]) -> Callable[[], None]: + """Replace ``owner.name`` with ``make(original)``; return the undo.""" + original = owner.__dict__[name] + setattr(owner, name, make(original)) + + def undo() -> None: + setattr(owner, name, original) + + return undo + + +@contextlib.contextmanager +def counting() -> Iterator[Counts]: + """Count datagrams, ``R`` calls and node executions inside the block.""" + from orcapod.core.datagrams.datagram import Datagram + from orcapod.core.nodes.function_node import FunctionJobNode + from orcapod.core.nodes.operator_node import OperatorJobNode + from orcapod.core.nodes.source_node import SourceNodeBase + from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod + from orcapod.side_effects import SideEffectJobNode + + counts = Counts() + undo: list[Callable[[], None]] = [] + + def wrap_init(original: Any) -> Any: + @functools.wraps(original) + def __init__(self: Any, *args: Any, **kwargs: Any) -> None: + counts.datagrams[(_NODE_KIND.get(), type(self).__name__)] += 1 + original(self, *args, **kwargs) + + return __init__ + + undo.append(_patch(Datagram, "__init__", wrap_init)) + + # ITL-1348 builds the rows of a table without ``__init__``: count those too. + if "_rows_of_table" in Datagram.__dict__: + + def wrap_rows_of_table(original: Any) -> Any: + func = original.__func__ + + @functools.wraps(func) + def _rows_of_table(cls: Any, *args: Any, **kwargs: Any) -> Iterator[Any]: + for item in func(cls, *args, **kwargs): + counts.datagrams[(_NODE_KIND.get(), cls.__name__)] += 1 + yield item + + return classmethod(_rows_of_table) + + undo.append(_patch(Datagram, "_rows_of_table", wrap_rows_of_table)) + + def wrap_rows_to_table(original: Any) -> Any: + func = original.__func__ + + @functools.wraps(func) + def _rows_to_table(rows: Any) -> Any: + caller = sys._getframe(1).f_code.co_name # pyright: ignore[reportPrivateUsage] # the caller's name is the measurement + start = time.perf_counter() + try: + return func(rows) + finally: + counts.rows_to_table_calls[caller] += 1 + counts.rows_to_table_rows[caller] += len(rows) + counts.rows_to_table_seconds[caller] += time.perf_counter() - start + + return staticmethod(_rows_to_table) + + undo.append(_patch(StaticOutputOperatorPod, "_rows_to_table", wrap_rows_to_table)) + + def wrap_execute(kind: str) -> Callable[[Any], Any]: + def make(original: Any) -> Any: + @functools.wraps(original) + def execute(self: Any, *args: Any, **kwargs: Any) -> Any: + token = _NODE_KIND.set(kind) + start = time.perf_counter() + try: + return original(self, *args, **kwargs) + finally: + counts.execute_calls[kind] += 1 + counts.execute_seconds[kind] += time.perf_counter() - start + _NODE_KIND.reset(token) + + return execute + + return make + + def wrap_async_execute(kind: str) -> Callable[[Any], Any]: + def make(original: Any) -> Any: + @functools.wraps(original) + async def async_execute(self: Any, *args: Any, **kwargs: Any) -> Any: + token = _NODE_KIND.set(kind) + start = time.perf_counter() + try: + return await original(self, *args, **kwargs) + finally: + counts.execute_calls[f"{kind} (async)"] += 1 + counts.execute_seconds[f"{kind} (async)"] += ( + time.perf_counter() - start + ) + _NODE_KIND.reset(token) + + return async_execute + + return make + + for cls, kind in ( + (SourceNodeBase, "source"), + (OperatorJobNode, "operator"), + (FunctionJobNode, "function"), + (SideEffectJobNode, "side_effect"), + ): + undo.append(_patch(cls, "execute", wrap_execute(kind))) + undo.append(_patch(cls, "async_execute", wrap_async_execute(kind))) + + try: + yield counts + finally: + for step in reversed(undo): + step() + + +def edges_per_node(job: Any) -> dict[str, dict[str, int]]: + """Each node's label with its number of predecessors and successors.""" + graph = job.dag + return { + str(getattr(node, "label", node)): { + "inputs": len(list(graph.predecessors(node))), + "successors": len(list(graph.successors(node))), + } + for node in graph.topological_sort() + } diff --git a/docs/dev/scripts/itl_1347/join_order_plugin.py b/docs/dev/scripts/itl_1347/join_order_plugin.py new file mode 100644 index 000000000..5713ff638 --- /dev/null +++ b/docs/dev/scripts/itl_1347/join_order_plugin.py @@ -0,0 +1,71 @@ +"""ITL-1357 measurement (ITL-1347 stage 0, a report only): Polars' inner-join row order. + +A pytest plugin. Loaded with ``-p join_order_plugin`` (``docs/dev/scripts/itl_1347`` on +``PYTHONPATH``), it wraps ``polars.DataFrame.join`` for the test session. Every inner join +called without ``maintain_order`` (the key-frame joins of ``Join``, ``MergeJoin`` and +``Rejoin``) is computed a second time with ``maintain_order="left_right"``, and the two +results are compared row for row. The join's own result is returned unchanged, so the tests +run as they do without the plugin. + +At the end of the session it writes ``ITL1357_REPORT`` (a JSON path) with the number of +such joins, how many gave the same row order, and, for each one that did not, the test, the +calling function and both row counts. Run it once with ``POLARS_MAX_THREADS=1`` and once at +the default. +""" + +from __future__ import annotations + +import json +import os +import sys +from typing import Any + +import pytest + +_state: dict[str, Any] = {"joins": 0, "same": 0, "different": [], "test": None} + + +def pytest_configure(config: Any) -> None: + import polars as pl + + original = pl.DataFrame.join + + def join(self: Any, other: Any, *args: Any, **kwargs: Any) -> Any: + result = original(self, other, *args, **kwargs) + how = kwargs.get("how", args[2] if len(args) > 2 else "inner") + if how != "inner" or "maintain_order" in kwargs: + return result + ordered = original(self, other, *args, maintain_order="left_right", **kwargs) + _state["joins"] += 1 + if result.equals(ordered): + _state["same"] += 1 + else: + caller = sys._getframe(1).f_code # pyright: ignore[reportPrivateUsage] # the caller is the measurement + _state["different"].append( + { + "test": _state["test"], + "caller": f"{caller.co_filename}:{caller.co_name}", + "rows": [result.height, ordered.height], + } + ) + return result + + pl.DataFrame.join = join # pyright: ignore[reportAttributeAccessIssue] # the measurement wraps it for this session + + +@pytest.hookimpl(tryfirst=True) +def pytest_runtest_setup(item: Any) -> None: + _state["test"] = item.nodeid + + +def pytest_sessionfinish(session: Any, exitstatus: int) -> None: + path = os.environ.get("ITL1357_REPORT") + report = { + "polars_max_threads": os.environ.get("POLARS_MAX_THREADS", "default"), + "inner_joins_without_maintain_order": _state["joins"], + "same_order_as_left_right": _state["same"], + "different": _state["different"], + } + if path: + with open(path, "w", encoding="utf-8") as handle: + json.dump(report, handle, indent=1) diff --git a/docs/dev/specs/itl-1347/stage-0.md b/docs/dev/specs/itl-1347/stage-0.md new file mode 100644 index 000000000..d4ba53b47 --- /dev/null +++ b/docs/dev/specs/itl-1347/stage-0.md @@ -0,0 +1,127 @@ +# ITL-1347 stage 0: measurements (2026-11-22) + +Stage 0 of `docs/dev/specs/itl-1347-job-table-transport.md`: measurement only, no library +change. The scripts are in `docs/dev/scripts/itl_1347/` (`README.md` there). The raw +records stay outside the repository. + +## Setup + +- **The two Orcapods**: + - *base*: `main` 8c6fc4f5 (0.4.0rc1, what ITL-1345 profiled); + - *job-speed*: `eywalker/job-speed` 0e15d0db, which already holds ITL-1348 (rows of a + table built without normalizing each again), ITL-1349 (modules loaded directly, not + through `LazyModule`) and ITL-1351 (a held node's rows counted without building them). +- **Environments**: each Orcapod was built as a wheel and installed into its own + environment. Before measuring, the installed `pipeline/node_run.py` was checked to match + its source (sha256). +- **Machine**: Python 3.14 on an Apple silicon Mac. One heavy process at a time; the + 1-minute load average is given with each number. +- **Workload**: a workshop-shaped pipeline on a local Delta copy. It has two sources + (63,349 and 28,780 rows), eight operator nodes (`GroupBy` ×2, `DropNulls`, `MapData` ×2, + `SelectDataColumns` ×2, `Join`) and two function nodes. Every edge has one successor. + +## Workshop-shaped job: time + +`job.run()` seconds; best of 3 for the warm runs. + +| | cold | warm 1 / 2 / 3 | **warm best** | async `job.run()` with every node held | load (warm runs) | +|---|---:|---:|---:|---:|---| +| base 8c6fc4f5 | 46.39 | 44.96 / 45.97 / 44.59 | **44.59** | 5.73–5.75 | 2.19 / 1.91 / 3.22 | +| job-speed 0e15d0db | 31.45 | 29.00 / 29.70 / 30.68 | **29.00** | 0.004–0.005 | 1.76 / 2.39 / 2.05 | + +Peak RSS of the whole notebook process: 5.67–5.78 GB (base), 6.19–6.28 GB (job-speed). + +## Workshop-shaped job: where rows are made and unmade (warm run) + +Counted by `instrument.counting()` around the `job.run()` cell. + +| | base | job-speed | +|---|---:|---:| +| datagrams made in source nodes (`Tag` + `Data`) | 184,258 | 184,258 | +| datagrams made in operator nodes | 57,822 | 57,822 | +| datagrams made in function nodes | 165 | 165 | +| `_rows_to_table` on edges (`_materialize_upstream`): calls / rows / seconds | 11 / 121,041 / 11.93 | 11 / 121,041 / 11.59 | +| `_rows_to_table` for operator nodes' kept output (`_materialize_to_stream`): calls / rows / seconds | 8 / 28,911 / 3.84 | 8 / 28,911 / 3.80 | +| source node `execute`, inclusive seconds | 14.74 | 3.54 | +| operator node `execute`, inclusive seconds | 15.62 | 12.50 | +| function node `execute`, inclusive seconds | 0.25 | 0.19 | + +job-speed makes the same datagrams as base: ITL-1348 made each one cheaper, not fewer. (A +first count on job-speed missed them, because ITL-1348 builds rows without +`Datagram.__init__`; `instrument.py` now counts `Datagram._rows_of_table` too.) + +The 121,041 edge rows split by producer as follows: +- the two sources: 92,129 rows; +- the operator nodes: 28,911 rows, of which 28,780 come from one node (`DropNulls`); +- the function node feeding the join: 1 row. + +On job-speed, `_rows_to_table` still costs about 15.4 s of the 29 s warm run: 11.6 s on +edges, 3.8 s for kept outputs. + +## What this means for the staged plan + +These numbers replace the spec's estimates, which came from the profile's shares: + +| Stage | Estimate in the spec | From these measurements, on job-speed (29.0 s warm) | +|---|---|---| +| 1: reuse an operator node's kept table on its edges | 4–8 s | **about 2.8 s**: operator outputs are 28,911 of the 121,041 edge rows, so about 24% of the 11.6 s edge rebuild | +| 2a: sources hand on their Arrow table | (with 2b) 14–20 s | about 8.8 s of edge rebuild (92,129 source rows) plus most of the 3.5 s source `execute` | +| 2b: operators keep and hand on `F(result)` | (with 2a) | the 3.8 s kept-output rebuild plus the operators' row iteration inside their 12.5 s `execute` | +| 3: function nodes | 8–14 s | small on this workload: two function nodes, 0.2 s in `execute`, 33 rows | + +Stage 1 alone is therefore worth about 10% of the warm run here. Most of the remaining gain +is in stage 2. ITL-1348's trusted row path has already removed most of the datagram cost +that the spec's estimates included. + +## Same results: base against job-speed + +- **Workshop-shaped job (warm run)**: every node's `as_table(all_info=True)` and every + stored table are equal byte for byte, except columns that each run makes afresh: + - `__record_id`, `__pod_ts` and `__data_id`; + - the `_source_*` tokens of function outputs, which embed a result's record id. + + Floats are compared by their bits. Arrow's `equals` holds NaN unequal to itself, and the + job has 539 NaN values per float column. +- **Fixture differential**: equal; see "Fixture differential" below. + +## ITL-1357: Polars' inner-join order (report only) + +- **Method**: `join_order_plugin.py` over `tests/test_core/operators/` (6,208 passed, 285 + xfailed). Every Polars inner join without `maintain_order` was recomputed with + `maintain_order="left_right"`, and the two row orders were compared. + +| Polars threads | inner joins without `maintain_order` | same order as `left_right` | different | +|---|---:|---:|---:| +| 1 | 2,912 | 2,265 | 647 | +| default | 2,912 | 2,265 | 647 | + +- **Callers of the differing joins**: `join._inner_join` (shared by `Join` and `MergeJoin`) + 628, and a test's own join 19. +- **Result**: `maintain_order="left_right"` does not reproduce today's order, so setting it + would be a result change, for its own decision (spec, decision 10). The counts are the + same at one thread and at the default. + +## Fixture differential + +- **Run**: `differential.py`, base 8c6fc4f5 against job-speed 0e15d0db. +- **Fixtures**: `tutorial` (the tutorial's pipeline), and `spikes` (36,616 spike rows, + every operator kind and a side effect). +- **Modes**: cold, warm, load-only and held, on both orchestrators, at one Polars thread and + at the default: 8 sync and 8 async cases per fixture. + +| Comparison | Result | +|---|---| +| sync job-speed against sync base, byte for byte | **equal in all 16 cases** (8 per fixture) | +| async job-speed against async base, as multisets | **equal in all 16 cases** | +| async against sync, on job-speed, as multisets | differs only by known `main` behaviours, the same on base: e3 (ITL-1062: duplicate inputs computed and stored again, with the summary's counts) and e8 (the async side-effect node's `__computed` column) | + +The run found two properties of the harness's inputs that are not results, and the +comparison now accounts for both. They were applied by re-comparing the same dumps +(`--compare-only`), with no new run: + +- `__pf_var_git_hash` (a function's git state) depends on the checkout, which changed + (`-dirty` to `-dirty-untracked`) when a file was added during the run. It is now an + environment column, left out like the volatile ones. +- `main` starts independent nodes (two sources, say) in an order that varies between two + runs of the same code. So observer events are compared node by node, each node's own + sequence in order, not as one global sequence. From 22bbca8d85f57c0b71704dd567d589da89cd95de Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" <> Date: Sun, 22 Nov 2026 01:46:24 -0800 Subject: [PATCH 08/86] wip(pipeline): ITL-1347 stage 2: nodes return output streams, arrow_schema(), equivalence tests (ITL-1360) Work in progress. Done: every node's execute returns its output stream (sources and operators from F of their Arrow table, function and side-effect nodes from their rows); sync orchestrator passes streams; held= streams; node_outputs are streams; arrow_schema()/arrow_types_declared on StreamBase and SourceNodeBase; L0/L1/L2/L5/L7 tests (36 passed). Open: tests that call the removed SyncPipelineOrchestrator._materialize_as_stream (5 files) and two baseline observer-type entries whose columns moved; the full targeted suites are not run. Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/nodes/function_node.py | 25 +- src/orcapod/core/nodes/operator_node.py | 49 +++- src/orcapod/core/nodes/source_node.py | 86 +++++- .../core/operators/static_output_pod.py | 107 +++---- src/orcapod/core/streams/base.py | 56 ++++ src/orcapod/pipeline/async_orchestrator.py | 39 ++- src/orcapod/pipeline/job.py | 4 +- src/orcapod/pipeline/loaded_side_effects.py | 5 +- src/orcapod/pipeline/node_run.py | 20 +- src/orcapod/pipeline/result.py | 11 +- src/orcapod/pipeline/sync_orchestrator.py | 118 +++----- .../protocols/core_protocols/streams.py | 26 ++ src/orcapod/protocols/node_protocols.py | 8 +- src/orcapod/side_effects.py | 27 +- .../function_pod/test_ephemeral_result.py | 26 +- .../function_pod/test_function_pod_ctx_arg.py | 4 +- .../nodes/test_function_node_iteration.py | 8 +- tests/test_core/nodes/test_node_execute.py | 6 +- .../operators/test_materialize_source_info.py | 2 +- .../test_side_effect_function_pod.py | 4 +- .../side_effect_pod/test_side_effect_pod.py | 16 +- ...est_postgresql_table_source_integration.py | 4 +- .../test_spiraldb_table_source_where.py | 6 +- .../sources/test_sqlite_table_source.py | 4 +- tests/test_core/test_tracker.py | 2 +- .../test_current_run_review_fixes.py | 10 +- .../test_job_node_rows_after_run.py | 2 +- tests/test_pipeline/test_node_protocols.py | 14 +- .../test_operator_kept_table_reuse.py | 181 ------------ .../test_operator_node_async_readback.py | 2 +- .../test_stream_transport_equivalence.py | 269 ++++++++++++++++++ 31 files changed, 725 insertions(+), 416 deletions(-) delete mode 100644 tests/test_pipeline/test_operator_kept_table_reuse.py create mode 100644 tests/test_pipeline/test_stream_transport_equivalence.py diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 6b8ee6a3a..3b2b2e1da 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -2456,6 +2456,19 @@ def as_node(self) -> FunctionNode: # Data processing # ------------------------------------------------------------------ + def _output_stream( + self, rows: list[tuple[TagProtocol, DataProtocol]] + ) -> StreamProtocol: + """The output stream of a run whose output rows are ``rows``. + + What the sync orchestrator built from a node's rows for its successors + (``StaticOutputOperatorPod._materialize_upstream``): the rows' table with this + node's identity, or the node's zero-row input when there is no row. + """ + from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod + + return StaticOutputOperatorPod._materialize_upstream(rows, self) + def execute_data( self, tag: TagProtocol, @@ -2485,7 +2498,7 @@ def execute( error_policy: Literal["continue", "fail_fast"] = "continue", run_id: str | None = None, load_only: bool = False, - ) -> list[tuple[TagProtocol, DataProtocol]]: + ) -> StreamProtocol: """Execute all data from a stream: compute, persist, and cache. For each data: fire ``on_data_start``, check the in-memory cache @@ -2511,8 +2524,10 @@ def execute( this way. Returns: - Materialized list of (tag, output_data) pairs, excluding - ``None`` outputs and failed data. + The node's output stream: its output rows (no row for a ``None`` output or + a failed row) as the table ``_rows_to_table`` builds from them, with this + node's identity (``StaticOutputOperatorPod._materialize_upstream``). The sync + orchestrator hands it to every successor (ITL-1347, stage 2). Raises: RuntimeError: If the node was loaded by ``PipelineJob.load`` and so @@ -2524,7 +2539,7 @@ def execute( from orcapod.pipeline.observer import NoOpObserver if load_only: - return self._execute_load_only(input_stream, observer) + return self._output_stream(self._execute_load_only(input_stream, observer)) if self._function_pod is None: raise self._cannot_compute_error() @@ -2653,7 +2668,7 @@ def execute( self.clear_cache() raise - return output + return self._output_stream(output) def _empty_data_cache_hit( self, tag: TagProtocol, data: EmptyData, base_entry_id: bytes diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index e51c19e50..ae33d7716 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -1645,7 +1645,7 @@ def execute( *input_streams: StreamProtocol, observer: ExecutionObserverProtocol | None = None, load_only: bool = False, - ) -> list[tuple[TagProtocol, DataProtocol]]: + ) -> StreamProtocol: """Execute input streams: compute, persist, and cache. Args: @@ -1657,7 +1657,10 @@ def execute( as in any run. Returns: - Materialized list of (tag, data) pairs. + The node's output stream: its rows as the table ``_rows_to_table`` builds + from them (``StaticOutputOperatorPod._output_stream``), with this node's + identity, built from the operator's result table without making rows + (ITL-1347, stage 2). The sync orchestrator hands it to every successor. Raises: ValueError: If the node caches (``LOG`` or ``REPLAY``) and a source @@ -1685,23 +1688,37 @@ def execute( # Check REPLAY cache first cached_output = self.get_cached_output() if cached_output is not None: - output = list(cached_output.iter_data()) + output = StaticOutputOperatorPod._output_stream( + cached_output.as_table(columns=ZERO_ROW_INPUT_COLUMNS), + cached_output.keys()[0], + stream_data_tags(cached_output), + self, + ) ctx_obs.on_node_end(node_label, node_hash) return output # Compute result_stream = self._operator.process(*input_streams) - # Materialize - output = list(result_stream.iter_data()) + # The result's table, as the table built from its rows would be, without + # making the rows (ITL-1347, stage 2). + result_table = result_stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS) + tag_keys = result_stream.keys()[0] + data_tags = stream_data_tags(result_stream) - # Cache, in row order with or without rows (ITL-1131, ITL-1133). The rows - # returned carry the table the kept stream is built over, so the sync - # orchestrator gives it to each successor without building it again - # (ITL-1347, stage 1). - self._cached_output_stream, output = ( - StaticOutputOperatorPod._kept_output_with_rows(result_stream, output) - ) + # Cache, in row order with or without rows (ITL-1131, ITL-1133). + if result_table.num_rows: + kept_table = StaticOutputOperatorPod._row_built_form( + result_table, tag_keys + ) + self._cached_output_stream = ArrowTableStream( + kept_table, tag_columns=tag_keys, data_tags=data_tags + ) + else: + kept_table = None + self._cached_output_stream = ( + StaticOutputOperatorPod._zero_rows_in_row_order(result_stream) + ) self._update_modified_time() @@ -1714,6 +1731,14 @@ def execute( ): self._store_output_stream(self._cached_output_stream) + # The output stream, built once the node holds its run (as the sync + # orchestrator built a successor's input after ``execute`` returned). + if kept_table is not None: + output = StaticOutputOperatorPod._as_upstream_stream( + kept_table, tag_keys, data_tags, self + ) + else: + output = StaticOutputOperatorPod._materialize_upstream([], self) ctx_obs.on_node_end(node_label, node_hash) return output except BaseException: diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index b522c117f..1688881c8 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -15,7 +15,7 @@ from abc import ABC, abstractmethod from collections.abc import AsyncIterator, Collection, Iterator, Mapping from datetime import datetime -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING, Any, cast import pyarrow as pa @@ -23,10 +23,12 @@ from orcapod.config import OrcapodConfig from orcapod.core.base import TraceableBase from orcapod.core.datagrams import Data, Tag +from orcapod.core.data_tags import stream_data_tags from orcapod.core.operators.drop_nulls import _without_none # pyright: ignore[reportPrivateUsage] # DropNulls' rule for removing None from a type, shared, never copied from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.core.streams.base import ( ZERO_ROW_INPUT_COLUMNS, + stream_arrow_schema, schema_requires_io, typed_arrow_schemas, typed_zero_row_table, @@ -1185,27 +1187,61 @@ def iter_data(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: """Yield ``(tag, data)`` pairs, or raise if data is unavailable.""" ... + def _rows_stream(self) -> "StreamProtocol": + """The stream whose rows are this node's rows (``iter_data``): this node itself.""" + return cast("StreamProtocol", self) + + def arrow_schema(self) -> pa.Schema: + """The Arrow schema of the columns this stream passes between job nodes. + + See ``stream_arrow_schema`` (ITL-1347): never reads, computes or polls a row. + The user tags are in the order of the node's rows (``_row_tag_keys``). + """ + return stream_arrow_schema(self, self._row_tag_keys()) + + def _row_tag_keys(self) -> tuple[str, ...]: + """The order of the user tags in this node's rows: its own key order.""" + return self.keys()[0] + + @property + def arrow_types_declared(self) -> bool: + """Whether ``arrow_schema()`` holds the rows' own Arrow types (ITL-1089, ITL-1347).""" + return typed_zero_row_table(self) is not None + def execute( self, *, observer: ExecutionObserverProtocol | None = None, - ) -> list[tuple[TagProtocol, DataProtocol]]: - """Execute this source node: materialize and return data. + ) -> StreamProtocol: + """Execute this source node: read its source once and return its output stream. + + The source's table, as the table built from its rows would be + (``StaticOutputOperatorPod._output_stream``), with this node's identity, built + without making rows (ITL-1347, stage 2). The sync orchestrator hands it to every + successor. Args: observer: Optional execution observer. Returns: - List of (tag, data) tuples. + The node's output stream. Raises: UnboundSourceError: When no concrete data is available. """ + from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod + node_label = self.label node_hash = self.content_hash().to_string() if observer is not None: observer.on_node_start(node_label, node_hash) - result = list(self.iter_data()) + # The stream this node's rows come from: its table and its tag order are the + # rows' (a slot's own key order can differ from its source's). + rows_stream = self._rows_stream() + table = rows_stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS) + result = StaticOutputOperatorPod._output_stream( + table, rows_stream.keys()[0], stream_data_tags(rows_stream), self + ) if observer is not None: observer.on_node_end(node_label, node_hash) return result @@ -1667,6 +1703,46 @@ def identity_structure(self) -> Any: return self._bound_source.identity_structure() return super().identity_structure() + def _row_tag_keys(self) -> tuple[str, ...]: + """The order of the user tags in this node's rows, known without reading a row. + + The bound source's key order; the declared order for a narrower source given + as the declared schema (``_DeclaredForm``); the slot's own when unbound. + """ + if self._bound_source is None: + return self.keys()[0] + if self._declared_form is not None: + return self._declared_form.tag_order + return self._bound_source.keys()[0] + + def _rows_stream(self) -> StreamProtocol: + """The stream whose rows are this node's rows (``iter_data``). + + The bound source, or, for a narrower source, the source's table given as the + declared schema (``_declared_stream``), whose rows are those ``_declared_rows`` + gives one by one. + + Raises: + UnboundSourceError: When no concrete source is attached. + """ + if self._bound_source is None: + raise UnboundSourceError( + f"SourceJobNode '{self._name}' has no concrete source bound. " + "Call job.bind(sources={'': source}) before running." + ) + if self._declared_form is None: + return self._bound_source + table = self._bound_source.as_table( + columns={ + "meta": True, + "source": True, + "system_tags": True, + "context": True, + "sort_by_tags": False, + } + ) + return self._declared_stream(self._bound_source, self._declared_form, table) + def iter_data(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: """Delegate to concrete source, or raise if unbound. diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index d0750405e..41007dc44 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -441,35 +441,68 @@ def _kept_output( Returns: A stream over the rows, in row order. """ - return StaticOutputOperatorPod._kept_output_with_rows(result, rows)[0] + if rows: + return StaticOutputOperatorPod._materialize_to_stream(rows) + return StaticOutputOperatorPod._zero_rows_in_row_order(result) @staticmethod - def _kept_output_with_rows( - result: StreamProtocol, - rows: Sequence[tuple[TagProtocol, DataProtocol]], - ) -> tuple[StreamProtocol, list[tuple[TagProtocol, DataProtocol]]]: - """Return what ``_kept_output`` returns, and ``rows`` with the table built from them. + def _row_built_form(table: pa.Table, tag_keys: 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. ``table`` holds + the user tags, system tags, data and source info (``ZERO_ROW_INPUT_COLUMNS``: no + context, meta or content-hash column, and each data-tag once, among the tags). + Each row's datagram normalizes its table to the large types without keeping + ``null`` (``Datagram._init_from_table``), so a ``null`` column becomes + ``large_string``. The columns then go in row order and each source-info field is + flagged nullable only when a token is null (``_as_row_built_table``). The + equality with ``_rows_to_table`` is tested over every operator, source kind and + column role (ITL-1347, L0-L2). + + Args: + table: A table of user tags, system tags, data and source info, with rows. + tag_keys: The user tag columns, in order. - With rows, the second value is a ``RowsWithTable``: the same rows, carrying the - table ``_rows_to_table(rows)`` the kept stream is built over. An operator node's - ``execute`` returns it, so the sync orchestrator gives each successor that table - (``_materialize_upstream``) instead of building it from the rows again (ITL-1347, - stage 1). Without rows, the rows are returned as a plain list. + Returns: + The table ``_rows_to_table`` would build from its rows. + """ + from orcapod.utils import arrow_utils + + return StaticOutputOperatorPod._as_row_built_table( + arrow_utils.normalize_table_to_large_types(table), tag_keys + ) + + @staticmethod + def _output_stream( + table: pa.Table, + tag_keys: Sequence[str], + data_tags: 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: - result: The operator's result of the run. - rows: ``result``'s rows, in order. + table: The node's rows: user tags, system tags, data and source info. + tag_keys: The user tag columns of the rows, in order. + data_tags: The data-tags among ``tag_keys``. + node: The node (or stream) whose output this is. Returns: - The kept stream, and the rows. + The output stream, with ``node``'s identity. """ - if rows: - row_table = StaticOutputOperatorPod._rows_to_table(rows) - return ( - StaticOutputOperatorPod._stream_over_row_table(row_table), - RowsWithTable(rows, row_table), - ) - return StaticOutputOperatorPod._zero_rows_in_row_order(result), list(rows) + if table.num_rows == 0: + return StaticOutputOperatorPod._materialize_upstream([], node) + return StaticOutputOperatorPod._as_upstream_stream( + StaticOutputOperatorPod._row_built_form(table, tag_keys), + tag_keys, + data_tags, + node, + ) @staticmethod def _flag_source_info_nullability(table: pa.Table) -> pa.Table: @@ -638,13 +671,6 @@ def _materialize_upstream( """ from orcapod.utils import arrow_utils - if rows and not zero_rows and isinstance(rows, RowsWithTable): - # The rows' own table, built once by the node that returned them: the - # same ``_rows_to_table(rows)`` as below, not built again (ITL-1347). - table, tag_keys, data_tags = rows.row_table - return StaticOutputOperatorPod._as_upstream_stream( - table, tag_keys, data_tags, upstream - ) if rows: table, tag_keys, data_tags = StaticOutputOperatorPod._rows_to_table(rows) if zero_rows: @@ -822,31 +848,6 @@ async def async_execute( await output.close() -class RowsWithTable(list[tuple[TagProtocol, DataProtocol]]): - """Rows of an operator node's run, carrying the table built from them. - - ``row_table`` is ``StaticOutputOperatorPod._rows_to_table`` of exactly these rows: the - table, the user tag keys and the data-tags. An operator node builds it once for the - output it keeps and returns its rows in this form, so whoever rebuilds the rows as a - stream (``_materialize_upstream``) takes the table instead of building it again - (ITL-1347, stage 1). It is a list in every other respect. - - Args: - rows: The rows, in order. - row_table: ``_rows_to_table(rows)``. - """ - - __slots__ = ("row_table",) - - def __init__( - self, - rows: Sequence[tuple[TagProtocol, DataProtocol]], - row_table: tuple[pa.Table, tuple[str, ...], tuple[str, ...]], - ) -> None: - super().__init__(rows) - self.row_table = row_table - - class _RowsOfStream(ArrowTableStream): """Rows standing in for the stream they came from, with its pipeline hash. diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py index 0f8a5cb33..e8dbb149b 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -184,6 +184,50 @@ def typed_zero_row_input(stream: object) -> pa.Table | None: ) +def stream_arrow_schema( + stream: object, tag_keys: Sequence[str] | None = None +) -> pa.Schema: + """Return ``stream``'s declared Arrow schema: what ``arrow_schema()`` answers (ITL-1347). + + The schema of the columns a job node passes on, without reading, computing or + polling a row: the stream's zero-row input (``typed_zero_row_input``, the Arrow types + its rows have) in row order (user tags, system tags, data, source info; + ``StaticOutputOperatorPod._in_row_order``), with no context and no meta column. A + stream that cannot type itself without rows answers with its Python schema + converted by its data context (``arrow_types_declared`` is then false). Each + source-info field is stated nullable: a table decides its flag from its tokens. A + ``null`` column keeps the zero-row ``null`` type; rows carry ``large_string`` + (ITL-1319). ITL-1307 later reads it from ``Schema`` instead, here. + + Args: + stream: The stream, source or node. + tag_keys: The order of the user tags in the stream's rows, when it differs from + ``keys()`` (a source slot gives its bound source's rows); default + ``keys()``. + + Returns: + The declared Arrow schema. + """ + from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod + from orcapod.system_constants import constants + + typed = cast(StreamProtocol, stream) + if tag_keys is None: + tag_keys = typed.keys()[0] + table = typed_zero_row_input(stream) + if table is None: + tag_schema, data_schema = typed.output_schema( + columns={"system_tags": True, "source": True} + ) + converter = StaticOutputOperatorPod._upstream_context(typed).type_converter # pyright: ignore[reportPrivateUsage] # the one place that resolves an upstream's context + table = arrow_utils.make_empty_table({**tag_schema, **data_schema}, converter) + schema = StaticOutputOperatorPod._in_row_order(table, tag_keys).schema # pyright: ignore[reportPrivateUsage] # the one statement of the row order + for index, field in enumerate(schema): + if field.name.startswith(constants.SOURCE_PREFIX): + schema = schema.set(index, field.with_nullable(True)) # pyright: ignore[reportUnknownMemberType] # stubs leave Field unparametrized + return schema + + def typed_arrow_schemas( stream: object, *, own: bool = True ) -> tuple[pa.Schema, pa.Schema]: @@ -919,6 +963,18 @@ def index( return Index(column, i, out=out, fail_on_miss=fail_on_miss)(self, label=label) + def arrow_schema(self) -> pa.Schema: + """The Arrow schema of the columns this stream passes between job nodes. + + See ``stream_arrow_schema`` (ITL-1347): never reads, computes or polls a row. + """ + return stream_arrow_schema(self) + + @property + def arrow_types_declared(self) -> bool: + """Whether ``arrow_schema()`` holds the rows' own Arrow types (ITL-1089, ITL-1347).""" + return typed_zero_row_table(self) is not None + @abstractmethod def keys( self, diff --git a/src/orcapod/pipeline/async_orchestrator.py b/src/orcapod/pipeline/async_orchestrator.py index 55cd52d5e..061616cba 100644 --- a/src/orcapod/pipeline/async_orchestrator.py +++ b/src/orcapod/pipeline/async_orchestrator.py @@ -39,7 +39,11 @@ from orcapod.channels import WritableChannel from orcapod.pipeline.dag import GraphProtocol - from orcapod.protocols.core_protocols import DataProtocol, TagProtocol + from orcapod.protocols.core_protocols import ( + DataProtocol, + StreamProtocol, + TagProtocol, + ) from orcapod.protocols.observability_protocols import ExecutionObserverProtocol logger = logging.getLogger(__name__) @@ -83,7 +87,7 @@ def run( run_id: str | None = None, pipeline_uri: str = "", load_only: bool = False, - held_rows: Mapping[Any, list[tuple[TagProtocol, DataProtocol]]] | None = None, + held: Mapping[Any, StreamProtocol] | None = None, ) -> OrchestratorResult: """Synchronous entry point — runs the async pipeline to completion. @@ -128,7 +132,7 @@ def run( run_id=run_id, pipeline_uri=pipeline_uri, load_only=load_only, - held_rows=held_rows, + held=held, ) ) @@ -150,7 +154,7 @@ def make_run() -> Coroutine[Any, Any, OrchestratorResult]: run_id=run_id, pipeline_uri=pipeline_uri, load_only=load_only, - held_rows=held_rows, + held=held, ) return _run_on_own_thread(make_run, rows_in_flight) @@ -164,7 +168,7 @@ async def run_async( run_id: str | None = None, pipeline_uri: str = "", load_only: bool = False, - held_rows: Mapping[Any, list[tuple[TagProtocol, DataProtocol]]] | None = None, + held: Mapping[Any, StreamProtocol] | None = None, ) -> OrchestratorResult: """Async entry point for callers already inside an event loop. @@ -177,7 +181,7 @@ async def run_async( pipeline_uri: Opaque URI string identifying this pipeline run. Forwarded verbatim to ``observer.on_run_start``. load_only: As for ``SyncPipelineOrchestrator.run``. - held_rows: As for ``SyncPipelineOrchestrator.run``: nodes not run, whose + held: As for ``SyncPipelineOrchestrator.run``: nodes not run, whose rows feed their successors. Returns: @@ -190,7 +194,7 @@ async def run_async( run_id=run_id, pipeline_uri=pipeline_uri, load_only=load_only, - held_rows=held_rows, + held=held, ) async def _run_async( @@ -202,9 +206,10 @@ async def _run_async( run_id: str | None = None, pipeline_uri: str = "", load_only: bool = False, - held_rows: Mapping[Any, list[tuple[TagProtocol, DataProtocol]]] | None = None, + held: Mapping[Any, StreamProtocol] | None = None, ) -> OrchestratorResult: """Core async logic: wire channels, launch tasks, collect results.""" + from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod from orcapod.pipeline.observer import NoOpObserver run_id = run_id or str(uuid.uuid4()) @@ -264,14 +269,19 @@ async def _run_async( collector = collectors[node] writer = _CollectingWriter(writer, collector) - if held_rows is not None and node in held_rows: + if held is not None and node in held: # Not run: the rows of its current run feed its successors. Its # own inputs are read and discarded, so no producer blocks on # a channel nobody reads. for upstream in in_edges.get(node, []): tg.create_task(_drain(edge_readers[(upstream, node)])) _start_node( - tg, failed_nodes, node, _send_held(held_rows[node], writer) + tg, + failed_nodes, + node, + # The held node's own rows, as before stage 2: the async + # path still carries rows (ITL-1347, stage 5 changes it). + _send_held(list(node.iter_data()), writer), ) elif is_source_node(node): _start_node( @@ -355,7 +365,14 @@ async def _run_async( tg.create_task(ch.reader.collect()) return OrchestratorResult( - node_outputs=collectors if materialize_results else {} + node_outputs=( + { + node: StaticOutputOperatorPod._materialize_upstream(rows, node) + for node, rows in collectors.items() + } + if materialize_results + else {} + ) ) except ExceptionGroup as group: # A failed database read or write stops the run. Raise it on its own, as the diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index ea3f5570f..1443d4f43 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -997,7 +997,7 @@ def run( pipeline_uri=prepared.pipeline_uri, materialize_results=materialize_results, load_only=load_only, - held_rows=plan.held_rows, + held=plan.held, ) summary = self._finish_run( prepared, @@ -1068,7 +1068,7 @@ async def run_async( pipeline_uri=prepared.pipeline_uri, materialize_results=materialize_results, load_only=load_only, - held_rows=plan.held_rows, + held=plan.held, ) summary = self._finish_run( prepared, diff --git a/src/orcapod/pipeline/loaded_side_effects.py b/src/orcapod/pipeline/loaded_side_effects.py index fc8d6ca79..aa5182742 100644 --- a/src/orcapod/pipeline/loaded_side_effects.py +++ b/src/orcapod/pipeline/loaded_side_effects.py @@ -263,7 +263,7 @@ def execute( observer: ExecutionObserverProtocol | None = None, run_id: str | None = None, load_only: bool = False, - ) -> list[tuple[TagProtocol, DataProtocol]]: + ) -> StreamProtocol: """Pass every row on in a load-only run, as every side-effect job node does. Args: @@ -273,7 +273,8 @@ def execute( load_only: Must be true: the node can only pass rows on. Returns: - The rows of ``input_stream``, which the node then holds as loaded only. + The output stream of the rows of ``input_stream``, which the node then holds + as loaded only. Raises: RuntimeError: If ``load_only`` is false; nothing is read then. diff --git a/src/orcapod/pipeline/node_run.py b/src/orcapod/pipeline/node_run.py index 44ae96fb9..9e67317fb 100644 --- a/src/orcapod/pipeline/node_run.py +++ b/src/orcapod/pipeline/node_run.py @@ -249,8 +249,8 @@ class RunPlan: Attributes: dag: The nodes the run touches: those it runs, and the predecessors that feed them (a source slot is read; any other one is held). - held_rows: The rows of each held node of ``dag``: the rows of its current run, - or of a stream outside the job; they feed the nodes after it as if it had + held: The output stream of each held node of ``dag``: of its current run, or + of a stream outside the job; it feeds the nodes after it as if the node had just run. to_run: The nodes the run runs, in dependency order. held_counts: Every node of the whole graph that holds a current run, with its @@ -258,7 +258,7 @@ class RunPlan: """ dag: Any - held_rows: dict[Any, list[Any]] + held: dict[Any, Any] to_run: list[Any] held_counts: dict[Any, int] @@ -332,15 +332,21 @@ def is_source(node: Any) -> bool: for node in to_run: for upstream in graph.predecessors(node): dag.add_edge(upstream, node) - held_rows = { - node: list(node.iter_data()) + from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod + + # A held node's output stream: what the sync orchestrator built from its rows for + # the nodes after it, exactly (ITL-1347, stage 2). + held = { + node: StaticOutputOperatorPod._materialize_upstream( + list(node.iter_data()), node + ) for node in included if not any(node is r for r in to_run) and not is_source(node) } # Counted from what each node holds: iterating an operator's rows would build a # (Tag, Data) pair per row only to count them (ITL-1351). held_counts = {node: node.held_row_count() for node in current} - return RunPlan(dag, held_rows, to_run, held_counts) + return RunPlan(dag, held, to_run, held_counts) def commit_run(databases: Sequence[ArrowDatabaseProtocol], ran: Sequence[Any]) -> None: @@ -425,7 +431,7 @@ def visit(node: Any) -> None: counter = RunCountingObserver() try: _ = SyncPipelineOrchestrator().run( - plan.dag, observer=counter, load_only=load_only, held_rows=plan.held_rows + plan.dag, observer=counter, load_only=load_only, held=plan.held ) except BaseException as run_error: if isinstance(run_error, Exception) and not load_only: diff --git a/src/orcapod/pipeline/result.py b/src/orcapod/pipeline/result.py index 94d158184..12448df8c 100644 --- a/src/orcapod/pipeline/result.py +++ b/src/orcapod/pipeline/result.py @@ -6,7 +6,7 @@ from typing import TYPE_CHECKING, Any if TYPE_CHECKING: - from orcapod.protocols.core_protocols import DataProtocol, TagProtocol + from orcapod.protocols.core_protocols import StreamProtocol @dataclass @@ -14,10 +14,9 @@ class OrchestratorResult: """Result of an orchestrator run. Attributes: - node_outputs: Mapping from graph node to its computed (tag, data) - pairs. Empty when ``materialize_results=False``. + node_outputs: Mapping from graph node to its output stream (backed by an + Arrow table; ``as_table()`` gives it, ``iter_data()`` its rows). Empty when + ``materialize_results=False``. """ - node_outputs: dict[Any, list[tuple["TagProtocol", "DataProtocol"]]] = field( - default_factory=dict - ) + node_outputs: dict[Any, "StreamProtocol"] = field(default_factory=dict) diff --git a/src/orcapod/pipeline/sync_orchestrator.py b/src/orcapod/pipeline/sync_orchestrator.py index bf9708a39..553307bfa 100644 --- a/src/orcapod/pipeline/sync_orchestrator.py +++ b/src/orcapod/pipeline/sync_orchestrator.py @@ -26,7 +26,7 @@ from orcapod.pipeline.dag import GraphProtocol from orcapod.protocols.observability_protocols import ExecutionObserverProtocol - from orcapod.protocols.core_protocols import DataProtocol, TagProtocol + from orcapod.protocols.core_protocols import StreamProtocol logger = logging.getLogger(__name__) @@ -38,8 +38,9 @@ class SyncPipelineOrchestrator: to ``node.execute(observer=...)`` which owns all per-data logic, cache lookups, and observer hooks internally. - The orchestrator is responsible only for topological ordering, - buffer management, and stream materialization between nodes. + The orchestrator is responsible only for topological ordering and for handing + each node's output stream to its successors: a node's ``execute`` returns the + stream every successor reads (ITL-1347, stage 2). """ def __init__( @@ -57,16 +58,16 @@ def run( run_id: str | None = None, pipeline_uri: str = "", load_only: bool = False, - held_rows: Mapping[Any, list[tuple[TagProtocol, DataProtocol]]] | None = None, + held: Mapping[Any, StreamProtocol] | None = None, ) -> OrchestratorResult: """Execute the node graph synchronously. Args: graph: A ``GraphProtocol`` DAG with GraphNode objects as vertices. observer: Optional execution observer forwarded to nodes. - materialize_results: If True, keep all node outputs in memory - and return them. If False, discard buffers after downstream - consumption (only DB-persisted results survive). + materialize_results: If True, keep every node's output stream and return + them. If False, drop each one once its successors have run (only + DB-persisted results survive). run_id: Optional run identifier. If not provided, a UUID is generated automatically. pipeline_uri: Opaque URI string identifying this pipeline run @@ -76,13 +77,13 @@ def run( (ITL-1095): function nodes load their inputs' stored results and skip the others, operators run without storing, and a side-effect node passes its rows on and delivers nothing. - held_rows: Nodes of ``graph`` that are not run: each one's rows (the rows - of its current run, or of a stream outside the job) feed its - successors as if it had just run. Used by ``node.run()``, which runs - only the nodes it depends on that hold no current run (ITL-1095). + held: Nodes of ``graph`` that are not run: each one's output stream (of + its current run, or of a stream outside the job) feeds its successors + as if it had just run. Used by ``node.run()``, which runs only the + nodes it depends on that hold no current run (ITL-1095). Returns: - OrchestratorResult with node outputs. + OrchestratorResult with each node's output stream. """ from orcapod.pipeline.observer import NoOpObserver @@ -94,23 +95,19 @@ def run( current: Any = None try: topo_order = list(graph.topological_sort()) - buffers: dict[Any, list[tuple[TagProtocol, DataProtocol]]] = {} + outputs: dict[Any, StreamProtocol] = {} processed: set[Any] = set() - held = held_rows if held_rows is not None else {} + held_streams = held if held is not None else {} for node in topo_order: current = node - if node in held: - buffers[node] = list(held[node]) + if node in held_streams: + outputs[node] = held_streams[node] elif is_source_node(node): - buffers[node] = node.execute(observer=effective_observer) + outputs[node] = node.execute(observer=effective_observer) elif is_function_node(node) or is_side_effect_function_node(node): - upstream_buf = self._gather_upstream(node, graph, buffers) - upstream_node = list(graph.predecessors(node))[0] - input_stream = self._materialize_as_stream( - upstream_buf, upstream_node - ) - buffers[node] = node.execute( + input_stream = self._single_input(node, graph, outputs) + outputs[node] = node.execute( input_stream, observer=effective_observer, error_policy=self._error_policy, @@ -118,22 +115,14 @@ def run( load_only=load_only, ) elif is_operator_node(node): - upstream_buffers = self._gather_upstream_multi(node, graph, buffers) - input_streams = [ - self._materialize_as_stream(buf, upstream_node) - for buf, upstream_node in upstream_buffers - ] - buffers[node] = node.execute( + input_streams = self._ordered_inputs(node, graph, outputs) + outputs[node] = node.execute( *input_streams, observer=effective_observer, load_only=load_only ) elif is_side_effect_node(node): - upstream_buf = self._gather_upstream(node, graph, buffers) - upstream_node = list(graph.predecessors(node))[0] - input_stream = self._materialize_as_stream( - upstream_buf, upstream_node - ) + input_stream = self._single_input(node, graph, outputs) # In a load-only run the node passes its rows on and delivers nothing. - buffers[node] = node.execute( + outputs[node] = node.execute( input_stream, observer=effective_observer, run_id=run_id, @@ -147,12 +136,12 @@ def run( processed.add(node) if not materialize_results: - self._gc_buffers(node, graph, buffers, processed) + self._gc_outputs(node, graph, outputs, processed) if not materialize_results: - buffers.clear() + outputs.clear() - return OrchestratorResult(node_outputs=buffers) + return OrchestratorResult(node_outputs=outputs) except OrcapodDatabaseError as exc: # Name the node the failure belongs to, if the raising site did not. if current is not None: @@ -170,70 +159,47 @@ def run( effective_observer.on_run_end(run_id) @staticmethod - def _gather_upstream( + def _single_input( node: Any, graph: "GraphProtocol[Any]", - buffers: dict[Any, list[tuple[Any, Any]]], - ) -> list[tuple[Any, Any]]: - """Gather a single upstream buffer (for function nodes).""" + outputs: dict[Any, StreamProtocol], + ) -> StreamProtocol: + """The output stream of a node's one predecessor (function and side-effect nodes).""" predecessors = list(graph.predecessors(node)) if len(predecessors) != 1: raise ValueError( f"FunctionNode expects exactly 1 upstream, got {len(predecessors)}" ) - return buffers[predecessors[0]] + return outputs[predecessors[0]] @staticmethod - def _gather_upstream_multi( + def _ordered_inputs( node: Any, graph: "GraphProtocol[Any]", - buffers: dict[Any, list[tuple[Any, Any]]], - ) -> list[tuple[list[tuple[Any, Any]], Any]]: - """Gather multiple upstream buffers with their nodes (for operators). - - Returns list of (buffer, upstream_node) tuples preserving the - order that matches the operator's input_streams order. - """ + outputs: dict[Any, StreamProtocol], + ) -> list[StreamProtocol]: + """The output streams of an operator node's predecessors, in ``node.upstreams`` order.""" predecessors = list(graph.predecessors(node)) upstream_order = {id(upstream): i for i, upstream in enumerate(node.upstreams)} sorted_preds = sorted( predecessors, key=lambda p: upstream_order.get(id(p), 0), ) - return [(buffers[p], p) for p in sorted_preds] - - @staticmethod - def _materialize_as_stream(buf: list[tuple[Any, Any]], upstream_node: Any) -> Any: - """Wrap a (tag, data) buffer as the upstream node's stream. - - ``StaticOutputOperatorPod._materialize_upstream`` builds it, the one - definition an async operator node shares when it rebuilds its inputs - for a run that produced no row. - - Args: - buf: List of (tag, data) tuples. - upstream_node: The node that produced this buffer. - - Returns: - An ArrowTableStream. - """ - from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod - - return StaticOutputOperatorPod._materialize_upstream(buf, upstream_node) + return [outputs[p] for p in sorted_preds] @staticmethod - def _gc_buffers( + def _gc_outputs( current_node: Any, graph: "GraphProtocol[Any]", - buffers: dict[Any, list[tuple[Any, Any]]], + outputs: dict[Any, StreamProtocol], processed: set[Any], ) -> None: - """Discard buffers no longer needed by any unprocessed downstream.""" + """Drop output streams no unprocessed successor still needs.""" for pred in graph.predecessors(current_node): - if pred not in buffers: + if pred not in outputs: continue all_successors_done = all( succ in processed for succ in graph.successors(pred) ) if all_successors_done: - del buffers[pred] + del outputs[pred] diff --git a/src/orcapod/protocols/core_protocols/streams.py b/src/orcapod/protocols/core_protocols/streams.py index 010d29232..1ebc044f8 100644 --- a/src/orcapod/protocols/core_protocols/streams.py +++ b/src/orcapod/protocols/core_protocols/streams.py @@ -171,6 +171,32 @@ def output_schema( """ ... + def arrow_schema(self) -> "pa.Schema": + """The Arrow schema of the columns the stream passes between job nodes. + + The user tags, system tags, data and source-info columns, in row order (user + tags, system tags, data, source info), with the Arrow types, nullability and + field metadata of the rows; no context and no meta column (ITL-1347). Known + without reading, computing or polling a row. Two exceptions keep today's + bytes: source-info fields are stated nullable (a table decides their flags + from its tokens), and a ``null`` column keeps the ``null`` type a zero-row table + has (rows carry ``large_string``; ITL-1319). + + Returns: + The declared Arrow schema. + """ + ... + + @property + def arrow_types_declared(self) -> bool: + """Whether ``arrow_schema()`` holds the rows' own Arrow types. + + ``False`` only when the stream cannot type itself without rows (an unbound + slot, a ``PollingSource`` never polled; ITL-1089): its schema is then converted + from the Python schema. + """ + ... + def iter_data(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: """ Generates explicit iterator over (tag, data) pairs in the stream. diff --git a/src/orcapod/protocols/node_protocols.py b/src/orcapod/protocols/node_protocols.py index 499c74b53..cf1080c53 100644 --- a/src/orcapod/protocols/node_protocols.py +++ b/src/orcapod/protocols/node_protocols.py @@ -46,7 +46,7 @@ def execute( self, *, observer: ExecutionObserverProtocol | None = None, - ) -> list[tuple[TagProtocol, DataProtocol]]: ... + ) -> StreamProtocol: ... async def async_execute( self, @@ -89,7 +89,7 @@ def execute( error_policy: Literal["continue", "fail_fast"] = "continue", run_id: str | None = None, load_only: bool = False, - ) -> list[tuple[TagProtocol, DataProtocol]]: ... + ) -> StreamProtocol: ... async def async_execute( self, @@ -129,7 +129,7 @@ def execute( *input_streams: StreamProtocol, observer: ExecutionObserverProtocol | None = None, load_only: bool = False, - ) -> list[tuple[TagProtocol, DataProtocol]]: ... + ) -> StreamProtocol: ... async def async_execute( self, @@ -162,7 +162,7 @@ def execute( observer: "ExecutionObserverProtocol | None" = None, run_id: str | None = None, load_only: bool = False, - ) -> "list[tuple[TagProtocol, DataProtocol]]": ... + ) -> "StreamProtocol": ... async def async_execute( self, diff --git a/src/orcapod/side_effects.py b/src/orcapod/side_effects.py index de75192ef..95f4c922e 100644 --- a/src/orcapod/side_effects.py +++ b/src/orcapod/side_effects.py @@ -13,7 +13,7 @@ import datetime import logging from collections.abc import Callable, Collection, Iterator, Sequence -from typing import TYPE_CHECKING, Any, Literal +from typing import TYPE_CHECKING, Any, Literal, cast import pyarrow as pa from typing_extensions import override @@ -1225,7 +1225,7 @@ def execute( observer: ExecutionObserverProtocol | None = None, run_id: str | None = None, load_only: bool = False, - ) -> list[tuple[TagProtocol, DataProtocol]]: + ) -> StreamProtocol: """Execute side-effect delivery for all rows in ``input_stream``. Args: @@ -1239,7 +1239,10 @@ def execute( delivering (ITL-1091). A run that raises leaves the node with no rows. Returns: - List of ``(tag, data)`` tuples — the pass-through rows. + The node's output stream: the rows it passed on, as the table + ``_rows_to_table`` builds from them, with this node's identity + (``StaticOutputOperatorPod._materialize_upstream``). The sync orchestrator + hands it to every successor (ITL-1347, stage 2). Raises: SideEffectLogDataContextError: If the invocation log holds deliveries @@ -1254,7 +1257,7 @@ def execute( self.clear_cache() raise self._hold(rows, load_only=True) - return rows + return self._output_stream(rows) try: results = self._deliver_rows(input_stream, run_id=run_id) except BaseException: @@ -1263,7 +1266,21 @@ def execute( self.clear_cache() raise self._hold(results) - return results + return self._output_stream(results) + + def _output_stream( + self, rows: list[tuple[TagProtocol, DataProtocol]] + ) -> StreamProtocol: + """The output stream of a run that passed ``rows`` on. + + What the sync orchestrator built from a node's rows for its successors + (``StaticOutputOperatorPod._materialize_upstream``). + """ + from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod + + return StaticOutputOperatorPod._materialize_upstream( + rows, cast("StreamProtocol", self) + ) def _deliver_rows( self, input_stream: StreamProtocol, *, run_id: str | None diff --git a/tests/test_core/function_pod/test_ephemeral_result.py b/tests/test_core/function_pod/test_ephemeral_result.py index 799c83bc1..2d0e6cfd1 100644 --- a/tests/test_core/function_pod/test_ephemeral_result.py +++ b/tests/test_core/function_pod/test_ephemeral_result.py @@ -152,7 +152,7 @@ def test_is_ephemeral_false_written_to_pipeline_db(self): stream = _make_stream([{"id": 0, "x": 10}]) node, db = _make_node(stream) - results = node.execute(stream) + results = list(node.execute(stream).iter_data()) assert len(results) == 1 all_records = db.get_all_records(node._versioned_pipeline_path) @@ -171,7 +171,7 @@ def test_is_ephemeral_true_written_to_pipeline_db(self): node, _ = _make_node(stream, pipeline_db=pipeline_db, is_result_ephemeral=True) node.set_ephemeral_database(ephemeral_store) - results = node.execute(stream) + results = list(node.execute(stream).iter_data()) assert len(results) == 1 all_records = pipeline_db.get_all_records(node._versioned_pipeline_path) @@ -191,7 +191,7 @@ def test_ephemeral_false_unchanged(self): """is_result_ephemeral=False: execute() behaves identically to current implementation.""" stream = _make_stream([{"id": 0, "x": 10}, {"id": 1, "x": 20}]) node, _ = _make_node(stream) - results = node.execute(stream) + results = list(node.execute(stream).iter_data()) assert len(results) == 2 vals = {tag.as_dict()["id"]: data.as_dict()["result"] for tag, data in results} assert vals == {0: 20, 1: 40} @@ -211,7 +211,7 @@ def test_ephemeral_result_written_to_memory_not_persistent_db(self): ) node.node_config = NodeConfig(is_result_ephemeral=True) node.set_ephemeral_database(ephemeral_store) - results = node.execute(stream) + results = list(node.execute(stream).iter_data()) assert len(results) == 1 assert results[0][1].as_dict()["result"] == 20 @@ -311,7 +311,7 @@ def counting_double(x: int) -> int: node.set_ephemeral_database(InMemoryArrowDatabase()) # Run 1: writes to persistent DB (is_result_ephemeral=False) - results = node.execute(stream) + results = list(node.execute(stream).iter_data()) assert len(results) == 1 assert results[0][1].as_dict()["result"] == 20 assert call_count["n"] == 1 @@ -320,7 +320,7 @@ def counting_double(x: int) -> int: node._cached_output_datas.clear() # Run 2: Phase 1 must find persistent result — no recompute - results2 = node.execute(stream) + results2 = list(node.execute(stream).iter_data()) assert len(results2) == 1 assert results2[0][1].as_dict()["result"] == 20 assert call_count["n"] == 1 # NOT recomputed @@ -374,7 +374,7 @@ def counting_double(x: int) -> int: node_both.set_ephemeral_database(ephemeral_store) node_both._cached_output_datas.clear() - results = node_both.execute(stream_both) + results = list(node_both.execute(stream_both).iter_data()) assert len(results) == 2 vals = {tag.as_dict()["id"]: data.as_dict()["result"] for tag, data in results} assert vals == {0: 20, 1: 40} @@ -482,7 +482,7 @@ def counting_double(x: int) -> int: # The anti-join should exclude the ephemeral row (entry_id clash with persistent row), # returning only the persistent result. No recomputation. - results = node.execute(stream) + results = list(node.execute(stream).iter_data()) assert len(results) == 1 assert results[0][1].as_dict()["result"] == 20 # call_count did not increase — persistent hit from anti-join merge, no recomputation @@ -524,7 +524,7 @@ def test_ephemeral_only_node(self): ) node.node_config = NodeConfig(is_result_ephemeral=True) node.set_ephemeral_database(ephemeral_store) - results = node.execute(stream) + results = list(node.execute(stream).iter_data()) assert len(results) == 1 assert results[0][1].as_dict()["result"] == 20 @@ -740,7 +740,7 @@ def test_persistent_miss_warns_and_recomputes(self, caplog): with caplog.at_level( logging.WARNING, logger="orcapod.core.nodes.function_node" ): - results = node2.execute(stream) + results = list(node2.execute(stream).iter_data()) assert len(results) == 1 # recomputed assert any( @@ -818,7 +818,7 @@ def test_ephemeral_only_node_no_persistent_db(self): ) node.node_config = NodeConfig(is_result_ephemeral=True) node.set_ephemeral_database(ephemeral_store) - results = node.execute(stream) + results = list(node.execute(stream).iter_data()) assert len(results) == 2 vals = {tag.as_dict()["id"]: data.as_dict()["result"] for tag, data in results} @@ -1021,7 +1021,7 @@ def test_legacy_records_without_ephemeral_col_treated_as_persistent(self): pipeline_database=pipeline_db, result_database=result_db, ) - results = node2.execute(stream) + results = list(node2.execute(stream).iter_data()) # Result must be served (from result DB cache or recomputed) assert len(results) == 1 @@ -1082,7 +1082,7 @@ def counting_double(x: int) -> int: result_database=result_db, ) count_before_session2 = call_count["n"] - results = node2.execute(stream) + results = list(node2.execute(stream).iter_data()) assert len(results) == 1 assert results[0][1].as_dict()["result"] == 20 assert call_count["n"] == count_before_session2 # NOT recomputed diff --git a/tests/test_core/function_pod/test_function_pod_ctx_arg.py b/tests/test_core/function_pod/test_function_pod_ctx_arg.py index 9a4460448..4ab26113a 100644 --- a/tests/test_core/function_pod/test_function_pod_ctx_arg.py +++ b/tests/test_core/function_pod/test_function_pod_ctx_arg.py @@ -156,14 +156,14 @@ def my_fn(value: int, ctx: InvocationContext) -> str: node1 = FunctionJobNode(function_pod=pod, input_stream=stream) node1.attach_databases(pipeline_database=pipeline_db) - results1 = node1.execute(stream) + results1 = list(node1.execute(stream).iter_data()) assert len(results1) == 2 assert call_count == 2 # Second run — same pod, same data, same DB — must NOT call fn again node2 = FunctionJobNode(function_pod=pod, input_stream=stream) node2.attach_databases(pipeline_database=pipeline_db) - results2 = node2.execute(stream) + results2 = list(node2.execute(stream).iter_data()) assert len(results2) == 2 assert call_count == 2 # NOT incremented diff --git a/tests/test_core/nodes/test_function_node_iteration.py b/tests/test_core/nodes/test_function_node_iteration.py index 29b5123eb..1364f648b 100644 --- a/tests/test_core/nodes/test_function_node_iteration.py +++ b/tests/test_core/nodes/test_function_node_iteration.py @@ -174,8 +174,12 @@ class CapturingObserver(NoOpObserver): def on_data_crash(self, node_label, tag, data, exc): errors.append(exc) - results = node.execute( - node._input_stream, observer=CapturingObserver(), error_policy="continue" + results = list( + node.execute( + node._input_stream, + observer=CapturingObserver(), + error_policy="continue", + ).iter_data() ) assert len(errors) == 1 assert isinstance(errors[0], ValueError) diff --git a/tests/test_core/nodes/test_node_execute.py b/tests/test_core/nodes/test_node_execute.py index 447ad1c1e..b34401b7e 100644 --- a/tests/test_core/nodes/test_node_execute.py +++ b/tests/test_core/nodes/test_node_execute.py @@ -101,7 +101,7 @@ def test_caches_internally(self, function_node_with_db): class TestFunctionNodeExecute: def test_returns_materialized_results(self, function_node_with_db): node, _, _ = function_node_with_db - results = node.execute(node._input_stream) + results = list(node.execute(node._input_stream).iter_data()) assert isinstance(results, list) assert len(results) == 2 values = sorted([pkt.as_dict()["result"] for _, pkt in results]) @@ -162,7 +162,7 @@ def operator_no_db(): class TestOperatorNodeExecute: def test_returns_materialized_results(self, operator_no_db): node, src = operator_no_db - results = node.execute(src) + results = list(node.execute(src).iter_data()) assert isinstance(results, list) assert len(results) == 2 @@ -181,6 +181,6 @@ def test_caches_internally(self, operator_no_db): def test_noop_db_in_off_mode(self, operator_no_db): node, src = operator_no_db - results = node.execute(src) + results = list(node.execute(src).iter_data()) assert len(results) == 2 assert node.get_all_records() is None diff --git a/tests/test_core/operators/test_materialize_source_info.py b/tests/test_core/operators/test_materialize_source_info.py index c6fee9a91..190c6ddec 100644 --- a/tests/test_core/operators/test_materialize_source_info.py +++ b/tests/test_core/operators/test_materialize_source_info.py @@ -688,7 +688,7 @@ def test_rerun_after_pre_fix_store(self, monkeypatch: pytest.MonkeyPatch): assert _stored_source(old) == [tokens[0]] * 3 new = self._node(db) - out = new.execute(_pin_source()) + out = list(new.execute(_pin_source()).iter_data()) # The run itself emits the corrected rows. assert _source_info_tokens(out) == tokens diff --git a/tests/test_core/side_effect_function/test_side_effect_function_pod.py b/tests/test_core/side_effect_function/test_side_effect_function_pod.py index ae7d470d1..0543c1ab7 100644 --- a/tests/test_core/side_effect_function/test_side_effect_function_pod.py +++ b/tests/test_core/side_effect_function/test_side_effect_function_pod.py @@ -176,14 +176,14 @@ def my_fn(value: int, ctx: InvocationContext) -> str: node1 = FunctionJobNode(function_pod=pod, input_stream=stream) node1.attach_databases(pipeline_database=pipeline_db) - results1 = node1.execute(stream) + results1 = list(node1.execute(stream).iter_data()) assert len(results1) == 2 assert call_count == 2 # Second run — same pod, same data, same DB — fn must NOT be called again node2 = FunctionJobNode(function_pod=pod, input_stream=stream) node2.attach_databases(pipeline_database=pipeline_db) - results2 = node2.execute(stream) + results2 = list(node2.execute(stream).iter_data()) assert len(results2) == 2 assert call_count == 2 # NOT incremented — cache hit diff --git a/tests/test_core/side_effect_pod/test_side_effect_pod.py b/tests/test_core/side_effect_pod/test_side_effect_pod.py index 18be593e4..f5eb4487d 100644 --- a/tests/test_core/side_effect_pod/test_side_effect_pod.py +++ b/tests/test_core/side_effect_pod/test_side_effect_pod.py @@ -320,7 +320,7 @@ def fn(value, ctx): calls.append(True) node, stream, db = self._make_node_with_db(fn) - results = node.execute(stream) + results = list(node.execute(stream).iter_data()) assert len(results) == 3 assert len(calls) == 3 @@ -356,14 +356,14 @@ def fn(value, ctx): node1 = SideEffectJobNode(side_effect_pod=pod, input_stream=stream) node1.attach_databases(pipeline_database=db) - results1 = node1.execute(stream) + results1 = list(node1.execute(stream).iter_data()) assert len(results1) == 2 assert len(calls) == 2 # Second run with same DB node2 = SideEffectJobNode(side_effect_pod=pod, input_stream=stream) node2.attach_databases(pipeline_database=db) - results2 = node2.execute(stream) + results2 = list(node2.execute(stream).iter_data()) assert len(results2) == 2 # rows still emitted (pass-through) assert len(calls) == 2 # fn NOT called again — completion check triggered @@ -441,7 +441,7 @@ def fn(value, ctx): # Run 1: fn raises → nothing written to DB. node1 = SideEffectJobNode(side_effect_pod=pod, input_stream=stream) node1.attach_databases(pipeline_database=db) - results1 = node1.execute(stream) + results1 = list(node1.execute(stream).iter_data()) assert len(results1) == 1 # row still emitted (drop_on_failure=False) assert call_count == 1 # fn was invoked @@ -451,7 +451,7 @@ def fn(value, ctx): # Run 2: no record found → fn is called again, still fails. node2 = SideEffectJobNode(side_effect_pod=pod, input_stream=stream) node2.attach_databases(pipeline_database=db) - results2 = node2.execute(stream) + results2 = list(node2.execute(stream).iter_data()) assert len(results2) == 1 assert call_count == 2 # retried — fn called a second time @@ -490,7 +490,7 @@ def fn(value, ctx): # Run 1: fn raises → no DB record. node1 = SideEffectJobNode(side_effect_pod=pod, input_stream=stream) node1.attach_databases(pipeline_database=db) - results1 = node1.execute(stream) + results1 = list(node1.execute(stream).iter_data()) assert len(results1) == 1 # emitted despite failure assert call_count == 1 @@ -500,7 +500,7 @@ def fn(value, ctx): # Run 2: no record → fn retried → succeeds → record written. node2 = SideEffectJobNode(side_effect_pod=pod, input_stream=stream) node2.attach_databases(pipeline_database=db) - results2 = node2.execute(stream) + results2 = list(node2.execute(stream).iter_data()) assert len(results2) == 1 assert call_count == 2 # fn called exactly once more @@ -512,7 +512,7 @@ def fn(value, ctx): # Run 3: record found → fn NOT called → row re-emitted from cache. node3 = SideEffectJobNode(side_effect_pod=pod, input_stream=stream) node3.attach_databases(pipeline_database=db) - results3 = node3.execute(stream) + results3 = list(node3.execute(stream).iter_data()) assert len(results3) == 1 assert call_count == 2 # still 2 — fn was skipped entirely diff --git a/tests/test_core/sources/test_postgresql_table_source_integration.py b/tests/test_core/sources/test_postgresql_table_source_integration.py index 46592b213..8dca286db 100644 --- a/tests/test_core/sources/test_postgresql_table_source_integration.py +++ b/tests/test_core/sources/test_postgresql_table_source_integration.py @@ -253,7 +253,9 @@ def double_response(trial: int, response: float) -> float: result = orch.run(exec_dag) fn_outputs = [ - v for k, v in result.node_outputs.items() if k.node_type == "function" + list(v.iter_data()) + for k, v in result.node_outputs.items() + if k.node_type == "function" ] assert len(fn_outputs) == 1 assert len(fn_outputs[0]) == 3 diff --git a/tests/test_core/sources/test_spiraldb_table_source_where.py b/tests/test_core/sources/test_spiraldb_table_source_where.py index db78b7787..05a84a55f 100644 --- a/tests/test_core/sources/test_spiraldb_table_source_where.py +++ b/tests/test_core/sources/test_spiraldb_table_source_where.py @@ -1933,7 +1933,9 @@ def test_execute_over_unrestricted_streams_still_caches( (("m2", 5), 5.5, 1), ] - logged = node.execute(_source(source_id="events", tag_only_columns=True)) + logged = list( + node.execute(_source(source_id="events", tag_only_columns=True)).iter_data() + ) assert self._keyed(logged) == expected stored = node.as_source().as_table().to_pylist() @@ -1952,7 +1954,7 @@ def test_execute_over_unrestricted_streams_still_caches( ) scans = len(fake_pyspiral.scan_log) - replayed = node.execute(other) + replayed = list(node.execute(other).iter_data()) assert self._keyed(replayed) == expected assert len(fake_pyspiral.scan_log) == scans diff --git a/tests/test_core/sources/test_sqlite_table_source.py b/tests/test_core/sources/test_sqlite_table_source.py index fe74de6ce..91008dc35 100644 --- a/tests/test_core/sources/test_sqlite_table_source.py +++ b/tests/test_core/sources/test_sqlite_table_source.py @@ -611,7 +611,9 @@ def double_response(trial: int, response: float) -> float: result = orch.run(exec_dag) fn_outputs = [ - v for k, v in result.node_outputs.items() if k.node_type == "function" + list(v.iter_data()) + for k, v in result.node_outputs.items() + if k.node_type == "function" ] assert len(fn_outputs) == 1 assert len(fn_outputs[0]) == 3 diff --git a/tests/test_core/test_tracker.py b/tests/test_core/test_tracker.py index 8f28798be..046239abb 100644 --- a/tests/test_core/test_tracker.py +++ b/tests/test_core/test_tracker.py @@ -251,7 +251,7 @@ def test_run_equivalent(self): """execute() on SourceJobNode returns all data rows.""" stream = _make_source() node = self._make_job_node(stream) - result = node.execute() + result = list(node.execute().iter_data()) assert len(result) == stream.as_table().num_rows def test_data_context_key(self): diff --git a/tests/test_pipeline/test_current_run_review_fixes.py b/tests/test_pipeline/test_current_run_review_fixes.py index 25f266174..7ad949768 100644 --- a/tests/test_pipeline/test_current_run_review_fixes.py +++ b/tests/test_pipeline/test_current_run_review_fixes.py @@ -17,6 +17,8 @@ import pyarrow as pa import pytest +from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod + from orcapod import PipelineJob, function_pod from orcapod.core.nodes import OperatorJobNode from orcapod.core.nodes.source_node import SourceJobNode @@ -750,14 +752,18 @@ def test_a_direct_async_run_drains_the_inputs_of_a_held_node( (grouped, summed), ): dag.add_edge(upstream, downstream) - held = {rowwise: list(rowwise.iter_data())} + held = { + rowwise: StaticOutputOperatorPod._materialize_upstream( # pyright: ignore[reportPrivateUsage] # a held node's output stream, as the run plan builds it + list(rowwise.iter_data()), rowwise + ) + } summed.clear_cache() grouped.clear_cache() orchestrator = AsyncPipelineOrchestrator(buffer_size=2, error_policy=error_policy) async def run() -> None: """Run the whole graph with ``rowwise`` held, under a time limit.""" - await asyncio.wait_for(orchestrator.run_async(dag, held_rows=held), timeout=30) + await asyncio.wait_for(orchestrator.run_async(dag, held=held), timeout=30) asyncio.run(run()) assert summed.as_table().num_rows == 2 diff --git a/tests/test_pipeline/test_job_node_rows_after_run.py b/tests/test_pipeline/test_job_node_rows_after_run.py index 6d00c1154..04ba3867a 100644 --- a/tests/test_pipeline/test_job_node_rows_after_run.py +++ b/tests/test_pipeline/test_job_node_rows_after_run.py @@ -422,7 +422,7 @@ def test_sync_one_of_two_equal_inputs_fails(self) -> None: node = self._node(self._flaky_pod()) received = sorted( (tag.as_dict()["k"], data.as_dict()["y"]) - for tag, data in node.execute(node.upstreams[0]) + for tag, data in list(node.execute(node.upstreams[0]).iter_data()) ) assert received == [(0, 6), (2, 8)] assert self._held(node) == received diff --git a/tests/test_pipeline/test_node_protocols.py b/tests/test_pipeline/test_node_protocols.py index fbd08b867..b59428341 100644 --- a/tests/test_pipeline/test_node_protocols.py +++ b/tests/test_pipeline/test_node_protocols.py @@ -200,14 +200,14 @@ def _make_source_node(self): def test_execute_returns_list(self): node = self._make_source_node() - result = node.execute() + result = list(node.execute().iter_data()) assert isinstance(result, list) assert len(result) == 3 def test_execute_populates_cached_results(self): """execute() on SourceJobNode returns correct data (no caching field).""" node = self._make_source_node() - result = node.execute() + result = list(node.execute().iter_data()) assert len(result) == 3 def test_execute_with_observer(self): @@ -234,7 +234,7 @@ def on_data_end(self, node_label, t, ip, op, cached): def test_execute_without_observer(self): """execute() works fine with no observer.""" node = self._make_source_node() - result = node.execute() + result = list(node.execute().iter_data()) assert len(result) == 3 @@ -337,7 +337,7 @@ def create_data_logger(self, t, p, **kwargs): return _NOOP_LOGGER input_stream = node._input_stream - result = node.execute(input_stream, observer=Obs()) + result = list(node.execute(input_stream, observer=Obs()).iter_data()) assert len(result) == 2 assert events[0][0] == "node_start" @@ -348,7 +348,7 @@ def create_data_logger(self, t, p, **kwargs): def test_execute_without_observer(self): node = self._make_function_node() input_stream = node._input_stream - result = node.execute(input_stream) + result = list(node.execute(input_stream).iter_data()) assert len(result) == 2 values = sorted([pkt.as_dict()["result"] for _, pkt in result]) assert values == [2, 4] @@ -488,14 +488,14 @@ def on_data_start(self, node_label, t, p): def on_data_end(self, node_label, t, ip, op, cached): pass - result = node.execute(*node._input_streams, observer=Obs()) + result = list(node.execute(*node._input_streams, observer=Obs()).iter_data()) assert len(result) == 2 assert events[0][0] == "node_start" assert events[1][0] == "node_end" def test_execute_without_observer(self): node = self._make_join_node() - result = node.execute(*node._input_streams) + result = list(node.execute(*node._input_streams).iter_data()) assert len(result) == 2 diff --git a/tests/test_pipeline/test_operator_kept_table_reuse.py b/tests/test_pipeline/test_operator_kept_table_reuse.py deleted file mode 100644 index ea0e46eed..000000000 --- a/tests/test_pipeline/test_operator_kept_table_reuse.py +++ /dev/null @@ -1,181 +0,0 @@ -"""ITL-1347 stage 1: a successor's input reuses the table its operator node kept. - -An operator node's ``execute`` returns its rows as ``RowsWithTable``, carrying the table -``_rows_to_table`` built for the output the node keeps. The sync orchestrator rebuilds a -successor's input with ``_materialize_upstream``, which now takes that table instead of -building it from the rows again. The governing rule of the spec -(``docs/dev/specs/itl-1347-job-table-transport.md``) is that nothing a run shows may change. -So every successor's input must equal, byte for byte and in identity, the input built from -the same rows as a plain list (the path before stage 1). The test checks that on every -edge of a job that uses every operator kind, over several tag orders, table layouts and tag -roles. These tests are about the orchestrator's internal hand-off, so they wrap it. -""" - -from __future__ import annotations - -import warnings -from collections.abc import Iterator -from typing import Any - -import pytest - -from orcapod import PipelineJob, function_pod -from orcapod.core.operators.static_output_pod import ( - RowsWithTable, - StaticOutputOperatorPod, -) -from orcapod.databases import InMemoryArrowDatabase -from orcapod.errors import ProvisionalHashWarning -from orcapod.operators import MergeJoin, Rejoin -from orcapod.pipeline import SyncPipelineOrchestrator -from tests.test_core.operators.several_items import ( - MAIN, - P, - Q, - Arrangement, - arrangements, - make_source, -) - -ALL_COLUMNS = { - "meta": True, - "source": True, - "system_tags": True, - "context": True, - "content_hash": True, -} - - -@function_pod(output_keys="d1_doubled") -def doubled(d1: int) -> int: - return 2 * d1 - - -def build_job(arrangement: Arrangement) -> Any: - """A job in which every operator kind feeds a successor.""" - main = make_source(MAIN, arrangement) - partner_p = make_source(P) - partner_q = make_source(Q) - job = PipelineJob(name="kept_table_reuse", database=InMemoryArrowDatabase()) - with job: - joined = main.join(partner_p, label="joined") - mapped = joined.map_data({"p1": "p1_renamed"}, label="mapped") - no_nulls = mapped.drop_nulls(["d2"], label="no_nulls") - no_nulls.select_data_columns(["d1", "p1_renamed"], label="after_no_nulls") - grouped = main.group_by(["t1"], label="grouped") - grouped.select_data_columns(["d1"], label="after_grouped") - batched = main.select_data_columns(["d1"]).batch(batch_size=2, label="batched") - batched.select_data_columns(["d1"], label="after_batched") - tagged = main.add_tags(k=1, label="tagged") - doubled.pod(tagged.select_data_columns(["d1"]), label="doubled") - semi = main.semi_join(partner_q, label="semi") - semi.select_data_columns(["d3"], label="after_semi") - merged = MergeJoin()( - main.select_data_columns(["d1"]), - partner_p.map_data({"p1": "d1"}).select_data_columns(["d1"]), - ) - merged.select_data_columns(["d1"], label="after_merged") - rejoined = Rejoin()( - main.select_data_columns(["d1"]), main.select_data_columns(["d3"]) - ) - rejoined.select_data_columns(["d1"], label="after_rejoined") - nothing = main.polars_filter(d1=999, label="nothing") - nothing.select_data_columns(["d1"], label="after_nothing") - return job - - -def _identity(stream: Any) -> tuple[Any, ...]: - return ( - type(stream), - stream.producer, - tuple(id(u) for u in stream.upstreams), - stream.pipeline_hash(), - stream.content_hash(), - stream.keys(), - stream.output_schema(), - stream.data_context_key, - ) - - -@pytest.fixture -def recorded_edges(monkeypatch: pytest.MonkeyPatch) -> Iterator[list[str]]: - """Wrap the orchestrator's input rebuild; check each input against the old path.""" - original = SyncPipelineOrchestrator._materialize_as_stream - reused: list[str] = [] - - def checked(buf: Any, upstream_node: Any) -> Any: - built = original(buf, upstream_node) - plain = StaticOutputOperatorPod._materialize_upstream( # pyright: ignore[reportPrivateUsage] # the path before stage 1 - list(buf), upstream_node - ) - assert _identity(built) == _identity(plain) - built_table = built.as_table(columns=ALL_COLUMNS).combine_chunks() - plain_table = plain.as_table(columns=ALL_COLUMNS).combine_chunks() - assert built_table.schema.equals(plain_table.schema, check_metadata=True) - assert built_table.equals(plain_table, check_metadata=True) - if isinstance(buf, RowsWithTable): - reused.append(upstream_node.label) - return built - - monkeypatch.setattr( - SyncPipelineOrchestrator, "_materialize_as_stream", staticmethod(checked) - ) - yield reused - - -@pytest.mark.parametrize("arrangement", arrangements(MAIN), ids=lambda a: a.id) -def test_every_successor_input_equals_the_rebuilt_one( - arrangement: Arrangement, recorded_edges: list[str] -) -> None: - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ProvisionalHashWarning) - job = build_job(arrangement) - job.run() - # Every operator node with rows handed its kept table on; the one with no rows - # (``nothing``) took the plain path, which gives its zero-row input as before. - assert { - "joined", - "mapped", - "no_nulls", - "grouped", - "batched", - "tagged", - "semi", - } <= set(recorded_edges) - assert "nothing" not in recorded_edges - - -def test_a_held_operator_node_takes_the_plain_path( - recorded_edges: list[str], -) -> None: - """A second run holds every node: buffers are plain lists, inputs as before.""" - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ProvisionalHashWarning) - job = build_job(arrangements(MAIN)[0]) - job.run() - recorded_edges.clear() - # Clear one function node so the second run has something to run, fed by a - # held operator node. - job.nodes["doubled"].clear_cache() - job.run() - assert recorded_edges == [] - - -def test_execute_returns_rows_equal_to_the_plain_list() -> None: - """The rows an operator node returns compare equal to the plain list of its rows.""" - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ProvisionalHashWarning) - job = build_job(arrangements(MAIN)[0]) - job.run() - node = job.nodes["joined"] - upstreams = [ - StaticOutputOperatorPod._materialize_upstream(list(u.iter_data()), u) # pyright: ignore[reportPrivateUsage] # the orchestrator's input form - for u in node.upstreams - ] - rows = node.execute(*upstreams) - assert isinstance(rows, RowsWithTable) - assert rows == list(rows) - table, tag_keys, data_tags = rows.row_table - assert table.num_rows == len(rows) - assert tag_keys == node.keys()[0] - assert isinstance(data_tags, tuple) diff --git a/tests/test_pipeline/test_operator_node_async_readback.py b/tests/test_pipeline/test_operator_node_async_readback.py index 7e7189be4..345d738a6 100644 --- a/tests/test_pipeline/test_operator_node_async_readback.py +++ b/tests/test_pipeline/test_operator_node_async_readback.py @@ -287,7 +287,7 @@ def make_node() -> OperatorJobNode: ) sync_node, async_node = make_node(), make_node() - sync_rows = sync_node.execute(source) + sync_rows = list(sync_node.execute(source).iter_data()) async def run() -> list[tuple[TagProtocol, DataProtocol]]: """Drive the node's public channel interface and collect forwarded rows.""" diff --git a/tests/test_pipeline/test_stream_transport_equivalence.py b/tests/test_pipeline/test_stream_transport_equivalence.py new file mode 100644 index 000000000..a6965a366 --- /dev/null +++ b/tests/test_pipeline/test_stream_transport_equivalence.py @@ -0,0 +1,269 @@ +"""ITL-1347 stage 2: a node's output stream equals the stream built from its rows. + +Every job node's ``execute`` now returns its output stream, which the sync orchestrator +hands to every successor. Sources build it from their Arrow table and operators from +their result's Arrow table, with no rows made (the row-built form F, +``StaticOutputOperatorPod._row_built_form``). The governing rule of the spec +(``docs/dev/specs/itl-1347-job-table-transport.md``) is that nothing a run shows may +change. So each output stream must equal, in identity and byte for byte, the stream the +orchestrator built before stage 2 from the same node's rows +(``_materialize_upstream(rows, node)``): + +- L2 (sources): rows are the source node's ``iter_data()``; +- L1 (operators): rows are the operator's result's ``iter_data()``, or the stored + stream's under ``REPLAY``; +- L0 (function and side-effect nodes): rows are the output stream's own rows; +- L5 (held nodes): a held node's stream equals the one built from its rows; +- L7: every node's declared ``arrow_schema()`` equals the schema of its output. + +The job uses every operator kind over several tag orders, table layouts and tag roles. +These tests are about the hand-off between nodes, so they wrap the nodes' ``execute``. +""" + +from __future__ import annotations + +import warnings +from collections.abc import Iterator +from typing import Any + +import pyarrow as pa +import pytest + +from orcapod import PipelineJob, function_pod, tap_pod +from orcapod.core.nodes.function_node import FunctionJobNode +from orcapod.core.nodes.operator_node import OperatorJobNode +from orcapod.core.nodes.source_node import SourceNodeBase +from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod +from orcapod.core.streams.base import ZERO_ROW_INPUT_COLUMNS +from orcapod.databases import InMemoryArrowDatabase +from orcapod.errors import ProvisionalHashWarning +from orcapod.operators import MergeJoin, Rejoin +from orcapod.side_effects import SideEffectJobNode +from orcapod.system_constants import constants +from orcapod.types import CacheMode +from tests.test_core.operators.several_items import ( + MAIN, + P, + Q, + Arrangement, + arrangements, + make_source, +) + +ALL_COLUMNS = { + "meta": True, + "source": True, + "system_tags": True, + "context": True, + "content_hash": True, +} + + +@function_pod(output_keys="d1_doubled") +def doubled(d1: int) -> int: + return 2 * d1 + + +@tap_pod +def noted(d1_doubled: int, ctx: Any) -> None: + return None + + +def build_job(arrangement: Arrangement, database: Any = None) -> Any: + """A job in which every operator kind, a function node and a side effect run.""" + main = make_source(MAIN, arrangement) + partner_p = make_source(P) + partner_q = make_source(Q) + job = PipelineJob( + name="stream_transport", database=database or InMemoryArrowDatabase() + ) + with job: + joined = main.join(partner_p, label="joined") + mapped = joined.map_data({"p1": "p1_renamed"}, label="mapped") + no_nulls = mapped.drop_nulls(["d2"], label="no_nulls") + no_nulls.select_data_columns(["d1", "p1_renamed"], label="after_no_nulls") + main.group_by(["t1"], label="grouped").select_data_columns( + ["d1"], label="after_grouped" + ) + main.select_data_columns(["d1"]).batch(batch_size=2, label="batched") + tagged = main.add_tags(k=1, label="tagged") + twice = doubled.pod(tagged.select_data_columns(["d1"]), label="doubled") + noted_stream: Any = noted + noted_stream(twice, label="noted") + main.semi_join(partner_q, label="semi").select_data_columns( + ["d3"], label="after_semi" + ) + MergeJoin()( + main.select_data_columns(["d1"]), + partner_p.map_data({"p1": "d1"}).select_data_columns(["d1"]), + ).select_data_columns(["d1"], label="after_merged") + Rejoin()( + main.select_data_columns(["d1"]), main.select_data_columns(["d3"]) + ).select_data_columns(["d1"], label="after_rejoined") + main.polars_filter(d1=999, label="nothing").select_data_columns( + ["d1"], label="after_nothing" + ) + return job + + +def _identity(stream: Any) -> tuple[Any, ...]: + return ( + type(stream), + stream.producer, + tuple(id(u) for u in stream.upstreams), + stream.pipeline_hash(), + stream.content_hash(), + stream.keys(), + stream.output_schema(), + stream.data_context_key, + ) + + +def assert_same_stream(got: Any, expected: Any) -> None: + """Equal identity, and equal tables byte for byte (every column group).""" + assert _identity(got) == _identity(expected) + got_table = got.as_table(columns=ALL_COLUMNS).combine_chunks() + expected_table = expected.as_table(columns=ALL_COLUMNS).combine_chunks() + assert got_table.schema.equals(expected_table.schema, check_metadata=True) + assert got_table.equals(expected_table, check_metadata=True) + + +def _rebuilt(rows: list[Any], node: Any) -> Any: + return StaticOutputOperatorPod._materialize_upstream(rows, node) # pyright: ignore[reportPrivateUsage] # the path before stage 2 + + +@pytest.fixture +def outputs(monkeypatch: pytest.MonkeyPatch) -> Iterator[dict[str, Any]]: + """Wrap every node kind's ``execute``; check each output against the row path.""" + seen: dict[str, Any] = {} + + source_execute = SourceNodeBase.execute + + def source(self: Any, **kwargs: Any) -> Any: + out = source_execute(self, **kwargs) + assert_same_stream(out, _rebuilt(list(self.iter_data()), self)) # L2 + seen[self.label] = out + return out + + operator_execute = OperatorJobNode.execute + + def operator(self: Any, *inputs: Any, **kwargs: Any) -> Any: + cached = self.get_cached_output() + if cached is not None: + rows = list(cached.iter_data()) + else: + rows = list(self._operator.process(*inputs).iter_data()) # pyright: ignore[reportPrivateUsage] # the operator's own result, as before stage 2 + out = operator_execute(self, *inputs, **kwargs) + assert_same_stream(out, _rebuilt(rows, self)) # L1 + seen[self.label] = out + return out + + def by_construction(original: Any) -> Any: + def execute(self: Any, *args: Any, **kwargs: Any) -> Any: + out = original(self, *args, **kwargs) + assert_same_stream(out, _rebuilt(list(out.iter_data()), self)) # L0 + seen[self.label] = out + return out + + return execute + + monkeypatch.setattr(SourceNodeBase, "execute", source) + monkeypatch.setattr(OperatorJobNode, "execute", operator) + monkeypatch.setattr( + FunctionJobNode, "execute", by_construction(FunctionJobNode.execute) + ) + monkeypatch.setattr( + SideEffectJobNode, "execute", by_construction(SideEffectJobNode.execute) + ) + yield seen + + +def _run(job: Any) -> None: + with warnings.catch_warnings(): + warnings.simplefilter("ignore", ProvisionalHashWarning) + job.run() + + +@pytest.mark.parametrize("arrangement", arrangements(MAIN), ids=lambda a: a.id) +def test_every_output_stream_equals_the_row_rebuild( + arrangement: Arrangement, outputs: dict[str, Any] +) -> None: + with warnings.catch_warnings(): + warnings.simplefilter("ignore", ProvisionalHashWarning) + job = build_job(arrangement) + _run(job) + assert {"joined", "nothing", "doubled", "noted", "semi", "batched"} <= set(outputs) + + +def test_a_replayed_operator_output_equals_the_row_rebuild( + outputs: dict[str, Any], +) -> None: + """REPLAY hands on the stored rows' stream, equal to the one built from them.""" + store = InMemoryArrowDatabase() + with warnings.catch_warnings(): + warnings.simplefilter("ignore", ProvisionalHashWarning) + job = build_job(arrangements(MAIN)[0], store) + node = job.nodes["joined"] + node.attach_databases( + pipeline_database=store.at("replay"), cache_mode=CacheMode.LOG + ) + _run(job) + node.attach_databases( + pipeline_database=store.at("replay"), cache_mode=CacheMode.REPLAY + ) + node.clear_cache() + outputs.clear() + _run(job) + assert "joined" in outputs + + +def test_a_held_node_hands_on_the_stream_built_from_its_rows( + outputs: dict[str, Any], +) -> None: + """L5: a second run holds every node but one; held streams feed it as before.""" + with warnings.catch_warnings(): + warnings.simplefilter("ignore", ProvisionalHashWarning) + job = build_job(arrangements(MAIN)[0]) + _run(job) + job.nodes["noted"].clear_cache() + outputs.clear() + _run(job) + # Only the cleared side effect ran; its input came from the held function node. + assert set(outputs) == {"noted"} + + +def _without_exceptions(schema: pa.Schema) -> dict[str, tuple[Any, bool, Any]]: + """Fields by name as (type, nullable, metadata), the spec's two exceptions applied. + + A source-info field's flag is decided by a table's tokens (stated nullable), and a + ``null`` column is ``large_string`` in rows (ITL-1319). Columns are matched by name: + the declared (zero-row) form can list them in another order than the rows do (a + data-tag's source info, an operator's tags under another layout), as on ``main``, + and column order is not a result (developer, 2026-11-22). + """ + fields: dict[str, tuple[Any, bool, Any]] = {} + for field in schema: + kind = pa.large_string() if pa.types.is_null(field.type) else field.type + nullable = ( + True if field.name.startswith(constants.SOURCE_PREFIX) else field.nullable + ) + fields[field.name] = (kind, nullable, field.metadata) + return fields + + +@pytest.mark.parametrize("arrangement", arrangements(MAIN)[::4], ids=lambda a: a.id) +def test_declared_arrow_schema_equals_the_output( + arrangement: Arrangement, outputs: dict[str, Any] +) -> None: + """L7: ``arrow_schema()`` of every node equals the schema of its output stream.""" + with warnings.catch_warnings(): + warnings.simplefilter("ignore", ProvisionalHashWarning) + job = build_job(arrangement) + _run(job) + for label, stream in outputs.items(): + node = job.nodes[label] + output = stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS) + assert _without_exceptions(node.arrow_schema()) == _without_exceptions( + output.schema + ), label + assert node.arrow_types_declared, label From 303902ad1862ce89686a1fd64941389dea90fd72 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 02:41:56 -0800 Subject: [PATCH 09/86] perf(pipeline): F takes the stream's keys and flags system tags by value (ITL-1360) The row-built form F now equals the table built from rows in two more ways: source info follows the data keys (a data-tag's first, in tag order), and every system-tag field, like every source-info field, is nullable only when a value is null; no schema metadata is kept. F is split into the row-by-row steps (_row_built_columns, for a channel's record batches) and the whole-table flags (_flag_by_values). _output_stream takes the keys. A test checks F against the rows over the whole async-sync matrix. Tests that called the removed SyncPipelineOrchestrator._materialize_as_stream call StaticOutputOperatorPod._materialize_upstream; test observers take the protocol's signatures. Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/nodes/operator_node.py | 10 +- src/orcapod/core/nodes/source_node.py | 5 +- .../core/operators/static_output_pod.py | 119 +++++++++++++--- .../nodes/test_function_node_iteration.py | 8 +- .../operators/test_materialize_source_info.py | 27 +++- .../operators/test_row_built_form.py | 130 ++++++++++++++++++ .../test_error_policy_continue.py | 3 +- tests/test_pipeline/test_node_protocols.py | 48 +++---- tests/test_pipeline/test_sync_orchestrator.py | 7 +- .../test_system_tag_run_stability.py | 10 +- 10 files changed, 298 insertions(+), 69 deletions(-) create mode 100644 tests/test_core/operators/test_row_built_form.py diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index ae33d7716..34b600658 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -1690,8 +1690,7 @@ def execute( if cached_output is not None: output = StaticOutputOperatorPod._output_stream( cached_output.as_table(columns=ZERO_ROW_INPUT_COLUMNS), - cached_output.keys()[0], - stream_data_tags(cached_output), + cached_output.keys(), self, ) ctx_obs.on_node_end(node_label, node_hash) @@ -1703,14 +1702,13 @@ def execute( # The result's table, as the table built from its rows would be, without # making the rows (ITL-1347, stage 2). result_table = result_stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS) - tag_keys = result_stream.keys()[0] + keys = result_stream.keys() + tag_keys = keys[0] data_tags = stream_data_tags(result_stream) # Cache, in row order with or without rows (ITL-1131, ITL-1133). if result_table.num_rows: - kept_table = StaticOutputOperatorPod._row_built_form( - result_table, tag_keys - ) + kept_table = StaticOutputOperatorPod._row_built_form(result_table, keys) self._cached_output_stream = ArrowTableStream( kept_table, tag_columns=tag_keys, data_tags=data_tags ) diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index 1688881c8..d403eb081 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -23,7 +23,6 @@ from orcapod.config import OrcapodConfig from orcapod.core.base import TraceableBase from orcapod.core.datagrams import Data, Tag -from orcapod.core.data_tags import stream_data_tags from orcapod.core.operators.drop_nulls import _without_none # pyright: ignore[reportPrivateUsage] # DropNulls' rule for removing None from a type, shared, never copied from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.core.streams.base import ( @@ -1239,9 +1238,7 @@ def execute( # rows' (a slot's own key order can differ from its source's). rows_stream = self._rows_stream() table = rows_stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS) - result = StaticOutputOperatorPod._output_stream( - table, rows_stream.keys()[0], stream_data_tags(rows_stream), self - ) + result = StaticOutputOperatorPod._output_stream(table, rows_stream.keys(), self) if observer is not None: observer.on_node_end(node_label, node_hash) return result diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index 41007dc44..4b8fd9cc8 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -446,37 +446,114 @@ def _kept_output( return StaticOutputOperatorPod._zero_rows_in_row_order(result) @staticmethod - def _row_built_form(table: pa.Table, tag_keys: Sequence[str]) -> pa.Table: + def _row_built_columns( + table: pa.Table, keys: tuple[Sequence[str], Sequence[str]] + ) -> pa.Table: + """Return ``table``'s columns as ``_rows_to_table`` lays out the table's rows. + + Every step of F (``_row_built_form``) that each row decides on its own, so it + gives the same result on a whole table and on each slice of it: + + 1. The columns a row-built table holds: the user tags, the system tags, the data + columns that are not data-tags, and the source info of every data column (a + data-tag's included). ``table`` holds no context, meta or content-hash column + (``ZERO_ROW_INPUT_COLUMNS``). + 2. In row order: user tags in tag order, system tags in table order, then the data + columns and their source info, both in the order of the data keys. A row's + ``Data`` lists its source info in the order of its data keys, data-tags first + in tag order (``Data._ensure_source_info_table``), so a data-tag's source info + comes before the other data columns' even when the data-tag is not the first + column of ``table``. + 3. Normalized to the large types without keeping ``null``: each row's datagram + stores a ``null`` column as ``large_string`` (``Datagram._init_from_table``). + + Whether a system-tag or source-info field is nullable depends on its values over + the complete table (``_flag_by_values``), so it is not decided here. + + Args: + table: A table of user tags, system tags, data and source info. + keys: The tag keys and the data keys of the stream ``table`` belongs to + (``stream.keys()``). + + Returns: + The same arrays, selected and ordered, in their large types. + """ + from orcapod.system_constants import constants + from orcapod.utils import arrow_utils + + tag_keys, data_keys = keys + names = set(table.column_names) + tags = set(tag_keys) + system_tags = [ + n for n in table.column_names if n.startswith(constants.SYSTEM_TAG_PREFIX) + ] + data = [n for n in data_keys if n not in tags] + source_info = [ + f"{constants.SOURCE_PREFIX}{n}" + for n in data_keys + if f"{constants.SOURCE_PREFIX}{n}" in names + ] + return arrow_utils.normalize_table_to_large_types( + table.select([*tag_keys, *system_tags, *data, *source_info]) + ) + + @staticmethod + def _flag_by_values(table: pa.Table) -> pa.Table: + """Flag each system-tag and source-info field nullable only when it holds a null. + + The last step of F (``_row_built_form``), which needs the complete table. A table + built from rows takes its system tags and source-info tokens from each row's + values, so those fields are non-nullable unless a value is missing, whatever + flags the table the rows came from had (a join over inputs tied on pipeline hash + declares its system tags nullable). The table built from rows also carries no + schema metadata (``arrow_utils.hstack_tables``), so none is kept. + + Args: + table: A table of user tags, system tags, data and source info. + + Returns: + The same arrays under the new field flags, with no schema metadata. + """ + from orcapod.system_constants import constants + + prefixes = (constants.SYSTEM_TAG_PREFIX, constants.SOURCE_PREFIX) + fields = [ + field.with_nullable(table.column(i).null_count > 0) + if field.name.startswith(prefixes) + else field + for i, field in enumerate(table.schema) + ] + # Same arrays, new field flags: no cast, so no value or type can change. + return pa.Table.from_arrays(table.columns, schema=pa.schema(fields)) + + @staticmethod + def _row_built_form( + table: pa.Table, keys: tuple[Sequence[str], Sequence[str]] + ) -> pa.Table: """Return ``table`` as ``_rows_to_table`` builds it from the table's own rows. - F in the ITL-1347 spec: the same table, without making the rows. ``table`` holds - the user tags, system tags, data and source info (``ZERO_ROW_INPUT_COLUMNS``: no - context, meta or content-hash column, and each data-tag once, among the tags). - Each row's datagram normalizes its table to the large types without keeping - ``null`` (``Datagram._init_from_table``), so a ``null`` column becomes - ``large_string``. The columns then go in row order and each source-info field is - flagged nullable only when a token is null (``_as_row_built_table``). The - equality with ``_rows_to_table`` is tested over every operator, source kind and - column role (ITL-1347, L0-L2). + F in the ITL-1347 spec: the same table, without making the rows. The columns, + their order and their types are decided row by row (``_row_built_columns``), the + system-tag and source-info field flags by their values over the whole table + (``_flag_by_values``). The equality with ``_rows_to_table`` is tested over every + operator, source kind and column role (ITL-1347, L0-L2). Args: table: A table of user tags, system tags, data and source info, with rows. - tag_keys: The user tag columns, in order. + 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. """ - from orcapod.utils import arrow_utils - - return StaticOutputOperatorPod._as_row_built_table( - arrow_utils.normalize_table_to_large_types(table), tag_keys + return StaticOutputOperatorPod._flag_by_values( + StaticOutputOperatorPod._row_built_columns(table, keys) ) @staticmethod def _output_stream( table: pa.Table, - tag_keys: Sequence[str], - data_tags: Sequence[str], + keys: tuple[Sequence[str], Sequence[str]], node: StreamProtocol, ) -> StreamProtocol: """Return the stream a node hands its successors, given the table of its rows. @@ -488,8 +565,7 @@ def _output_stream( Args: table: The node's rows: user tags, system tags, data and source info. - tag_keys: The user tag columns of the rows, in order. - data_tags: The data-tags among ``tag_keys``. + 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: @@ -497,10 +573,11 @@ def _output_stream( """ 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, tag_keys), + StaticOutputOperatorPod._row_built_form(table, keys), tag_keys, - data_tags, + data_tag_names(tag_keys, data_keys), node, ) diff --git a/tests/test_core/nodes/test_function_node_iteration.py b/tests/test_core/nodes/test_function_node_iteration.py index 1364f648b..d5b79758e 100644 --- a/tests/test_core/nodes/test_function_node_iteration.py +++ b/tests/test_core/nodes/test_function_node_iteration.py @@ -9,6 +9,8 @@ from unittest.mock import patch +from typing import Any + import pyarrow as pa import pytest @@ -171,8 +173,10 @@ def sometimes_fail(x: int) -> int: from orcapod.pipeline.observer import NoOpObserver class CapturingObserver(NoOpObserver): - def on_data_crash(self, node_label, tag, data, exc): - errors.append(exc) + def on_data_crash( + self, node_label: str, tag: Any, data: Any, error: Exception + ) -> None: + errors.append(error) results = list( node.execute( diff --git a/tests/test_core/operators/test_materialize_source_info.py b/tests/test_core/operators/test_materialize_source_info.py index 190c6ddec..51368151b 100644 --- a/tests/test_core/operators/test_materialize_source_info.py +++ b/tests/test_core/operators/test_materialize_source_info.py @@ -1,7 +1,7 @@ """Every materialized row keeps its own source info (ITL-845). ``StaticOutputOperatorPod._materialize_to_stream`` and -``SyncPipelineOrchestrator._materialize_as_stream`` turn collected (Tag, Data) +``StaticOutputOperatorPod._materialize_upstream`` turn collected (Tag, Data) pairs back into a stream. They used to read row 0's source info and stamp it on every row, so rows from index 1 onward were attributed to row 0. These tests send rows with distinct source-info tokens through every path that materializes @@ -42,7 +42,6 @@ from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod from orcapod.core.sources import ArrowTableSource, DictSource from orcapod.databases import DeltaTableDatabase, InMemoryArrowDatabase -from orcapod.pipeline.sync_orchestrator import SyncPipelineOrchestrator from orcapod.protocols.database_protocols import ArrowDatabaseProtocol from orcapod.protocols.core_protocols import DataProtocol, StreamProtocol, TagProtocol from orcapod.system_constants import constants @@ -136,9 +135,9 @@ def _materialize(rows: Sequence[Row]) -> StreamProtocol: def _materialize_buffer(buf: Sequence[Row], node: Any) -> StreamProtocol: - """Call ``SyncPipelineOrchestrator._materialize_as_stream``, the helper under test.""" + """Call ``StaticOutputOperatorPod._materialize_upstream``, the helper under test.""" # Non-public on purpose: these tests are about this helper itself. - return SyncPipelineOrchestrator._materialize_as_stream(list(buf), node) # pyright: ignore[reportPrivateUsage] + return StaticOutputOperatorPod._materialize_upstream(list(buf), node) # pyright: ignore[reportPrivateUsage] def _broadcast_row_zero(monkeypatch: pytest.MonkeyPatch) -> None: @@ -155,9 +154,29 @@ def broadcasting( [(tag, data.with_source_info(**row_zero)) for tag, data in rows] ) + original_form = StaticOutputOperatorPod._row_built_form # pyright: ignore[reportPrivateUsage] + + def broadcasting_form( + table: pa.Table, keys: tuple[Sequence[str], Sequence[str]] + ) -> pa.Table: + """Stamp row 0's source info on every row of the row-built form (ITL-1347).""" + formed = original_form(table, keys) + for i, name in enumerate(formed.column_names): + if name.startswith(constants.SOURCE_PREFIX): + column = formed.column(i) + first = column.slice(0, 1).combine_chunks() + repeated = pa.concat_arrays([first] * formed.num_rows) + formed = formed.set_column(i, formed.schema.field(i), repeated) + return formed + monkeypatch.setattr( StaticOutputOperatorPod, "_rows_to_table", staticmethod(broadcasting) ) + # An operator node keeps the row-built form of its result's table, without + # making the rows (ITL-1347, stage 2). + monkeypatch.setattr( + StaticOutputOperatorPod, "_row_built_form", staticmethod(broadcasting_form) + ) def _stored_source(node: OperatorJobNode, column: str = "x") -> list[Any]: diff --git a/tests/test_core/operators/test_row_built_form.py b/tests/test_core/operators/test_row_built_form.py new file mode 100644 index 000000000..69ad9fca0 --- /dev/null +++ b/tests/test_core/operators/test_row_built_form.py @@ -0,0 +1,130 @@ +"""F, the row-built form of a table, equals the table built from its rows (ITL-1347, L0). + +``StaticOutputOperatorPod._row_built_form`` (F in the spec, +``docs/dev/specs/itl-1347-job-table-transport.md``) gives a node's output table as +``_rows_to_table`` (R) builds it from the node's rows, without making the rows. Every +operator, column role and arrangement of the async-sync matrix is checked: the column +names and their order, every field (type, nullability, field metadata), the schema +metadata, and every value (floats by their bits). + +Two properties each case covers by construction: + +- A data-tag's source info comes first among the source info, in tag order, whatever + its column's place in the table (``source_mid``, ``tag_by``): a row lists its source + info in the order of its data keys. +- A system-tag field is nullable only when a value is null: a join over inputs tied on + pipeline hash (``ref_join_3_tied``) declares its system tags nullable, a table built + from rows does not. +""" + +from __future__ import annotations + +from typing import Any + +import pyarrow as pa +import pyarrow.compute as pc +import pytest + +from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod +from orcapod.core.streams.base import ZERO_ROW_INPUT_COLUMNS +from tests.test_core.operators.test_async_sync_equivalence import ( + AFTER_OPERATOR_CASES, + CASES, + FUNCTION_POD_CASES, + Case, +) + + +_FLOAT_BITS = {16: pa.uint16(), 32: pa.uint32(), 64: pa.uint64()} + + +def _as_bits(array: Any) -> Any: # pyright: ignore[reportExplicitAny] # any Arrow array kind + """``array``'s values, with every float, at any depth, as its bit pattern. + + Arrow's ``equals`` holds NaN unequal to itself, so floats are compared as unsigned + integers of their width. Lists and structs are taken apart into their validity, their + lengths and their children's values, so the physical layout (a list's first offset, + the bytes behind a null) does not count. + """ + kind = array.type + if isinstance(array, pa.ExtensionArray): + return ("extension", _as_bits(array.storage)) + if pa.types.is_floating(kind): + filled = pc.if_else(pc.is_null(array), pa.scalar(0, kind), array) + return ("float", array.is_null(), filled.view(_FLOAT_BITS[kind.bit_width])) + if pa.types.is_map(kind): + return ( + "map", + array.is_null(), + pc.list_value_length(array), + _as_bits(array.keys), + _as_bits(array.items), + ) + if ( + pa.types.is_list(kind) + or pa.types.is_large_list(kind) + or pa.types.is_fixed_size_list(kind) + ): + return ( + "list", + array.is_null(), + pc.list_value_length(array), + _as_bits(array.flatten()), + ) + if pa.types.is_struct(kind): + return ( + "struct", + array.is_null(), + tuple(_as_bits(child) for child in array.flatten()), + ) + return ("value", array) + + +def assert_same_values(formed: pa.Table, built: pa.Table) -> None: + """Every column of ``formed`` holds the values of ``built``, floats by their bits. + + The physical layout (a list's first offset, the bytes behind a null) is not a + value and may differ. + """ + for name in built.column_names: + expected, got = built.column(name), formed.column(name) + assert got.type == expected.type, name + assert _as_bits(got.combine_chunks()) == _as_bits(expected.combine_chunks()), ( + name + ) + + +def _all_cases() -> list[Any]: + cases: list[Any] = [pytest.param(c, id=c.label) for c in CASES] + cases += list(AFTER_OPERATOR_CASES) + cases += [pytest.param(c, id=f"fp-{c.label}") for c in FUNCTION_POD_CASES] + return cases + + +@pytest.mark.parametrize("case", _all_cases()) +def test_row_built_form_equals_the_table_built_from_rows(case: Case) -> None: + """F of an operator's result table equals R of its rows, field and bit for bit.""" + result = case.make_op()(*case.make_sources()) + rows = list(result.iter_data()) + if not rows: + pytest.skip("no rows: F is defined on a table with rows") + built, _, _ = StaticOutputOperatorPod._rows_to_table(rows) # pyright: ignore[reportPrivateUsage] # R, the oracle + formed = StaticOutputOperatorPod._row_built_form( # pyright: ignore[reportPrivateUsage] # F, under test + result.as_table(columns=ZERO_ROW_INPUT_COLUMNS), result.keys() + ) + assert formed.column_names == built.column_names + assert formed.schema.equals(built.schema, check_metadata=True) + assert_same_values(formed, built) + + +def test_row_built_columns_is_the_same_on_every_slice() -> None: + """The row-by-row steps of F give the same columns on a slice as on the whole.""" + case = next(c for c in CASES if c.label == "ref_join_3_tied") + result = case.make_op()(*case.make_sources()) + table = result.as_table(columns=ZERO_ROW_INPUT_COLUMNS) + keys = result.keys() + whole = StaticOutputOperatorPod._row_built_columns(table, keys) # pyright: ignore[reportPrivateUsage] # under test + for start in range(table.num_rows): + part = StaticOutputOperatorPod._row_built_columns(table.slice(start, 1), keys) # pyright: ignore[reportPrivateUsage] # under test + assert part.schema.equals(whole.schema, check_metadata=True) + assert part.equals(whole.slice(start, 1)) diff --git a/tests/test_pipeline/test_error_policy_continue.py b/tests/test_pipeline/test_error_policy_continue.py index 31ad95450..88e99241c 100644 --- a/tests/test_pipeline/test_error_policy_continue.py +++ b/tests/test_pipeline/test_error_policy_continue.py @@ -14,6 +14,7 @@ from orcapod.core.sources import ArrowTableSource from orcapod.databases import InMemoryArrowDatabase from orcapod.pipeline.job import PipelineJob +from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod from orcapod.pipeline.sync_orchestrator import SyncPipelineOrchestrator @@ -80,7 +81,7 @@ def identity(value: int) -> int: # Don't run — buffer will be empty node = job.nodes["fn"] - stream = SyncPipelineOrchestrator._materialize_as_stream([], node) + stream = StaticOutputOperatorPod._materialize_upstream([], node) tag_schema, data_schema = stream.output_schema() # "result" is declared as int (required), must NOT become int | None diff --git a/tests/test_pipeline/test_node_protocols.py b/tests/test_pipeline/test_node_protocols.py index b59428341..23482ce18 100644 --- a/tests/test_pipeline/test_node_protocols.py +++ b/tests/test_pipeline/test_node_protocols.py @@ -3,6 +3,8 @@ from __future__ import annotations +from typing import Any + import pytest from unittest.mock import MagicMock @@ -15,6 +17,7 @@ is_operator_node, ) import pyarrow as pa +from orcapod.pipeline.observer import NoOpObserver from orcapod.core.sources import ArrowTableSource from orcapod.core.nodes.source_node import SourceJobNode from orcapod.channels import Channel @@ -312,30 +315,31 @@ def test_execute_with_observer(self): node = self._make_function_node() events = [] - class Obs: - def contextualize(self, *identity_path): + class Obs(NoOpObserver): + def contextualize(self, *identity_path: str) -> Obs: return self - def on_node_start(self, node_label, node_hash, **kwargs): + def on_node_start( + self, node_label: str, node_hash: str, tag_schema: Any = None + ) -> None: events.append(("node_start", node_label)) - def on_node_end(self, node_label, node_hash, **kwargs): + def on_node_end(self, node_label: str, node_hash: str) -> None: events.append(("node_end", node_label)) - def on_data_start(self, node_label, t, p): + def on_data_start(self, node_label: str, tag: Any, data: Any) -> None: events.append(("data_start",)) - def on_data_end(self, node_label, t, ip, op, cached): + def on_data_end( + self, + node_label: str, + tag: Any, + input_data: Any, + output_data: Any, + cached: bool, + ) -> None: events.append(("data_end", cached)) - def on_data_crash(self, node_label, t, p, exc): - pass - - def create_data_logger(self, t, p, **kwargs): - from orcapod.pipeline.observer import _NOOP_LOGGER - - return _NOOP_LOGGER - input_stream = node._input_stream result = list(node.execute(input_stream, observer=Obs()).iter_data()) @@ -472,22 +476,18 @@ def test_execute_with_observer(self): node = self._make_join_node() events = [] - class Obs: - def contextualize(self, *identity_path): + class Obs(NoOpObserver): + def contextualize(self, *identity_path: str) -> Obs: return self - def on_node_start(self, node_label, node_hash, **kwargs): + def on_node_start( + self, node_label: str, node_hash: str, tag_schema: Any = None + ) -> None: events.append(("node_start", node_label)) - def on_node_end(self, node_label, node_hash, **kwargs): + def on_node_end(self, node_label: str, node_hash: str) -> None: events.append(("node_end", node_label)) - def on_data_start(self, node_label, t, p): - pass - - def on_data_end(self, node_label, t, ip, op, cached): - pass - result = list(node.execute(*node._input_streams, observer=Obs()).iter_data()) assert len(result) == 2 assert events[0][0] == "node_start" diff --git a/tests/test_pipeline/test_sync_orchestrator.py b/tests/test_pipeline/test_sync_orchestrator.py index 4f334c709..ffd2c7907 100644 --- a/tests/test_pipeline/test_sync_orchestrator.py +++ b/tests/test_pipeline/test_sync_orchestrator.py @@ -12,6 +12,7 @@ from orcapod.core.sources import ArrowTableSource from orcapod.databases import InMemoryArrowDatabase from orcapod.pipeline import AsyncPipelineOrchestrator +from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod from orcapod.pipeline.sync_orchestrator import SyncPipelineOrchestrator from orcapod.pipeline.job import PipelineJob @@ -337,7 +338,7 @@ def test_materialized_stream_has_same_pipeline_hash(self): ) buf = list(node.iter_data()) - stream = SyncPipelineOrchestrator._materialize_as_stream(buf, node) + stream = StaticOutputOperatorPod._materialize_upstream(buf, node) assert stream.pipeline_hash() == node.pipeline_hash() def test_materialized_stream_has_same_content_hash(self): @@ -356,7 +357,7 @@ def test_materialized_stream_has_same_content_hash(self): op_node.run() buf = list(op_node.iter_data()) - stream = SyncPipelineOrchestrator._materialize_as_stream(buf, op_node) + stream = StaticOutputOperatorPod._materialize_upstream(buf, op_node) assert stream.content_hash() == op_node.content_hash() def test_materialized_stream_preserves_system_tags(self): @@ -371,7 +372,7 @@ def test_materialized_stream_preserves_system_tags(self): op_node.run() buf = list(op_node.iter_data()) - stream = SyncPipelineOrchestrator._materialize_as_stream(buf, op_node) + stream = StaticOutputOperatorPod._materialize_upstream(buf, op_node) expected_tag_schema = op_node.output_schema(columns={"system_tags": True})[0] actual_tag_schema = stream.output_schema(columns={"system_tags": True})[0] diff --git a/tests/test_pipeline/test_system_tag_run_stability.py b/tests/test_pipeline/test_system_tag_run_stability.py index 48c50565c..19a757caf 100644 --- a/tests/test_pipeline/test_system_tag_run_stability.py +++ b/tests/test_pipeline/test_system_tag_run_stability.py @@ -27,7 +27,6 @@ from orcapod.core.sources.arrow_table_source import ArrowTableSource from orcapod.databases import DeltaTableDatabase from orcapod.pipeline.job import PipelineJob -from orcapod.pipeline.sync_orchestrator import SyncPipelineOrchestrator from orcapod.side_effects import SideEffectPod, sink_pod Key = tuple[tuple[str, Any], ...] @@ -148,8 +147,8 @@ def test_operator_materialize_to_stream(self) -> None: rows = stream.as_table().to_pylist() assert rows == [{"a": 1, "b": 2, "v": 10}, {"a": 3, "b": 4, "v": 20}] - def test_orchestrator_materialize_as_stream(self) -> None: - """The orchestrator materializer emits rows in the first row's column order.""" + def test_materialize_upstream_keeps_first_row_column_order(self) -> None: + """The upstream materializer emits rows in the first row's column order.""" rows = _rows_with_swapped_tag_order() # The rebuilt stream takes the upstream's data context (ITL-1080) and, for an # upstream with no producer, its pipeline hash (ITL-1094): here a plain @@ -162,7 +161,10 @@ def test_orchestrator_materialize_as_stream(self) -> None: rows ).pipeline_hash, ) - stream = SyncPipelineOrchestrator._materialize_as_stream(rows, upstream) + stream = StaticOutputOperatorPod._materialize_upstream( + rows, + upstream, # pyright: ignore[reportArgumentType] # a stand-in upstream: the attributes the materializer reads + ) rows = stream.as_table().to_pylist() assert rows == [{"a": 1, "b": 2, "v": 10}, {"a": 3, "b": 4, "v": 20}] From 840267db0a35ff8e7a954e579ac56b11803bf17c Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 02:44:21 -0800 Subject: [PATCH 10/86] perf(pipeline): arrow_schema() lists F's columns in F's order (ITL-1360) arrow_schema() takes the columns and order of the row-built form from one statement (_row_built_names): source info in data-key order, a data-tag's first. System-tag fields, like source-info fields, are stated nullable: a table decides their flags from its values. A source node gives its rows' tag and data keys (_row_keys). Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/nodes/source_node.py | 33 +++++++++------ .../core/operators/static_output_pod.py | 40 ++++++++++++++----- src/orcapod/core/streams/base.py | 29 ++++++++------ .../protocols/core_protocols/streams.py | 13 +++--- .../test_stream_transport_equivalence.py | 27 +++++++------ 5 files changed, 88 insertions(+), 54 deletions(-) diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index d403eb081..7c999a49d 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -23,6 +23,7 @@ from orcapod.config import OrcapodConfig from orcapod.core.base import TraceableBase from orcapod.core.datagrams import Data, Tag +from orcapod.core.data_tags import data_tag_names from orcapod.core.operators.drop_nulls import _without_none # pyright: ignore[reportPrivateUsage] # DropNulls' rule for removing None from a type, shared, never copied from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.core.streams.base import ( @@ -1194,13 +1195,13 @@ def arrow_schema(self) -> pa.Schema: """The Arrow schema of the columns this stream passes between job nodes. See ``stream_arrow_schema`` (ITL-1347): never reads, computes or polls a row. - The user tags are in the order of the node's rows (``_row_tag_keys``). + The columns are in the order of the node's rows (``_row_keys``). """ - return stream_arrow_schema(self, self._row_tag_keys()) + return stream_arrow_schema(self, self._row_keys()) - def _row_tag_keys(self) -> tuple[str, ...]: - """The order of the user tags in this node's rows: its own key order.""" - return self.keys()[0] + def _row_keys(self) -> tuple[tuple[str, ...], tuple[str, ...]]: + """The tag and data keys of this node's rows: its own keys.""" + return self.keys() @property def arrow_types_declared(self) -> bool: @@ -1700,17 +1701,23 @@ def identity_structure(self) -> Any: return self._bound_source.identity_structure() return super().identity_structure() - def _row_tag_keys(self) -> tuple[str, ...]: - """The order of the user tags in this node's rows, known without reading a row. + def _row_keys(self) -> tuple[tuple[str, ...], tuple[str, ...]]: + """The tag and data keys of this node's rows, known without reading a row. - The bound source's key order; the declared order for a narrower source given - as the declared schema (``_DeclaredForm``); the slot's own when unbound. + The bound source's keys; for a narrower source given as the declared schema + (``_DeclaredForm``), the declared order with the data-tags first among the data + keys, as the stream over its table lists them (``_declared_stream``); the slot's + own when unbound. """ if self._bound_source is None: - return self.keys()[0] - if self._declared_form is not None: - return self._declared_form.tag_order - return self._bound_source.keys()[0] + return self.keys() + form = self._declared_form + if form is not None: + data_tags = data_tag_names(form.tag_order, form.data_order) + others = tuple(n for n in form.data_order if n not in data_tags) + return form.tag_order, (*data_tags, *others) + tag_keys, data_keys = self._bound_source.keys() + return tuple(tag_keys), tuple(data_keys) def _rows_stream(self) -> StreamProtocol: """The stream whose rows are this node's rows (``iter_data``). diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index 4b8fd9cc8..0e70690f3 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -478,24 +478,46 @@ def _row_built_columns( Returns: The same arrays, selected and ordered, in their large types. """ - from orcapod.system_constants import constants from orcapod.utils import arrow_utils + return arrow_utils.normalize_table_to_large_types( + table.select( + StaticOutputOperatorPod._row_built_names(table.column_names, keys) + ) + ) + + @staticmethod + 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 user tags in tag order, the system tags in the order of ``names``, the data + columns that are not data-tags, then the source info of every data column; 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. + """ + from orcapod.system_constants import constants + tag_keys, data_keys = keys - names = set(table.column_names) + present = set(names) tags = set(tag_keys) - system_tags = [ - n for n in table.column_names if n.startswith(constants.SYSTEM_TAG_PREFIX) - ] + system_tags = [n for n in names if n.startswith(constants.SYSTEM_TAG_PREFIX)] data = [n for n in data_keys if n not in tags] source_info = [ f"{constants.SOURCE_PREFIX}{n}" for n in data_keys - if f"{constants.SOURCE_PREFIX}{n}" in names + if f"{constants.SOURCE_PREFIX}{n}" in present ] - return arrow_utils.normalize_table_to_large_types( - table.select([*tag_keys, *system_tags, *data, *source_info]) - ) + return [*tag_keys, *system_tags, *data, *source_info] @staticmethod def _flag_by_values(table: pa.Table) -> pa.Table: diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py index e8dbb149b..54bbaee86 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -185,25 +185,26 @@ def typed_zero_row_input(stream: object) -> pa.Table | None: def stream_arrow_schema( - stream: object, tag_keys: Sequence[str] | None = None + stream: object, keys: tuple[Sequence[str], Sequence[str]] | None = None ) -> pa.Schema: """Return ``stream``'s declared Arrow schema: what ``arrow_schema()`` answers (ITL-1347). The schema of the columns a job node passes on, without reading, computing or polling a row: the stream's zero-row input (``typed_zero_row_input``, the Arrow types - its rows have) in row order (user tags, system tags, data, source info; - ``StaticOutputOperatorPod._in_row_order``), with no context and no meta column. A + its rows have) with the columns of F, in F's order + (``StaticOutputOperatorPod._row_built_names``: user tags, system tags, data, source + info, data and source info in data-key order), with no context and no meta column. A stream that cannot type itself without rows answers with its Python schema converted by its data context (``arrow_types_declared`` is then false). Each - source-info field is stated nullable: a table decides its flag from its tokens. A - ``null`` column keeps the zero-row ``null`` type; rows carry ``large_string`` - (ITL-1319). ITL-1307 later reads it from ``Schema`` instead, here. + system-tag and source-info field is stated nullable: a table decides its flag from + its values (F's last step). A ``null`` column keeps the zero-row ``null`` type; rows + carry ``large_string`` (ITL-1319). ITL-1307 later reads it from ``Schema`` instead, + here. Args: stream: The stream, source or node. - tag_keys: The order of the user tags in the stream's rows, when it differs from - ``keys()`` (a source slot gives its bound source's rows); default - ``keys()``. + keys: The tag and data keys of the stream's rows, when they differ from + ``keys()`` (a source slot gives its bound source's rows); default ``keys()``. Returns: The declared Arrow schema. @@ -212,8 +213,8 @@ def stream_arrow_schema( from orcapod.system_constants import constants typed = cast(StreamProtocol, stream) - if tag_keys is None: - tag_keys = typed.keys()[0] + if keys is None: + keys = typed.keys() table = typed_zero_row_input(stream) if table is None: tag_schema, data_schema = typed.output_schema( @@ -221,9 +222,11 @@ def stream_arrow_schema( ) converter = StaticOutputOperatorPod._upstream_context(typed).type_converter # pyright: ignore[reportPrivateUsage] # the one place that resolves an upstream's context table = arrow_utils.make_empty_table({**tag_schema, **data_schema}, converter) - schema = StaticOutputOperatorPod._in_row_order(table, tag_keys).schema # pyright: ignore[reportPrivateUsage] # the one statement of the row order + names = StaticOutputOperatorPod._row_built_names(table.column_names, keys) # pyright: ignore[reportPrivateUsage] # the one statement of F's columns + schema = table.select(names).schema + prefixes = (constants.SYSTEM_TAG_PREFIX, constants.SOURCE_PREFIX) for index, field in enumerate(schema): - if field.name.startswith(constants.SOURCE_PREFIX): + if field.name.startswith(prefixes): schema = schema.set(index, field.with_nullable(True)) # pyright: ignore[reportUnknownMemberType] # stubs leave Field unparametrized return schema diff --git a/src/orcapod/protocols/core_protocols/streams.py b/src/orcapod/protocols/core_protocols/streams.py index 1ebc044f8..5dff04d96 100644 --- a/src/orcapod/protocols/core_protocols/streams.py +++ b/src/orcapod/protocols/core_protocols/streams.py @@ -175,12 +175,13 @@ def arrow_schema(self) -> "pa.Schema": """The Arrow schema of the columns the stream passes between job nodes. The user tags, system tags, data and source-info columns, in row order (user - tags, system tags, data, source info), with the Arrow types, nullability and - field metadata of the rows; no context and no meta column (ITL-1347). Known - without reading, computing or polling a row. Two exceptions keep today's - bytes: source-info fields are stated nullable (a table decides their flags - from its tokens), and a ``null`` column keeps the ``null`` type a zero-row table - has (rows carry ``large_string``; ITL-1319). + tags, system tags, data, source info; data and source info in data-key order), + with the Arrow types, nullability and field metadata of the rows; no context and + no meta column (ITL-1347). Known without reading, computing or polling a row. + Two exceptions keep today's bytes: system-tag and source-info fields are stated + nullable (a table decides their flags from its values), and a ``null`` column + keeps the ``null`` type a zero-row table has (rows carry ``large_string``; + ITL-1319). Returns: The declared Arrow schema. diff --git a/tests/test_pipeline/test_stream_transport_equivalence.py b/tests/test_pipeline/test_stream_transport_equivalence.py index a6965a366..77e6c6491 100644 --- a/tests/test_pipeline/test_stream_transport_equivalence.py +++ b/tests/test_pipeline/test_stream_transport_equivalence.py @@ -233,22 +233,23 @@ def test_a_held_node_hands_on_the_stream_built_from_its_rows( def _without_exceptions(schema: pa.Schema) -> dict[str, tuple[Any, bool, Any]]: - """Fields by name as (type, nullable, metadata), the spec's two exceptions applied. + """Fields by name as (type, nullable, metadata), the spec's exceptions applied. - A source-info field's flag is decided by a table's tokens (stated nullable), and a - ``null`` column is ``large_string`` in rows (ITL-1319). Columns are matched by name: - the declared (zero-row) form can list them in another order than the rows do (a - data-tag's source info, an operator's tags under another layout), as on ``main``, - and column order is not a result (developer, 2026-11-22). + A system-tag or source-info field's flag is decided by a table's values (stated + nullable), and a ``null`` column is ``large_string`` in rows (ITL-1319). Columns are + matched by name: an operator node's declared tag order can differ from its rows' + under another physical layout, as on ``main``, and column order is not a result + (developer, 2026-11-22). """ - fields: dict[str, tuple[Any, bool, Any]] = {} - for field in schema: - kind = pa.large_string() if pa.types.is_null(field.type) else field.type - nullable = ( - True if field.name.startswith(constants.SOURCE_PREFIX) else field.nullable + prefixes = (constants.SYSTEM_TAG_PREFIX, constants.SOURCE_PREFIX) + return { + field.name: ( + pa.large_string() if pa.types.is_null(field.type) else field.type, + True if field.name.startswith(prefixes) else field.nullable, + field.metadata, ) - fields[field.name] = (kind, nullable, field.metadata) - return fields + for field in schema + } @pytest.mark.parametrize("arrangement", arrangements(MAIN)[::4], ids=lambda a: a.id) From e8d5851771ed6fae1b4d128e0ba23d56938cdcc6 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 02:44:45 -0800 Subject: [PATCH 11/86] docs(changelog): ITL-1360 fragment Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1360.md | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 changelog.d/ITL-1360.md diff --git a/changelog.d/ITL-1360.md b/changelog.d/ITL-1360.md new file mode 100644 index 000000000..5e6886038 --- /dev/null +++ b/changelog.d/ITL-1360.md @@ -0,0 +1,26 @@ +### Changed + +- **A job node's `execute` returns its output stream** — `execute` of a source, operator, + function and side-effect job node (and of the node protocols) returned the node's rows as + a list of (tag, data) pairs, and the sync orchestrator rebuilt a table from them for each + successor. It now returns the node's output stream, which the sync orchestrator hands to + every successor as it is: a source node gives its source's Arrow table, and an operator + node its result's table (REPLAY: its stored table), each in the form a table built from + the rows has, without making the rows. `OrchestratorResult.node_outputs` holds each + node's output stream, and a held node gives the stream of its held rows. Every + successor's input is unchanged: columns, types, row order, system tags, source info, + pipeline and content hashes. No hash, stored table or output changes. This replaces the + rows that carried their table (`RowsWithTable`) of the first stage. Second stage of the + table transport between job nodes (`docs/dev/specs/itl-1347-job-table-transport.md`). + (ITL-1360) + +### Added + +- **`arrow_schema()` and `arrow_types_declared` on every stream** — `StreamProtocol`, + every stream and every source node state the Arrow schema of the columns a job node + passes on (user tags, system tags, data and source info, in row order), without reading, + computing or polling a row. System-tag and source-info fields are stated nullable, since + a table decides their flags from its values; a `null` column keeps the `null` type of a + table with no rows. `arrow_types_declared` is false only for a stream that cannot type + itself without rows (an unbound slot, a `PollingSource` not yet polled), whose schema is + converted from its Python schema. (ITL-1360) From ab0bd08ba1e882d5ee709fc874efc42ecf171376 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 02:46:16 -0800 Subject: [PATCH 12/86] test(pipeline): L7 for a loaded job (ITL-1360) Co-Authored-By: Claude Opus 5.5 --- .../test_stream_transport_equivalence.py | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/tests/test_pipeline/test_stream_transport_equivalence.py b/tests/test_pipeline/test_stream_transport_equivalence.py index 77e6c6491..68f608d1c 100644 --- a/tests/test_pipeline/test_stream_transport_equivalence.py +++ b/tests/test_pipeline/test_stream_transport_equivalence.py @@ -22,8 +22,11 @@ from __future__ import annotations +import subprocess +import sys import warnings from collections.abc import Iterator +from pathlib import Path from typing import Any import pyarrow as pa @@ -268,3 +271,50 @@ def test_declared_arrow_schema_equals_the_output( output.schema ), label assert node.arrow_types_declared, label + + +def test_a_loaded_job_describes_its_nodes( + tmp_path: Path, outputs: dict[str, Any] +) -> None: + """L7 for a loaded job: each loaded node's ``arrow_schema()`` equals its output. + + A loaded node describes itself from the Arrow type texts its saved file holds + (ITL-640). The job is run and saved in another process, so that the loaded job + holds no run of this process. + """ + script = ( + "import sys, warnings\n" + "from pathlib import Path\n" + "from orcapod.databases import DeltaTableDatabase\n" + "from tests.test_core.operators.several_items import MAIN, arrangements\n" + "from tests.test_pipeline.test_stream_transport_equivalence import build_job\n" + "warnings.simplefilter('ignore')\n" + "root = Path(sys.argv[1])\n" + "job = build_job(arrangements(MAIN)[0], DeltaTableDatabase(root / 'store'))\n" + "job.run()\n" + "job.save(root / 'job.json')\n" + ) + repository = Path(__file__).resolve().parents[2] + subprocess.run( + [sys.executable, "-c", script, str(tmp_path)], check=True, cwd=repository + ) + with warnings.catch_warnings(): + warnings.simplefilter("ignore", ProvisionalHashWarning) + loaded = PipelineJob.load(tmp_path / "job.json") + # In-memory sources are not saved: bind them again. + loaded.bind( + sources={ + "s": make_source(MAIN, arrangements(MAIN)[0]), + "p": make_source(P), + "q": make_source(Q), + } + ) + loaded.run(load_only=True) + assert {"joined", "doubled", "noted", "semi", "batched"} <= set(outputs) + for label, stream in outputs.items(): + node = loaded.nodes[label] + output = stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS) + assert _without_exceptions(node.arrow_schema()) == _without_exceptions( + output.schema + ), label + assert node.arrow_types_declared, label From 3ab16e543f10c28e475dbc6525b221e742fd092e Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 02:52:50 -0800 Subject: [PATCH 13/86] refactor(streams): F's per-slice step as module functions of streams.base (ITL-1360) row_built_names and row_built_columns move, unchanged, from StaticOutputOperatorPod to core/streams/base.py, so a stream applies them without importing the operators. StaticOutputOperatorPod and stream_arrow_schema call them. Co-Authored-By: Claude Opus 5.5 --- .../core/operators/static_output_pod.py | 81 +------------------ src/orcapod/core/streams/base.py | 78 +++++++++++++++++- .../operators/test_row_built_form.py | 6 +- 3 files changed, 81 insertions(+), 84 deletions(-) diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index 0e70690f3..c46ec8786 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -33,6 +33,7 @@ short_stream_repr, typed_zero_row_input, typed_zero_row_table, + row_built_columns, ) from orcapod.core.streams.view import ( STALE_NOTE, @@ -445,80 +446,6 @@ def _kept_output( return StaticOutputOperatorPod._materialize_to_stream(rows) return StaticOutputOperatorPod._zero_rows_in_row_order(result) - @staticmethod - def _row_built_columns( - table: pa.Table, keys: tuple[Sequence[str], Sequence[str]] - ) -> pa.Table: - """Return ``table``'s columns as ``_rows_to_table`` lays out the table's rows. - - Every step of F (``_row_built_form``) that each row decides on its own, so it - gives the same result on a whole table and on each slice of it: - - 1. The columns a row-built table holds: the user tags, the system tags, the data - columns that are not data-tags, and the source info of every data column (a - data-tag's included). ``table`` holds no context, meta or content-hash column - (``ZERO_ROW_INPUT_COLUMNS``). - 2. In row order: user tags in tag order, system tags in table order, then the data - columns and their source info, both in the order of the data keys. A row's - ``Data`` lists its source info in the order of its data keys, data-tags first - in tag order (``Data._ensure_source_info_table``), so a data-tag's source info - comes before the other data columns' even when the data-tag is not the first - column of ``table``. - 3. Normalized to the large types without keeping ``null``: each row's datagram - stores a ``null`` column as ``large_string`` (``Datagram._init_from_table``). - - Whether a system-tag or source-info field is nullable depends on its values over - the complete table (``_flag_by_values``), so it is not decided here. - - Args: - table: A table of user tags, system tags, data and source info. - keys: The tag keys and the data keys of the stream ``table`` belongs to - (``stream.keys()``). - - Returns: - The same arrays, selected and ordered, in their large types. - """ - from orcapod.utils import arrow_utils - - return arrow_utils.normalize_table_to_large_types( - table.select( - StaticOutputOperatorPod._row_built_names(table.column_names, keys) - ) - ) - - @staticmethod - 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 user tags in tag order, the system tags in the order of ``names``, the data - columns that are not data-tags, then the source info of every data column; 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. - """ - from orcapod.system_constants import constants - - 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)] - 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] - @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. @@ -555,7 +482,7 @@ def _row_built_form( """Return ``table`` as ``_rows_to_table`` builds it from the table's own rows. F in the ITL-1347 spec: the same table, without making the rows. The columns, - their order and their types are decided row by row (``_row_built_columns``), the + their order and their types are decided row by row (``streams.base.row_built_columns``), the system-tag and source-info field flags by their values over the whole table (``_flag_by_values``). The equality with ``_rows_to_table`` is tested over every operator, source kind and column role (ITL-1347, L0-L2). @@ -568,9 +495,7 @@ def _row_built_form( Returns: The table ``_rows_to_table`` would build from its rows. """ - return StaticOutputOperatorPod._flag_by_values( - StaticOutputOperatorPod._row_built_columns(table, keys) - ) + return StaticOutputOperatorPod._flag_by_values(row_built_columns(table, keys)) @staticmethod def _output_stream( diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py index 54bbaee86..d97faf142 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,78 @@ 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``). + + 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 arrays, selected and ordered, in their large types. + """ + return arrow_utils.normalize_table_to_large_types( + table.select(row_built_names(table.column_names, keys)) + ) + + +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, then the source info of every data column; 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)] + 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 stream_arrow_schema( stream: object, keys: tuple[Sequence[str], Sequence[str]] | None = None ) -> pa.Schema: @@ -192,7 +265,7 @@ def stream_arrow_schema( The schema of the columns a job node passes on, without reading, computing or polling a row: the stream's zero-row input (``typed_zero_row_input``, the Arrow types its rows have) with the columns of F, in F's order - (``StaticOutputOperatorPod._row_built_names``: user tags, system tags, data, source + (``row_built_names``: user tags, system tags, data, source info, data and source info in data-key order), with no context and no meta column. A stream that cannot type itself without rows answers with its Python schema converted by its data context (``arrow_types_declared`` is then false). Each @@ -210,7 +283,6 @@ def stream_arrow_schema( The declared Arrow schema. """ from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod - from orcapod.system_constants import constants typed = cast(StreamProtocol, stream) if keys is None: @@ -222,7 +294,7 @@ def stream_arrow_schema( ) converter = StaticOutputOperatorPod._upstream_context(typed).type_converter # pyright: ignore[reportPrivateUsage] # the one place that resolves an upstream's context table = arrow_utils.make_empty_table({**tag_schema, **data_schema}, converter) - names = StaticOutputOperatorPod._row_built_names(table.column_names, keys) # pyright: ignore[reportPrivateUsage] # the one statement of F's columns + names = row_built_names(table.column_names, keys) schema = table.select(names).schema prefixes = (constants.SYSTEM_TAG_PREFIX, constants.SOURCE_PREFIX) for index, field in enumerate(schema): diff --git a/tests/test_core/operators/test_row_built_form.py b/tests/test_core/operators/test_row_built_form.py index 69ad9fca0..b421bd843 100644 --- a/tests/test_core/operators/test_row_built_form.py +++ b/tests/test_core/operators/test_row_built_form.py @@ -26,7 +26,7 @@ import pytest from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod -from orcapod.core.streams.base import ZERO_ROW_INPUT_COLUMNS +from orcapod.core.streams.base import ZERO_ROW_INPUT_COLUMNS, row_built_columns from tests.test_core.operators.test_async_sync_equivalence import ( AFTER_OPERATOR_CASES, CASES, @@ -123,8 +123,8 @@ def test_row_built_columns_is_the_same_on_every_slice() -> None: result = case.make_op()(*case.make_sources()) table = result.as_table(columns=ZERO_ROW_INPUT_COLUMNS) keys = result.keys() - whole = StaticOutputOperatorPod._row_built_columns(table, keys) # pyright: ignore[reportPrivateUsage] # under test + whole = row_built_columns(table, keys) for start in range(table.num_rows): - part = StaticOutputOperatorPod._row_built_columns(table.slice(start, 1), keys) # pyright: ignore[reportPrivateUsage] # under test + part = row_built_columns(table.slice(start, 1), keys) assert part.schema.equals(whole.schema, check_metadata=True) assert part.equals(whole.slice(start, 1)) From a425c84fb562e5365ce862fa929810fbf0de4d20 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 03:05:23 -0800 Subject: [PATCH 14/86] fix(pipeline): F equals the rows for narrower sources and raw streams (ITL-1360) A narrower source's output is F of its table given as the declared schema (_DeclaredForm.apply), with the declared keys: its data-tags keep their source info, as each declared row does. F leaves meta (__) columns and their source info out, and gives system-tag and source-info fields the form a row builds from their values (row_built_provenance: no field metadata; a source-info list of nullable 'item' fields), so F equals the rows on raw streams too (Codex on PR #483, findings 5 and 7). arrow_schema() states the same fields. The pre-ITL-845 test hook is defined once, and patches F as well. Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/nodes/source_node.py | 48 +++++------ src/orcapod/core/streams/base.py | 85 +++++++++++++++++-- .../operators/test_row_built_form.py | 63 ++++++++++++++ .../test_tag_table_source_info.py | 23 +---- 4 files changed, 169 insertions(+), 50 deletions(-) diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index 7c999a49d..7644f1703 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -1187,9 +1187,15 @@ def iter_data(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: """Yield ``(tag, data)`` pairs, or raise if data is unavailable.""" ... - def _rows_stream(self) -> "StreamProtocol": - """The stream whose rows are this node's rows (``iter_data``): this node itself.""" - return cast("StreamProtocol", self) + def _rows_table(self) -> tuple[pa.Table, tuple[tuple[str, ...], tuple[str, ...]]]: + """The table of this node's rows (``iter_data``) and the rows' keys. + + Here this node's own table (``ZERO_ROW_INPUT_COLUMNS``) and keys. + """ + stream = cast("StreamProtocol", self) + tag_keys, data_keys = stream.keys() + table = stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS) + return table, (tuple(tag_keys), tuple(data_keys)) def arrow_schema(self) -> pa.Schema: """The Arrow schema of the columns this stream passes between job nodes. @@ -1235,11 +1241,10 @@ def execute( node_hash = self.content_hash().to_string() if observer is not None: observer.on_node_start(node_label, node_hash) - # The stream this node's rows come from: its table and its tag order are the - # rows' (a slot's own key order can differ from its source's). - rows_stream = self._rows_stream() - table = rows_stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS) - result = StaticOutputOperatorPod._output_stream(table, rows_stream.keys(), self) + # The table and keys of this node's rows: a slot's own key order can differ + # from its source's. + table, keys = self._rows_table() + result = StaticOutputOperatorPod._output_stream(table, keys, self) if observer is not None: observer.on_node_end(node_label, node_hash) return result @@ -1719,12 +1724,14 @@ def _row_keys(self) -> tuple[tuple[str, ...], tuple[str, ...]]: tag_keys, data_keys = self._bound_source.keys() return tuple(tag_keys), tuple(data_keys) - def _rows_stream(self) -> StreamProtocol: - """The stream whose rows are this node's rows (``iter_data``). + def _rows_table(self) -> tuple[pa.Table, tuple[tuple[str, ...], tuple[str, ...]]]: + """The table of this node's rows (``iter_data``) and the rows' keys. - The bound source, or, for a narrower source, the source's table given as the - declared schema (``_declared_stream``), whose rows are those ``_declared_rows`` - gives one by one. + The bound source's table and keys; for a narrower source, the source's table + given as the declared schema (``_DeclaredForm.apply``, which serves a whole + table as it serves each row in ``_declared_rows``) with the declared keys + (``_row_keys``). Its data-tags keep their source info, as each declared row + does. Raises: UnboundSourceError: When no concrete source is attached. @@ -1734,18 +1741,11 @@ def _rows_stream(self) -> StreamProtocol: f"SourceJobNode '{self._name}' has no concrete source bound. " "Call job.bind(sources={'': source}) before running." ) + table = self._bound_source.as_table(columns=ZERO_ROW_INPUT_COLUMNS) if self._declared_form is None: - return self._bound_source - table = self._bound_source.as_table( - columns={ - "meta": True, - "source": True, - "system_tags": True, - "context": True, - "sort_by_tags": False, - } - ) - return self._declared_stream(self._bound_source, self._declared_form, table) + tag_keys, data_keys = self._bound_source.keys() + return table, (tuple(tag_keys), tuple(data_keys)) + return self._declared_form.apply(table), self._row_keys() def iter_data(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: """Delegate to concrete source, or raise if unbound. diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py index d97faf142..3610e05ac 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -205,9 +205,13 @@ def row_built_columns( 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. + 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. @@ -215,10 +219,75 @@ def row_built_columns( (``stream.keys()``). Returns: - The same arrays, selected and ordered, in their large types. + The same values, selected and ordered, in their large types. """ - return arrow_utils.normalize_table_to_large_types( - table.select(row_built_names(table.column_names, keys)) + 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, table.schema.metadata) ) @@ -232,7 +301,8 @@ def row_built_names( 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, then the source info of every data column; 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``). @@ -248,6 +318,9 @@ def row_built_names( 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}" @@ -295,7 +368,7 @@ def stream_arrow_schema( converter = StaticOutputOperatorPod._upstream_context(typed).type_converter # pyright: ignore[reportPrivateUsage] # the one place that resolves an upstream's context table = arrow_utils.make_empty_table({**tag_schema, **data_schema}, converter) names = row_built_names(table.column_names, keys) - schema = table.select(names).schema + schema = row_built_provenance(table.select(names)).schema prefixes = (constants.SYSTEM_TAG_PREFIX, constants.SOURCE_PREFIX) for index, field in enumerate(schema): if field.name.startswith(prefixes): diff --git a/tests/test_core/operators/test_row_built_form.py b/tests/test_core/operators/test_row_built_form.py index b421bd843..2c6cc5e9a 100644 --- a/tests/test_core/operators/test_row_built_form.py +++ b/tests/test_core/operators/test_row_built_form.py @@ -25,8 +25,11 @@ import pyarrow.compute as pc import pytest +from orcapod.core.operators import DropNulls, SelectDataColumns from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod +from orcapod.core.streams import ArrowTableStream from orcapod.core.streams.base import ZERO_ROW_INPUT_COLUMNS, row_built_columns +from orcapod.system_constants import constants from tests.test_core.operators.test_async_sync_equivalence import ( AFTER_OPERATOR_CASES, CASES, @@ -128,3 +131,63 @@ def test_row_built_columns_is_the_same_on_every_slice() -> None: part = row_built_columns(table.slice(start, 1), keys) assert part.schema.equals(whole.schema, check_metadata=True) assert part.equals(whole.slice(start, 1)) + + +def _raw_stream() -> ArrowTableStream: + """A raw stream with provenance fields no source writes (Codex on PR #483). + + A system-tag field with field metadata, a list-valued source-info column whose item + field is named ``member`` and non-nullable, and a meta (``__``) data column with + its own source info. + """ + system_tag = f"{constants.SYSTEM_TAG_PREFIX}source_id::abc" + member = pa.field("member", pa.large_string(), nullable=False) + table = pa.table( + { + "k": pa.array([1, 2], pa.int64()), + "j": pa.array(["a", "b"], pa.large_string()), + system_tag: pa.array(["s1", "s2"], pa.large_string()), + "x": pa.array([1.0, float("nan")]), + "z": pa.array([3, None], pa.int8()), + "__note": pa.array(["a", "b"]), + "_source_x": pa.array([["a", "b"], ["c"]], pa.large_list(member)), + "_source_z": pa.array(["t1", "t2"], pa.large_string()), + "_source___note": pa.array(["n1", "n2"], pa.large_string()), + } + ) + position = table.schema.get_field_index(system_tag) + schema = table.schema.set( + position, table.schema.field(position).with_metadata({b"m": b"v"}) + ) + return ArrowTableStream( + pa.Table.from_arrays(table.columns, schema=schema), tag_columns=["k", "j"] + ) + + +@pytest.mark.parametrize( + "make", + [ + pytest.param(_raw_stream, id="raw"), + pytest.param( + lambda: SelectDataColumns(["z", "x"])(_raw_stream()), id="select-z-x" + ), + pytest.param(lambda: DropNulls(["j", "k"])(_raw_stream()), id="drop-nulls"), + ], +) +def test_row_built_form_of_a_raw_stream(make: Any) -> None: + """F equals R on a raw stream: provenance fields as rows build them, no meta. + + R takes a system tag and a source-info token from its values, so the system-tag + field has no metadata and a list token's item field is nullable ``item``; a meta + column is not data, so neither it nor its source info is passed on. + """ + stream = make() + built, _, _ = StaticOutputOperatorPod._rows_to_table(list(stream.iter_data())) # pyright: ignore[reportPrivateUsage] # R, the oracle + formed = StaticOutputOperatorPod._row_built_form( # pyright: ignore[reportPrivateUsage] # F, under test + stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS), stream.keys() + ) + assert "__note" not in formed.column_names + assert "_source___note" not in formed.column_names + assert formed.column_names == built.column_names + assert formed.schema.equals(built.schema, check_metadata=True) + assert_same_values(formed, built) diff --git a/tests/test_pipeline/test_tag_table_source_info.py b/tests/test_pipeline/test_tag_table_source_info.py index 094b66702..048b4d47d 100644 --- a/tests/test_pipeline/test_tag_table_source_info.py +++ b/tests/test_pipeline/test_tag_table_source_info.py @@ -32,12 +32,13 @@ from orcapod.core.function_pod import FunctionPod from orcapod.core.nodes.function_node import FunctionJobNode from orcapod.core.operators import SelectDataColumns -from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod +from tests.test_core.operators.test_materialize_source_info import ( + _broadcast_row_zero, # pyright: ignore[reportPrivateUsage] # the one re-creation of the pre-fix broadcast +) from orcapod.core.sources import ArrowTableSource from orcapod.databases import DeltaTableDatabase, InMemoryArrowDatabase from orcapod.pipeline import AsyncPipelineOrchestrator from orcapod.pipeline.job import PipelineJob -from orcapod.protocols.core_protocols import DataProtocol, TagProtocol from orcapod.protocols.database_protocols import ArrowDatabaseProtocol from orcapod.system_constants import PIPELINE_DB_SCHEMA_VERSION @@ -160,24 +161,6 @@ def _output_source_info_tokens(job: PipelineJob, label: str, column: str) -> lis return [data.source_info()[column] for _, data in rows] -def _broadcast_row_zero(monkeypatch: pytest.MonkeyPatch) -> None: - """Make every materialization stamp row 0's source info, as before ITL-845.""" - original = StaticOutputOperatorPod._rows_to_table # pyright: ignore[reportPrivateUsage] # re-creating the pre-fix behaviour - - def broadcasting( - rows: Sequence[tuple[TagProtocol, DataProtocol]], - ) -> tuple[pa.Table, tuple[str, ...], tuple[str, ...]]: - """Stamp row 0's source info on every row, then build the table.""" - row_zero = rows[0][1].source_info() - return original( - [(tag, data.with_source_info(**row_zero)) for tag, data in rows] - ) - - monkeypatch.setattr( - StaticOutputOperatorPod, "_rows_to_table", staticmethod(broadcasting) - ) - - @pytest.mark.parametrize("orchestrator", ["sync", "async"]) class TestFreshRunStoresPerRowSourceInfo: def test_source_into_function(self, orchestrator: str): From f06846308aa92a195fd403813a04ba3ec38997c9 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 03:06:16 -0800 Subject: [PATCH 15/86] fix(side_effects): cast the node to StreamProtocol through object (ITL-1360) Co-Authored-By: Claude Opus 5.5 --- src/orcapod/side_effects.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/orcapod/side_effects.py b/src/orcapod/side_effects.py index 95f4c922e..81a834fc2 100644 --- a/src/orcapod/side_effects.py +++ b/src/orcapod/side_effects.py @@ -1278,8 +1278,12 @@ def _output_stream( """ from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod + # A side-effect job node is a stream (``StreamBase``) that the checker cannot + # match against the protocol through its mixins. + # A side-effect job node is a ``StreamBase``; the checker cannot match its + # mixin members against ``StreamProtocol``, so the cast goes through object. return StaticOutputOperatorPod._materialize_upstream( - rows, cast("StreamProtocol", self) + rows, cast("StreamProtocol", cast(object, self)) ) def _deliver_rows( From 5b39d5bb50d26d1209033d04ccbb53a7870811c6 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 03:14:56 -0800 Subject: [PATCH 16/86] fix(function_node): a type disagreement fails the run with as_table's error (ITL-1360) A function node builds its output stream before its run commits. Rows that cannot make one table (rows of a store written before ITL-928 next to rows computed now) fail the run at the node with the InputValidationError its as_table() raises, naming the column and both types, never a bare ArrowInvalid. Named difference e9 in the spec (provisional, coordinator decision 2026-11-22, pending the developer). Stage 1's changelog text is folded into the ITL-1360 fragment: one fragment for the PR that carries both stages. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1347.md | 11 -------- changelog.d/ITL-1360.md | 14 +++++++--- .../dev/specs/itl-1347-job-table-transport.md | 7 +++-- src/orcapod/core/nodes/function_node.py | 18 ++++++++++-- .../test_function_node_arrow_types.py | 28 +++++++++++++++---- 5 files changed, 53 insertions(+), 25 deletions(-) delete mode 100644 changelog.d/ITL-1347.md diff --git a/changelog.d/ITL-1347.md b/changelog.d/ITL-1347.md deleted file mode 100644 index 1396fe682..000000000 --- a/changelog.d/ITL-1347.md +++ /dev/null @@ -1,11 +0,0 @@ -### Changed - -- **A job run hands an operator node's kept table to the nodes after it** — an operator node - in a job keeps its run's output as a table built from its rows, and the sync orchestrator - then built the same table again from the same rows for each node that reads it. The node - now returns its rows carrying the table it built (`RowsWithTable`), and the orchestrator - wraps that table for each successor (`_materialize_upstream`). The table is built once - instead of once per successor plus once to keep. Every successor's input is the same: - columns, types, row order, system tags, source info, pipeline and content hashes. No hash, - stored table or output changes. First stage of the table transport between job nodes - (`docs/dev/specs/itl-1347-job-table-transport.md`). (ITL-1347) diff --git a/changelog.d/ITL-1360.md b/changelog.d/ITL-1360.md index 5e6886038..0d7f58069 100644 --- a/changelog.d/ITL-1360.md +++ b/changelog.d/ITL-1360.md @@ -9,10 +9,16 @@ the rows has, without making the rows. `OrchestratorResult.node_outputs` holds each node's output stream, and a held node gives the stream of its held rows. Every successor's input is unchanged: columns, types, row order, system tags, source info, - pipeline and content hashes. No hash, stored table or output changes. This replaces the - rows that carried their table (`RowsWithTable`) of the first stage. Second stage of the - table transport between job nodes (`docs/dev/specs/itl-1347-job-table-transport.md`). - (ITL-1360) + pipeline and content hashes. No hash, stored table or output changes. An operator node's + table is built once, for what it keeps and for every successor, instead of once to keep + and once per successor. The first two stages of the table transport between job nodes + (`docs/dev/specs/itl-1347-job-table-transport.md`). (ITL-1347, ITL-1360) +- **A function node whose rows disagree on a column's type fails the run** — rows read from + a store written before ITL-928 (a `uint32` tag read back as `int32`) and rows computed now + cannot make one table. The run now fails at the node with the `InputValidationError` + naming the column and both types that the node's `as_table()` raised before; a node with a + successor used to fail with a bare `ArrowInvalid`, and one without completed the run. Such + a store must be rebuilt. (ITL-1360) ### Added diff --git a/docs/dev/specs/itl-1347-job-table-transport.md b/docs/dev/specs/itl-1347-job-table-transport.md index ce0097d17..c517ae50f 100644 --- a/docs/dev/specs/itl-1347-job-table-transport.md +++ b/docs/dev/specs/itl-1347-job-table-transport.md @@ -509,9 +509,9 @@ with the developer's approval, given row by row. Each row gets its own test: it row, by name. The developer has accepted some behaviours of `main` that are not listed as rows; they are kept as `main` has them, and documented below. -**No row changes a sync-path result.** On the sync path the branch equals `main` byte for -byte. Stages 1–4 hold this by construction and by L0–L5, and a lemma that fails stops its -stage. +**No row changes a sync-path result, except e9** (provisional, pending the developer). On +the sync path the branch equals `main` byte for byte. Stages 1–4 hold this by construction +and by L0–L5, and a lemma that fails stops its stage. | # | What differs | On `main` today | On the branch | Why `main` is wrong (bug, reproducer) | Approval needed | |---|---|---|---|---|---| @@ -521,6 +521,7 @@ stage. | e6 | Async values that depend on an earlier validation of the same operator object | `SemiJoin._validated_common_keys` and `Index._element_arrow_type_fallback` hold the last validation's values (ITL-858, section 1.2). One operator object applied to two streams can use the other stream's keys or fallback type | Read from each input's description, with no state | The ITL-858 finding; filed as ITL-1358. Reproducer: one `SemiJoin` instance validated on stream B, then run async over stream A with other keys. To be confirmed in stage 5 | ITL-1358 (filed); fixed with stage 5 once a reproducer confirms it | | e7 | What a consumer does after its producer failed (async, failure path) | The producer closes its output in `finally`, so a consumer sees a normal end and may finish, and a `LOG` operator node may store, a partial result before the task group cancels it | Readers raise `UpstreamFailedError` at the failure point instead of seeing a normal end, so no consumer finishes, or stores its result, as if its input were complete. Batches a consumer processed before the failure are still processed, and a streaming node may already have passed them on or a function node stored results for them, as on `main`; there is no rollback. A barrier operator never computes over a partial input. The run raises the producer's own error, as today | A candidate race, to be confirmed with a reproducer in stage 5: a `fail_fast` function node raising on row 3 of 6, feeding a `Select` node in `LOG` mode; check the operator cache after the failed run. If `main` never stores in practice, this row is no difference | filed by the developer only once a test reproduces it | | e8 | Meta columns of an async side-effect node's rows | An async side-effect node passes on and holds the rows it receives as they are, so a computed row keeps its `__computed` meta column (from the cached function pod), and the node's `as_table(all_info=True)` shows it. On sync, its input is rebuilt from rows (`_rows_to_table` drops meta), so the column is absent | Async drops input meta columns as sync does. With table transport this follows from the transport columns, which hold no meta column | A `main` bug: the async and sync paths give the node different columns. Found by the stage 0 harness on `job-speed` 0e15d0db, which does not change side-effect nodes; the stage 0 differential checks it on pinned `main`. Reproducer: a function node (with a result store) feeding a `tap_pod`, async against sync, comparing the side-effect node's `as_table(all_info=True)` columns | approved (developer, 2026-11-22) | +| e9 | A sync function node whose output rows disagree on a column's Arrow type | A node with no successor completes the run; its `as_table()` raises `InputValidationError` ("Function node 'double': Rows disagree on the Arrow type of column 'k': int32 and uint32"). A node with a successor fails the run with a bare pyarrow `ArrowInvalid`, raised where the successor's input is rebuilt | The node builds its output stream when it runs (stage 2), so the run fails at the node, before it commits, with the `InputValidationError` `as_table()` raises (same type and message), with or without a successor; the node then holds no run. What is stored equals `main`'s: the row computed before the disagreement could be seen stays written, as after any failure | Not a `main` bug to fix: a consequence of building the output stream in `execute`, and for a node with a successor an improvement (`main`'s `ArrowInvalid` names nothing). It arises only from a store written before ITL-928, whose cached rows give a `uint32` tag back as `int32`; such a store must be rebuilt. Reproducer: `tests/test_core/function_pod/test_function_node_arrow_types.py::test_new_rows_over_a_store_written_before_the_fix_raise_naming_the_column` (leaf and with successor) | provisional, coordinator decision 2026-11-22, pending developer | **Resolved: refusals after rows have flowed (was c, question 9).** The developer's `Rejoin` rule (ITL-1355) removes every data-dependent refusal from `Rejoin`: it checks only what its diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 3b2b2e1da..21075cb8f 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -2467,7 +2467,14 @@ def _output_stream( """ from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod - return StaticOutputOperatorPod._materialize_upstream(rows, self) + try: + return StaticOutputOperatorPod._materialize_upstream(rows, self) + except pa.ArrowInvalid: + # Rows that disagree on a column's Arrow type (cached rows of a store + # written before ITL-928): raise what ``as_table`` raises for them, naming + # the node, the column and both types (ITL-1360, e9). + self._table_from_pairs(rows) + raise def execute_data( self, @@ -2649,6 +2656,13 @@ def execute( self._row_processed, ctx_obs, node_label, node_hash ) + # The output stream, built before the run is committed: rows that cannot + # make one table fail the run (ITL-1360, e9). + try: + result_stream = self._output_stream(output) + except InputValidationError: + ctx_obs.on_node_end(node_label, node_hash) + raise self._commit_or_end_node( self._commit_at_node_end, ctx_obs, node_label, node_hash ) @@ -2668,7 +2682,7 @@ def execute( self.clear_cache() raise - return self._output_stream(output) + return result_stream def _empty_data_cache_hit( self, tag: TagProtocol, data: EmptyData, base_entry_id: bytes diff --git a/tests/test_core/function_pod/test_function_node_arrow_types.py b/tests/test_core/function_pod/test_function_node_arrow_types.py index 6886d8715..99e389c77 100644 --- a/tests/test_core/function_pod/test_function_node_arrow_types.py +++ b/tests/test_core/function_pod/test_function_node_arrow_types.py @@ -291,27 +291,45 @@ def _as_written_before_the_fix(root: pathlib.Path) -> None: ) +@pytest.mark.parametrize("chained", [False, True], ids=["leaf", "with_successor"]) def test_new_rows_over_a_store_written_before_the_fix_raise_naming_the_column( - tmp_path: pathlib.Path, + chained: bool, tmp_path: pathlib.Path ) -> None: """Rows of one node never make a column of a type none of them has. A Delta database written before ITL-928 gives a ``uint32`` tag back as ``int32``: rows served from it and rows computed now disagree, and the node says so instead of picking a type. Such a database must be rebuilt. + + The run fails at the node, with the error ``as_table`` raises for such rows (main + raised it only on a later read of a node with no successor, and a bare + ``ArrowInvalid`` in the run of one with a successor; ITL-1360, difference e9). The + node then holds no run. """ - _build(DeltaTableDatabase(tmp_path), _source_table("uint32").slice(0, 2)).run() + _build( + DeltaTableDatabase(tmp_path), + _source_table("uint32").slice(0, 2), + chained=chained, + ).run() _as_written_before_the_fix(tmp_path) - job = _build(DeltaTableDatabase(tmp_path), _source_table("uint32")) - job.run() + job = _build(DeltaTableDatabase(tmp_path), _source_table("uint32"), chained=chained) with pytest.raises(InputValidationError) as raised: - job.nodes["double"].as_table() + job.run() message = str(raised.value) + assert message.startswith("Function node 'double': ") assert "'k'" in message assert "int32" in message assert "uint32" in message + # A run that raised defines no rows. + assert job.nodes["double"].as_table().num_rows == 0 + # What is stored is what main stores: the row computed before the disagreement + # could be seen stays written, as after any failure, next to the two old rows. + stored = _build(DeltaTableDatabase(tmp_path), _source_table("uint32")) + records = stored.nodes["double"].get_all_records() + assert records is not None + assert records.num_rows == 3 def test_new_rows_over_a_store_written_after_the_fix_keep_the_tag_type( From 49a81d6a8c70d803c3f0d319f36b8c72c14611cd Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 03:23:17 -0800 Subject: [PATCH 17/86] fix(streams): type the schema metadata row_built_provenance keeps (ITL-1360) Co-Authored-By: Claude Opus 5.5 --- docs/dev/specs/itl-1347-job-table-transport.md | 2 +- src/orcapod/core/streams/base.py | 5 ++++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/docs/dev/specs/itl-1347-job-table-transport.md b/docs/dev/specs/itl-1347-job-table-transport.md index c517ae50f..af8b392bf 100644 --- a/docs/dev/specs/itl-1347-job-table-transport.md +++ b/docs/dev/specs/itl-1347-job-table-transport.md @@ -521,7 +521,7 @@ and by L0–L5, and a lemma that fails stops its stage. | e6 | Async values that depend on an earlier validation of the same operator object | `SemiJoin._validated_common_keys` and `Index._element_arrow_type_fallback` hold the last validation's values (ITL-858, section 1.2). One operator object applied to two streams can use the other stream's keys or fallback type | Read from each input's description, with no state | The ITL-858 finding; filed as ITL-1358. Reproducer: one `SemiJoin` instance validated on stream B, then run async over stream A with other keys. To be confirmed in stage 5 | ITL-1358 (filed); fixed with stage 5 once a reproducer confirms it | | e7 | What a consumer does after its producer failed (async, failure path) | The producer closes its output in `finally`, so a consumer sees a normal end and may finish, and a `LOG` operator node may store, a partial result before the task group cancels it | Readers raise `UpstreamFailedError` at the failure point instead of seeing a normal end, so no consumer finishes, or stores its result, as if its input were complete. Batches a consumer processed before the failure are still processed, and a streaming node may already have passed them on or a function node stored results for them, as on `main`; there is no rollback. A barrier operator never computes over a partial input. The run raises the producer's own error, as today | A candidate race, to be confirmed with a reproducer in stage 5: a `fail_fast` function node raising on row 3 of 6, feeding a `Select` node in `LOG` mode; check the operator cache after the failed run. If `main` never stores in practice, this row is no difference | filed by the developer only once a test reproduces it | | e8 | Meta columns of an async side-effect node's rows | An async side-effect node passes on and holds the rows it receives as they are, so a computed row keeps its `__computed` meta column (from the cached function pod), and the node's `as_table(all_info=True)` shows it. On sync, its input is rebuilt from rows (`_rows_to_table` drops meta), so the column is absent | Async drops input meta columns as sync does. With table transport this follows from the transport columns, which hold no meta column | A `main` bug: the async and sync paths give the node different columns. Found by the stage 0 harness on `job-speed` 0e15d0db, which does not change side-effect nodes; the stage 0 differential checks it on pinned `main`. Reproducer: a function node (with a result store) feeding a `tap_pod`, async against sync, comparing the side-effect node's `as_table(all_info=True)` columns | approved (developer, 2026-11-22) | -| e9 | A sync function node whose output rows disagree on a column's Arrow type | A node with no successor completes the run; its `as_table()` raises `InputValidationError` ("Function node 'double': Rows disagree on the Arrow type of column 'k': int32 and uint32"). A node with a successor fails the run with a bare pyarrow `ArrowInvalid`, raised where the successor's input is rebuilt | The node builds its output stream when it runs (stage 2), so the run fails at the node, before it commits, with the `InputValidationError` `as_table()` raises (same type and message), with or without a successor; the node then holds no run. What is stored equals `main`'s: the row computed before the disagreement could be seen stays written, as after any failure | Not a `main` bug to fix: a consequence of building the output stream in `execute`, and for a node with a successor an improvement (`main`'s `ArrowInvalid` names nothing). It arises only from a store written before ITL-928, whose cached rows give a `uint32` tag back as `int32`; such a store must be rebuilt. Reproducer: `tests/test_core/function_pod/test_function_node_arrow_types.py::test_new_rows_over_a_store_written_before_the_fix_raise_naming_the_column` (leaf and with successor) | provisional, coordinator decision 2026-11-22, pending developer | +| e9 | A sync function node whose output rows disagree on a column's Arrow type | A node with no successor completes the run; its `as_table()` raises `InputValidationError` ("Function node 'double': Rows disagree on the Arrow type of column 'k': int32 and uint32"). A node with a successor fails the run with a bare pyarrow `ArrowInvalid`, raised where the successor's input is rebuilt | The node builds its output stream when it runs (stage 2), so the run fails at the node, before it commits, with the `InputValidationError` `as_table()` raises (same type and message), with or without a successor; the node then holds no run. What is stored equals `main`'s: the row computed before the disagreement could be seen is stored, as on `main` (2 stored rows before the run, 3 after, on both) | Not a `main` bug to fix: a consequence of building the output stream in `execute`, and for a node with a successor an improvement (`main`'s `ArrowInvalid` names nothing). It arises only from a store written before ITL-928, whose cached rows give a `uint32` tag back as `int32`; such a store must be rebuilt. Reproducer: `tests/test_core/function_pod/test_function_node_arrow_types.py::test_new_rows_over_a_store_written_before_the_fix_raise_naming_the_column` (leaf and with successor) | provisional, coordinator decision 2026-11-22, pending developer | **Resolved: refusals after rows have flowed (was c, question 9).** The developer's `Rejoin` rule (ITL-1355) removes every data-dependent refusal from `Rejoin`: it checks only what its diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py index b7a68d0f4..38ade1cb1 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -287,7 +287,10 @@ def row_built_provenance(table: pa.Table) -> pa.Table: if not changed: return table return pa.Table.from_arrays( - columns, schema=pa.schema(fields, table.schema.metadata) + columns, + schema=pa.schema( + fields, cast("dict[bytes | str, bytes | str] | None", table.schema.metadata) + ), ) From fbf8aff26cf487532300d3957b5d4861ee41a97a Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 03:35:43 -0800 Subject: [PATCH 18/86] fix(function_node): a failed write is reported before e9 (ITL-1360) The output stream is built after the run's writes are committed, so a store write error keeps precedence as on main. Co-Authored-By: Claude Opus 5.5 --- docs/dev/specs/itl-1347-job-table-transport.md | 2 +- src/orcapod/core/nodes/function_node.py | 11 ++++++----- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/docs/dev/specs/itl-1347-job-table-transport.md b/docs/dev/specs/itl-1347-job-table-transport.md index af8b392bf..08d27f4ba 100644 --- a/docs/dev/specs/itl-1347-job-table-transport.md +++ b/docs/dev/specs/itl-1347-job-table-transport.md @@ -521,7 +521,7 @@ and by L0–L5, and a lemma that fails stops its stage. | e6 | Async values that depend on an earlier validation of the same operator object | `SemiJoin._validated_common_keys` and `Index._element_arrow_type_fallback` hold the last validation's values (ITL-858, section 1.2). One operator object applied to two streams can use the other stream's keys or fallback type | Read from each input's description, with no state | The ITL-858 finding; filed as ITL-1358. Reproducer: one `SemiJoin` instance validated on stream B, then run async over stream A with other keys. To be confirmed in stage 5 | ITL-1358 (filed); fixed with stage 5 once a reproducer confirms it | | e7 | What a consumer does after its producer failed (async, failure path) | The producer closes its output in `finally`, so a consumer sees a normal end and may finish, and a `LOG` operator node may store, a partial result before the task group cancels it | Readers raise `UpstreamFailedError` at the failure point instead of seeing a normal end, so no consumer finishes, or stores its result, as if its input were complete. Batches a consumer processed before the failure are still processed, and a streaming node may already have passed them on or a function node stored results for them, as on `main`; there is no rollback. A barrier operator never computes over a partial input. The run raises the producer's own error, as today | A candidate race, to be confirmed with a reproducer in stage 5: a `fail_fast` function node raising on row 3 of 6, feeding a `Select` node in `LOG` mode; check the operator cache after the failed run. If `main` never stores in practice, this row is no difference | filed by the developer only once a test reproduces it | | e8 | Meta columns of an async side-effect node's rows | An async side-effect node passes on and holds the rows it receives as they are, so a computed row keeps its `__computed` meta column (from the cached function pod), and the node's `as_table(all_info=True)` shows it. On sync, its input is rebuilt from rows (`_rows_to_table` drops meta), so the column is absent | Async drops input meta columns as sync does. With table transport this follows from the transport columns, which hold no meta column | A `main` bug: the async and sync paths give the node different columns. Found by the stage 0 harness on `job-speed` 0e15d0db, which does not change side-effect nodes; the stage 0 differential checks it on pinned `main`. Reproducer: a function node (with a result store) feeding a `tap_pod`, async against sync, comparing the side-effect node's `as_table(all_info=True)` columns | approved (developer, 2026-11-22) | -| e9 | A sync function node whose output rows disagree on a column's Arrow type | A node with no successor completes the run; its `as_table()` raises `InputValidationError` ("Function node 'double': Rows disagree on the Arrow type of column 'k': int32 and uint32"). A node with a successor fails the run with a bare pyarrow `ArrowInvalid`, raised where the successor's input is rebuilt | The node builds its output stream when it runs (stage 2), so the run fails at the node, before it commits, with the `InputValidationError` `as_table()` raises (same type and message), with or without a successor; the node then holds no run. What is stored equals `main`'s: the row computed before the disagreement could be seen is stored, as on `main` (2 stored rows before the run, 3 after, on both) | Not a `main` bug to fix: a consequence of building the output stream in `execute`, and for a node with a successor an improvement (`main`'s `ArrowInvalid` names nothing). It arises only from a store written before ITL-928, whose cached rows give a `uint32` tag back as `int32`; such a store must be rebuilt. Reproducer: `tests/test_core/function_pod/test_function_node_arrow_types.py::test_new_rows_over_a_store_written_before_the_fix_raise_naming_the_column` (leaf and with successor) | provisional, coordinator decision 2026-11-22, pending developer | +| e9 | A sync function node whose output rows disagree on a column's Arrow type | A node with no successor completes the run; its `as_table()` raises `InputValidationError` ("Function node 'double': Rows disagree on the Arrow type of column 'k': int32 and uint32"). A node with a successor fails the run with a bare pyarrow `ArrowInvalid`, raised where the successor's input is rebuilt | The node builds its output stream when it runs (stage 2), so the run fails at the node, once its writes are committed (a failed write is still reported first, as on `main`) and before the node takes the run, with the `InputValidationError` `as_table()` raises (same type and message), with or without a successor; the node then holds no run. What is stored equals `main`'s: the row computed before the disagreement could be seen is stored, as on `main` (2 stored rows before the run, 3 after, on both) | Not a `main` bug to fix: a consequence of building the output stream in `execute`, and for a node with a successor an improvement (`main`'s `ArrowInvalid` names nothing). It arises only from a store written before ITL-928, whose cached rows give a `uint32` tag back as `int32`; such a store must be rebuilt. Reproducer: `tests/test_core/function_pod/test_function_node_arrow_types.py::test_new_rows_over_a_store_written_before_the_fix_raise_naming_the_column` (leaf and with successor) | provisional, coordinator decision 2026-11-22, pending developer | **Resolved: refusals after rows have flowed (was c, question 9).** The developer's `Rejoin` rule (ITL-1355) removes every data-dependent refusal from `Rejoin`: it checks only what its diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 21075cb8f..60d6dc365 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -2656,16 +2656,17 @@ def execute( self._row_processed, ctx_obs, node_label, node_hash ) - # The output stream, built before the run is committed: rows that cannot - # make one table fail the run (ITL-1360, e9). + self._commit_or_end_node( + self._commit_at_node_end, ctx_obs, node_label, node_hash + ) + # The output stream, built once the run is committed (a failed write is + # reported first, as on main) and before the node takes the run: rows that + # cannot make one table fail the run (ITL-1360, e9). try: result_stream = self._output_stream(output) except InputValidationError: ctx_obs.on_node_end(node_label, node_hash) raise - self._commit_or_end_node( - self._commit_at_node_end, ctx_obs, node_label, node_hash - ) # The node's rows are those of this run's inputs, whatever else it caches. self._set_run_rows(emitted_entry_ids, failed=failed_rows) # Mark this node as freshly computed before the observer hears the end, so From 1740220e16b4d1eb1ec288017d17fcd087abe19a Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 03:37:42 -0800 Subject: [PATCH 19/86] fix(databases): import pyarrow directly in databases/utils.py (ITL-1349) Main's #471 (ITL-1334) reads pyarrow through LazyModule there; on this branch a module that import orcapod loads is imported directly (tests/test_utils/test_lazy_module_use.py). Co-Authored-By: Claude Fable 5.2 --- src/orcapod/databases/utils.py | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/src/orcapod/databases/utils.py b/src/orcapod/databases/utils.py index 8cd9f0018..9e71f6647 100644 --- a/src/orcapod/databases/utils.py +++ b/src/orcapod/databases/utils.py @@ -6,15 +6,12 @@ from collections.abc import Iterable, Mapping from typing import TYPE_CHECKING, Any, cast +import pyarrow as pa + from orcapod.utils import arrow_utils -from orcapod.utils.lazy_module import LazyModule if TYPE_CHECKING: - import pyarrow as pa - from orcapod.protocols.database_protocols import TableCommittingDatabaseProtocol -else: - pa = LazyModule("pyarrow") def coerce_record_id(record_id: str | bytes) -> bytes: From 6947e719386557ca4521b5f966f422f0be8957a1 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 03:38:45 -0800 Subject: [PATCH 20/86] docs(operators): state F's domain; pin its one exception and the bind refusal (ITL-1360) Co-Authored-By: Claude Opus 5.5 --- .../core/operators/static_output_pod.py | 18 ++++- .../operators/test_row_built_form.py | 75 +++++++++++++++++++ 2 files changed, 89 insertions(+), 4 deletions(-) diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index c46ec8786..8f5e5afe8 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -482,10 +482,20 @@ def _row_built_form( """Return ``table`` as ``_rows_to_table`` builds it from the table's own rows. F in the ITL-1347 spec: the same table, without making the rows. The columns, - their order and their types are decided row by row (``streams.base.row_built_columns``), the - system-tag and source-info field flags by their values over the whole table - (``_flag_by_values``). The equality with ``_rows_to_table`` is tested over every - operator, source kind and column role (ITL-1347, L0-L2). + their order and their types are decided row by row + (``streams.base.row_built_columns``), the system-tag and source-info field flags + by their values over the whole table (``_flag_by_values``). The equality with + ``_rows_to_table`` is tested over every operator, source kind and column role + (ITL-1347, L0-L2). + + Its domain: F equals ``_rows_to_table`` for every stream whose source-info tokens + are strings or non-empty lists of tokens, which is every stream a source or an + operator makes (a token list has one element per member of a batch, group or + merge). The one exception is a hand-built raw ``ArrowTableStream`` whose + source-info column is a list type holding only empty lists: a row types its + tokens from their values, so ``_rows_to_table`` loses the list levels the + empty lists do not show, while F keeps the column's type. Such a stream reaches + a job only when bound to a slot with a copied source-id and record-id pair. Args: table: A table of user tags, system tags, data and source info, with rows. diff --git a/tests/test_core/operators/test_row_built_form.py b/tests/test_core/operators/test_row_built_form.py index 2c6cc5e9a..0fba4c92d 100644 --- a/tests/test_core/operators/test_row_built_form.py +++ b/tests/test_core/operators/test_row_built_form.py @@ -191,3 +191,78 @@ def test_row_built_form_of_a_raw_stream(make: Any) -> None: assert formed.column_names == built.column_names assert formed.schema.equals(built.schema, check_metadata=True) assert_same_values(formed, built) + + +def _source_table() -> pa.Table: + """A source's table with its system tags and source info (one tag, one data).""" + from orcapod.sources import DictSource + + source = DictSource( + [{"k": 1, "x": 1}, {"k": 2, "x": 2}], + tag_columns=["k"], + tag_only_columns=True, + source_id="s", + ) + return source.as_table(columns={"source": True, "system_tags": True}) + + +def test_empty_source_info_lists_are_outside_the_domain_of_the_row_built_form() -> None: + """F's one named exception: source-info tokens that are only empty lists. + + No source or operator makes an empty token list. A hand-built raw stream can: + ``_rows_to_table`` types the tokens from their values (one list level, the empty + lists show no more), while F keeps the column's two levels. Pinned so that a + change to either side is seen (the refusal of such a stream is the developer's + decision). + """ + table = _source_table() + position = table.schema.get_field_index("_source_x") + empty = pa.array([[], []], pa.large_list(pa.large_list(pa.large_string()))) + stream = ArrowTableStream( + table.set_column(position, "_source_x", empty), tag_columns=["k"] + ) + built, _, _ = StaticOutputOperatorPod._rows_to_table(list(stream.iter_data())) # pyright: ignore[reportPrivateUsage] # R, the oracle + formed = StaticOutputOperatorPod._row_built_form( # pyright: ignore[reportPrivateUsage] # F, under test + stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS), stream.keys() + ) + assert built.schema.field("_source_x").type == pa.large_list(pa.large_string()) + assert formed.schema.field("_source_x").type == pa.large_list( + pa.large_list(pa.large_string()) + ) + + +def test_a_source_with_a_nullable_system_tag_is_not_bound() -> None: + """A system-tag field with a null never reaches a job: a slot refuses the source. + + So F never meets one; ``_rows_to_table`` could not build its rows (two rows would + give the field two nullability flags). + """ + from orcapod import PipelineJob + from orcapod.databases import InMemoryArrowDatabase + from orcapod.errors import SourceSpecMismatchError + from orcapod.sources import DictSource + + source = DictSource( + [{"k": 1, "x": 1}, {"k": 2, "x": 2}], + tag_columns=["k"], + tag_only_columns=True, + source_id="s", + ) + job = PipelineJob(name="nullable_system_tag", database=InMemoryArrowDatabase()) + with job: + source.select_data_columns(["x"], label="selected") + table = _source_table() + record_id = next( + name + for name in table.column_names + if name.startswith(constants.SYSTEM_TAG_PREFIX) and "record_id" in name + ) + position = table.schema.get_field_index(record_id) + with_null = table.set_column( + position, + pa.field(record_id, pa.large_string(), nullable=True), + pa.array(["row_0", None], pa.large_string()), + ) + slot = next(label for label in job.nodes if label != "selected") + with pytest.raises(SourceSpecMismatchError, match="record_id"): + job.bind(sources={slot: ArrowTableStream(with_null, tag_columns=["k"])}) From 0b344c930064621da8de8dbd6c2f3d1cb9e8607b Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 04:55:50 -0800 Subject: [PATCH 21/86] feat(channels): channels of Arrow record batches and the operators' record-batch form (ITL-1362, part 1) (#483) * wip(channels): input and output channels of Arrow record batches; operators' record-batch form (ITL-1362) Work in progress, part 1 of ITL-1347 stage 5 (the channel layer); not wired into nodes or orchestrators, so no result of the branch changes. - channels.py: InputChannel and OutputChannel (Arrow record batches), the conversions channel_from_stream and stream_from_batches, transport_columns; UpstreamFailedError in orcapod.errors; StreamBase.open_channel() and the StreamProtocol member. - Operators: StaticOutputOperatorPod.async_execute_batches (barrier by to_stream(); ROW_BY_ROW operators per record batch through static_process; Batch(n) by arrival), beside the row async_execute until the wiring. - Tests: tests/test_channels/test_record_batch_channels.py (29 pass) and tests/test_core/operators/test_record_batch_execution.py (691 pass, 27 fail: every failure is the Python-schema assertion of the zero-row test, not yet investigated). Not done: basedpyright, changelog fragment, CLAUDE.md, the 27 zero-row cases, review of the interim names. See the handoff note. Co-Authored-By: Claude Fable 5.2 * test(channels): compare Arrow types of a zero-row result; StreamProtocol.open_channel waits for part 2 (ITL-1362) Co-Authored-By: Claude Opus 5.5 * docs(channels): rule for record-batch channels and ROW_BY_ROW; fail() is seen at once (ITL-1362) Co-Authored-By: Claude Opus 5.5 * test(channels): type fixes in the record-batch tests (ITL-1362) Co-Authored-By: Claude Opus 5.5 * refactor(channels): record-batch channels in core/record_batch_channels, conversions beside the operator helpers, protocols in channels.py; no import cycle (ITL-1362) StreamBase.open_channel is deferred to part 2: any form of it is an import cycle (base -> channel classes -> ArrowTableStream -> base). channel_from_stream(stream) opens a channel. Co-Authored-By: Claude Opus 5.5 * refactor(channels): F from stage 2 (_row_built_columns, _flag_by_values, _output_stream); record-batch protocols in protocols/core_protocols, channels.py as on job-speed (ITL-1362) Co-Authored-By: Claude Opus 5.5 * fix(channels): Codex round 1 on #483: in-flight send ends with the channel, strict send check, partial input never a stream, cancelled read closes, Batch takes differing provenance flags (ITL-1362) - send waiting for room raises at once on close (ChannelClosed) or fail (the failure) and publishes nothing more; a zero-row batch is checked and not kept - send takes exactly the description's types in their large variants, the field metadata of user fields, and only nulls where the description is null (transport_schema keeps the null type) - collect()/to_stream() of a reader closed before its producer completed raise; a cancelled receive() closes the reader; close() unregisters it - Batch opens provenance flags of arrived batches before concatenating (with_open_provenance_flags, as stream_from_batches) and holds no zero-row batch - tests: the job-sync oracle of barrier operators; AddTags -> Batch arrivals; F's provenance schema and raw meta columns as strict xfails, TODO(ITL-1360) Co-Authored-By: Claude Opus 5.5 * refactor(channels): stage 2's F verbatim (row_built_columns, row_built_names, row_built_provenance in streams/base.py; _flag_by_values, _row_built_form, _output_stream); F's two tests pass (ITL-1362) transport_schema follows stage 2's stream_arrow_schema recipe (still interim, TODO(ITL-1360)). row_built_provenance casts the schema metadata for the pyarrow stubs (the one line that differs from stage 2's b58decad, to be adopted there). Co-Authored-By: Claude Opus 5.5 * fix(channels): Codex round 2 on #483: a close during a send fails the channel, an early-closed input fails every loop, metadata at every depth, nulls on values sent, names without Arrow types (ITL-1362) - close() while a send waits for a reader's room fails the channel (the send raises ChannelClosed; readers' next read raises UpstreamFailedError caused by ChannelClosed): readers never complete normally with different inputs - an input reader closed before its producer completed raises ChannelClosed from receive() and from iteration, so no loop (row by row, Batch by arrival, barrier) takes it for the end; the operator fails its output - send compares user-field metadata at every depth; provenance fields carry none at any depth - the null-only rule reads the logical values of the slice sent (validity- and slice-aware; maps through their entries) - without Arrow types in the description, a batch whose names contradict the stream's keys is refused - tests: all of the above; F's two raw-stream edges as strict xfails (TODO(ITL-1360)) Co-Authored-By: Claude Opus 5.5 * fix(channels): types of the null check and its tests (ITL-1362) Co-Authored-By: Claude Opus 5.5 * test(channels): pin F's two documented exceptions instead of xfails; stage 2's _row_built_form docstring verbatim (ITL-1362) Co-Authored-By: Claude Opus 5.5 * fix(channels): CodeRabbit round on #483: one send at a time, any abort of a partly delivered send fails the channel, schema set only by a batch that passes, the output closed in the protected block, every input closed (ITL-1362) - non-retained sends are serialized, so every reader gets one batch order - a send aborted after it reached one reader (close, fail, cancellation, any error) fails the channel; one aborted before any reader leaves it usable - an inferred schema is saved only after the batch passes the check - operators close their output inside the protected block and close every input even when one close fails (close_inputs) - RecordBatchInput.to_stream documents that it needs an unread channel - docstrings for the channel feeds, readers and helpers; the per-arrival test synchronizes on each input's result instead of sleeping and reading _sent - ITL-1365 (DropTagColumns' predicted tag order) pinned as a strict xfail Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Edgar Y. Walker <> Co-authored-by: Claude Fable 5.2 Co-authored-by: Edgar Y. Walker --- .zed/rules | 16 + CLAUDE.md | 16 + src/orcapod/core/operators/add_tags.py | 2 + src/orcapod/core/operators/batch.py | 63 +- .../core/operators/column_selection.py | 10 + src/orcapod/core/operators/drop_nulls.py | 2 + src/orcapod/core/operators/index.py | 2 + src/orcapod/core/operators/mappers.py | 6 + src/orcapod/core/operators/pick.py | 2 + .../core/operators/static_output_pod.py | 347 ++++- src/orcapod/core/record_batch_channels.py | 667 ++++++++++ src/orcapod/core/streams/base.py | 149 +++ src/orcapod/errors.py | 11 + .../core_protocols/record_batch_channels.py | 86 ++ .../test_record_batch_channels.py | 1151 +++++++++++++++++ .../operators/test_record_batch_execution.py | 731 +++++++++++ 16 files changed, 3259 insertions(+), 2 deletions(-) create mode 100644 src/orcapod/core/record_batch_channels.py create mode 100644 src/orcapod/protocols/core_protocols/record_batch_channels.py create mode 100644 tests/test_channels/test_record_batch_channels.py create mode 100644 tests/test_core/operators/test_record_batch_execution.py diff --git a/.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) From 404038504e9dfd0f1b4d819451e4727785fccfca Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 04:57:01 -0800 Subject: [PATCH 22/86] perf(function_node): entry ids from the input table's slices (ITL-1361, stage 3a) FunctionJobNode._input_entries takes each row's entry-id preimage from slices of an Arrow-backed input stream: the tag side with its system tags (flags by value, as a row has them) and the hash of the data columns, equal to the data datagram's content hash. Other stream kinds take the row path. L3 lemma test over the async-sync matrix, handed on and raw. Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/nodes/function_node.py | 91 +++++++++++++++--- ...test_function_node_entry_ids_from_table.py | 94 +++++++++++++++++++ 2 files changed, 173 insertions(+), 12 deletions(-) create mode 100644 tests/test_core/nodes/test_function_node_entry_ids_from_table.py diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 60d6dc365..8d0f0fc01 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -181,11 +181,31 @@ def _build_record_id_preimage( A single-row ``pa.Table`` with system-tag columns and ``INPUT_DATA_HASH_COL`` (``large_binary``, the prefixed digest). """ - return tag.as_table(columns={"system_tags": True}).append_column( + return _with_input_data_hash( + tag.as_table(columns={"system_tags": True}), input_data + ) + + +def _with_input_data_hash( + tag_table: "pa.Table", input_data: "DataProtocol | ContentHash" +) -> "pa.Table": + """Return a row's tag table (with system tags) with its input data hash appended. + + The one statement of the entry-id preimage's last column (``_build_record_id_preimage``). + + Args: + tag_table: The row's one-row tag table, system tags included. + input_data: The row's data datagram, or its content hash. + + Returns: + The preimage: ``tag_table`` and ``INPUT_DATA_HASH_COL`` (``large_binary``). + """ + data_hash = ( + input_data if isinstance(input_data, ContentHash) else input_data.content_hash() + ) + return tag_table.append_column( constants.INPUT_DATA_HASH_COL, - pa.array( - [input_data.content_hash().to_prefixed_digest()], type=pa.large_binary() - ), + pa.array([data_hash.to_prefixed_digest()], type=pa.large_binary()), ) @@ -2039,10 +2059,7 @@ def _execute_load_only( ) tag_schema = input_stream.output_schema(columns={"system_tags": True})[0] ctx_obs.on_node_start(node_label, node_hash, tag_schema=tag_schema) - inputs = [ - (tag, data, self.compute_base_entry_id(tag, data)) - for tag, data in input_stream.iter_data() - ] + inputs = self._input_entries(input_stream) _ = self.get_cached_results(base_entry_ids=[eid for _, _, eid in inputs]) for tag, data, entry_id in inputs: entry = self._stored_entry(entry_id) @@ -2574,10 +2591,7 @@ def execute( try: # Collect upstream entries and resolve base_entry_ids (stable across # recomputation) - upstream_entries: list[tuple[TagProtocol, DataProtocol, bytes]] = [ - (tag, data, self.compute_base_entry_id(tag, data)) - for tag, data in input_stream.iter_data() - ] + upstream_entries = self._input_entries(input_stream) base_entry_ids = [eid for _, _, eid in upstream_entries] # Hot-load any already-computed results from DB into _cached_output_datas. @@ -3044,6 +3058,59 @@ def compute_base_entry_id( self._build_entry_id_preimage(tag, input_data) ).to_prefixed_digest() + def _input_entries( + self, input_stream: StreamProtocol + ) -> list[tuple[TagProtocol, DataProtocol, bytes]]: + """Return ``input_stream``'s rows, each with its base entry id. + + The id is ``compute_base_entry_id`` of the row. For a stream over an Arrow + table (every stream a job hands a node, ITL-1347), each row's preimage is + taken from slices of the stream's table instead of tables built from the + row's values: the tag side is its user tags and system tags, the system-tag + field flags set by their values as a row's are (``_flag_by_values``), and the + input data hash is ``hash_table`` of its data columns, which is the data + datagram's content hash (``Datagram.identity_structure``). The same ids, + without building each row's tables (ITL-1361). + + Args: + input_stream: The node's input. + + Returns: + ``(tag, data, base entry id)`` for each row, in the stream's order. + """ + from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod + + rows = list(input_stream.iter_data()) + if not rows or not isinstance(input_stream, ArrowTableStream): + return [ + (tag, data, self.compute_base_entry_id(tag, data)) for tag, data in rows + ] + tag_keys, data_keys = input_stream.keys() + table = input_stream.as_table(columns={"system_tags": True}) + system_tags = [ + name + for name in table.column_names + if name.startswith(constants.SYSTEM_TAG_PREFIX) + ] + tag_side = StaticOutputOperatorPod._flag_by_values( # pyright: ignore[reportPrivateUsage] # F's flags, as a row has them + table.select([*tag_keys, *system_tags]) + ) + data_side = table.select(list(data_keys)) + hasher = self.data_context.arrow_hasher + return [ + ( + tag, + data, + hasher.hash_table( + _with_input_data_hash( + tag_side.slice(index, 1), + hasher.hash_table(data_side.slice(index, 1)), + ) + ).to_prefixed_digest(), + ) + for index, (tag, data) in enumerate(rows) + ] + def compute_pipeline_entry_id( self, tag: TagProtocol, diff --git a/tests/test_core/nodes/test_function_node_entry_ids_from_table.py b/tests/test_core/nodes/test_function_node_entry_ids_from_table.py new file mode 100644 index 000000000..2f9020ecd --- /dev/null +++ b/tests/test_core/nodes/test_function_node_entry_ids_from_table.py @@ -0,0 +1,94 @@ +"""A function node's entry ids taken from its input table equal the rows' (ITL-1361, L3). + +``FunctionJobNode._input_entries`` computes each input row's base entry id from slices of +the input stream's Arrow table (the tag side with its system tags, and the hash of the +data columns) instead of from tables built from each row's datagrams +(``compute_base_entry_id``). The ids decide which stored results a run finds, so they must +be equal for every input a job can hand a node: every operator, column role and +arrangement of the async-sync matrix, behind an operator and behind a function pod, in +the form a job hands it on (``_materialize_upstream``). +""" + +from __future__ import annotations + +from typing import Any + +import pytest + +from orcapod.core.data_function import PythonDataFunction +from orcapod.core.data_tags import stream_data_tags +from orcapod.core.function_pod import FunctionPod +from orcapod.core.nodes.function_node import FunctionJobNode +from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod +from orcapod.core.streams import ArrowTableStream +from orcapod.databases import InMemoryArrowDatabase +from tests.test_core.operators.test_async_sync_equivalence import ( + AFTER_OPERATOR_CASES, + CASES, + FUNCTION_POD_CASES, + Case, + source_a, +) + + +def _constant(i8: int) -> int: + return i8 + + +def _node() -> FunctionJobNode: + """A function node; only its data context's hasher is used by the ids.""" + pod = FunctionPod(PythonDataFunction(_constant, output_keys="c")) + return FunctionJobNode( + pod, + source_a().select_data_columns(["i8"]), + pipeline_database=InMemoryArrowDatabase(), + ) + + +def _all_cases() -> list[Any]: + cases: list[Any] = [pytest.param(c, id=c.label) for c in CASES] + cases += list(AFTER_OPERATOR_CASES) + cases += [pytest.param(c, id=f"fp-{c.label}") for c in FUNCTION_POD_CASES] + return cases + + +@pytest.mark.parametrize("handed_on", [True, False], ids=["handed_on", "raw"]) +@pytest.mark.parametrize("case", _all_cases()) +def test_entry_ids_from_the_table_equal_the_rows(case: Case, handed_on: bool) -> None: + """Every row's id from table slices equals ``compute_base_entry_id`` of its row. + + For the stream a job hands a node (``handed_on``), and for a raw stream over the + operator result's own table, whose system-tag fields may be declared nullable (a + join over inputs tied on pipeline hash). + """ + result = case.make_op()(*case.make_sources()) + rows = list(result.iter_data()) + if not rows: + pytest.skip("no rows") + stream = ( + StaticOutputOperatorPod._materialize_upstream(rows, result) # pyright: ignore[reportPrivateUsage] # the stream a job hands a node + if handed_on + else ArrowTableStream( + result.as_table(columns={"system_tags": True, "source": True}), + tag_columns=result.keys()[0], + data_tags=stream_data_tags(result), + ) + ) + node = _node() + entries = node._input_entries(stream) # pyright: ignore[reportPrivateUsage] # under test + expected = [ + node.compute_base_entry_id(tag, data) for tag, data in stream.iter_data() + ] + assert [entry_id for _, _, entry_id in entries] == expected + + +def test_entry_ids_of_a_stream_that_is_not_a_table_stream_take_the_row_path() -> None: + """Any other stream kind (here a source) is read row by row, as before.""" + stream = source_a() + assert not isinstance(stream, ArrowTableStream) + node = _node() + entries = node._input_entries(stream) # pyright: ignore[reportPrivateUsage] # under test + expected = [ + node.compute_base_entry_id(tag, data) for tag, data in stream.iter_data() + ] + assert [entry_id for _, _, entry_id in entries] == expected From 335c4bc8e5c6a1992d35a1350f2c2f43a296e5f1 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 05:01:09 -0800 Subject: [PATCH 23/86] fix(pipeline): F types source info from its tokens, over the whole table (ITL-1360) Codex on PR #485, finding 1. A row types each source-info token from its value (arrow_utils.source_info_arrow_type); F now does the same on the complete table (_type_source_info_by_values, beside _flag_by_values), so a list of None or of empty lists is kept and stored as the rows give it. Tokens of two types (a list on one row, None on another) cannot make one table: F raises SourceInfoTypesDisagree and the node builds its rows, which raise main's ArrowInvalid; a source node ends its node first, as on main. The domain exception of F is gone; its test is an equality test. Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/nodes/operator_node.py | 29 +++- src/orcapod/core/nodes/source_node.py | 15 +- .../core/operators/static_output_pod.py | 129 +++++++++++++-- .../operators/test_row_built_form.py | 155 ++++++++++++++++-- 4 files changed, 286 insertions(+), 42 deletions(-) diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index 34b600658..36904bf59 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -38,7 +38,10 @@ ) from orcapod.channels import Channel, ChannelClosed, ReadableChannel, WritableChannel from orcapod.config import OrcapodConfig -from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod +from orcapod.core.operators.static_output_pod import ( + SourceInfoTypesDisagree, + StaticOutputOperatorPod, +) from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.core.streams.base import ( ZERO_ROW_INPUT_COLUMNS, @@ -1688,11 +1691,16 @@ def execute( # Check REPLAY cache first cached_output = self.get_cached_output() if cached_output is not None: - output = StaticOutputOperatorPod._output_stream( - cached_output.as_table(columns=ZERO_ROW_INPUT_COLUMNS), - cached_output.keys(), - self, - ) + try: + output = StaticOutputOperatorPod._output_stream( + cached_output.as_table(columns=ZERO_ROW_INPUT_COLUMNS), + cached_output.keys(), + self, + ) + except SourceInfoTypesDisagree as error: + StaticOutputOperatorPod._raise_as_rows_do( + cached_output.iter_data(), error + ) ctx_obs.on_node_end(node_label, node_hash) return output @@ -1708,7 +1716,14 @@ def execute( # Cache, in row order with or without rows (ITL-1131, ITL-1133). if result_table.num_rows: - kept_table = StaticOutputOperatorPod._row_built_form(result_table, keys) + try: + kept_table = StaticOutputOperatorPod._row_built_form( + result_table, keys + ) + except SourceInfoTypesDisagree as error: + StaticOutputOperatorPod._raise_as_rows_do( + result_stream.iter_data(), error + ) self._cached_output_stream = ArrowTableStream( kept_table, tag_columns=tag_keys, data_tags=data_tags ) diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index 7644f1703..7da04da1c 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -1235,7 +1235,10 @@ def execute( Raises: UnboundSourceError: When no concrete data is available. """ - from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod + from orcapod.core.operators.static_output_pod import ( + SourceInfoTypesDisagree, + StaticOutputOperatorPod, + ) node_label = self.label node_hash = self.content_hash().to_string() @@ -1244,7 +1247,15 @@ def execute( # The table and keys of this node's rows: a slot's own key order can differ # from its source's. table, keys = self._rows_table() - result = StaticOutputOperatorPod._output_stream(table, keys, self) + try: + result = StaticOutputOperatorPod._output_stream(table, keys, self) + except SourceInfoTypesDisagree as error: + # Rows whose source-info tokens cannot make one table: the node has read + # its rows, and the run fails where its rows are handed on, raising what + # their concatenation raises. + if observer is not None: + observer.on_node_end(node_label, node_hash) + StaticOutputOperatorPod._raise_as_rows_do(self.iter_data(), error) if observer is not None: observer.on_node_end(node_label, node_hash) return result diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index ac7717972..077cf4817 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -3,9 +3,9 @@ import asyncio import logging from abc import abstractmethod -from collections.abc import Collection, Iterator, Sequence +from collections.abc import Collection, Iterable, Iterator, Sequence from datetime import datetime, timezone -from typing import TYPE_CHECKING, Any, ClassVar, cast +from typing import TYPE_CHECKING, Any, ClassVar, NoReturn, cast import pyarrow as pa @@ -66,6 +66,15 @@ from orcapod.protocols.hashing_protocols import SemanticHasherProtocol +class SourceInfoTypesDisagree(ValueError): + """Two rows give one source-info column different types (``_row_built_form``). + + A table built from such rows cannot be concatenated: the caller builds the rows + (``StaticOutputOperatorPod._rows_to_table``), which raises the error a table built + from rows raises, so the run fails as it does when rows are handed on. + """ + + class StaticOutputOperatorPod(TraceableBase): """Abstract base class for pods whose core logic yields a static output stream. @@ -493,27 +502,81 @@ def _flag_by_values(table: pa.Table) -> pa.Table: # 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 _type_source_info_by_values(table: pa.Table) -> pa.Table: + """Type each source-info column from its tokens, as the rows of a table built from rows do. + + A step of F (``_row_built_form``) on the complete table, beside + ``_flag_by_values``. A row's ``Data`` types each source-info token from its + value (``arrow_utils.source_info_arrow_type``, the one rule): a string or + ``None`` as ``large_string``, a list as ``large_list`` of its first informative + element's type, so a list of ``None`` or of empty lists shows fewer levels than + its column may declare. The rows' tables are then concatenated, which needs + every row to give a column one type. This step gives each column that type, + built from the same values. A ``large_string`` column is every row's type + already and is left as it is. + + Args: + table: A table of user tags, system tags, data and source info, after the + per-slice steps (``streams.base.row_built_columns``). + + Returns: + The table with each source-info column of the type its tokens give. + + Raises: + SourceInfoTypesDisagree: If two rows give one source-info column different + types, where the rows' tables cannot be concatenated. The caller builds + the rows (``_rows_to_table``), which raises the error a table built from + rows raises. + """ + from orcapod.system_constants import constants + from orcapod.utils import arrow_utils + + columns = list(table.columns) + fields = list(table.schema) + changed = False + for index, field in enumerate(fields): + if not field.name.startswith(constants.SOURCE_PREFIX): + continue + if pa.types.is_large_string(field.type): + continue + values = table.column(index).to_pylist() + kinds = {arrow_utils.source_info_arrow_type(value) for value in values} + if len(kinds) != 1: + raise SourceInfoTypesDisagree(field.name) + (kind,) = kinds + if kind == field.type: + continue + columns[index] = pa.chunked_array([pa.array(values, type=kind)]) + fields[index] = pa.field(field.name, kind, nullable=field.nullable) + changed = True + 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), + ), + ) + @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. + F in the ITL-1347 spec: the same table, without making the rows. Two steps: + + - per slice (``streams.base.row_built_columns``), what each row decides on its + own: the columns, their order, their large types, and the provenance fields' + form (no system-tag field metadata, source-info lists of nullable items); + - on the complete table, what depends on the values of every row: each + source-info column's type, from its tokens (``_type_source_info_by_values``), + then the system-tag and source-info field flags (``_flag_by_values``). + + The equality with ``_rows_to_table`` is tested over every operator, source kind, + column role and raw-stream provenance shape (ITL-1347, L0-L2). Args: table: A table of user tags, system tags, data and source info, with rows. @@ -522,8 +585,38 @@ def _row_built_form( Returns: The table ``_rows_to_table`` would build from its rows. + + Raises: + SourceInfoTypesDisagree: If the rows' tokens give a source-info column two + types (``_type_source_info_by_values``). + """ + return StaticOutputOperatorPod._flag_by_values( + StaticOutputOperatorPod._type_source_info_by_values( + row_built_columns(table, keys) + ) + ) + + @staticmethod + def _raise_as_rows_do( + rows: Iterable[tuple[TagProtocol, DataProtocol]], + error: SourceInfoTypesDisagree, + ) -> NoReturn: + """Build ``rows`` into a table to raise the error a table built from them raises. + + Called when ``_row_built_form`` finds rows whose source-info tokens cannot make + one table (``SourceInfoTypesDisagree``): the rows' own concatenation + (``_rows_to_table``) raises exactly what a run that hands rows on raises. + + Args: + rows: The rows of the table F was given, in order. + error: The disagreement F found, raised if the rows do concatenate. + + Raises: + pyarrow.ArrowInvalid: As ``_rows_to_table`` raises it. + SourceInfoTypesDisagree: ``error``, if the rows concatenate after all. """ - return StaticOutputOperatorPod._flag_by_values(row_built_columns(table, keys)) + StaticOutputOperatorPod._rows_to_table(list(rows)) + raise error @staticmethod def _output_stream( diff --git a/tests/test_core/operators/test_row_built_form.py b/tests/test_core/operators/test_row_built_form.py index 0fba4c92d..23a54bedf 100644 --- a/tests/test_core/operators/test_row_built_form.py +++ b/tests/test_core/operators/test_row_built_form.py @@ -25,8 +25,15 @@ import pyarrow.compute as pc import pytest -from orcapod.core.operators import DropNulls, SelectDataColumns -from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod +from orcapod import PipelineJob +from orcapod.core.operators import Batch, DropNulls, SelectDataColumns +from orcapod.core.operators.static_output_pod import ( + SourceInfoTypesDisagree, + StaticOutputOperatorPod, +) +from orcapod.databases import InMemoryArrowDatabase +from orcapod.pipeline.observer import NoOpObserver +from orcapod.types import CacheMode from orcapod.core.streams import ArrowTableStream from orcapod.core.streams.base import ZERO_ROW_INPUT_COLUMNS, row_built_columns from orcapod.system_constants import constants @@ -206,29 +213,147 @@ def _source_table() -> pa.Table: return source.as_table(columns={"source": True, "system_tags": True}) -def test_empty_source_info_lists_are_outside_the_domain_of_the_row_built_form() -> None: - """F's one named exception: source-info tokens that are only empty lists. +def _with_source_x(values: list[Any], kind: pa.DataType) -> ArrowTableStream: + """A source's rows as a raw stream, ``_source_x`` replaced by ``values`` of ``kind``. - No source or operator makes an empty token list. A hand-built raw stream can: - ``_rows_to_table`` types the tokens from their values (one list level, the empty - lists show no more), while F keeps the column's two levels. Pinned so that a - change to either side is seen (the refusal of such a stream is the developer's - decision). + It keeps the source's system-tag pair, so a job slot accepts it (Codex on PR #485). """ table = _source_table() position = table.schema.get_field_index("_source_x") - empty = pa.array([[], []], pa.large_list(pa.large_list(pa.large_string()))) - stream = ArrowTableStream( - table.set_column(position, "_source_x", empty), tag_columns=["k"] + return ArrowTableStream( + table.set_column( + position, + pa.field("_source_x", kind, nullable=True), + pa.array(values, kind), + ), + tag_columns=["k"], ) + + +_STRINGS = pa.large_list(pa.large_string()) +_NESTED = pa.large_list(_STRINGS) + + +@pytest.mark.parametrize( + "make", + [ + pytest.param(lambda: _with_source_x([[], []], _NESTED), id="empty-lists"), + pytest.param(lambda: _with_source_x([None, None], _STRINGS), id="null-lists"), + pytest.param( + lambda: _with_source_x([[None], [None]], _NESTED), id="lists-of-null" + ), + pytest.param( + lambda: Batch(batch_size=1)( + _with_source_x([None, None], pa.large_string()) + ), + id="batch-1-of-null-tokens", + ), + pytest.param( + lambda: Batch(batch_size=2)(_with_source_x([None, None], _STRINGS)), + id="batch-2-of-null-lists", + ), + pytest.param(lambda: _with_source_x([None, None], pa.null()), id="null-type"), + ], +) +def test_source_info_types_follow_the_tokens(make: Any) -> None: + """F types each source-info column from its tokens, as the rows do. + + A list of ``None`` or of empty lists shows fewer levels than its column declares; + the rows type it from the tokens (``arrow_utils.source_info_arrow_type``), and so + does F, over the whole table. + """ + stream = make() built, _, _ = StaticOutputOperatorPod._rows_to_table(list(stream.iter_data())) # pyright: ignore[reportPrivateUsage] # R, the oracle formed = StaticOutputOperatorPod._row_built_form( # pyright: ignore[reportPrivateUsage] # F, under test stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS), stream.keys() ) - assert built.schema.field("_source_x").type == pa.large_list(pa.large_string()) - assert formed.schema.field("_source_x").type == pa.large_list( - pa.large_list(pa.large_string()) + assert formed.column_names == built.column_names + assert formed.schema.equals(built.schema, check_metadata=True) + assert_same_values(formed, built) + + +def test_tokens_of_two_types_raise_as_the_rows_do() -> None: + """A list token on one row and ``None`` on another: no table holds both rows. + + The rows' tables cannot be concatenated (``ArrowInvalid``); F says so + (``SourceInfoTypesDisagree``), and a node then builds the rows, which raise. + """ + stream = _with_source_x([["s"], None], _STRINGS) + with pytest.raises(pa.ArrowInvalid, match="Schema at index 1 was different"): + StaticOutputOperatorPod._rows_to_table(list(stream.iter_data())) # pyright: ignore[reportPrivateUsage] # R, the oracle + with pytest.raises(SourceInfoTypesDisagree, match="_source_x"): + StaticOutputOperatorPod._row_built_form( # pyright: ignore[reportPrivateUsage] # F, under test + stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS), stream.keys() + ) + + +class _NodeEvents(NoOpObserver): + """Records node starts and ends.""" + + def __init__(self) -> None: + self.events: list[tuple[str, str]] = [] + + def contextualize(self, *identity_path: str) -> _NodeEvents: + return self + + def on_node_start( + self, node_label: str, node_hash: str, tag_schema: Any = None + ) -> None: + self.events.append(("start", node_label)) + + def on_node_end(self, node_label: str, node_hash: str) -> None: + self.events.append(("end", node_label)) + + +def _batched_job(database: InMemoryArrowDatabase) -> PipelineJob: + """``source -> select x -> Batch(2)``, the batch node in ``LOG`` mode.""" + from orcapod.sources import DictSource + + source = DictSource( + [{"k": 1, "x": 1}, {"k": 2, "x": 2}], + tag_columns=["k"], + tag_only_columns=True, + source_id="s", + ) + job = PipelineJob(name="source_info_types", database=database) + with job: + Batch(batch_size=2)(source.select_data_columns(["x"]), label="batched") + job.nodes["batched"].attach_databases( + pipeline_database=database.at("log"), cache_mode=CacheMode.LOG ) + return job + + +def test_a_job_keeps_and_stores_the_token_type_the_rows_give() -> None: + """A bound raw source with null list tokens, through ``Batch(2)`` in ``LOG`` mode. + + The rows type ``[None, None]`` as ``large_list``: kept and stored so, + as on ``main``, not as the list of the input's declared list type. + """ + database = InMemoryArrowDatabase() + job = _batched_job(database) + job.bind(sources={"s": _with_source_x([None, None], _STRINGS)}) + job.run() + node = job.nodes["batched"] + kept = node.as_table(columns={"source": True}) + assert kept.schema.field("_source_x").type == _STRINGS + stored = node.get_all_records(columns={"source": True}) + assert stored is not None + assert stored.schema.field("_source_x").type == _STRINGS + + +def test_a_job_over_tokens_of_two_types_fails_as_main_does() -> None: + """The run raises the rows' ``ArrowInvalid`` after the source node has ended. + + On ``main`` the source node hands its rows on, and the run fails where they are + concatenated for its successor: the same error, after the same events. + """ + job = _batched_job(InMemoryArrowDatabase()) + job.bind(sources={"s": _with_source_x([["s"], None], _STRINGS)}) + observer = _NodeEvents() + with pytest.raises(pa.ArrowInvalid, match="Schema at index 1 was different"): + job.run(observer=observer) + assert observer.events == [("start", "s"), ("end", "s")] def test_a_source_with_a_nullable_system_tag_is_not_bound() -> None: From 942fe148d2c5718a2682a58998b525d3017aca66 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 05:03:40 -0800 Subject: [PATCH 24/86] fix(source_node): a source's rows keep their data order (ITL-1360) Codex on PR #485, finding 2. A PollingSource states its declared key order, but its rows (and a table built from them) list the data in the fetched table's order. The source node takes its rows' keys from the table by the rule its rows follow (_keys_of_rows), so an operator after it keeps and stores the columns as on main. L2 test with a poller fetching in another order. Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/nodes/source_node.py | 34 +++++++-- .../test_stream_transport_equivalence.py | 74 ++++++++++++++++++- 2 files changed, 102 insertions(+), 6 deletions(-) diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index 7da04da1c..2fdfccd1d 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -13,7 +13,7 @@ import json import logging from abc import ABC, abstractmethod -from collections.abc import AsyncIterator, Collection, Iterator, Mapping +from collections.abc import AsyncIterator, Collection, Iterator, Mapping, Sequence from datetime import datetime from typing import TYPE_CHECKING, Any, cast @@ -185,6 +185,32 @@ def _declared_positions(self, names: list[str]) -> list[int]: return order +def _keys_of_rows( + table: pa.Table, keys: tuple[Sequence[str], Sequence[str]] +) -> tuple[tuple[str, ...], tuple[str, ...]]: + """Return the tag and data keys a source's rows have, given its table and ``keys()``. + + A source's rows come from a stream over its table (``ArrowTableStream``), whose rows + list their tags in the stream's tag order and their data with the data-tags first, + in tag order, then the other data columns in the table's order. A source whose + ``keys()`` states its declared order (a ``PollingSource`` whose fetched table has + another column order) has rows in the table's order all the same, as a table built + from its rows does (Codex on PR #485). + + Args: + table: The source's table, as its rows are read from it. + keys: The source's ``keys()``. + + Returns: + The tag keys, and the data keys in the order of the rows. + """ + tag_keys, data_keys = (tuple(keys[0]), tuple(keys[1])) + data_tags = data_tag_names(tag_keys, data_keys) + data = set(data_keys) - set(tag_keys) + in_table = tuple(name for name in table.column_names if name in data) + return tag_keys, (*data_tags, *in_table) + + def _system_tag_columns( source: StreamProtocol, tag_names: Collection[str] ) -> tuple[list[str], list[str], list[str]]: @@ -1193,9 +1219,8 @@ def _rows_table(self) -> tuple[pa.Table, tuple[tuple[str, ...], tuple[str, ...]] Here this node's own table (``ZERO_ROW_INPUT_COLUMNS``) and keys. """ stream = cast("StreamProtocol", self) - tag_keys, data_keys = stream.keys() table = stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS) - return table, (tuple(tag_keys), tuple(data_keys)) + return table, _keys_of_rows(table, stream.keys()) def arrow_schema(self) -> pa.Schema: """The Arrow schema of the columns this stream passes between job nodes. @@ -1754,8 +1779,7 @@ def _rows_table(self) -> tuple[pa.Table, tuple[tuple[str, ...], tuple[str, ...]] ) table = self._bound_source.as_table(columns=ZERO_ROW_INPUT_COLUMNS) if self._declared_form is None: - tag_keys, data_keys = self._bound_source.keys() - return table, (tuple(tag_keys), tuple(data_keys)) + return table, _keys_of_rows(table, self._bound_source.keys()) return self._declared_form.apply(table), self._row_keys() def iter_data(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: diff --git a/tests/test_pipeline/test_stream_transport_equivalence.py b/tests/test_pipeline/test_stream_transport_equivalence.py index 68f608d1c..3874d5c87 100644 --- a/tests/test_pipeline/test_stream_transport_equivalence.py +++ b/tests/test_pipeline/test_stream_transport_equivalence.py @@ -40,7 +40,7 @@ from orcapod.core.streams.base import ZERO_ROW_INPUT_COLUMNS from orcapod.databases import InMemoryArrowDatabase from orcapod.errors import ProvisionalHashWarning -from orcapod.operators import MergeJoin, Rejoin +from orcapod.operators import MergeJoin, Rejoin, SelectDataColumns from orcapod.side_effects import SideEffectJobNode from orcapod.system_constants import constants from orcapod.types import CacheMode @@ -318,3 +318,75 @@ def test_a_loaded_job_describes_its_nodes( output.schema ), label assert node.arrow_types_declared, label + + +def _poller(fetched_order: tuple[str, ...]) -> Any: + """A ``PollingSource`` declaring tags ``k, j`` and data ``b, a``. + + It fetches a table with its columns in ``fetched_order``: a valid source whose + declared order is not its rows' (Codex on PR #485). + """ + from orcapod.core.sources import PollingSource + from tests.test_hashing.test_logical_type_forms import ( + _TableImpl, # pyright: ignore[reportPrivateUsage] # the one test polling implementation + ) + + columns = { + "k": pa.array(["1", "2"], pa.large_string()), + "j": pa.array(["x", "y"], pa.large_string()), + "a": pa.array([1, 2], pa.int64()), + "b": pa.array([3, 4], pa.int64()), + } + declared = pa.schema( + [pa.field(name, columns[name].type, False) for name in ("k", "j", "b", "a")] + ) + fetched = pa.table({name: columns[name] for name in fetched_order}) + fetched = fetched.cast(pa.schema([f.with_nullable(False) for f in fetched.schema])) + return PollingSource( + _TableImpl(fetched, declared), + tag_columns=["k", "j"], + record_id_columns=["k", "j"], + source_id="poller", + ) + + +@pytest.mark.filterwarnings("ignore::orcapod.errors.ProvisionalHashWarning") +@pytest.mark.parametrize( + "fetched_order", + [("j", "k", "a", "b"), ("k", "j", "b", "a"), ("k", "b", "j", "a")], + ids="-".join, +) +def test_a_poller_fetching_in_another_order_hands_on_its_rows( + fetched_order: tuple[str, ...], outputs: dict[str, Any] +) -> None: + """L2 for a poller whose fetched column order differs from its declared order. + + The source node's output equals its rows rebuilt (checked by ``outputs``), and the + operator after it keeps and stores its columns in the rows' order, as on ``main``. + """ + # Built before the job captures: importing the polling implementation's module + # inside ``with job`` would capture the sources that module builds. + poller = _poller(fetched_order) + database = InMemoryArrowDatabase() + job = PipelineJob(name="poller_order", database=database) + with job: + SelectDataColumns(["a", "b"])(poller, label="selected") + job.nodes["selected"].attach_databases( + pipeline_database=database.at("log"), cache_mode=CacheMode.LOG + ) + _run(job) + node = job.nodes["selected"] + rows_order = [ + *job.nodes["selected"].keys()[0], + *(name for name in fetched_order if name in ("a", "b")), + ] + source_order = [f"{constants.SOURCE_PREFIX}{n}" for n in rows_order[2:]] + kept = node.as_table(columns={"source": True}).column_names + assert kept == [*rows_order, *source_order] + stored = node.get_all_records(columns={"source": True}) + assert stored is not None + assert [name for name in stored.column_names if not name.startswith("__")] == [ + *rows_order, + *source_order, + ] + assert "poller" in outputs From a6582388b64d66f533c0a30b5cfc9189b71d7fb7 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 05:06:38 -0800 Subject: [PATCH 25/86] fix(pipeline): async held rows as planned; async outputs built on read (ITL-1360) Codex on PR #485, findings 3 and 4. The run plan keeps the rows of each held node as it took them (RunPlan.held_rows) beside their output streams. The async orchestrator takes those rows again (held_rows, as on main) and sends them, instead of reading the node again; the sync orchestrator takes the streams. The async orchestrator's node_outputs builds each node's stream when it is first read (StreamsOnRead), so an async run over rows that cannot make one table (e9's store written before ITL-928) finishes and holds its rows, as on main; e9 stays a sync-only difference. Co-Authored-By: Claude Opus 5.5 --- src/orcapod/pipeline/async_orchestrator.py | 34 ++++++------- src/orcapod/pipeline/job.py | 33 ++++++++---- src/orcapod/pipeline/node_run.py | 18 ++++--- src/orcapod/pipeline/result.py | 43 +++++++++++++++- .../test_function_node_arrow_types.py | 27 ++++++++++ .../test_current_run_review_fixes.py | 10 +--- .../test_stream_transport_equivalence.py | 51 +++++++++++++++++++ 7 files changed, 172 insertions(+), 44 deletions(-) diff --git a/src/orcapod/pipeline/async_orchestrator.py b/src/orcapod/pipeline/async_orchestrator.py index 061616cba..a9f87691c 100644 --- a/src/orcapod/pipeline/async_orchestrator.py +++ b/src/orcapod/pipeline/async_orchestrator.py @@ -24,7 +24,7 @@ OrcapodDatabaseWriteError, TypeIdentityError, ) -from orcapod.pipeline.result import OrchestratorResult +from orcapod.pipeline.result import OrchestratorResult, StreamsOnRead from orcapod.utils.database_errors import keep_database_error from orcapod.protocols.node_protocols import ( is_function_node, @@ -41,7 +41,6 @@ from orcapod.pipeline.dag import GraphProtocol from orcapod.protocols.core_protocols import ( DataProtocol, - StreamProtocol, TagProtocol, ) from orcapod.protocols.observability_protocols import ExecutionObserverProtocol @@ -87,7 +86,7 @@ def run( run_id: str | None = None, pipeline_uri: str = "", load_only: bool = False, - held: Mapping[Any, StreamProtocol] | None = None, + held_rows: Mapping[Any, list[tuple[TagProtocol, DataProtocol]]] | None = None, ) -> OrchestratorResult: """Synchronous entry point — runs the async pipeline to completion. @@ -132,7 +131,7 @@ def run( run_id=run_id, pipeline_uri=pipeline_uri, load_only=load_only, - held=held, + held_rows=held_rows, ) ) @@ -154,7 +153,7 @@ def make_run() -> Coroutine[Any, Any, OrchestratorResult]: run_id=run_id, pipeline_uri=pipeline_uri, load_only=load_only, - held=held, + held_rows=held_rows, ) return _run_on_own_thread(make_run, rows_in_flight) @@ -168,7 +167,7 @@ async def run_async( run_id: str | None = None, pipeline_uri: str = "", load_only: bool = False, - held: Mapping[Any, StreamProtocol] | None = None, + held_rows: Mapping[Any, list[tuple[TagProtocol, DataProtocol]]] | None = None, ) -> OrchestratorResult: """Async entry point for callers already inside an event loop. @@ -181,8 +180,9 @@ async def run_async( pipeline_uri: Opaque URI string identifying this pipeline run. Forwarded verbatim to ``observer.on_run_start``. load_only: As for ``SyncPipelineOrchestrator.run``. - held: As for ``SyncPipelineOrchestrator.run``: nodes not run, whose - rows feed their successors. + held_rows: Nodes not run, with the rows of their current run as the run's + plan took them (``RunPlan.held_rows``): those rows feed their + successors. The async path carries rows until ITL-1347 stage 5. Returns: OrchestratorResult with node outputs. @@ -194,7 +194,7 @@ async def run_async( run_id=run_id, pipeline_uri=pipeline_uri, load_only=load_only, - held=held, + held_rows=held_rows, ) async def _run_async( @@ -206,7 +206,7 @@ async def _run_async( run_id: str | None = None, pipeline_uri: str = "", load_only: bool = False, - held: Mapping[Any, StreamProtocol] | None = None, + held_rows: Mapping[Any, list[tuple[TagProtocol, DataProtocol]]] | None = None, ) -> OrchestratorResult: """Core async logic: wire channels, launch tasks, collect results.""" from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod @@ -269,7 +269,7 @@ async def _run_async( collector = collectors[node] writer = _CollectingWriter(writer, collector) - if held is not None and node in held: + if held_rows is not None and node in held_rows: # Not run: the rows of its current run feed its successors. Its # own inputs are read and discarded, so no producer blocks on # a channel nobody reads. @@ -279,9 +279,8 @@ async def _run_async( tg, failed_nodes, node, - # The held node's own rows, as before stage 2: the async - # path still carries rows (ITL-1347, stage 5 changes it). - _send_held(list(node.iter_data()), writer), + # The rows the plan took (ITL-1347, stage 5 changes it). + _send_held(held_rows[node], writer), ) elif is_source_node(node): _start_node( @@ -366,10 +365,9 @@ async def _run_async( return OrchestratorResult( node_outputs=( - { - node: StaticOutputOperatorPod._materialize_upstream(rows, node) - for node, rows in collectors.items() - } + StreamsOnRead( + collectors, StaticOutputOperatorPod._materialize_upstream + ) if materialize_results else {} ) diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index 1443d4f43..e2b84a81a 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -990,15 +990,28 @@ def run( counter = RunCountingObserver() effective_orchestrator = orchestrator or SyncPipelineOrchestrator() with self._executing(prepared, plan, commit_every_rows, load_only=load_only): - _ = effective_orchestrator.run( - plan.dag, - observer=_with_counter(observer, counter), - run_id=prepared.run_id, - pipeline_uri=prepared.pipeline_uri, - materialize_results=materialize_results, - load_only=load_only, - held=plan.held, - ) + if isinstance(effective_orchestrator, SyncPipelineOrchestrator): + # Held nodes give their output streams on the sync path (ITL-1347). + _ = effective_orchestrator.run( + plan.dag, + observer=_with_counter(observer, counter), + run_id=prepared.run_id, + pipeline_uri=prepared.pipeline_uri, + materialize_results=materialize_results, + load_only=load_only, + held=plan.held, + ) + else: + # The async path sends the rows the plan took (until stage 5). + _ = effective_orchestrator.run( + plan.dag, + observer=_with_counter(observer, counter), + run_id=prepared.run_id, + pipeline_uri=prepared.pipeline_uri, + materialize_results=materialize_results, + load_only=load_only, + held_rows=plan.held_rows, + ) summary = self._finish_run( prepared, counter, @@ -1068,7 +1081,7 @@ async def run_async( pipeline_uri=prepared.pipeline_uri, materialize_results=materialize_results, load_only=load_only, - held=plan.held, + held_rows=plan.held_rows, ) summary = self._finish_run( prepared, diff --git a/src/orcapod/pipeline/node_run.py b/src/orcapod/pipeline/node_run.py index 9e67317fb..ad0ab8561 100644 --- a/src/orcapod/pipeline/node_run.py +++ b/src/orcapod/pipeline/node_run.py @@ -251,7 +251,10 @@ class RunPlan: them (a source slot is read; any other one is held). held: The output stream of each held node of ``dag``: of its current run, or of a stream outside the job; it feeds the nodes after it as if the node had - just run. + just run (the sync orchestrator). + held_rows: The rows of each held node, as the plan took them; ``held`` is + built from them. The async orchestrator sends them (it carries rows until + ITL-1347 stage 5). to_run: The nodes the run runs, in dependency order. held_counts: Every node of the whole graph that holds a current run, with its row count, for the summary. @@ -261,6 +264,7 @@ class RunPlan: held: dict[Any, Any] to_run: list[Any] held_counts: dict[Any, int] + held_rows: dict[Any, list[Any]] def plan_run(graph: Any, *, load_only: bool, outside: Sequence[Any] = ()) -> RunPlan: @@ -336,17 +340,19 @@ def is_source(node: Any) -> bool: # A held node's output stream: what the sync orchestrator built from its rows for # the nodes after it, exactly (ITL-1347, stage 2). - held = { - node: StaticOutputOperatorPod._materialize_upstream( - list(node.iter_data()), node - ) + held_rows = { + node: list(node.iter_data()) for node in included if not any(node is r for r in to_run) and not is_source(node) } + held = { + node: StaticOutputOperatorPod._materialize_upstream(rows, node) + for node, rows in held_rows.items() + } # Counted from what each node holds: iterating an operator's rows would build a # (Tag, Data) pair per row only to count them (ITL-1351). held_counts = {node: node.held_row_count() for node in current} - return RunPlan(dag, held, to_run, held_counts) + return RunPlan(dag, held, to_run, held_counts, held_rows) def commit_run(databases: Sequence[ArrowDatabaseProtocol], ran: Sequence[Any]) -> None: diff --git a/src/orcapod/pipeline/result.py b/src/orcapod/pipeline/result.py index 12448df8c..bb117de2d 100644 --- a/src/orcapod/pipeline/result.py +++ b/src/orcapod/pipeline/result.py @@ -2,6 +2,7 @@ from __future__ import annotations +from collections.abc import Callable, Iterator, Mapping from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any @@ -9,6 +10,43 @@ from orcapod.protocols.core_protocols import StreamProtocol +class StreamsOnRead(Mapping[Any, "StreamProtocol"]): + """Each node's output stream, built when it is first read. + + The async orchestrator collects each node's rows as they are sent; a node's stream + is built from them (``build``) the first time it is read, and kept. A run whose + rows cannot make one table (rows of a store written before ITL-928) therefore + finishes, as it does on ``main``, and only reading that node's output raises, as + reading its rows as a table does (ITL-1360). + """ + + def __init__( + self, + rows: Mapping[Any, Any], + build: Callable[[Any, Any], "StreamProtocol"], + ) -> None: + """Hold each node's rows and how a stream is built from them. + + Args: + rows: Each node's collected rows. + build: Builds a node's stream from its rows, given ``(rows, node)``. + """ + self._rows = dict(rows) + self._build = build + self._built: dict[Any, StreamProtocol] = {} + + def __getitem__(self, node: Any) -> "StreamProtocol": + if node not in self._built: + self._built[node] = self._build(self._rows[node], node) + return self._built[node] + + def __iter__(self) -> Iterator[Any]: + return iter(self._rows) + + def __len__(self) -> int: + return len(self._rows) + + @dataclass class OrchestratorResult: """Result of an orchestrator run. @@ -16,7 +54,8 @@ class OrchestratorResult: Attributes: node_outputs: Mapping from graph node to its output stream (backed by an Arrow table; ``as_table()`` gives it, ``iter_data()`` its rows). Empty when - ``materialize_results=False``. + ``materialize_results=False``. The async orchestrator builds each stream + when it is first read (``StreamsOnRead``). """ - node_outputs: dict[Any, "StreamProtocol"] = field(default_factory=dict) + node_outputs: Mapping[Any, "StreamProtocol"] = field(default_factory=dict) diff --git a/tests/test_core/function_pod/test_function_node_arrow_types.py b/tests/test_core/function_pod/test_function_node_arrow_types.py index b7a431498..56cc00a5d 100644 --- a/tests/test_core/function_pod/test_function_node_arrow_types.py +++ b/tests/test_core/function_pod/test_function_node_arrow_types.py @@ -394,3 +394,30 @@ def test_a_null_typed_row_is_compared_as_null() -> None: with pytest.raises(InputValidationError, match="'k': null and int64"): _concat_row_tables(rows) + + +@pytest.mark.parametrize("materialize_results", [True, False]) +def test_an_async_run_over_a_store_written_before_the_fix_finishes( + materialize_results: bool, tmp_path: pathlib.Path +) -> None: + """e9 is sync only: an async run over such a store finishes and holds its rows. + + The async orchestrator builds a node's output stream when it is read + (``StreamsOnRead``), so the run finishes as on ``main`` with either value of + ``materialize_results``; reading the node's rows as one table raises, as it does + on ``main``. + """ + from orcapod.pipeline import AsyncPipelineOrchestrator + + _build(DeltaTableDatabase(tmp_path), _source_table("uint32").slice(0, 2)).run() + _as_written_before_the_fix(tmp_path) + job = _build(DeltaTableDatabase(tmp_path), _source_table("uint32")) + job.run( + orchestrator=AsyncPipelineOrchestrator(), + materialize_results=materialize_results, + ) + + node = job.nodes["double"] + assert len(list(node.iter_data())) == 3 + with pytest.raises(InputValidationError, match="'k'"): + node.as_table() diff --git a/tests/test_pipeline/test_current_run_review_fixes.py b/tests/test_pipeline/test_current_run_review_fixes.py index 7ad949768..25f266174 100644 --- a/tests/test_pipeline/test_current_run_review_fixes.py +++ b/tests/test_pipeline/test_current_run_review_fixes.py @@ -17,8 +17,6 @@ import pyarrow as pa import pytest -from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod - from orcapod import PipelineJob, function_pod from orcapod.core.nodes import OperatorJobNode from orcapod.core.nodes.source_node import SourceJobNode @@ -752,18 +750,14 @@ def test_a_direct_async_run_drains_the_inputs_of_a_held_node( (grouped, summed), ): dag.add_edge(upstream, downstream) - held = { - rowwise: StaticOutputOperatorPod._materialize_upstream( # pyright: ignore[reportPrivateUsage] # a held node's output stream, as the run plan builds it - list(rowwise.iter_data()), rowwise - ) - } + held = {rowwise: list(rowwise.iter_data())} summed.clear_cache() grouped.clear_cache() orchestrator = AsyncPipelineOrchestrator(buffer_size=2, error_policy=error_policy) async def run() -> None: """Run the whole graph with ``rowwise`` held, under a time limit.""" - await asyncio.wait_for(orchestrator.run_async(dag, held=held), timeout=30) + await asyncio.wait_for(orchestrator.run_async(dag, held_rows=held), timeout=30) asyncio.run(run()) assert summed.as_table().num_rows == 2 diff --git a/tests/test_pipeline/test_stream_transport_equivalence.py b/tests/test_pipeline/test_stream_transport_equivalence.py index 3874d5c87..0d10ecf07 100644 --- a/tests/test_pipeline/test_stream_transport_equivalence.py +++ b/tests/test_pipeline/test_stream_transport_equivalence.py @@ -40,6 +40,8 @@ from orcapod.core.streams.base import ZERO_ROW_INPUT_COLUMNS from orcapod.databases import InMemoryArrowDatabase from orcapod.errors import ProvisionalHashWarning +from orcapod.pipeline import AsyncPipelineOrchestrator +from orcapod.pipeline.observer import NoOpObserver from orcapod.operators import MergeJoin, Rejoin, SelectDataColumns from orcapod.side_effects import SideEffectJobNode from orcapod.system_constants import constants @@ -390,3 +392,52 @@ def test_a_poller_fetching_in_another_order_hands_on_its_rows( *source_order, ] assert "poller" in outputs + + +@function_pod(output_keys="z") +def plus_one(d1_doubled: int) -> int: + return d1_doubled + 1 + + +class _ClearsOnRunStart(NoOpObserver): + """Clears ``node`` when the run starts and counts ``label``'s data starts.""" + + def __init__(self, node: Any, label: str) -> None: + self._node = node + self._label = label + self.data_starts = 0 + + def contextualize(self, *identity_path: str) -> _ClearsOnRunStart: + return self + + def on_run_start(self, run_id: str, pipeline_uri: str = "") -> None: + self._node.clear_cache() + + def on_data_start(self, node_label: str, tag: Any, data: Any) -> None: + if node_label == self._label: + self.data_starts += 1 + + +def test_an_async_held_node_sends_the_rows_the_plan_took() -> None: + """The async run sends a held node's rows as planned, not as read again later. + + An observer clears the held node when the run starts; the rows the plan took still + feed the node after it, as on ``main`` (Codex on PR #485). + """ + from orcapod.sources import DictSource + + job = PipelineJob(name="held_snapshot", database=InMemoryArrowDatabase()) + with job: + source = DictSource( + [{"k": i, "d1": i} for i in range(3)], + tag_columns=["k"], + tag_only_columns=True, + source_id="s", + ) + plus_one.pod(doubled.pod(source, label="twice"), label="plus") + job.run() + job.nodes["plus"].clear_cache() + observer = _ClearsOnRunStart(job.nodes["twice"], "plus") + summary = job.run(orchestrator=AsyncPipelineOrchestrator(), observer=observer) + assert summary.nodes["twice"].held == 3 + assert observer.data_starts == 3 From 44d95c3bd8853dcfb6380135cbe543b89e1ae396 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 05:08:31 -0800 Subject: [PATCH 26/86] fix(streams): a description never polls; L7 compares column order (ITL-1360) Codex on PR #485, findings 5 and 6. stream_arrow_schema's fallback for a stream that cannot type itself without rows asks only for its tags and system tags and states a string source-info field for each data column: asking for its source-info columns made a PollingSource that had not polled fetch its first batch. L7 compares columns in order. The arrangements where a source's tag schema is in layout order while its keys and rows follow the declared order (ITL-1365, being fixed on main) are strict xfails naming it, as is the reviewer's plain operator stream. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1360.md | 4 +- src/orcapod/core/streams/base.py | 13 +- .../test_stream_transport_equivalence.py | 123 ++++++++++++++++-- 3 files changed, 126 insertions(+), 14 deletions(-) diff --git a/changelog.d/ITL-1360.md b/changelog.d/ITL-1360.md index 0d7f58069..ce18adf22 100644 --- a/changelog.d/ITL-1360.md +++ b/changelog.d/ITL-1360.md @@ -7,7 +7,9 @@ every successor as it is: a source node gives its source's Arrow table, and an operator node its result's table (REPLAY: its stored table), each in the form a table built from the rows has, without making the rows. `OrchestratorResult.node_outputs` holds each - node's output stream, and a held node gives the stream of its held rows. Every + node's output stream (the async orchestrator builds it when it is first read), and + on the sync path a held node gives the stream of its held rows; the async path still + sends a held node's rows as the run's plan took them (`held_rows`). Every successor's input is unchanged: columns, types, row order, system tags, source info, pipeline and content hashes. No hash, stored table or output changes. An operator node's table is built once, for what it keeps and for every successor, instead of once to keep diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py index 38ade1cb1..f396b9c4f 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -365,11 +365,18 @@ def stream_arrow_schema( keys = typed.keys() table = typed_zero_row_input(stream) if table is None: - tag_schema, data_schema = typed.output_schema( - columns={"system_tags": True, "source": True} - ) + # Only what the stream declares: asking for its source-info columns would make + # a source that has not polled poll (a description never computes, polls or + # reads). A source's tokens are strings, so each data column's source info is + # a string field. + tag_schema, data_schema = typed.output_schema(columns={"system_tags": True}) converter = StaticOutputOperatorPod._upstream_context(typed).type_converter # pyright: ignore[reportPrivateUsage] # the one place that resolves an upstream's context table = arrow_utils.make_empty_table({**tag_schema, **data_schema}, converter) + for name in data_schema: + table = table.append_column( + pa.field(f"{constants.SOURCE_PREFIX}{name}", pa.large_string()), + pa.array([], pa.large_string()), + ) names = row_built_names(table.column_names, keys) schema = row_built_provenance(table.select(names)).schema prefixes = (constants.SYSTEM_TAG_PREFIX, constants.SOURCE_PREFIX) diff --git a/tests/test_pipeline/test_stream_transport_equivalence.py b/tests/test_pipeline/test_stream_transport_equivalence.py index 0d10ecf07..04977f91d 100644 --- a/tests/test_pipeline/test_stream_transport_equivalence.py +++ b/tests/test_pipeline/test_stream_transport_equivalence.py @@ -237,27 +237,55 @@ def test_a_held_node_hands_on_the_stream_built_from_its_rows( assert set(outputs) == {"noted"} -def _without_exceptions(schema: pa.Schema) -> dict[str, tuple[Any, bool, Any]]: - """Fields by name as (type, nullable, metadata), the spec's exceptions applied. +def _without_exceptions(schema: pa.Schema) -> list[tuple[str, Any, bool, Any]]: + """Fields in order as (name, type, nullable, metadata), the spec's exceptions applied. A system-tag or source-info field's flag is decided by a table's values (stated - nullable), and a ``null`` column is ``large_string`` in rows (ITL-1319). Columns are - matched by name: an operator node's declared tag order can differ from its rows' - under another physical layout, as on ``main``, and column order is not a result - (developer, 2026-11-22). + nullable), and a ``null`` column is ``large_string`` in rows (ITL-1319). Column + order counts on the sync path (Codex on PR #485). """ prefixes = (constants.SYSTEM_TAG_PREFIX, constants.SOURCE_PREFIX) - return { - field.name: ( + return [ + ( + field.name, pa.large_string() if pa.types.is_null(field.type) else field.type, True if field.name.startswith(prefixes) else field.nullable, field.metadata, ) for field in schema - } + ] + + +def _tag_schema_out_of_key_order(arrangement: Arrangement) -> bool: + """Whether the source's tag schema lists its tags in another order than its keys. + + ITL-1365: ``ArrowTableStream`` builds its tag schema in the table's layout order, + while its keys and rows follow the declared tag order; an operator predicts its + keys from that schema, so its ``arrow_schema()`` lists the tags in the layout + order and its rows do not. + """ + source = make_source(MAIN, arrangement) + return tuple(source.output_schema()[0]) != tuple(source.keys()[0]) + + +def _l7_arrangements() -> list[Any]: + return [ + pytest.param( + arrangement, + id=arrangement.id, + marks=pytest.mark.xfail( + strict=True, + raises=AssertionError, + reason="ITL-1365: a tag schema in layout order, keys in declared order", + ), + ) + if _tag_schema_out_of_key_order(arrangement) + else pytest.param(arrangement, id=arrangement.id) + for arrangement in arrangements(MAIN)[::4] + ] -@pytest.mark.parametrize("arrangement", arrangements(MAIN)[::4], ids=lambda a: a.id) +@pytest.mark.parametrize("arrangement", _l7_arrangements()) def test_declared_arrow_schema_equals_the_output( arrangement: Arrangement, outputs: dict[str, Any] ) -> None: @@ -441,3 +469,78 @@ def test_an_async_held_node_sends_the_rows_the_plan_took() -> None: summary = job.run(orchestrator=AsyncPipelineOrchestrator(), observer=observer) assert summary.nodes["twice"].held == 3 assert observer.data_starts == 3 + + +@pytest.mark.filterwarnings("ignore::orcapod.errors.ProvisionalHashWarning") +def test_describing_a_poller_that_has_not_polled_reads_nothing() -> None: + """L7: ``arrow_schema()`` of a poller that has not polled never fetches. + + It answers from the declared schema, the same every time, with each data column's + source info, and ``arrow_types_declared`` stays false (Codex on PR #485). + """ + from orcapod.core.sources import PollingSource + from orcapod.types import Schema + from tests.test_hashing.test_logical_type_forms import ( + _TableImpl, # pyright: ignore[reportPrivateUsage] # the one test polling implementation + ) + + fetches: list[int] = [] + + class Counting(_TableImpl): + async def fetch(self, cursor: Any = None) -> Any: + fetches.append(1) + return await super().fetch(cursor) + + def schema(self) -> Any: + return Schema({"k": str, "a": int, "b": int}) + + table = pa.table( + { + "k": pa.array(["1"], pa.large_string()), + "a": pa.array([1]), + "b": pa.array([2]), + } + ) + poller = PollingSource( + Counting(table, table.schema), + tag_columns=["k"], + record_id_columns=["k"], + source_id="unpolled", + ) + first = poller.arrow_schema() + second = poller.arrow_schema() + assert fetches == [] + assert first.equals(second, check_metadata=True) + assert [n for n in first.names if n.startswith(constants.SOURCE_PREFIX)] == [ + "_source_a", + "_source_b", + ] + assert not poller.arrow_types_declared + + +@pytest.mark.xfail( + strict=True, + raises=AssertionError, + reason="ITL-1365: a tag schema in layout order, keys in declared order", +) +def test_an_operator_stream_declares_its_tags_in_its_rows_order() -> None: + """A plain operator stream's ``arrow_schema()`` lists its tags as its rows do. + + Tags declared ``b, a`` over a table laid out ``a, b`` (Codex on PR #485). + """ + from orcapod.core.sources import ArrowTableSource + + table = pa.table( + { + "a": pa.array([1, 2]), + "b": pa.array([3, 4]), + "w": pa.array([5, 6]), + "x": pa.array([7, 8]), + } + ) + source = ArrowTableSource( + table, tag_columns=["b", "a"], tag_only_columns=True, source_id="s" + ) + stream = SelectDataColumns(["x"])(source) + built, _, _ = StaticOutputOperatorPod._rows_to_table(list(stream.iter_data())) # pyright: ignore[reportPrivateUsage] # the rows' order + assert stream.arrow_schema().names[:2] == built.column_names[:2] From f770d1a5335df3dff4678f3727fe88d849ce9735 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 05:31:11 -0800 Subject: [PATCH 27/86] perf(function_node): a stored hit takes its id by a shallow copy (ITL-1361) _with_datagram_id copied each stored result's Data by building it again from its table; it now copies the datagram the stored stream built, with the stored id (Datagram.with_datagram_uuid). A test pins the copy to the rebuilt datagram in every view, over several tag types and both stores. Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/datagrams/datagram.py | 18 +++++ src/orcapod/core/nodes/function_node.py | 12 ++-- .../nodes/test_stored_hit_datagram_id.py | 69 +++++++++++++++++++ 3 files changed, 92 insertions(+), 7 deletions(-) create mode 100644 tests/test_core/nodes/test_stored_hit_datagram_id.py diff --git a/src/orcapod/core/datagrams/datagram.py b/src/orcapod/core/datagrams/datagram.py index 23acd12ac..c93fd11c8 100644 --- a/src/orcapod/core/datagrams/datagram.py +++ b/src/orcapod/core/datagrams/datagram.py @@ -1197,6 +1197,24 @@ def with_columns( # 8. Utility Operations # ------------------------------------------------------------------ + def with_datagram_uuid(self, record_uuid: uuid.UUID) -> Self: + """Return a shallow copy of this datagram whose datagram id is ``record_uuid``. + + Every column, type, source-info token and cached content hash is this + datagram's (``copy``); only the id differs. A row read back from a store is built + by a stream, which gives it a fresh id; the id it was stored under is set here + (ITL-1060). + + Args: + record_uuid: The datagram id of the copy. + + Returns: + The copy. + """ + new_d = self.copy(include_cache=True, preserve_id=False) + new_d._datagram_uuid = record_uuid + return new_d + def copy(self, include_cache: bool = True, preserve_id: bool = True) -> Self: """Return a shallow copy of this datagram. diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 8d0f0fc01..b8a4875a0 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -283,10 +283,12 @@ def _bare_digest(hash_string: str) -> str: def _with_datagram_id(data: Data, datagram_id: uuid.UUID) -> Data: - """Return ``data`` rebuilt with ``datagram_id`` as its datagram id. + """Return ``data`` with ``datagram_id`` as its datagram id. A stored row read back is built by a stream, which gives every row a fresh id. - The rebuilt datagram has the same columns, types, source info and data context. + The copy shares the row's columns, types, source info and data context + (``Datagram.with_datagram_uuid``), instead of building the datagram again from its + table (ITL-1361). Args: data: The datagram a stream built from a stored row. @@ -295,11 +297,7 @@ def _with_datagram_id(data: Data, datagram_id: uuid.UUID) -> Data: Returns: A datagram equal to ``data`` whose ``datagram_uuid`` is ``datagram_id``. """ - return Data( - data.as_table(columns={"source": True}), - record_uuid=datagram_id, - data_context=data.data_context_key, - ) + return data.with_datagram_uuid(datagram_id) def _executor_supports_concurrent( diff --git a/tests/test_core/nodes/test_stored_hit_datagram_id.py b/tests/test_core/nodes/test_stored_hit_datagram_id.py new file mode 100644 index 000000000..4a0a1acbf --- /dev/null +++ b/tests/test_core/nodes/test_stored_hit_datagram_id.py @@ -0,0 +1,69 @@ +"""A stored hit takes its stored datagram id by a shallow copy (ITL-1361, ITL-1060). + +``_with_datagram_id`` used to build each stored result's ``Data`` again from its table +to give it the id it was stored under. It now copies the datagram the stored stream +built (``Datagram.with_datagram_uuid``). The copy must be the rebuilt datagram in every +view: columns, types, meta, source info, content hash and id. +""" + +from __future__ import annotations + +import pathlib +import uuid +from typing import Any + +import pytest + +from orcapod.core.datagrams import Data +from orcapod.databases import DeltaTableDatabase, InMemoryArrowDatabase +from tests.test_core.function_pod.test_function_node_arrow_types import ( + TAG_COLUMNS, + _build, # pyright: ignore[reportPrivateUsage] # the job these tests share + _source_table, # pyright: ignore[reportPrivateUsage] # the job these tests share +) + + +def _rebuilt(data: Data, datagram_id: uuid.UUID) -> Data: + """The datagram as ``_with_datagram_id`` built it before.""" + return Data( + data.as_table(columns={"source": True}), + record_uuid=datagram_id, + data_context=data.data_context_key, + ) + + +def _views(data: Data) -> list[Any]: + return [ + data.as_table(all_info=True), + data.as_table(columns={"source": True}), + data.keys(all_info=True), + data.source_info(), + data.content_hash(), + data.datagram_uuid, + data.arrow_schema(all_info=True), + data.data_context_key, + ] + + +@pytest.mark.parametrize("store", ["memory", "delta"]) +@pytest.mark.parametrize("name", list(TAG_COLUMNS)) +def test_a_stored_hit_is_the_rebuilt_datagram( + name: str, store: str, tmp_path: pathlib.Path +) -> None: + """Every stored hit equals the datagram rebuilt with its stored id, in every view.""" + database: Any = ( + InMemoryArrowDatabase() if store == "memory" else DeltaTableDatabase(tmp_path) + ) + table = _source_table(name) + _build(database, table).run() + node = _build(database, table).nodes["double"] + loaded = node._load_cached_entries() # pyright: ignore[reportPrivateUsage] # the stored hits under test + assert loaded + for _, data in loaded.values(): + assert isinstance(data, Data) + rebuilt = _rebuilt(data, data.datagram_uuid) + for got, expected in zip(_views(data), _views(rebuilt), strict=True): + if hasattr(got, "equals"): + assert got.equals(expected, check_metadata=True) + else: + assert got == expected From b9f987905c3c1da3fa59dda4acf81a5da059d732 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 05:36:45 -0800 Subject: [PATCH 28/86] fix(pipeline): channels check source-info types as tokens; no new import cycle (ITL-1360) A source-info column's type follows its tokens over the complete table, so a channel's batch check (record_batch_channels._schema_mismatch) takes any token type there, as it takes any nullability; the channels test that pinned F's old empty-list exception is an equality test. The side-effect node builds its output stream through function_node.rows_as_output_stream instead of importing the operator module, which closed a new import cycle with the record-batch protocol module. Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/nodes/function_node.py | 22 ++++++++++++++++ src/orcapod/core/record_batch_channels.py | 25 ++++++++++++++++++- src/orcapod/side_effects.py | 17 ++++++------- .../operators/test_record_batch_execution.py | 22 ++++++---------- 4 files changed, 62 insertions(+), 24 deletions(-) diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 60d6dc365..de4920088 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -282,6 +282,28 @@ def _with_datagram_id(data: Data, datagram_id: uuid.UUID) -> Data: ) +def rows_as_output_stream( + rows: Sequence[tuple[TagProtocol, DataProtocol]], node: StreamProtocol +) -> StreamProtocol: + """Return ``rows`` as ``node``'s output stream, as the sync orchestrator built it. + + ``StaticOutputOperatorPod._materialize_upstream``, for the job nodes whose output is + still their rows (function and side-effect nodes, until ITL-1347 stages 3 and 4): + the rows' table with the node's identity, or its zero-row input with no row. One + place imports the operator module for them. + + Args: + rows: The node's output rows, in order. + node: The node. + + Returns: + The node's output stream. + """ + from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod + + return StaticOutputOperatorPod._materialize_upstream(rows, node) # pyright: ignore[reportPrivateUsage] # the one definition of a rebuilt upstream + + def _executor_supports_concurrent( data_function: DataFunctionProtocol, ) -> bool: diff --git a/src/orcapod/core/record_batch_channels.py b/src/orcapod/core/record_batch_channels.py index a6f5e57ab..8b258b5b1 100644 --- a/src/orcapod/core/record_batch_channels.py +++ b/src/orcapod/core/record_batch_channels.py @@ -563,7 +563,10 @@ def _schema_mismatch(declared: pa.Schema, batch: pa.RecordBatch) -> str | None: ``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``). + follows the values of the complete table (``_flag_by_values``). Nor is a + source-info column's type, which follows its tokens over the complete table + (``_type_source_info_by_values``): it must only be a token type (``large_string``, + or ``large_list`` of a token type). """ sent = batch.schema if declared.names != sent.names: @@ -571,6 +574,14 @@ def _schema_mismatch(declared: pa.Schema, batch: pa.RecordBatch) -> str | None: 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.name.startswith(constants.SOURCE_PREFIX): + if not _is_token_type(column.type): + return f"column {column.name!r} is {column.type}, not a token type" + 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 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( @@ -603,6 +614,18 @@ def _schema_mismatch(declared: pa.Schema, batch: pa.RecordBatch) -> str | None: return None +def _is_token_type(kind: pa.DataType) -> bool: + """Whether ``kind`` is a source-info token type: ``large_string``, or a list of one. + + The types ``arrow_utils.source_info_arrow_type`` gives a token. + """ + if pa.types.is_large_string(kind): + return True + if isinstance(kind, pa.LargeListType): + return _is_token_type(kind.value_type) # pyright: ignore[reportUnknownArgumentType, reportUnknownMemberType] + return False + + def _without_metadata(kind: pa.DataType) -> pa.DataType: """``kind`` with the field metadata of every nested field removed.""" if isinstance(kind, pa.LargeListType): diff --git a/src/orcapod/side_effects.py b/src/orcapod/side_effects.py index 81a834fc2..071aa82ac 100644 --- a/src/orcapod/side_effects.py +++ b/src/orcapod/side_effects.py @@ -20,7 +20,11 @@ from orcapod.core.base import TraceableBase from orcapod.core.nodes.staleness import RunHoldingNode -from orcapod.core.nodes.function_node import _build_record_id_preimage, run_job_node +from orcapod.core.nodes.function_node import ( + _build_record_id_preimage, + rows_as_output_stream, + run_job_node, +) from orcapod.core.streams.base import ( StreamBase, check_head_size, @@ -1274,17 +1278,12 @@ def _output_stream( """The output stream of a run that passed ``rows`` on. What the sync orchestrator built from a node's rows for its successors - (``StaticOutputOperatorPod._materialize_upstream``). + (``StaticOutputOperatorPod._materialize_upstream``, through + ``rows_as_output_stream``). """ - from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod - - # A side-effect job node is a stream (``StreamBase``) that the checker cannot - # match against the protocol through its mixins. # A side-effect job node is a ``StreamBase``; the checker cannot match its # mixin members against ``StreamProtocol``, so the cast goes through object. - return StaticOutputOperatorPod._materialize_upstream( - rows, cast("StreamProtocol", cast(object, self)) - ) + return rows_as_output_stream(rows, cast("StreamProtocol", cast(object, self))) def _deliver_rows( self, input_stream: StreamProtocol, *, run_id: str | None diff --git a/tests/test_core/operators/test_record_batch_execution.py b/tests/test_core/operators/test_record_batch_execution.py index c47c11a3c..beddb5ece 100644 --- a/tests/test_core/operators/test_record_batch_execution.py +++ b/tests/test_core/operators/test_record_batch_execution.py @@ -592,15 +592,11 @@ def _schema_outcome(make: Callable[[], StreamProtocol]) -> tuple[str, Any]: @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.""" +def test_empty_source_info_lists_are_typed_from_their_tokens(layout: str) -> None: + """A raw stream whose source-info column is a nested list type holding only empty + lists: the channel's result equals the job's sync path, both typing the tokens from + their values over the complete table (``_type_source_info_by_values``), as the rows + do: one list level, not the column's two.""" raw = ArrowTableStream( pa.table( { @@ -618,11 +614,9 @@ def test_empty_source_info_lists_are_outside_the_row_built_forms_domain( 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()) + assert got.to_pylist() == rebuilt.to_pylist() + assert got.schema.equals(rebuilt.schema) + assert got.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: From 1319a77bd2754b5c638c019fcc3f3d1a919ebac4 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 05:39:51 -0800 Subject: [PATCH 29/86] perf(side_effects): a side-effect node hands on its input table at the rows passed on (ITL-1361, stage 4) A side-effect job node passes its input rows on unchanged, or drops those whose delivery failed. Its output stream is F of the input's table taken at the positions of the rows passed on (function_node.passed_rows_output_stream), instead of the table rebuilt from those rows; a load-only run hands on the whole input. Other input kinds take the row path. L4 test over the several-items arrangements, dropping and keeping, run and load-only. Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/nodes/function_node.py | 40 ++++++++ src/orcapod/side_effects.py | 36 ++++--- .../test_side_effect_output_table.py | 98 +++++++++++++++++++ 3 files changed, 161 insertions(+), 13 deletions(-) create mode 100644 tests/test_pipeline/test_side_effect_output_table.py diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 1f505be7c..accdc1e8e 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -322,6 +322,46 @@ def rows_as_output_stream( return StaticOutputOperatorPod._materialize_upstream(rows, node) # pyright: ignore[reportPrivateUsage] # the one definition of a rebuilt upstream +def passed_rows_output_stream( + input_stream: StreamProtocol, + rows: Sequence[tuple[TagProtocol, DataProtocol]], + passed: Sequence[int] | None, + node: StreamProtocol, +) -> StreamProtocol: + """Return the output stream of a node that passes on some of its input rows. + + ``rows`` are input rows themselves (a side-effect node passes a row on unchanged), + so for an input over an Arrow table the output is F of the input's table taken at + the rows' positions (``passed``; all rows when ``None``), with ``node``'s identity: + the table a row-by-row rebuild of ``rows`` gives (``rows_as_output_stream``), made + without making the rows again (ITL-1361, stage 4). Any other input takes the row + path. + + Args: + input_stream: The node's input. + rows: The rows passed on, in order. + passed: Their positions in ``input_stream``, or ``None`` for every row. + node: The node. + + Returns: + The node's output stream. + """ + from orcapod.core.operators.static_output_pod import ( + SourceInfoTypesDisagree, + StaticOutputOperatorPod, + ) + + if not rows or not isinstance(input_stream, ArrowTableStream): + return StaticOutputOperatorPod._materialize_upstream(rows, node) # pyright: ignore[reportPrivateUsage] # the one definition of a rebuilt upstream + table = input_stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS) + if passed is not None: + table = table.take(pa.array(passed, type=pa.int64())) + try: + return StaticOutputOperatorPod._output_stream(table, input_stream.keys(), node) # pyright: ignore[reportPrivateUsage] # F with the node's identity + except SourceInfoTypesDisagree as error: + StaticOutputOperatorPod._raise_as_rows_do(rows, error) # pyright: ignore[reportPrivateUsage] # the rows' own error + + def _executor_supports_concurrent( data_function: DataFunctionProtocol, ) -> bool: diff --git a/src/orcapod/side_effects.py b/src/orcapod/side_effects.py index 071aa82ac..024534983 100644 --- a/src/orcapod/side_effects.py +++ b/src/orcapod/side_effects.py @@ -22,7 +22,7 @@ from orcapod.core.nodes.staleness import RunHoldingNode from orcapod.core.nodes.function_node import ( _build_record_id_preimage, - rows_as_output_stream, + passed_rows_output_stream, run_job_node, ) from orcapod.core.streams.base import ( @@ -1261,37 +1261,46 @@ def execute( self.clear_cache() raise self._hold(rows, load_only=True) - return self._output_stream(rows) + return self._output_stream(input_stream, rows, None) try: - results = self._deliver_rows(input_stream, run_id=run_id) + results, passed = self._deliver_rows(input_stream, run_id=run_id) except BaseException: # A run that raised defines no rows: the node is stale, and so is every # node below it (ITL-1095). self.clear_cache() raise self._hold(results) - return self._output_stream(results) + return self._output_stream(input_stream, results, passed) def _output_stream( - self, rows: list[tuple[TagProtocol, DataProtocol]] + self, + input_stream: StreamProtocol, + rows: list[tuple[TagProtocol, DataProtocol]], + passed: list[int] | None, ) -> StreamProtocol: """The output stream of a run that passed ``rows`` on. - What the sync orchestrator built from a node's rows for its successors - (``StaticOutputOperatorPod._materialize_upstream``, through - ``rows_as_output_stream``). + What the sync orchestrator built from a node's rows for its successors: F of + the input's table at the rows' positions (``passed_rows_output_stream``). """ # A side-effect job node is a ``StreamBase``; the checker cannot match its # mixin members against ``StreamProtocol``, so the cast goes through object. - return rows_as_output_stream(rows, cast("StreamProtocol", cast(object, self))) + return passed_rows_output_stream( + input_stream, rows, passed, cast("StreamProtocol", cast(object, self)) + ) def _deliver_rows( self, input_stream: StreamProtocol, *, run_id: str | None - ) -> list[tuple[TagProtocol, DataProtocol]]: - """Deliver every row of ``input_stream``; return the rows passed on.""" + ) -> tuple[list[tuple[TagProtocol, DataProtocol]], list[int]]: + """Deliver every row of ``input_stream``. + + Returns: + The rows passed on, and their positions in ``input_stream``. + """ self._refuse_log_of_another_data_context() results: list[tuple[TagProtocol, DataProtocol]] = [] - for tag, data in input_stream.iter_data(): + passed: list[int] = [] + for index, (tag, data) in enumerate(input_stream.iter_data()): result = _execute_side_effect_row( fn=self._pod._fn, tag=tag, @@ -1308,7 +1317,8 @@ def _deliver_rows( ) if result is not None: results.append(result) - return results + passed.append(index) + return results, passed def _hold( self, rows: list[tuple[TagProtocol, DataProtocol]], *, load_only: bool = False diff --git a/tests/test_pipeline/test_side_effect_output_table.py b/tests/test_pipeline/test_side_effect_output_table.py new file mode 100644 index 000000000..7dc7b7b83 --- /dev/null +++ b/tests/test_pipeline/test_side_effect_output_table.py @@ -0,0 +1,98 @@ +"""A side-effect node's output is its input table at the rows it passed on (ITL-1361, L4). + +A side-effect job node passes its input rows on unchanged (or drops the ones whose +delivery failed). Its output stream is F of the input's Arrow table taken at the rows' +positions (``passed_rows_output_stream``), instead of the table rebuilt from the rows. +It must equal the rebuild (``StaticOutputOperatorPod._materialize_upstream`` of the +rows passed on) in identity and in every column group, for every arrangement of the +several-items family, with rows dropped and with none, and on a load-only run. +""" + +from __future__ import annotations + +import warnings +from typing import Any + +import pytest + +from orcapod import PipelineJob +from orcapod.databases import InMemoryArrowDatabase +from orcapod.errors import ProvisionalHashWarning +from orcapod.side_effects import SideEffectJobNode, SideEffectPodConfig, side_effect_pod +from tests.test_core.operators.several_items import MAIN, arrangements, make_source +from tests.test_pipeline.test_stream_transport_equivalence import ( + _rebuilt, # pyright: ignore[reportPrivateUsage] # the row rebuild these tests share + assert_same_stream, +) + + +def _drop_odd(d1: int, ctx: Any) -> None: + """Fail the delivery of every other row (``d1`` is 10, 20, ...): the row is dropped.""" + if (d1 // 10) % 2: + raise ValueError("odd") + + +_DROPPING = side_effect_pod( + _drop_odd, + config=SideEffectPodConfig( + track_completion=False, drop_on_failure=True, on_error="log" + ), +) + + +def _keep_all(d1: int, ctx: Any) -> None: + """Deliver every row.""" + return None + + +_KEEPING = side_effect_pod( + _keep_all, config=SideEffectPodConfig(track_completion=False, on_error="log") +) + + +@pytest.fixture +def side_effect_outputs(monkeypatch: pytest.MonkeyPatch) -> list[tuple[Any, Any]]: + """Each side-effect node's output, with the rows it held, as ``execute`` gave it.""" + seen: list[tuple[Any, Any]] = [] + original = SideEffectJobNode.execute + + def execute(self: Any, *args: Any, **kwargs: Any) -> Any: + out = original(self, *args, **kwargs) + seen.append((out, list(self._held_rows or []))) # pyright: ignore[reportPrivateUsage] # the rows the run passed on + return out + + monkeypatch.setattr(SideEffectJobNode, "execute", execute) + return seen + + +@pytest.mark.parametrize("load_only", [False, True], ids=["run", "load_only"]) +@pytest.mark.parametrize("pod", [_DROPPING, _KEEPING], ids=["dropping", "keeping"]) +@pytest.mark.parametrize("arrangement", arrangements(MAIN), ids=lambda a: a.id) +def test_the_output_is_the_rebuild_of_the_rows_passed_on( + arrangement: Any, + pod: Any, + load_only: bool, + side_effect_outputs: list[tuple[Any, Any]], +) -> None: + """L4: the output equals the rows passed on, rebuilt with the node's identity.""" + database = InMemoryArrowDatabase() + with warnings.catch_warnings(): + warnings.simplefilter("ignore", ProvisionalHashWarning) + source = make_source(MAIN, arrangement) + job = PipelineJob(name="side_effect_output", database=database) + with job: + delivered: Any = pod + delivered(source.select_data_columns(["d1"]), label="delivered") + if load_only: + job.run() + # A node holding a current run is not run again: clear it. + job.nodes["delivered"].clear_cache() + side_effect_outputs.clear() + job.run(load_only=load_only) + assert side_effect_outputs + node = job.nodes["delivered"] + for out, rows in side_effect_outputs: + assert_same_stream(out, _rebuilt(rows, node)) + if pod is _DROPPING and not load_only: + _, rows = side_effect_outputs[-1] + assert 0 < len(rows) < len(list(source.iter_data())) From bdb9a39ee7e6dbfc15d99538e0726e6f8c14868e Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 05:46:45 -0800 Subject: [PATCH 30/86] perf(function_node): output rows of stored results taken from their table (ITL-1361, stage 3) A function node keeps the table of the stored results it loads and each loaded result's position in it. Its output stream is built from pieces in the rows' order: runs of stored results taken from that table (row-built columns), the other rows built from their datagrams, concatenated by name in the first piece's order, then F's whole-table steps. A row whose result was replaced since is not found (positions are kept by object). Any piece that cannot be concatenated falls back to the rows' own build, which raises what it raises. L3 test against the rebuild of every output row: arrangements, stored and computed interleaved, None results, duplicate inputs. Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/nodes/function_node.py | 123 +++++++++++++++++- .../test_function_output_table.py | 117 +++++++++++++++++ 2 files changed, 237 insertions(+), 3 deletions(-) create mode 100644 tests/test_pipeline/test_function_output_table.py diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index accdc1e8e..8d7eb0cb7 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -40,6 +40,7 @@ with_fall_through, ) from orcapod.core.data_tags import ( + data_tag_names, mark_data_tags, require_database_keeps_marker, stored_data_tags, @@ -54,6 +55,7 @@ ZERO_ROW_INPUT_COLUMNS, StreamBase, check_head_size, + row_built_columns, short_stream_repr, ) from orcapod.core.streams.view import ( @@ -362,6 +364,27 @@ def passed_rows_output_stream( StaticOutputOperatorPod._raise_as_rows_do(rows, error) # pyright: ignore[reportPrivateUsage] # the rows' own error +class _StoredHitTable(NamedTuple): + """The table of stored results a node loaded, and its stream's keys (ITL-1361).""" + + table: "pa.Table" + keys: tuple[tuple[str, ...], tuple[str, ...]] + + +def _provenance_nullable(table: "pa.Table") -> "pa.Table": + """``table`` with every system-tag and source-info field nullable. + + Pieces of one output are concatenated before F's last step flags these fields by + the values of the complete table; until then a piece's flags follow its own values. + """ + prefixes = (constants.SYSTEM_TAG_PREFIX, constants.SOURCE_PREFIX) + fields = [ + field.with_nullable(True) if field.name.startswith(prefixes) else field + for field in table.schema + ] + return pa.Table.from_arrays(table.columns, schema=pa.schema(fields)) + + def _executor_supports_concurrent( data_function: DataFunctionProtocol, ) -> bool: @@ -1508,6 +1531,8 @@ def __init__( self._cached_output_table: "pa.Table | None" = None self._cached_content_hash_column: "pa.Array | None" = None self._run_entry_counts = None + self._stored_hit_tables: list[_StoredHitTable] = [] + self._stored_hit_positions: dict[int, tuple[DataProtocol, int, int]] = {} # DB persistence state (initially None; set via __init__ params or attach_databases) self._pipeline_database: ArrowDatabaseProtocol | None = None @@ -1935,6 +1960,8 @@ def from_descriptor( node._cached_output_datas = {} node._cached_output_table = None node._cached_content_hash_column = None + node._stored_hit_tables = [] + node._stored_hit_positions = {} # FunctionJobNode — orchestrator config node._node_config = NodeConfig() @@ -1986,6 +2013,8 @@ def clear_cache(self) -> None: self._cached_output_datas.clear() self._cached_output_table = None self._cached_content_hash_column = None + self._stored_hit_tables = [] + self._stored_hit_positions = {} self._run_entry_counts = None self._run_load_only = False self._run_not_stored = 0 @@ -2545,6 +2574,9 @@ def _output_stream( from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod try: + output = self._output_from_stored_tables(rows) + if output is not None: + return output return StaticOutputOperatorPod._materialize_upstream(rows, self) except pa.ArrowInvalid: # Rows that disagree on a column's Arrow type (cached rows of a store @@ -2553,6 +2585,77 @@ def _output_stream( self._table_from_pairs(rows) raise + def _output_from_stored_tables( + self, rows: list[tuple[TagProtocol, DataProtocol]] + ) -> StreamProtocol | None: + """Return the output stream of ``rows``, taking stored results from their table. + + What ``_materialize_upstream`` builds from ``rows``, without building again the + rows of results read from the store: those are taken from the stored rows' + table (in its row-built form, ``row_built_columns``), and the other rows are + built from their datagrams (``_rows_to_table``). The pieces, in the rows' order, + are concatenated by name in the first piece's column order, as the rows are in + the first row's order, then F's steps on the complete table type the source + info and flag the provenance fields by their values (ITL-1361). + + Returns: + The output stream, or ``None`` when no row is a stored result, or when the + pieces cannot be concatenated: the rows' own build then gives the stream, + or raises what it raises. + """ + from orcapod.core.operators.static_output_pod import ( + SourceInfoTypesDisagree, + StaticOutputOperatorPod, + ) + + pieces: list[ + tuple[int, list[int]] | list[tuple[TagProtocol, DataProtocol]] + ] = [] + any_stored = False + for tag, data in rows: + position = self._stored_hit_positions.get(id(data)) + if position is not None and position[0] is data: + any_stored = True + _, table_index, row = position + last = pieces[-1] if pieces else None + if isinstance(last, tuple) and last[0] == table_index: + last[1].append(row) + else: + pieces.append((table_index, [row])) + else: + last = pieces[-1] if pieces else None + if isinstance(last, list): + last.append((tag, data)) + else: + pieces.append([(tag, data)]) + if not any_stored: + return None + tables: list[pa.Table] = [] + try: + for piece in pieces: + if isinstance(piece, tuple): + stored = self._stored_hit_tables[piece[0]] + table = row_built_columns(stored.table, stored.keys).take( + pa.array(piece[1], type=pa.int64()) + ) + else: + table = StaticOutputOperatorPod._rows_to_table(piece)[0] # pyright: ignore[reportPrivateUsage] # the rows' own build + table = StaticOutputOperatorPod._type_source_info_by_values(table) # pyright: ignore[reportPrivateUsage] # F's whole-table step, per piece + tables.append(_provenance_nullable(table)) + combined = arrow_utils.concat_tables_by_name(tables) + formed = StaticOutputOperatorPod._flag_by_values( # pyright: ignore[reportPrivateUsage] # F's whole-table steps + StaticOutputOperatorPod._type_source_info_by_values(combined) # pyright: ignore[reportPrivateUsage] + ) + except (pa.ArrowInvalid, SourceInfoTypesDisagree): + return None + first_tag, first_data = rows[0] + return StaticOutputOperatorPod._as_upstream_stream( # pyright: ignore[reportPrivateUsage] # the node's identity + formed, + tuple(first_tag.keys()), + data_tag_names(first_tag.keys(), first_data.keys()), + self, + ) + def execute_data( self, tag: TagProtocol, @@ -3940,12 +4043,26 @@ def _load_cached_entries( stored = self._stored_rows_stream(fetched) if stored is not None: base_entry_ids_col, stream, data_ids = stored - for base_eid, data_id, (tag, data) in zip( - base_entry_ids_col, data_ids, stream.iter_data(), strict=True + # The stored rows' table, so an output of these results is taken from it + # instead of being built again from their datagrams (ITL-1361). + table_index = len(self._stored_hit_tables) + self._stored_hit_tables.append( + _StoredHitTable( + stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS), stream.keys() + ) + ) + for row, (base_eid, data_id, (tag, data)) in enumerate( + zip(base_entry_ids_col, data_ids, stream.iter_data(), strict=True) ): # A stored result is the datagram its own provenance names: it # carries the stored ``__data_id`` as its datagram id (ITL-1060). - loaded[base_eid] = (tag, _with_datagram_id(data, data_id)) + stored_data = _with_datagram_id(data, data_id) + loaded[base_eid] = (tag, stored_data) + self._stored_hit_positions[id(stored_data)] = ( + stored_data, + table_index, + row, + ) # --- Process EmptyData tokens (ephemeral misses) --- for base_eid, empty_data in fetched.empty_data_tokens.items(): diff --git a/tests/test_pipeline/test_function_output_table.py b/tests/test_pipeline/test_function_output_table.py new file mode 100644 index 000000000..6224fdb48 --- /dev/null +++ b/tests/test_pipeline/test_function_output_table.py @@ -0,0 +1,117 @@ +"""A function node's output takes stored results from their table (ITL-1361, L3). + +``FunctionJobNode._output_stream`` builds its output from pieces: the rows of results +read from the store are taken from the stored rows' table, the others are built from +their datagrams, and F's whole-table steps finish the table. It must equal the table +rebuilt from every output row (``StaticOutputOperatorPod._materialize_upstream``), in +identity and in every column group, whatever mix of stored and computed rows a run has: +all stored, none stored, interleaved, duplicate inputs, a function returning ``None``, +over the several-items arrangements (tag orders, layouts, data-tags). +""" + +from __future__ import annotations + +import warnings +from typing import Any + +import pytest + +from orcapod import PipelineJob, function_pod +from orcapod.core.nodes.function_node import FunctionJobNode +from orcapod.databases import InMemoryArrowDatabase +from orcapod.errors import ProvisionalHashWarning +from tests.test_core.operators.several_items import MAIN, arrangements, make_source +from tests.test_pipeline.test_stream_transport_equivalence import ( + _rebuilt, # pyright: ignore[reportPrivateUsage] # the row rebuild these tests share + assert_same_stream, +) + + +@function_pod(output_keys="half") +def halved(d1: int) -> int | None: + """``d1 / 10`` for an even tenth, ``None`` (no output row) otherwise.""" + return d1 // 10 if (d1 // 10) % 2 == 0 else None + + +@function_pod(output_keys="tripled") +def tripled(d1: int) -> int: + return 3 * d1 + + +@pytest.fixture +def compared(monkeypatch: pytest.MonkeyPatch) -> list[int]: + """Check every function node output against the rebuild of its rows.""" + checked: list[int] = [] + original = FunctionJobNode._output_stream # pyright: ignore[reportPrivateUsage] # under test + + def output_stream(self: Any, rows: list[Any]) -> Any: + out = original(self, rows) + assert_same_stream(out, _rebuilt(rows, self)) + checked.append(len(rows)) + return out + + monkeypatch.setattr(FunctionJobNode, "_output_stream", output_stream) + return checked + + +def _job(source: Any, pod: Any, database: Any) -> PipelineJob: + job = PipelineJob(name="function_output", database=database) + with job: + pod.pod(source.select_data_columns(["d1"]), label="fn") + return job + + +@pytest.mark.parametrize("pod", [tripled, halved], ids=["every_row", "some_none"]) +@pytest.mark.parametrize("arrangement", arrangements(MAIN), ids=lambda a: a.id) +def test_the_output_is_the_rebuild_of_its_rows( + arrangement: Any, pod: Any, compared: list[int] +) -> None: + """Computed, then stored and computed, then all stored.""" + database = InMemoryArrowDatabase() + with warnings.catch_warnings(): + warnings.simplefilter("ignore", ProvisionalHashWarning) + # First the first three rows (same positional record ids as in the full + # source): the full run then takes them from the store and computes the rest. + _job(make_source(MAIN, arrangement, rows=[0, 1, 2]), pod, database).run() + _job(make_source(MAIN, arrangement), pod, database).run() + _job(make_source(MAIN, arrangement), pod, database).run() + assert len(compared) == 3 + + +def _keyed(keys: list[int]) -> Any: + """Rows keyed by ``j`` (``record_id_columns``), so a subset keeps its record ids.""" + from orcapod.sources import DictSource + + return DictSource( + [{"k": j % 3, "j": j, "d1": 10 * j} for j in keys], + tag_columns=["k", "j"], + record_id_columns=["j"], + tag_only_columns=True, + source_id="keyed", + ) + + +@pytest.mark.parametrize("pod", [tripled, halved], ids=["every_row", "some_none"]) +def test_stored_and_computed_rows_interleave(pod: Any, compared: list[int]) -> None: + """Every other row stored: the output alternates stored and computed rows.""" + database = InMemoryArrowDatabase() + _job(_keyed([0, 2, 4, 6]), pod, database).run() + _job(_keyed(list(range(8))), pod, database).run() + _job(_keyed([7, 6, 5, 4, 3, 2, 1, 0]), pod, database).run() + assert len(compared) == 3 + + +def test_duplicate_inputs_give_one_row_each(compared: list[int]) -> None: + """Two equal inputs are two output rows, both from the store on a warm run.""" + from orcapod.sources import DictSource + + database = InMemoryArrowDatabase() + source = DictSource( + [{"k": i % 2, "j": i, "d1": 10 * (i % 2)} for i in range(4)], + tag_columns=["k", "j"], + tag_only_columns=True, + source_id="duplicates", + ) + _job(source, tripled, database).run() + _job(source, tripled, database).run() + assert compared == [4, 4] From 31b9cc1c342e51d489797f517cfb7a35e323ffa0 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 05:51:43 -0800 Subject: [PATCH 31/86] perf(function_node): input rows are views made only when read (ITL-1361, stage 3) For an input over an Arrow table, a function node's input rows are row views (_RowView over _LazyRows): every attribute is the row's datagram, made on the first read. The observers a job installs read no input row, so a run over stored results makes none; a row whose function runs is processed as its datagram. Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/nodes/function_node.py | 93 ++++++++++++++++++++++--- 1 file changed, 84 insertions(+), 9 deletions(-) diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 8d7eb0cb7..29f1b5fb2 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -364,6 +364,78 @@ def passed_rows_output_stream( StaticOutputOperatorPod._raise_as_rows_do(rows, error) # pyright: ignore[reportPrivateUsage] # the rows' own error +class _LazyRows: + """A stream's rows, made on the first read of any of them (ITL-1361). + + A run over stored results reads no input row's values: it passes the rows to the + observers only. The rows are made once, when one is first read. + """ + + def __init__(self, stream: StreamProtocol) -> None: + self._stream = stream + self._rows: list[tuple[TagProtocol, DataProtocol]] | None = None + + def get(self) -> list[tuple[TagProtocol, DataProtocol]]: + """The stream's rows, made on the first call.""" + if self._rows is None: + self._rows = list(self._stream.iter_data()) + return self._rows + + +class _RowView: + """One input row's tag or data, made only when it is read (``RowView`` in the spec). + + Every attribute is the datagram's: the first read makes the input's rows + (``_LazyRows``). The observers a job installs read no input row, so a run over + stored results makes none (ITL-1361). + """ + + __slots__ = ("_index", "_part", "_rows") + + def __init__(self, rows: _LazyRows, index: int, part: int) -> None: + self._rows = rows + self._index = index + self._part = part + + def datagram(self) -> Any: + """The row's datagram (its tag for part 0, its data for part 1).""" + return self._rows.get()[self._index][self._part] + + def __getattr__(self, name: str) -> Any: + return getattr(self.datagram(), name) + + def __getitem__(self, key: Any) -> Any: + return self.datagram()[key] + + def __iter__(self) -> Iterator[Any]: + return iter(self.datagram()) + + def __len__(self) -> int: + return len(self.datagram()) + + def __contains__(self, key: object) -> bool: + return key in self.datagram() + + def __eq__(self, other: object) -> bool: + if isinstance(other, _RowView): + other = other.datagram() + return bool(self.datagram() == other) + + def __hash__(self) -> int: + return hash(self.datagram()) + + def __repr__(self) -> str: + return repr(self.datagram()) + + def __str__(self) -> str: + return str(self.datagram()) + + +def _datagram(value: Any) -> Any: + """The datagram behind a ``_RowView``, or ``value`` itself.""" + return value.datagram() if isinstance(value, _RowView) else value + + class _StoredHitTable(NamedTuple): """The table of stored results a node loaded, and its stream's keys (ITL-1361).""" @@ -2785,8 +2857,8 @@ def execute( pkt_logger = ctx_obs.create_data_logger(tag, data) try: tag_out, result = self._process_data_internal( - tag, - data, + _datagram(tag), + _datagram(data), logger=pkt_logger, run_id=run_id, base_entry_id=base_entry_id, @@ -3233,7 +3305,8 @@ def _input_entries( field flags set by their values as a row's are (``_flag_by_values``), and the input data hash is ``hash_table`` of its data columns, which is the data datagram's content hash (``Datagram.identity_structure``). The same ids, - without building each row's tables (ITL-1361). + without building each row's tables (ITL-1361). The rows are then views + (``_RowView``), made only when one is read. Args: input_stream: The node's input. @@ -3243,13 +3316,15 @@ def _input_entries( """ from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod - rows = list(input_stream.iter_data()) - if not rows or not isinstance(input_stream, ArrowTableStream): + if not isinstance(input_stream, ArrowTableStream): return [ - (tag, data, self.compute_base_entry_id(tag, data)) for tag, data in rows + (tag, data, self.compute_base_entry_id(tag, data)) + for tag, data in input_stream.iter_data() ] tag_keys, data_keys = input_stream.keys() table = input_stream.as_table(columns={"system_tags": True}) + # The rows themselves are made only when one is read (``_RowView``). + lazy = _LazyRows(input_stream) system_tags = [ name for name in table.column_names @@ -3262,8 +3337,8 @@ def _input_entries( hasher = self.data_context.arrow_hasher return [ ( - tag, - data, + cast(TagProtocol, _RowView(lazy, index, 0)), + cast(DataProtocol, _RowView(lazy, index, 1)), hasher.hash_table( _with_input_data_hash( tag_side.slice(index, 1), @@ -3271,7 +3346,7 @@ def _input_entries( ) ).to_prefixed_digest(), ) - for index, (tag, data) in enumerate(rows) + for index in range(table.num_rows) ] def compute_pipeline_entry_id( From f072298428961fe8b5c5a4a8386cef99c2a9db2a Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 05:51:58 -0800 Subject: [PATCH 32/86] test(function_node): an observer reading row views sees the input rows (ITL-1361) Co-Authored-By: Claude Opus 5.5 --- .../test_function_output_table.py | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/tests/test_pipeline/test_function_output_table.py b/tests/test_pipeline/test_function_output_table.py index 6224fdb48..5caea3c05 100644 --- a/tests/test_pipeline/test_function_output_table.py +++ b/tests/test_pipeline/test_function_output_table.py @@ -20,6 +20,7 @@ from orcapod.core.nodes.function_node import FunctionJobNode from orcapod.databases import InMemoryArrowDatabase from orcapod.errors import ProvisionalHashWarning +from orcapod.pipeline.observer import NoOpObserver from tests.test_core.operators.several_items import MAIN, arrangements, make_source from tests.test_pipeline.test_stream_transport_equivalence import ( _rebuilt, # pyright: ignore[reportPrivateUsage] # the row rebuild these tests share @@ -115,3 +116,37 @@ def test_duplicate_inputs_give_one_row_each(compared: list[int]) -> None: _job(source, tripled, database).run() _job(source, tripled, database).run() assert compared == [4, 4] + + +class _ReadsRows(NoOpObserver): + """Records every input row an observer is shown, as its values.""" + + def __init__(self) -> None: + self.rows: list[tuple[Any, Any]] = [] + + def contextualize(self, *identity_path: str) -> _ReadsRows: + return self + + def on_data_start(self, node_label: str, tag: Any, data: Any) -> None: + self.rows.append( + (tag.as_dict(all_info=True), data.as_dict(columns={"source": True})) + ) + + +def test_an_observer_reading_the_input_rows_sees_them(compared: list[int]) -> None: + """On a run over stored results, the rows an observer reads are the input's rows. + + The node shows its observers views of its input rows (``_RowView``), made when + read; their values are the rows' own. + """ + database = InMemoryArrowDatabase() + source = _keyed(list(range(6))) + _job(source, tripled, database).run() + job = _job(source, tripled, database) + observer = _ReadsRows() + job.run(observer=observer) + expected = [ + (tag.as_dict(all_info=True), data.as_dict(columns={"source": True})) + for tag, data in source.select_data_columns(["d1"]).iter_data() + ] + assert observer.rows == expected From 7599ba72391b2bf29021615206abcfe5bbadb749 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 05:52:08 -0800 Subject: [PATCH 33/86] docs(changelog): ITL-1361 fragment Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1361.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 changelog.d/ITL-1361.md diff --git a/changelog.d/ITL-1361.md b/changelog.d/ITL-1361.md new file mode 100644 index 000000000..c3e6fee0e --- /dev/null +++ b/changelog.d/ITL-1361.md @@ -0,0 +1,12 @@ +### Changed + +- **Function and side-effect job nodes work on their input's Arrow table** — on the sync + path, a function job node takes each input row's entry id from slices of its input's + table (the tag side with its system tags, and the hash of the data columns) instead of + tables built from the row's values; shows its observers views of its input rows, made + only when read; gives a stored result the id it was stored under by a shallow copy; + and builds its output with the rows of stored results taken from the stored table. A + side-effect job node hands on its input's table at the rows it passed on. Every + output, stored row, entry id, observer event and error is as before. Third and fourth + stages of the table transport between job nodes + (`docs/dev/specs/itl-1347-job-table-transport.md`). (ITL-1361) From ea5fbd79e807c41b39acbb54a84e2667c0a1aef5 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 06:00:38 -0800 Subject: [PATCH 34/86] feat(operators): streaming join kernels for Join, MergeJoin and SemiJoin on Arrow record batches (ITL-1362) (#482) * feat(operators): streaming join kernels for Join, MergeJoin and SemiJoin on Arrow record batches (ITL-1362) Vectorized symmetric hash joins for the async path (ITL-1347 stage 5, part "joins"), not yet wired into async_execute. A kernel is built from the operator and its input streams; push(input_index, record_batch) and close(input_index) return the output record batches. Key checks run before the first batch (the sync static_process over zero-row inputs, so the sync errors and messages, e1/ITL-856). Matching uses the sync join's prepared key frames, one Polars join per arriving batch; values are taken by row number. Join is a staggered chain in canonical order; MergeJoin is binary in argument order; SemiJoin streams its left input. No sync code path changes. Tests: tests/test_core/operators/test_streaming_joins.py (48), random batch cuts and interleavings compared with static_process as multisets with the same columns/types. Co-Authored-By: Claude Opus 5.5 * fix(operators): streaming joins match, type and hold as the sync path does (ITL-1362) Codex review round 1 of #482: - A null list, struct or decimal256 key matched another null. The kernel now matches by the sync join's own rule: the constant join key and Polars' inner join are one definition each (join._with_common_key, join._matched_pairs), used by Join, MergeJoin and the kernels (pure extractions of the sync code). - The kernel reads every input in its row-built form (F of the ITL-1347 spec: null as large_string), as a job's edges carry it: preflight, batch types and zero_row_result follow it. An input that ends empty is checked again in its zero-row form at the last close, as the sync path reads it. - System-tag flags, like source-info flags, are settled by values on the complete table: every emitted batch declares both nullable. - A refusal that depends on values (source-info token lists of different lengths) is raised when its batch arrives, with the sync error; documented. - A Join step that can never emit again releases its successor and every earlier step; SemiJoin never holds a left row with a top-level null key (semijoin._has_whole_key, shared with the sync path). Tests: the oracle is the sync operator over inputs rebuilt from rows; flags compared after settling both kinds; zero_row_result compared with the sync operator's own; null keys in the list and struct pools, a decimal256 pool, one and two shared keys. Co-Authored-By: Claude Opus 5.5 * test(operators): streaming join kernels in three arrangements; a rejected batch changes nothing (ITL-1362) CodeRabbit's review of #482 (round 1, with fe3f3214): the tag-role tests of Join, MergeJoin and SemiJoin run in three arrangements (declared and reversed tag order; tags first, data first reversed, interleaved layouts); a batch refused for one column leaves the kernel able to take the corrected batch. Docstrings for the input guard and Join's push and close hooks. Co-Authored-By: Claude Opus 5.5 * fix(operators): streaming Join keeps merging steps when a later input ends empty (ITL-1362) CodeRabbit's review of #482 at eb8d0261: when a later input in canonical order ends empty, the sync Join still merges the earlier inputs' data-tag source info (refusing token lists of different lengths) before it meets the empty input. The kernel released every earlier step; it now keeps the steps up to the last earlier one that merges source info matching, drops that step's output, and releases the rest. Only streaming_joins.py and its tests change; no sync file. Co-Authored-By: Claude Opus 5.5 * fix(operators): streaming join kernels, Codex review round 2 of #482 (ITL-1362) - An empty run whose empty input has a null column ends with the sync result's types: when no row was emitted, the last close's result over the inputs as they ended becomes zero_row_result. - A row whose key holds a top-level null is never held by a link, so a closed input holding only such rows is exhausted like an empty one. - Module docstring: the kernels' domain is what a job carries (no source takes a null-typed column); the first offending source-info pair observed is refused, which may depend on arrival; SemiJoin with no shared tag. - F is now the job-speed definition (streams.base.row_built_columns, StaticOutputOperatorPod._flag_by_values) instead of an interim copy. - Tests: an empty run's types; a source refuses a null-typed column; two schedules with several offending pairs; a closed input with only null keys; the multiset oracle compares temporal values as Arrow integers, with time64[ns] and timestamp[ns] key pools. Only streaming_joins.py and its tests change. Co-Authored-By: Claude Opus 5.5 * fix(operators): streaming joins skip key preparation for a closed empty side; tighter tests (ITL-1362) CodeRabbit's review of #482 at 251bb525: - A link returns before filtering and preparing keys when the other side has closed holding no row (nothing can pair, and nothing is held). - The several-offending-pairs test asserts the lengths of the pair each schedule exposes (1 and 2; 1 and 3), not only the message form. - The late-empty fixture gives every populated pair different lengths, so it refuses whatever the pipeline-hash order. - The multiset oracle compares temporal values at any depth (lists, structs) as their integers; a regression test. Only streaming_joins.py and its tests change. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Edgar Y. Walker <> Co-authored-by: Claude Opus 5.5 Co-authored-by: Edgar Y. Walker --- src/orcapod/core/operators/join.py | 59 +- src/orcapod/core/operators/merge_join.py | 21 +- src/orcapod/core/operators/semijoin.py | 28 +- src/orcapod/core/operators/streaming_joins.py | 998 +++++++++++++++ .../operators/test_streaming_joins.py | 1117 +++++++++++++++++ 5 files changed, 2195 insertions(+), 28 deletions(-) create mode 100644 src/orcapod/core/operators/streaming_joins.py create mode 100644 tests/test_core/operators/test_streaming_joins.py diff --git a/src/orcapod/core/operators/join.py b/src/orcapod/core/operators/join.py index 0f8afc2d6..aa7960a33 100644 --- a/src/orcapod/core/operators/join.py +++ b/src/orcapod/core/operators/join.py @@ -5,6 +5,7 @@ from collections.abc import Callable, Collection, Mapping, Sequence from typing import Any, ClassVar +import polars as pl import pyarrow as pa from orcapod.core.operators.meta_columns import ( @@ -63,6 +64,44 @@ _PENDING_MEMBERS = "\x00join-pending-members\x00" +# The constant key every join adds to both sides' keys (``_with_common_key``): with it, +# inputs that share no tag give every pair, and Polars applies its multi-key rule, under +# which a row whose key holds a top-level null matches nothing (a null list, struct or +# ``decimal256`` key too, which a single-key Polars join would match with another null). +_COMMON_JOIN_KEY = "_common" + + +def _with_common_key(table: "pa.Table") -> "pa.Table": + """Return ``table`` with the constant join key ``_COMMON_JOIN_KEY`` as its first column. + + ``int8`` explicitly, so a zero-row table gets no ``null``-typed column, which Polars + refuses in a join. + """ + return table.add_column( + 0, _COMMON_JOIN_KEY, pa.array([0] * len(table), type=pa.int8()) + ) + + +def _matched_pairs( + left: "pl.DataFrame", right: "pl.DataFrame", keys: Sequence[str] +) -> "pl.DataFrame": + """The pairs of rows a join matches: Polars' inner join of two key frames. + + The one statement of which rows a join pairs, for the sync join (``_inner_join``) + and the streaming kernels. ``keys`` holds ``_COMMON_JOIN_KEY`` and both frames hold + it (``_with_common_key``); the frames are ``arrow_keys.polars_key_frame``'s. + + Args: + left: The left key frame, with its row-number column. + right: The right key frame, with its row-number column. + keys: The key columns, ``_COMMON_JOIN_KEY`` among them. + + Returns: + One row per matched pair, holding both row-number columns. + """ + return left.join(right, on=list(keys), how="inner") + + def _inner_join(left: "pa.Table", right: "pa.Table", keys: list[str]) -> "pa.Table": """Inner-join two tables on their key columns, every value taken from the tables. @@ -84,8 +123,10 @@ def _inner_join(left: "pa.Table", right: "pa.Table", keys: list[str]) -> "pa.Tab The joined table. Its fields carry no flags of the inputs (every field nullable); the caller restores them. """ - pairs = polars_key_frame(left, keys, _LEFT_ROW).join( - polars_key_frame(right, keys, _RIGHT_ROW), on=keys, how="inner" + pairs = _matched_pairs( + polars_key_frame(left, keys, _LEFT_ROW), + polars_key_frame(right, keys, _RIGHT_ROW), + keys, ) left_rows = pairs.get_column(_LEFT_ROW).to_arrow() right_rows = pairs.get_column(_RIGHT_ROW).to_arrow() @@ -413,8 +454,6 @@ def static_process(self, *streams: StreamProtocol) -> StreamProtocol: # data column (meta columns are dropped, so they never collide). tag_schema, data_schema = self._joined_user_schemas(*streams) - COMMON_JOIN_KEY = "_common" - n_char = self.orcapod_config.hashing.system_tag_n_char stream = ordered_streams[0] @@ -428,9 +467,7 @@ def static_process(self, *streams: StreamProtocol) -> StreamProtocol: ) # trick to get cartesian product; use int8 explicitly so that zero-row # tables don't produce a null-typed column that Polars rejects on join - table = table.add_column( - 0, COMMON_JOIN_KEY, pa.array([0] * len(table), type=pa.int8()) - ) + table = _with_common_key(table) table = arrow_utils.append_to_system_tags( table, f"{stream.pipeline_hash().to_hex(n_char)}:0", @@ -448,9 +485,7 @@ def static_process(self, *streams: StreamProtocol) -> StreamProtocol: ) # trick to ensure that there will always be at least one shared key # this ensure that no overlap in keys lead to full caretesian product - next_table = next_table.add_column( - 0, COMMON_JOIN_KEY, pa.array([0] * len(next_table), type=pa.int8()) - ) + next_table = _with_common_key(next_table) common_tag_keys = tag_keys.intersection(next_tag_keys) next_data_tags = set(stream_data_tags(next_stream)) @@ -482,7 +517,7 @@ def static_process(self, *streams: StreamProtocol) -> StreamProtocol: arrow_utils.column_arrow_type(next_table.schema, key), ) require_matchable_key("Join", key, key_type) - common_tag_keys.add(COMMON_JOIN_KEY) + common_tag_keys.add(_COMMON_JOIN_KEY) table_ref_schema = table.schema table = _inner_join(table, next_table, list(common_tag_keys)) @@ -501,7 +536,7 @@ def static_process(self, *streams: StreamProtocol) -> StreamProtocol: # reorder columns to bring tag columns to the front # TODO: come up with a better algorithm - table = table.drop(COMMON_JOIN_KEY) + table = table.drop(_COMMON_JOIN_KEY) for name in sorted(merged_source): table = self._fold_source_column(table, name) diff --git a/src/orcapod/core/operators/merge_join.py b/src/orcapod/core/operators/merge_join.py index b4d926c3d..563b198b8 100644 --- a/src/orcapod/core/operators/merge_join.py +++ b/src/orcapod/core/operators/merge_join.py @@ -12,6 +12,8 @@ from orcapod.core.operators.join import ( _MERGED_SOURCE_PREFIX, # pyright: ignore[reportPrivateUsage] # one definition, shared with Join _inner_join, # pyright: ignore[reportPrivateUsage] # one definition, shared with Join + _COMMON_JOIN_KEY, # pyright: ignore[reportPrivateUsage] # one definition, shared with Join + _with_common_key, # pyright: ignore[reportPrivateUsage] # one definition, shared with Join Join, ) from orcapod.core.operators.key_nullability import ( @@ -476,24 +478,19 @@ def binary_static_process( # Inner join on the shared tag keys. A constant key makes the join a # cartesian product when the inputs share no tag; int8 explicitly, so a # zero-row table doesn't produce a null-typed column (same as Join). - COMMON_JOIN_KEY = "_common" - output_nullable.pop(COMMON_JOIN_KEY, None) - left_table = left_table.add_column( - 0, COMMON_JOIN_KEY, pa.array([0] * len(left_table), type=pa.int8()) - ) - right_table = right_table.add_column( - 0, COMMON_JOIN_KEY, pa.array([0] * len(right_table), type=pa.int8()) - ) - join_keys = sorted(shared_tag_keys | {COMMON_JOIN_KEY}) + output_nullable.pop(_COMMON_JOIN_KEY, None) + left_table = _with_common_key(left_table) + right_table = _with_common_key(right_table) + join_keys = sorted(shared_tag_keys | {_COMMON_JOIN_KEY}) # The right-table columns the join suffixes with ``_right``: those the # left table also has, other than the keys. - left_col_set = set(left_table.column_names) - {COMMON_JOIN_KEY} - right_col_set = set(right_table.column_names) - {COMMON_JOIN_KEY} + left_col_set = set(left_table.column_names) - {_COMMON_JOIN_KEY} + right_col_set = set(right_table.column_names) - {_COMMON_JOIN_KEY} suffixed_bases = (right_col_set & left_col_set) - set(join_keys) joined = _inner_join(left_table, right_table, join_keys) - joined = joined.drop(COMMON_JOIN_KEY) + joined = joined.drop(_COMMON_JOIN_KEY) for left_name, right_name in right_source.items(): joined = Join._merge_source_columns(joined, left_name, right_name) # pyright: ignore[reportPrivateUsage] # Join's one rule joined = Join._fold_source_column(joined, left_name) # pyright: ignore[reportPrivateUsage] # Join's one rule diff --git a/src/orcapod/core/operators/semijoin.py b/src/orcapod/core/operators/semijoin.py index 5bc03d11d..e9c64cd51 100644 --- a/src/orcapod/core/operators/semijoin.py +++ b/src/orcapod/core/operators/semijoin.py @@ -32,6 +32,29 @@ _LEFT_ROW = "__semi_join_left_row" +def _has_whole_key( + table: "pa.Table", keys: Sequence[str] +) -> "pa.ChunkedArray[Any] | pa.BooleanArray": + """Whether each row's key holds no top-level null, as a boolean mask. + + A row whose key holds a top-level null matches nothing in a semi-join: Polars + already applies that to scalar keys but treats a null struct or list as equal to + another, so such rows are dropped before the match (the sync path and the + streaming kernel alike). + + Args: + table: The rows. + keys: The key columns, at least one. + + Returns: + One boolean per row. + """ + valid = table.column(keys[0]).is_valid() + for name in keys[1:]: + valid = pc.and_(valid, table.column(name).is_valid()) + return valid + + class SemiJoin(BinaryOperator): """ Binary operator that performs a semi-join between two streams. @@ -218,10 +241,7 @@ def binary_static_process( # Polars already applies that to scalar keys but treats a null struct or # list as equal to another, so drop right rows with a null key. right_keys = right_table.select(list(common_keys)) - valid = right_keys.column(0).is_valid() - for index in range(1, right_keys.num_columns): - valid = pc.and_(valid, right_keys.column(index).is_valid()) - right_keys = right_keys.filter(valid) + right_keys = right_keys.filter(_has_whole_key(right_keys, common_keys)) # Polars, unlike Arrow's hash join, accepts nested (list, struct) keys. # It decides which left rows match from the prepared keys and the left diff --git a/src/orcapod/core/operators/streaming_joins.py b/src/orcapod/core/operators/streaming_joins.py new file mode 100644 index 000000000..6b9d64e7c --- /dev/null +++ b/src/orcapod/core/operators/streaming_joins.py @@ -0,0 +1,998 @@ +"""Streaming join kernels: symmetric hash joins on Arrow record batches (ITL-1362). + +The async path of ``Join``, ``MergeJoin`` and ``SemiJoin`` (ITL-1347, stage 5) reads its +inputs as Arrow record batches, in whatever order they arrive, and must give the rows of +the operator's sync ``static_process`` over the same inputs, as a multiset (row order is +not a result on the async path; developer, November 22, 2026). A kernel is that +computation without the channels: the channel layer creates one per run from the input +streams (the descriptions) and hands it each arriving record batch (``push``) and each +input's end (``close``); every call returns the output rows it decided, as record batches. + +The oracle is the sync operator over its inputs as a job's edges carry them: each input +rebuilt from its rows (``StaticOutputOperatorPod._materialize_upstream``), which is the +row-built form F of the ITL-1347 spec. Batches arrive in that form (``null`` columns as +``large_string``, ITL-1319), and every type a kernel holds is that form's. + +The kernels serve a job's edges, so their domain is the inputs a job can carry. A +``null``-typed column is outside it: no source accepts one (the Arrow hasher refuses the +type, also with no rows), the type converter maps no Python type to it, and a bound +stream must match its slot. A kernel still accepts a raw stream with such a column and +gives the sync rows for it, but a refusal it raises for such a column before the first +batch is decided on the row-built form and may name ``large_string`` where the sync path +over a raw empty stream names ``null``. + +How a kernel stays equal to the sync path: + +- **Schema-decided checks before the first batch.** The constructor applies the + operator's own ``static_process`` to the inputs' zero-row streams in the row-built form + (the description's Arrow types, or its Python schema when it cannot type itself, put + through F), which processes no data and raises exactly the sync path's errors for + those columns and types (ITL-856, e1 of the ITL-1347 spec). Its result, + ``zero_row_result``, is the output's description: its columns are what every emitted + batch holds (``output_columns``). +- **Value-decided refusals when the batch arrives.** A refusal that depends on values, + not on the description, cannot be raised before them: merging the source-info token + lists of a data-tag several inputs join on refuses lists of different lengths + (``ValueError``, from the sync path's own helper and with its message). A kernel raises + it for the first offending pair it observes, when that pair's batch arrives; rows + already emitted belong to a run that then fails. With several offending pairs, which + one is reported may depend on arrival (the sync path reports the first in its own + order): the error type is the sync path's and the message has its form. +- **An input that ends empty.** The sync path reads an input with no rows in its zero-row + form, where a ``null`` column stays ``null``, not ``large_string``. When the last input + closes, a kernel whose empty inputs have such a column applies ``static_process`` again + over that mix, and raises what it raises; when it emitted no row, that result is its + ``zero_row_result`` from then on (the output's types are the sync result's). The + re-check refuses only shared columns (keys, colliding data columns), and an input with + no rows that shares a tag with the others empties the result (an inner join), so no + row was emitted before it can refuse. ``SemiJoin`` with no shared tag passes every + left row whatever its right input holds, and has no shared column to refuse. +- **Matching is the sync join's.** Each input keeps the rows it needs as Arrow tables and + a Polars frame of their prepared keys and row numbers (``arrow_keys.polars_key_frame``), + with the constant key every join adds (``join._with_common_key``). An arriving batch's + key frame is joined with the other side's accumulated key frame by the sync path's own + rule (``join._matched_pairs``), in one vectorized join, never per row: a top-level + null key matches nothing. Every value is then taken from the Arrow tables by row + number, so it is the input's, bit for bit. Each pair is emitted once, by whichever of + its two rows arrives second. +- **The same column work.** A matched pair's table goes through the steps the sync path + applies to its joined table (system-tag renaming by each input's pipeline hash and + position, field flags, merged source info, system-tag value sorting, merged lists), + with the sync path's helpers. Each of them works row by row, so applying them per + batch of pairs gives the sync rows. +- **Field flags.** A batch's flags are the sync result's, except the system-tag and + source-info fields: a complete table decides those by its values (``StaticOutputOperatorPod._flag_by_values``, + the last step of F), so a kernel declares every such field nullable and the stream made + from its batches settles them. + +A kernel holds only what can still match: a side's rows are dropped when the other side +closes (nothing can arrive to match them), and an arriving row is not kept once the +other side has closed. A row whose key holds a top-level null is never kept (it matches +nothing). A step of a ``Join`` chain that can never emit again (a side closed holding no +row that can match) closes its successor's left side and releases the earlier steps, +except those the sync path still merges before it (``StreamingJoin._close``). +""" + +from __future__ import annotations + +from abc import ABC, abstractmethod +from collections.abc import Callable, Sequence +from typing import Any, ClassVar + +import numpy as np +import polars as pl +import pyarrow as pa +import pyarrow.compute as pc + +from orcapod.core.data_tags import stream_data_tags +from orcapod.core.operators.arrow_keys import polars_key_frame +from orcapod.core.operators.join import ( + _COMMON_JOIN_KEY, # pyright: ignore[reportPrivateUsage] # Join's one rule + _MERGED_SOURCE_PREFIX, # pyright: ignore[reportPrivateUsage] # Join's one rule + Join, + _matched_pairs, # pyright: ignore[reportPrivateUsage] # Join's one rule + _with_common_key, # pyright: ignore[reportPrivateUsage] # Join's one rule +) +from orcapod.core.operators.key_nullability import key_nullable +from orcapod.core.operators.merge_join import ( + MergeJoin, + _merged_list, # pyright: ignore[reportPrivateUsage] # MergeJoin's one rule + _output_types, # pyright: ignore[reportPrivateUsage] # MergeJoin's one rule +) +from orcapod.core.operators.semijoin import ( + SemiJoin, + _has_whole_key, # pyright: ignore[reportPrivateUsage] # SemiJoin's one rule +) +from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod +from orcapod.core.streams.base import ZERO_ROW_INPUT_COLUMNS, row_built_columns +from orcapod.protocols.core_protocols import StreamProtocol +from orcapod.system_constants import constants +from orcapod.utils import arrow_utils + +# The column groups an operator input and result are read with: user tags, system tags, +# data and source info. No meta column and no context column: neither is transported. +TRANSPORT_COLUMNS: dict[str, bool] = {"source": True, "system_tags": True} + +# The row-number columns of the key frames, one per side of a binary join; never a key +# (keys are tag columns, and a tag never starts with the meta prefix ``__``). +_ROW = ("__streaming_left_row", "__streaming_right_row") + + +def _settled_by_values(schema: pa.Schema) -> pa.Schema: + """``schema`` with every system-tag and source-info field nullable. + + What a kernel declares for the fields a complete table decides by its values + (``StaticOutputOperatorPod._flag_by_values``): one record batch of many cannot. + """ + prefixes = (constants.SYSTEM_TAG_PREFIX, constants.SOURCE_PREFIX) + return pa.schema( + [ + field.with_nullable(True) if field.name.startswith(prefixes) else field + for field in schema + ] + ) + + +def _row_built_zero_rows(stream: StreamProtocol) -> tuple[StreamProtocol, bool]: + """``stream`` with no rows, as an input rebuilt from rows of it reads. + + The zero-row input (``_materialize_upstream`` with no rows) put through F: what + ``_materialize_upstream(rows, stream, zero_rows=True)`` gives, without rows. + + Args: + stream: An input stream (its description). + + Returns: + The zero-row stream in the row-built form, and whether its Arrow types differ + from the zero-row input's (a ``null`` column, which rows carry as + ``large_string``). + """ + pod = StaticOutputOperatorPod + zero = pod._materialize_upstream([], stream) # pyright: ignore[reportPrivateUsage] # the operators' one form of an input + table = zero.as_table(columns=ZERO_ROW_INPUT_COLUMNS) + row_built = pod._flag_by_values(row_built_columns(table, stream.keys())) # pyright: ignore[reportPrivateUsage] # F's last step + differs = any( + field.type != table.schema.field(field.name).type for field in row_built.schema + ) + built = pod._as_upstream_stream( # pyright: ignore[reportPrivateUsage] # the operators' one form of an input + row_built, stream.keys()[0], stream_data_tags(stream), stream + ) + return built, differs + + +def _key_frame(table: pa.Table, keys: Sequence[str], row: str) -> pl.DataFrame: + """The frame a join matches ``table``'s rows on, rows numbered from 0. + + The prepared keys and the constant join key, as the sync join builds its frames + (``join._with_common_key``, ``arrow_keys.polars_key_frame``). + + Args: + table: The rows. + keys: The shared tag columns. + row: The row-number column. + + Returns: + The key frame. + """ + return polars_key_frame( + _with_common_key(table.select(list(keys))), [*keys, _COMMON_JOIN_KEY], row + ) + + +def _match( + arriving: pl.DataFrame, held: pl.DataFrame, keys: Sequence[str] +) -> pl.DataFrame: + """Join two key frames by the sync join's rule (``join._matched_pairs``). + + Both frames hold the constant join key, so inputs that share no tag give every pair + and a top-level null key matches nothing, as on the sync path. + + Args: + arriving: The arriving batch's key frame. + held: The other side's accumulated key frame. + keys: The shared tag columns. + + Returns: + One row per matched pair, holding both row-number columns. + """ + return _matched_pairs(arriving, held, [*keys, _COMMON_JOIN_KEY]) + + +def _joined_by_rows( + left: pa.Table, + right: pa.Table, + keys: Sequence[str], + left_rows: pa.Array[Any], + right_rows: pa.Array[Any], +) -> pa.Table: + """Take matched pairs from two tables, in the layout of ``join._inner_join``. + + The left columns (one of each key, the left row's value), then the right columns that + are not keys, a name the left table also has taking the suffix ``_right``. + + Args: + left: The left table. + right: The right table. + keys: The key columns. + left_rows: The left row of each pair. + right_rows: The right row of each pair. + + Returns: + The joined table, fields without the inputs' flags (as ``_inner_join``). + """ + names: list[str] = [] + arrays: list[Any] = [] + for name in left.column_names: + names.append(name) + arrays.append(left.column(name).take(left_rows)) + for name in right.column_names: + if name in keys: + continue + names.append(f"{name}_right" if name in left.column_names else name) + arrays.append(right.column(name).take(right_rows)) + return pa.Table.from_arrays(arrays, names=names) + + +class _Side: + """One side of a binary symmetric hash join: the rows it holds and their key frame. + + Args: + keys: The key columns. + row: This side's row-number column. + """ + + def __init__(self, keys: Sequence[str], row: str) -> None: + self.keys: list[str] = list(keys) + self.row: str = row + self.closed: bool = False + self.schema: pa.Schema | None = None + self._tables: list[pa.Table] = [] + self._frames: list[pl.DataFrame] = [] + self._table: pa.Table | None = None + self._frame: pl.DataFrame | None = None + self.rows: int = 0 + + def key_frame(self, table: pa.Table) -> pl.DataFrame: + """The key frame of ``table``, its rows numbered from 0.""" + return _key_frame(table, self.keys, self.row) + + def append(self, table: pa.Table, frame: pl.DataFrame) -> None: + """Hold ``table``'s rows, with ``frame`` from ``key_frame``.""" + self._tables.append(table) + # Numbered after the rows already held, as ``table()`` holds them. + self._frames.append( + frame.with_columns(pl.col(self.row) + self.rows) if self.rows else frame + ) + self._table = None + self._frame = None + self.rows += table.num_rows + + def table(self) -> pa.Table: + """Every row held, numbered as in ``frame``.""" + if self._table is None: + self._table = pa.concat_tables(self._tables) + return self._table + + def frame(self) -> pl.DataFrame: + """The key frame of every row held.""" + if self._frame is None: + self._frame = pl.concat(self._frames, rechunk=False) + self._frames = [self._frame] + return self._frame + + def clear(self) -> None: + """Drop every row held.""" + self._tables, self._frames = [], [] + self._table, self._frame = None, None + self.rows = 0 + + +class _BinaryLink: + """A binary symmetric hash join of two sides, left and right. + + Args: + keys: The key columns. + finish: Turns the pairs' joined table (``_joined_by_rows`` layout) into the + link's output rows; given the two sides' schemas. + """ + + def __init__( + self, + keys: Sequence[str], + finish: Callable[[pa.Table, pa.Schema, pa.Schema], pa.Table], + ) -> None: + self.keys: list[str] = list(keys) + self.sides: tuple[_Side, _Side] = (_Side(keys, _ROW[0]), _Side(keys, _ROW[1])) + self._finish: Callable[[pa.Table, pa.Schema, pa.Schema], pa.Table] = finish + + @property + def held_rows(self) -> int: + """The rows both sides hold.""" + return self.sides[0].rows + self.sides[1].rows + + @property + def exhausted(self) -> bool: + """Whether the link can never emit again: a side closed holding no row. + + A side holds only rows that can match (``push`` drops a row with a null key). + + A closed side's rows are held while the other side is open; with none, no row + still to arrive can pair. Two closed sides hold no row (each close drops the + other side's rows). + """ + return any(side.closed and not side.rows for side in self.sides) + + def release(self) -> None: + """End both sides: the link's output is never needed again.""" + for side in self.sides: + side.closed = True + side.clear() + + def push(self, side: int, table: pa.Table) -> pa.Table | None: + """Match ``table``'s rows with the other side's, then hold them if still needed. + + Args: + side: 0 for the left side, 1 for the right. + table: The arriving rows; every table of one side has one schema. + + Returns: + The output rows of the new pairs, or ``None`` when there is none. + """ + this, other = self.sides[side], self.sides[1 - side] + if this.schema is None: + this.schema = table.schema + if other.closed and not other.rows: + # Nothing can pair with these rows, and none is held: no key to prepare. + return None + if self.keys: + # A row whose key holds a top-level null matches nothing: never held, so a + # closed side holding only such rows is exhausted. + table = table.filter(_has_whole_key(table, self.keys)) + if not table.num_rows: + return None + frame = this.key_frame(table) + result = None + if other.rows: + pairs = _match(frame, other.frame(), self.keys) + if pairs.height: + rows = ( + pairs.get_column(_ROW[0]).to_arrow(), + pairs.get_column(_ROW[1]).to_arrow(), + ) + tables = (table, other.table()) if side == 0 else (other.table(), table) + joined = _joined_by_rows(*tables, self.keys, *rows) + assert self.sides[0].schema is not None + assert self.sides[1].schema is not None + result = self._finish( + joined, self.sides[0].schema, self.sides[1].schema + ) + # A row is held only for rows still to arrive on the other side. + if not other.closed: + this.append(table, frame) + return result + + def close(self, side: int) -> None: + """Note that ``side`` ends: the other side's rows can never match again.""" + self.sides[side].closed = True + self.sides[1 - side].clear() + + +class StreamingJoinKernel(ABC): + """The streaming form of a join operator, over Arrow record batches. + + Created from the operator and its input streams, in call order; the streams are the + descriptions (keys, Arrow types, pipeline hashes) and no row of them is read. The + channel layer then calls ``push`` with each record batch an input delivers and + ``close`` when an input ends, and sends on the record batches each call returns. A + batch holds an input's transport columns (user tags, system tags, data and source + info, by name, in any order); the batches emitted hold ``output_columns``. + + Args: + operator: The operator. + inputs: Its input streams, in call order. + + Raises: + InputValidationError: Whatever the sync path raises for these inputs' columns + and types (``static_process`` over the zero-row inputs). + """ + + # How many inputs the operator takes; ``None`` for one or more. + ARITY: ClassVar[int | None] = None + + def __init__( + self, operator: StaticOutputOperatorPod, inputs: Sequence[StreamProtocol] + ) -> None: + if not inputs or (self.ARITY is not None and len(inputs) != self.ARITY): + raise ValueError( + f"{type(self).__name__} takes " + + (f"{self.ARITY}" if self.ARITY is not None else "one or more") + + f" inputs, got {len(inputs)}" + ) + self.operator: StaticOutputOperatorPod = operator + self.inputs: tuple[StreamProtocol, ...] = tuple(inputs) + # Each input as the sync path reads rows of it, with no rows (the row-built + # form), and whether that differs from how it reads the input with none. + built = [_row_built_zero_rows(stream) for stream in self.inputs] + self._zero_rows: tuple[StreamProtocol, ...] = tuple(z for z, _ in built) + self._null_typed: tuple[bool, ...] = tuple(d for _, d in built) + # The schema of every batch of an input, in its row-built layout; the fields a + # complete table decides by values declared nullable. + self._layouts: tuple[pa.Schema, ...] = tuple( + _settled_by_values(stream.as_table(columns=TRANSPORT_COLUMNS).schema) + for stream in self._zero_rows + ) + self._closed: list[bool] = [False] * len(self.inputs) + self._received: list[bool] = [False] * len(self.inputs) + self._emitted_any: bool = False + # The sync path over no rows: its checks, and the output's columns. + self.zero_row_result: StreamProtocol = operator.static_process(*self._zero_rows) + self.output_columns: tuple[str, ...] = tuple( + self.zero_row_result.as_table(columns=TRANSPORT_COLUMNS).column_names + ) + + @property + @abstractmethod + def held_rows(self) -> int: + """How many input rows the kernel holds now (rows that may still match).""" + + def push(self, input_index: int, batch: pa.RecordBatch) -> list[pa.RecordBatch]: + """Take one record batch of an input; return the output rows it decides. + + Args: + input_index: The input, in call order. + batch: The batch, holding the input's transport columns. + + Returns: + The output record batches, possibly none. + + Raises: + ValueError: If the input has closed, or the batch lacks a column of the + input's description or holds one of another Arrow type. + """ + self._require_open(input_index) + table = self._as_input_table(input_index, batch) + if not table.num_rows: + return [] + self._received[input_index] = True + return self._emitted(self._push(input_index, table)) + + def close(self, input_index: int) -> list[pa.RecordBatch]: + """Note that an input has ended; return the output rows that decides. + + Args: + input_index: The input, in call order. + + Returns: + The output record batches, possibly none. + + Raises: + ValueError: If the input has closed already. + InputValidationError: When the last input closes, what the sync path raises + over inputs some of which had no rows, read in their zero-row form + (module docstring). + """ + self._require_open(input_index) + self._closed[input_index] = True + emitted = self._emitted(self._close(input_index)) + if all(self._closed): + result = self._check_empty_inputs() + if result is not None and not self._emitted_any and not emitted: + # No row: the output is the sync path's result over the inputs as + # they ended, whose types an empty input decides. + self.zero_row_result = result + return emitted + + def _check_empty_inputs(self) -> StreamProtocol | None: + """Apply the sync path's checks to the inputs as they ended. + + An input with no rows is read in its zero-row form, where a ``null`` column stays + ``null``; only such an input can make the checks differ from the constructor's. + + Returns: + The sync path's result over the inputs as they ended, with no rows, or + ``None`` when it is the constructor's. + """ + empty = [ + not received and null_typed + for received, null_typed in zip(self._received, self._null_typed) + ] + if not any(empty): + return None + pod = StaticOutputOperatorPod + return self.operator.static_process( + *( + pod._materialize_upstream([], stream) # pyright: ignore[reportPrivateUsage] # the operators' one form of an input + if is_empty + else zero_rows + for stream, zero_rows, is_empty in zip( + self.inputs, self._zero_rows, empty + ) + ) + ) + + @abstractmethod + def _push(self, input_index: int, table: pa.Table) -> list[pa.Table]: + """Take an input's rows; return the output tables they decide. + + Args: + input_index: The input, in call order. + table: Its rows in its layout (``_as_input_table``), never empty. + + Returns: + The output tables, possibly none. + """ + + @abstractmethod + def _close(self, input_index: int) -> list[pa.Table]: + """Note an input's end; return the output tables that decides. + + Args: + input_index: The input, in call order; open until this call. + + Returns: + The output tables, possibly none. + """ + + def _require_open(self, input_index: int) -> None: + """Refuse an input that does not exist or has closed already. + + Args: + input_index: The input, in call order. + + Raises: + ValueError: If the kernel has no such input, or it has closed. + """ + if not 0 <= input_index < len(self.inputs): + raise ValueError( + f"{type(self).__name__}: no input {input_index} " + + f"(it has {len(self.inputs)})" + ) + if self._closed[input_index]: + raise ValueError( + f"{type(self).__name__}: input {input_index} has closed already" + ) + + def _as_input_table(self, input_index: int, batch: pa.RecordBatch) -> pa.Table: + """Return a batch's columns in the input's layout, under one schema per input. + + The schema is the input's row-built form (``null`` columns as ``large_string``, + ITL-1319), every system-tag and source-info field nullable (a complete table + decides those). A batch with no rows may also carry a column in the type of the + input's zero-row form (``null``): it holds no value. + """ + layout = self._layouts[input_index] + names = set(batch.schema.names) + if missing := [name for name in layout.names if name not in names]: + raise ValueError( + f"{type(self).__name__}: a batch of input {input_index} lacks " + + f"the column(s) {missing} its stream describes" + ) + table = pa.Table.from_batches([batch]).select(layout.names) + for field, actual in zip(layout, table.schema): + if field.type != actual.type and ( + table.num_rows or not pa.types.is_null(actual.type) + ): + raise ValueError( + f"{type(self).__name__}: column {field.name!r} of input " + + f"{input_index} is {actual.type} in a batch, but " + + f"{field.type} in its stream" + ) + if not table.num_rows: + return layout.empty_table() + return pa.Table.from_arrays(table.columns, schema=layout) + + def _emitted(self, tables: list[pa.Table]) -> list[pa.RecordBatch]: + """The record batches of the output tables, holding ``output_columns``. + + Every system-tag and source-info field is declared nullable: the complete + table's values decide those flags (``StaticOutputOperatorPod._flag_by_values``). + """ + batches: list[pa.RecordBatch] = [] + for table in tables: + if table.num_rows: + self._emitted_any = True + table = table.select(list(self.output_columns)).combine_chunks() + table = pa.Table.from_arrays( + table.columns, schema=_settled_by_values(table.schema) + ) + batches.extend(table.to_batches()) + return batches + + def _suffix(self, input_index: int, position: int) -> str: + """What an input's system-tag column names gain: ``{pipeline hash}:{position}``.""" + n_char = self.operator.orcapod_config.hashing.system_tag_n_char + pipeline_hash = self.inputs[input_index].pipeline_hash() + return f"{pipeline_hash.to_hex(n_char)}:{position}" + + +class StreamingJoin(StreamingJoinKernel): + """``Join`` on record batches: a staggered chain of binary symmetric hash joins. + + The inputs are taken in ``Join``'s canonical order (by pipeline hash, ties in call + order), and joined as ``static_process`` joins them: the first with the second, the + result with the third, and so on, each step on the tags its two sides share. Each + step is a binary symmetric hash join whose left side receives the previous step's + rows as they are decided. A data-tag several inputs join on keeps its members' + source-info tokens pending through the chain, folded when the last step emits a row. + + Args: + operator: The ``Join``. + inputs: Its input streams, in call order. + """ + + def __init__(self, operator: Join, inputs: Sequence[StreamProtocol]) -> None: + super().__init__(operator, inputs) + self._join = operator + order = sorted( + range(len(inputs)), key=lambda i: inputs[i].pipeline_hash().to_hex() + ) + self._position = {index: position for position, index in enumerate(order)} + self._renames: dict[int, dict[str, str]] = {} + self._links: list[_BinaryLink] = [] + # Whether each step merges source info (a data-tag both its sides hold), which + # refuses token lists of different lengths: a refusal decided by values. + self._merges: list[bool] = [] + # The steps whose output is dropped: no later step it reaches can emit, but the + # step still matches, so a value-decided refusal is raised as on sync. + self._sinks: set[int] = set() + self._merged_source: set[str] = set() + if len(inputs) == 1: + return + first = inputs[order[0]] + tag_keys = set(first.keys()[0]) + data_tags = set(stream_data_tags(first)) + for position, index in enumerate(order[1:], start=1): + stream = inputs[index] + next_tags = set(stream.keys()[0]) + next_data_tags = set(stream_data_tags(stream)) + merged = Join._merged_data_tags( # pyright: ignore[reportPrivateUsage] # Join's one rule + tag_keys, data_tags, next_tags, next_data_tags + ) + rename = { + f"{constants.SOURCE_PREFIX}{name}": f"{_MERGED_SOURCE_PREFIX}{name}" + for name in sorted(merged) + } + self._renames[index] = rename + self._merged_source |= set(rename) + keys = sorted(tag_keys & next_tags) + last = position == len(inputs) - 1 + self._links.append( + _BinaryLink(keys, self._link_finish(keys, rename, final=last)) + ) + self._merges.append(bool(rename)) + tag_keys |= next_tags + data_tags |= next_data_tags + + @property + def held_rows(self) -> int: + return sum(link.held_rows for link in self._links) + + def _link_finish( + self, keys: Sequence[str], rename: dict[str, str], *, final: bool + ) -> Callable[[pa.Table, pa.Schema, pa.Schema], pa.Table]: + """What one step does to its joined pairs, as ``Join.static_process`` does.""" + + def finish( + joined: pa.Table, left_schema: pa.Schema, right_schema: pa.Schema + ) -> pa.Table: + table = arrow_utils.restore_schema_nullability( + joined, left_schema, right_schema + ) + table = Join._shared_key_nullability( # pyright: ignore[reportPrivateUsage] # Join's one rule + table, left_schema, right_schema, keys + ) + for left_name, right_name in rename.items(): + table = Join._merge_source_columns(table, left_name, right_name) # pyright: ignore[reportPrivateUsage] # Join's one rule + if not final: + return table + for name in sorted(self._merged_source): + table = Join._fold_source_column(table, name) # pyright: ignore[reportPrivateUsage] # Join's one rule + return arrow_utils.sort_system_tag_values(table) + + return finish + + def _push(self, input_index: int, table: pa.Table) -> list[pa.Table]: + """Feed an input's rows into its step and forward what each step emits. + + The input at canonical position 0 is the first step's left side, the input at + position ``p`` the right side of step ``p - 1``. The rows a step emits are its + successor's left side, up to the last step, whose rows are the output. + + Args: + input_index: The input, in call order. + table: Its rows, never empty. + + Returns: + The last step's output, possibly none. + """ + if not self._links: + return [table] + position = self._position[input_index] + table = arrow_utils.append_to_system_tags( + table, self._suffix(input_index, position) + ) + if rename := self._renames.get(input_index): + table = table.rename_columns([rename.get(c, c) for c in table.column_names]) + step, side = (0, 0) if position == 0 else (position - 1, 1) + result = self._links[step].push(side, table) + while result is not None and step < len(self._links) - 1: + if step in self._sinks: + return [] + step += 1 + result = self._links[step].push(0, result) + return [] if result is None else [result] + + def _close(self, input_index: int) -> list[pa.Table]: + """End an input's side of its step, and every side that can no longer receive. + + A step that can never emit again (``_BinaryLink.exhausted``) closes its + successor's left side. The earlier steps' rows could only reach it, so they are + released, except the steps up to the last earlier one that merges source info: + the sync path joins those steps before it reaches the empty one, and a merge + refuses token lists of different lengths (a value-decided refusal, module + docstring). Those steps keep matching, and the last of them drops its output + (``_sinks``). Closing never emits a row. + + Args: + input_index: The input, in call order. + + Returns: + No table. + """ + if not self._links: + return [] + position = self._position[input_index] + step, side = (0, 0) if position == 0 else (position - 1, 1) + self._links[step].close(side) + for step, link in enumerate(self._links): + if not link.exhausted: + continue + # The last earlier step that merges source info, and every step before it, + # keep matching; the steps after it, up to this one, are released. + merging = [j for j in range(step) if self._merges[j]] + kept = merging[-1] if merging else -1 + if kept >= 0: + self._sinks.add(kept) + for earlier in self._links[kept + 1 : step]: + earlier.release() + if ( + step + 1 < len(self._links) + and not self._links[step + 1].sides[0].closed + ): + self._links[step + 1].close(0) + return [] + + +class StreamingMergeJoin(StreamingJoinKernel): + """``MergeJoin`` on record batches: one binary symmetric hash join, argument order. + + Each matched pair's merged lists are built from the pair's two rows, the first + argument's value first, as ``MergeJoin.binary_static_process`` builds them. + + Args: + operator: The ``MergeJoin``. + inputs: Its two input streams, in argument order. + """ + + ARITY: ClassVar[int | None] = 2 + + def __init__(self, operator: MergeJoin, inputs: Sequence[StreamProtocol]) -> None: + super().__init__(operator, inputs) + left, right = inputs + left_tags, left_data = left.keys() + right_tags, right_data = right.keys() + self._shared_tags = set(left_tags) & set(right_tags) + merged = Join._merged_data_tags( # pyright: ignore[reportPrivateUsage] # Join's one rule + left_tags, stream_data_tags(left), right_tags, stream_data_tags(right) + ) + right_names = set(self._layouts[1].names) + self._rename = { + f"{constants.SOURCE_PREFIX}{name}": f"{_MERGED_SOURCE_PREFIX}{name}" + for name in sorted(merged) + if f"{constants.SOURCE_PREFIX}{name}" in right_names + } + self._colliding = (set(left_data) & set(right_data)) - merged + self._captured = ( + set(left_tags) | set(left_data) | set(right_tags) | set(right_data) + ) + # The left input's converter, as the sync path takes it. + self._type_converter = StaticOutputOperatorPod._upstream_context( # pyright: ignore[reportPrivateUsage] # the operators' one rule + left + ).type_converter + self._link = _BinaryLink(sorted(self._shared_tags), self._finish) + + @property + def held_rows(self) -> int: + return self._link.held_rows + + def _finish( + self, joined: pa.Table, left_schema: pa.Schema, right_schema: pa.Schema + ) -> pa.Table: + """``MergeJoin.binary_static_process`` from its joined table on.""" + output_types = _output_types( + {f.name: f.type for f in left_schema}, + {f.name: f.type for f in right_schema}, + ) + left_nullable = { + f.name: f.nullable for f in left_schema if f.name in self._captured + } + right_nullable = { + f.name: f.nullable for f in right_schema if f.name in self._captured + } + output_nullable = {**right_nullable, **left_nullable} + for name in self._shared_tags: + output_nullable[name] = key_nullable( + left_nullable[name], right_nullable[name] + ) + for name in self._colliding: + output_nullable[name] = False + source_name = f"{constants.SOURCE_PREFIX}{name}" + if source_name in output_nullable: + output_nullable[source_name] = False + # The columns the sync path does not capture (system tags and source info) are + # flagged by their values over the complete table; a batch declares them + # nullable (module docstring). + for schema in (right_schema, left_schema): + for field in schema: + if field.name not in self._captured: + output_nullable.setdefault(field.name, True) + left_names = set(left_schema.names) + suffixed = (set(right_schema.names) & left_names) - self._shared_tags + for left_name, right_name in self._rename.items(): + joined = Join._merge_source_columns(joined, left_name, right_name) # pyright: ignore[reportPrivateUsage] # Join's one rule + joined = Join._fold_source_column(joined, left_name) # pyright: ignore[reportPrivateUsage] # Join's one rule + for name in sorted(self._colliding): + source_name = f"{constants.SOURCE_PREFIX}{name}" + pairs = [(name, output_types[name])] + if ( + source_name in joined.column_names + and f"{source_name}_right" in joined.column_names + ): + pairs.append((source_name, output_types[source_name])) + for column, element_type in pairs: + list_type = arrow_utils.aggregated_list_type( + element_type, self._type_converter, column=column + ) + merged_list = _merged_list( + joined.column(column), joined.column(f"{column}_right"), list_type + ) + index = joined.column_names.index(column) + joined = joined.drop_columns([column, f"{column}_right"]) + joined = joined.add_column(index, column, merged_list) + output_types[column] = list_type + for base_name in suffixed: + suffixed_name = f"{base_name}_right" + if suffixed_name not in joined.column_names: + continue + if base_name not in joined.column_names: + index = joined.column_names.index(suffixed_name) + column_data = joined.column(suffixed_name) + joined = joined.drop_columns([suffixed_name]) + joined = joined.add_column(index, base_name, column_data) + else: + joined = joined.drop_columns([suffixed_name]) + schema = pa.schema( + [ + pa.field(name, output_types[name], nullable=output_nullable[name]) + for name in joined.column_names + ] + ) + return pa.Table.from_arrays( + [ + column if column.type == field.type else column.cast(field.type) + for column, field in zip(joined.columns, schema) + ], + schema=schema, + ) + + def _push(self, input_index: int, table: pa.Table) -> list[pa.Table]: + table = arrow_utils.append_to_system_tags( + table, self._suffix(input_index, input_index) + ) + if input_index == 1 and self._rename: + table = table.rename_columns( + [self._rename.get(c, c) for c in table.column_names] + ) + result = self._link.push(input_index, table) + return [] if result is None else [result] + + def _close(self, input_index: int) -> list[pa.Table]: + self._link.close(input_index) + return [] + + +class StreamingSemiJoin(StreamingJoinKernel): + """``SemiJoin`` on record batches: the left input streams. + + A left row is emitted as soon as its key is among the right rows seen so far; a left + row with no such match waits until a right row matches it or the right input closes, + when it is dropped. The right input's rows are held as keys only, while the left + input is open. With no tag shared by the inputs, every left row passes, as + ``static_process`` returns the left stream. + + Args: + operator: The ``SemiJoin``. + inputs: Its two input streams, left then right. + """ + + ARITY: ClassVar[int | None] = 2 + + def __init__(self, operator: SemiJoin, inputs: Sequence[StreamProtocol]) -> None: + super().__init__(operator, inputs) + left, right = inputs + self._keys = list(SemiJoin._match_keys(left.keys()[0], right.keys()[0])) # pyright: ignore[reportPrivateUsage] # SemiJoin's one rule + # The left rows not decided yet, and the right rows' keys. + self._waiting: pa.Table | None = None + self._right_frames: list[pl.DataFrame] = [] + self._right_frame: pl.DataFrame | None = None + + @property + def held_rows(self) -> int: + waiting = self._waiting.num_rows if self._waiting is not None else 0 + return waiting + sum(frame.height for frame in self._right_frames) + + def _right_keys(self) -> pl.DataFrame | None: + """The key frame of every right row held, or ``None`` with none.""" + if not self._right_frames: + return None + if self._right_frame is None: + self._right_frame = pl.concat(self._right_frames, rechunk=False) + self._right_frames = [self._right_frame] + return self._right_frame + + def _kept(self, left: pa.Table, right_keys: pl.DataFrame) -> pa.Array[Any]: + """Whether each left row's key is among ``right_keys``, as a boolean mask.""" + kept = polars_key_frame(left, self._keys, _ROW[0]).join( + right_keys, on=self._keys, how="semi" + ) + mask = np.zeros(left.num_rows, dtype=np.bool_) + mask[kept.get_column(_ROW[0]).to_numpy()] = True + return pa.array(mask) + + def _push(self, input_index: int, table: pa.Table) -> list[pa.Table]: + if not self._keys: + return [table] if input_index == 0 else [] + if input_index == 0: + right_keys = self._right_keys() + if right_keys is None: + kept = pa.array(np.zeros(table.num_rows, dtype=np.bool_)) + else: + kept = self._kept(table, right_keys) + if not self._closed[1]: + # A left row whose key holds a top-level null never matches. + undecided = table.filter( + pc.and_(pc.invert(kept), _has_whole_key(table, self._keys)) + ) + if undecided.num_rows: + self._waiting = ( + undecided + if self._waiting is None + else pa.concat_tables([self._waiting, undecided]) + ) + return [table.filter(kept)] + # A right batch: only its keys, and only rows whose keys hold no top-level null + # (the sync path drops those: such a key never matches). + keys = table.select(self._keys) + keys = keys.filter(_has_whole_key(keys, self._keys)) + if not keys.num_rows: + return [] + frame = polars_key_frame(keys, self._keys) + if not self._closed[0]: + self._right_frames.append(frame) + self._right_frame = None + if self._waiting is None: + return [] + kept = self._kept(self._waiting, frame) + decided = self._waiting.filter(kept) + remaining = self._waiting.filter(pc.invert(kept)) + self._waiting = remaining if remaining.num_rows else None + return [decided] + + def _close(self, input_index: int) -> list[pa.Table]: + if input_index == 0: + # No left row will arrive: the right keys can match nothing new. + self._right_frames, self._right_frame = [], None + else: + # No right row will arrive: the undecided left rows never match. + self._waiting = None + return [] diff --git a/tests/test_core/operators/test_streaming_joins.py b/tests/test_core/operators/test_streaming_joins.py new file mode 100644 index 000000000..35ee15176 --- /dev/null +++ b/tests/test_core/operators/test_streaming_joins.py @@ -0,0 +1,1117 @@ +"""Streaming join kernels give the sync join's rows, whatever the batches and arrivals. + +ITL-1362 (ITL-1347, stage 5): ``Join``, ``MergeJoin`` and ``SemiJoin`` run on the async +path as symmetric hash joins over Arrow record batches (``core/operators/streaming_joins``). +Row order is not a result on the async path (developer, November 22, 2026), so a kernel +must give the rows of the operator's sync ``static_process`` over the same inputs as a +multiset, with the same columns and Arrow types. + +The oracle is the sync operator over its inputs as a job's edges carry them: each input +rebuilt from its rows (``StaticOutputOperatorPod._materialize_upstream``, the row-built +form F of the ITL-1347 spec, where a ``null`` column is ``large_string``). These tests +feed each kernel those inputs' transport tables cut into batches of random sizes (empty +and one-row batches included), in random interleavings of the inputs and of their ends, +and compare. + +Field flags are compared as the stream built from the batches settles them: the +system-tag and source-info fields by their values over the complete table (the last step +of F, ``_flag_by_values``), on both sides, rows or none. +""" + +from __future__ import annotations + +import itertools +import random +import re +import struct +import warnings +from collections import Counter +from collections.abc import Callable, Sequence +from datetime import datetime, timezone +from decimal import Decimal +from typing import Any + +import pyarrow as pa +import pytest + +from orcapod.core.operators import Join, MergeJoin, SemiJoin +from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod +from orcapod.core.operators.streaming_joins import ( + TRANSPORT_COLUMNS, + StreamingJoin, + StreamingJoinKernel, + StreamingMergeJoin, + StreamingSemiJoin, +) +from orcapod.core.sources import ArrowTableSource +from orcapod.core.streams import ArrowTableStream +from orcapod.errors import InputValidationError +from orcapod.protocols.core_protocols import StreamProtocol +from orcapod.system_constants import constants + +from .several_items import MAIN, MIXED, P, PLAIN, Q, R, DATA_TAGS, Arrangement +from .several_items import DATA_FIRST_REVERSED, INTERLEAVED, TAGS_FIRST, Spec +from .several_items import make_source + +# How each source presents its columns besides its tag roles: the declared tag order, +# tags first; the reversed tag order, data first in reverse; tags and data interleaved. +VARIANTS = ( + "declared/tags_first", + "reversed/data_first_reversed", + "declared/interleaved", +) + + +def _arranged(spec: Spec, variant: str, roles: str) -> ArrowTableSource: + """``spec`` as a source in one of ``VARIANTS``, with the given tag roles.""" + order, layout = variant.split("/") + tags = spec.tags if order == "declared" else tuple(reversed(spec.tags)) + layouts = { + "tags_first": TAGS_FIRST, + "data_first_reversed": DATA_FIRST_REVERSED, + "interleaved": INTERLEAVED, + } + return make_source(spec, Arrangement(tags, layouts[layout], roles)) + + +SEEDS = range(12) +# The fields whose flags a complete table decides by its values. +SETTLED_PREFIXES = (constants.SYSTEM_TAG_PREFIX, constants.SOURCE_PREFIX) +# Batch sizes drawn for the cuts: empty and one-row batches included. +SIZES = (0, 1, 1, 2, 3, 5, 64) + + +@pytest.fixture(autouse=True) +def _quiet_provisional() -> Any: + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + yield + + +def _transport(stream: StreamProtocol) -> pa.Table: + """A stream's transport columns.""" + return stream.as_table(columns=TRANSPORT_COLUMNS) + + +def _row_built(stream: StreamProtocol, *, zero_rows: bool = False) -> StreamProtocol: + """``stream`` as an operator in a job reads it: rebuilt from its rows (form F).""" + return StaticOutputOperatorPod._materialize_upstream( # pyright: ignore[reportPrivateUsage] # the oracle + list(stream.iter_data()), stream, zero_rows=zero_rows + ) + + +def _sent(stream: StreamProtocol) -> pa.Table: + """An input's rows as the channel layer sends them: the row-built transport table.""" + return _transport(_row_built(stream)) + + +def _cut(table: pa.Table, rng: random.Random) -> list[pa.RecordBatch]: + """``table`` as record batches of random sizes, in order.""" + batches: list[pa.RecordBatch] = [] + start = 0 + while start < table.num_rows: + size = rng.choice(SIZES) + if size == 0: + batches.append( + pa.record_batch( + [pa.array([], field.type) for field in table.schema], + schema=table.schema, + ) + ) + else: + batches.extend(table.slice(start, size).combine_chunks().to_batches()) + start += size + return batches + + +def _arrivals( + tables: Sequence[pa.Table], rng: random.Random +) -> list[tuple[int, pa.RecordBatch | None]]: + """A random interleaving of every input's batches, each input closing after its last. + + ``None`` stands for an input's end. + """ + queues = [[*_cut(table, rng), None] for table in tables] + events: list[tuple[int, pa.RecordBatch | None]] = [] + while any(queues): + index = rng.choice([i for i, queue in enumerate(queues) if queue]) + events.append((index, queues[index].pop(0))) + return events + + +def _run( + kernel: StreamingJoinKernel, events: Sequence[tuple[int, pa.RecordBatch | None]] +) -> list[pa.RecordBatch]: + out: list[pa.RecordBatch] = [] + for index, batch in events: + out.extend(kernel.close(index) if batch is None else kernel.push(index, batch)) + return out + + +def _value(value: Any) -> Any: + """A value in a form that compares bit for bit (floats by their bits).""" + if isinstance(value, float): + return ("float", struct.pack(" pa.DataType: + """``arrow_type`` with every temporal type, at any depth, as its integer storage.""" + types = pa.types + if ( + types.is_timestamp(arrow_type) + or types.is_time64(arrow_type) + or types.is_duration(arrow_type) + or types.is_date64(arrow_type) + ): + return pa.int64() + if types.is_time32(arrow_type) or types.is_date32(arrow_type): + return pa.int32() + if types.is_large_list(arrow_type) or types.is_list(arrow_type): + item = arrow_type.value_field + inner = item.with_type(_integer_type(item.type)) + return ( + pa.large_list(inner) if types.is_large_list(arrow_type) else pa.list_(inner) + ) + if types.is_fixed_size_list(arrow_type): + item = arrow_type.value_field + return pa.list_(item.with_type(_integer_type(item.type)), arrow_type.list_size) + if types.is_struct(arrow_type): + return pa.struct( + [field.with_type(_integer_type(field.type)) for field in arrow_type] + ) + return arrow_type + + +def _exact(column: pa.ChunkedArray[Any]) -> pa.ChunkedArray[Any]: + """A column with its temporal values, at any depth, as their integer storage. + + Python values drop nanoseconds, so a temporal value is compared as its integer. + """ + target = _integer_type(column.type) + return column if target == column.type else column.cast(target) + + +def _rows(table: pa.Table) -> Counter[tuple[Any, ...]]: + """The rows as a multiset, every value compared exactly (floats by bits).""" + names = sorted(table.column_names) + exact = pa.table([_exact(table.column(name)) for name in names], names=names) + return Counter( + tuple(_value(row[name]) for name in names) for row in exact.to_pylist() + ) + + +def assert_same_fields(got: pa.Table, want: pa.Table) -> None: + """Same columns, types, field metadata and flags, after settling both (F's last step).""" + assert sorted(got.column_names) == sorted(want.column_names) + got = StaticOutputOperatorPod._flag_by_values(got.select(want.column_names)) # pyright: ignore[reportPrivateUsage] # F's last step + want = StaticOutputOperatorPod._flag_by_values(want) # pyright: ignore[reportPrivateUsage] # F's last step + for field in want.schema: + other = got.schema.field(field.name) + assert other.type == field.type, field.name + assert other.metadata == field.metadata, field.name + assert other.nullable == field.nullable, field.name + + +def assert_same_rows( + batches: Sequence[pa.RecordBatch], kernel: StreamingJoinKernel, expected: pa.Table +) -> None: + """The emitted batches equal ``expected`` as a multiset, with its columns and types. + + With no batch, the kernel's own zero-row result stands for its output. + """ + for batch in batches: + assert batch.schema.names == list(kernel.output_columns) + # One schema for every batch of the run; the fields a complete table decides + # by its values are declared nullable (``_flag_by_values`` settles them). + assert batch.schema == batches[0].schema + for field in batch.schema: + if field.name.startswith(SETTLED_PREFIXES): + assert field.nullable, field.name + got = ( + pa.Table.from_batches(batches) + if batches + else _transport(kernel.zero_row_result).select(list(kernel.output_columns)) + ) + assert_same_fields(got, expected) + assert _rows(got.select(expected.column_names)) == _rows(expected) + + +def _check( + make_kernel: Callable[[Sequence[StreamProtocol]], StreamingJoinKernel], + sync: Callable[..., StreamProtocol], + inputs: Sequence[StreamProtocol], + seeds: Sequence[int] = SEEDS, +) -> None: + rebuilt = [_row_built(stream) for stream in inputs] + expected = _transport(sync(*rebuilt)) + # The kernel's zero-row result is the sync operator's over the inputs rebuilt from + # their rows with none kept. + zero_rows = _transport( + sync(*(_row_built(stream, zero_rows=True) for stream in inputs)) + ) + tables = [_transport(stream) for stream in rebuilt] + for seed in seeds: + kernel = make_kernel(inputs) + assert_same_fields(_transport(kernel.zero_row_result), zero_rows) + # Column order is not a result on the async path (developer, November 22, + # 2026), so it is not compared with the sync result's. The kernel is + # consistent with itself: its zero-row result lists ``output_columns`` in + # order, and every emitted batch does too (``assert_same_rows``). + assert ( + list(kernel.output_columns) + == _transport(kernel.zero_row_result).column_names + ) + batches = _run(kernel, _arrivals(tables, random.Random(seed))) + assert_same_rows(batches, kernel, expected) + assert kernel.held_rows == 0 + + +# --------------------------------------------------------------------------- +# Inputs: keys of several types, with repeats, nulls, NaN and signed zeros +# --------------------------------------------------------------------------- + +NAN = float("nan") +KEY_POOLS: dict[str, tuple[pa.DataType, list[Any]]] = { + "int": (pa.int64(), [1, 2, 3, 2]), + "nullable_int": (pa.int64(), [1, None, 2, None]), + "string": (pa.large_string(), ["a", "b", "a", "c"]), + "float": (pa.float64(), [0.0, -0.0, NAN, 1.5]), + "decimal": (pa.decimal128(10, 2), [Decimal("1.10"), Decimal("2.00"), None]), + "timestamp_tz": ( + pa.timestamp("us", tz="UTC"), + [ + datetime(2026, 1, 1, tzinfo=timezone.utc), + datetime(2026, 1, 2, tzinfo=timezone.utc), + ], + ), + # Values that differ below a microsecond: compared as Arrow integers, never as + # Python values (which drop nanoseconds). + "time64_ns": (pa.time64("ns"), [1, 2, 1001, 2]), + "timestamp_ns": (pa.timestamp("ns", tz="UTC"), [1, 2, 1001, 2, None]), + "decimal256": ( + pa.decimal256(40, 2), + [Decimal("1.10"), Decimal("-2.00"), None, Decimal("1.10")], + ), + # Top-level nulls: a null list, struct or decimal256 key matches nothing, as on the + # sync path (a single-key Polars join would match two of them). + "struct": ( + pa.struct([("a", pa.int64()), ("b", pa.large_string())]), + [{"a": 1, "b": "x"}, {"a": 1, "b": "y"}, {"a": 2, "b": "x"}, None], + ), + "list": (pa.large_list(pa.int64()), [[1, 2], [2], [], [1, 2], None]), +} +# The pools whose keys may hold a top-level null. +NULL_POOLS = ("decimal", "decimal256", "list", "nullable_int", "struct", "timestamp_ns") + + +def _keyed_source( + source_id: str, + pool: str, + n: int, + data: dict[str, pa.DataType], + seed: int, + *, + extra_tag: str | None = None, +) -> ArrowTableSource: + """A source with tag ``k`` drawn from ``KEY_POOLS[pool]`` and the given data columns.""" + rng = random.Random(seed) + arrow_type, values = KEY_POOLS[pool] + columns: dict[str, pa.Array[Any]] = { + "k": pa.array([rng.choice(values) for _ in range(n)], arrow_type) + } + tags = ["k"] + if extra_tag is not None: + columns[extra_tag] = pa.array( + [rng.choice(["u", "v"]) for _ in range(n)], pa.large_string() + ) + tags.append(extra_tag) + for name, data_type in data.items(): + if pa.types.is_floating(data_type): + column = pa.array([rng.random() for _ in range(n)], data_type) + elif pa.types.is_integer(data_type): + column = pa.array(list(range(n)), data_type) + else: + column = pa.array([f"{name}{i}" for i in range(n)], data_type) + columns[name] = column + schema = pa.schema( + pa.field(name, column.type, nullable=column.null_count > 0) + for name, column in columns.items() + ) + return ArrowTableSource( + pa.table(list(columns.values()), schema=schema), + tag_columns=tags, + tag_only_columns=True, + source_id=source_id, + ) + + +# --------------------------------------------------------------------------- +# Join +# --------------------------------------------------------------------------- + + +def _join_kernel(inputs: Sequence[StreamProtocol]) -> StreamingJoinKernel: + return StreamingJoin(Join(), inputs) + + +@pytest.mark.parametrize("shared", ["one key", "two keys"]) +@pytest.mark.parametrize("pool", sorted(KEY_POOLS)) +def test_join_two_inputs_every_key_type(pool: str, shared: str) -> None: + left = _keyed_source( + "a", pool, 12, {"x": pa.int64(), "x2": pa.float64()}, 1, extra_tag="g" + ) + right = _keyed_source( + "b", + pool, + 10, + {"y": pa.int64(), "y2": pa.large_string()}, + 2, + extra_tag="g" if shared == "two keys" else None, + ) + for inputs in ((left, right), (right, left)): + _check(_join_kernel, Join().static_process, inputs) + + +@pytest.mark.parametrize("pool", NULL_POOLS) +def test_join_three_inputs_with_null_keys(pool: str) -> None: + sources = [ + _keyed_source(name, pool, 10, {f"x{name}": pa.int64()}, seed) + for seed, name in enumerate("abc") + ] + for order in itertools.permutations(range(3)): + _check( + _join_kernel, + Join().static_process, + [sources[i] for i in order], + seeds=range(3), + ) + + +@pytest.mark.parametrize( + ("arrow_type", "values"), + [ + (pa.large_list(pa.int64()), [None, [1]]), + (pa.struct([("a", pa.int64())]), [None, {"a": 1}]), + (pa.decimal256(40, 2), [None, Decimal("1.00")]), + ], +) +@pytest.mark.parametrize( + ("operator", "kernel"), + [ + (Join(), StreamingJoin), + (MergeJoin(), StreamingMergeJoin), + (SemiJoin(), StreamingSemiJoin), + ], +) +def test_a_null_key_matches_nothing( + arrow_type: pa.DataType, values: list[Any], operator: Any, kernel: Any +) -> None: + # The reviewer's minimal case: two null keys, one shared key, one-row batches. + def keyed(source_id: str, data: str) -> ArrowTableSource: + return ArrowTableSource( + pa.table({"k": pa.array(values, arrow_type), data: [1, 2]}), + tag_columns=["k"], + tag_only_columns=True, + source_id=source_id, + ) + + inputs = (keyed("a", "v"), keyed("b", "w")) + expected = _transport(operator.static_process(*map(_row_built, inputs))) + assert expected.num_rows == 1 + _check(lambda i: kernel(operator, i), operator.static_process, inputs) + + +@pytest.mark.parametrize("order", list(itertools.permutations(range(3)))) +def test_join_three_inputs_every_argument_order(order: tuple[int, ...]) -> None: + sources = [ + make_source(MAIN), + make_source(P), + make_source(Q), + ] + inputs = [sources[i] for i in order] + _check(_join_kernel, Join().static_process, inputs, seeds=range(6)) + + +@pytest.mark.parametrize("variant", VARIANTS) +@pytest.mark.parametrize("roles", [PLAIN, DATA_TAGS, MIXED]) +def test_join_four_inputs_in_each_tag_role(roles: str, variant: str) -> None: + # Data-tags shared by several inputs keep their members' tokens pending through + # the chain and fold them when the last step emits (``join_v1``). + sources = [_arranged(spec, variant, roles) for spec in (MAIN, P, Q, R)] + for inputs in (sources, list(reversed(sources))): + _check(_join_kernel, Join().static_process, inputs, seeds=range(6)) + + +def test_join_inputs_sharing_no_tag_give_every_pair() -> None: + left = _keyed_source("a", "int", 5, {"x": pa.int64()}, 3) + right = ArrowTableSource( + pa.table({"h": ["p", "q", "r"], "y": [1.0, 2.0, 3.0]}), + tag_columns=["h"], + tag_only_columns=True, + source_id="h", + ) + _check(_join_kernel, Join().static_process, (left, right)) + + +def test_join_inputs_of_one_pipeline_hash_sort_their_system_tags() -> None: + # One schema, so one pipeline hash: the system-tag values are sorted per row. Two + # inputs of one schema share their data columns, so only data-tags (merged by the + # join, their tokens folded) can be joined. + def keys_only(source_id: str, values: list[str]) -> ArrowTableSource: + return ArrowTableSource( + pa.table({"k": pa.array(values, pa.large_string())}), + tag_columns=["k"], + source_id=source_id, + ) + + first = keys_only("a", ["a", "b", "a", "c", "b"]) + second = keys_only("b", ["b", "a", "b", "d"]) + assert first.pipeline_hash() == second.pipeline_hash() + for inputs in ((first, second), (second, first)): + _check(_join_kernel, Join().static_process, inputs) + + +def test_join_of_one_input_passes_its_rows() -> None: + _check(_join_kernel, Join().static_process, (make_source(MAIN),)) + + +# --------------------------------------------------------------------------- +# MergeJoin +# --------------------------------------------------------------------------- + + +def _merge_kernel(inputs: Sequence[StreamProtocol]) -> StreamingJoinKernel: + return StreamingMergeJoin(MergeJoin(), inputs) + + +@pytest.mark.parametrize("shared", ["one key", "two keys"]) +@pytest.mark.parametrize( + "pool", ["int", "nullable_int", "float", "struct", "list", "decimal256"] +) +def test_merge_join_colliding_columns_in_both_argument_orders( + pool: str, shared: str +) -> None: + left = _keyed_source( + "a", pool, 10, {"x": pa.int64(), "c": pa.float64()}, 6, extra_tag="g" + ) + right = _keyed_source( + "b", + pool, + 8, + {"c": pa.float64(), "y": pa.int64()}, + 7, + extra_tag="g" if shared == "two keys" else None, + ) + for inputs in ((left, right), (right, left)): + _check(_merge_kernel, MergeJoin().static_process, inputs) + + +@pytest.mark.parametrize("variant", VARIANTS) +@pytest.mark.parametrize("roles", [PLAIN, DATA_TAGS, MIXED]) +def test_merge_join_in_each_tag_role(roles: str, variant: str) -> None: + main = _arranged(MAIN, variant, roles) + partner = _arranged(P, variant, roles) + for inputs in ((main, partner), (partner, main)): + _check(_merge_kernel, MergeJoin().static_process, inputs) + + +# --------------------------------------------------------------------------- +# SemiJoin +# --------------------------------------------------------------------------- + + +def _semi_kernel(inputs: Sequence[StreamProtocol]) -> StreamingJoinKernel: + return StreamingSemiJoin(SemiJoin(), inputs) + + +@pytest.mark.parametrize("shared", ["one key", "two keys"]) +@pytest.mark.parametrize("pool", sorted(KEY_POOLS)) +def test_semi_join_every_key_type(pool: str, shared: str) -> None: + left = _keyed_source("a", pool, 12, {"x": pa.int64()}, 8, extra_tag="g") + right = _keyed_source( + "b", + pool, + 5, + {"y": pa.int64()}, + 9, + extra_tag="g" if shared == "two keys" else None, + ) + _check(_semi_kernel, SemiJoin().static_process, (left, right)) + + +@pytest.mark.parametrize("variant", VARIANTS) +@pytest.mark.parametrize("roles", [PLAIN, DATA_TAGS, MIXED]) +def test_semi_join_in_each_tag_role(roles: str, variant: str) -> None: + main = _arranged(MAIN, variant, roles) + for partner_spec in (P, Q): + partner = make_source(partner_spec, rows=[0, 2]) + _check(_semi_kernel, SemiJoin().static_process, (main, partner)) + + +def test_semi_join_without_a_shared_tag_passes_every_left_row() -> None: + left = make_source(MAIN) + right = ArrowTableSource( + pa.table({"h": ["p"], "y": [1.0]}), + tag_columns=["h"], + tag_only_columns=True, + source_id="h", + ) + _check(_semi_kernel, SemiJoin().static_process, (left, right)) + + +# --------------------------------------------------------------------------- +# Checks before the first batch (e1, ITL-856) +# --------------------------------------------------------------------------- + + +def _typed(source_id: str, key_type: pa.DataType, n: int) -> ArrowTableStream: + table = pa.table( + {"k": pa.array(list(range(n)), key_type), source_id: pa.array(list(range(n)))} + ) + return ArrowTableStream(table, tag_columns=["k"]) + + +@pytest.mark.parametrize( + ("operator", "kernel"), + [ + (Join(), StreamingJoin), + (MergeJoin(), StreamingMergeJoin), + (SemiJoin(), StreamingSemiJoin), + ], +) +def test_disagreeing_key_types_raise_before_the_first_batch( + operator: Any, kernel: Any +) -> None: + # The sync path's error over rows ... + with pytest.raises(InputValidationError) as sync_error: + operator.static_process(_typed("x", pa.int16(), 2), _typed("y", pa.int32(), 2)) + # ... is the kernel's, from the descriptions, also when an input has no row. + with pytest.raises(InputValidationError) as kernel_error: + kernel(operator, (_typed("x", pa.int16(), 0), _typed("y", pa.int32(), 2))) + assert str(kernel_error.value) == str(sync_error.value) + + +def test_a_batch_must_hold_its_inputs_columns_and_types() -> None: + left, right = make_source(MAIN), make_source(P) + kernel = StreamingJoin(Join(), (left, right)) + table = _transport(left) + with pytest.raises(ValueError, match="lacks"): + kernel.push(0, table.drop_columns(["d1"]).to_batches()[0]) + with pytest.raises(ValueError, match="'d1'"): + kernel.push( + 0, + table.set_column( + table.column_names.index("d1"), + "d1", + table.column("d1").cast(pa.int32()), + ).to_batches()[0], + ) + + +def test_a_rejected_batch_changes_nothing() -> None: + # A batch refused for one column leaves the kernel as it was: the corrected batch + # is taken, as on a fresh kernel. + left = _with_null_column("x", True, "v", tag=False) + right = _with_null_column("x", False, "w", tag=False) + sent = _sent(left).combine_chunks() + wrong = sent.set_column( + sent.column_names.index("v"), "v", sent.column("v").cast(pa.int32()) + ) + for operator, kernel in ((MergeJoin(), StreamingMergeJoin),): + instance = kernel(operator, (left, right)) + with pytest.raises(ValueError, match="'v'"): + instance.push(0, wrong.to_batches()[0]) + out = instance.push(0, sent.to_batches()[0]) + out += instance.push(1, _sent(right).combine_chunks().to_batches()[0]) + out += instance.close(0) + instance.close(1) + expected = _transport( + operator.static_process(_row_built(left), _row_built(right)) + ) + assert_same_rows(out, instance, expected) + + +def test_an_input_closes_once_and_takes_no_batch_after() -> None: + left, right = make_source(MAIN), make_source(P) + kernel = StreamingJoin(Join(), (left, right)) + assert kernel.close(0) == [] + with pytest.raises(ValueError, match="closed already"): + kernel.close(0) + with pytest.raises(ValueError, match="closed already"): + kernel.push(0, _transport(left).to_batches()[0]) + with pytest.raises(ValueError, match="no input 2"): + kernel.push(2, _transport(left).to_batches()[0]) + + +# --------------------------------------------------------------------------- +# What a kernel holds +# --------------------------------------------------------------------------- + + +def test_join_drops_a_sides_rows_when_the_other_side_closes() -> None: + left, right = make_source(MAIN), make_source(P) + kernel = StreamingJoin(Join(), (left, right)) + left_table, right_table = _transport(left), _transport(right) + kernel.push(0, left_table.to_batches()[0]) + kernel.push(1, right_table.slice(0, 1).to_batches()[0]) + assert kernel.held_rows == left_table.num_rows + 1 + # The right input ends: no left row can match anything new, the right rows stay. + kernel.close(1) + assert kernel.held_rows == 1 + # A left row arriving now is matched against the right rows and not kept. + kernel.push(0, left_table.slice(0, 2).to_batches()[0]) + assert kernel.held_rows == 1 + kernel.close(0) + assert kernel.held_rows == 0 + + +def test_semi_join_holds_undecided_left_rows_only_until_the_right_input_ends() -> None: + left, right = make_source(MAIN), make_source(P, rows=[0]) + kernel = StreamingSemiJoin(SemiJoin(), (left, right)) + left_table = _transport(left) + assert kernel.push(0, left_table.to_batches()[0]) == [] + assert kernel.held_rows == left_table.num_rows + emitted = kernel.push(1, _transport(right).to_batches()[0]) + matched = sum(batch.num_rows for batch in emitted) + assert matched > 0 + assert kernel.held_rows == left_table.num_rows - matched + 1 + # The right input ends: the undecided left rows are dropped; the right keys stay + # for left rows still to arrive. + kernel.close(1) + assert kernel.held_rows == 1 + kernel.close(0) + assert kernel.held_rows == 0 + + +def test_kernels_change_no_sync_result() -> None: + # A kernel applies the operator only to zero-row inputs; its sync result over rows + # is the same before and after kernels were made from it. + inputs = (make_source(MAIN), make_source(P)) + before = _rows(_transport(Join().static_process(*inputs))) + operator = Join() + StreamingJoin(operator, inputs) + assert _rows(_transport(operator.static_process(*inputs))) == before + + +# --------------------------------------------------------------------------- +# Inputs rebuilt from rows: ``null`` columns are ``large_string`` (form F, ITL-1319) +# --------------------------------------------------------------------------- + + +def _with_null_column( + name: str, null_type: bool, data: str, *, tag: bool, n: int = 2 +) -> ArrowTableStream: + """A raw stream with column ``name`` all null, typed ``null`` or ``large_string``.""" + column_type = pa.null() if null_type else pa.large_string() + columns: dict[str, pa.Array[Any]] = { + "k": pa.array(list(range(n)), pa.int64()), + name: pa.array([None] * n, column_type), + data: pa.array(list(range(n)), pa.int64()), + } + return ArrowTableStream( + pa.table(list(columns.values()), names=list(columns)), + tag_columns=["k", name] if tag else ["k"], + ) + + +ALL_KERNELS: list[tuple[Any, Any]] = [ + (Join(), StreamingJoin), + (MergeJoin(), StreamingMergeJoin), + (SemiJoin(), StreamingSemiJoin), +] + + +@pytest.mark.parametrize(("operator", "kernel"), ALL_KERNELS) +def test_a_null_typed_tag_meets_a_large_string_tag_as_rows_carry_it( + operator: Any, kernel: Any +) -> None: + # Rows carry the ``null`` tag as ``large_string``: the sync path over the inputs + # rebuilt from rows accepts the pair (all null, so nothing matches), and so does + # the kernel, built from the descriptions. + left = _with_null_column("n", True, "v", tag=True) + right = _with_null_column("n", False, "w", tag=True) + for inputs in ((left, right), (right, left)): + _check(lambda i: kernel(operator, i), operator.static_process, inputs) + + +def test_merge_join_merges_a_null_typed_and_a_large_string_column() -> None: + left = _with_null_column("x", True, "v", tag=False) + right = _with_null_column("x", False, "w", tag=False) + for inputs in ((left, right), (right, left)): + expected = _transport(MergeJoin().static_process(*map(_row_built, inputs))) + assert expected.column("x").to_pylist() == [[None, None]] * 2 + _check(_merge_kernel, MergeJoin().static_process, inputs) + + +@pytest.mark.parametrize(("operator", "kernel"), ALL_KERNELS) +def test_a_zero_row_batch_of_the_zero_row_form_does_not_fix_a_type( + operator: Any, kernel: Any +) -> None: + # Both inputs describe ``x`` as ``null`` (a colliding data column for MergeJoin, a + # shared tag otherwise). An empty batch typed as the zero-row form (``null``) holds + # no value and is taken; the populated batches after it are in the row-built form + # (``large_string``) and are taken too. + tag = not isinstance(operator, MergeJoin) + left = _with_null_column("x", True, "v", tag=tag) + right = _with_null_column("x", True, "w", tag=tag) + for inputs in ((left, right), (right, left)): + instance = kernel(operator, inputs) + out: list[pa.RecordBatch] = [] + for index, stream in enumerate(inputs): + schema = _transport(stream).schema + empty = pa.record_batch( + [pa.array([], field.type) for field in schema], schema=schema + ) + assert pa.types.is_null(empty.schema.field("x").type) + out += instance.push(index, empty) + out += instance.push(index, _sent(stream).combine_chunks().to_batches()[0]) + for index in range(2): + out += instance.close(index) + expected = _transport(operator.static_process(*map(_row_built, inputs))) + assert_same_rows(out, instance, expected) + + +def test_a_null_typed_input_that_ends_empty_is_read_in_its_zero_row_form() -> None: + # With no rows, the sync path reads an input in its zero-row form, where ``null`` + # stays ``null``: a ``null`` key against a ``large_string`` one is refused, while + # the kernel, which cannot know the input will be empty, refuses at the last close. + for operator, kernel in ALL_KERNELS: + left = _with_null_column("n", True, "v", tag=True, n=0) + right = _with_null_column("n", False, "w", tag=True) + with pytest.raises(Exception) as sync_error: + operator.static_process(_row_built(left), _row_built(right)) + instance = kernel(operator, (left, right)) + assert instance.push(1, _sent(right).combine_chunks().to_batches()[0]) == [] + assert instance.close(0) == [] + with pytest.raises(type(sync_error.value)) as kernel_error: + instance.close(1) + assert str(kernel_error.value) == str(sync_error.value) + # Two ``null`` inputs that both end empty are accepted, as on the sync path. + both = (left, _with_null_column("n", True, "w", tag=True, n=0)) + operator.static_process(*map(_row_built, both)) + instance = kernel(operator, both) + assert instance.close(0) == [] + assert instance.close(1) == [] + + +# --------------------------------------------------------------------------- +# System-tag flags are settled on the complete table +# --------------------------------------------------------------------------- + + +def test_merge_join_over_a_join_of_inputs_of_one_pipeline_hash() -> None: + # A Join of inputs tied on pipeline hash declares its system tags nullable; a table + # built from its rows flags them by their values. MergeJoin over it, in the kernel, + # declares them nullable and the complete table settles them as the sync path's. + def tied(source_id: str, keys: list[int], groups: list[str]) -> ArrowTableSource: + return ArrowTableSource( + pa.table( + { + "k": pa.array(keys, pa.int64()), + "g": pa.array(groups, pa.large_string()), + } + ), + tag_columns=["k", "g"], + source_id=source_id, + ) + + joined = Join()( + tied("a", [1, 2, 3], ["x", "y", "x"]), + tied("b", [2, 1, 3], ["y", "x", "x"]), + tied("c", [3, 2, 1], ["x", "y", "x"]), + ) + other = _keyed_source("o", "int", 6, {"z": pa.int64()}, 4) + for inputs in ((joined, other), (other, joined)): + _check(_merge_kernel, MergeJoin().static_process, inputs) + _check(_join_kernel, Join().static_process, inputs, seeds=range(4)) + + +# --------------------------------------------------------------------------- +# A refusal that depends on values is raised when its batch arrives +# --------------------------------------------------------------------------- + + +def _data_tag_stream(data: str, tokens: list[list[str]]) -> ArrowTableStream: + """A stream with data-tag ``k`` whose source info is a token list per row.""" + token_list = pa.large_list(pa.large_string()) + return ArrowTableStream( + pa.table( + { + "k": pa.array([1, 2], pa.int64()), + data: pa.array([1, 2], pa.int64()), + "_source_k": pa.array(tokens, token_list), + f"_source_{data}": pa.array([["s"], ["t"]], token_list), + } + ), + tag_columns=["k"], + data_tags=["k"], + ) + + +@pytest.mark.parametrize( + ("operator", "kernel"), [(Join(), StreamingJoin), (MergeJoin(), StreamingMergeJoin)] +) +def test_source_info_lists_of_different_lengths_raise_when_their_batch_arrives( + operator: Any, kernel: Any +) -> None: + # The descriptions agree (one type of token list); the lengths are values. The + # sync path refuses the run; the kernel raises the same error when the offending + # pair arrives, after the rows already decided (module docstring). + left = _data_tag_stream("v", [["a"], ["b"]]) + right = _data_tag_stream("w", [["c"], ["d", "e"]]) + with pytest.raises(ValueError, match="different lengths") as sync_error: + operator.static_process(_row_built(left), _row_built(right)) + instance = kernel(operator, (left, right)) + instance.push(0, _sent(left).combine_chunks().to_batches()[0]) + sent = _sent(right).combine_chunks() + emitted = instance.push(1, sent.slice(0, 1).to_batches()[0]) + assert sum(batch.num_rows for batch in emitted) == 1 + with pytest.raises(ValueError, match="different lengths") as kernel_error: + instance.push(1, sent.slice(1, 1).to_batches()[0]) + assert str(kernel_error.value) == str(sync_error.value) + + +def test_join_releases_every_step_once_an_input_ends_empty() -> None: + # Three inputs: when the first in canonical order ends with no row, no step can + # emit again, so the rows of the other inputs are not held while they are open. + sources = [make_source(MAIN), make_source(P), make_source(Q)] + order = sorted(range(3), key=lambda i: sources[i].pipeline_hash().to_hex()) + for first in (order[0], order[1]): + kernel = StreamingJoin(Join(), sources) + assert kernel.close(first) == [] + for index in range(3): + if index != first: + kernel.push( + index, _sent(sources[index]).combine_chunks().to_batches()[0] + ) + assert kernel.held_rows == 0 + rest = [index for index in range(3) if index != first] + assert kernel.close(rest[0]) == [] + assert kernel.close(rest[1]) == [] + + +def test_join_releases_the_steps_before_one_that_cannot_emit() -> None: + # The last input in canonical order ends empty: the earlier steps' rows could + # only reach that step, so none is held. + sources = [make_source(MAIN), make_source(P), make_source(Q)] + order = sorted(range(3), key=lambda i: sources[i].pipeline_hash().to_hex()) + kernel = StreamingJoin(Join(), sources) + assert kernel.close(order[2]) == [] + for index in order[:2]: + kernel.push(index, _sent(sources[index]).combine_chunks().to_batches()[0]) + assert kernel.held_rows == 0 + + +@pytest.mark.parametrize("pool", NULL_POOLS) +def test_semi_join_never_holds_a_left_row_with_a_null_key(pool: str) -> None: + left = _keyed_source("a", pool, 30, {"x": pa.int64()}, 11) + # The same seed: a right row for every left key, the null ones included. + right = _keyed_source("b", pool, 30, {"y": pa.int64()}, 11) + left_rows = _sent(left).combine_chunks() + null_keys = left_rows.column("k").null_count + assert null_keys > 0 + kernel = StreamingSemiJoin(SemiJoin(), (left, right)) + assert kernel.push(0, left_rows.to_batches()[0]) == [] + assert kernel.held_rows == left_rows.num_rows - null_keys + # The left input ends and the right rows arrive: every left row with a key is + # emitted, and nothing is held. + kernel.close(0) + emitted = kernel.push(1, _sent(right).combine_chunks().to_batches()[0]) + assert sum(batch.num_rows for batch in emitted) == left_rows.num_rows - null_keys + assert kernel.held_rows == 0 + assert kernel.close(1) == [] + + +def test_join_still_refuses_merged_source_info_when_a_later_input_ends_empty() -> None: + # The sync path joins the inputs in canonical order: it merges the first two + # inputs' data-tag source info (refusing lists of different lengths) before it + # meets the empty last input. The kernel's earlier steps keep matching after that + # input closed, so it refuses the same pair with the same error. + def stream(data: str, tokens: list[list[str]]) -> ArrowTableStream: + return ( + _data_tag_stream(data, tokens) if tokens else _empty_data_tag_stream(data) + ) + + variants = { + name: [ + stream("v", [] if name == "v" else [["a"], ["b"]]), + stream("w", [] if name == "w" else [["c"], ["d", "e"]]), + stream("z", [] if name == "z" else [["f"], ["g", "h", "i"]]), + ] + for name in ("v", "w", "z") + } + checked = 0 + for name, inputs in variants.items(): + order = sorted(range(3), key=lambda i: inputs[i].pipeline_hash().to_hex()) + empty = "vwz".index(name) + if order[2] != empty: + continue + first, second = order[0], order[1] + rebuilt = [_row_built(s) for s in inputs] + with pytest.raises(ValueError, match="different lengths") as sync_error: + Join().static_process(*rebuilt) + kernel = StreamingJoin(Join(), inputs) + assert kernel.close(empty) == [] + kernel.push(first, _sent(inputs[first]).combine_chunks().to_batches()[0]) + with pytest.raises(ValueError, match="different lengths") as kernel_error: + kernel.push(second, _sent(inputs[second]).combine_chunks().to_batches()[0]) + assert str(kernel_error.value) == str(sync_error.value) + checked += 1 + assert checked > 0 + + +def _empty_data_tag_stream(data: str) -> ArrowTableStream: + """``_data_tag_stream``'s columns, with no row.""" + return ArrowTableStream( + _data_tag_stream(data, [["x"], ["y"]]) + .as_table(columns=TRANSPORT_COLUMNS) + .slice(0, 0), + tag_columns=["k"], + data_tags=["k"], + ) + + +@pytest.mark.parametrize(("operator", "kernel"), ALL_KERNELS) +def test_an_empty_run_ends_with_the_types_of_the_sync_result( + operator: Any, kernel: Any +) -> None: + # The left input ends with no row and a ``null`` data column: the sync result has + # no row and keeps ``x: null``. The kernel emits nothing and its zero-row result, + # the output's description, takes the sync result's types at the last close. + left = _with_null_column("x", True, "v", tag=False, n=0) + right = ArrowTableStream( + pa.table({"k": pa.array([0, 1], pa.int64()), "y": pa.array([1, 2])}), + tag_columns=["k"], + ) + want = _transport(operator.static_process(_row_built(left), _row_built(right))) + assert want.num_rows == 0 + assert pa.types.is_null(want.schema.field("x").type) + instance = kernel(operator, (left, right)) + out = instance.push(1, _sent(right).combine_chunks().to_batches()[0]) + out += instance.close(1) + instance.close(0) + assert out == [] + assert_same_rows(out, instance, want) + + +def test_a_source_refuses_a_null_typed_column() -> None: + # The kernels' domain is what a job carries (module docstring): no source takes a + # ``null``-typed column, with rows or without, tag or data. + for table, tags in ( + (pa.table({"k": [1], "x": pa.array([None], pa.null())}), ["k"]), + (pa.table({"k": pa.array([None], pa.null()), "x": [1]}), ["k"]), + ( + pa.table({"k": pa.array([], pa.int64()), "x": pa.array([], pa.null())}), + ["k"], + ), + ): + with pytest.raises(ValueError, match="type null"): + ArrowTableSource( + table, tag_columns=tags, tag_only_columns=True, source_id="s" + ) + + +def _tokens_stream( + data: str, keys: list[int], tokens: list[list[str]] +) -> ArrowTableStream: + """A stream with data-tag ``k`` (keys in this order) and token lists per row.""" + token_list = pa.large_list(pa.large_string()) + return ArrowTableStream( + pa.table( + { + "k": pa.array(keys, pa.int64()), + data: pa.array(list(range(len(keys))), pa.int64()), + "_source_k": pa.array(tokens, token_list), + f"_source_{data}": pa.array([["s"]] * len(keys), token_list), + } + ), + tag_columns=["k"], + data_tags=["k"], + ) + + +@pytest.mark.parametrize( + ("operator", "kernel"), [(Join(), StreamingJoin), (MergeJoin(), StreamingMergeJoin)] +) +def test_with_several_offending_pairs_the_first_observed_is_refused( + operator: Any, kernel: Any +) -> None: + # Both pairs (k=1, k=2) have token lists of different lengths. Which one is + # reported depends on arrival; the type is the sync path's and the message has its + # form (module docstring). + left = _tokens_stream("v", [1, 2], [["a"], ["b"]]) + right = _tokens_stream("w", [2, 1], [["c", "d"], ["e", "f", "g"]]) + form = r"cannot merge source info of lists of different lengths: \[(\d+), (\d+)\]" + with pytest.raises(ValueError, match=form): + operator.static_process(_row_built(left), _row_built(right)) + inputs = (left, right) + for whole in (0, 1): + instance = kernel(operator, inputs) + instance.push(whole, _sent(inputs[whole]).combine_chunks().to_batches()[0]) + first_row = _sent(inputs[1 - whole]).combine_chunks().slice(0, 1) + with pytest.raises(ValueError, match=form) as error: + instance.push(1 - whole, first_row.to_batches()[0]) + # Each schedule exposes one pair: the left input whole, then the right's first + # row (k=2: lengths 1 and 2); the right whole, then the left's first row (k=1: + # lengths 1 and 3). The order of the two lengths follows the merge's sides. + lengths = re.search(form, str(error.value)) + assert lengths is not None + assert sorted(map(int, lengths.groups())) == ([1, 2] if whole == 0 else [1, 3]) + + +def test_join_releases_every_step_once_an_input_ends_with_only_null_keys() -> None: + # A closed input whose rows all have a null key can match nothing: as good as + # empty, so no step holds rows for it. + def keyed(source_id: str, keys: list[int | None], data: str) -> ArrowTableSource: + column = pa.array(keys, pa.int64()) + return ArrowTableSource( + pa.table( + [column, pa.array(list(range(len(keys))), pa.int64())], + schema=pa.schema( + [ + pa.field("k", pa.int64(), nullable=True), + pa.field(data, pa.int64()), + ] + ), + ), + tag_columns=["k"], + tag_only_columns=True, + source_id=source_id, + ) + + for null_input in range(3): + sources = [ + keyed( + name, + [None, None] if i == null_input else [1, 2, 3, 1, 2, 3], + f"d{name}", + ) + for i, name in enumerate("abc") + ] + kernel = StreamingJoin(Join(), sources) + kernel.push( + null_input, _sent(sources[null_input]).combine_chunks().to_batches()[0] + ) + assert kernel.close(null_input) == [] + for index in range(3): + if index != null_input: + kernel.push( + index, _sent(sources[index]).combine_chunks().to_batches()[0] + ) + assert kernel.held_rows == 0, null_input + + +def test_the_oracle_tells_nested_temporal_values_apart() -> None: + # Python values drop nanoseconds; the oracle compares temporal values, at any + # depth, as their integers. + for arrow_type, wrap in ( + (pa.large_list(pa.time64("ns")), lambda v: [v]), + (pa.struct([("t", pa.timestamp("ns", tz="UTC"))]), lambda v: {"t": v}), + ): + one = pa.table({"x": pa.array([wrap(1)], arrow_type)}) + two = pa.table({"x": pa.array([wrap(2)], arrow_type)}) + assert _rows(one) != _rows(two) + assert _rows(one) == _rows(pa.table({"x": pa.array([wrap(1)], arrow_type)})) From 25386a1a432106064be8f3ae652869c9571aa2c6 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 06:47:17 -0800 Subject: [PATCH 35/86] test(pipeline): name ITL-1366's input as difference e10 (ITL-1360) A declared source slot over a narrower source with one data-tag among two tags: main raises ValueError when the source's rows are rebuilt for its successor; the sync path completes with the rows the bind describes; the async path raises as main does until stage 5. Spec row e10, provisional (coordinator decision 2026-11-22, pending the developer). Co-Authored-By: Claude Opus 5.5 --- .../dev/specs/itl-1347-job-table-transport.md | 3 +- .../test_declared_slot_one_data_tag.py | 93 +++++++++++++++++++ 2 files changed, 95 insertions(+), 1 deletion(-) create mode 100644 tests/test_pipeline/test_declared_slot_one_data_tag.py diff --git a/docs/dev/specs/itl-1347-job-table-transport.md b/docs/dev/specs/itl-1347-job-table-transport.md index 08d27f4ba..430710056 100644 --- a/docs/dev/specs/itl-1347-job-table-transport.md +++ b/docs/dev/specs/itl-1347-job-table-transport.md @@ -509,7 +509,7 @@ with the developer's approval, given row by row. Each row gets its own test: it row, by name. The developer has accepted some behaviours of `main` that are not listed as rows; they are kept as `main` has them, and documented below. -**No row changes a sync-path result, except e9** (provisional, pending the developer). On +**No row changes a sync-path result, except e9 and e10** (provisional, pending the developer). On the sync path the branch equals `main` byte for byte. Stages 1–4 hold this by construction and by L0–L5, and a lemma that fails stops its stage. @@ -522,6 +522,7 @@ and by L0–L5, and a lemma that fails stops its stage. | e7 | What a consumer does after its producer failed (async, failure path) | The producer closes its output in `finally`, so a consumer sees a normal end and may finish, and a `LOG` operator node may store, a partial result before the task group cancels it | Readers raise `UpstreamFailedError` at the failure point instead of seeing a normal end, so no consumer finishes, or stores its result, as if its input were complete. Batches a consumer processed before the failure are still processed, and a streaming node may already have passed them on or a function node stored results for them, as on `main`; there is no rollback. A barrier operator never computes over a partial input. The run raises the producer's own error, as today | A candidate race, to be confirmed with a reproducer in stage 5: a `fail_fast` function node raising on row 3 of 6, feeding a `Select` node in `LOG` mode; check the operator cache after the failed run. If `main` never stores in practice, this row is no difference | filed by the developer only once a test reproduces it | | e8 | Meta columns of an async side-effect node's rows | An async side-effect node passes on and holds the rows it receives as they are, so a computed row keeps its `__computed` meta column (from the cached function pod), and the node's `as_table(all_info=True)` shows it. On sync, its input is rebuilt from rows (`_rows_to_table` drops meta), so the column is absent | Async drops input meta columns as sync does. With table transport this follows from the transport columns, which hold no meta column | A `main` bug: the async and sync paths give the node different columns. Found by the stage 0 harness on `job-speed` 0e15d0db, which does not change side-effect nodes; the stage 0 differential checks it on pinned `main`. Reproducer: a function node (with a result store) feeding a `tap_pod`, async against sync, comparing the side-effect node's `as_table(all_info=True)` columns | approved (developer, 2026-11-22) | | e9 | A sync function node whose output rows disagree on a column's Arrow type | A node with no successor completes the run; its `as_table()` raises `InputValidationError` ("Function node 'double': Rows disagree on the Arrow type of column 'k': int32 and uint32"). A node with a successor fails the run with a bare pyarrow `ArrowInvalid`, raised where the successor's input is rebuilt | The node builds its output stream when it runs (stage 2), so the run fails at the node, once its writes are committed (a failed write is still reported first, as on `main`) and before the node takes the run, with the `InputValidationError` `as_table()` raises (same type and message), with or without a successor; the node then holds no run. What is stored equals `main`'s: the row computed before the disagreement could be seen is stored, as on `main` (2 stored rows before the run, 3 after, on both) | Not a `main` bug to fix: a consequence of building the output stream in `execute`, and for a node with a successor an improvement (`main`'s `ArrowInvalid` names nothing). It arises only from a store written before ITL-928, whose cached rows give a `uint32` tag back as `int32`; such a store must be rebuilt. Reproducer: `tests/test_core/function_pod/test_function_node_arrow_types.py::test_new_rows_over_a_store_written_before_the_fix_raise_naming_the_column` (leaf and with successor) | provisional, coordinator decision 2026-11-22, pending developer | +| e10 | ITL-1366: a declared source slot over a narrower source with one data-tag among two tags | The run raises `ValueError` ("Duplicate column name 'k'") where the source's rows are rebuilt for its successor (`_rows_to_table`: the row's tag and data both hold the data-tag), when exactly one of the two tags is a data-tag and the tags are declared `j, k`; the source node has ended, the successor never starts. The same on the async path | Sync: the source node hands on F of the declared table (`_DeclaredForm.apply` of the bound table, the data-tag once, among the tags) and the run completes with the rows the bind describes. Async: as on `main` until stage 5 | A `main` bug (ITL-1366): the bind is accepted, then the rows cannot be built. Reproducer: `tests/test_pipeline/test_declared_slot_one_data_tag.py` (no, one or both data-tags, both tag orders, sync and async) | provisional, coordinator decision 2026-11-22, pending developer | **Resolved: refusals after rows have flowed (was c, question 9).** The developer's `Rejoin` rule (ITL-1355) removes every data-dependent refusal from `Rejoin`: it checks only what its diff --git a/tests/test_pipeline/test_declared_slot_one_data_tag.py b/tests/test_pipeline/test_declared_slot_one_data_tag.py new file mode 100644 index 000000000..490c5f006 --- /dev/null +++ b/tests/test_pipeline/test_declared_slot_one_data_tag.py @@ -0,0 +1,93 @@ +"""A declared slot over a narrower source with one data-tag among two tags (ITL-1366, e10). + +A source slot declared from a source whose ``x`` is ``int | None``, bound to the same +table with ``x: int`` (a narrower source, given as the declared schema), feeding an +operator. On ``main`` the run raises ``ValueError`` ("Duplicate column name") where the +source's rows are rebuilt for its successor, when exactly one of the two tags is a +data-tag and the tags are declared ``j, k``. On the sync path the branch hands on the +declared table itself (F over ``_DeclaredForm.apply`` of the bound table), and the run +completes with the rows the bind describes (spec row e10; provisional, coordinator +decision 2026-11-22, pending the developer). The async path still carries rows until +ITL-1347 stage 5 and raises as ``main`` does. +""" + +from __future__ import annotations + +from typing import Any + +import pyarrow as pa +import pytest + +from orcapod import PipelineJob +from orcapod.databases import InMemoryArrowDatabase +from orcapod.pipeline import AsyncPipelineOrchestrator +from orcapod.sources import ArrowTableSource + +ROWS = [ + {"j": 3, "k": 5, "x": 1, "y": 7.5}, + {"j": 4, "k": 6, "x": 2, "y": 8.5}, +] + +ROLES: dict[str, bool | tuple[str, ...]] = { + "no_data_tag": True, + "k_data_tag": ("j",), + "j_data_tag": ("k",), + "both_data_tags": (), +} + + +def _source(nullable_x: bool, order: tuple[str, str], roles: Any) -> ArrowTableSource: + table = pa.table( + { + "x": pa.array([1, 2], pa.int64()), + "k": pa.array([5, 6], pa.int64()), + "j": pa.array([3, 4], pa.int64()), + "y": pa.array([7.5, 8.5], pa.float64()), + } + ) + table = table.cast( + pa.schema([f.with_nullable(f.name == "x" and nullable_x) for f in table.schema]) + ) + return ArrowTableSource( + table, tag_columns=list(order), tag_only_columns=roles, source_id="s" + ) + + +def _bound_job(order: tuple[str, str], roles: Any) -> PipelineJob: + """The slot declared with ``x: int | None``, bound to the table with ``x: int``.""" + job = PipelineJob(name="declared_one_data_tag", database=InMemoryArrowDatabase()) + with job: + _source(True, order, roles).select_data_columns(["y", "x"], label="selected") + slot = next(label for label in job.nodes if label != "selected") + job.bind(sources={slot: _source(False, order, roles)}) + return job + + +def _rows(job: PipelineJob) -> list[dict[str, Any]]: + table = job.nodes["selected"].as_table() + return sorted(table.to_pylist(), key=lambda row: row["j"]) + + +@pytest.mark.parametrize("roles", list(ROLES), ids=list(ROLES)) +@pytest.mark.parametrize("order", [("j", "k"), ("k", "j")], ids=["j-k", "k-j"]) +def test_the_sync_run_completes_with_the_rows_the_bind_describes( + order: tuple[str, str], roles: str +) -> None: + """Every arrangement runs on the sync path and gives the bound table's rows.""" + job = _bound_job(order, ROLES[roles]) + job.run() + assert _rows(job) == ROWS + + +@pytest.mark.parametrize("roles", list(ROLES), ids=list(ROLES)) +@pytest.mark.parametrize("order", [("j", "k"), ("k", "j")], ids=["j-k", "k-j"]) +def test_the_async_run_is_as_on_main(order: tuple[str, str], roles: str) -> None: + """The async path carries rows until stage 5: it raises where ``main`` raises.""" + job = _bound_job(order, ROLES[roles]) + raises_on_main = order == ("j", "k") and roles in ("k_data_tag", "j_data_tag") + if raises_on_main: + with pytest.raises(ValueError, match="Duplicate column name"): + job.run(orchestrator=AsyncPipelineOrchestrator()) + else: + job.run(orchestrator=AsyncPipelineOrchestrator()) + assert _rows(job) == ROWS From afc0525ac239aedbeafb4b4748b00ef552fcdd61 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 06:57:10 -0800 Subject: [PATCH 36/86] fix(function_node): typed row views; the id test counts both paths (ITL-1361) Row views are cast to the datagram protocols through object; the table path's per-row id is one method (_base_entry_id_of_slices), which the 'computed once per row' test counts beside compute_base_entry_id. Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/nodes/function_node.py | 34 ++++++++++++++----- ...test_function_node_entry_ids_from_table.py | 7 ++-- .../test_pipeline/test_job_batched_commits.py | 8 +++++ 3 files changed, 36 insertions(+), 13 deletions(-) diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 29f1b5fb2..b2344032f 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -3334,21 +3334,37 @@ def _input_entries( table.select([*tag_keys, *system_tags]) ) data_side = table.select(list(data_keys)) - hasher = self.data_context.arrow_hasher + # A row view stands for the row's datagram (``_RowView``): the checker cannot + # see that through its delegation, so the cast goes through object. return [ ( - cast(TagProtocol, _RowView(lazy, index, 0)), - cast(DataProtocol, _RowView(lazy, index, 1)), - hasher.hash_table( - _with_input_data_hash( - tag_side.slice(index, 1), - hasher.hash_table(data_side.slice(index, 1)), - ) - ).to_prefixed_digest(), + cast(TagProtocol, cast(object, _RowView(lazy, index, 0))), + cast(DataProtocol, cast(object, _RowView(lazy, index, 1))), + self._base_entry_id_of_slices( + tag_side.slice(index, 1), data_side.slice(index, 1) + ), ) for index in range(table.num_rows) ] + def _base_entry_id_of_slices(self, tag_row: pa.Table, data_row: pa.Table) -> bytes: + """One row's base entry id from its one-row tag and data slices. + + ``compute_base_entry_id`` of the row, from its table (``_input_entries``): the + tag side with its system tags, and the hash of its data columns. + + Args: + tag_row: The row's user tags and system tags, flags as a row has them. + data_row: The row's data columns. + + Returns: + The base entry id. + """ + hasher = self.data_context.arrow_hasher + return hasher.hash_table( + _with_input_data_hash(tag_row, hasher.hash_table(data_row)) + ).to_prefixed_digest() + def compute_pipeline_entry_id( self, tag: TagProtocol, diff --git a/tests/test_core/nodes/test_function_node_entry_ids_from_table.py b/tests/test_core/nodes/test_function_node_entry_ids_from_table.py index 2f9020ecd..39ade1539 100644 --- a/tests/test_core/nodes/test_function_node_entry_ids_from_table.py +++ b/tests/test_core/nodes/test_function_node_entry_ids_from_table.py @@ -15,9 +15,8 @@ import pytest -from orcapod.core.data_function import PythonDataFunction from orcapod.core.data_tags import stream_data_tags -from orcapod.core.function_pod import FunctionPod +from orcapod import function_pod from orcapod.core.nodes.function_node import FunctionJobNode from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod from orcapod.core.streams import ArrowTableStream @@ -31,15 +30,15 @@ ) +@function_pod(output_keys="c") def _constant(i8: int) -> int: return i8 def _node() -> FunctionJobNode: """A function node; only its data context's hasher is used by the ids.""" - pod = FunctionPod(PythonDataFunction(_constant, output_keys="c")) return FunctionJobNode( - pod, + _constant.pod, # pyright: ignore[reportArgumentType] # a function pod; the checker does not match it to FunctionPodProtocol source_a().select_data_columns(["i8"]), pipeline_database=InMemoryArrowDatabase(), ) diff --git a/tests/test_pipeline/test_job_batched_commits.py b/tests/test_pipeline/test_job_batched_commits.py index 8f9c864cc..ddc4546d6 100644 --- a/tests/test_pipeline/test_job_batched_commits.py +++ b/tests/test_pipeline/test_job_batched_commits.py @@ -440,14 +440,22 @@ def test_base_entry_id_is_computed_once_per_row( """Each row's base entry id is computed once, not once per use.""" # Counts calls of a public node method through a class-level spy; the test is # about how often the node computes the id. + # A row's id is made from its datagrams (``compute_base_entry_id``) or, for an + # input over an Arrow table, from its table slices (ITL-1361): both are counted. calls = {"n": 0} original = FunctionJobNode.compute_base_entry_id + original_of_slices = FunctionJobNode._base_entry_id_of_slices # pyright: ignore[reportPrivateUsage] # the table path's id def counting(self: FunctionJobNode, tag: Any, input_data: Any) -> bytes: calls["n"] += 1 return original(self, tag, input_data) + def counting_slices(self: FunctionJobNode, tag_row: Any, data_row: Any) -> bytes: + calls["n"] += 1 + return original_of_slices(self, tag_row, data_row) + monkeypatch.setattr(FunctionJobNode, "compute_base_entry_id", counting) + monkeypatch.setattr(FunctionJobNode, "_base_entry_id_of_slices", counting_slices) job = build_job(InMemoryArrowDatabase(), 20) job.run(orchestrator=ORCHESTRATORS[orchestrator]()) assert calls["n"] == 20 From 6757ed663d2361bb60174df37edb4d15d893ed37 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 07:02:20 -0800 Subject: [PATCH 37/86] fix(source_node): a narrower bind's rows keep main's key order; descriptions follow the rows (ITL-1360) Codex on PR #485, round 2, findings 1 and 5. A narrower source's rows are given as the declared schema one by one, the tag and the data table each through _DeclaredForm.apply, where a tag that is also data takes its place from the declared data order. _row_keys derives the keys by that same apply over zero-row tag and data tables (repeats dropped, missing names appended, for ITL-1366's one data-tag of two: e10), and the bound table is only retyped (_DeclaredForm.retype), since F selects by the keys. L2 sweep over declared layouts, tag orders and data-tag roles against the row path, kept and raw stored. A stream's description takes its data order from its table (keys_of_rows, now in streams.base), so a poller that fetched in another order is described as its rows are. A source-info field's type, like its flag, is decided by the values of a complete table: said in arrow_schema()'s docstring and the spec; L7 leaves both out by name, and pins a poller after a fetch and a value-decided list depth. Co-Authored-By: Claude Opus 5.5 --- .../dev/specs/itl-1347-job-table-transport.md | 10 +- src/orcapod/core/nodes/source_node.py | 116 +++++++++++------ src/orcapod/core/streams/base.py | 38 +++++- .../protocols/core_protocols/streams.py | 10 +- .../test_pipeline/test_narrower_bind_order.py | 120 ++++++++++++++++++ .../test_stream_transport_equivalence.py | 64 +++++++++- 6 files changed, 303 insertions(+), 55 deletions(-) create mode 100644 tests/test_pipeline/test_narrower_bind_order.py diff --git a/docs/dev/specs/itl-1347-job-table-transport.md b/docs/dev/specs/itl-1347-job-table-transport.md index 430710056..3b9203c6a 100644 --- a/docs/dev/specs/itl-1347-job-table-transport.md +++ b/docs/dev/specs/itl-1347-job-table-transport.md @@ -194,9 +194,13 @@ A run checks its sources first (ITL-1102), which polls them. **ITL-1307 later.** When `Schema` carries its Arrow schema, `arrow_schema()` reads the two schemas plus the system-tag and source-info fields, in one place (`StreamBase`). -Two exceptions keep today's bytes: -- **Source-info nullability** is decided by a complete Arrow table's values (F step 5). - `arrow_schema()` states those fields nullable (question 5). +Three exceptions keep today's bytes: +- **Source-info and system-tag nullability** is decided by a complete Arrow table's values + (F step 5). `arrow_schema()` states those fields nullable (question 5). +- **Source-info types** are decided by a complete Arrow table's tokens, as each row types + its tokens from their values (`_type_source_info_by_values`): a list of `None` or of + empty lists shows fewer list levels than its column declares. `arrow_schema()` states the + declared token type; consumers must not rely on it (Codex on PR #485). - **`null` columns.** Rows carry `large_string`, and a zero-row Arrow table carries `null`, as today (ITL-1319). diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index 2fdfccd1d..7c1f31ae1 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -23,14 +23,15 @@ from orcapod.config import OrcapodConfig from orcapod.core.base import TraceableBase from orcapod.core.datagrams import Data, Tag -from orcapod.core.data_tags import data_tag_names from orcapod.core.operators.drop_nulls import _without_none # pyright: ignore[reportPrivateUsage] # DropNulls' rule for removing None from a type, shared, never copied from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.core.streams.base import ( ZERO_ROW_INPUT_COLUMNS, + keys_of_rows, stream_arrow_schema, schema_requires_io, typed_arrow_schemas, + typed_zero_row_input, typed_zero_row_table, ) from orcapod.core.streams.view import ( @@ -154,6 +155,24 @@ def apply(self, table: pa.Table) -> pa.Table: source-info columns in declared order within the positions each group holds. """ + table = self.retype(table) + return table.select(self._declared_positions(table.column_names)) + + def retype(self, table: pa.Table) -> pa.Table: + """Return *table*'s arrays under the declared fields, in *table*'s column order. + + The fields ``apply`` gives (the columns in ``nullable`` flagged nullable, the + columns in ``renames`` renamed), without placing the columns: a table whose + columns are then selected by the rows' keys (the row-built form, ITL-1347) + needs no placement, and a table holding a data-tag once, among the tags, would + lose a column to a placement made for a row's separate tag and data tables. + + Args: + table: Rows read from the bound source. + + Returns: + The same arrays under the declared fields. + """ schema = table.schema for position, field in enumerate(table.schema): if field.name in self.nullable: @@ -162,8 +181,7 @@ def apply(self, table: pa.Table) -> pa.Table: field = field.with_name(self.renames[field.name]) schema = schema.set(position, field) # pyright: ignore[reportUnknownMemberType] # stubs leave Field unparametrized # Same arrays under the declared fields: no cast, so no value or type changes. - table = pa.Table.from_arrays(table.columns, schema=schema) - return table.select(self._declared_positions(table.column_names)) + return pa.Table.from_arrays(table.columns, schema=schema) def _declared_positions(self, names: list[str]) -> list[int]: """Return the column positions of *names* with each group in declared order. @@ -185,30 +203,16 @@ def _declared_positions(self, names: list[str]) -> list[int]: return order -def _keys_of_rows( - table: pa.Table, keys: tuple[Sequence[str], Sequence[str]] -) -> tuple[tuple[str, ...], tuple[str, ...]]: - """Return the tag and data keys a source's rows have, given its table and ``keys()``. - - A source's rows come from a stream over its table (``ArrowTableStream``), whose rows - list their tags in the stream's tag order and their data with the data-tags first, - in tag order, then the other data columns in the table's order. A source whose - ``keys()`` states its declared order (a ``PollingSource`` whose fetched table has - another column order) has rows in the table's order all the same, as a table built - from its rows does (Codex on PR #485). - - Args: - table: The source's table, as its rows are read from it. - keys: The source's ``keys()``. +def _each_once(order: Sequence[str], names: Sequence[str]) -> tuple[str, ...]: + """``order`` with each of ``names`` once: repeats dropped, missing names appended. - Returns: - The tag keys, and the data keys in the order of the rows. + ``_DeclaredForm.apply`` places a row's columns; with one data-tag among two tags it + can place a column twice and lose another (ITL-1366, where ``main`` then fails to + build the rows). The keys keep its order and hold each name once (spec row e10). """ - tag_keys, data_keys = (tuple(keys[0]), tuple(keys[1])) - data_tags = data_tag_names(tag_keys, data_keys) - data = set(data_keys) - set(tag_keys) - in_table = tuple(name for name in table.column_names if name in data) - return tag_keys, (*data_tags, *in_table) + wanted = set(names) + kept = tuple(dict.fromkeys(n for n in order if n in wanted)) + return (*kept, *(n for n in names if n not in kept)) def _system_tag_columns( @@ -1220,7 +1224,7 @@ def _rows_table(self) -> tuple[pa.Table, tuple[tuple[str, ...], tuple[str, ...]] """ stream = cast("StreamProtocol", self) table = stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS) - return table, _keys_of_rows(table, stream.keys()) + return table, keys_of_rows(table, stream.keys()) def arrow_schema(self) -> pa.Schema: """The Arrow schema of the columns this stream passes between job nodes. @@ -1742,23 +1746,54 @@ def identity_structure(self) -> Any: return self._bound_source.identity_structure() return super().identity_structure() - def _row_keys(self) -> tuple[tuple[str, ...], tuple[str, ...]]: - """The tag and data keys of this node's rows, known without reading a row. + def _row_keys( + self, table: pa.Table | None = None + ) -> tuple[tuple[str, ...], tuple[str, ...]]: + """The tag and data keys of this node's rows, as ``iter_data`` gives them. + + The bound source's rows have the keys of its table (``keys_of_rows``). A + narrower source's rows are given as the declared schema one by one + (``_declared_row``: its tag table and its data table each through + ``_DeclaredForm.apply``), so their keys are those of a zero-row tag table and a + zero-row data table of the bound source through the same ``apply``: a tag that + is also data takes its place from the declared data order, as on ``main``. + + Args: + table: The bound source's table (``ZERO_ROW_INPUT_COLUMNS``, with or + without rows). Default: its typed zero-row table, which reads no row; + the declared keys when it cannot say its types without rows. - The bound source's keys; for a narrower source given as the declared schema - (``_DeclaredForm``), the declared order with the data-tags first among the data - keys, as the stream over its table lists them (``_declared_stream``); the slot's - own when unbound. + Returns: + The tag keys and the data keys of the rows. """ if self._bound_source is None: return self.keys() + bound_keys = self._bound_source.keys() + if table is None: + table = typed_zero_row_input(self._bound_source) + if table is None: + return self.keys() + rows_keys = keys_of_rows(table, bound_keys) form = self._declared_form - if form is not None: - data_tags = data_tag_names(form.tag_order, form.data_order) - others = tuple(n for n in form.data_order if n not in data_tags) - return form.tag_order, (*data_tags, *others) - tag_keys, data_keys = self._bound_source.keys() - return tuple(tag_keys), tuple(data_keys) + if form is None: + return rows_keys + tag_keys, data_keys = rows_keys + names = table.column_names + system_tags = [n for n in names if n.startswith(constants.SYSTEM_TAG_PREFIX)] + source_info = [n for n in names if n.startswith(constants.SOURCE_PREFIX)] + empty = table.slice(0, 0) + tag_order = form.apply(empty.select([*tag_keys, *system_tags])).column_names + data_order = form.apply(empty.select([*data_keys, *source_info])).column_names + return ( + _each_once( + [n for n in tag_order if not n.startswith(constants.SYSTEM_TAG_PREFIX)], + tag_keys, + ), + _each_once( + [n for n in data_order if not n.startswith(constants.SOURCE_PREFIX)], + data_keys, + ), + ) def _rows_table(self) -> tuple[pa.Table, tuple[tuple[str, ...], tuple[str, ...]]]: """The table of this node's rows (``iter_data``) and the rows' keys. @@ -1778,9 +1813,10 @@ def _rows_table(self) -> tuple[pa.Table, tuple[tuple[str, ...], tuple[str, ...]] "Call job.bind(sources={'': source}) before running." ) table = self._bound_source.as_table(columns=ZERO_ROW_INPUT_COLUMNS) + keys = self._row_keys(table) if self._declared_form is None: - return table, _keys_of_rows(table, self._bound_source.keys()) - return self._declared_form.apply(table), self._row_keys() + return table, keys + return self._declared_form.retype(table), keys def iter_data(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: """Delegate to concrete source, or raise if unbound. diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py index f396b9c4f..d081777fe 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -21,6 +21,7 @@ import pyarrow as pa from orcapod.core.base import TraceableBase +from orcapod.core.data_tags import data_tag_names from orcapod.core.streams.view import ( SCHEMA_NEEDS_POLL_NOTE, ViewStatus, @@ -333,6 +334,32 @@ def row_built_names( return [*tag_keys, *system_tags, *data, *source_info] +def keys_of_rows( + table: pa.Table, keys: tuple[Sequence[str], Sequence[str]] +) -> tuple[tuple[str, ...], tuple[str, ...]]: + """Return the tag and data keys a source's rows have, given its table and ``keys()``. + + A source's rows come from a stream over its table (``ArrowTableStream``), whose rows + list their tags in the stream's tag order and their data with the data-tags first, + in tag order, then the other data columns in the table's order. A source whose + ``keys()`` states its declared order (a ``PollingSource`` whose fetched table has + another column order) has rows in the table's order all the same, as a table built + from its rows does (Codex on PR #485). + + Args: + table: The source's table, as its rows are read from it. + keys: The source's ``keys()``. + + Returns: + The tag keys, and the data keys in the order of the rows. + """ + tag_keys, data_keys = (tuple(keys[0]), tuple(keys[1])) + data_tags = data_tag_names(tag_keys, data_keys) + data = set(data_keys) - set(tag_keys) + in_table = tuple(name for name in table.column_names if name in data) + return tag_keys, (*data_tags, *in_table) + + def stream_arrow_schema( stream: object, keys: tuple[Sequence[str], Sequence[str]] | None = None ) -> pa.Schema: @@ -346,7 +373,10 @@ def stream_arrow_schema( stream that cannot type itself without rows answers with its Python schema converted by its data context (``arrow_types_declared`` is then false). Each system-tag and source-info field is stated nullable: a table decides its flag from - its values (F's last step). A ``null`` column keeps the zero-row ``null`` type; rows + its values (F's last step). A source-info field's type is stated as the declared + token type; a complete table decides it from its tokens + (``StaticOutputOperatorPod._type_source_info_by_values``), so consumers must not + rely on it. A ``null`` column keeps the zero-row ``null`` type; rows carry ``large_string`` (ITL-1319). ITL-1307 later reads it from ``Schema`` instead, here. @@ -361,8 +391,7 @@ def stream_arrow_schema( from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod typed = cast(StreamProtocol, stream) - if keys is None: - keys = typed.keys() + given_keys = keys table = typed_zero_row_input(stream) if table is None: # Only what the stream declares: asking for its source-info columns would make @@ -377,6 +406,9 @@ def stream_arrow_schema( pa.field(f"{constants.SOURCE_PREFIX}{name}", pa.large_string()), pa.array([], pa.large_string()), ) + # The rows' keys: the data in the order of the stream's table (a poller that + # fetched its columns in another order than it declares lists them so). + keys = given_keys if given_keys is not None else keys_of_rows(table, typed.keys()) names = row_built_names(table.column_names, keys) schema = row_built_provenance(table.select(names)).schema prefixes = (constants.SYSTEM_TAG_PREFIX, constants.SOURCE_PREFIX) diff --git a/src/orcapod/protocols/core_protocols/streams.py b/src/orcapod/protocols/core_protocols/streams.py index 5dff04d96..a5f544601 100644 --- a/src/orcapod/protocols/core_protocols/streams.py +++ b/src/orcapod/protocols/core_protocols/streams.py @@ -178,10 +178,12 @@ def arrow_schema(self) -> "pa.Schema": tags, system tags, data, source info; data and source info in data-key order), with the Arrow types, nullability and field metadata of the rows; no context and no meta column (ITL-1347). Known without reading, computing or polling a row. - Two exceptions keep today's bytes: system-tag and source-info fields are stated - nullable (a table decides their flags from its values), and a ``null`` column - keeps the ``null`` type a zero-row table has (rows carry ``large_string``; - ITL-1319). + Three properties are decided by the values of a complete table, not by the + description: whether a system-tag or source-info field is nullable (stated + nullable here), and a source-info field's type (stated as the declared token + type; a list of ``None`` or of empty lists shows fewer levels, so consumers must + not rely on it). And a ``null`` column keeps the ``null`` type a zero-row table + has (rows carry ``large_string``; ITL-1319). Returns: The declared Arrow schema. diff --git a/tests/test_pipeline/test_narrower_bind_order.py b/tests/test_pipeline/test_narrower_bind_order.py new file mode 100644 index 000000000..a754b8647 --- /dev/null +++ b/tests/test_pipeline/test_narrower_bind_order.py @@ -0,0 +1,120 @@ +"""A narrower bind hands on its rows in their order (ITL-1360, L2; Codex on PR #485). + +A source slot declared from a source whose ``x`` is ``int | None``, bound to the same +columns with ``x: int`` (a narrower source, given as the declared schema), feeding a +``Batch`` node in ``LOG`` mode. The source node's output is F of the bound table with +the keys its rows have (``SourceJobNode._row_keys``: ``_DeclaredForm.apply`` of a +row's tag and data tables, as each row is given). Every pairing of declared layout, tag +order and data-tag roles must keep and store what the row path keeps and stores: the +same run with the source's output built from its rows +(``StaticOutputOperatorPod._materialize_upstream``), as on ``main``. The arrangements +where the row path raises (one data-tag of two, ITL-1366) are spec row e10, tested in +``test_declared_slot_one_data_tag.py``. +""" + +from __future__ import annotations + +import itertools +from typing import Any + +import pyarrow as pa +import pytest + +from orcapod import PipelineJob +from orcapod.core.nodes.source_node import SourceNodeBase +from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod +from orcapod.databases import InMemoryArrowDatabase +from orcapod.operators import Batch +from orcapod.sources import ArrowTableSource +from orcapod.types import CacheMode + +ROLES: dict[str, bool | tuple[str, ...]] = { + "no_data_tag": True, + "a_data_tag": ("b",), + "b_data_tag": ("a",), + "both_data_tags": (), +} + + +def _source( + nullable_x: bool, layout: tuple[str, ...], tag_order: tuple[str, str], roles: Any +) -> ArrowTableSource: + columns = { + "x": pa.array([1, 2], pa.int64()), + "a": pa.array([5, 6], pa.int64()), + "b": pa.array([3, 4], pa.int64()), + } + table = pa.table({name: columns[name] for name in layout}) + table = table.cast( + pa.schema([f.with_nullable(f.name == "x" and nullable_x) for f in table.schema]) + ) + return ArrowTableSource( + table, tag_columns=list(tag_order), tag_only_columns=roles, source_id="s" + ) + + +def _run( + layout: tuple[str, ...], tag_order: tuple[str, str], roles: Any +) -> tuple[list[str], pa.Schema]: + """Run the job; return the batch node's kept columns and its raw stored schema.""" + database = InMemoryArrowDatabase() + job = PipelineJob(name="narrower_bind_order", database=database) + with job: + Batch(batch_size=2)(_source(True, layout, tag_order, roles), label="batched") + job.nodes["batched"].attach_databases( + pipeline_database=database.at("log"), cache_mode=CacheMode.LOG + ) + slot = next(label for label in job.nodes if label != "batched") + job.bind(sources={slot: _source(False, ("x", "a", "b"), tag_order, roles)}) + job.run() + node = job.nodes["batched"] + kept = node.as_table(columns={"source": True}).column_names + stored = node.get_all_records(columns={"source": True}) + assert stored is not None + return kept, stored.schema + + +def _row_path(monkeypatch: pytest.MonkeyPatch) -> None: + """Make every source node hand on its rows rebuilt, as on ``main``.""" + + def execute(self: Any, *, observer: Any = None) -> Any: + if observer is not None: + observer.on_node_start(self.label, self.content_hash().to_string()) + out = StaticOutputOperatorPod._materialize_upstream( + list(self.iter_data()), self + ) # pyright: ignore[reportPrivateUsage] # the row path + if observer is not None: + observer.on_node_end(self.label, self.content_hash().to_string()) + return out + + monkeypatch.setattr(SourceNodeBase, "execute", execute) + + +def _raises_on_the_row_path(roles: str) -> bool: + """The row path raises only with one data-tag of two (ITL-1366, e10).""" + return roles in ("a_data_tag", "b_data_tag") + + +@pytest.mark.parametrize("roles", list(ROLES), ids=list(ROLES)) +@pytest.mark.parametrize("tag_order", [("a", "b"), ("b", "a")], ids=["a-b", "b-a"]) +@pytest.mark.parametrize( + "layout", list(itertools.permutations(("a", "b", "x"))), ids="".join +) +def test_a_narrower_bind_keeps_and_stores_as_the_row_path( + layout: tuple[str, ...], + tag_order: tuple[str, str], + roles: str, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Kept columns and the raw stored schema equal the row path's, in order.""" + got = _run(layout, tag_order, ROLES[roles]) + with monkeypatch.context() as patch: + _row_path(patch) + try: + expected = _run(layout, tag_order, ROLES[roles]) + except ValueError as error: + assert "Duplicate column name" in str(error) + assert _raises_on_the_row_path(roles) + pytest.skip("the row path raises here: spec row e10") + assert got[0] == expected[0] + assert got[1].equals(expected[1], check_metadata=True) diff --git a/tests/test_pipeline/test_stream_transport_equivalence.py b/tests/test_pipeline/test_stream_transport_equivalence.py index 04977f91d..b9652d0aa 100644 --- a/tests/test_pipeline/test_stream_transport_equivalence.py +++ b/tests/test_pipeline/test_stream_transport_equivalence.py @@ -42,7 +42,7 @@ from orcapod.errors import ProvisionalHashWarning from orcapod.pipeline import AsyncPipelineOrchestrator from orcapod.pipeline.observer import NoOpObserver -from orcapod.operators import MergeJoin, Rejoin, SelectDataColumns +from orcapod.operators import Batch, MergeJoin, Rejoin, SelectDataColumns from orcapod.side_effects import SideEffectJobNode from orcapod.system_constants import constants from orcapod.types import CacheMode @@ -240,15 +240,20 @@ def test_a_held_node_hands_on_the_stream_built_from_its_rows( def _without_exceptions(schema: pa.Schema) -> list[tuple[str, Any, bool, Any]]: """Fields in order as (name, type, nullable, metadata), the spec's exceptions applied. - A system-tag or source-info field's flag is decided by a table's values (stated - nullable), and a ``null`` column is ``large_string`` in rows (ITL-1319). Column - order counts on the sync path (Codex on PR #485). + Decided by the values of a complete table, not by the description: a system-tag or + source-info field's flag (stated nullable) and a source-info field's type (left out). + A ``null`` column is ``large_string`` in rows (ITL-1319). Column order counts on the + sync path (Codex on PR #485). """ prefixes = (constants.SYSTEM_TAG_PREFIX, constants.SOURCE_PREFIX) return [ ( field.name, - pa.large_string() if pa.types.is_null(field.type) else field.type, + None + if field.name.startswith(constants.SOURCE_PREFIX) + else pa.large_string() + if pa.types.is_null(field.type) + else field.type, True if field.name.startswith(prefixes) else field.nullable, field.metadata, ) @@ -544,3 +549,52 @@ def test_an_operator_stream_declares_its_tags_in_its_rows_order() -> None: stream = SelectDataColumns(["x"])(source) built, _, _ = StaticOutputOperatorPod._rows_to_table(list(stream.iter_data())) # pyright: ignore[reportPrivateUsage] # the rows' order assert stream.arrow_schema().names[:2] == built.column_names[:2] + + +@pytest.mark.filterwarnings("ignore::orcapod.errors.ProvisionalHashWarning") +def test_a_poller_that_fetched_describes_its_rows_order() -> None: + """L7: after a fetch in another order than declared, the description follows the rows. + + A poller declaring ``k, j, b, a`` that fetched ``j, k, a, b`` lists its data as its + rows do (Codex on PR #485). + """ + poller = _poller(("j", "k", "a", "b")) + rows = list(poller.iter_data()) + built, _, _ = StaticOutputOperatorPod._rows_to_table(rows) # pyright: ignore[reportPrivateUsage] # the rows' order + assert poller.arrow_types_declared + assert _without_exceptions(poller.arrow_schema()) == _without_exceptions( + built.schema + ) + + +def test_a_value_decided_source_info_depth_is_a_named_exception() -> None: + """L7: ``Batch`` over null list tokens; the description and the rows agree but for it. + + The rows give ``[None, None]`` one list level (``large_list``); the + description states the declared token type. A source-info type is decided by the + values of a complete table and is one of the description's named exceptions. + """ + from orcapod.core.streams import ArrowTableStream + from orcapod.sources import DictSource + + table = DictSource( + [{"k": 1, "x": 1}, {"k": 2, "x": 2}], + tag_columns=["k"], + tag_only_columns=True, + source_id="s", + ).as_table(columns={"source": True, "system_tags": True}) + position = table.schema.get_field_index("_source_x") + strings = pa.large_list(pa.large_string()) + raw = ArrowTableStream( + table.set_column( + position, + pa.field("_source_x", strings, nullable=True), + pa.array([None, None], strings), + ), + tag_columns=["k"], + ) + batched = Batch(batch_size=2)(raw) + built, _, _ = StaticOutputOperatorPod._rows_to_table(list(batched.iter_data())) # pyright: ignore[reportPrivateUsage] # the rows + declared = batched.arrow_schema() + assert declared.field("_source_x").type != built.schema.field("_source_x").type + assert _without_exceptions(declared) == _without_exceptions(built.schema) From b5f5a185e1793539355a35a39a351fc855e9e89a Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 07:03:23 -0800 Subject: [PATCH 38/86] fix(pipeline): held streams built when read and not kept; membership builds nothing (ITL-1360) Codex on PR #485, round 2, findings 2, 6 and 7. A run plan's held streams are StreamsOnRead (keep=False): built when the sync orchestrator reaches the node, never while planning (an async run over a held node whose rows cannot make one table then runs as on main), and released once the node's successors ran. Membership, length and iteration of StreamsOnRead never build a stream. Co-Authored-By: Claude Opus 5.5 --- src/orcapod/pipeline/node_run.py | 16 +-- src/orcapod/pipeline/result.py | 31 +++-- .../test_function_node_arrow_types.py | 36 ++++++ .../test_held_streams_on_read.py | 112 ++++++++++++++++++ 4 files changed, 179 insertions(+), 16 deletions(-) create mode 100644 tests/test_pipeline/test_held_streams_on_read.py diff --git a/src/orcapod/pipeline/node_run.py b/src/orcapod/pipeline/node_run.py index ad0ab8561..f39f403c6 100644 --- a/src/orcapod/pipeline/node_run.py +++ b/src/orcapod/pipeline/node_run.py @@ -14,7 +14,7 @@ from __future__ import annotations -from collections.abc import Iterable, Iterator, Sequence +from collections.abc import Iterable, Iterator, Mapping, Sequence from dataclasses import dataclass from typing import TYPE_CHECKING, Any @@ -25,6 +25,7 @@ run_node_summaries, ) from orcapod.pipeline.restrictions import restrictions_in_force, source_name +from orcapod.pipeline.result import StreamsOnRead from orcapod.utils.database_errors import flush_best_effort if TYPE_CHECKING: @@ -251,7 +252,7 @@ class RunPlan: them (a source slot is read; any other one is held). held: The output stream of each held node of ``dag``: of its current run, or of a stream outside the job; it feeds the nodes after it as if the node had - just run (the sync orchestrator). + just run (the sync orchestrator). Built when read (``StreamsOnRead``). held_rows: The rows of each held node, as the plan took them; ``held`` is built from them. The async orchestrator sends them (it carries rows until ITL-1347 stage 5). @@ -261,7 +262,7 @@ class RunPlan: """ dag: Any - held: dict[Any, Any] + held: Mapping[Any, Any] to_run: list[Any] held_counts: dict[Any, int] held_rows: dict[Any, list[Any]] @@ -345,10 +346,11 @@ def is_source(node: Any) -> bool: for node in included if not any(node is r for r in to_run) and not is_source(node) } - held = { - node: StaticOutputOperatorPod._materialize_upstream(rows, node) - for node, rows in held_rows.items() - } + # Built when the sync orchestrator reaches the node, never while planning (an + # async run reads only the rows), and not kept by the plan (ITL-1360). + held = StreamsOnRead( + held_rows, StaticOutputOperatorPod._materialize_upstream, keep=False + ) # Counted from what each node holds: iterating an operator's rows would build a # (Tag, Data) pair per row only to count them (ITL-1351). held_counts = {node: node.held_row_count() for node in current} diff --git a/src/orcapod/pipeline/result.py b/src/orcapod/pipeline/result.py index bb117de2d..c0a95a4a7 100644 --- a/src/orcapod/pipeline/result.py +++ b/src/orcapod/pipeline/result.py @@ -11,34 +11,47 @@ class StreamsOnRead(Mapping[Any, "StreamProtocol"]): - """Each node's output stream, built when it is first read. + """Each node's output stream, built from its rows when it is read. The async orchestrator collects each node's rows as they are sent; a node's stream - is built from them (``build``) the first time it is read, and kept. A run whose - rows cannot make one table (rows of a store written before ITL-928) therefore - finishes, as it does on ``main``, and only reading that node's output raises, as - reading its rows as a table does (ITL-1360). + is built from them (``build``) when it is read. A run whose rows cannot make one + table (rows of a store written before ITL-928) therefore finishes, as it does on + ``main``, and only reading that node's output raises, as reading its rows as a + table does (ITL-1360). Membership, length and iteration never build a stream. A run + plan's held streams are built the same way, when the sync orchestrator reaches the + node, and are not kept (``keep=False``): the orchestrator drops each one once its + successors have run. """ def __init__( self, rows: Mapping[Any, Any], build: Callable[[Any, Any], "StreamProtocol"], + *, + keep: bool = True, ) -> None: """Hold each node's rows and how a stream is built from them. Args: - rows: Each node's collected rows. + rows: Each node's rows. build: Builds a node's stream from its rows, given ``(rows, node)``. + keep: Keep a stream once built, so a second read returns it again. """ self._rows = dict(rows) self._build = build + self._keep = keep self._built: dict[Any, StreamProtocol] = {} def __getitem__(self, node: Any) -> "StreamProtocol": - if node not in self._built: - self._built[node] = self._build(self._rows[node], node) - return self._built[node] + if node in self._built: + return self._built[node] + stream = self._build(self._rows[node], node) + if self._keep: + self._built[node] = stream + return stream + + def __contains__(self, node: object) -> bool: + return node in self._rows def __iter__(self) -> Iterator[Any]: return iter(self._rows) diff --git a/tests/test_core/function_pod/test_function_node_arrow_types.py b/tests/test_core/function_pod/test_function_node_arrow_types.py index 56cc00a5d..4d27611ef 100644 --- a/tests/test_core/function_pod/test_function_node_arrow_types.py +++ b/tests/test_core/function_pod/test_function_node_arrow_types.py @@ -421,3 +421,39 @@ def test_an_async_run_over_a_store_written_before_the_fix_finishes( assert len(list(node.iter_data())) == 3 with pytest.raises(InputValidationError, match="'k'"): node.as_table() + + +def test_a_second_async_run_holds_the_node_and_sends_its_rows( + tmp_path: pathlib.Path, +) -> None: + """The plan builds no held stream for an async run: it sends the held rows as on main. + + Over a store written before ITL-928, the held ``double`` holds rows that cannot + make one table; a second async run (``increment`` cleared) holds it and sends its + three rows on, as on ``main`` (Codex on PR #485, round 2). + """ + from orcapod.pipeline import AsyncPipelineOrchestrator + from orcapod.pipeline.observer import NoOpObserver + + class DataStarts(NoOpObserver): + def __init__(self) -> None: + self.count = 0 + + def contextualize(self, *identity_path: str) -> DataStarts: + return self + + def on_data_start(self, node_label: str, tag: Any, data: Any) -> None: + if node_label == "increment": + self.count += 1 + + _build( + DeltaTableDatabase(tmp_path), _source_table("uint32").slice(0, 2), chained=True + ).run() + _as_written_before_the_fix(tmp_path) + job = _build(DeltaTableDatabase(tmp_path), _source_table("uint32"), chained=True) + job.run(orchestrator=AsyncPipelineOrchestrator()) + job.nodes["increment"].clear_cache() + observer = DataStarts() + summary = job.run(orchestrator=AsyncPipelineOrchestrator(), observer=observer) + assert summary.nodes["double"].held == 3 + assert observer.count == 3 diff --git a/tests/test_pipeline/test_held_streams_on_read.py b/tests/test_pipeline/test_held_streams_on_read.py new file mode 100644 index 000000000..99c031830 --- /dev/null +++ b/tests/test_pipeline/test_held_streams_on_read.py @@ -0,0 +1,112 @@ +"""Held streams and async outputs are built when read (ITL-1360; Codex on PR #485). + +A run plan's held streams (``RunPlan.held``) and the async orchestrator's +``node_outputs`` are ``StreamsOnRead``: a node's stream is built from its rows when it +is read. Membership, length and iteration never build one; the plan keeps no held +stream it has built, so the sync orchestrator releases it once its successors ran. +""" + +from __future__ import annotations + +import gc +import weakref +from typing import Any + +import pytest + +from orcapod import PipelineJob, function_pod +from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod +from orcapod.databases import InMemoryArrowDatabase +from orcapod.pipeline.observer import NoOpObserver +from orcapod.pipeline.result import StreamsOnRead +from orcapod.sources import DictSource + + +def test_membership_length_and_iteration_build_nothing() -> None: + """``in``, ``len`` and iteration read the nodes only; reading a value builds it.""" + + def build(rows: Any, node: Any) -> Any: + raise AssertionError(f"built {node}") + + outputs = StreamsOnRead({"a": [], "b": []}, build) + assert "a" in outputs + assert "c" not in outputs + assert len(outputs) == 2 + assert list(outputs) == ["a", "b"] + with pytest.raises(AssertionError, match="built a"): + _ = outputs["a"] + + +def test_a_kept_stream_is_built_once_and_an_unkept_one_each_read() -> None: + built: list[Any] = [] + + def build(rows: Any, node: Any) -> Any: + built.append(node) + return object() + + kept = StreamsOnRead({"a": []}, build) + assert kept["a"] is kept["a"] + unkept = StreamsOnRead({"a": []}, build, keep=False) + _ = unkept["a"] + _ = unkept["a"] + assert built == ["a", "a", "a"] + + +@function_pod(output_keys="y") +def step(x: int) -> int: + return x + 1 + + +def test_a_held_stream_is_released_once_its_successors_ran( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """``source -> a -> b -> c -> d`` with ``a`` held: its stream is gone when ``c`` starts.""" + job = PipelineJob(name="held_lifetime", database=InMemoryArrowDatabase()) + with job: + source = DictSource( + [{"k": i, "x": i} for i in range(3)], + tag_columns=["k"], + tag_only_columns=True, + source_id="s", + ) + a = step.pod(source, label="a") + b = step.pod(a.map_data({"y": "x"}), label="b") + c = step.pod(b.map_data({"y": "x"}), label="c") + step.pod(c.map_data({"y": "x"}), label="d") + job.run() + for label in ("b", "c", "d"): + job.nodes[label].clear_cache() + for node in job.nodes.values(): + if node.label.startswith("MapData"): + node.clear_cache() + + held: list[weakref.ref[Any]] = [] + original = StaticOutputOperatorPod._materialize_upstream # pyright: ignore[reportPrivateUsage] # the held stream's build + + def materialize(rows: Any, upstream: Any, **kwargs: Any) -> Any: + stream = original(rows, upstream, **kwargs) + if getattr(upstream, "label", None) == "a": + held.append(weakref.ref(stream)) + return stream + + monkeypatch.setattr( + StaticOutputOperatorPod, "_materialize_upstream", staticmethod(materialize) + ) + + alive_at_c: list[bool] = [] + + class AtC(NoOpObserver): + def contextualize(self, *identity_path: str) -> AtC: + return self + + def on_node_start( + self, node_label: str, node_hash: str, tag_schema: Any = None + ) -> None: + if node_label == "c": + gc.collect() + alive_at_c.append(any(ref() is not None for ref in held)) + + summary = job.run(observer=AtC(), materialize_results=False) + assert summary.nodes["a"].held == 3 + assert held + assert alive_at_c == [False] From c6c47aab98ad9550429c1a191dd4ee712a20e63f Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 07:04:01 -0800 Subject: [PATCH 39/86] fix(streams): an undeclared poller that has not polled is described with no column (ITL-1360) Codex on PR #485, round 2, finding 3. A stream whose schema is known only by polling (schema_requires_io) is described with no column, as a head shows it: no fetch, no modified-time change, arrow_types_declared stays false. Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/streams/base.py | 9 ++++- .../test_stream_transport_equivalence.py | 39 +++++++++++++++++++ 2 files changed, 47 insertions(+), 1 deletion(-) diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py index d081777fe..dac45879a 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -371,7 +371,9 @@ def stream_arrow_schema( (``row_built_names``: user tags, system tags, data, source info, data and source info in data-key order), with no context and no meta column. A stream that cannot type itself without rows answers with its Python schema - converted by its data context (``arrow_types_declared`` is then false). Each + converted by its data context (``arrow_types_declared`` is then false), and one + whose schema is known only by polling (nothing declared, nothing polled: + ``schema_requires_io``) answers with no column. Each system-tag and source-info field is stated nullable: a table decides its flag from its values (F's last step). A source-info field's type is stated as the declared token type; a complete table decides it from its tokens @@ -393,6 +395,11 @@ def stream_arrow_schema( typed = cast(StreamProtocol, stream) given_keys = keys table = typed_zero_row_input(stream) + if table is None and schema_requires_io(stream, ColumnConfig(system_tags=True)): + # Nothing declared, nothing polled (a poller with no declared schema): the + # columns are known only from rows, and a description never polls. No column, + # as a head says (``SCHEMA_NEEDS_POLL_NOTE``); ``arrow_types_declared`` is false. + return pa.schema([]) if table is None: # Only what the stream declares: asking for its source-info columns would make # a source that has not polled poll (a description never computes, polls or diff --git a/tests/test_pipeline/test_stream_transport_equivalence.py b/tests/test_pipeline/test_stream_transport_equivalence.py index b9652d0aa..f13f9dc89 100644 --- a/tests/test_pipeline/test_stream_transport_equivalence.py +++ b/tests/test_pipeline/test_stream_transport_equivalence.py @@ -598,3 +598,42 @@ def test_a_value_decided_source_info_depth_is_a_named_exception() -> None: declared = batched.arrow_schema() assert declared.field("_source_x").type != built.schema.field("_source_x").type assert _without_exceptions(declared) == _without_exceptions(built.schema) + + +@pytest.mark.filterwarnings("ignore::orcapod.errors.ProvisionalHashWarning") +def test_describing_an_undeclared_poller_that_has_not_polled_reads_nothing() -> None: + """L7: a poller with no declared schema is described with no column, and not polled. + + Its columns are known only from rows; the description never fetches, its modified + time does not move and ``arrow_types_declared`` stays false (Codex on PR #485). + """ + from orcapod.core.sources import PollingSource + from tests.test_hashing.test_logical_type_forms import ( + _TableImpl, # pyright: ignore[reportPrivateUsage] # the one test polling implementation + ) + + fetches: list[int] = [] + + class Undeclared(_TableImpl): + async def fetch(self, cursor: Any = None) -> Any: + fetches.append(1) + return await super().fetch(cursor) + + def schema(self) -> Any: + return None + + table = pa.table( + {"k": pa.array(["1"], pa.large_string()), "a": pa.array([1], pa.int64())} + ) + poller = PollingSource( + Undeclared(table, table.schema), + tag_columns=["k"], + record_id_columns=["k"], + source_id="undeclared", + ) + modified = poller.last_modified + assert poller.arrow_schema() == pa.schema([]) + assert poller.arrow_schema() == pa.schema([]) + assert fetches == [] + assert poller.last_modified == modified + assert not poller.arrow_types_declared From 5a1725e4952a460a1d023f36d06c7474cc106eec Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 07:05:00 -0800 Subject: [PATCH 40/86] fix(pipeline): any failure of F's whole-table build falls back to the rows (ITL-1360) Codex on PR #485, round 2, finding 4. RowBuiltFormUnavailable is the one signal that a node's output must come from its rows: raised by _row_built_form for tokens of two types (SourceInfoTypesDisagree, now its subclass) and for any Arrow error of the whole-table build. Source and operator nodes catch it and build their rows, which raise main's error after main's observer events. Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/nodes/operator_node.py | 6 +-- src/orcapod/core/nodes/source_node.py | 4 +- .../core/operators/static_output_pod.py | 43 +++++++++++++------ .../operators/test_row_built_form.py | 16 +++++++ 4 files changed, 51 insertions(+), 18 deletions(-) diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index 36904bf59..be0bd1162 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -39,7 +39,7 @@ from orcapod.channels import Channel, ChannelClosed, ReadableChannel, WritableChannel from orcapod.config import OrcapodConfig from orcapod.core.operators.static_output_pod import ( - SourceInfoTypesDisagree, + RowBuiltFormUnavailable, StaticOutputOperatorPod, ) from orcapod.core.streams.arrow_table_stream import ArrowTableStream @@ -1697,7 +1697,7 @@ def execute( cached_output.keys(), self, ) - except SourceInfoTypesDisagree as error: + except RowBuiltFormUnavailable as error: StaticOutputOperatorPod._raise_as_rows_do( cached_output.iter_data(), error ) @@ -1720,7 +1720,7 @@ def execute( kept_table = StaticOutputOperatorPod._row_built_form( result_table, keys ) - except SourceInfoTypesDisagree as error: + except RowBuiltFormUnavailable as error: StaticOutputOperatorPod._raise_as_rows_do( result_stream.iter_data(), error ) diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index 7c1f31ae1..230543548 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -1265,7 +1265,7 @@ def execute( UnboundSourceError: When no concrete data is available. """ from orcapod.core.operators.static_output_pod import ( - SourceInfoTypesDisagree, + RowBuiltFormUnavailable, StaticOutputOperatorPod, ) @@ -1278,7 +1278,7 @@ def execute( table, keys = self._rows_table() try: result = StaticOutputOperatorPod._output_stream(table, keys, self) - except SourceInfoTypesDisagree as error: + except RowBuiltFormUnavailable as error: # Rows whose source-info tokens cannot make one table: the node has read # its rows, and the run fails where its rows are handed on, raising what # their concatenation raises. diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index 077cf4817..49c75276a 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -66,12 +66,20 @@ from orcapod.protocols.hashing_protocols import SemanticHasherProtocol -class SourceInfoTypesDisagree(ValueError): +class RowBuiltFormUnavailable(ValueError): + """F cannot be built from the whole table (``_row_built_form``). + + The one signal that a node's output must come from its rows instead: the caller + builds the rows (``StaticOutputOperatorPod._rows_to_table``, through + ``_raise_as_rows_do``), which raises the error a table built from rows raises, so + the run fails as it does when rows are handed on, with the same observer events. + """ + + +class SourceInfoTypesDisagree(RowBuiltFormUnavailable): """Two rows give one source-info column different types (``_row_built_form``). - A table built from such rows cannot be concatenated: the caller builds the rows - (``StaticOutputOperatorPod._rows_to_table``), which raises the error a table built - from rows raises, so the run fails as it does when rows are handed on. + A table built from such rows cannot be concatenated. """ @@ -587,24 +595,33 @@ def _row_built_form( The table ``_rows_to_table`` would build from its rows. Raises: - SourceInfoTypesDisagree: If the rows' tokens give a source-info column two - types (``_type_source_info_by_values``). + RowBuiltFormUnavailable: If the whole table cannot be built: the rows' + tokens give a source-info column two types + (``SourceInfoTypesDisagree``), or an Arrow conversion fails. The node + then builds its rows (``_raise_as_rows_do``). """ - return StaticOutputOperatorPod._flag_by_values( - StaticOutputOperatorPod._type_source_info_by_values( - row_built_columns(table, keys) + try: + return StaticOutputOperatorPod._flag_by_values( + StaticOutputOperatorPod._type_source_info_by_values( + row_built_columns(table, keys) + ) ) - ) + except RowBuiltFormUnavailable: + raise + except pa.ArrowException as error: + # Values the whole table cannot be built from (a token the rows' own + # conversion refuses too): the rows decide, as on ``main``. + raise RowBuiltFormUnavailable(str(error)) from error @staticmethod def _raise_as_rows_do( rows: Iterable[tuple[TagProtocol, DataProtocol]], - error: SourceInfoTypesDisagree, + error: RowBuiltFormUnavailable, ) -> NoReturn: """Build ``rows`` into a table to raise the error a table built from them raises. Called when ``_row_built_form`` finds rows whose source-info tokens cannot make - one table (``SourceInfoTypesDisagree``): the rows' own concatenation + one table (``RowBuiltFormUnavailable``): the rows' own concatenation (``_rows_to_table``) raises exactly what a run that hands rows on raises. Args: @@ -613,7 +630,7 @@ def _raise_as_rows_do( Raises: pyarrow.ArrowInvalid: As ``_rows_to_table`` raises it. - SourceInfoTypesDisagree: ``error``, if the rows concatenate after all. + RowBuiltFormUnavailable: ``error``, if the rows build after all. """ StaticOutputOperatorPod._rows_to_table(list(rows)) raise error diff --git a/tests/test_core/operators/test_row_built_form.py b/tests/test_core/operators/test_row_built_form.py index 23a54bedf..c511d1b5c 100644 --- a/tests/test_core/operators/test_row_built_form.py +++ b/tests/test_core/operators/test_row_built_form.py @@ -391,3 +391,19 @@ def test_a_source_with_a_nullable_system_tag_is_not_bound() -> None: slot = next(label for label in job.nodes if label != "selected") with pytest.raises(SourceSpecMismatchError, match="record_id"): job.bind(sources={slot: ArrowTableStream(with_null, tag_columns=["k"])}) + + +def test_a_token_the_rows_cannot_convert_fails_as_main_does() -> None: + """A conversion failure of F's whole-table build falls back to the rows, as on main. + + Each row's token ``[None, [[]]]`` gives one list level (``source_info_arrow_type``), + whose conversion fails (``ArrowTypeError``). The node builds its rows, which raise + the same error, after the source node has ended (Codex on PR #485, round 2). + """ + nested = pa.large_list(_NESTED) + job = _batched_job(InMemoryArrowDatabase()) + job.bind(sources={"s": _with_source_x([[None, [[]]], [None, [[]]]], nested)}) + observer = _NodeEvents() + with pytest.raises(pa.ArrowTypeError, match="Expected bytes"): + job.run(observer=observer) + assert observer.events == [("start", "s"), ("end", "s")] From 95c9d1723a7137c0b9ac9f057a692a60642a599b Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 07:16:54 -0800 Subject: [PATCH 41/86] test(pipeline): type the held-lifetime test's streams (ITL-1360) Co-Authored-By: Claude Opus 5.5 --- tests/test_pipeline/test_held_streams_on_read.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/test_pipeline/test_held_streams_on_read.py b/tests/test_pipeline/test_held_streams_on_read.py index 99c031830..daed771fc 100644 --- a/tests/test_pipeline/test_held_streams_on_read.py +++ b/tests/test_pipeline/test_held_streams_on_read.py @@ -69,9 +69,9 @@ def test_a_held_stream_is_released_once_its_successors_ran( tag_only_columns=True, source_id="s", ) - a = step.pod(source, label="a") - b = step.pod(a.map_data({"y": "x"}), label="b") - c = step.pod(b.map_data({"y": "x"}), label="c") + a: Any = step.pod(source, label="a") + b: Any = step.pod(a.map_data({"y": "x"}), label="b") + c: Any = step.pod(b.map_data({"y": "x"}), label="c") step.pod(c.map_data({"y": "x"}), label="d") job.run() for label in ("b", "c", "d"): From 63a6af6205ea5b3bb03b81e2cf5054163331e7e7 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 07:17:45 -0800 Subject: [PATCH 42/86] fix(function_node): stage 3 falls back to the rows on RowBuiltFormUnavailable (ITL-1361) Merges stage 2's round-2 fixes; the function node's stored-table output and the side-effect node's passed-rows output fall back to the rows' own build on the one signal F's whole-table build gives, or on any Arrow error of the piece concatenation. Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/nodes/function_node.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index b2344032f..74d8c7fa6 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -349,7 +349,7 @@ def passed_rows_output_stream( The node's output stream. """ from orcapod.core.operators.static_output_pod import ( - SourceInfoTypesDisagree, + RowBuiltFormUnavailable, StaticOutputOperatorPod, ) @@ -360,7 +360,7 @@ def passed_rows_output_stream( table = table.take(pa.array(passed, type=pa.int64())) try: return StaticOutputOperatorPod._output_stream(table, input_stream.keys(), node) # pyright: ignore[reportPrivateUsage] # F with the node's identity - except SourceInfoTypesDisagree as error: + except RowBuiltFormUnavailable as error: StaticOutputOperatorPod._raise_as_rows_do(rows, error) # pyright: ignore[reportPrivateUsage] # the rows' own error @@ -2676,7 +2676,7 @@ def _output_from_stored_tables( or raises what it raises. """ from orcapod.core.operators.static_output_pod import ( - SourceInfoTypesDisagree, + RowBuiltFormUnavailable, StaticOutputOperatorPod, ) @@ -2718,7 +2718,7 @@ def _output_from_stored_tables( formed = StaticOutputOperatorPod._flag_by_values( # pyright: ignore[reportPrivateUsage] # F's whole-table steps StaticOutputOperatorPod._type_source_info_by_values(combined) # pyright: ignore[reportPrivateUsage] ) - except (pa.ArrowInvalid, SourceInfoTypesDisagree): + except (pa.ArrowException, RowBuiltFormUnavailable): return None first_tag, first_data = rows[0] return StaticOutputOperatorPod._as_upstream_stream( # pyright: ignore[reportPrivateUsage] # the node's identity From 7dfff51e33b0573448fef715088a4adc9bf99856 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 07:24:09 -0800 Subject: [PATCH 43/86] feat(operators): streaming Rejoin kernel on Arrow record batches (ITL-1362) (#487) * feat(operators): streaming join kernels for Join, MergeJoin and SemiJoin on Arrow record batches (ITL-1362) Vectorized symmetric hash joins for the async path (ITL-1347 stage 5, part "joins"), not yet wired into async_execute. A kernel is built from the operator and its input streams; push(input_index, record_batch) and close(input_index) return the output record batches. Key checks run before the first batch (the sync static_process over zero-row inputs, so the sync errors and messages, e1/ITL-856). Matching uses the sync join's prepared key frames, one Polars join per arriving batch; values are taken by row number. Join is a staggered chain in canonical order; MergeJoin is binary in argument order; SemiJoin streams its left input. No sync code path changes. Tests: tests/test_core/operators/test_streaming_joins.py (48), random batch cuts and interleavings compared with static_process as multisets with the same columns/types. Co-Authored-By: Claude Opus 5.5 * fix(operators): streaming joins match, type and hold as the sync path does (ITL-1362) Codex review round 1 of #482: - A null list, struct or decimal256 key matched another null. The kernel now matches by the sync join's own rule: the constant join key and Polars' inner join are one definition each (join._with_common_key, join._matched_pairs), used by Join, MergeJoin and the kernels (pure extractions of the sync code). - The kernel reads every input in its row-built form (F of the ITL-1347 spec: null as large_string), as a job's edges carry it: preflight, batch types and zero_row_result follow it. An input that ends empty is checked again in its zero-row form at the last close, as the sync path reads it. - System-tag flags, like source-info flags, are settled by values on the complete table: every emitted batch declares both nullable. - A refusal that depends on values (source-info token lists of different lengths) is raised when its batch arrives, with the sync error; documented. - A Join step that can never emit again releases its successor and every earlier step; SemiJoin never holds a left row with a top-level null key (semijoin._has_whole_key, shared with the sync path). Tests: the oracle is the sync operator over inputs rebuilt from rows; flags compared after settling both kinds; zero_row_result compared with the sync operator's own; null keys in the list and struct pools, a decimal256 pool, one and two shared keys. Co-Authored-By: Claude Opus 5.5 * test(operators): streaming join kernels in three arrangements; a rejected batch changes nothing (ITL-1362) CodeRabbit's review of #482 (round 1, with fe3f3214): the tag-role tests of Join, MergeJoin and SemiJoin run in three arrangements (declared and reversed tag order; tags first, data first reversed, interleaved layouts); a batch refused for one column leaves the kernel able to take the corrected batch. Docstrings for the input guard and Join's push and close hooks. Co-Authored-By: Claude Opus 5.5 * fix(operators): streaming Join keeps merging steps when a later input ends empty (ITL-1362) CodeRabbit's review of #482 at eb8d0261: when a later input in canonical order ends empty, the sync Join still merges the earlier inputs' data-tag source info (refusing token lists of different lengths) before it meets the empty input. The kernel released every earlier step; it now keeps the steps up to the last earlier one that merges source info matching, drops that step's output, and releases the rest. Only streaming_joins.py and its tests change; no sync file. Co-Authored-By: Claude Opus 5.5 * fix(operators): streaming join kernels, Codex review round 2 of #482 (ITL-1362) - An empty run whose empty input has a null column ends with the sync result's types: when no row was emitted, the last close's result over the inputs as they ended becomes zero_row_result. - A row whose key holds a top-level null is never held by a link, so a closed input holding only such rows is exhausted like an empty one. - Module docstring: the kernels' domain is what a job carries (no source takes a null-typed column); the first offending source-info pair observed is refused, which may depend on arrival; SemiJoin with no shared tag. - F is now the job-speed definition (streams.base.row_built_columns, StaticOutputOperatorPod._flag_by_values) instead of an interim copy. - Tests: an empty run's types; a source refuses a null-typed column; two schedules with several offending pairs; a closed input with only null keys; the multiset oracle compares temporal values as Arrow integers, with time64[ns] and timestamp[ns] key pools. Only streaming_joins.py and its tests change. Co-Authored-By: Claude Opus 5.5 * feat(operators): streaming Rejoin kernel on Arrow record batches (ITL-1362) StreamingRejoin applies ITL-1355's rule per arriving batch: in Join's canonical order, each step is a symmetric match on every column both sides share (system tags, shared user tags, a shared data-tag's source info, the data context), Join's equality, nulls equal outside the system tags, a null system tag matching nothing. Each side keeps only its unmatched rows (a removal mask, compacted when most rows are removed); repeats of an origin row pair one to one in arrival order (occurrence numbers), so the work stays linear; once a side closes, the other side's rows are dropped. Each input's rows carry its own data context, so inputs of two contexts match nothing, as on the sync path. RejoinDifferingColumnWarning: differing columns are noted per batch and warned once at the last close, through the operator. With two inputs this is the sync warning; with three or more it is detected per link, so a difference between non-adjacent inputs for an origin row the middle input lacks is not warned about (provisionally accepted; rows identical; pinned by a test). No sync file changes: rejoin.py is unchanged; the kernel uses its existing Rejoin._warn_differing_once and _described. Co-Authored-By: Claude Opus 5.5 * fix(operators): streaming joins skip key preparation for a closed empty side; tighter tests (ITL-1362) CodeRabbit's review of #482 at 251bb525: - A link returns before filtering and preparing keys when the other side has closed holding no row (nothing can pair, and nothing is held). - The several-offending-pairs test asserts the lengths of the pair each schedule exposes (1 and 2; 1 and 3), not only the message form. - The late-empty fixture gives every populated pair different lengths, so it refuses whatever the pipeline-hash order. - The multiset oracle compares temporal values at any depth (lists, structs) as their integers; a regression test. Only streaming_joins.py and its tests change. Co-Authored-By: Claude Opus 5.5 * fix(operators): streaming Rejoin, Codex review of #487 (ITL-1362) - A match that takes the last row a closed side held exhausts the step; the chain is now released after every push, not only on a close. - Values are taken from the chunks that hold them (_take_rows): Arrow's take on a chunked column concatenates the whole column, a copy of the held table per batch. Cost is one vectorized join per batch, O(held rows), as in the Join kernels (docstring corrected; no "linear" claim). - The docstring states what holds: rows equal the sync rows for every schedule with unique origins, and with repeated origins for two inputs; with three or more inputs and repeated origins the pairing of repeats can depend on arrival (the spec's named risk; option X is the exact alternative). The warning is guaranteed for two inputs with unique origins, best effort otherwise (option B is the alternative). Refusals: the base class's empty-input check can refuse at the last close. - Tests: the reviewer's cases pinned (three inputs with repeats, two schedules; the binary warning with repeats; adjacent inputs whose prefix lacks the origin; the chain released by a match), the two-input warning over 24 schedules, and one join and no held-table copy per batch (a proxy memory pool per batch; only compactions copy, at most log2 n of them). Only streaming_joins.py and its Rejoin tests change; no sync file. Co-Authored-By: Claude Opus 5.5 * fix(operators): streaming Rejoin, at most two joins per batch per step; exact docstrings (ITL-1362) Codex review round 2 and CodeRabbit's review of #487 at 70471b93: - The warning check runs one join on the system tags for the arriving rows that matched nothing, then compares each other shared column over those pairs in one vectorized eq_missing (Join's equality, nulls equal), instead of one join per column: at most two Polars joins per batch per step. The docstring states the cost exactly: O(held rows) per batch plus O(m log m) to take the m pairs from the held chunks (one vectorized lookup and sort). - Module and test headers: the kernels are not yet wired into async_execute; row equality holds within the limits each kernel states. - Tests: a partly matching batch costs two joins and warns as sync (the reviewer's case); four inputs keep the last step's buffered matches when earlier steps release, a late row to a released step is not held, all 24 call orders give the sync rows; an extension and a nested payload cross held chunks and compaction. Only streaming_joins.py and the Rejoin tests change. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Edgar Y. Walker <> Co-authored-by: Claude Opus 5.5 Co-authored-by: Edgar Y. Walker --- src/orcapod/core/operators/streaming_joins.py | 528 +++++++++++- .../operators/test_streaming_rejoin.py | 777 ++++++++++++++++++ 2 files changed, 1300 insertions(+), 5 deletions(-) create mode 100644 tests/test_core/operators/test_streaming_rejoin.py diff --git a/src/orcapod/core/operators/streaming_joins.py b/src/orcapod/core/operators/streaming_joins.py index 6b9d64e7c..ab8ef14d9 100644 --- a/src/orcapod/core/operators/streaming_joins.py +++ b/src/orcapod/core/operators/streaming_joins.py @@ -1,10 +1,12 @@ """Streaming join kernels: symmetric hash joins on Arrow record batches (ITL-1362). -The async path of ``Join``, ``MergeJoin`` and ``SemiJoin`` (ITL-1347, stage 5) reads its -inputs as Arrow record batches, in whatever order they arrive, and must give the rows of -the operator's sync ``static_process`` over the same inputs, as a multiset (row order is -not a result on the async path; developer, November 22, 2026). A kernel is that -computation without the channels: the channel layer creates one per run from the input +The async path of ``Join``, ``MergeJoin``, ``SemiJoin`` and ``Rejoin`` (ITL-1347, stage +5) is to read its inputs as Arrow record batches, in whatever order they arrive; these +kernels are that computation, not yet wired into ``async_execute``. A kernel gives the +rows of the operator's sync ``static_process`` over the same inputs as a multiset (row +order is not a result on the async path; developer, November 22, 2026), within the +limits each kernel's docstring states (``StreamingRejoin``: repeated origins with three +or more inputs). A kernel is that computation without the channels: the channel layer creates one per run from the input streams (the descriptions) and hands it each arriving record batch (``push``) and each input's end (``close``); every call returns the output rows it decided, as record batches. @@ -99,6 +101,10 @@ _merged_list, # pyright: ignore[reportPrivateUsage] # MergeJoin's one rule _output_types, # pyright: ignore[reportPrivateUsage] # MergeJoin's one rule ) +from orcapod.core.operators.rejoin import ( + Rejoin, + _described, # pyright: ignore[reportPrivateUsage] # Rejoin's one rule +) from orcapod.core.operators.semijoin import ( SemiJoin, _has_whole_key, # pyright: ignore[reportPrivateUsage] # SemiJoin's one rule @@ -996,3 +1002,515 @@ def _close(self, input_index: int) -> list[pa.Table]: # No right row will arrive: the undecided left rows never match. self._waiting = None return [] + + +# The occurrence-number column of a Rejoin key frame, and the prefix of the other side's +# columns in the warning's pairs (never an input column: those never start so). +_OCCURRENCE = "__streaming_occurrence" +_OTHER = "__streaming_other_" + + +def _with_context(table: pa.Table, context_key: str) -> pa.Table: + """``table`` with the data context column every row of it carries on the sync path. + + An input a job rebuilds from rows carries its producer's data context on every row + (``StaticOutputOperatorPod._as_upstream_stream``), and ``Rejoin`` matches on it. + Transport batches carry no context column, so the kernel adds the input's own. + """ + return table.append_column( + pa.field(constants.CONTEXT_KEY, pa.large_string(), nullable=False), + pa.array([context_key] * table.num_rows, pa.large_string()), + ) + + +def _with_system_tags(table: pa.Table, keys: Sequence[str]) -> pa.Table: + """The rows of ``table`` whose system tags are all present: a null matches nothing.""" + if not table.num_rows: + return table + return table.filter(_has_whole_key(table, keys)) + + +def _take_rows(table: pa.Table, rows: np.ndarray[Any, np.dtype[np.int64]]) -> pa.Table: + """The rows of ``table`` with these numbers, in this order, without combining chunks. + + Arrow's ``take`` on a chunked column concatenates its chunks first, a copy of the + whole column. Here only the chunks that hold a wanted row are read: each one's rows + are taken from it alone, and the small result is put in the order asked for. + + Args: + table: A table, of any number of chunks. + rows: Row numbers in ``table``. + + Returns: + The rows, as one chunk. + """ + batches = table.to_batches() + if len(batches) <= 1: + return table.take(pa.array(rows, pa.int64())) + lengths = np.fromiter((b.num_rows for b in batches), np.int64, len(batches)) + starts = np.concatenate([np.zeros(1, np.int64), np.cumsum(lengths)[:-1]]) + chunks = np.searchsorted(starts, rows, side="right") - 1 + order = np.argsort(chunks, kind="stable") + sorted_rows, sorted_chunks = rows[order], chunks[order] + edges = np.flatnonzero(np.diff(sorted_chunks)) + 1 + parts: list[pa.Table] = [] + for group in np.split(np.arange(len(sorted_rows)), edges): + chunk = int(sorted_chunks[group[0]]) + local = sorted_rows[group] - starts[chunk] + parts.append( + pa.Table.from_batches([batches[chunk]]).take(pa.array(local, pa.int64())) + ) + taken = pa.concat_tables(parts).combine_chunks() + return taken.take(pa.array(np.argsort(order, kind="stable"), pa.int64())) + + +def _occurrences(frame: pl.DataFrame, among: Sequence[str]) -> pl.DataFrame: + """Number each row among the rows before it equal to it in ``among`` (0, 1, ...). + + With it, rows that repeat an origin row are matched one to one in the order they + arrived (``Rejoin``'s occurrence rule), and no join ever pairs every repeat of one + side with every repeat of the other: the pairs made are only the pairs kept. + """ + return frame.with_columns( + pl.int_range(pl.len()).over(list(among)).alias(_OCCURRENCE) + ) + + +class _Remaining: + """An input's rows not matched yet, with a key frame and a mask of removed rows. + + Removing a row only clears its mask bit; the rows are compacted when the removed + ones are the majority, so a batch never copies the whole table. + + Args: + columns: The shared columns of the key frame (system tags first). + row: The row-number column. + """ + + def __init__(self, columns: Sequence[str], row: str) -> None: + self.columns: list[str] = list(columns) + self.row: str = row + self.closed: bool = False + self.schema: pa.Schema | None = None + self._tables: list[pa.Table] = [] + self._frames: list[pl.DataFrame] = [] + self._alive: list[np.ndarray[Any, np.dtype[np.bool_]]] = [] + self._table: pa.Table | None = None + self._frame: pl.DataFrame | None = None + self.size: int = 0 + self.rows: int = 0 + + def append(self, table: pa.Table) -> None: + """Hold ``table``'s rows.""" + if not table.num_rows: + return + frame = polars_key_frame(table, self.columns, self.row) + self._frames.append(frame.with_columns(pl.col(self.row) + self.size)) + self._tables.append(table) + self._alive.append(np.ones(table.num_rows, dtype=np.bool_)) + self._table, self._frame = None, None + self.size += table.num_rows + self.rows += table.num_rows + + def table(self) -> pa.Table: + """Every row appended and not compacted away, numbered as in ``frame``.""" + if self._table is None: + self._table = pa.concat_tables(self._tables) + self._tables = [self._table] + return self._table + + def frame(self) -> pl.DataFrame: + """The key frame of the rows not removed, in the order they arrived.""" + if self._frame is None: + frame = pl.concat(self._frames, rechunk=False) + alive = np.concatenate(self._alive) + self._frames, self._alive = [frame], [alive] + self._frame = frame.filter(pl.Series(alive)) + return self._frame + + def remove(self, rows: np.ndarray[Any, np.dtype[np.int64]]) -> None: + """Remove the rows with these numbers (each held and not removed yet).""" + if not len(rows): + return + self.frame() + alive = self._alive[0] + alive[rows] = False + self.rows -= len(rows) + self._frame = None + if self.rows * 2 < self.size: + self._compact() + + def _compact(self) -> None: + """Drop the removed rows and number the rest from 0.""" + alive = np.concatenate(self._alive) + table = self.table().filter(pa.array(alive)) + self.clear() + self.append(table) + + def clear(self) -> None: + """Drop every row held.""" + self._tables, self._frames, self._alive = [], [], [] + self._table, self._frame = None, None + self.size = 0 + self.rows = 0 + + +class _RejoinLink: + """One step of ``Rejoin``: a symmetric match of two sides on every shared column. + + Args: + system: The system-tag columns, sorted. + others: The other columns both sides have (shared user tags, a shared data-tag's + source info, the data context), sorted. + finish: Turns the pairs' table into the link's output; given both schemas. + """ + + def __init__( + self, + system: Sequence[str], + others: Sequence[str], + finish: Callable[[pa.Table, pa.Schema, pa.Schema], pa.Table], + ) -> None: + self.system: list[str] = list(system) + self.others: list[str] = list(others) + self.shared: list[str] = [*system, *others] + self.sides: tuple[_Remaining, _Remaining] = ( + _Remaining(self.shared, _ROW[0]), + _Remaining(self.shared, _ROW[1]), + ) + self._finish: Callable[[pa.Table, pa.Schema, pa.Schema], pa.Table] = finish + # The shared columns other than system tags in which rows of one origin row + # (their system tags match) were seen to differ. + self.differing: set[str] = set() + + @property + def held_rows(self) -> int: + """The unmatched rows both sides hold.""" + return self.sides[0].rows + self.sides[1].rows + + @property + def exhausted(self) -> bool: + """Whether the link can never emit again: a side closed holding no row.""" + return any(side.closed and not side.rows for side in self.sides) + + def release(self) -> None: + """End both sides: the link's output is never needed again.""" + for side in self.sides: + side.closed = True + side.clear() + + def close(self, side: int) -> None: + """Note that ``side`` ends: the other side's rows can never match again.""" + self.sides[side].closed = True + self.sides[1 - side].clear() + + def push(self, side: int, table: pa.Table) -> pa.Table | None: + """Match ``table``'s rows with the other side's remaining rows. + + Args: + side: 0 for the left side, 1 for the right. + table: The arriving rows (with the data context column). + + Returns: + The output rows of the matched pairs, or ``None`` when there is none. + """ + this, other = self.sides[side], self.sides[1 - side] + if this.schema is None: + this.schema = table.schema + table = _with_system_tags(table, self.system) + if not table.num_rows: + return None + row, other_row = _ROW[side], _ROW[1 - side] + frame = _occurrences(polars_key_frame(table, self.shared, row), self.shared) + result = None + unmatched = np.ones(table.num_rows, dtype=np.bool_) + if other.rows: + held = _occurrences(other.frame(), self.shared) + pairs = frame.join( + held, on=[*self.shared, _OCCURRENCE], how="inner", nulls_equal=True + ) + if pairs.height: + mine = pairs.get_column(row).to_numpy() + theirs = pairs.get_column(other_row).to_numpy() + unmatched[mine] = False + tables = (table, other.table()) if side == 0 else (other.table(), table) + rows = (mine, theirs) if side == 0 else (theirs, mine) + result = self._pairs(*tables, *rows) + other.remove(theirs) + rest = table.filter(pa.array(unmatched)) if not unmatched.all() else table + if rest.num_rows and other.rows and self.others: + self._note_differing(rest, other, side) + if not other.closed: + this.append(rest) + return result + + def _pairs( + self, + left: pa.Table, + right: pa.Table, + left_rows: np.ndarray[Any, np.dtype[np.int64]], + right_rows: np.ndarray[Any, np.dtype[np.int64]], + ) -> pa.Table: + """The matched pairs as ``Rejoin._rejoin_pair`` builds them, by row number. + + Values are taken from the chunks that hold them (``_take_rows``): no held + table is copied. + """ + left_taken = _take_rows(left, left_rows) + right_taken = _take_rows(right, right_rows) + names: list[str] = [] + arrays: list[Any] = [] + for name in left.column_names: + names.append(name) + arrays.append(left_taken.column(name)) + for name in right.column_names: + if name not in left.column_names: + names.append(name) + arrays.append(right_taken.column(name)) + assert self.sides[0].schema is not None + assert self.sides[1].schema is not None + return self._finish( + pa.Table.from_arrays(arrays, names=names), + self.sides[0].schema, + self.sides[1].schema, + ) + + def _note_differing(self, rest: pa.Table, other: _Remaining, side: int) -> None: + """Note the shared columns in which unmatched rows of one origin row differ. + + One more join, of the arriving rows that matched nothing on the system tags only + against the other side's remaining rows, pairs the rows of one origin row (their + repeats in arrival order), with both sides' prepared values of the other shared + columns. Each such column is then compared over those pairs in one vectorized + expression, ``eq_missing`` on the prepared values: ``Join``'s equality (NaN + equals NaN, ``-0.0`` equals ``0.0``, at any depth) with a null equal to a null, + as the sync path compares them. + """ + row = _ROW[side] + names = [name for name in self.others if name not in self.differing] + if not names: + return + origin = [*self.system, _OCCURRENCE] + mine = _occurrences(polars_key_frame(rest, self.shared, row), self.system) + theirs = _occurrences(other.frame(), self.system).select( + [*origin, *(pl.col(name).alias(_OTHER + name) for name in names)] + ) + pairs = mine.select([*origin, *names]).join(theirs, on=origin, how="inner") + if not pairs.height: + return + differ = pairs.select( + (~pl.col(name).eq_missing(pl.col(_OTHER + name))).any().alias(name) + for name in names + ).row(0, named=True) + self.differing.update(name for name, differs in differ.items() if differs) + + +class StreamingRejoin(StreamingJoinKernel): + """``Rejoin`` on record batches: symmetric matches on every shared column. + + ITL-1355's rule, as ``Rejoin.static_process`` applies it: the inputs are taken in + ``Join``'s canonical order (by pipeline hash, ties in call order) and rejoined pair by + pair, the rows rejoined so far with the next input, each step an inner join on every + column both sides have (system tags, shared user tags, a shared data-tag's source + info, the data context) under ``Join``'s equality, a null equal to a null outside the + system tags and a null system tag matching nothing. Each step is a ``_RejoinLink``: + + - each side keeps only its rows not matched yet (a matched row leaves at once), so + the memory held is the unmatched rows; + - an arriving batch is matched, in one vectorized join, with the other side's + remaining rows; rows that repeat an origin row pair one to one in arrival order; + - once one side closes, the other side's remaining rows are dropped, and an arriving + row either matches at once or is dropped. + + Cost, per arriving batch and per step it reaches: at most two Polars joins against + the other side's remaining rows, the match and, when some arriving rows matched + nothing and the other side holds rows, one more on the system tags for the warning + (each other shared column then compared in one vectorized expression); and the + occurrence numbers of the remaining rows. That is O(held rows) per batch, as in the + ``Join`` kernels, plus O(m log m) to take the m pairs it makes from the held chunks + (``_take_rows``: one vectorized chunk lookup and one sort for all of them), never by + copying a whole held table; a compaction copies the remaining rows when half of + those held were removed. A long run of one-row batches against a large buffer is + quadratic in the rows. + + Rows: they equal the sync path's as a multiset, for every arrival schedule, when + origins are unique (system tags unique in each input, as every source makes them), + and also with repeated origins for two inputs (and at the first step of a chain): + the k-th repeat of one input pairs with the k-th of the other, in each input's row + order, as on the sync path. With three or more inputs and repeated origins, the + pairing of repeats at a later step can depend on arrival and differ from the sync + path, which ranks the rows rejoined so far in its table order among the rows that + survived the earlier step. The approved spec names this risk ("Duplicates ... 'match + once' pairs duplicates in arrival order, which can differ between sync and async + (risks; ITL-1356 removes the case)"); the developer's rule for ``Rejoin`` is that + system tags are unique by construction. The exact alternative (option X) is + survival-aware ranking: per-step counters, and rows of a repeated origin held until + every earlier row of that origin has a final fate at the step before. + + The data context: a job's rows carry their producer's data context, which ``Rejoin`` + matches on. Transport batches carry none, so each input's rows are given the data + context of its stream (``StaticOutputOperatorPod._upstream_context``): inputs of two + data contexts match nothing, and a link holds their rows to the end. + + The warning: rows of one origin row (system tags equal) that differ in another + shared column are noted per batch, between an arriving row that matched nothing and + the other side's remaining rows; when the last input closes, the kernel issues + ``RejoinDifferingColumnWarning`` once for the columns noted, through the operator + (``Rejoin._warn_differing_once``), as the sync path issues it once for its run. + + - Guaranteed: with two inputs and unique origins, the warning is the sync path's + (the same columns, once) for every arrival schedule. + - Best effort otherwise (provisional, November 22, 2026; the rows are never + affected): the kernel reports only differences between rows the chain actually + compares, so a difference can be missed, and with repeated origins it can depend + on arrival. With three or more inputs a step compares the rows rejoined so far + with the next input: a difference between two inputs for an origin row that an + input before the later of them lacks is not seen (whether or not the two are + adjacent in the chain). With repeated origins a repeat already matched is no + longer compared, while the sync path compares repeats by occurrence whatever + their matches. The sync path compares every pair of inputs over all their rows; + the alternative (option B) is pairwise detection, which would keep every input's + shared-column keys for every row until all inputs close. + + ``Rejoin`` refuses nothing for what rows hold: every refusal it raises for its inputs' + columns and types comes before the first batch, except the base class's check of an + input that ends empty, which can refuse at the last close (``StreamingJoinKernel``). + + Args: + operator: The ``Rejoin``. + inputs: Its input streams, in call order. + """ + + def __init__(self, operator: Rejoin, inputs: Sequence[StreamProtocol]) -> None: + super().__init__(operator, inputs) + self._rejoin = operator + order = sorted( + range(len(inputs)), key=lambda i: inputs[i].pipeline_hash().to_hex() + ) + self._position = {index: position for position, index in enumerate(order)} + self._contexts = [ + StaticOutputOperatorPod._upstream_context(stream).context_key # pyright: ignore[reportPrivateUsage] # the operators' one rule + for stream in inputs + ] + self._user_tags: set[str] = { + name for stream in inputs for name in stream.keys()[0] + } + self._links: list[_RejoinLink] = [] + if len(inputs) == 1: + return + layouts = [self._layouts[i] for i in order] + system = sorted( + name + for name in layouts[0].names + if name.startswith(constants.SYSTEM_TAG_PREFIX) + ) + left_names = [*layouts[0].names, constants.CONTEXT_KEY] + user_tags = set(inputs[order[0]].keys()[0]) + for index in order[1:]: + right_names = [*self._layouts[index].names, constants.CONTEXT_KEY] + others = sorted( + name + for name in right_names + if name in left_names and name not in system + ) + next_tags = set(inputs[index].keys()[0]) + self._links.append( + _RejoinLink(system, others, self._link_finish(user_tags & next_tags)) + ) + left_names = [ + *left_names, + *(name for name in right_names if name not in left_names), + ] + user_tags |= next_tags + + @property + def held_rows(self) -> int: + return sum(link.held_rows for link in self._links) + + def _link_finish( + self, shared_tags: set[str] + ) -> Callable[[pa.Table, pa.Schema, pa.Schema], pa.Table]: + """What one step does to its pairs, as ``Rejoin._rejoin_pair`` does.""" + + def finish( + table: pa.Table, left_schema: pa.Schema, right_schema: pa.Schema + ) -> pa.Table: + table = arrow_utils.restore_schema_nullability( + table, left_schema, right_schema + ) + return Join._shared_key_nullability( # pyright: ignore[reportPrivateUsage] # Join's one rule + table, left_schema, right_schema, shared_tags + ) + + return finish + + def _push(self, input_index: int, table: pa.Table) -> list[pa.Table]: + """Feed an input's rows into its step and forward what each step emits. + + Args: + input_index: The input, in call order. + table: Its rows, never empty. + + Returns: + The last step's output, possibly none. + """ + if not self._links: + return [table] + table = _with_context(table, self._contexts[input_index]) + position = self._position[input_index] + step, side = (0, 0) if position == 0 else (position - 1, 1) + result = self._links[step].push(side, table) + while result is not None and step < len(self._links) - 1: + step += 1 + result = self._links[step].push(0, result) + # A match can take the last row a closed side held: that step is exhausted. + self._release_exhausted() + return [] if result is None else [result] + + def _release_exhausted(self) -> None: + """Release what a step that can never emit again makes useless. + + Such a step (a side closed holding no row, ``_RejoinLink.exhausted``) closes its + successor's left side, and every earlier step is released: its rows could only + reach this one. A step is exhausted by a close, or by a match that takes the + last row a closed side held. + """ + for step, link in enumerate(self._links): + if not link.exhausted: + continue + for earlier in self._links[:step]: + earlier.release() + if ( + step + 1 < len(self._links) + and not self._links[step + 1].sides[0].closed + ): + self._links[step + 1].close(0) + + def _close(self, input_index: int) -> list[pa.Table]: + """End an input's side, every side that can no longer receive, and warn last. + + A step that can never emit again closes its successor's left side and releases + every earlier step, whose rows could only reach it. When the last input closes, + the differing columns noted are warned of once. + + Args: + input_index: The input, in call order. + + Returns: + No table. + """ + if not self._links: + return [] + position = self._position[input_index] + step, side = (0, 0) if position == 0 else (position - 1, 1) + self._links[step].close(side) + self._release_exhausted() + if all(self._closed): + differing = {name for link in self._links for name in link.differing} + if differing: + self._rejoin._warn_differing_once( # pyright: ignore[reportPrivateUsage] # Rejoin's one rule + tuple( + sorted(_described(name, self._user_tags) for name in differing) + ) + ) + return [] diff --git a/tests/test_core/operators/test_streaming_rejoin.py b/tests/test_core/operators/test_streaming_rejoin.py new file mode 100644 index 000000000..f33819534 --- /dev/null +++ b/tests/test_core/operators/test_streaming_rejoin.py @@ -0,0 +1,777 @@ +"""The streaming Rejoin kernel gives the sync Rejoin's rows, within its stated limits. + +ITL-1362 (ITL-1347, stage 5): ``StreamingRejoin`` is the streaming form of ``Rejoin`` on +Arrow record batches, not yet wired into ``async_execute`` (which is still the barrier). +It applies ITL-1355's rule: an inner join on every column the inputs share (system +tags, shared user tags, a shared data-tag's source info, the data context), ``Join``'s +equality, a null equal to a null outside the system tags, a null system tag matching +nothing, each row matching at most once. Its rows equal the sync rows as a multiset for +every schedule with unique origins, and with repeated origins for two inputs; with +three or more inputs and repeated origins, arrival order can change the pairing +(``test_repeats_with_three_inputs_can_pair_by_arrival``), and the warning is guaranteed +only for two inputs with unique origins; those documented differences are pinned below. +These are direct tests of the kernel, not of an async execution path. The oracle and the arrivals are those of +``test_streaming_joins``: the sync operator over the inputs rebuilt from rows, compared +as a multiset, after random batch cuts and interleavings. +""" + +from __future__ import annotations + +import dataclasses +import itertools +import math +import random +import warnings +from collections.abc import Sequence +from pathlib import Path +from typing import Any + +import polars as pl +import pyarrow as pa +import pytest + +from orcapod import contexts +from orcapod.core.operators import Rejoin +from orcapod.core.operators.streaming_joins import ( + StreamingJoinKernel, + StreamingRejoin, +) +from orcapod.core.sources import ArrowTableSource +from orcapod.core.streams import ArrowTableStream +from orcapod.errors import InputValidationError, RejoinDifferingColumnWarning +from orcapod.protocols.core_protocols import StreamProtocol +from orcapod.system_constants import constants + +from .test_streaming_joins import ( + _arrivals, # pyright: ignore[reportPrivateUsage] # the shared harness + _rows, # pyright: ignore[reportPrivateUsage] # the shared harness + _check, # pyright: ignore[reportPrivateUsage] # the shared harness + _row_built, # pyright: ignore[reportPrivateUsage] # the shared harness + _run, # pyright: ignore[reportPrivateUsage] # the shared harness + _sent, # pyright: ignore[reportPrivateUsage] # the shared harness + _transport, # pyright: ignore[reportPrivateUsage] # the shared harness + assert_same_rows, +) + + +@pytest.fixture(autouse=True) +def _quiet_provisional() -> Any: + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + yield + + +def _kernel(inputs: Sequence[StreamProtocol]) -> StreamingJoinKernel: + return StreamingRejoin(Rejoin(), inputs) + + +def _origin(n: int = 12, *, data_tags: bool = False) -> ArrowTableSource: + """``n`` rows: tags ``subject`` and ``unit``; data ``rate``, ``depth``, ``area``.""" + return ArrowTableSource( + pa.table( + { + "subject": pa.array([f"s{i % 3}" for i in range(n)], pa.large_string()), + "unit": pa.array(list(range(n)), pa.int64()), + "rate": pa.array([float(i) for i in range(n)], pa.float64()), + "depth": pa.array([10 * i for i in range(n)], pa.int64()), + "area": pa.array(["V1"] * n, pa.large_string()), + } + ), + tag_columns=["subject", "unit"], + tag_only_columns=False if data_tags else True, + source_id="units", + ) + + +def _branches(origin: Any) -> list[Any]: + """Three branches of one stream, each with its own data column and rows.""" + return [ + origin.select_data_columns(["rate"]), + origin.polars_filter(pl.col("depth") >= 30).select_data_columns(["depth"]), + origin.polars_filter(pl.col("rate") < 9.0).select_data_columns(["area"]), + ] + + +# --------------------------------------------------------------------------- +# The rows, against the sync path +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize("data_tags", [False, True]) +def test_two_branches_in_both_orders(data_tags: bool) -> None: + first, second, _ = _branches(_origin(data_tags=data_tags)) + for inputs in ((first, second), (second, first)): + _check(_kernel, Rejoin().static_process, inputs) + + +@pytest.mark.parametrize("order", list(itertools.permutations(range(3)))) +def test_three_branches_in_every_order(order: tuple[int, ...]) -> None: + branches = _branches(_origin(data_tags=True)) + _check(_kernel, Rejoin().static_process, [branches[i] for i in order], range(6)) + + +def test_a_single_input_passes_its_rows() -> None: + _check(_kernel, Rejoin().static_process, (_branches(_origin())[0],)) + + +def test_a_shared_tag_that_differs_on_some_rows_matches_only_where_equal() -> None: + origin = _origin() + left = origin.select_data_columns(["rate"]).add_tags(run=1) + right = origin.polars_filter(pl.col("unit") < 6).select_data_columns(["depth"]) + right = right.add_tags(run=1) + other = origin.polars_filter(pl.col("unit") >= 6).select_data_columns(["depth"]) + other = other.add_tags(run=2) + for inputs in ((left, right), (right, left), (left, other), (other, left)): + _check(_kernel, Rejoin().static_process, inputs) + + +def _hand_branch( + data: str, *, origin: list[str | None], tag: list[int | None] +) -> ArrowTableStream: + """A hand-built branch: tag ``k``, one system tag, data column ``data``.""" + n = len(origin) + return ArrowTableStream( + pa.table( + { + "k": pa.array(tag, pa.int64()), + data: pa.array([float(i) for i in range(n)], pa.float64()), + "origin": pa.array(origin, pa.large_string()), + } + ), + tag_columns=["k"], + system_tag_columns=["origin"], + ) + + +def test_a_null_system_tag_matches_nothing_and_a_null_tag_equals_a_null() -> None: + # Rows rebuilt from datagrams cannot hold a null system tag (provenance is never + # null), so the oracle here is the sync path over the raw streams, and the + # kernel is fed their tables. + left = _hand_branch("a", origin=["r1", None, "r3", "r4"], tag=[1, 2, None, 4]) + right = _hand_branch("b", origin=["r1", None, "r3", "r4"], tag=[1, 2, None, 5]) + for inputs in ((left, right), (right, left)): + expected = _transport(Rejoin().static_process(*inputs)) + assert sorted(expected.column("k").to_pylist(), key=str) == [1, None] + tables = [_transport(stream) for stream in inputs] + for seed in range(6): + kernel = StreamingRejoin(Rejoin(), inputs) + batches = _run(kernel, _arrivals(tables, random.Random(seed))) + assert_same_rows(batches, kernel, expected) + assert kernel.held_rows == 0 + + +def _repeated(n: int, data: str, k: list[int] | None = None) -> ArrowTableStream: + """``n`` rows of ONE origin row: tag ``k``, one system tag, data ``data`` = 0..n-1.""" + return ArrowTableStream( + pa.table( + { + "k": pa.array(k or [1] * n, pa.int64()), + data: pa.array(range(n), pa.int64()), + "origin": pa.array(["x"] * n, pa.large_string()), + } + ), + tag_columns=["k"], + system_tag_columns=["origin"], + ) + + +def test_repeats_of_an_origin_row_pair_one_to_one_in_arrival_order() -> None: + # Each input's batches arrive in its row order, so the arrival-order pairing of + # the occurrence rule is the sync path's row-order pairing. + for left, right in ( + (_repeated(9, "a"), _repeated(6, "b")), + (_repeated(8, "a", [1, 2] * 4), _repeated(7, "b", [2, 1, 2, 2, 1, 1, 2])), + ): + for inputs in ((left, right), (right, left)): + _check(_kernel, Rejoin().static_process, inputs) + + +def test_thousands_of_repeats_stay_linear() -> None: + # 3,000 rows of one origin row on each side, in one-row batches: each arriving row + # pairs with one remaining row (never with every repeat), and the remaining set + # holds at most the rows not paired yet. + n = 3000 + left, right = _repeated(n, "a"), _repeated(n - 7, "b") + kernel = StreamingRejoin(Rejoin(), (left, right)) + out: list[pa.RecordBatch] = [] + largest = 0 + lefts = _sent(left).combine_chunks().to_batches(max_chunksize=1) + rights = _sent(right).combine_chunks().to_batches(max_chunksize=1) + for index in range(n): + out += kernel.push(0, lefts[index]) + if index < len(rights): + out += kernel.push(1, rights[index]) + largest = max(largest, kernel.held_rows) + assert largest <= 8 + assert sum(batch.num_rows for batch in out) == n - 7 + assert kernel.held_rows == 7 + kernel.close(1) + assert kernel.held_rows == 0 + kernel.close(0) + + +# --------------------------------------------------------------------------- +# What the kernel holds +# --------------------------------------------------------------------------- + + +def test_only_unmatched_rows_are_held() -> None: + first, second, _ = _branches(_origin()) + kernel = StreamingRejoin(Rejoin(), (first, second)) + first_rows, second_rows = _sent(first), _sent(second) + kernel.push(0, first_rows.combine_chunks().to_batches()[0]) + assert kernel.held_rows == first_rows.num_rows + emitted = kernel.push(1, second_rows.combine_chunks().to_batches()[0]) + matched = sum(batch.num_rows for batch in emitted) + assert matched == second_rows.num_rows + # Every matched row left both sides: only the first input's unmatched rows stay. + assert kernel.held_rows == first_rows.num_rows - matched + kernel.close(1) + assert kernel.held_rows == 0 + kernel.close(0) + + +def test_after_one_input_closes_the_other_inputs_rows_are_not_held() -> None: + first, second, _ = _branches(_origin()) + second_rows = _sent(second).combine_chunks() + kernel = StreamingRejoin(Rejoin(), (first, second)) + kernel.push(1, second_rows.slice(0, 3).to_batches()[0]) + assert kernel.held_rows == 3 + # The first input ends with no row: the second's rows can never match. + kernel.close(0) + assert kernel.held_rows == 0 + kernel.push(1, second_rows.slice(3).to_batches()[0]) + assert kernel.held_rows == 0 + assert kernel.close(1) == [] + + +def test_three_inputs_release_every_step_once_an_input_ends_empty() -> None: + branches = _branches(_origin(data_tags=True)) + for empty in range(3): + kernel = StreamingRejoin(Rejoin(), branches) + kernel.close(empty) + for index in range(3): + if index != empty: + kernel.push( + index, _sent(branches[index]).combine_chunks().to_batches()[0] + ) + assert kernel.held_rows == 0, empty + + +# --------------------------------------------------------------------------- +# The warning and the data context +# --------------------------------------------------------------------------- + + +def _warnings_of(run: Any) -> list[str]: + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + run() + return sorted( + str(w.message) + for w in caught + if issubclass(w.category, RejoinDifferingColumnWarning) + ) + + +def _sync_warnings(inputs: Sequence[StreamProtocol]) -> list[str]: + rebuilt = [_row_built(stream) for stream in inputs] + return _warnings_of(lambda: Rejoin().static_process(*rebuilt)) + + +def _kernel_warnings(inputs: Sequence[StreamProtocol], seed: int) -> list[str]: + tables = [_sent(stream) for stream in inputs] + + def run() -> None: + kernel = StreamingRejoin(Rejoin(), inputs) + _run(kernel, _arrivals(tables, random.Random(seed))) + + return _warnings_of(run) + + +def test_two_inputs_that_differ_in_shared_columns_warn_as_the_sync_path() -> None: + # Rows of one origin row whose shared tag ``k`` differs: a non-match, and one + # warning for the run naming the column, as on the sync path. + left = _hand_branch("a", origin=["r1", "r2", "r3"], tag=[1, 2, 3]) + for right in ( + _hand_branch("b", origin=["r1", "r2", "r3"], tag=[1, 9, 3]), + _hand_branch("b", origin=["r1", "r2", "r3"], tag=[1, 2, 3]), + _hand_branch("b", origin=["r4", "r2", "r3"], tag=[1, None, 3]), + ): + for inputs in ((left, right), (right, left)): + want = _sync_warnings(inputs) + for seed in range(6): + assert _kernel_warnings(inputs, seed) == want + _check(_kernel, Rejoin().static_process, inputs, range(4)) + + +OTHER_CONTEXT = "std:v1:test-other" + + +@pytest.fixture +def other_context(monkeypatch: pytest.MonkeyPatch) -> contexts.DataContext: + """A copy of the default data context under another key (as ``test_rejoin``).""" + other = dataclasses.replace( + contexts.get_default_context(), context_key=OTHER_CONTEXT + ) + registry = contexts._get_registry() # pyright: ignore[reportPrivateUsage] # the test registers a second context + original = registry.get_context + + def get_context(key: Any = None) -> contexts.DataContext: # pyright: ignore[reportExplicitAny] # the registry's own argument + return other if key == OTHER_CONTEXT else original(key) + + monkeypatch.setattr(registry, "get_context", get_context) + return other + + +def _in_context(context: contexts.DataContext, data: str) -> ArrowTableStream: + """A raw stream of the given data context: tag ``g``, one system tag, ``data``.""" + return ArrowTableStream( + pa.table( + { + "g": pa.array([1, 2, 3], pa.int64()), + data: pa.array([0.5, 0.25, 0.125], pa.float64()), + "origin": pa.array(["r1", "r2", "r3"], pa.large_string()), + constants.CONTEXT_KEY: pa.array( + [context.context_key] * 3, pa.large_string() + ), + } + ), + tag_columns=["g"], + system_tag_columns=["origin"], + data_context=context, + ) + + +def test_inputs_of_two_data_contexts_match_nothing_and_warn_as_the_sync_path( + other_context: contexts.DataContext, +) -> None: + default = contexts.get_default_context() + for inputs in ( + (_in_context(default, "a"), _in_context(other_context, "b")), + (_in_context(other_context, "b"), _in_context(default, "a")), + ): + want = _sync_warnings(inputs) + assert want + for seed in range(4): + assert _kernel_warnings(inputs, seed) == want + _check(_kernel, Rejoin().static_process, inputs, range(4)) + + +# --------------------------------------------------------------------------- +# Refusals before the first batch (e1, ITL-856) +# --------------------------------------------------------------------------- + + +def test_refusals_are_the_sync_paths_before_the_first_batch() -> None: + origin = _origin() + joined = origin.select_data_columns(["rate"]).join( + ArrowTableSource( + pa.table({"subject": pa.array(["s0"], pa.large_string()), "x": [1]}), + tag_columns=["subject"], + tag_only_columns=True, + source_id="x", + ) + ) + left = _hand_branch("a", origin=["r1"], tag=[1]) + retyped = ArrowTableStream( + pa.table( + { + "k": pa.array([1], pa.int32()), + "b": pa.array([0.0]), + "origin": pa.array(["r1"], pa.large_string()), + } + ), + tag_columns=["k"], + system_tag_columns=["origin"], + ) + for inputs in ( + (origin.select_data_columns(["depth"]), joined), + (left, retyped), + (left, _hand_branch("a", origin=["r1"], tag=[1])), + ): + with pytest.raises(InputValidationError) as sync_error: + Rejoin().static_process(*map(_row_built, inputs)) + with pytest.raises(InputValidationError) as kernel_error: + StreamingRejoin(Rejoin(), inputs) + assert str(kernel_error.value) == str(sync_error.value) + + +def test_every_batch_names_the_output_columns_in_order() -> None: + branches = _branches(_origin(data_tags=True)) + kernel = StreamingRejoin(Rejoin(), branches) + batches = _run( + kernel, _arrivals([_sent(stream) for stream in branches], random.Random(1)) + ) + assert batches + expected = _transport(Rejoin().static_process(*map(_row_built, branches))) + assert_same_rows(batches, kernel, expected) + + +def test_three_inputs_miss_a_difference_the_middle_input_lacks() -> None: + # A documented difference from the sync path (StreamingRejoin's docstring): with + # three inputs the warning is detected per link, so a difference between the first + # and the last input (canonical order) for an origin row the middle input lacks is + # warned about by the sync path only. The rows are identical. The alternative, + # pairwise detection with every input's keys kept to the end, was not chosen + # (option B, November 22, 2026). + names = ["a", "b", "c"] + order = sorted( + names, + key=lambda n: ( + _hand_branch(n, origin=["r1", "r2"], tag=[1, 2]).pipeline_hash().to_hex() + ), + ) + first, middle, last = order + inputs = [ + _hand_branch(first, origin=["r1", "r2"], tag=[1, 2]), + _hand_branch(middle, origin=["r1"], tag=[1]), + _hand_branch(last, origin=["r1", "r2"], tag=[1, 9]), + ] + assert [ + inputs[i] + for i in sorted(range(3), key=lambda i: inputs[i].pipeline_hash().to_hex()) + ] == inputs + assert len(_sync_warnings(inputs)) == 1 + for seed in range(4): + assert _kernel_warnings(inputs, seed) == [] + _check(_kernel, Rejoin().static_process, inputs, range(4)) + + +def test_a_match_that_takes_a_closed_inputs_last_row_releases_the_chain() -> None: + # Canonical order first, middle, last: the last input sends its only row (x) and + # closes; the first sends x and y; the middle sends x, which matches through to + # the last input's x. The last step then holds nothing on a closed side and can + # never emit again, so the first step's y, and any row the first input sends + # after, are not held. + names = sorted( + "abc", + key=lambda n: _hand_branch(n, origin=["x"], tag=[1]).pipeline_hash().to_hex(), + ) + first = _hand_branch(names[0], origin=["x", "y"], tag=[1, 2]) + middle = _hand_branch(names[1], origin=["x"], tag=[1]) + last = _hand_branch(names[2], origin=["x"], tag=[1]) + inputs = [first, middle, last] + assert sorted(inputs, key=lambda s: s.pipeline_hash().to_hex()) == inputs + kernel = StreamingRejoin(Rejoin(), inputs) + assert kernel.push(2, _sent(last).combine_chunks().to_batches()[0]) == [] + assert kernel.close(2) == [] + assert kernel.push(0, _sent(first).combine_chunks().to_batches()[0]) == [] + emitted = kernel.push(1, _sent(middle).combine_chunks().to_batches()[0]) + assert sum(batch.num_rows for batch in emitted) == 1 + assert kernel.held_rows == 0 + more = _hand_branch(names[0], origin=["z"], tag=[3]) + assert kernel.push(0, _sent(more).combine_chunks().to_batches()[0]) == [] + assert kernel.held_rows == 0 + + +# --------------------------------------------------------------------------- +# Documented differences from the sync path (StreamingRejoin's docstring) +# --------------------------------------------------------------------------- + + +def _in_canonical_order(make: Any, candidates: Sequence[tuple[str, ...]]) -> list[Any]: + """The first ``make(names)`` whose streams are already in canonical order.""" + for names in candidates: + inputs = make(names) + if sorted(inputs, key=lambda s: s.pipeline_hash().to_hex()) == inputs: + return inputs + raise AssertionError("no arrangement in canonical order") + + +def _pushed( + inputs: Sequence[StreamProtocol], schedule: Sequence[tuple[int, int, int]] +) -> tuple[pa.Table, list[str]]: + """The kernel's rows and warnings for ``schedule``: (input, first row, row count), + each input's rows in its own order, then every input closed.""" + rows = [_sent(stream).combine_chunks() for stream in inputs] + out: list[pa.RecordBatch] = [] + + def run() -> None: + kernel = StreamingRejoin(Rejoin(), inputs) + for index, start, count in schedule: + out.extend( + kernel.push(index, rows[index].slice(start, count).to_batches()[0]) + ) + for index in range(len(inputs)): + out.extend(kernel.close(index)) + + caught = _warnings_of(run) + return pa.Table.from_batches(out), caught + + +def test_repeats_with_three_inputs_can_pair_by_arrival() -> None: + # The spec's named risk ("Duplicates ... 'match once' pairs duplicates in arrival + # order, which can differ between sync and async (risks; ITL-1356 removes the + # case)"). One origin row repeated: the first two inputs pair their repeats on + # tag k (orders [1, 2] and [2, 1]); the third, without k, pairs by occurrence + # with the rows rejoined so far. The sync path ranks those in its table order, + # among the rows that survived the first step; the kernel ranks them as they + # arrive. Two schedules that keep each input's row order: one gives the sync + # rows, one does not. The exact alternative is option X: survival-aware ranking + # with per-step counters, rows of a repeated origin held until every earlier row + # of that origin has a final fate at the step before. + def keyed(data: str, k: list[int]) -> ArrowTableStream: + return _repeated(len(k), data, k) + + def plain(data: str) -> ArrowTableStream: + return ArrowTableStream( + pa.table( + { + data: pa.array([10, 20], pa.int64()), + "origin": pa.array(["x", "x"], pa.large_string()), + } + ), + tag_columns=[], + system_tag_columns=["origin"], + ) + + inputs = _in_canonical_order( + lambda n: [keyed(n[0], [1, 2]), keyed(n[1], [2, 1]), plain(n[2])], + list(itertools.permutations("abcdefgh", 3)), + ) + want = _rows(_transport(Rejoin().static_process(*map(_row_built, inputs)))) + whole, _ = _pushed(inputs, [(0, 0, 2), (1, 0, 2), (2, 0, 2)]) + one_by_one, _ = _pushed(inputs, [(0, 0, 2), (1, 0, 1), (1, 1, 1), (2, 0, 2)]) + assert _rows(whole) == want + assert _rows(one_by_one) != want + assert whole.num_rows == one_by_one.num_rows == 2 + + +def test_the_warning_for_repeats_of_two_inputs_can_depend_on_arrival() -> None: + # Best effort with repeated origins: the sync path compares repeats by occurrence + # whatever their matches, the kernel only rows that matched nothing. One origin, + # k = [1, 2] against [2, 1]: the rows are the sync rows in both schedules; the + # warning is the sync path's when the rows alternate, and missed when the first + # input's rows are all held first. The alternative is option B: pairwise + # detection with every input's keys kept to the end. + inputs = [ + _hand_branch("a", origin=["o", "o"], tag=[1, 2]), + _hand_branch("b", origin=["o", "o"], tag=[2, 1]), + ] + want_rows = _rows(_transport(Rejoin().static_process(*map(_row_built, inputs)))) + assert len(_sync_warnings(inputs)) == 1 + buffered, buffered_warnings = _pushed(inputs, [(0, 0, 2), (1, 0, 1), (1, 1, 1)]) + alternating, alternating_warnings = _pushed( + inputs, [(0, 0, 1), (1, 0, 1), (0, 1, 1), (1, 1, 1)] + ) + assert _rows(buffered) == _rows(alternating) == want_rows + assert buffered_warnings == [] + assert alternating_warnings == _sync_warnings(inputs) + + +def test_the_warning_misses_adjacent_inputs_when_an_earlier_input_lacks_the_row() -> ( + None +): + # Best effort with three inputs: the first input (canonical order) has only origin + # y; the next two have origin x with different k. They are adjacent, but their x + # rows are never compared: the step that would compare them sees the rows + # rejoined so far, which lack x. The sync path warns; the rows are identical. The + # alternative is option B: pairwise detection with every input's keys kept. + inputs = _in_canonical_order( + lambda n: [ + _hand_branch(n[0], origin=["y"], tag=[1]), + _hand_branch(n[1], origin=["x"], tag=[1]), + _hand_branch(n[2], origin=["x"], tag=[2]), + ], + list(itertools.permutations("abcdef", 3)), + ) + assert len(_sync_warnings(inputs)) == 1 + for seed in range(4): + assert _kernel_warnings(inputs, seed) == [] + _check(_kernel, Rejoin().static_process, inputs, range(4)) + + +def test_two_inputs_with_unique_origins_warn_as_the_sync_path_for_every_schedule() -> ( + None +): + # The guarantee: two inputs, unique origins, every arrival schedule. + left = _hand_branch("a", origin=["r1", "r2", "r3", "r4"], tag=[1, 2, 3, None]) + right = _hand_branch("b", origin=["r4", "r3", "r2", "r5"], tag=[None, 7, 2, 1]) + for inputs in ((left, right), (right, left)): + want = _sync_warnings(inputs) + assert len(want) == 1 + for seed in range(24): + assert _kernel_warnings(inputs, seed) == want + + +# --------------------------------------------------------------------------- +# Cost: one join per batch, no whole-table copy +# --------------------------------------------------------------------------- + + +_POOLS: list[Any] = [] + + +def test_each_batch_costs_one_join_and_copies_no_held_table( + monkeypatch: pytest.MonkeyPatch, +) -> None: + # N repeats held in N one-row chunks, then their N partners one row at a time: + # each partner batch runs one Polars join against the held rows (O(held) per + # batch, as in the Join kernels) and takes its values from the held chunks by row + # number; no held table is copied, so a batch allocates far less Arrow memory + # than the held rows occupy. + n = 400 + left, right = _repeated(n, "a"), _repeated(n, "b") + kernel = StreamingRejoin(Rejoin(), (left, right)) + for batch in _sent(left).combine_chunks().to_batches(max_chunksize=1): + kernel.push(0, batch) + held_bytes = _sent(left).nbytes + joins = 0 + original = pl.DataFrame.join + + def counted(self: pl.DataFrame, *args: Any, **kwargs: Any) -> pl.DataFrame: + nonlocal joins + joins += 1 + return original(self, *args, **kwargs) + + monkeypatch.setattr(pl.DataFrame, "join", counted) + previous = pa.default_memory_pool() + large: list[int] = [] + for index, batch in enumerate( + _sent(right).combine_chunks().to_batches(max_chunksize=1) + ): + before_joins = joins + # A pool of its own per batch: its peak counts every Arrow allocation of the + # batch, also one freed before the batch returns. Pools are kept for the + # process: arrays allocated in one may outlive the test. + pool = pa.proxy_memory_pool(previous) + _POOLS.append(pool) + pa.set_memory_pool(pool) + try: + emitted = kernel.push(1, batch) + finally: + pa.set_memory_pool(previous) + assert sum(b.num_rows for b in emitted) == 1 + assert joins - before_joins == 1 + if (pool.max_memory() or 0) >= held_bytes / 4: + large.append(index) + # Only the compactions copy the remaining rows: when half the rows held were + # removed since the last one, so at most log2(n) times in the run. + assert len(large) <= math.ceil(math.log2(n)), large + assert kernel.held_rows == 0 + + +def test_a_partly_matching_batch_costs_two_joins( + monkeypatch: pytest.MonkeyPatch, +) -> None: + # Held: origins x and z with k = [1, 1]. Arriving in one batch: x and z with + # k = [2, 1]. z matches (the match join); x matched nothing but shares its + # origin with a held row, so one more join on the system tags finds the pair and + # a vectorized comparison names k. Two joins, and the warning is the sync path's. + left = _hand_branch("a", origin=["x", "z"], tag=[1, 1]) + right = _hand_branch("b", origin=["x", "z"], tag=[2, 1]) + joins = 0 + original = pl.DataFrame.join + + def counted(self: pl.DataFrame, *args: Any, **kwargs: Any) -> pl.DataFrame: + nonlocal joins + joins += 1 + return original(self, *args, **kwargs) + + kernel = StreamingRejoin(Rejoin(), (left, right)) + kernel.push(0, _sent(left).combine_chunks().to_batches()[0]) + monkeypatch.setattr(pl.DataFrame, "join", counted) + caught: list[pa.RecordBatch] = [] + + def run() -> None: + caught.extend(kernel.push(1, _sent(right).combine_chunks().to_batches()[0])) + caught.extend(kernel.close(0) + kernel.close(1)) + + found = _warnings_of(run) + monkeypatch.undo() + assert joins == 2 + assert sum(batch.num_rows for batch in caught) == 1 + assert found == _sync_warnings((left, right)) + assert len(found) == 1 + + +def test_four_inputs_keep_buffered_matches_when_earlier_steps_release() -> None: + # Canonical inputs I0..I3. x and y match through the first two steps and wait at + # the last step for I3. Then I1 closes: the steps before the last can never emit + # again and are released, but the last step keeps its two buffered rows, which + # I3 then matches. A late row of I0 (z) goes to a released step and is not held. + # Every call order of the four inputs gives the sync rows. + names = sorted( + "abcd", + key=lambda n: _hand_branch(n, origin=["x"], tag=[1]).pipeline_hash().to_hex(), + ) + canonical = [ + _hand_branch(names[0], origin=["x", "y", "z"], tag=[1, 2, 3]), + *(_hand_branch(n, origin=["x", "y"], tag=[1, 2]) for n in names[1:]), + ] + assert sorted(canonical, key=lambda s: s.pipeline_hash().to_hex()) == canonical + expected = _transport(Rejoin().static_process(*map(_row_built, canonical))) + assert expected.num_rows == 2 + sent = [_sent(stream).combine_chunks() for stream in canonical] + for call_order in itertools.permutations(range(4)): + inputs = [canonical[i] for i in call_order] + at = {position: call_order.index(position) for position in range(4)} + kernel = StreamingRejoin(Rejoin(), inputs) + out: list[pa.RecordBatch] = [] + out += kernel.push(at[0], sent[0].slice(0, 2).to_batches()[0]) + out += kernel.push(at[1], sent[1].to_batches()[0]) + out += kernel.push(at[2], sent[2].to_batches()[0]) + assert kernel.held_rows == 2 + out += kernel.close(at[1]) + assert kernel.held_rows == 2 + out += kernel.push(at[0], sent[0].slice(2, 1).to_batches()[0]) + assert kernel.held_rows == 2 + out += kernel.push(at[3], sent[3].to_batches()[0]) + assert kernel.held_rows == 0 + for position in (0, 2, 3): + out += kernel.close(at[position]) + assert_same_rows(out, kernel, expected) + + +def test_extension_and_nested_payloads_cross_held_chunks_and_compaction() -> None: + # A logical (extension) payload and a nested payload, held in one-row chunks and + # matched in another order, across the compactions: every value is taken from + # its chunk, bit for bit, and the rows are the sync rows. + n = 40 + path_type = contexts.get_default_context().type_converter.python_type_to_arrow_type( + Path + ) + assert isinstance(path_type, pa.BaseExtensionType) + nested_type = pa.large_list( + pa.struct([("a", pa.int64()), ("b", pa.large_list(pa.int64()))]) + ) + origin = ArrowTableSource( + pa.table( + { + "unit": pa.array(range(n), pa.int64()), + "path": pa.ExtensionArray.from_storage( + path_type, + pa.array( + [f"/data/f{i}.bin" for i in range(n)], path_type.storage_type + ), + ), + "nested": pa.array( + [[{"a": i, "b": [i, i + 1]}] for i in range(n)], nested_type + ), + "other": pa.array([float(i) for i in range(n)], pa.float64()), + } + ), + tag_columns=["unit"], + tag_only_columns=True, + source_id="payloads", + ) + held = origin.select_data_columns(["path", "nested"]) + arriving = origin.select_data_columns(["other"]) + expected = _transport( + Rejoin().static_process(_row_built(held), _row_built(arriving)) + ) + assert expected.num_rows == n + for inputs, first in (((held, arriving), 0), ((arriving, held), 1)): + kernel = StreamingRejoin(Rejoin(), inputs) + out: list[pa.RecordBatch] = [] + for batch in _sent(held).combine_chunks().to_batches(max_chunksize=1): + out += kernel.push(first, batch) + rows = _sent(arriving).combine_chunks() + for start in reversed(range(0, n, 3)): + out += kernel.push(1 - first, rows.slice(start, 3).to_batches()[0]) + out += kernel.close(0) + kernel.close(1) + assert kernel.held_rows == 0 + assert_same_rows(out, kernel, expected) + got = pa.Table.from_batches(out) + assert got.schema.field("path").type == path_type From 324c40e51f591207fbf789de57589c4cdfebbb31 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 07:51:21 -0800 Subject: [PATCH 44/86] refactor(channels): open_channel() on every stream; the input channel imports no concrete stream (ITL-1362, part 2 section 0) (#488) * refactor(channels): InputChannel in core/streams/record_batch_input; StreamBase and SourceNodeBase open_channel(); StreamProtocol declares it (ITL-1362) L1 of the approved part 2 layout: the concrete input channel imports no concrete stream, node or operator, and reads through a feed (next, close, to_stream). A stream opens a channel itself (CompleteStreamFeed, in streams/base.py beside F's per-slice step); to_stream() of such a channel is the stream. The output channel's reader feed gives stream_from_batches of what it delivered. channel_from_stream is gone: stream.open_channel(). Co-Authored-By: Claude Opus 5.5 * refactor(channels): the record-batch protocols beside StreamProtocol in protocols/core_protocols/streams.py (ITL-1362) StreamProtocol.open_channel returns RecordBatchInput and RecordBatchInput.stream is a StreamProtocol: one module, no import cycle. The separate module is gone; core_protocols exports both protocols. Co-Authored-By: Claude Opus 5.5 * docs: name the protocol module correctly in the record-batch channel rule (ITL-1362) Co-Authored-By: Claude Opus 5.5 * docs: the record-batch channel rule names each channel's module (ITL-1362) Co-Authored-By: Claude Opus 5.5 * fix(channels): channel_to_stream is the one conversion from an input channel to a stream; a channel is read once, a fixed snapshot (ITL-1362) Codex review of #488. The rule 'to_stream() of a channel on a complete stream is the stream itself' is withdrawn in its general form: - channel_to_stream(channel), beside stream_from_batches, reads the channel to its end (every read error raised before an operator runs) and rebuilds a fixed snapshot through stream_from_batches; only an unread channel whose stream _output_stream built (ROW_BUILT_OUTPUT, set there only) gives that stream - to_stream() is removed from RecordBatchInput, InputChannel and the feeds (a builder sits above core/streams/base.py, so a stream's feed cannot reach one without an import cycle); RecordBatchInput.unread is added - a channel is single pass: after its end it never reads its stream again - a source node's batches follow its bound source's keys (its rows' order) - the feed drops a batch once delivered Co-Authored-By: Claude Opus 5.5 * fix(channels): Codex round 2 on #488: the shortcut belongs to the feed, a source node's channel is its execute() output, one consumer per reader, only the feed's end is the end (ITL-1362) - RecordBatchInput.opened_on: only a channel opened on a complete stream may give that stream (when _output_stream built it); a reader of an output channel always collects, whatever its description - a source node's channel carries exactly its execute() output, built at the first read from one binding (_materialize_upstream of its rows; TODO(ITL-1360)) - RecordBatchInput.reserve(): the first read or conversion takes the reader at call time; a second consumer is refused, naming it; a closed reader converts to ChannelClosed - only the feed returning None ends a channel: a ChannelClosed raised by the feed's own read is a read error - the complete-stream feed reads the table before the keys (one fetch) Co-Authored-By: Claude Opus 5.5 * fix(channels): a reader belongs to one consumer for its whole life; channel_to_stream reserves at call time (ITL-1362) Codex round 3 on #488: the first read binds a reader to the calling asyncio task, and a read from another task is refused, between batches as well as while one is pending; after the end a reader answers ChannelClosed to anyone (nothing to take); close() stays callable from anywhere. reserve() holds an unread reader for a claim, and no read is taken until a task takes it over with the claim: channel_to_stream is a plain function that reserves synchronously and returns the conversion, which adopts the claim in the task that runs it. Tests whose readers had two consuming tasks now give each reader one. Co-Authored-By: Claude Opus 5.5 * fix(channels): CodeRabbit on #488: cleanup on failure leaves nothing behind, a claim is taken over once, the consumer task is released, the delivered column order is kept (ITL-1362) - a barrier's input conversions are started inside the protected block, and on any failure every started conversion is cancelled and awaited - a reader releases its consumer task at its end and on close; a redeemed claim is cleared; a feed raising StopAsyncIteration is a read error (only None ends) - stream_from_batches keeps the delivered column order, with the roles from the description (a source node whose plain tags the slot orders otherwise, ITL-1365) - reserve()/unread document the claim-held state - tests read with asyncio.timeout, not wait_for (Python 3.11 runs wait_for's argument in another task); helper docstrings; the batch-release check runs before the channel is drained Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Edgar Y. Walker Co-authored-by: Claude Opus 5.5 --- .zed/rules | 35 +- CLAUDE.md | 35 +- src/orcapod/core/nodes/source_node.py | 70 ++ src/orcapod/core/operators/batch.py | 2 +- .../core/operators/static_output_pod.py | 131 ++- src/orcapod/core/record_batch_channels.py | 233 +---- src/orcapod/core/streams/base.py | 66 ++ .../core/streams/record_batch_input.py | 287 ++++++ .../protocols/core_protocols/__init__.py | 9 +- .../core_protocols/record_batch_channels.py | 86 -- .../protocols/core_protocols/streams.py | 102 +++ .../test_record_batch_channels.py | 818 ++++++++++++++++-- .../operators/test_record_batch_execution.py | 120 ++- 13 files changed, 1562 insertions(+), 432 deletions(-) create mode 100644 src/orcapod/core/streams/record_batch_input.py delete mode 100644 src/orcapod/protocols/core_protocols/record_batch_channels.py diff --git a/.zed/rules b/.zed/rules index 6967e6d81..bbd720618 100644 --- a/.zed/rules +++ b/.zed/rules @@ -1299,21 +1299,26 @@ data. The rules: context from those datagrams (data_context_key). Add new async operators to tests/test_core/operators/test_async_sync_equivalence.py. - Record-batch channels (ITL-1347, ITL-1362; not wired into nodes or orchestrators yet): - orcapod.core.record_batch_channels.InputChannel / OutputChannel carry a stream's rows as - Arrow record batches; operators see them only through the protocols RecordBatchInput / - RecordBatchOutput of protocols/core_protocols/record_batch_channels.py, which imports no - concrete core module (keep modules interacting through protocols: basedpyright counts local - and TYPE_CHECKING imports as import cycles). A channel owns no description: an input channel - refers to its stream (channel_from_stream(stream)), an output channel to the stream it - produces, and OutputChannel.result() closes it into that stream. The conversions are in one - place, core/operators/static_output_pod.py (stream_from_batches, transport_schema, and F, - _row_built_form); never build a stream from record batches elsewhere. An operator's - record-batch form (async_execute_batches, renamed async_execute when wired) applies its one - static_process body: per record batch when the class declares ROW_BY_ROW = True (each output - row comes from one input row), otherwise as a barrier over the whole input (to_stream()); - Batch with a size has its own form, grouping rows by arrival. A new operator whose output - rows each come from one input row declares ROW_BY_ROW; write no other per-operator batch - code. + InputChannel (core/streams/record_batch_input.py) and OutputChannel + (core/record_batch_channels.py) carry a stream's rows as Arrow record batches; operators see + them only through the protocols RecordBatchInput / RecordBatchOutput of + protocols/core_protocols/streams.py (beside StreamProtocol), which imports no concrete core + module (keep modules interacting through protocols: basedpyright counts local and + TYPE_CHECKING imports as import cycles). A channel owns no description: an input channel + refers to its stream (stream.open_channel()), an output channel to the stream it produces, + and OutputChannel.result() closes it into that stream. The conversions are in one place, + core/operators/static_output_pod.py (stream_from_batches, transport_schema, and F, + _row_built_form); never build a stream from record batches elsewhere. + channel_to_stream(channel) is the one conversion from an input channel to a stream: it reads + the channel to its end (one pass, every read error raised before an operator runs) and + rebuilds a fixed snapshot through stream_from_batches; only an unread channel whose stream + _output_stream built (ROW_BUILT_OUTPUT, set there only) gives that stream as it is. An + operator's record-batch form (async_execute_batches, renamed async_execute when wired) + applies its one static_process body: per record batch when the class declares ROW_BY_ROW = + True (each output row comes from one input row), otherwise as a barrier over the whole input + (channel_to_stream); Batch with a size has its own form, grouping rows by arrival. A new + operator whose output rows each come from one input row declares ROW_BY_ROW; write no other + per-operator batch code. - The type converter keys synthesized struct classes by the large-normalized struct, so struct and struct are one Python type (a workaround, TODO(ITL-841)). diff --git a/CLAUDE.md b/CLAUDE.md index 7b781c65c..0c6d59591 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1346,21 +1346,26 @@ data. The rules: context from those datagrams (`data_context_key`). Add new async operators to `tests/test_core/operators/test_async_sync_equivalence.py`. - Record-batch channels (ITL-1347, ITL-1362; not wired into nodes or orchestrators yet): - `orcapod.core.record_batch_channels.InputChannel` / `OutputChannel` carry a stream's rows as - Arrow record batches; operators see them only through the protocols `RecordBatchInput` / - `RecordBatchOutput` of `protocols/core_protocols/record_batch_channels.py`, which imports no - concrete core module (keep modules interacting through protocols: basedpyright counts local - and `TYPE_CHECKING` imports as import cycles). A channel owns no description: an input - channel refers to its stream (`channel_from_stream(stream)`), an output channel to the - stream it produces, and `OutputChannel.result()` closes it into that stream. The conversions - are in one place, `core/operators/static_output_pod.py` (`stream_from_batches`, - `transport_schema`, and F, `_row_built_form`); never build a stream from record batches - elsewhere. An operator's record-batch form (`async_execute_batches`, renamed `async_execute` - when wired) applies its one `static_process` body: per record batch when the class declares - `ROW_BY_ROW = True` (each output row comes from one input row), otherwise as a barrier over - the whole input (`to_stream()`); `Batch` with a size has its own form, grouping rows by - arrival. A new operator whose output rows each come from one input row declares - `ROW_BY_ROW`; write no other per-operator batch code. + `InputChannel` (`core/streams/record_batch_input.py`) and `OutputChannel` + (`core/record_batch_channels.py`) carry a stream's rows as Arrow record batches; operators + see them only through the protocols `RecordBatchInput` / `RecordBatchOutput` of + `protocols/core_protocols/streams.py` (beside `StreamProtocol`), which imports no concrete + core module (keep modules interacting through protocols: basedpyright counts local and + `TYPE_CHECKING` imports as import cycles). A channel owns no description: an input channel + refers to its stream (`stream.open_channel()`), an output channel to the stream it produces, + and `OutputChannel.result()` closes it into that stream. The conversions are in one place, + `core/operators/static_output_pod.py` (`stream_from_batches`, `transport_schema`, and F, + `_row_built_form`); never build a stream from record batches elsewhere. + `channel_to_stream(channel)` is the one conversion from an input channel to a stream: it + reads the channel to its end (one pass, every read error raised before an operator runs) and + rebuilds a fixed snapshot through `stream_from_batches`; only an unread channel whose stream + `_output_stream` built (`ROW_BUILT_OUTPUT`, set there only) gives that stream as it is. An + operator's record-batch form (`async_execute_batches`, renamed `async_execute` when wired) + applies its one `static_process` body: per record batch when the class declares `ROW_BY_ROW + = True` (each output row comes from one input row), otherwise as a barrier over the whole + input (`channel_to_stream`); `Batch` with a size has its own form, grouping rows by arrival. + A new operator whose output rows each come from one input row declares `ROW_BY_ROW`; write + no other per-operator batch code. - The type converter keys synthesized struct classes by the large-normalized struct, so `struct` and `struct` are one Python type (a workaround, `TODO(ITL-841)`). diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index b522c117f..9bb629109 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -7,6 +7,8 @@ from __future__ import annotations +from collections import deque + import contextlib import dataclasses import functools @@ -27,10 +29,12 @@ from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.core.streams.base import ( ZERO_ROW_INPUT_COLUMNS, + row_built_columns, schema_requires_io, typed_arrow_schemas, typed_zero_row_table, ) +from orcapod.core.streams.record_batch_input import SOURCE_BATCH_ROWS, InputChannel from orcapod.core.streams.view import ( ViewStatus, StreamView, @@ -57,6 +61,9 @@ if TYPE_CHECKING: from orcapod.channels import WritableChannel from orcapod.protocols.core_protocols import StreamProtocol + from orcapod.protocols.core_protocols.streams import ( + RecordBatchInput, + ) from orcapod.protocols.observability_protocols import ExecutionObserverProtocol logger = logging.getLogger(__name__) @@ -412,6 +419,55 @@ def _require_stream_arrow_types(stream: Any, slot: str) -> None: raise _no_arrow_type_error(slot, missing) +class _ExecuteOutputFeed: + """The record batches of a source node's own ``execute()`` output. + + Built at the first read from the rows ``execute()`` gives, rebuilt as a job does + (``StaticOutputOperatorPod._materialize_upstream``): slow, and correct by + definition. One binding is read, at that moment. A batch is dropped once + delivered. + """ + + # TODO(ITL-1360): the channel of stage 2's ``execute()`` output stream. + + def __init__(self, node: SourceNodeBase) -> None: + """Make the feed; nothing is read until the first ``next``. + + Args: + node: The source node whose output it delivers. + """ + self._node = node + self._batches: deque[pa.RecordBatch] | None = None + + async def next(self) -> pa.RecordBatch | None: + """Return the next record batch of the node's output, or ``None`` at the end.""" + if self._batches is None: + from orcapod.core.operators.static_output_pod import ( + StaticOutputOperatorPod, + ) + + rows = self._node.execute() + output = StaticOutputOperatorPod._materialize_upstream(rows, self._node) # pyright: ignore[reportPrivateUsage] # the job's rebuild of a node's rows + table = row_built_columns( + output.as_table(columns=ZERO_ROW_INPUT_COLUMNS), output.keys() + ) + self._batches = deque( + batch + for batch in table.to_batches(max_chunksize=SOURCE_BATCH_ROWS) + if batch.num_rows + ) + return self._batches.popleft() if self._batches else None + + def close(self) -> None: + """Stop reading: the batches not read are dropped.""" + self._batches = deque() + + @property + def opened_on(self) -> StreamProtocol | None: + """``None``: the node is not the stream its batches rebuild.""" + return None + + class SourceNodeBase(TraceableBase, ABC): """Abstract base for SourceNode and SourceJobNode. @@ -1163,6 +1219,20 @@ def run(self) -> StreamView: display_all_rows=False, ) + def open_channel(self) -> RecordBatchInput: + """Open an input channel on this node's rows, for async computation (ITL-1347). + + The channel carries exactly this node's own ``execute()`` output: its rows, + as the table a job builds from them, in Arrow record batches. Everything + (the binding, the declared form, the column order, the source info) is read + at the first read, from one binding; opening reads nothing. The description + is this node. An unbound node's first read raises what reading it raises. + + Returns: + The input channel. + """ + return InputChannel(self, _ExecuteOutputFeed(self)) + async def async_iter_data(self): """Asynchronous iterator over (tag, data) pairs. diff --git a/src/orcapod/core/operators/batch.py b/src/orcapod/core/operators/batch.py index 78af8e8d1..e17e28fd4 100644 --- a/src/orcapod/core/operators/batch.py +++ b/src/orcapod/core/operators/batch.py @@ -7,7 +7,7 @@ import pyarrow as pa from orcapod.core.operators.meta_columns import WithoutMetaWriter -from orcapod.protocols.core_protocols.record_batch_channels import ( +from orcapod.protocols.core_protocols.streams import ( RecordBatchInput, RecordBatchOutput, ) diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index 6cdc6ab7e..e32ae30df 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -3,13 +3,13 @@ import asyncio import logging from abc import abstractmethod -from collections.abc import Collection, Iterator, Sequence +from collections.abc import Collection, Coroutine, Iterator, Sequence from datetime import datetime, timezone from typing import TYPE_CHECKING, Any, ClassVar, cast import pyarrow as pa -from orcapod.protocols.core_protocols.record_batch_channels import ( +from orcapod.protocols.core_protocols.streams import ( RecordBatchInput, RecordBatchOutput, ) @@ -547,14 +547,19 @@ def _output_stream( The output stream, with ``node``'s identity. """ if table.num_rows == 0: - return StaticOutputOperatorPod._materialize_upstream([], node) - tag_keys, data_keys = keys - return StaticOutputOperatorPod._as_upstream_stream( - StaticOutputOperatorPod._row_built_form(table, keys), - tag_keys, - data_tag_names(tag_keys, data_keys), - node, - ) + stream = StaticOutputOperatorPod._materialize_upstream([], node) + else: + tag_keys, data_keys = keys + stream = StaticOutputOperatorPod._as_upstream_stream( + StaticOutputOperatorPod._row_built_form(table, keys), + tag_keys, + data_tag_names(tag_keys, data_keys), + node, + ) + # The one place a stream is marked as a complete, immutable output in the + # row-built form (ITL-1347): ``channel_to_stream`` may give it as it is. + setattr(stream, ROW_BUILT_OUTPUT, True) + return stream @staticmethod def _flag_source_info_nullability(table: pa.Table) -> pa.Table: @@ -900,7 +905,7 @@ async def async_execute_batches( A row-by-row operator (``ROW_BY_ROW``) is applied to each record batch as it arrives and sends that batch's result at once. Every other operator reads - all of its inputs first (``InputChannel.to_stream``) and then runs exactly + all of its inputs first (``channel_to_stream``) and then runs exactly the sync call, so an input with no rows gives the typed zero-row result of the sync path, with no row to send. @@ -1012,12 +1017,17 @@ async def _streams_of(inputs: Sequence[RecordBatchInput]) -> list[StreamProtocol UpstreamFailedError: If an input's producer failed; the other inputs are no longer read. """ - tasks = [asyncio.ensure_future(channel.to_stream()) for channel in inputs] + tasks: list[asyncio.Future[StreamProtocol]] = [] try: + for channel in inputs: + tasks.append(asyncio.ensure_future(channel_to_stream(channel))) return list(await asyncio.gather(*tasks)) except BaseException: + # Every conversion already started is cancelled and awaited: none is left + # running, or raising with nobody to hear it. for task in tasks: _ = task.cancel() + _ = await asyncio.gather(*tasks, return_exceptions=True) raise @@ -1065,6 +1075,67 @@ def transport_schema(stream: StreamProtocol) -> pa.Schema | None: return row_built_provenance(zero_rows.select(names)).schema +ROW_BUILT_OUTPUT = "_orcapod_row_built_output" +"""The attribute that marks a stream ``_output_stream`` built (ITL-1347). + +Set in that one place, never inferred from a class: such a stream is a complete, +immutable output already in the row-built form, so a consumer of its record batches +would rebuild exactly it, and ``channel_to_stream`` may give it without reading. +""" + + +def channel_to_stream( + channel: RecordBatchInput, +) -> Coroutine[Any, Any, StreamProtocol]: + """Return what an input channel delivers, as a stream: the one such conversion. + + It reads the channel to its end (one pass; every error of the read, such as an + unbound source's or a failed producer's, is raised here, before any operator runs) + and builds a fixed snapshot of what was delivered through the one settlement path + (``stream_from_batches``). The only shortcut: a channel opened on a complete + stream that ``_output_stream`` built (``ROW_BUILT_OUTPUT``), not read yet, gives + that stream, which is exactly what its batches would rebuild; the channel is then + closed. A reader of an output channel always collects, whatever its description. + + The channel is reserved when this function is called, before the returned + coroutine is awaited, so nothing can read it in between; the task that runs the + coroutine takes the channel over, and any other task's read is refused. + + Args: + channel: The input channel, not read yet. + + Returns: + The conversion to await: a complete, re-readable stream of the channel's + input. + + Raises: + RuntimeError: If a read of the channel was already called (a batch received, + its end reached, or another consumer still waiting): a stream of part of + an input is never made, and a channel is never read again. + ChannelClosed: If the channel was closed, before or during the read. + UpstreamFailedError: If the producer failed or was cancelled. + """ + claim = channel.reserve() # at call time: nothing can read it before the await + return _channel_to_stream(channel, claim) + + +async def _channel_to_stream( + channel: RecordBatchInput, claim: object +) -> StreamProtocol: + """Read a reserved channel and return its input as a stream (``channel_to_stream``). + + Args: + channel: The channel ``channel_to_stream`` reserved. + claim: Its claim, which the task running this conversion takes over. + """ + channel.reserve(claim) + opened_on = channel.opened_on + if opened_on is not None and getattr(opened_on, ROW_BUILT_OUTPUT, False): + await channel.close() + return opened_on + return stream_from_batches(channel.stream, await channel.collect()) + + def stream_from_batches( stream: StreamProtocol, batches: Sequence[pa.RecordBatch] ) -> StreamProtocol: @@ -1072,7 +1143,7 @@ def stream_from_batches( The one place a stream is made from Arrow record batches: what an output channel gives once closed (``OutputChannel.result``), what an input channel delivered - (``InputChannel.to_stream``), and the record batches a row-by-row operator is + (``channel_to_stream``), and the record batches a row-by-row operator is applied to. The batches are put under one another in the order given, and the table is handed on as a node hands its rows to its successors (``_output_stream``): in the row-built form, each system-tag and source-info field @@ -1091,7 +1162,39 @@ def stream_from_batches( if not batches: return StaticOutputOperatorPod._materialize_upstream([], stream) # pyright: ignore[reportPrivateUsage] # the zero-row input of an operator table = pa.Table.from_batches([with_open_provenance_flags(b) for b in batches]) - return StaticOutputOperatorPod._output_stream(table, stream.keys(), stream) # pyright: ignore[reportPrivateUsage] # F and the identity, stage 2's + return StaticOutputOperatorPod._output_stream( # pyright: ignore[reportPrivateUsage] # F and the identity, stage 2's + table, _keys_in_delivered_order(stream.keys(), table.column_names), stream + ) + + +def _keys_in_delivered_order( + keys: tuple[Sequence[str], Sequence[str]], names: Sequence[str] +) -> tuple[list[str], list[str]]: + """The description's tag and data keys, in the order the delivered rows have them. + + The roles come from the description; the order from the batches, so a stream + made from them keeps the columns as they were delivered. They agree for every + stream whose description follows its rows (an operator's or a function's); + a source node whose plain tags are declared in another order than its columns + describes itself in the slot's order (ITL-1365) while its rows are not. + + Args: + keys: The describing stream's tag keys and data keys. + names: The delivered table's column names. + + Returns: + The tag keys and the data keys, data-tags first in tag order. + """ + tag_keys, data_keys = keys + tags, data = set(tag_keys), set(data_keys) + position = {name: i for i, name in enumerate(names)} + ordered_tags = sorted(tag_keys, key=lambda n: position.get(n, len(names))) + data_tags = [n for n in ordered_tags if n in data] + plain = sorted( + (n for n in data_keys if n not in tags), + key=lambda n: position.get(n, len(names)), + ) + return ordered_tags, data_tags + plain def with_open_provenance_flags(batch: pa.RecordBatch) -> pa.RecordBatch: diff --git a/src/orcapod/core/record_batch_channels.py b/src/orcapod/core/record_batch_channels.py index a6f5e57ab..66527f145 100644 --- a/src/orcapod/core/record_batch_channels.py +++ b/src/orcapod/core/record_batch_channels.py @@ -1,22 +1,21 @@ -"""Channels of Arrow record batches (ITL-1347). +"""The output channel of Arrow record batches (ITL-1347). -``InputChannel`` and ``OutputChannel`` carry a stream's rows as Arrow record batches; they -implement ``RecordBatchInput`` and ``RecordBatchOutput`` -(``orcapod.protocols.core_protocols.record_batch_channels``). The +``OutputChannel`` implements ``RecordBatchOutput`` +(``orcapod.protocols.core_protocols.streams``): the producer side of a +node's async output. Each consumer reads through its own ``InputChannel`` +(``open_reader``, ``orcapod.core.streams.record_batch_input``), which is the fan-out. The stream is primary and owns the description (keys, schemas, data context, pipeline hash); a -channel refers to its stream and restates nothing. An input channel is opened from a -stream (``channel_from_stream``) or from an output channel (``OutputChannel.open_reader``); -an output channel, once closed, gives its rows back as a stream (``OutputChannel.result``). -A stream is made from record batches by one function, ``stream_from_batches`` of -``orcapod.core.operators.static_output_pod``. +channel refers to its stream and restates nothing. Once closed, an output channel gives its +rows back as a stream (``OutputChannel.result``). A stream is made from record batches by +one function, ``stream_from_batches`` of ``orcapod.core.operators.static_output_pod``; a +channel is opened on a complete stream by ``stream.open_channel()``. """ from __future__ import annotations import asyncio from collections import deque -from collections.abc import AsyncIterator -from typing import TYPE_CHECKING, Any, Protocol, cast +from typing import TYPE_CHECKING, Any, cast import pyarrow as pa import pyarrow.compute as pc @@ -26,11 +25,8 @@ stream_from_batches, transport_schema, ) -from orcapod.core.streams.base import ( - ZERO_ROW_INPUT_COLUMNS, - row_built_columns, - row_built_names, -) +from orcapod.core.streams.base import row_built_names +from orcapod.core.streams.record_batch_input import InputChannel from orcapod.errors import UpstreamFailedError from orcapod.system_constants import constants from orcapod.utils import arrow_utils @@ -38,67 +34,10 @@ if TYPE_CHECKING: from orcapod.protocols.core_protocols import StreamProtocol -SOURCE_BATCH_ROWS = 65_536 -"""The most rows of one Arrow record batch a complete stream is read in. - -Developer decision, November 22, 2026 (ITL-1347, question 6): a source sends record -batches of at most 65,536 rows; an operator sends its result's own record batches. -""" - BATCH_BUFFER_SIZE = 8 """How many Arrow record batches an input channel queues before its producer waits.""" -class _BatchFeed(Protocol): - """Where an input channel's record batches come from.""" - - async def next(self) -> pa.RecordBatch | None: - """Return the next record batch, or ``None`` at the end.""" - ... - - def close(self) -> None: - """Stop reading: nothing waits for this reader any more.""" - ... - - -class _StreamFeed: - """The record batches of a complete stream, read at this reader's own position.""" - - def __init__(self, stream: StreamProtocol) -> None: - """Make a feed of ``stream``'s rows; nothing is read until the first ``next``. - - Args: - stream: The complete stream to read. - """ - self._stream = stream - self._batches: deque[pa.RecordBatch] | None = None - - async def next(self) -> pa.RecordBatch | None: - """Return the stream's next record batch, or ``None`` at the end. - - The stream's table is read on the first call, not when the feed is made, in - the row-built form (``row_built_columns``) and cut into batches of at most - ``SOURCE_BATCH_ROWS`` rows; batches with no rows are skipped. - """ - if self._batches is None: - # On the first read, not when the channel is opened: opening computes - # nothing. - table = row_built_columns( - self._stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS), - self._stream.keys(), - ) - self._batches = deque( - batch - for batch in table.to_batches(max_chunksize=SOURCE_BATCH_ROWS) - if batch.num_rows - ) - return self._batches.popleft() if self._batches else None - - def close(self) -> None: - """Stop reading: the batches not read are dropped. No producer waits on it.""" - self._batches = deque() - - class _OutputFeed: """One reader of an output channel, with its own position.""" @@ -142,6 +81,11 @@ async def next(self) -> pa.RecordBatch | None: await output._changed.wait() # pyright: ignore[reportPrivateUsage] return None + @property + def opened_on(self) -> StreamProtocol | None: + """``None``: a reader of an output reads what its producer sends.""" + return None + def close(self) -> None: """Stop reading and unregister from the output. @@ -157,132 +101,6 @@ def close(self) -> None: output._notify() # pyright: ignore[reportPrivateUsage] # the producer stops waiting -class InputChannel: - """A single-pass, back-pressured reader of a stream's Arrow record batches. - - The Arrow-record-batch form of ``ReadableChannel``. The description of what it - delivers is its ``stream``, known before the first batch: the producing node, or - the stream it was opened from. A channel has no identity of its own and is read - once; to read again, go back to a stream (the one it was opened from, or the one - ``to_stream`` gives). - - Made by ``channel_from_stream`` or by ``OutputChannel.open_reader``, never - directly. - """ - - def __init__(self, stream: StreamProtocol, feed: _BatchFeed) -> None: - """Make an input channel; use ``channel_from_stream`` or ``open_reader``. - - Args: - stream: The stream whose rows the channel delivers: its description. - feed: Where the record batches come from. - """ - self._stream = stream - self._feed = feed - self._received = 0 - self._ended = False - # Closed by its consumer before the producer completed. - self._closed = False - - @property - def stream(self) -> StreamProtocol: - """The stream whose rows this channel delivers: the description.""" - return self._stream - - async def receive(self) -> pa.RecordBatch: - """Return the next Arrow record batch. - - A read that is cancelled while it waits closes the channel, as ``close`` does: - a consumer that stops reading never holds its producer. - - Raises: - ChannelClosed: At the end, and after ``close``. After a ``close`` that came - before the producer completed, the error says so, and iteration - (``async for``) raises it instead of ending: no consumer loop takes - part of an input for all of it. - UpstreamFailedError: If the producer failed or was cancelled. - """ - if self._closed: - raise self._closed_early() - if self._ended: - raise ChannelClosed() - try: - batch = await self._feed.next() - except asyncio.CancelledError: - await self.close() - raise - if batch is None: - if self._closed: # woken by its own early close - raise self._closed_early() - self._ended = True - raise ChannelClosed() - self._received += 1 - return batch - - def __aiter__(self) -> AsyncIterator[pa.RecordBatch]: - """Iterate over the remaining record batches, in arrival order.""" - return self - - async def __anext__(self) -> pa.RecordBatch: - """Return the next record batch; end the iteration at the producer's end. - - A channel closed before its producer completed does not end the iteration: - its ``ChannelClosed`` is raised, so a loop never takes part of an input for - all of it. - """ - try: - return await self.receive() - except ChannelClosed: - if self._closed: - raise # closed before its producer completed: not the end - raise StopAsyncIteration - - def _closed_early(self) -> ChannelClosed: - """The error of a read after a close that came before the producer completed.""" - return ChannelClosed( - f"The input channel of {_named(self._stream)} was closed before its " - + "producer completed; it has no complete input to give." - ) - - async def collect(self) -> list[pa.RecordBatch]: - """Read to the end and return every remaining record batch, in arrival order. - - Raises: - ChannelClosed: If the channel was closed before its producer completed: - what was read is part of the input, never returned as all of it. - UpstreamFailedError: If the producer failed or was cancelled. - """ - return [batch async for batch in self] - - async def to_stream(self) -> StreamProtocol: - """Read to the end and return what the channel delivered, as a stream. - - The stream holds the record batches in arrival order, with the identity of - ``stream`` (``stream_from_batches``). It is how an operator that needs all of - an input reads it. Called on a channel not read yet: a stream of part of an - input is never made. - - Raises: - RuntimeError: If a record batch has already been received. - ChannelClosed: If the channel was closed before its producer completed. - UpstreamFailedError: If the producer failed or was cancelled. - """ - if self._received: - raise RuntimeError( - "to_stream() gives everything an input channel delivers, as a stream; " - + f"{self._received} record batch(es) of this one have been received " - + "already." - ) - return stream_from_batches(self._stream, await self.collect()) - - async def close(self) -> None: - """Stop reading. The producer no longer waits for this reader.""" - if not self._ended: - self._closed = True - self._ended = True - self._feed.close() - - class OutputChannel: """The producer side of a node's async output, in Arrow record batches. @@ -531,23 +349,6 @@ def result(self) -> StreamProtocol: return self._result -def channel_from_stream(stream: StreamProtocol) -> InputChannel: - """Open an input channel on a complete stream. - - The channel delivers the stream's rows in the row-built form (``row_built_columns``) as - Arrow record batches of at most ``SOURCE_BATCH_ROWS`` rows. Several channels may be - opened on one stream, each with its own position; nothing is computed until the - first read, and nothing is queued, since the stream is complete. - - Args: - stream: The stream to read; it is the channel's description. - - Returns: - The input channel. - """ - return InputChannel(stream, _StreamFeed(stream)) - - def _named(stream: Any) -> str: # pyright: ignore[reportExplicitAny] # any stream or node """How an error names a stream: its label, or what it prints as.""" label = getattr(stream, "label", None) diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py index f4c28d96a..3d941e5cb 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -2,6 +2,7 @@ import logging from abc import abstractmethod +from collections import deque from collections.abc import ( AsyncIterator, Callable, @@ -21,6 +22,7 @@ import pyarrow as pa from orcapod.core.base import TraceableBase +from orcapod.core.streams.record_batch_input import SOURCE_BATCH_ROWS, InputChannel from orcapod.core.streams.view import ( SCHEMA_NEEDS_POLL_NOTE, ViewStatus, @@ -34,6 +36,7 @@ StreamProtocol, TagProtocol, ) +from orcapod.protocols.core_protocols.streams import RecordBatchInput from orcapod.system_constants import constants from orcapod.types import ColumnConfig, Schema from orcapod.utils import arrow_utils @@ -333,6 +336,54 @@ def row_built_names( return [*tag_keys, *system_tags, *data, *source_info] +class CompleteStreamFeed: + """The record batches of a complete stream, read at one reader's own position. + + The feed of a channel opened on a stream (``StreamBase.open_channel()``). Nothing + is read until the first ``next``; then the stream's table is read once (a fixed + snapshot: a stream that changes later is not read again), in the row-built form + (``row_built_columns``), and cut into record batches of at most + ``SOURCE_BATCH_ROWS`` rows. A batch is dropped by the feed once delivered. The + stream is complete, so nothing is queued and no producer waits on a reader. + """ + + def __init__(self, stream: StreamProtocol) -> None: + """Make a feed of ``stream``'s rows; nothing is read until the first ``next``. + + Args: + stream: The complete stream to read. + """ + self._stream = stream + self._batches: deque[pa.RecordBatch] | None = None + + async def next(self) -> pa.RecordBatch | None: + """Return the stream's next record batch, or ``None`` at the end. + + The stream's table is read on the first call, not when the channel is opened; + batches with no rows are skipped. + """ + if self._batches is None: + # The table first: reading it is the stream's one read (an unpolled + # source polls here), and its keys are then known without another. + table = self._stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS) + table = row_built_columns(table, self._stream.keys()) + self._batches = deque( + batch + for batch in table.to_batches(max_chunksize=SOURCE_BATCH_ROWS) + if batch.num_rows + ) + return self._batches.popleft() if self._batches else None + + def close(self) -> None: + """Stop reading: the batches not read are dropped.""" + self._batches = deque() + + @property + def opened_on(self) -> StreamProtocol | None: + """The complete stream this feed reads.""" + return self._stream + + def typed_arrow_schemas( stream: object, *, own: bool = True ) -> tuple[pa.Schema, pa.Schema]: @@ -1146,6 +1197,21 @@ def iter_data( self, ) -> Iterator[tuple[TagProtocol, DataProtocol]]: ... + def open_channel(self) -> RecordBatchInput: + """Open an input channel on this stream, for async computation (ITL-1347). + + The channel delivers this stream's rows as Arrow record batches of at most + ``SOURCE_BATCH_ROWS`` rows, in the row-built form, read once and in order; its + description is this stream (``channel.stream``). Several channels may be + opened on one stream, each with its own position, and the stream stays as it + is. Nothing is read until the channel is first read; then the stream is read + once, a fixed snapshot. + + Returns: + The input channel. + """ + return InputChannel(self, CompleteStreamFeed(self)) + async def async_iter_data( self, ) -> AsyncIterator[tuple[TagProtocol, DataProtocol]]: diff --git a/src/orcapod/core/streams/record_batch_input.py b/src/orcapod/core/streams/record_batch_input.py new file mode 100644 index 000000000..98d23e33b --- /dev/null +++ b/src/orcapod/core/streams/record_batch_input.py @@ -0,0 +1,287 @@ +"""The input channel of Arrow record batches (ITL-1347). + +``InputChannel`` implements ``RecordBatchInput`` +(``orcapod.protocols.core_protocols.streams``): a single-pass, +back-pressured reader of a stream's Arrow record batches. The stream is primary and owns +the description (keys, schemas, data context, pipeline hash); a channel refers to its +stream and restates nothing. + +A channel reads through a feed (``BatchFeed``), which says where its record batches come +from: a complete stream (``StreamBase.open_channel()``), or an output channel +(``OutputChannel.open_reader()`` in ``orcapod.core.record_batch_channels``). This module +imports no concrete stream, node or operator, so a stream can open a channel without an +import cycle. +""" + +from __future__ import annotations + +import asyncio +from collections.abc import AsyncIterator +from typing import TYPE_CHECKING, Any, Protocol + +from orcapod.channels import ChannelClosed + +if TYPE_CHECKING: + import pyarrow as pa + + from orcapod.protocols.core_protocols.streams import StreamProtocol + +SOURCE_BATCH_ROWS = 65_536 +"""The most rows of one Arrow record batch a complete stream is read in. + +Developer decision, November 22, 2026 (ITL-1347, question 6): a source sends record +batches of at most 65,536 rows; an operator sends its result's own record batches. +""" + + +class BatchFeed(Protocol): + """Where an input channel's record batches come from.""" + + async def next(self) -> pa.RecordBatch | None: + """Return the next record batch, or ``None`` at the end.""" + ... + + def close(self) -> None: + """Stop reading: nothing waits for this reader any more.""" + ... + + @property + def opened_on(self) -> StreamProtocol | None: + """The complete stream the feed reads, or ``None`` (a reader of an output).""" + ... + + +class InputChannel: + """A single-pass, back-pressured reader of a stream's Arrow record batches. + + The Arrow-record-batch form of ``ReadableChannel``. The description of what it + delivers is its ``stream``, known before the first batch: the producing node, or + the stream it was opened from. A channel has no identity of its own and is read + once; to read again, go back to a stream (the one it was opened from, or the one + ``channel_to_stream`` makes of what it delivered). + + Made by ``stream.open_channel()`` or by ``OutputChannel.open_reader()``, never + directly. + """ + + def __init__(self, stream: StreamProtocol, feed: BatchFeed) -> None: + """Make an input channel; use ``open_channel`` or ``open_reader``. + + Args: + stream: The stream whose rows the channel delivers: its description. + feed: Where the record batches come from. + """ + self._stream = stream + self._feed = feed + self._received = 0 + # The producer's end was reached (the feed returned ``None``). + self._ended = False + # Closed by its consumer before the producer completed. + self._closed = False + # A read was called: the channel has a consumer (reserved at call time). + self._started = False + # A read is in progress. + self._reading = False + # The consumer: the asyncio task the channel belongs to, for its whole life, + # and the claim a conversion holds while it moves to the task that runs it. + self._owner: asyncio.Task[Any] | None = None + self._claim: object | None = None + + @property + def stream(self) -> StreamProtocol: + """The stream whose rows this channel delivers: the description.""" + return self._stream + + @property + def unread(self) -> bool: + """Whether no read was called and the channel is not closed. + + A reserved channel (``reserve()``) is not unread, even before its first read. + """ + return not self._started and not self._ended and not self._closed + + @property + def opened_on(self) -> StreamProtocol | None: + """The complete stream this channel reads, when it was opened on one. + + ``None`` for a reader of an output channel, whatever its description: only a + complete stream's own feed delivers exactly that stream. + """ + return self._feed.opened_on + + def reserve(self, claim: object | None = None) -> object: + """Take the channel for one consumer that will read all of it. + + Without ``claim``: the channel, not read yet, is held for the returned claim: + no read is taken, from any task, until a task takes it over with the claim + (the task that runs a conversion). With the claim it returned: the calling + task takes the channel over, and any other task's read is then refused. + + Args: + claim: The claim an earlier ``reserve()`` returned, to take it over. + + Returns: + The claim. + + Raises: + RuntimeError: If a read was called on it already (by any consumer, also + one still waiting), so all of the input can no longer be given; or + if ``claim`` is not this channel's claim. + ChannelClosed: If it was closed. + """ + if self._closed: + raise self._closed_early() + if claim is not None: + if claim is not self._claim: + raise RuntimeError( + f"The input channel of {_named(self._stream)} is claimed by " + + "another consumer." + ) + self._owner = _current_task() + self._claim = None # redeemed: a later reserve(claim) is refused + return claim + if self._started or self._ended or self._owner is not None: + raise RuntimeError( + f"The input channel of {_named(self._stream)} has been read already, " + + "or is being read by another consumer; all of its input can no " + + "longer be given." + ) + self._started = True + self._owner = None # held for the claim until a task takes it over + self._claim = object() + return self._claim + + def _belong_to_caller(self) -> None: + """Bind the channel to the calling task on its first read; refuse any other. + + A channel has one consumer for its whole life: between batches as well as + while a read is pending, a read from another task is refused. + """ + task = _current_task() + if self._owner is None and self._claim is not None: + raise RuntimeError( + f"The input channel of {_named(self._stream)} is held for a " + + "conversion that has not started; no other read is taken." + ) + if self._owner is None: + self._owner = task + elif self._owner is not task: + raise RuntimeError( + f"The input channel of {_named(self._stream)} belongs to another " + + "consumer (another task); a channel has one consumer." + ) + + async def receive(self) -> pa.RecordBatch: + """Return the next Arrow record batch. + + A read that is cancelled while it waits closes the channel, as ``close`` does: + a consumer that stops reading never holds its producer. + + Raises: + ChannelClosed: At the end, and after ``close``. After a ``close`` that came + before the producer completed, the error says so, and iteration + (``async for``) raises it instead of ending: no consumer loop takes + part of an input for all of it. A ``ChannelClosed`` raised by the + feed's own read is a read error too: only the feed's end ends it. + RuntimeError: If the channel belongs to another consumer (another task; + the first read binds it), or a read of it is in progress. + UpstreamFailedError: If the producer failed or was cancelled. + """ + if self._closed: + raise self._closed_early() + if self._ended: + raise ChannelClosed() # after the end there is nothing to take, for anyone + self._belong_to_caller() + if self._reading: + raise RuntimeError( + f"The input channel of {_named(self._stream)} is being read by another " + + "consumer; a channel has one consumer." + ) + self._started = True + self._reading = True + try: + batch = await self._feed.next() + except asyncio.CancelledError: + await self.close() + raise + except StopAsyncIteration as error: + # Only ``None`` is the feed's end: a raised StopAsyncIteration would end + # an ``async for`` over part of the input. + raise RuntimeError( + f"The read of the input channel of {_named(self._stream)} raised " + + "StopAsyncIteration; a feed ends by returning None." + ) from error + finally: + self._reading = False + if batch is None: + if self._closed: # woken by its own early close + raise self._closed_early() + self._ended = True + self._owner = None # nothing left to read: the consumer is released + raise ChannelClosed() + self._received += 1 + return batch + + def __aiter__(self) -> AsyncIterator[pa.RecordBatch]: + """Iterate over the remaining record batches, in arrival order.""" + return self + + async def __anext__(self) -> pa.RecordBatch: + """Return the next record batch; end the iteration at the producer's end. + + A channel closed before its producer completed does not end the iteration: + its ``ChannelClosed`` is raised, so a loop never takes part of an input for + all of it. + """ + try: + return await self.receive() + except ChannelClosed: + # Only the producer's end ends the iteration: an early close, or a + # ChannelClosed raised by the feed's own read, is a read error. + if self._ended and not self._closed: + raise StopAsyncIteration + raise + + def _closed_early(self) -> ChannelClosed: + """The error of a read after a close that came before the producer completed.""" + return ChannelClosed( + f"The input channel of {_named(self._stream)} was closed before its " + + "producer completed; it has no complete input to give." + ) + + async def collect(self) -> list[pa.RecordBatch]: + """Read to the end and return every remaining record batch, in arrival order. + + Raises: + ChannelClosed: If the channel was closed before its producer completed: + what was read is part of the input, never returned as all of it. + UpstreamFailedError: If the producer failed or was cancelled. + """ + return [batch async for batch in self] + + async def close(self) -> None: + """Stop reading. The producer no longer waits for this reader. + + Callable from any task. The consumer task is released: no read is taken + after a close, from any task. + """ + if not self._ended: + self._closed = True + self._ended = True + self._owner = None + self._claim = None + self._feed.close() + + +def _current_task() -> asyncio.Task[Any] | None: + """The running asyncio task, or ``None`` outside one.""" + try: + return asyncio.current_task() + except RuntimeError: # no running event loop + return None + + +def _named(stream: Any) -> str: # pyright: ignore[reportExplicitAny] # any stream or node + """How an error names a stream: its label, or what it prints as.""" + label = getattr(stream, "label", None) + return repr(label) if label else repr(stream) diff --git a/src/orcapod/protocols/core_protocols/__init__.py b/src/orcapod/protocols/core_protocols/__init__.py index caf52a0a9..7ec5f81d9 100644 --- a/src/orcapod/protocols/core_protocols/__init__.py +++ b/src/orcapod/protocols/core_protocols/__init__.py @@ -8,7 +8,12 @@ from .data_function import DataFunctionProtocol from .pod import ArgumentGroup, PodProtocol from .sources import DynamicSourceProtocol, SourceProtocol -from .streams import StreamViewProtocol, StreamProtocol +from .streams import ( + RecordBatchInput, + RecordBatchOutput, + StreamProtocol, + StreamViewProtocol, +) from .side_effect_pod import SideEffectPodProtocol from .trackers import TrackerProtocol, TrackerManagerProtocol @@ -21,6 +26,8 @@ "SourceProtocol", "StreamViewProtocol", "StreamProtocol", + "RecordBatchInput", + "RecordBatchOutput", "PodProtocol", "ArgumentGroup", "PipelineElementProtocol", diff --git a/src/orcapod/protocols/core_protocols/record_batch_channels.py b/src/orcapod/protocols/core_protocols/record_batch_channels.py deleted file mode 100644 index 27f34aa69..000000000 --- a/src/orcapod/protocols/core_protocols/record_batch_channels.py +++ /dev/null @@ -1,86 +0,0 @@ -"""Protocols of the channels of Arrow record batches (ITL-1347). - -``RecordBatchInput`` and ``RecordBatchOutput`` are what an operator's record-batch form -reads and writes. The stream is primary and owns the description (keys, schemas, data -context, pipeline hash); a channel refers to its stream and restates nothing. The -implementations are in ``orcapod.core.record_batch_channels``. -""" - -from __future__ import annotations - -from collections.abc import AsyncIterator -from typing import TYPE_CHECKING, Protocol - -if TYPE_CHECKING: - import pyarrow as pa - - from orcapod.protocols.core_protocols.streams import StreamProtocol - - -class RecordBatchInput(Protocol): - """A single-pass reader of a stream's Arrow record batches. - - The Arrow-record-batch form of ``ReadableChannel`` (``orcapod.channels``); ``InputChannel`` of - ``orcapod.core.record_batch_channels`` is the implementation. Its description is - its ``stream``, known before the first batch. - """ - - @property - def stream(self) -> StreamProtocol: - """The stream whose rows this channel delivers: the description.""" - ... - - async def receive(self) -> pa.RecordBatch: - """Return the next Arrow record batch. - - Raises: - ChannelClosed: At the end, and after ``close``. - UpstreamFailedError: If the producer failed or was cancelled. - """ - ... - - def __aiter__(self) -> AsyncIterator[pa.RecordBatch]: - """Iterate over the remaining record batches, in arrival order.""" - ... - - async def collect(self) -> list[pa.RecordBatch]: - """Read to the end and return every remaining record batch, in arrival order.""" - ... - - async def to_stream(self) -> StreamProtocol: - """Read to the end and return what the channel delivered, as a stream. - - All of the input or nothing: it needs a channel not read yet. ``collect`` - drains the batches that remain; ``to_stream`` never makes a stream of part of - an input. - - Raises: - RuntimeError: If a record batch has already been received. - ChannelClosed: If the channel was closed before its producer completed. - UpstreamFailedError: If the producer failed or was cancelled. - """ - ... - - async def close(self) -> None: - """Stop reading. The producer no longer waits for this reader.""" - ... - - -class RecordBatchOutput(Protocol): - """The producer side of a stream's Arrow record batches. - - The Arrow-record-batch form of ``WritableChannel`` (``orcapod.channels``); ``OutputChannel`` of - ``orcapod.core.record_batch_channels`` is the implementation. - """ - - async def send(self, batch: pa.RecordBatch) -> None: - """Send one Arrow record batch of the stream's transport columns.""" - ... - - async def close(self) -> None: - """Complete the output.""" - ... - - def fail(self, error: BaseException) -> None: - """End the output with the producer's failure or cancellation.""" - ... diff --git a/src/orcapod/protocols/core_protocols/streams.py b/src/orcapod/protocols/core_protocols/streams.py index 010d29232..ec42f4c7e 100644 --- a/src/orcapod/protocols/core_protocols/streams.py +++ b/src/orcapod/protocols/core_protocols/streams.py @@ -183,6 +183,19 @@ def iter_data(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: """ ... + def open_channel(self) -> RecordBatchInput: + """Open an input channel on this stream, for async computation (ITL-1347). + + The channel delivers the stream's rows as Arrow record batches, read once and + in order; its description is this stream. Several channels may be opened on + one stream, each with its own position (``channel_to_stream`` makes a stream of + what a channel delivers). + + Returns: + The input channel. + """ + ... + def async_iter_data(self) -> AsyncIterator[tuple[TagProtocol, DataProtocol]]: """ Generates asynchronous iterator over (tag, data) pairs in the stream. @@ -568,3 +581,92 @@ def batch( Self: New stream containing batched (tag, data) pairs. """ ... + + +# --------------------------------------------------------------------------- +# Channels of Arrow record batches (ITL-1347): the stream is the description +# --------------------------------------------------------------------------- + + +class RecordBatchInput(Protocol): + """A single-pass reader of a stream's Arrow record batches. + + The Arrow-record-batch form of ``ReadableChannel`` (``orcapod.channels``); ``InputChannel`` of + ``orcapod.core.streams.record_batch_input`` is the implementation. Its description is + its ``stream``, known before the first batch. + """ + + @property + def stream(self) -> StreamProtocol: + """The stream whose rows this channel delivers: the description.""" + ... + + async def receive(self) -> pa.RecordBatch: + """Return the next Arrow record batch. + + Raises: + ChannelClosed: At the end, and after ``close``. + UpstreamFailedError: If the producer failed or was cancelled. + """ + ... + + def __aiter__(self) -> AsyncIterator[pa.RecordBatch]: + """Iterate over the remaining record batches, in arrival order.""" + ... + + async def collect(self) -> list[pa.RecordBatch]: + """Read to the end and return every remaining record batch, in arrival order.""" + ... + + @property + def unread(self) -> bool: + """Whether no read was called and the channel is not closed. + + A reserved channel (``reserve()``) is not unread, even before its first read. + """ + ... + + @property + def opened_on(self) -> StreamProtocol | None: + """The complete stream this channel reads, when it was opened on one; else + ``None`` (a reader of an output channel, whatever its description).""" + ... + + def reserve(self, claim: object | None = None) -> object: + """Take the channel for one consumer that will read all of it. + + Without ``claim``, the unread channel is held for the returned claim, not for + the calling task: no task, the reserving one included, can read it until a + task takes it over with that claim (``reserve(claim)``), after which only + that task reads it. A claim is taken over once. + + Raises: + RuntimeError: If a read was called on it already, or ``claim`` is not its + claim. + ChannelClosed: If it was closed. + """ + ... + + async def close(self) -> None: + """Stop reading. The producer no longer waits for this reader.""" + ... + + +class RecordBatchOutput(Protocol): + """The producer side of a stream's Arrow record batches. + + The Arrow-record-batch form of ``WritableChannel`` (``orcapod.channels``); ``OutputChannel`` of + ``orcapod.core.record_batch_channels`` is the implementation. + """ + + async def send(self, batch: pa.RecordBatch) -> None: + """Send one Arrow record batch of the stream's transport columns.""" + ... + + async def close(self) -> None: + """Complete the output.""" + ... + + def fail(self, error: BaseException) -> None: + """End the output with the producer's failure or cancellation.""" + ... diff --git a/tests/test_channels/test_record_batch_channels.py b/tests/test_channels/test_record_batch_channels.py index 4c03cefd3..95821c2cd 100644 --- a/tests/test_channels/test_record_batch_channels.py +++ b/tests/test_channels/test_record_batch_channels.py @@ -2,10 +2,10 @@ A stream is primary and owns the description; a channel is a separate, single-pass carrier of the stream's rows as Arrow record batches. An input channel is opened from a -complete stream (``channel_from_stream``) or from an output channel +complete stream (``stream.open_channel()``) or from an output channel (``OutputChannel.open_reader``); an output channel, once closed, gives its rows back as an ordinary stream (``result()``), and so does an input channel that is read to its end -(``to_stream()``). One test per rule of the design's table "The hard semantics". +(``channel_to_stream``). One test per rule of the design's table "The hard semantics". The oracle of every table is ``R``: the table today's code builds from a stream's rows (``StaticOutputOperatorPod._rows_to_table``). @@ -14,6 +14,8 @@ from __future__ import annotations import asyncio +import gc +import weakref from collections.abc import Awaitable, Callable, Sequence from typing import Any, TypeVar from unittest import mock @@ -21,7 +23,7 @@ import pyarrow as pa import pytest -from orcapod.protocols.core_protocols.record_batch_channels import ( +from orcapod.protocols.core_protocols.streams import ( RecordBatchInput, RecordBatchOutput, ) @@ -30,23 +32,32 @@ ReadableChannel, WritableChannel, ) -from orcapod.core.operators import MapData, PolarsFilter, SelectDataColumns +from orcapod.core.operators import MapData, PolarsFilter, SelectDataColumns, SemiJoin from orcapod.core.operators.static_output_pod import ( + ROW_BUILT_OUTPUT, StaticOutputOperatorPod, + channel_to_stream, stream_from_batches, transport_schema, ) from orcapod.core.record_batch_channels import ( BATCH_BUFFER_SIZE, - SOURCE_BATCH_ROWS, - InputChannel, OutputChannel, _schema_mismatch, # pyright: ignore[reportPrivateUsage] # the check itself is tested - channel_from_stream, ) +from orcapod.core.streams.record_batch_input import SOURCE_BATCH_ROWS, InputChannel +from orcapod.core.nodes.source_node import SourceJobNode, SourceNode from orcapod.core.streams import ArrowTableStream -from orcapod.errors import UpstreamFailedError +from orcapod.errors import UnboundSourceError, UpstreamFailedError +from orcapod.protocols.core_protocols import StreamProtocol +from orcapod.core.sources import PollingSource +from orcapod.core.sources.source_proxy import SourceProxy +from orcapod.databases import InMemoryArrowDatabase +from orcapod.pipeline import SyncPipelineOrchestrator +from orcapod.pipeline.job import PipelineJob from orcapod.sources import ArrowTableSource +from orcapod.types import Schema +from tests.test_channels.test_polling_source import FakeDynamicSource, _batch T = TypeVar("T") ALL = {"system_tags": True, "source": True} @@ -97,7 +108,7 @@ def batches_of(stream: Any, rows: int = SOURCE_BATCH_ROWS) -> list[pa.RecordBatc """``stream``'s record batches, cut every ``rows`` rows.""" async def read() -> list[pa.RecordBatch]: - return await channel_from_stream(stream).collect() + return await stream.open_channel().collect() return pa.Table.from_batches(run(read)).to_batches(max_chunksize=rows) @@ -106,20 +117,688 @@ async def read() -> list[pa.RecordBatch]: def test_a_channel_opened_on_a_stream_delivers_its_rows_and_refers_to_it() -> None: - """The record batches are the stream's rows; the description is the stream.""" + """The record batches are the stream's rows in the row-built form; the description + is the stream, and ``channel_to_stream`` rebuilds what the channel delivered, with + the stream's identity.""" stream = source() - channel = channel_from_stream(stream) + channel = stream.open_channel() assert isinstance(channel, InputChannel) assert isinstance(channel, ReadableChannel) as_protocol: RecordBatchInput = channel # what an operator reads (type-checked) assert as_protocol.stream is stream - delivered = run(channel.to_stream) + batches = run(stream.open_channel().collect) + assert same(pa.Table.from_batches(batches), R(stream)) + delivered = run(lambda: channel_to_stream(channel)) assert same(delivered.as_table(columns=ALL), R(stream)) assert delivered.keys() == stream.keys() - assert delivered.output_schema() == stream.output_schema() assert delivered.data_context_key == stream.data_context_key assert delivered.pipeline_hash() == stream.pipeline_hash() + with pytest.raises(ChannelClosed): + _ = run(channel.receive) # read to its end + + +def test_a_source_node_opens_a_channel_on_its_rows() -> None: + """A source node is a stream too. A job's source node delivers its source's rows in + the row-built form, which ``channel_to_stream`` rebuilds. An unbound slot opens a + channel (opening reads nothing), and its first read raises.""" + stream = source() + node = SourceJobNode.from_stream(stream, name="events") + assert isinstance(node, StreamProtocol) + batches = run(node.open_channel().collect) + assert same(pa.Table.from_batches(batches), R(node)) + rebuilt = run(lambda: channel_to_stream(node.open_channel())) + assert same(rebuilt.as_table(columns=ALL), R(node)) + + slot = SourceNode.from_stream(stream, name="events") + assert isinstance(slot, StreamProtocol) + channel = slot.open_channel() + with pytest.raises(UnboundSourceError): + _ = run(channel.receive) + + +def test_a_bound_source_node_sends_its_rows_in_their_own_column_order() -> None: + """A source whose physical columns are x, j, k, y with tags declared k, j: the + node's batches have the column order of its own rows (``execute()``: k, j, ...), + not the slot's schema order.""" + stream = ArrowTableSource( + pa.table( + { + "x": pa.array([1, 2], pa.int64()), + "j": pa.array([3, 4], pa.int64()), + "k": pa.array([5, 6], pa.int64()), + "y": pa.array([7.5, 8.5], pa.float64()), + } + ), + tag_columns=["k", "j"], + tag_only_columns=True, + source_id="ordered", + ) + node = SourceJobNode.from_stream(stream, name="ordered") + assert node.keys()[0] != stream.keys()[0] # the slot's order is another + rows = node.execute() + expected = StaticOutputOperatorPod._rows_to_table(rows)[0] + batches = run(node.open_channel().collect) + assert pa.Table.from_batches(batches).schema.names == expected.schema.names + assert same(pa.Table.from_batches(batches), expected) + + +def _keyed_source( + tag_only: tuple[str, ...], *, source_id: str = "keyed", offset: int = 0 +) -> ArrowTableSource: + """Tags ``k, j`` (data-tags unless named in ``tag_only``), data ``x, y``; every + field non-nullable, so a slot may declare ``x: int | None`` (a narrower bind).""" + table = pa.table( + { + "x": pa.array([1 + offset, 2 + offset], pa.int64()), + "k": pa.array([5 + offset, 6 + offset], pa.int64()), + "j": pa.array([3 + offset, 4 + offset], pa.int64()), + "y": pa.array([7.5, 8.5], pa.float64()), + } + ) + table = table.cast(pa.schema([f.with_nullable(False) for f in table.schema])) + return ArrowTableSource( + table, tag_columns=["k", "j"], tag_only_columns=tag_only, source_id=source_id + ) + + +def _declared_node(source: ArrowTableSource) -> SourceJobNode: + """A slot that declares tags ``j, k`` and data ``y, x: int | None`` (the source's + data-tags first), bound to ``source``: the declared form.""" + data_tags = [t for t in ("j", "k") if t in source.keys()[1]] + return SourceJobNode( + "keyed", + tag_schema=Schema({"j": int, "k": int}), + data_schema=Schema( + {**{t: int for t in data_tags}, "y": float, "x": int | None} + ), + bound_source=source, + ) + + +@pytest.mark.parametrize( + ("bind", "tag_only"), + [ + ("transparent", ()), + ("transparent", ("j",)), + ("transparent", ("k",)), + # A declared slot with one of two data-tags fails on main already, in its + # own execute() rows (duplicate column); reported separately. + ("declared", ()), + ], + ids=["transparent-both", "transparent-k", "transparent-j", "declared-both"], +) +def test_a_source_nodes_channel_carries_its_execute_output( + bind: str, tag_only: tuple[str, ...] +) -> None: + """A source node's batches, and the stream rebuilt from them, are its own + ``execute()`` output (schema, order, values, content hash), with data-tags in each + tag position (the declared slot orders the tags j, k against the source's k, j); + the node's own output channel takes them.""" + source = _keyed_source(tag_only) + node = ( + SourceJobNode.from_stream(source, name="keyed") + if bind == "transparent" + else _declared_node(source) + ) + expected = StaticOutputOperatorPod._materialize_upstream(node.execute(), node) # pyright: ignore[reportPrivateUsage] # the job's rebuild of the rows + wanted = expected.as_table(columns=ALL) + assert any( + name.startswith("_source_") and name.removeprefix("_source_") in ("j", "k") + for name in wanted.column_names + ) # data-tag tokens are there + + async def read() -> tuple[list[pa.RecordBatch], Any]: + batches = await node.open_channel().collect() + output = OutputChannel(node) + for batch in batches: + await output.send(batch) # the node's description takes them + await output.close() + return batches, await channel_to_stream(node.open_channel()) + + batches, rebuilt = run(read) + assert same(pa.Table.from_batches(batches), R(expected)) + assert same(rebuilt.as_table(columns=ALL), wanted) + assert rebuilt.content_hash() == expected.content_hash() + + +def test_a_rebind_before_the_first_read_is_read_whole() -> None: + """A channel opened on a source node, then the node rebound: the first read reads + the new binding only (rows, order and source info from one binding).""" + node = SourceJobNode.from_stream(_keyed_source(()), name="keyed") + channel = node.open_channel() + node.bound_source = _keyed_source((), source_id="other", offset=10) + expected = StaticOutputOperatorPod._materialize_upstream(node.execute(), node) # pyright: ignore[reportPrivateUsage] # the job's rebuild of the rows + batches = run(channel.collect) + assert same(pa.Table.from_batches(batches), R(expected)) + + +def test_a_source_nodes_conversion_keeps_the_delivered_column_order() -> None: + """Plain tags declared ``k, j`` over physical columns ``x, j, k, y``: the stream + ``channel_to_stream`` makes keeps the columns in the order they were delivered + (the node's rows), though the node describes itself in the slot's order.""" + stream = ArrowTableSource( + pa.table( + { + "x": pa.array([1, 2], pa.int64()), + "j": pa.array([3, 4], pa.int64()), + "k": pa.array([5, 6], pa.int64()), + "y": pa.array([7.5, 8.5], pa.float64()), + } + ), + tag_columns=["k", "j"], + tag_only_columns=True, + source_id="ordered", + ) + node = SourceJobNode.from_stream(stream, name="ordered") + assert node.keys()[0] == ("j", "k") # the slot's order + + async def read() -> tuple[list[str], list[str]]: + batches = await node.open_channel().collect() + rebuilt = await channel_to_stream(node.open_channel()) + return batches[0].schema.names, rebuilt.as_table(columns=ALL).column_names + + delivered, rebuilt = run(read) + assert delivered[:2] == ["k", "j"] + assert rebuilt == delivered + + +@pytest.mark.xfail( + strict=True, + raises=ValueError, + reason="ITL-1365: a source node whose plain tags are declared in another order " + "than their columns (x, j, k, y with tags k, j) describes itself in the slot's " + "order (keys() j, k; its zero-row input too, as on main), while its rows are in " + "the bound source's order, so its own description refuses its batches", +) +def test_a_source_nodes_description_takes_its_rows_in_their_own_order() -> None: + """Plain tags declared ``k, j`` over physical columns ``x, j, k, y``: the node's + own output channel takes the batches its channel delivers.""" + stream = ArrowTableSource( + pa.table( + { + "x": pa.array([1, 2], pa.int64()), + "j": pa.array([3, 4], pa.int64()), + "k": pa.array([5, 6], pa.int64()), + "y": pa.array([7.5, 8.5], pa.float64()), + } + ), + tag_columns=["k", "j"], + tag_only_columns=True, + source_id="ordered", + ) + node = SourceJobNode.from_stream(stream, name="ordered") + + async def read() -> None: + output = OutputChannel(node) + for batch in await node.open_channel().collect(): + await output.send(batch) + + run(read) + + +def test_a_flagged_stream_is_given_as_it_is_only_by_its_own_channel() -> None: + """The shortcut belongs to a channel opened on a stream ``_output_stream`` built: + such a channel gives that stream. A reader of an output channel whose description + is that same stream reads its producer: other rows, or its failure.""" + stream = source(2) + batches = batches_of(stream, 1) + + async def flagged_stream() -> Any: + output = OutputChannel(stream) + for batch in batches: + await output.send(batch) + await output.close() + return await channel_to_stream(output.open_reader()) + + flagged = run(flagged_stream) + assert getattr(flagged, ROW_BUILT_OUTPUT, False) + + async def read() -> None: + direct = flagged.open_channel() + assert await channel_to_stream(direct) is flagged + other = OutputChannel(flagged) + reader = other.open_reader() + await other.send(batches[0]) + await other.close() + rebuilt = await channel_to_stream(reader) + assert rebuilt is not flagged + assert rebuilt.as_table().num_rows == 1 + failed = OutputChannel(flagged) + failing = failed.open_reader() + failed.fail(OSError("disk gone")) + with pytest.raises(UpstreamFailedError): + _ = await channel_to_stream(failing) + op = SemiJoin() + semi_output = OutputChannel(op(stream, flagged)) + broken = OutputChannel(flagged) + broken_reader = broken.open_reader() + broken.fail(OSError("disk gone")) + with pytest.raises(UpstreamFailedError): + await op.async_execute_batches( + [stream.open_channel(), broken_reader], semi_output + ) + + run(read) + + +@pytest.mark.parametrize("retain", [True, False], ids=["retained", "bounded"]) +def test_a_reader_has_one_consumer(retain: bool) -> None: + """A receive waiting on a reader holds it: a second consumer of the same reader + (a conversion, or another receive) is refused, naming it, and the waiting + receive gets the batch.""" + stream = source(1) + (batch,) = batches_of(stream) + + async def read() -> int: + output = OutputChannel(stream, retain=retain) + reader = output.open_reader() + waiting = asyncio.ensure_future(reader.receive()) + await asyncio.sleep(0) + assert not reader.unread + with pytest.raises(RuntimeError, match="read already|another consumer"): + _ = await channel_to_stream(reader) + with pytest.raises(RuntimeError, match="another consumer"): + _ = await reader.receive() + await output.send(batch) + await output.close() + return (await waiting).num_rows + + assert run(read) == 1 + + +@pytest.mark.parametrize("retain", [True, False], ids=["retained", "bounded"]) +def test_a_reader_belongs_to_its_first_consumer_between_batches(retain: bool) -> None: + """Task A iterates a reader and pauses after its first batch; task B's read of the + same reader, between A's batches, is refused, and A reads all three batches.""" + stream = source(3) + batches = batches_of(stream, 1) + + async def read() -> int: + output = OutputChannel(stream, retain=retain, buffer_size=4) + reader = output.open_reader() + for batch in batches: + await output.send(batch) + await output.close() + paused, resume = asyncio.Event(), asyncio.Event() + + async def consumer_a() -> int: + seen = 0 + async for _ in reader: + seen += 1 + if seen == 1: + paused.set() + await resume.wait() + return seen + + async def consumer_b() -> None: + _ = await reader.receive() + + a = asyncio.ensure_future(consumer_a()) + await paused.wait() + with pytest.raises(RuntimeError, match="belongs to another consumer"): + await asyncio.ensure_future(consumer_b()) + resume.set() + return await a + + assert run(read) == 3 + + +@pytest.mark.parametrize("retain", [True, False], ids=["retained", "bounded"]) +def test_a_reserved_reader_is_read_only_through_its_claim(retain: bool) -> None: + """``reserve()`` holds the reader for its claim: no read is taken (from another + task, nor from the reserving task) until a task takes it over with the claim; + then only that task reads.""" + stream = source(2) + batches = batches_of(stream, 1) + + async def read() -> int: + output = OutputChannel(stream, retain=retain, buffer_size=4) + reader = output.open_reader() + for batch in batches: + await output.send(batch) + await output.close() + claim = reader.reserve() + with pytest.raises(RuntimeError, match="held for a conversion"): + _ = await reader.receive() + + async def other() -> None: + _ = await reader.receive() + + with pytest.raises(RuntimeError, match="held for a conversion"): + await asyncio.ensure_future(other()) + with pytest.raises(RuntimeError, match="claimed by another consumer"): + _ = reader.reserve(object()) + + async def owner() -> int: + _ = reader.reserve(claim) + return len(await reader.collect()) + + taken = await asyncio.ensure_future(owner()) + with pytest.raises(ChannelClosed): + _ = await reader.receive() # read to its end: nothing left, for anyone + return taken + + assert run(read) == 2 + + +@pytest.mark.parametrize("retain", [True, False], ids=["retained", "bounded"]) +def test_a_conversion_reserves_the_reader_when_it_is_created(retain: bool) -> None: + """``pending = channel_to_stream(reader)`` reserves at once: a receive before + ``await pending`` is refused, and the conversion gets every batch.""" + stream = source(2) + batches = batches_of(stream, 1) + + async def read() -> int: + output = OutputChannel(stream, retain=retain, buffer_size=4) + reader = output.open_reader() + for batch in batches: + await output.send(batch) + await output.close() + pending = channel_to_stream(reader) + with pytest.raises(RuntimeError, match="held for a conversion"): + _ = await reader.receive() + return (await pending).as_table().num_rows + + assert run(read) == 2 + + +def test_a_claim_is_taken_over_once() -> None: + """A redeemed claim cannot be redeemed again: the channel stays with the task that + took it over.""" + stream = source(2) + batches = batches_of(stream, 1) + + async def read() -> int: + output = OutputChannel(stream) + reader = output.open_reader() + for batch in batches: + await output.send(batch) + await output.close() + claim = reader.reserve() + _ = reader.reserve(claim) + + async def thief() -> None: + _ = reader.reserve(claim) + + with pytest.raises(RuntimeError, match="claimed by another consumer"): + await asyncio.ensure_future(thief()) + return len(await reader.collect()) + + assert run(read) == 2 + + +def test_a_reader_releases_its_consumer_task_at_its_end_and_on_close() -> None: + """The consumer task is not kept by the reader once it has nothing left to read: + after the end, or after ``close()``.""" + stream = source(2) + batches = batches_of(stream, 1) + + async def read() -> tuple[bool, bool]: + released: list[bool] = [] + for ending in ("end", "close"): + output = OutputChannel(stream) + reader = output.open_reader() + for batch in batches: + await output.send(batch) + await output.close() + + async def consume() -> None: + if ending == "end": + _ = await reader.collect() + else: + _ = await reader.receive() + await reader.close() + + task = asyncio.ensure_future(consume()) + await task + reference = weakref.ref(task) + del task + await asyncio.sleep(0) # the loop drops its own references to the task + gc.collect() + released.append(reference() is None) + return released[0], released[1] + + assert run(read) == (True, True) + + +class _StoppingFeed: + """A feed whose second read raises ``StopAsyncIteration`` instead of returning + ``None``: a broken feed, not the end of its input.""" + + def __init__(self, batch: pa.RecordBatch) -> None: + self._batch: pa.RecordBatch | None = batch + + async def next(self) -> pa.RecordBatch | None: + """Return the one batch, then raise ``StopAsyncIteration``.""" + if self._batch is None: + raise StopAsyncIteration + batch, self._batch = self._batch, None + return batch + + def close(self) -> None: + """Nothing to release.""" + + @property + def opened_on(self) -> None: + """Not a complete stream's feed.""" + return None + + +def test_a_feed_raising_stop_async_iteration_is_a_read_error() -> None: + """Only a feed returning ``None`` ends a channel: a raised ``StopAsyncIteration`` + is a read error, so ``collect()`` and a barrier never take one batch for all.""" + stream = source(2) + (first, _) = batches_of(stream, 1) + + async def read() -> None: + with pytest.raises(RuntimeError, match="StopAsyncIteration"): + _ = await InputChannel(stream, _StoppingFeed(first)).collect() + with pytest.raises(RuntimeError, match="StopAsyncIteration"): + _ = await channel_to_stream(InputChannel(stream, _StoppingFeed(first))) + + run(read) + + +def test_a_barrier_leaves_no_conversion_behind_when_an_input_was_read() -> None: + """A barrier whose second input was read already: its setup fails, and the first + input's conversion, already started, is cancelled and awaited, so no task fails + later with nobody to hear it.""" + left = source(2) + right = source(2, source_id="other") + unheard: list[Any] = [] + + async def read() -> None: + asyncio.get_running_loop().set_exception_handler( + lambda _loop, context: unheard.append(context) + ) + first, second = left.open_channel(), right.open_channel() + _ = await second.receive() + op = SemiJoin() + output = OutputChannel(op(left, right)) + with pytest.raises(RuntimeError, match="read already"): + await op.async_execute_batches([first, second], output) + gc.collect() + await asyncio.sleep(0.01) + + run(read) + gc.collect() + assert unheard == [] + + +def test_a_closed_reader_cannot_be_converted() -> None: + """A reader closed before any read: ``channel_to_stream`` raises ``ChannelClosed``, + as documented, not the error of a channel already read.""" + stream = source(1) + + async def read() -> None: + reader = OutputChannel(stream).open_reader() + await reader.close() + with pytest.raises(ChannelClosed, match="closed before its producer"): + _ = await channel_to_stream(reader) + + run(read) + + +class _ClosingFetch(FakeDynamicSource): + """A dynamic source whose fetch raises ``ChannelClosed`` (its own input closed + early); its schema is declared, so nothing before the read fetches.""" + + async def fetch(self, cursor: Any = None) -> Any: + """Record the fetch, then fail it as a source whose own input closed.""" + self.fetch_cursors.append(cursor) + raise ChannelClosed("underlying input closed early") + + +def test_a_channel_closed_inside_the_read_is_a_read_error() -> None: + """A ``ChannelClosed`` raised by the feed's own read (the source's) is not the end + of the input: iteration, ``collect`` and ``channel_to_stream`` raise it, and a + barrier fails before its body.""" + declared = Schema({"id": int, "val": int}) + + def polling() -> PollingSource[Any]: + fake = _ClosingFetch( + batches=[_batch(1, 10), _batch(2, 20)], schema_override=declared + ) + return PollingSource( + fake, tag_columns="id", record_id_columns="id", source_id="closing" + ) + + async def read() -> None: + with pytest.raises(ChannelClosed, match="underlying input"): + _ = await polling().open_channel().collect() + channel = polling().open_channel() + with pytest.raises(ChannelClosed, match="underlying input"): + _ = await channel_to_stream(channel) + assert not channel.unread + left = source() + right = polling() + op = SemiJoin() + output = OutputChannel(op(left, right)) + with pytest.raises(ChannelClosed, match="underlying input"): + await op.async_execute_batches( + [left.open_channel(), right.open_channel()], output + ) + + run(read) + + +def test_a_delivered_batch_is_not_kept_by_the_feed() -> None: + """Once delivered, a batch is not held by the channel: a consumer that drops it + frees it, also while the channel is still open.""" + n = SOURCE_BATCH_ROWS + 3 + stream = ArrowTableSource( + pa.table( + {"k": pa.array(range(n), pa.int64()), "v": pa.array(range(n), pa.int64())} + ), + tag_columns=["k"], + tag_only_columns=True, + source_id="large", + ) + + async def read() -> bool: + channel = stream.open_channel() + first = await channel.receive() + reference = weakref.ref(first) + del first + gc.collect() + released_while_open = reference() is None # before the channel is drained + rest = await channel.collect() + assert sum(batch.num_rows for batch in rest) == 3 + return released_while_open + + assert run(read) + + +def test_an_unbound_input_fails_a_barrier_before_it_runs() -> None: + """``SemiJoin`` with no shared tag never reads its right input on the sync path, + but ``channel_to_stream`` reads every input first: an unbound right input (a slot, + or a ``SourceProxy``) raises what reading it raises, before the operator runs.""" + left = source() + other = ArrowTableSource( + pa.table({"other": pa.array([1], pa.int64()), "v": pa.array([0.5])}), + tag_columns=["other"], + tag_only_columns=True, + source_id="other", + ) + slot = SourceNode.from_stream(other, name="other") + proxy = SourceProxy( + source_id="other", + expected_class_name="ArrowTableSource", + tag_schema=Schema({"other": int}), + data_schema=Schema({"v": float}), + content_hash_str=other.content_hash().to_string(), + pipeline_hash_str=other.pipeline_hash().to_string(), + ) + for right, raised in ((slot, UnboundSourceError), (proxy, NotImplementedError)): + op = SemiJoin() + + async def go(right: Any = right) -> None: + output = OutputChannel(op(left, right)) + await op.async_execute_batches( + [left.open_channel(), right.open_channel()], output + ) + + with pytest.raises(raised): + run(go) + + +def test_an_exhausted_channel_never_yields_rows_later() -> None: + """A job node's channel read to its end before the node's run delivered nothing; + after the run, the same channel neither gives the run's rows nor reads again.""" + job = PipelineJob(name="exhausted", database=InMemoryArrowDatabase()) + with job: + _ = SelectDataColumns(["subject", "trial", "note"])(source(), label="selected") + node = job.nodes["selected"] + + async def before_run() -> Any: + channel = node.open_channel() + assert await channel.collect() == [] + return channel + + channel = run(before_run) + _ = job.run(orchestrator=SyncPipelineOrchestrator()) + assert node.as_table().num_rows == 7 + + async def after_run() -> None: + assert await channel.collect() == [] # single pass: nothing more + with pytest.raises(RuntimeError, match="read already"): + _ = await channel_to_stream(channel) + + run(after_run) + + +def test_a_polling_source_is_read_once_through_a_channel() -> None: + """A fresh ``PollingSource``: opening a channel fetches nothing; reading it fetches + once and the stream ``channel_to_stream`` gives is a fixed snapshot, read again + with no further fetch, also through ``collect``.""" + fake = FakeDynamicSource(batches=[_batch(i, 10 * i) for i in range(1, 6)]) + polling = PollingSource( + fake, tag_columns="id", record_id_columns="id", source_id="polled" + ) + + async def read() -> None: + channel = polling.open_channel() + other = polling.open_channel() + assert len(fake.fetch_cursors) == 0 # opening reads nothing + snapshot = await channel_to_stream(channel) + fetched = len(fake.fetch_cursors) + assert fetched == 1 # exactly one fetch for the channel's first read + assert len(await other.collect()) >= 1 + assert len(fake.fetch_cursors) == 2 # and one for the other channel's + fetched = len(fake.fetch_cursors) + rows = snapshot.as_table().num_rows + assert snapshot.as_table().num_rows == rows # a fixed snapshot + assert len(fake.fetch_cursors) == fetched # read again: no fetch + second = polling.open_channel() + assert len(fake.fetch_cursors) == fetched + batches = await second.collect() + read_once = len(fake.fetch_cursors) + assert await second.collect() == [] # one pass + assert len(fake.fetch_cursors) == read_once # never read again + assert batches + + run(read) def test_opening_a_channel_computes_nothing() -> None: @@ -131,7 +810,7 @@ def test_opening_a_channel_computes_nothing() -> None: autospec=True, side_effect=ArrowTableSource.as_table, ) as read: - channel = channel_from_stream(stream) + channel = stream.open_channel() assert read.call_count == 0 _ = run(channel.receive) assert read.call_count == 1 @@ -142,7 +821,7 @@ def test_two_channels_on_one_stream_have_their_own_positions() -> None: stream = source() async def read() -> tuple[int, int, int]: - first, second = channel_from_stream(stream), channel_from_stream(stream) + first, second = stream.open_channel(), stream.open_channel() one = await first.receive() rest = await second.collect() return one.num_rows, sum(b.num_rows for b in rest), len(await first.collect()) @@ -160,7 +839,7 @@ def test_a_stream_is_read_in_record_batches_of_bounded_size() -> None: tag_only_columns=True, source_id="many", ) - sizes = [batch.num_rows for batch in run(channel_from_stream(stream).collect)] + sizes = [batch.num_rows for batch in run(stream.open_channel().collect)] assert sizes == [SOURCE_BATCH_ROWS, 10] @@ -168,7 +847,7 @@ def test_a_channel_is_read_once_and_the_stream_again() -> None: """A channel is single-pass; to read again, go back to a stream.""" async def read() -> tuple[int, int]: - channel = channel_from_stream(source()) + channel = source().open_channel() first = await channel.collect() with pytest.raises(ChannelClosed): _ = await channel.receive() @@ -177,8 +856,9 @@ async def read() -> tuple[int, int]: assert run(read) == (1, 0) -def test_to_stream_is_everything_or_nothing() -> None: - """``to_stream()`` on a channel already read is refused: never part of an input.""" +def test_channel_to_stream_is_everything_or_nothing() -> None: + """``channel_to_stream`` on a channel already read is refused: never part of an + input, and a channel is never read again.""" batches = batches_of(source(), 2) @@ -189,8 +869,8 @@ async def read() -> None: await output.close() channel = output.open_reader() _ = await channel.receive() - with pytest.raises(RuntimeError, match="1 record batch"): - _ = await channel.to_stream() + with pytest.raises(RuntimeError, match="read already"): + _ = await channel_to_stream(channel) run(read) @@ -230,7 +910,7 @@ async def write() -> OutputChannel: def test_the_identity_of_a_result_with_and_without_a_producer() -> None: - """``result()`` and ``to_stream()`` take the describing stream's identity: its + """``result()`` and ``channel_to_stream`` take the describing stream's identity: its producer and upstreams when it has a producer, its pipeline hash when it has none.""" root = source() produced = SelectDataColumns(["subject", "trial", "amplitude"])(root) @@ -240,7 +920,7 @@ async def both(stream: Any, batches: list[pa.RecordBatch]) -> tuple[Any, Any]: for batch in batches: await output.send(batch) await output.close() - return output.result(), await output.open_reader().to_stream() + return output.result(), await channel_to_stream(output.open_reader()) for stream in (root, produced): batches = batches_of(stream, 3) @@ -253,7 +933,7 @@ async def both(stream: Any, batches: list[pa.RecordBatch]) -> tuple[Any, Any]: def test_a_close_with_no_batch_is_the_typed_zero_row_stream() -> None: - """Zero rows: ``result()`` and ``to_stream()`` are typed by the description, never + """Zero rows: ``result()`` and ``channel_to_stream`` are typed by the description, never by rows, with the columns of a run with rows.""" stream = SelectDataColumns(["subject", "trial", "amplitude", "trace"])(source()) with_rows = R(stream) @@ -263,7 +943,7 @@ async def empty() -> tuple[Any, Any]: reader = output.open_reader() await output.close() await output.close() # a second close does nothing - return output.result(), await reader.to_stream() + return output.result(), await channel_to_stream(reader) for made in run(empty): table = made.as_table(columns=ALL) @@ -505,17 +1185,21 @@ async def write() -> tuple[type[object], list[int]]: assert rows == [1] -def test_to_stream_of_a_channel_closed_before_its_end_raises() -> None: - """A reader closed while ``to_stream()`` (or ``collect()``) reads never makes part +def test_channel_to_stream_of_a_channel_closed_before_its_end_raises() -> None: + """A reader closed while ``channel_to_stream`` (or ``collect()``) reads never makes part of an input into a stream.""" stream = source(2) first, second = batches_of(stream, 1) async def write() -> None: - for read in ("to_stream", "collect"): + for read in ("channel_to_stream", "collect"): output = OutputChannel(stream, retain=False, buffer_size=4) reader = output.open_reader() - reading = asyncio.ensure_future(getattr(reader, read)()) + reading = asyncio.ensure_future( + channel_to_stream(reader) + if read == "channel_to_stream" + else reader.collect() + ) await output.send(first) await asyncio.sleep(0) await reader.close() @@ -768,13 +1452,18 @@ async def trials(reader: InputChannel, start: list[Any]) -> list[Any]: got.extend(batch.column("trial").to_pylist()) return got - readers = asyncio.ensure_future( - asyncio.gather(trials(fast, [0]), trials(slow, [])) - ) - _ = await asyncio.gather(*sending) - await output.close() - fast_order, slow_order = await readers - return fast_order, slow_order + async def close_after_sends() -> None: + """Close the output once both sends are done (they wait for the slow + reader's room, which its own consumer task frees).""" + _ = await asyncio.gather(*sending) + await output.close() + + # Each reader has one consumer: this task keeps reading the fast one. + slow_order = asyncio.ensure_future(trials(slow, [])) + closing = asyncio.ensure_future(close_after_sends()) + fast_order = await trials(fast, [0]) + await closing + return fast_order, await slow_order fast_order, slow_order = run(write) assert fast_order == slow_order == [0, 1, 2] @@ -904,24 +1593,30 @@ async def produce() -> None: await output.close() producer = asyncio.ensure_future(produce()) - # Two batches fit each queue. The fast reader makes room for a third, which - # then waits for the slow reader: that send does not return. - got_fast = [await fast.receive() for _ in range(3)] + # Two batches fit each queue. The fast reader (one consumer, its own task) + # makes room for a third, which then waits for the slow reader: that send + # does not return, and the fast reader waits for its fourth batch. + three_read = asyncio.Event() + + async def fast_consumer() -> int: + """The fast reader's one consumer: read three batches, signal, then wait + for the rest, which come only as the slow reader makes room.""" + got = [await fast.receive() for _ in range(3)] + three_read.set() + return len(got) + len(await fast.collect()) + + fast_reading = asyncio.ensure_future(fast_consumer()) + await three_read.wait() await asyncio.sleep(0.01) sent_while_slow_is_full = len(sent) - starved = asyncio.ensure_future(fast.receive()) - await asyncio.sleep(0.01) - fast_waits_for_the_slow_reader = not starved.done() - - async def rest_of_fast() -> int: - return 1 + len(await fast.collect()) if await starved else 0 - - rest, slow_batches = await asyncio.gather(rest_of_fast(), slow.collect()) + fast_waits_for_the_slow_reader = not fast_reading.done() + slow_batches = await slow.collect() + fast_total = await fast_reading await producer return ( sent_while_slow_is_full, fast_waits_for_the_slow_reader, - len(got_fast) + rest, + fast_total, len(slow_batches), ) @@ -996,9 +1691,18 @@ async def write() -> list[BaseException]: output = OutputChannel(stream, retain=retain) unread, waiting, barrier = (output.open_reader() for _ in range(3)) await output.send(batches[0]) - _ = await waiting.receive() - blocked = asyncio.ensure_future(waiting.receive()) - whole = asyncio.ensure_future(barrier.to_stream()) + first_read = asyncio.Event() + + async def waiting_consumer() -> Any: + """The reader's one consumer: read a batch, signal, then wait for the next, + which the producer's failure ends.""" + _ = await waiting.receive() + first_read.set() + return await waiting.receive() + + blocked = asyncio.ensure_future(waiting_consumer()) + await first_read.wait() + whole = asyncio.ensure_future(channel_to_stream(barrier)) await asyncio.sleep(0) output.fail(boom) output.fail(RuntimeError("a second failure changes nothing")) @@ -1033,7 +1737,7 @@ async def write() -> int: await output.send(batch) await output.close() output.fail(OSError("too late")) - return (await output.open_reader().to_stream()).as_table().num_rows + return (await channel_to_stream(output.open_reader())).as_table().num_rows assert run(write) == 7 @@ -1044,7 +1748,7 @@ async def write() -> int: def execute( op: StaticOutputOperatorPod, streams: Sequence[Any], - inputs: Callable[[], Awaitable[list[InputChannel]]], + inputs: Callable[[], Awaitable[list[RecordBatchInput]]], ) -> OutputChannel: """Run ``op`` over input channels; return its output channel.""" @@ -1074,7 +1778,7 @@ def test_an_operator_fails_its_output_when_its_input_failed( batches = batches_of(stream, 2) op = make_op() - async def inputs() -> list[InputChannel]: + async def inputs() -> list[RecordBatchInput]: feed = OutputChannel(stream) await feed.send(batches[0]) feed.fail(OSError("disk gone")) @@ -1134,15 +1838,15 @@ def test_an_operator_reads_its_input_to_the_end_and_closes_its_output() -> None: stream = source() op = SelectDataColumns(["subject", "trial", "note"]) - async def inputs() -> list[InputChannel]: - return [channel_from_stream(stream)] + async def inputs() -> list[RecordBatchInput]: + return [stream.open_channel()] output = execute(op, [stream], inputs) assert same(output.result().as_table(columns=ALL), R(op(stream))) def test_stream_from_batches_is_the_one_conversion() -> None: - """``result()`` and ``to_stream()`` are ``stream_from_batches``: its table equals the + """``result()`` and ``channel_to_stream`` are ``stream_from_batches``: its table equals the rows' table for every way the batches are cut, and no batch gives zero rows.""" stream = source() for rows in (1, 2, 5, 7): diff --git a/tests/test_core/operators/test_record_batch_execution.py b/tests/test_core/operators/test_record_batch_execution.py index c47c11a3c..568b44975 100644 --- a/tests/test_core/operators/test_record_batch_execution.py +++ b/tests/test_core/operators/test_record_batch_execution.py @@ -4,7 +4,7 @@ (``async_execute_batches``) reads input channels opened from streams and writes an output channel, which closes into a stream. An operator whose output rows each come from one input row is applied to every record batch as it arrives; every other -operator reads all of its inputs first (``InputChannel.to_stream``) and then runs the +operator reads all of its inputs first (``channel_to_stream``) and then runs the sync call; ``Batch`` batches consecutive arrivals. For every case of the async/sync matrix (``test_async_sync_equivalence.CASES``) the @@ -27,19 +27,22 @@ import pyarrow as pa import pytest +import orcapod.contexts as contexts import orcapod.core.operators as operators from orcapod.core.operators import AddTags, Batch, PolarsFilter, SelectDataColumns from orcapod.core.operators.static_output_pod import ( StaticOutputOperatorPod, stream_from_batches, ) -from orcapod.core.record_batch_channels import ( - InputChannel, - OutputChannel, - channel_from_stream, -) +from orcapod.core.record_batch_channels import OutputChannel +from orcapod.protocols.core_protocols.streams import RecordBatchInput from orcapod.channels import ChannelClosed from orcapod.core.streams import ArrowTableStream +from orcapod.databases import InMemoryArrowDatabase +from orcapod.pipeline import SyncPipelineOrchestrator +from orcapod.pipeline.job import PipelineJob +from orcapod.system_constants import constants +from tests.test_core.operators.test_rejoin import other_context # noqa: F401 # the fixture from orcapod.errors import UpstreamFailedError from orcapod.protocols.core_protocols import StreamProtocol from tests.test_core.operators.test_async_sync_equivalence import ( @@ -83,11 +86,11 @@ def _cut(table: pa.Table, sizes: tuple[int, ...] | None) -> list[pa.RecordBatch] async def _channel( stream: StreamProtocol, sizes: tuple[int, ...] | None -) -> InputChannel: +) -> RecordBatchInput: """An input channel delivering ``stream``'s rows in record batches of ``sizes``.""" - batches = await channel_from_stream(stream).collect() + batches = await stream.open_channel().collect() if sizes is None or not batches: - return channel_from_stream(stream) + return stream.open_channel() rows = pa.Table.from_batches(batches) feed = OutputChannel(stream) for batch in _cut(rows, sizes): @@ -263,7 +266,7 @@ def test_a_row_by_row_operator_sends_each_batch_as_it_arrives(case: Case) -> Non assert expected is not None async def go() -> list[pa.RecordBatch]: - rows = pa.Table.from_batches(await channel_from_stream(source).collect()) + rows = pa.Table.from_batches(await source.open_channel().collect()) inputs = _cut(rows, (1,)) wanted = [ case.make_op()(stream_from_batches(source, [batch])).as_table().num_rows @@ -279,11 +282,15 @@ async def go() -> list[pa.RecordBatch]: await asyncio.wait_for(feed.send(batch), TIMEOUT) if rows_wanted: # This row's result arrives before the next row is sent. - result = await asyncio.wait_for(results.receive(), TIMEOUT) + # asyncio.timeout, not wait_for: on Python 3.11 wait_for reads in + # another task, and a reader has one consumer. + async with asyncio.timeout(TIMEOUT): + result = await results.receive() assert result.num_rows == rows_wanted received.append(result) await feed.close() - assert await asyncio.wait_for(results.collect(), TIMEOUT) == [] + async with asyncio.timeout(TIMEOUT): + assert await results.collect() == [] await asyncio.wait_for(task, TIMEOUT) return received @@ -321,15 +328,17 @@ async def go() -> tuple[int, int]: output = OutputChannel(op(source)) results = output.open_reader() task = asyncio.ensure_future(op.async_execute_batches([reader], output)) - rows = pa.Table.from_batches(await channel_from_stream(source).collect()) + rows = pa.Table.from_batches(await source.open_channel().collect()) one_row = _cut(rows, (1,)) await feed.send(one_row[0]) await feed.send(one_row[1]) - first = await asyncio.wait_for(results.receive(), TIMEOUT) + async with asyncio.timeout(TIMEOUT): + first = await results.receive() assert not task.done() await feed.send(one_row[2]) await feed.close() - rest = await asyncio.wait_for(results.collect(), TIMEOUT) + async with asyncio.timeout(TIMEOUT): + rest = await results.collect() await task return first.num_rows, sum(batch.num_rows for batch in rest) @@ -386,28 +395,28 @@ def _outcome(make: Callable[[], StreamProtocol]) -> tuple[str, Any]: def test_a_barrier_operator_sees_its_input_as_a_job_gives_it(label: str) -> None: """The record-batch form is held to what a job's sync path gives an operator: the upstream rebuilt from its rows (``_materialize_upstream``: ``null`` as - ``large_string``, the columns in row order), not the raw stream it came from. A + ``large_string``, the columns in row order), not the raw stream it came from, in + every layout: ``channel_to_stream`` rebuilds what the channel delivered. A predicate that reads a ``null`` column's type or the column order follows that form (documented behaviour, e5); in a job neither case reaches an operator: a source refuses a ``null`` column, and a job refuses an expression that selects columns by position.""" make_stream, make_op = BARRIER_ORACLE_CASES[label] stream = make_stream() - oracle = _outcome( + job_sync = _outcome( lambda: make_op()( StaticOutputOperatorPod._materialize_upstream( # pyright: ignore[reportPrivateUsage] # the job's sync input list(stream.iter_data()), stream ) ) ) - assert _outcome(lambda: run_on_channels(make_op(), [stream], None)) == oracle - for layout in ("one_row_per_batch", "mixed_sizes"): + # The raw stream gives another outcome: the case tells the two oracles apart. + assert _outcome(lambda: make_op()(stream)) != job_sync + for layout in LAYOUTS: assert ( _outcome(lambda: run_on_channels(make_op(), [stream], LAYOUTS[layout])) - == oracle + == job_sync ) - # The raw stream gives another outcome: the case tells the two oracles apart. - assert _outcome(lambda: make_op()(stream)) != oracle # --- Arrivals from another producer ------------------------------------------------------- @@ -519,7 +528,7 @@ def test_a_meta_column_does_not_travel() -> None: assert expected is not None async def go() -> tuple[list[str], StreamProtocol]: - batches = await channel_from_stream(raw).collect() + batches = await raw.open_channel().collect() output = OutputChannel(raw) for batch in batches: await output.send(batch) @@ -549,7 +558,7 @@ def test_an_input_closed_early_fails_a_streaming_operator( op = make_op() async def go() -> None: - rows = pa.Table.from_batches(await channel_from_stream(source).collect()) + rows = pa.Table.from_batches(await source.open_channel().collect()) first, second = _cut(rows, (1,))[:2] feed = OutputChannel(source, retain=False, buffer_size=4) reader = feed.open_reader() @@ -670,9 +679,10 @@ async def go() -> None: output = _FailingClose(op(source)) results = output.open_reader() with pytest.raises(OSError, match="flush failed"): - await op.async_execute_batches([channel_from_stream(source)], output) + await op.async_execute_batches([source.open_channel()], output) with pytest.raises(UpstreamFailedError): - _ = await asyncio.wait_for(results.collect(), TIMEOUT) + async with asyncio.timeout(TIMEOUT): + _ = await results.collect() asyncio.run(go()) @@ -684,7 +694,7 @@ def test_every_input_is_closed_when_one_close_fails() -> None: op = operators.SemiJoin() async def go() -> None: - first, second = channel_from_stream(left), channel_from_stream(right) + first, second = left.open_channel(), right.open_channel() async def failing_close() -> None: raise OSError("cannot close") @@ -729,3 +739,59 @@ def test_drop_tag_columns_over_three_tags_sends_its_result() -> None: assert expected is not None result = run_on_channels(operators.DropTagColumns(["a"]), [stream], None) assert_same_table(result.as_table(columns=ALL), expected) + + +# --- A barrier over a job's own nodes ------------------------------------------------------ + + +def test_rejoin_over_job_nodes_with_rows_of_two_data_contexts( + other_context: contexts.DataContext, # noqa: F811 # the fixture, by name +) -> None: + """``Rejoin`` of a job's source node with a renaming branch held from the run, rows + in two data contexts: reading the source node's channel rebuilds its rows in the + row-built form (never its raw table with its own context column), so the result + has both rows, as the sync run does.""" + table = pa.table( + { + "k": pa.array([1, 2], pa.int64()), + "x": pa.array([1.0, 2.0], pa.float64()), + "y": pa.array([3, 4], pa.int64()), + "source_id::a": pa.array(["s", "s"], pa.large_string()), + "record_id::a": pa.array(["r0", "r1"], pa.large_string()), + constants.CONTEXT_KEY: pa.array( + [contexts.get_default_context().context_key, other_context.context_key], + pa.large_string(), + ), + } + ) + table = table.cast( + pa.schema( + [ + f.with_nullable(False) if f.name.endswith("::a") else f + for f in table.schema + ] + ) + ) + raw = ArrowTableStream( + table, tag_columns=["k"], system_tag_columns=["source_id::a", "record_id::a"] + ) + job = PipelineJob(name="rejoin-contexts", database=InMemoryArrowDatabase()) + with job: + branch = operators.MapData({"x": "u", "y": "v"})(raw, label="branch") + _ = operators.Rejoin()(raw, branch, label="rejoin") + _ = job.run(orchestrator=SyncPipelineOrchestrator()) + rejoin = job.nodes["rejoin"] + assert rejoin.as_table().num_rows == 2 + upstreams = rejoin.upstreams + + async def go() -> StreamProtocol: + op = operators.Rejoin() + output = OutputChannel(op(*upstreams)) + await op.async_execute_batches([u.open_channel() for u in upstreams], output) + return output.result() + + result = asyncio.run(go()) + assert result.as_table().num_rows == 2 + assert sorted(map(str, result.as_table().to_pylist())) == sorted( + map(str, rejoin.as_table().to_pylist()) + ) From a3d90a5ff3e29c7b784115bda3c46652ecc4528b Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 08:32:42 -0800 Subject: [PATCH 45/86] fix(pipeline): rows built on read off the provably-equal routes (ITL-1360) Codex on PR #485, round 3. One rule closes the class of the last three rounds: the eager whole-table build is used only where it is provably main's result (a transparent bind, an operator's own result, REPLAY of a table F can build). On every other route a node hands on the rows main would hold, as RowsOnRead, whose table main's own row path (_materialize_upstream) builds where the sync orchestrator gives it to a successor (at_edge): a narrower bind (no key re-derivation; its description is its declared schema's, arrow_types_declared false), a whole-table build that is unavailable (the rows read once), REPLAY of a stored table F cannot build, a held node (built at the successor's edge, not kept by the plan), and a function or side-effect node's rows. main's order, error and moment follow by construction; a leaf nobody reads is never built. e9 and e10 are gone: a leaf function node over a store written before ITL-928 completes and its as_table() raises main's InputValidationError, with a successor main's ArrowInvalid surfaces at the edge; ITL-1366's input raises main's ValueError at the successor's edge, sync, async and channel alike. Their tests are equality-with-main tests. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1360.md | 11 +- .../dev/specs/itl-1347-job-table-transport.md | 12 +- src/orcapod/core/nodes/function_node.py | 40 +-- src/orcapod/core/nodes/operator_node.py | 10 +- src/orcapod/core/nodes/source_node.py | 161 +++++------ .../core/operators/static_output_pod.py | 68 +++++ src/orcapod/core/streams/base.py | 10 +- src/orcapod/pipeline/node_run.py | 21 +- src/orcapod/pipeline/sync_orchestrator.py | 8 +- .../test_function_node_arrow_types.py | 92 +++++-- .../test_declared_slot_one_data_tag.py | 34 +-- .../test_pipeline/test_narrower_bind_order.py | 38 +-- tests/test_pipeline/test_rows_on_read.py | 254 ++++++++++++++++++ .../test_stream_transport_equivalence.py | 10 +- 14 files changed, 554 insertions(+), 215 deletions(-) create mode 100644 tests/test_pipeline/test_rows_on_read.py diff --git a/changelog.d/ITL-1360.md b/changelog.d/ITL-1360.md index ce18adf22..6579ccde7 100644 --- a/changelog.d/ITL-1360.md +++ b/changelog.d/ITL-1360.md @@ -6,7 +6,10 @@ successor. It now returns the node's output stream, which the sync orchestrator hands to every successor as it is: a source node gives its source's Arrow table, and an operator node its result's table (REPLAY: its stored table), each in the form a table built from - the rows has, without making the rows. `OrchestratorResult.node_outputs` holds each + the rows has, without making the rows. Where that is not provably the table its rows give + (a narrower bind, a table the whole-table build cannot use, a held node, a function or + side-effect node), the node hands on its rows, built into a table where a successor reads + them, as before. `OrchestratorResult.node_outputs` holds each node's output stream (the async orchestrator builds it when it is first read), and on the sync path a held node gives the stream of its held rows; the async path still sends a held node's rows as the run's plan took them (`held_rows`). Every @@ -15,12 +18,6 @@ table is built once, for what it keeps and for every successor, instead of once to keep and once per successor. The first two stages of the table transport between job nodes (`docs/dev/specs/itl-1347-job-table-transport.md`). (ITL-1347, ITL-1360) -- **A function node whose rows disagree on a column's type fails the run** — rows read from - a store written before ITL-928 (a `uint32` tag read back as `int32`) and rows computed now - cannot make one table. The run now fails at the node with the `InputValidationError` - naming the column and both types that the node's `as_table()` raised before; a node with a - successor used to fail with a bare `ArrowInvalid`, and one without completed the run. Such - a store must be rebuilt. (ITL-1360) ### Added diff --git a/docs/dev/specs/itl-1347-job-table-transport.md b/docs/dev/specs/itl-1347-job-table-transport.md index 3b9203c6a..086097dc3 100644 --- a/docs/dev/specs/itl-1347-job-table-transport.md +++ b/docs/dev/specs/itl-1347-job-table-transport.md @@ -513,9 +513,13 @@ with the developer's approval, given row by row. Each row gets its own test: it row, by name. The developer has accepted some behaviours of `main` that are not listed as rows; they are kept as `main` has them, and documented below. -**No row changes a sync-path result, except e9 and e10** (provisional, pending the developer). On -the sync path the branch equals `main` byte for byte. Stages 1–4 hold this by construction -and by L0–L5, and a lemma that fails stops its stage. +**No row changes a sync-path result.** On the sync path the branch equals `main` byte for +byte. Stages 1–4 hold this by construction and by L0–L5, and a lemma that fails stops its +stage. Where building a node's output from its whole table is not provably `main`'s result +(a narrower bind, a whole-table build that is unavailable, an odd stored table, a held +node, a node whose output is still its rows), the node hands on its rows and the table is +built from them by `main`'s row path where a successor reads them (`RowsOnRead`, +`at_edge`): `main`'s order, error and moment by construction (Codex on PR #485, round 3). | # | What differs | On `main` today | On the branch | Why `main` is wrong (bug, reproducer) | Approval needed | |---|---|---|---|---|---| @@ -525,8 +529,6 @@ and by L0–L5, and a lemma that fails stops its stage. | e6 | Async values that depend on an earlier validation of the same operator object | `SemiJoin._validated_common_keys` and `Index._element_arrow_type_fallback` hold the last validation's values (ITL-858, section 1.2). One operator object applied to two streams can use the other stream's keys or fallback type | Read from each input's description, with no state | The ITL-858 finding; filed as ITL-1358. Reproducer: one `SemiJoin` instance validated on stream B, then run async over stream A with other keys. To be confirmed in stage 5 | ITL-1358 (filed); fixed with stage 5 once a reproducer confirms it | | e7 | What a consumer does after its producer failed (async, failure path) | The producer closes its output in `finally`, so a consumer sees a normal end and may finish, and a `LOG` operator node may store, a partial result before the task group cancels it | Readers raise `UpstreamFailedError` at the failure point instead of seeing a normal end, so no consumer finishes, or stores its result, as if its input were complete. Batches a consumer processed before the failure are still processed, and a streaming node may already have passed them on or a function node stored results for them, as on `main`; there is no rollback. A barrier operator never computes over a partial input. The run raises the producer's own error, as today | A candidate race, to be confirmed with a reproducer in stage 5: a `fail_fast` function node raising on row 3 of 6, feeding a `Select` node in `LOG` mode; check the operator cache after the failed run. If `main` never stores in practice, this row is no difference | filed by the developer only once a test reproduces it | | e8 | Meta columns of an async side-effect node's rows | An async side-effect node passes on and holds the rows it receives as they are, so a computed row keeps its `__computed` meta column (from the cached function pod), and the node's `as_table(all_info=True)` shows it. On sync, its input is rebuilt from rows (`_rows_to_table` drops meta), so the column is absent | Async drops input meta columns as sync does. With table transport this follows from the transport columns, which hold no meta column | A `main` bug: the async and sync paths give the node different columns. Found by the stage 0 harness on `job-speed` 0e15d0db, which does not change side-effect nodes; the stage 0 differential checks it on pinned `main`. Reproducer: a function node (with a result store) feeding a `tap_pod`, async against sync, comparing the side-effect node's `as_table(all_info=True)` columns | approved (developer, 2026-11-22) | -| e9 | A sync function node whose output rows disagree on a column's Arrow type | A node with no successor completes the run; its `as_table()` raises `InputValidationError` ("Function node 'double': Rows disagree on the Arrow type of column 'k': int32 and uint32"). A node with a successor fails the run with a bare pyarrow `ArrowInvalid`, raised where the successor's input is rebuilt | The node builds its output stream when it runs (stage 2), so the run fails at the node, once its writes are committed (a failed write is still reported first, as on `main`) and before the node takes the run, with the `InputValidationError` `as_table()` raises (same type and message), with or without a successor; the node then holds no run. What is stored equals `main`'s: the row computed before the disagreement could be seen is stored, as on `main` (2 stored rows before the run, 3 after, on both) | Not a `main` bug to fix: a consequence of building the output stream in `execute`, and for a node with a successor an improvement (`main`'s `ArrowInvalid` names nothing). It arises only from a store written before ITL-928, whose cached rows give a `uint32` tag back as `int32`; such a store must be rebuilt. Reproducer: `tests/test_core/function_pod/test_function_node_arrow_types.py::test_new_rows_over_a_store_written_before_the_fix_raise_naming_the_column` (leaf and with successor) | provisional, coordinator decision 2026-11-22, pending developer | -| e10 | ITL-1366: a declared source slot over a narrower source with one data-tag among two tags | The run raises `ValueError` ("Duplicate column name 'k'") where the source's rows are rebuilt for its successor (`_rows_to_table`: the row's tag and data both hold the data-tag), when exactly one of the two tags is a data-tag and the tags are declared `j, k`; the source node has ended, the successor never starts. The same on the async path | Sync: the source node hands on F of the declared table (`_DeclaredForm.apply` of the bound table, the data-tag once, among the tags) and the run completes with the rows the bind describes. Async: as on `main` until stage 5 | A `main` bug (ITL-1366): the bind is accepted, then the rows cannot be built. Reproducer: `tests/test_pipeline/test_declared_slot_one_data_tag.py` (no, one or both data-tags, both tag orders, sync and async) | provisional, coordinator decision 2026-11-22, pending developer | **Resolved: refusals after rows have flowed (was c, question 9).** The developer's `Rejoin` rule (ITL-1355) removes every data-dependent refusal from `Rejoin`: it checks only what its diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index de4920088..3f32b20d1 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -285,12 +285,11 @@ def _with_datagram_id(data: Data, datagram_id: uuid.UUID) -> Data: def rows_as_output_stream( rows: Sequence[tuple[TagProtocol, DataProtocol]], node: StreamProtocol ) -> StreamProtocol: - """Return ``rows`` as ``node``'s output stream, as the sync orchestrator built it. + """Return ``rows`` as ``node``'s output stream: the rows, built when read. - ``StaticOutputOperatorPod._materialize_upstream``, for the job nodes whose output is - still their rows (function and side-effect nodes, until ITL-1347 stages 3 and 4): - the rows' table with the node's identity, or its zero-row input with no row. One - place imports the operator module for them. + For the job nodes whose output is still their rows (function and side-effect + nodes, until ITL-1347 stages 3 and 4): ``RowsOnRead``, built by ``main``'s row path + where a successor reads it. One place imports the operator module for them. Args: rows: The node's output rows, in order. @@ -299,9 +298,9 @@ def rows_as_output_stream( Returns: The node's output stream. """ - from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod + from orcapod.core.operators.static_output_pod import RowsOnRead - return StaticOutputOperatorPod._materialize_upstream(rows, node) # pyright: ignore[reportPrivateUsage] # the one definition of a rebuilt upstream + return cast(StreamProtocol, cast(object, RowsOnRead(rows, node))) def _executor_supports_concurrent( @@ -2483,20 +2482,13 @@ def _output_stream( ) -> StreamProtocol: """The output stream of a run whose output rows are ``rows``. - What the sync orchestrator built from a node's rows for its successors - (``StaticOutputOperatorPod._materialize_upstream``): the rows' table with this - node's identity, or the node's zero-row input when there is no row. + The rows, their table built when read by ``main``'s row path + (``RowsOnRead``): the sync orchestrator builds it where a successor reads it, + as ``main`` rebuilt the rows there, and a leaf's is never built (ITL-1347). """ - from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod + from orcapod.core.operators.static_output_pod import RowsOnRead - try: - return StaticOutputOperatorPod._materialize_upstream(rows, self) - except pa.ArrowInvalid: - # Rows that disagree on a column's Arrow type (cached rows of a store - # written before ITL-928): raise what ``as_table`` raises for them, naming - # the node, the column and both types (ITL-1360, e9). - self._table_from_pairs(rows) - raise + return cast(StreamProtocol, cast(object, RowsOnRead(rows, self))) def execute_data( self, @@ -2681,14 +2673,6 @@ def execute( self._commit_or_end_node( self._commit_at_node_end, ctx_obs, node_label, node_hash ) - # The output stream, built once the run is committed (a failed write is - # reported first, as on main) and before the node takes the run: rows that - # cannot make one table fail the run (ITL-1360, e9). - try: - result_stream = self._output_stream(output) - except InputValidationError: - ctx_obs.on_node_end(node_label, node_hash) - raise # The node's rows are those of this run's inputs, whatever else it caches. self._set_run_rows(emitted_entry_ids, failed=failed_rows) # Mark this node as freshly computed before the observer hears the end, so @@ -2705,7 +2689,7 @@ def execute( self.clear_cache() raise - return result_stream + return self._output_stream(output) def _empty_data_cache_hit( self, tag: TagProtocol, data: EmptyData, base_entry_id: bytes diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index be0bd1162..ccdaa6f35 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -40,6 +40,7 @@ from orcapod.config import OrcapodConfig from orcapod.core.operators.static_output_pod import ( RowBuiltFormUnavailable, + RowsOnRead, StaticOutputOperatorPod, ) from orcapod.core.streams.arrow_table_stream import ArrowTableStream @@ -1697,9 +1698,12 @@ def execute( cached_output.keys(), self, ) - except RowBuiltFormUnavailable as error: - StaticOutputOperatorPod._raise_as_rows_do( - cached_output.iter_data(), error + except RowBuiltFormUnavailable: + # A stored table F cannot build from: its rows, built when read, + # as main handed them on (ITL-1347). + output = cast( + StreamProtocol, + cast(object, RowsOnRead(cached_output.iter_data(), self)), ) ctx_obs.on_node_end(node_label, node_hash) return output diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index 8862b6bca..b9467328d 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -15,7 +15,7 @@ import json import logging from abc import ABC, abstractmethod -from collections.abc import AsyncIterator, Collection, Iterator, Mapping, Sequence +from collections.abc import AsyncIterator, Collection, Iterator, Mapping from datetime import datetime from typing import TYPE_CHECKING, Any, cast @@ -162,24 +162,6 @@ def apply(self, table: pa.Table) -> pa.Table: source-info columns in declared order within the positions each group holds. """ - table = self.retype(table) - return table.select(self._declared_positions(table.column_names)) - - def retype(self, table: pa.Table) -> pa.Table: - """Return *table*'s arrays under the declared fields, in *table*'s column order. - - The fields ``apply`` gives (the columns in ``nullable`` flagged nullable, the - columns in ``renames`` renamed), without placing the columns: a table whose - columns are then selected by the rows' keys (the row-built form, ITL-1347) - needs no placement, and a table holding a data-tag once, among the tags, would - lose a column to a placement made for a row's separate tag and data tables. - - Args: - table: Rows read from the bound source. - - Returns: - The same arrays under the declared fields. - """ schema = table.schema for position, field in enumerate(table.schema): if field.name in self.nullable: @@ -188,7 +170,8 @@ def retype(self, table: pa.Table) -> pa.Table: field = field.with_name(self.renames[field.name]) schema = schema.set(position, field) # pyright: ignore[reportUnknownMemberType] # stubs leave Field unparametrized # Same arrays under the declared fields: no cast, so no value or type changes. - return pa.Table.from_arrays(table.columns, schema=schema) + table = pa.Table.from_arrays(table.columns, schema=schema) + return table.select(self._declared_positions(table.column_names)) def _declared_positions(self, names: list[str]) -> list[int]: """Return the column positions of *names* with each group in declared order. @@ -210,18 +193,6 @@ def _declared_positions(self, names: list[str]) -> list[int]: return order -def _each_once(order: Sequence[str], names: Sequence[str]) -> tuple[str, ...]: - """``order`` with each of ``names`` once: repeats dropped, missing names appended. - - ``_DeclaredForm.apply`` places a row's columns; with one data-tag among two tags it - can place a column twice and lose another (ITL-1366, where ``main`` then fails to - build the rows). The keys keep its order and hold each name once (spec row e10). - """ - wanted = set(names) - kept = tuple(dict.fromkeys(n for n in order if n in wanted)) - return (*kept, *(n for n in names if n not in kept)) - - def _system_tag_columns( source: StreamProtocol, tag_names: Collection[str] ) -> tuple[list[str], list[str], list[str]]: @@ -1279,10 +1250,14 @@ def iter_data(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: """Yield ``(tag, data)`` pairs, or raise if data is unavailable.""" ... - def _rows_table(self) -> tuple[pa.Table, tuple[tuple[str, ...], tuple[str, ...]]]: + def _rows_table( + self, + ) -> tuple[pa.Table, tuple[tuple[str, ...], tuple[str, ...]]] | None: """The table of this node's rows (``iter_data``) and the rows' keys. - Here this node's own table (``ZERO_ROW_INPUT_COLUMNS``) and keys. + Here this node's own table (``ZERO_ROW_INPUT_COLUMNS``) and keys. ``None`` where + F of a table is not provably the rows' own table: the node then hands on its + rows (``RowsOnRead``). """ stream = cast("StreamProtocol", self) table = stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS) @@ -1328,6 +1303,7 @@ def execute( """ from orcapod.core.operators.static_output_pod import ( RowBuiltFormUnavailable, + RowsOnRead, StaticOutputOperatorPod, ) @@ -1335,18 +1311,19 @@ def execute( node_hash = self.content_hash().to_string() if observer is not None: observer.on_node_start(node_label, node_hash) - # The table and keys of this node's rows: a slot's own key order can differ - # from its source's. - table, keys = self._rows_table() - try: - result = StaticOutputOperatorPod._output_stream(table, keys, self) - except RowBuiltFormUnavailable as error: - # Rows whose source-info tokens cannot make one table: the node has read - # its rows, and the run fails where its rows are handed on, raising what - # their concatenation raises. - if observer is not None: - observer.on_node_end(node_label, node_hash) - StaticOutputOperatorPod._raise_as_rows_do(self.iter_data(), error) + # The table and keys of this node's rows, when F of the table is provably the + # rows' own table; otherwise (a narrower bind) the rows, built when read. + rows_table = self._rows_table() + result: StreamProtocol + if rows_table is None: + result = cast("StreamProtocol", RowsOnRead(self.iter_data(), self)) + else: + table, keys = rows_table + try: + result = StaticOutputOperatorPod._output_stream(table, keys, self) + except RowBuiltFormUnavailable: + # The rows decide (read once, here), built when read, as on main. + result = cast("StreamProtocol", RowsOnRead(self.iter_data(), self)) if observer is not None: observer.on_node_end(node_label, node_hash) return result @@ -1808,63 +1785,46 @@ def identity_structure(self) -> Any: return self._bound_source.identity_structure() return super().identity_structure() - def _row_keys( - self, table: pa.Table | None = None - ) -> tuple[tuple[str, ...], tuple[str, ...]]: - """The tag and data keys of this node's rows, as ``iter_data`` gives them. - - The bound source's rows have the keys of its table (``keys_of_rows``). A - narrower source's rows are given as the declared schema one by one - (``_declared_row``: its tag table and its data table each through - ``_DeclaredForm.apply``), so their keys are those of a zero-row tag table and a - zero-row data table of the bound source through the same ``apply``: a tag that - is also data takes its place from the declared data order, as on ``main``. - - Args: - table: The bound source's table (``ZERO_ROW_INPUT_COLUMNS``, with or - without rows). Default: its typed zero-row table, which reads no row; - the declared keys when it cannot say its types without rows. + def _row_keys(self) -> tuple[tuple[str, ...], tuple[str, ...]]: + """The tag and data keys of this node's rows, known without reading a row. - Returns: - The tag keys and the data keys of the rows. + The bound source's rows have the keys of its table (``keys_of_rows``, over its + typed zero-row table, which reads no row). A narrower bind (``_DeclaredForm``) + and an unbound slot answer with the slot's own keys: their description reports + its types undeclared (``arrow_types_declared``). """ - if self._bound_source is None: + if self._bound_source is None or self._declared_form is not None: return self.keys() - bound_keys = self._bound_source.keys() + table = typed_zero_row_input(self._bound_source) if table is None: - table = typed_zero_row_input(self._bound_source) - if table is None: - return self.keys() - rows_keys = keys_of_rows(table, bound_keys) - form = self._declared_form - if form is None: - return rows_keys - tag_keys, data_keys = rows_keys - names = table.column_names - system_tags = [n for n in names if n.startswith(constants.SYSTEM_TAG_PREFIX)] - source_info = [n for n in names if n.startswith(constants.SOURCE_PREFIX)] - empty = table.slice(0, 0) - tag_order = form.apply(empty.select([*tag_keys, *system_tags])).column_names - data_order = form.apply(empty.select([*data_keys, *source_info])).column_names - return ( - _each_once( - [n for n in tag_order if not n.startswith(constants.SYSTEM_TAG_PREFIX)], - tag_keys, - ), - _each_once( - [n for n in data_order if not n.startswith(constants.SOURCE_PREFIX)], - data_keys, - ), - ) + return self.keys() + return keys_of_rows(table, self._bound_source.keys()) - def _rows_table(self) -> tuple[pa.Table, tuple[tuple[str, ...], tuple[str, ...]]]: - """The table of this node's rows (``iter_data``) and the rows' keys. + def arrow_schema(self) -> pa.Schema: + """The Arrow schema of the columns this stream passes between job nodes. + + See ``stream_arrow_schema``. A narrower bind hands on its rows as ``main`` gives + them (``RowsOnRead``), so its description is the declared Python schema's + (``arrow_types_declared`` is false): no second placement rule. + """ + if self._declared_form is not None: + return stream_arrow_schema(self, self.keys(), typed=False) + return stream_arrow_schema(self, self._row_keys()) - The bound source's table and keys; for a narrower source, the source's table - given as the declared schema (``_DeclaredForm.apply``, which serves a whole - table as it serves each row in ``_declared_rows``) with the declared keys - (``_row_keys``). Its data-tags keep their source info, as each declared row - does. + @property + def arrow_types_declared(self) -> bool: + """False for a narrower bind (see ``arrow_schema``), else as every source node.""" + if self._declared_form is not None: + return False + return super().arrow_types_declared + + def _rows_table( + self, + ) -> tuple[pa.Table, tuple[tuple[str, ...], tuple[str, ...]]] | None: + """The bound source's table and the keys of its rows (``keys_of_rows``). + + ``None`` for a narrower bind: its rows are given as the declared schema one by + one (``_declared_rows``), so the node hands on those rows (``RowsOnRead``). Raises: UnboundSourceError: When no concrete source is attached. @@ -1874,11 +1834,10 @@ def _rows_table(self) -> tuple[pa.Table, tuple[tuple[str, ...], tuple[str, ...]] f"SourceJobNode '{self._name}' has no concrete source bound. " "Call job.bind(sources={'': source}) before running." ) + if self._declared_form is not None: + return None table = self._bound_source.as_table(columns=ZERO_ROW_INPUT_COLUMNS) - keys = self._row_keys(table) - if self._declared_form is None: - return table, keys - return self._declared_form.retype(table), keys + return table, keys_of_rows(table, self._bound_source.keys()) def iter_data(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: """Delegate to concrete source, or raise if unbound. diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index a815101be..f9017efd0 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -1353,6 +1353,74 @@ def with_open_provenance_flags(batch: pa.RecordBatch) -> pa.RecordBatch: return pa.RecordBatch.from_arrays(batch.columns, schema=schema) +class RowsOnRead: + """A node's output held as its rows, its table built on first read (ITL-1347). + + The one rule for every route where building the output from the whole table is + not provably ``main``'s result (a narrower bind, a whole-table build that is + unavailable, an odd stored table, a held node, a node whose output is still its + rows): the node hands on the rows ``main`` would hold, and the table is built from + them by ``main``'s own row path (``StaticOutputOperatorPod._materialize_upstream``) + when the stream is first read. The sync orchestrator reads each input of a node + before running it (``at_edge``), where ``main`` rebuilt it; a stream nobody reads + is never built, as ``main`` never rebuilt a leaf's rows. Every attribute is the + built stream's. + """ + + # Not a stream the row-built form already made: a channel opened on it reads it. + _orcapod_row_built_output = False + + def __init__( + self, rows: Sequence[tuple[TagProtocol, DataProtocol]], node: StreamProtocol + ) -> None: + """Hold ``node``'s rows; nothing is built. + + Args: + rows: The rows ``main`` would hold, in order (read once, here). + node: The node (or stream) whose output they are. + """ + self._rows: list[tuple[TagProtocol, DataProtocol]] | None = list(rows) + self._node = node + self._stream: StreamProtocol | None = None + + def built(self) -> StreamProtocol: + """The stream, built from the rows on the first call (``main``'s row path).""" + if self._stream is None: + rows = self._rows if self._rows is not None else [] + self._stream = StaticOutputOperatorPod._materialize_upstream( + rows, self._node + ) + self._rows = None + return self._stream + + def __getattr__(self, name: str) -> Any: + return getattr(self.built(), name) + + def __iter__(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: + return iter(self.built().iter_data()) + + def __repr__(self) -> str: + return f"RowsOnRead({short_stream_repr(self._node)})" + + +def at_edge(stream: StreamProtocol) -> StreamProtocol: + """``stream`` as a node's input: a ``RowsOnRead`` output is built here. + + The sync orchestrator reads every input of a node before it runs the node, where + ``main`` rebuilt the rows of the node before it, so an error of that build surfaces + at the same point, after the same observer events. + + Args: + stream: An output a node handed on. + + Returns: + The stream to give the node. + """ + if isinstance(stream, RowsOnRead): + return stream.built() + return stream + + class _RowsOfStream(ArrowTableStream): """Rows standing in for the stream they came from, with its pipeline hash. diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py index bebc82ad2..46293426c 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -364,7 +364,10 @@ def keys_of_rows( def stream_arrow_schema( - stream: object, keys: tuple[Sequence[str], Sequence[str]] | None = None + stream: object, + keys: tuple[Sequence[str], Sequence[str]] | None = None, + *, + typed: bool = True, ) -> pa.Schema: """Return ``stream``'s declared Arrow schema: what ``arrow_schema()`` answers (ITL-1347). @@ -389,6 +392,9 @@ def stream_arrow_schema( stream: The stream, source or node. keys: The tag and data keys of the stream's rows, when they differ from ``keys()`` (a source slot gives its bound source's rows); default ``keys()``. + typed: Take the stream's typed zero-row table (``typed_zero_row_input``); + ``False`` describes it from its declared Python schema only (a narrower + bind, whose rows ``main``'s row path places). Returns: The declared Arrow schema. @@ -397,7 +403,7 @@ def stream_arrow_schema( typed = cast(StreamProtocol, stream) given_keys = keys - table = typed_zero_row_input(stream) + table = typed_zero_row_input(stream) if typed else None if table is None and schema_requires_io(stream, ColumnConfig(system_tags=True)): # Nothing declared, nothing polled (a poller with no declared schema): the # columns are known only from rows, and a description never polls. No column, diff --git a/src/orcapod/pipeline/node_run.py b/src/orcapod/pipeline/node_run.py index f39f403c6..49a035b4a 100644 --- a/src/orcapod/pipeline/node_run.py +++ b/src/orcapod/pipeline/node_run.py @@ -243,6 +243,13 @@ def check_sources(streams: Iterable[Any]) -> tuple[str, ...]: return tuple(unchecked) +def _rows_on_read(rows: Sequence[Any], node: Any) -> Any: + """A held node's output: its rows, built where a successor reads them (``RowsOnRead``).""" + from orcapod.core.operators.static_output_pod import RowsOnRead + + return RowsOnRead(rows, node) + + @dataclass(frozen=True) class RunPlan: """What a run does with each node of its graph (ITL-1095). @@ -252,7 +259,7 @@ class RunPlan: them (a source slot is read; any other one is held). held: The output stream of each held node of ``dag``: of its current run, or of a stream outside the job; it feeds the nodes after it as if the node had - just run (the sync orchestrator). Built when read (``StreamsOnRead``). + just run (the sync orchestrator). Built when read (``RowsOnRead``). held_rows: The rows of each held node, as the plan took them; ``held`` is built from them. The async orchestrator sends them (it carries rows until ITL-1347 stage 5). @@ -337,8 +344,6 @@ def is_source(node: Any) -> bool: for node in to_run: for upstream in graph.predecessors(node): dag.add_edge(upstream, node) - from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod - # A held node's output stream: what the sync orchestrator built from its rows for # the nodes after it, exactly (ITL-1347, stage 2). held_rows = { @@ -346,11 +351,11 @@ def is_source(node: Any) -> bool: for node in included if not any(node is r for r in to_run) and not is_source(node) } - # Built when the sync orchestrator reaches the node, never while planning (an - # async run reads only the rows), and not kept by the plan (ITL-1360). - held = StreamsOnRead( - held_rows, StaticOutputOperatorPod._materialize_upstream, keep=False - ) + # The rows main held, built where a successor reads them (``RowsOnRead``, + # ``at_edge``), never while planning; an async run reads only the rows. + # The plan keeps no output it handed out (``keep=False``): the orchestrator drops + # each once the node's successors ran. + held = StreamsOnRead(held_rows, _rows_on_read, keep=False) # Counted from what each node holds: iterating an operator's rows would build a # (Tag, Data) pair per row only to count them (ITL-1351). held_counts = {node: node.held_row_count() for node in current} diff --git a/src/orcapod/pipeline/sync_orchestrator.py b/src/orcapod/pipeline/sync_orchestrator.py index 553307bfa..523322fa4 100644 --- a/src/orcapod/pipeline/sync_orchestrator.py +++ b/src/orcapod/pipeline/sync_orchestrator.py @@ -170,7 +170,9 @@ def _single_input( raise ValueError( f"FunctionNode expects exactly 1 upstream, got {len(predecessors)}" ) - return outputs[predecessors[0]] + from orcapod.core.operators.static_output_pod import at_edge + + return at_edge(outputs[predecessors[0]]) @staticmethod def _ordered_inputs( @@ -185,7 +187,9 @@ def _ordered_inputs( predecessors, key=lambda p: upstream_order.get(id(p), 0), ) - return [outputs[p] for p in sorted_preds] + from orcapod.core.operators.static_output_pod import at_edge + + return [at_edge(outputs[p]) for p in sorted_preds] @staticmethod def _gc_outputs( diff --git a/tests/test_core/function_pod/test_function_node_arrow_types.py b/tests/test_core/function_pod/test_function_node_arrow_types.py index 4d27611ef..bd76bc8a5 100644 --- a/tests/test_core/function_pod/test_function_node_arrow_types.py +++ b/tests/test_core/function_pod/test_function_node_arrow_types.py @@ -296,41 +296,48 @@ def _as_written_before_the_fix(root: pathlib.Path) -> None: ) -@pytest.mark.parametrize("chained", [False, True], ids=["leaf", "with_successor"]) def test_new_rows_over_a_store_written_before_the_fix_raise_naming_the_column( - chained: bool, tmp_path: pathlib.Path + tmp_path: pathlib.Path, ) -> None: """Rows of one node never make a column of a type none of them has. A Delta database written before ITL-928 gives a ``uint32`` tag back as ``int32``: rows served from it and rows computed now disagree, and the node says so instead - of picking a type. Such a database must be rebuilt. - - The run fails at the node, with the error ``as_table`` raises for such rows (main - raised it only on a later read of a node with no successor, and a bare - ``ArrowInvalid`` in the run of one with a successor; ITL-1360, difference e9). The - node then holds no run. + of picking a type. Such a database must be rebuilt. A leaf's run completes (its + rows are never built into one table, ``RowsOnRead``), as on ``main``. """ - _build( - DeltaTableDatabase(tmp_path), - _source_table("uint32").slice(0, 2), - chained=chained, - ).run() + _build(DeltaTableDatabase(tmp_path), _source_table("uint32").slice(0, 2)).run() _as_written_before_the_fix(tmp_path) - job = _build(DeltaTableDatabase(tmp_path), _source_table("uint32"), chained=chained) + job = _build(DeltaTableDatabase(tmp_path), _source_table("uint32")) + job.run() with pytest.raises(InputValidationError) as raised: - job.run() + job.nodes["double"].as_table() message = str(raised.value) - assert message.startswith("Function node 'double': ") assert "'k'" in message assert "int32" in message assert "uint32" in message - # A run that raised defines no rows. - assert job.nodes["double"].as_table().num_rows == 0 - # What is stored is what main stores: the row computed before the disagreement - # could be seen stays written, as after any failure, next to the two old rows. + + +def test_rows_over_a_store_written_before_the_fix_fail_at_the_successor( + tmp_path: pathlib.Path, +) -> None: + """With a successor, the run fails where the rows are built for it, as on ``main``. + + The node's rows are built into one table where its successor reads them + (``at_edge``): the concatenation raises ``ArrowInvalid`` there, as ``main``'s row + rebuild does. The computed row is stored, as on ``main``. + """ + _build( + DeltaTableDatabase(tmp_path), _source_table("uint32").slice(0, 2), chained=True + ).run() + _as_written_before_the_fix(tmp_path) + job = _build(DeltaTableDatabase(tmp_path), _source_table("uint32"), chained=True) + + with pytest.raises(pa.ArrowInvalid): + job.run() + stored = _build(DeltaTableDatabase(tmp_path), _source_table("uint32")) records = stored.nodes["double"].get_all_records() assert records is not None @@ -457,3 +464,48 @@ def on_data_start(self, node_label: str, tag: Any, data: Any) -> None: summary = job.run(orchestrator=AsyncPipelineOrchestrator(), observer=observer) assert summary.nodes["double"].held == 3 assert observer.count == 3 + + +def test_a_held_nodes_rows_are_built_at_its_successors_edge( + tmp_path: pathlib.Path, +) -> None: + """A held node's rows are built where its successor reads them, as on ``main``. + + A direct sync run: ``double`` held (its rows cannot make one table), an independent + source, then ``increment`` after ``double``. The independent source runs before + ``increment``'s input is built and raises (Codex on PR #485, round 3). + """ + from orcapod.core.operators.static_output_pod import RowsOnRead + from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator + from orcapod.pipeline.dag import OrcaDAG + from orcapod.pipeline.observer import NoOpObserver + + _build( + DeltaTableDatabase(tmp_path), _source_table("uint32").slice(0, 2), chained=True + ).run() + _as_written_before_the_fix(tmp_path) + job = _build(DeltaTableDatabase(tmp_path), _source_table("uint32"), chained=True) + job.run(orchestrator=AsyncPipelineOrchestrator()) + double, increment = job.nodes["double"], job.nodes["increment"] + increment.clear_cache() + independent = _build(InMemoryArrowDatabase(), _source_table("uint32")).nodes["src"] + + starts: list[str] = [] + + class Starts(NoOpObserver): + def contextualize(self, *identity_path: str) -> Starts: + return self + + def on_node_start( + self, node_label: str, node_hash: str, tag_schema: Any = None + ) -> None: + starts.append(node_label) + + dag: OrcaDAG[Any] = OrcaDAG() + dag.add_node(double) + dag.add_node(independent) + dag.add_edge(double, increment) + held = {double: RowsOnRead(list(double.iter_data()), double)} + with pytest.raises(pa.ArrowInvalid): + SyncPipelineOrchestrator().run(dag, observer=Starts(), held=held) + assert starts == ["src"] diff --git a/tests/test_pipeline/test_declared_slot_one_data_tag.py b/tests/test_pipeline/test_declared_slot_one_data_tag.py index 490c5f006..88fcc4045 100644 --- a/tests/test_pipeline/test_declared_slot_one_data_tag.py +++ b/tests/test_pipeline/test_declared_slot_one_data_tag.py @@ -1,14 +1,13 @@ -"""A declared slot over a narrower source with one data-tag among two tags (ITL-1366, e10). +"""A declared slot over a narrower source with one data-tag among two tags (ITL-1366). A source slot declared from a source whose ``x`` is ``int | None``, bound to the same table with ``x: int`` (a narrower source, given as the declared schema), feeding an operator. On ``main`` the run raises ``ValueError`` ("Duplicate column name") where the source's rows are rebuilt for its successor, when exactly one of the two tags is a -data-tag and the tags are declared ``j, k``. On the sync path the branch hands on the -declared table itself (F over ``_DeclaredForm.apply`` of the bound table), and the run -completes with the rows the bind describes (spec row e10; provisional, coordinator -decision 2026-11-22, pending the developer). The async path still carries rows until -ITL-1347 stage 5 and raises as ``main`` does. +data-tag and the tags are declared ``j, k`` (ITL-1366, a ``main`` bug fixed there +separately). A narrower bind hands on its rows as ``main`` gives them (``RowsOnRead``), +built where the successor reads them: the branch raises the same error at the same +point, on the sync and the async path, and completes every other arrangement. """ from __future__ import annotations @@ -68,26 +67,21 @@ def _rows(job: PipelineJob) -> list[dict[str, Any]]: return sorted(table.to_pylist(), key=lambda row: row["j"]) +@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"]) @pytest.mark.parametrize("roles", list(ROLES), ids=list(ROLES)) @pytest.mark.parametrize("order", [("j", "k"), ("k", "j")], ids=["j-k", "k-j"]) -def test_the_sync_run_completes_with_the_rows_the_bind_describes( - order: tuple[str, str], roles: str +def test_the_run_is_as_on_main( + order: tuple[str, str], roles: str, asynchronous: bool ) -> None: - """Every arrangement runs on the sync path and gives the bound table's rows.""" - job = _bound_job(order, ROLES[roles]) - job.run() - assert _rows(job) == ROWS - - -@pytest.mark.parametrize("roles", list(ROLES), ids=list(ROLES)) -@pytest.mark.parametrize("order", [("j", "k"), ("k", "j")], ids=["j-k", "k-j"]) -def test_the_async_run_is_as_on_main(order: tuple[str, str], roles: str) -> None: - """The async path carries rows until stage 5: it raises where ``main`` raises.""" + """Raises where ``main`` raises (ITL-1366), else gives the bound table's rows.""" job = _bound_job(order, ROLES[roles]) + kwargs: dict[str, Any] = ( + {"orchestrator": AsyncPipelineOrchestrator()} if asynchronous else {} + ) raises_on_main = order == ("j", "k") and roles in ("k_data_tag", "j_data_tag") if raises_on_main: with pytest.raises(ValueError, match="Duplicate column name"): - job.run(orchestrator=AsyncPipelineOrchestrator()) + job.run(**kwargs) else: - job.run(orchestrator=AsyncPipelineOrchestrator()) + job.run(**kwargs) assert _rows(job) == ROWS diff --git a/tests/test_pipeline/test_narrower_bind_order.py b/tests/test_pipeline/test_narrower_bind_order.py index a754b8647..45bca4160 100644 --- a/tests/test_pipeline/test_narrower_bind_order.py +++ b/tests/test_pipeline/test_narrower_bind_order.py @@ -2,14 +2,13 @@ A source slot declared from a source whose ``x`` is ``int | None``, bound to the same columns with ``x: int`` (a narrower source, given as the declared schema), feeding a -``Batch`` node in ``LOG`` mode. The source node's output is F of the bound table with -the keys its rows have (``SourceJobNode._row_keys``: ``_DeclaredForm.apply`` of a -row's tag and data tables, as each row is given). Every pairing of declared layout, tag +``Batch`` node in ``LOG`` mode. The source node hands on its rows as ``main`` gives +them (``_declared_rows``), built where the successor reads them (``RowsOnRead``). +Every pairing of declared layout, tag order and data-tag roles must keep and store what the row path keeps and stores: the same run with the source's output built from its rows -(``StaticOutputOperatorPod._materialize_upstream``), as on ``main``. The arrangements -where the row path raises (one data-tag of two, ITL-1366) are spec row e10, tested in -``test_declared_slot_one_data_tag.py``. +(``StaticOutputOperatorPod._materialize_upstream``), as on ``main``, also where the +row path raises (one data-tag of two, ITL-1366). """ from __future__ import annotations @@ -90,9 +89,12 @@ def execute(self: Any, *, observer: Any = None) -> Any: monkeypatch.setattr(SourceNodeBase, "execute", execute) -def _raises_on_the_row_path(roles: str) -> bool: - """The row path raises only with one data-tag of two (ITL-1366, e10).""" - return roles in ("a_data_tag", "b_data_tag") +def _outcome(layout: tuple[str, ...], tag_order: tuple[str, str], roles: Any) -> Any: + """The run's kept columns and raw stored schema, or the error it raised.""" + try: + return _run(layout, tag_order, roles) + except ValueError as error: + return (type(error), str(error)) @pytest.mark.parametrize("roles", list(ROLES), ids=list(ROLES)) @@ -106,15 +108,17 @@ def test_a_narrower_bind_keeps_and_stores_as_the_row_path( roles: str, monkeypatch: pytest.MonkeyPatch, ) -> None: - """Kept columns and the raw stored schema equal the row path's, in order.""" - got = _run(layout, tag_order, ROLES[roles]) + """Kept columns and the raw stored schema equal the row path's, in order. + + Where the row path raises (one data-tag of two, ITL-1366, a ``main`` bug), the + branch raises the same error. + """ + got = _outcome(layout, tag_order, ROLES[roles]) with monkeypatch.context() as patch: _row_path(patch) - try: - expected = _run(layout, tag_order, ROLES[roles]) - except ValueError as error: - assert "Duplicate column name" in str(error) - assert _raises_on_the_row_path(roles) - pytest.skip("the row path raises here: spec row e10") + expected = _outcome(layout, tag_order, ROLES[roles]) + if isinstance(expected[1], str): + assert got == expected + return assert got[0] == expected[0] assert got[1].equals(expected[1], check_metadata=True) diff --git a/tests/test_pipeline/test_rows_on_read.py b/tests/test_pipeline/test_rows_on_read.py new file mode 100644 index 000000000..971969730 --- /dev/null +++ b/tests/test_pipeline/test_rows_on_read.py @@ -0,0 +1,254 @@ +"""Outputs held as rows, built where a successor reads them (ITL-1347; Codex on PR #485). + +On every route where building a node's output from its whole table is not provably +``main``'s result, the node hands on its rows (``RowsOnRead``), built by ``main``'s row +path where the sync orchestrator gives them to a successor (``at_edge``). So the +order, the error and the moment it surfaces are ``main``'s: a narrower bind, a source +whose whole-table build is unavailable (its rows read once), a held node. A leaf +nobody reads is never built. +""" + +from __future__ import annotations + +from typing import Any + +import pyarrow as pa +import pytest + +from orcapod import PipelineJob +from orcapod.core.streams import ArrowTableStream +from orcapod.databases import InMemoryArrowDatabase +from orcapod.operators import Batch +from orcapod.pipeline.dag import OrcaDAG +from orcapod.pipeline.observer import NoOpObserver +from orcapod.pipeline.sync_orchestrator import SyncPipelineOrchestrator +from orcapod.sources import ArrowTableSource, DictSource +from orcapod.types import CacheMode +from tests.test_core.operators.test_row_built_form import ( + _NESTED, # pyright: ignore[reportPrivateUsage] # the shared provenance fixtures + _NodeEvents, # pyright: ignore[reportPrivateUsage] + _source_table, # pyright: ignore[reportPrivateUsage] + _with_source_x, # pyright: ignore[reportPrivateUsage] +) + +_UNCONVERTIBLE = pa.large_list(_NESTED) + + +def _unconvertible() -> ArrowTableStream: + """Tokens ``[None, [[]]]``: the whole-table build is unavailable, the rows raise.""" + return _with_source_x([[None, [[]]], [None, [[]]]], _UNCONVERTIBLE) + + +def _plain() -> DictSource: + return DictSource( + [{"k": 1, "x": 1}, {"k": 2, "x": 2}], + tag_columns=["k"], + tag_only_columns=True, + source_id="s", + ) + + +def test_a_fallback_source_reads_its_rows_once() -> None: + """A rebind after the source node ended does not change what it handed on. + + Its rows were read once, when it ran: the successor's edge raises the original + rows' ``ArrowTypeError``, as on ``main``. + """ + job = PipelineJob(name="read_once", database=InMemoryArrowDatabase()) + with job: + Batch(batch_size=2)(_plain().select_data_columns(["x"]), label="batched") + job.bind(sources={"s": _unconvertible()}) + node = job.nodes["s"] + + class RebindsAtEnd(NoOpObserver): + def contextualize(self, *identity_path: str) -> RebindsAtEnd: + return self + + def on_node_end(self, node_label: str, node_hash: str) -> None: + if node_label == "s": + node.bound_source = _plain() + + with pytest.raises(pa.ArrowTypeError, match="Expected bytes"): + job.run(observer=RebindsAtEnd()) + + +def test_a_fallback_source_nobody_reads_completes() -> None: + """A source whose rows cannot be built, as a leaf of a direct sync run: it completes. + + ``main`` never rebuilt a leaf's rows; neither does the branch (``RowsOnRead``). + """ + job = PipelineJob(name="leaf", database=InMemoryArrowDatabase()) + with job: + _plain().select_data_columns(["x"], label="selected") + job.bind(sources={"s": _unconvertible()}) + dag: OrcaDAG[Any] = OrcaDAG() + dag.add_node(job.nodes["s"]) + observer = _NodeEvents() + SyncPipelineOrchestrator().run(dag, observer=observer, materialize_results=False) + assert observer.events == [("start", "s"), ("end", "s")] + + +def test_a_narrower_raw_bind_keeps_the_slots_system_tag_order() -> None: + """A raw stream whose system tags are record id then source id, bound narrower. + + ``main`` gives each row the slot's order (source id, then record id); so do the + kept and the raw stored tables (Codex on PR #485, round 3). + """ + from orcapod.system_constants import constants + + table = _source_table() + source_id = next(n for n in table.column_names if "source_id" in n) + record_id = next(n for n in table.column_names if "record_id" in n) + others = [n for n in table.column_names if n not in (source_id, record_id)] + reversed_pair = table.select([*others, record_id, source_id]) + raw = ArrowTableStream(reversed_pair, tag_columns=["k"]) + + database = InMemoryArrowDatabase() + job = PipelineJob(name="reversed_pair", database=database) + with job: + declared = DictSource( + [{"k": 1, "x": 1}, {"k": 2, "x": None}], + tag_columns=["k"], + tag_only_columns=True, + source_id="s", + ) + Batch(batch_size=2)(declared, label="batched") + job.nodes["batched"].attach_databases( + pipeline_database=database.at("log"), cache_mode=CacheMode.LOG + ) + job.bind(sources={"s": raw}) + job.run() + node = job.nodes["batched"] + kept = node.as_table(columns={"system_tags": True}).column_names + system_tags = [n for n in kept if n.startswith(constants.SYSTEM_TAG_PREFIX)] + assert ["source_id" in n for n in system_tags] == [True, False] + stored = node.get_all_records(columns={"system_tags": True}) + assert stored is not None + stored_tags = [ + n for n in stored.column_names if n.startswith(constants.SYSTEM_TAG_PREFIX) + ] + assert ["source_id" in n for n in stored_tags] == [True, False] + + +def test_a_narrower_bind_is_described_from_its_declared_schema() -> None: + """A narrower bind's description never places columns: its types are undeclared. + + With one data-tag among two tags (ITL-1366's input), the description does not + raise; ``arrow_types_declared`` is false (Codex on PR #485, round 3). + """ + table = pa.table( + { + "x": pa.array([1, 2], pa.int64()), + "k": pa.array([5, 6], pa.int64()), + "j": pa.array([3, 4], pa.int64()), + "y": pa.array([7.5, 8.5], pa.float64()), + } + ) + + def source(nullable_x: bool) -> ArrowTableSource: + fields = [f.with_nullable(f.name == "x" and nullable_x) for f in table.schema] + return ArrowTableSource( + table.cast(pa.schema(fields)), + tag_columns=["j", "k"], + tag_only_columns=("j",), + source_id="s", + ) + + job = PipelineJob(name="narrower_description", database=InMemoryArrowDatabase()) + with job: + source(True).select_data_columns(["y", "x"], label="selected") + slot = next(label for label in job.nodes if label != "selected") + job.bind(sources={slot: source(False)}) + node = job.nodes[slot] + schema = node.arrow_schema() + assert not node.arrow_types_declared + assert set(node.keys()[0]) <= set(schema.names) + + +def test_a_narrower_bind_channel_raises_as_its_rows_do() -> None: + """The source node's channel carries its rows: ITL-1366's input raises as on main. + + ``open_channel()`` reads the node's output, the rows built when read, which raise + the duplicate-column error ``main``'s row path raises. + """ + import asyncio + + table = pa.table( + { + "x": pa.array([1, 2], pa.int64()), + "k": pa.array([5, 6], pa.int64()), + "j": pa.array([3, 4], pa.int64()), + "y": pa.array([7.5, 8.5], pa.float64()), + } + ) + + def source(nullable_x: bool) -> ArrowTableSource: + fields = [f.with_nullable(f.name == "x" and nullable_x) for f in table.schema] + return ArrowTableSource( + table.cast(pa.schema(fields)), + tag_columns=["j", "k"], + tag_only_columns=("j",), + source_id="s", + ) + + job = PipelineJob(name="narrower_channel", database=InMemoryArrowDatabase()) + with job: + source(True).select_data_columns(["y", "x"], label="selected") + slot = next(label for label in job.nodes if label != "selected") + job.bind(sources={slot: source(False)}) + node: Any = job.nodes[slot] + with pytest.raises(ValueError, match="Duplicate column name"): + asyncio.run(node.open_channel().collect()) + + +def _replay_job(database: InMemoryArrowDatabase, *, with_successor: bool) -> Any: + """``source -> select x`` with the select node replaying from ``database``.""" + job = PipelineJob(name="replay_odd", database=InMemoryArrowDatabase()) + with job: + selected = _plain().select_data_columns(["x"], label="selected") + if with_successor: + Batch(batch_size=2)(selected, label="batched") + job.nodes["selected"].attach_databases( + pipeline_database=database, cache_mode=CacheMode.REPLAY + ) + return job + + +@pytest.mark.parametrize("with_successor", [False, True], ids=["leaf", "successor"]) +def test_replay_of_a_table_the_whole_table_build_cannot_use( + with_successor: bool, +) -> None: + """REPLAY of a stored table with unconvertible tokens hands on its rows. + + The node ends as usual; a leaf completes; a successor's edge raises the rows' + ``ArrowTypeError``, as ``main``'s row rebuild does (Codex on PR #485, round 3). + """ + logged = InMemoryArrowDatabase() + job = PipelineJob(name="replay_odd", database=InMemoryArrowDatabase()) + with job: + _plain().select_data_columns(["x"], label="selected") + node: Any = job.nodes["selected"] + node.attach_databases(pipeline_database=logged, cache_mode=CacheMode.LOG) + job.run() + path = node._stored_table_path # pyright: ignore[reportPrivateUsage] # the table to seed + stored = logged.get_all_records(path, record_id_column="__record_id") + assert stored is not None + position = stored.schema.get_field_index("_source_x") + odd = stored.set_column( + position, + pa.field("_source_x", _UNCONVERTIBLE, nullable=True), + pa.array([[None, [[]]]] * stored.num_rows, _UNCONVERTIBLE), + ) + seeded = InMemoryArrowDatabase() + seeded.add_records(path, odd, record_id_column="__record_id") + + replay = _replay_job(seeded, with_successor=with_successor) + observer = _NodeEvents() + if with_successor: + with pytest.raises(pa.ArrowTypeError, match="Expected bytes"): + replay.run(observer=observer) + assert ("end", "selected") in observer.events + assert ("start", "batched") not in observer.events + else: + replay.run(observer=observer) + assert ("end", "selected") in observer.events diff --git a/tests/test_pipeline/test_stream_transport_equivalence.py b/tests/test_pipeline/test_stream_transport_equivalence.py index f13f9dc89..7b9ff4193 100644 --- a/tests/test_pipeline/test_stream_transport_equivalence.py +++ b/tests/test_pipeline/test_stream_transport_equivalence.py @@ -36,7 +36,7 @@ from orcapod.core.nodes.function_node import FunctionJobNode from orcapod.core.nodes.operator_node import OperatorJobNode from orcapod.core.nodes.source_node import SourceNodeBase -from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod +from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod, at_edge from orcapod.core.streams.base import ZERO_ROW_INPUT_COLUMNS from orcapod.databases import InMemoryArrowDatabase from orcapod.errors import ProvisionalHashWarning @@ -125,7 +125,13 @@ def _identity(stream: Any) -> tuple[Any, ...]: def assert_same_stream(got: Any, expected: Any) -> None: - """Equal identity, and equal tables byte for byte (every column group).""" + """Equal identity, and equal tables byte for byte (every column group). + + ``got`` is taken as a successor receives it (``at_edge``: an output held as its rows + is built there). + """ + got = at_edge(got) + expected = at_edge(expected) assert _identity(got) == _identity(expected) got_table = got.as_table(columns=ALL_COLUMNS).combine_chunks() expected_table = expected.as_table(columns=ALL_COLUMNS).combine_chunks() From 2064af382d72a1e4e492a190ea99ec19f7661a50 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 08:40:13 -0800 Subject: [PATCH 46/86] fix(channels): a conversion that never starts releases its reader (ITL-1362, carried from #488) (#489) * fix(channels): a conversion that never starts releases its reader; the test fixture reads a stream once (ITL-1362) Carried from CodeRabbit's review body on #488: - channel_to_stream still reserves at call time; the reservation's claim is held weakly, and a claim freed before any task took it over (the conversion's task cancelled before its first step, or the conversion never awaited) closes the reader, outside the coroutine body, so a bounded producer no longer waits on it - the record-batch matrix's _channel fixture returns the stream's own channel for the one-batch layout, and otherwise reads the stream once Co-Authored-By: Claude Opus 5.5 * fix(channels): a freed claim releases the reader's feed even when the channel object is gone (ITL-1362) CodeRabbit on #489: with a reader of a bounded output dropped before its claim, the claim's release found no channel and left the feed registered, so the producer waited for ever. The release now holds the feed itself (the reader's place in its producer, which never refers to the channel) and always closes it; it marks the channel closed when the channel still exists. One release, two effects. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Edgar Y. Walker Co-authored-by: Claude Opus 5.5 --- .../core/operators/static_output_pod.py | 5 +- .../core/streams/record_batch_input.py | 69 +++++++++++++++++-- .../protocols/core_protocols/streams.py | 3 +- .../test_record_batch_channels.py | 53 ++++++++++++++ .../operators/test_record_batch_execution.py | 14 ++-- 5 files changed, 130 insertions(+), 14 deletions(-) diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index e32ae30df..62b990060 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -1099,7 +1099,10 @@ def channel_to_stream( The channel is reserved when this function is called, before the returned coroutine is awaited, so nothing can read it in between; the task that runs the - coroutine takes the channel over, and any other task's read is refused. + coroutine takes the channel over, and any other task's read is refused. If the + coroutine never starts (its task is cancelled first, or it is never awaited), + the reservation's claim is freed with it and the channel is closed, so no + producer waits on it. Args: channel: The input channel, not read yet. diff --git a/src/orcapod/core/streams/record_batch_input.py b/src/orcapod/core/streams/record_batch_input.py index 98d23e33b..86dfe2947 100644 --- a/src/orcapod/core/streams/record_batch_input.py +++ b/src/orcapod/core/streams/record_batch_input.py @@ -16,6 +16,7 @@ from __future__ import annotations import asyncio +import weakref from collections.abc import AsyncIterator from typing import TYPE_CHECKING, Any, Protocol @@ -84,8 +85,12 @@ def __init__(self, stream: StreamProtocol, feed: BatchFeed) -> None: self._reading = False # The consumer: the asyncio task the channel belongs to, for its whole life, # and the claim a conversion holds while it moves to the task that runs it. + # The claim is held weakly: a claim freed before a task took it over (its + # conversion cancelled before it started, or never awaited) closes the + # channel, so no producer waits on a reader nobody will read. self._owner: asyncio.Task[Any] | None = None - self._claim: object | None = None + self._claim: weakref.ref[_Claim] | None = None + self._claim_release: weakref.finalize[Any, Any] | None = None @property def stream(self) -> StreamProtocol: @@ -132,13 +137,14 @@ def reserve(self, claim: object | None = None) -> object: if self._closed: raise self._closed_early() if claim is not None: - if claim is not self._claim: + held = self._claim() if self._claim is not None else None + if held is None or claim is not held: raise RuntimeError( f"The input channel of {_named(self._stream)} is claimed by " + "another consumer." ) self._owner = _current_task() - self._claim = None # redeemed: a later reserve(claim) is refused + self._drop_claim() # redeemed: a later reserve(claim) is refused return claim if self._started or self._ended or self._owner is not None: raise RuntimeError( @@ -148,8 +154,35 @@ def reserve(self, claim: object | None = None) -> object: ) self._started = True self._owner = None # held for the claim until a task takes it over - self._claim = object() - return self._claim + new_claim = _Claim() + self._claim = weakref.ref(new_claim) + # The release holds the feed (the reader's place in its producer, which never + # refers to the channel), so it is released even if the channel object has + # been freed first. + self._claim_release = weakref.finalize( + new_claim, _release_claim, self._feed, weakref.ref(self) + ) + return new_claim + + def _drop_claim(self) -> None: + """Forget the claim: taken over, or the channel closed.""" + if self._claim_release is not None: + _ = self._claim_release.detach() + self._claim_release = None + self._claim = None + + def _abandon(self) -> None: + """Mark the channel closed: its claim was freed before any task took it over. + + Synchronous (it runs when the claim is freed); its feed is closed by the + claim's release itself (``_release_claim``). + """ + self._claim_release = None + self._claim = None + if not self._ended: + self._closed = True + self._ended = True + self._owner = None def _belong_to_caller(self) -> None: """Bind the channel to the calling task on its first read; refuse any other. @@ -269,10 +302,34 @@ async def close(self) -> None: self._closed = True self._ended = True self._owner = None - self._claim = None + self._drop_claim() self._feed.close() +class _Claim: + """The claim ``reserve()`` returns; the channel is held for it while it lives. + + A plain class, so that the channel can hold it weakly. + """ + + +def _release_claim(feed: BatchFeed, channel_ref: weakref.ref[InputChannel]) -> None: + """Release a reader whose claim was freed before any task took it over. + + The reader's feed (its place in its producer) is closed in every case, so no + producer waits on it, also when the channel object was freed first; the channel, + if it still exists, is marked closed. + + Args: + feed: The reader's feed. + channel_ref: The channel, held weakly. + """ + feed.close() + channel = channel_ref() + if channel is not None: + channel._abandon() # pyright: ignore[reportPrivateUsage] # the claim's release + + def _current_task() -> asyncio.Task[Any] | None: """The running asyncio task, or ``None`` outside one.""" try: diff --git a/src/orcapod/protocols/core_protocols/streams.py b/src/orcapod/protocols/core_protocols/streams.py index ec42f4c7e..2ee788b67 100644 --- a/src/orcapod/protocols/core_protocols/streams.py +++ b/src/orcapod/protocols/core_protocols/streams.py @@ -638,7 +638,8 @@ def reserve(self, claim: object | None = None) -> object: Without ``claim``, the unread channel is held for the returned claim, not for the calling task: no task, the reserving one included, can read it until a task takes it over with that claim (``reserve(claim)``), after which only - that task reads it. A claim is taken over once. + that task reads it. A claim is taken over once; a claim freed before it was + taken over closes the channel. Raises: RuntimeError: If a read was called on it already, or ``claim`` is not its diff --git a/tests/test_channels/test_record_batch_channels.py b/tests/test_channels/test_record_batch_channels.py index 95821c2cd..e12bc7d59 100644 --- a/tests/test_channels/test_record_batch_channels.py +++ b/tests/test_channels/test_record_batch_channels.py @@ -626,6 +626,59 @@ async def read() -> None: assert unheard == [] +@pytest.mark.parametrize("never", ["cancelled", "dropped"]) +def test_a_conversion_that_never_starts_releases_its_reader(never: str) -> None: + """``channel_to_stream`` reserves at call time. If its conversion never starts (its + task is cancelled before the first step, or it is dropped unawaited), the + reservation is released: the reader is closed and a bounded producer no longer + waits on it.""" + stream = source(4) + batches = batches_of(stream, 1) + + async def read() -> None: + output = OutputChannel(stream, retain=False, buffer_size=1) + reader = output.open_reader() + if never == "cancelled": + task = asyncio.ensure_future(channel_to_stream(reader)) + _ = task.cancel() + _ = await asyncio.gather(task, return_exceptions=True) + del task + else: + pending = channel_to_stream(reader) + pending.close() # what dropping an unawaited coroutine does + del pending + gc.collect() + for batch in batches: # would wait forever on a held reader of one slot + await asyncio.wait_for(output.send(batch), 1) + await output.close() + with pytest.raises(ChannelClosed): + _ = await reader.receive() + + run(read) + + +def test_a_dropped_reader_whose_claim_is_freed_later_releases_its_producer() -> None: + """A reader of a bounded output is reserved, then the reader object is dropped + before its claim: when the claim is freed, the reader's place in the output is + released all the same, so sends past its queue complete.""" + stream = source(4) + batches = batches_of(stream, 1) + + async def read() -> None: + output = OutputChannel(stream, retain=False, buffer_size=1) + reader = output.open_reader() + claim = reader.reserve() + del reader + gc.collect() # the channel is gone; its claim is not + del claim + gc.collect() + for batch in batches: # would wait forever on a reader still registered + await asyncio.wait_for(output.send(batch), 1) + await output.close() + + run(read) + + def test_a_closed_reader_cannot_be_converted() -> None: """A reader closed before any read: ``channel_to_stream`` raises ``ChannelClosed``, as documented, not the error of a channel already read.""" diff --git a/tests/test_core/operators/test_record_batch_execution.py b/tests/test_core/operators/test_record_batch_execution.py index 568b44975..71e6b7cad 100644 --- a/tests/test_core/operators/test_record_batch_execution.py +++ b/tests/test_core/operators/test_record_batch_execution.py @@ -87,14 +87,16 @@ def _cut(table: pa.Table, sizes: tuple[int, ...] | None) -> list[pa.RecordBatch] async def _channel( stream: StreamProtocol, sizes: tuple[int, ...] | None ) -> RecordBatchInput: - """An input channel delivering ``stream``'s rows in record batches of ``sizes``.""" - batches = await stream.open_channel().collect() - if sizes is None or not batches: + """An input channel delivering ``stream``'s rows in record batches of ``sizes``: + the stream's own channel for ``None``, else one read of it, cut and re-sent + through an output channel (never a second read of the stream).""" + if sizes is None: return stream.open_channel() - rows = pa.Table.from_batches(batches) + batches = await stream.open_channel().collect() feed = OutputChannel(stream) - for batch in _cut(rows, sizes): - await feed.send(batch) + if batches: + for batch in _cut(pa.Table.from_batches(batches), sizes): + await feed.send(batch) await feed.close() return feed.open_reader() From a31ed4b62386f9095fd942d612fbad3c7564ead0 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 08:45:53 -0800 Subject: [PATCH 47/86] fix(pipeline): RowsOnRead typed through rows_on_read (ITL-1360) Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/nodes/function_node.py | 8 ++++---- src/orcapod/core/nodes/operator_node.py | 7 ++----- src/orcapod/core/nodes/source_node.py | 8 ++++---- .../core/operators/static_output_pod.py | 19 ++++++++++++++++++- src/orcapod/core/streams/base.py | 6 +++--- src/orcapod/pipeline/node_run.py | 4 ++-- .../test_function_node_arrow_types.py | 4 ++-- 7 files changed, 35 insertions(+), 21 deletions(-) diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 3f32b20d1..ebd445e5c 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -298,9 +298,9 @@ def rows_as_output_stream( Returns: The node's output stream. """ - from orcapod.core.operators.static_output_pod import RowsOnRead + from orcapod.core.operators.static_output_pod import rows_on_read - return cast(StreamProtocol, cast(object, RowsOnRead(rows, node))) + return rows_on_read(rows, node) def _executor_supports_concurrent( @@ -2486,9 +2486,9 @@ def _output_stream( (``RowsOnRead``): the sync orchestrator builds it where a successor reads it, as ``main`` rebuilt the rows there, and a leaf's is never built (ITL-1347). """ - from orcapod.core.operators.static_output_pod import RowsOnRead + from orcapod.core.operators.static_output_pod import rows_on_read - return cast(StreamProtocol, cast(object, RowsOnRead(rows, self))) + return rows_on_read(rows, self) def execute_data( self, diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index ccdaa6f35..925eab47a 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -40,8 +40,8 @@ from orcapod.config import OrcapodConfig from orcapod.core.operators.static_output_pod import ( RowBuiltFormUnavailable, - RowsOnRead, StaticOutputOperatorPod, + rows_on_read, ) from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.core.streams.base import ( @@ -1701,10 +1701,7 @@ def execute( except RowBuiltFormUnavailable: # A stored table F cannot build from: its rows, built when read, # as main handed them on (ITL-1347). - output = cast( - StreamProtocol, - cast(object, RowsOnRead(cached_output.iter_data(), self)), - ) + output = rows_on_read(cached_output.iter_data(), self) ctx_obs.on_node_end(node_label, node_hash) return output diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index b9467328d..5c7b5afcf 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -1303,8 +1303,8 @@ def execute( """ from orcapod.core.operators.static_output_pod import ( RowBuiltFormUnavailable, - RowsOnRead, StaticOutputOperatorPod, + rows_on_read, ) node_label = self.label @@ -1316,14 +1316,14 @@ def execute( rows_table = self._rows_table() result: StreamProtocol if rows_table is None: - result = cast("StreamProtocol", RowsOnRead(self.iter_data(), self)) + result = rows_on_read(self.iter_data(), self) else: table, keys = rows_table try: result = StaticOutputOperatorPod._output_stream(table, keys, self) except RowBuiltFormUnavailable: # The rows decide (read once, here), built when read, as on main. - result = cast("StreamProtocol", RowsOnRead(self.iter_data(), self)) + result = rows_on_read(self.iter_data(), self) if observer is not None: observer.on_node_end(node_label, node_hash) return result @@ -1808,7 +1808,7 @@ def arrow_schema(self) -> pa.Schema: (``arrow_types_declared`` is false): no second placement rule. """ if self._declared_form is not None: - return stream_arrow_schema(self, self.keys(), typed=False) + return stream_arrow_schema(self, self.keys(), from_table=False) return stream_arrow_schema(self, self._row_keys()) @property diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index f9017efd0..6d5eec544 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -1371,7 +1371,7 @@ class RowsOnRead: _orcapod_row_built_output = False def __init__( - self, rows: Sequence[tuple[TagProtocol, DataProtocol]], node: StreamProtocol + self, rows: Iterable[tuple[TagProtocol, DataProtocol]], node: StreamProtocol ) -> None: """Hold ``node``'s rows; nothing is built. @@ -1403,6 +1403,23 @@ def __repr__(self) -> str: return f"RowsOnRead({short_stream_repr(self._node)})" +def rows_on_read( + rows: Iterable[tuple[TagProtocol, DataProtocol]], node: StreamProtocol +) -> StreamProtocol: + """``RowsOnRead`` of ``rows`` as a stream (it delegates every member to the built one). + + Args: + rows: The rows ``main`` would hold, in order (read once, here). + node: The node (or stream) whose output they are. + + Returns: + The output, built from the rows when first read. + """ + # ``RowsOnRead`` stands for the stream it builds; the checker cannot see that + # through its delegation, so the cast goes through object. + return cast(StreamProtocol, cast(object, RowsOnRead(rows, node))) + + def at_edge(stream: StreamProtocol) -> StreamProtocol: """``stream`` as a node's input: a ``RowsOnRead`` output is built here. diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py index 46293426c..c61c38c17 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -367,7 +367,7 @@ def stream_arrow_schema( stream: object, keys: tuple[Sequence[str], Sequence[str]] | None = None, *, - typed: bool = True, + from_table: bool = True, ) -> pa.Schema: """Return ``stream``'s declared Arrow schema: what ``arrow_schema()`` answers (ITL-1347). @@ -392,7 +392,7 @@ def stream_arrow_schema( stream: The stream, source or node. keys: The tag and data keys of the stream's rows, when they differ from ``keys()`` (a source slot gives its bound source's rows); default ``keys()``. - typed: Take the stream's typed zero-row table (``typed_zero_row_input``); + from_table: Take the stream's typed zero-row table (``typed_zero_row_input``); ``False`` describes it from its declared Python schema only (a narrower bind, whose rows ``main``'s row path places). @@ -403,7 +403,7 @@ def stream_arrow_schema( typed = cast(StreamProtocol, stream) given_keys = keys - table = typed_zero_row_input(stream) if typed else None + table = typed_zero_row_input(stream) if from_table else None if table is None and schema_requires_io(stream, ColumnConfig(system_tags=True)): # Nothing declared, nothing polled (a poller with no declared schema): the # columns are known only from rows, and a description never polls. No column, diff --git a/src/orcapod/pipeline/node_run.py b/src/orcapod/pipeline/node_run.py index 49a035b4a..88a0e5ffe 100644 --- a/src/orcapod/pipeline/node_run.py +++ b/src/orcapod/pipeline/node_run.py @@ -245,9 +245,9 @@ def check_sources(streams: Iterable[Any]) -> tuple[str, ...]: def _rows_on_read(rows: Sequence[Any], node: Any) -> Any: """A held node's output: its rows, built where a successor reads them (``RowsOnRead``).""" - from orcapod.core.operators.static_output_pod import RowsOnRead + from orcapod.core.operators.static_output_pod import rows_on_read - return RowsOnRead(rows, node) + return rows_on_read(rows, node) @dataclass(frozen=True) diff --git a/tests/test_core/function_pod/test_function_node_arrow_types.py b/tests/test_core/function_pod/test_function_node_arrow_types.py index bd76bc8a5..195d72133 100644 --- a/tests/test_core/function_pod/test_function_node_arrow_types.py +++ b/tests/test_core/function_pod/test_function_node_arrow_types.py @@ -475,7 +475,7 @@ def test_a_held_nodes_rows_are_built_at_its_successors_edge( source, then ``increment`` after ``double``. The independent source runs before ``increment``'s input is built and raises (Codex on PR #485, round 3). """ - from orcapod.core.operators.static_output_pod import RowsOnRead + from orcapod.core.operators.static_output_pod import rows_on_read from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator from orcapod.pipeline.dag import OrcaDAG from orcapod.pipeline.observer import NoOpObserver @@ -505,7 +505,7 @@ def on_node_start( dag.add_node(double) dag.add_node(independent) dag.add_edge(double, increment) - held = {double: RowsOnRead(list(double.iter_data()), double)} + held = {double: rows_on_read(double.iter_data(), double)} with pytest.raises(pa.ArrowInvalid): SyncPipelineOrchestrator().run(dag, observer=Starts(), held=held) assert starts == ["src"] From 3223e6444a0cede44a0acf0129bf9019e9b02978 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 09:23:00 -0800 Subject: [PATCH 48/86] fix(pipeline): the eager route only for library source kinds; RowsOnRead is a stream (ITL-1360) Codex on PR #485, round 4. - TABLE_IS_ROWS, declared once on RootSource (False) and True on the library source kinds whose as_table() and iter_data() read the same data with no effect: only a node bound to one hands on F of its table. Any other bound stream (a side-effect or function pod stream, an operator's result, a raw stream, a poller) hands on its rows, as main iterated them. - No table is prepared before main prepares it: a result with no row (source or operator) is RowsOnRead too, so its zero-row form is derived at the successor's edge and the operator is never called a second time. - RowsOnRead satisfies StreamProtocol structurally on 3.11-3.13 (every protocol member declared on the class; producer, upstreams, context, label and modified time read without building); iter_data() gives the rows it holds unchanged (meta included), sync and async node_outputs alike; arrow_schema() is the node's declared one (arrow_types_declared false) and open_channel() builds only at its first read. - A description whose types are undeclared gives names in no guaranteed order: transport_schema returns None for it and the channel's name check compares names as a set. Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/nodes/operator_node.py | 4 +- src/orcapod/core/nodes/source_node.py | 25 ++- .../core/operators/static_output_pod.py | 148 ++++++++++++-- src/orcapod/core/record_batch_channels.py | 5 +- .../core/sources/arrow_table_source.py | 1 + src/orcapod/core/sources/base.py | 10 + src/orcapod/core/sources/cached_source.py | 1 + src/orcapod/core/sources/csv_source.py | 1 + src/orcapod/core/sources/data_frame_source.py | 1 + src/orcapod/core/sources/db_table_source.py | 1 + .../core/sources/delta_table_source.py | 1 + src/orcapod/core/sources/derived_source.py | 1 + src/orcapod/core/sources/dict_source.py | 1 + src/orcapod/core/sources/list_source.py | 1 + .../core/sources/spiraldb_table_source.py | 1 + src/orcapod/pipeline/async_orchestrator.py | 8 +- .../protocols/core_protocols/streams.py | 8 +- tests/test_pipeline/test_rows_on_read.py | 181 ++++++++++++++++++ 18 files changed, 361 insertions(+), 38 deletions(-) diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index 925eab47a..c7b237fe3 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -1752,7 +1752,9 @@ def execute( kept_table, tag_keys, data_tags, self ) else: - output = StaticOutputOperatorPod._materialize_upstream([], self) + # Its zero-row form is derived where a successor reads it, as on main: + # the operator is not called again here (``RowsOnRead``). + output = rows_on_read([], self) ctx_obs.on_node_end(node_label, node_hash) return output except BaseException: diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index 5c7b5afcf..8795c9702 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -17,7 +17,7 @@ from abc import ABC, abstractmethod from collections.abc import AsyncIterator, Collection, Iterator, Mapping from datetime import datetime -from typing import TYPE_CHECKING, Any, cast +from typing import TYPE_CHECKING, Any import pyarrow as pa @@ -1253,15 +1253,13 @@ def iter_data(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: def _rows_table( self, ) -> tuple[pa.Table, tuple[tuple[str, ...], tuple[str, ...]]] | None: - """The table of this node's rows (``iter_data``) and the rows' keys. + """The table of this node's rows (``iter_data``) and the rows' keys, or ``None``. - Here this node's own table (``ZERO_ROW_INPUT_COLUMNS``) and keys. ``None`` where - F of a table is not provably the rows' own table: the node then hands on its - rows (``RowsOnRead``). + ``None`` here: a node that carries no data of its own hands on its rows + (``RowsOnRead``), which raise what reading it raises. A bound job node gives + its bound source's table when F of it is provably the rows' own table. """ - stream = cast("StreamProtocol", self) - table = stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS) - return table, keys_of_rows(table, stream.keys()) + return None def arrow_schema(self) -> pa.Schema: """The Arrow schema of the columns this stream passes between job nodes. @@ -1823,8 +1821,10 @@ def _rows_table( ) -> tuple[pa.Table, tuple[tuple[str, ...], tuple[str, ...]]] | None: """The bound source's table and the keys of its rows (``keys_of_rows``). - ``None`` for a narrower bind: its rows are given as the declared schema one by - one (``_declared_rows``), so the node hands on those rows (``RowsOnRead``). + ``None`` for a narrower bind (its rows are given as the declared schema one by + one, ``_declared_rows``) and for a bound stream that is not a library source + kind whose table is its rows (``TABLE_IS_ROWS``): the node then hands on those + rows (``RowsOnRead``). Raises: UnboundSourceError: When no concrete source is attached. @@ -1836,6 +1836,11 @@ def _rows_table( ) if self._declared_form is not None: return None + if not getattr(type(self._bound_source), "TABLE_IS_ROWS", False): + # Not a library source kind whose table is its rows (a side-effect or + # function pod stream, an operator's result, a raw stream, a poller): its + # rows, as main iterated them. + return None table = self._bound_source.as_table(columns=ZERO_ROW_INPUT_COLUMNS) return table, keys_of_rows(table, self._bound_source.keys()) diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index 13edc119a..5f51eb2a4 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -3,7 +3,14 @@ import asyncio import logging from abc import abstractmethod -from collections.abc import Collection, Coroutine, Iterable, Iterator, Sequence +from collections.abc import ( + AsyncIterator, + Collection, + Coroutine, + Iterable, + Iterator, + Sequence, +) from datetime import datetime, timezone from typing import TYPE_CHECKING, Any, ClassVar, NoReturn, cast @@ -657,7 +664,9 @@ def _output_stream( The output stream, with ``node``'s identity. """ if table.num_rows == 0: - return StaticOutputOperatorPod._materialize_upstream([], node) + # No row: the zero-row input is derived where a successor reads it, as on + # main (``RowsOnRead``): nothing is prepared before then. + return rows_on_read([], node) tag_keys, data_keys = keys return StaticOutputOperatorPod._as_upstream_stream( StaticOutputOperatorPod._row_built_form(table, keys), @@ -1181,12 +1190,18 @@ def transport_schema(stream: StreamProtocol) -> pa.Schema | None: 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). + rows (an unbound input slot, a source that has not polled yet, a description + whose types are undeclared: ``arrow_types_declared`` false). """ # 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 + if not getattr(stream, "arrow_types_declared", True): + # The rows decide the types (and the column order) of a description whose + # types are undeclared (a narrower bind, ``RowsOnRead``): the first batch sets + # them. + return None typed = StaticOutputOperatorPod._zero_row_input(stream) # pyright: ignore[reportPrivateUsage] # the zero-row form of an input if typed is None: return None @@ -1360,14 +1375,21 @@ class RowsOnRead: """A node's output held as its rows, its table built on first read (ITL-1347). The one rule for every route where building the output from the whole table is - not provably ``main``'s result (a narrower bind, a whole-table build that is - unavailable, an odd stored table, a held node, a node whose output is still its - rows): the node hands on the rows ``main`` would hold, and the table is built from - them by ``main``'s own row path (``StaticOutputOperatorPod._materialize_upstream``) - when the stream is first read. The sync orchestrator reads each input of a node - before running it (``at_edge``), where ``main`` rebuilt it; a stream nobody reads - is never built, as ``main`` never rebuilt a leaf's rows. Every attribute is the - built stream's. + not provably ``main``'s result (a narrower bind, a bound stream that is not a + library source kind, a whole-table build that is unavailable, an odd stored table, + a held node, a result with no row, a node whose output is still its rows): the node + hands on the rows ``main`` would hold, and the table is built from them by + ``main``'s own row path (``StaticOutputOperatorPod._materialize_upstream``) when + the table is first read. The sync orchestrator reads each input of a node before + running it (``at_edge``), where ``main`` rebuilt it; a stream nobody reads is never + built, as ``main`` never rebuilt a leaf's rows. + + It is a stream (``StreamProtocol``), structurally: every member of the protocol is + the built stream's, except those that read nothing. Its rows (``iter_data``, + iteration) are the rows it holds, unchanged, as ``main`` returned them. Its + description (``arrow_schema``) is the node's declared one and builds nothing + (``arrow_types_declared`` is false). Opening a channel builds nothing; the + channel's first read does. """ # Not a stream the row-built form already made: a channel opened on it reads it. @@ -1382,30 +1404,120 @@ def __init__( rows: The rows ``main`` would hold, in order (read once, here). node: The node (or stream) whose output they are. """ - self._rows: list[tuple[TagProtocol, DataProtocol]] | None = list(rows) + self._rows: list[tuple[TagProtocol, DataProtocol]] = list(rows) self._node = node self._stream: StreamProtocol | None = None def built(self) -> StreamProtocol: """The stream, built from the rows on the first call (``main``'s row path).""" if self._stream is None: - rows = self._rows if self._rows is not None else [] self._stream = StaticOutputOperatorPod._materialize_upstream( - rows, self._node + self._rows, self._node ) - self._rows = None return self._stream - def __getattr__(self, name: str) -> Any: - return getattr(self.built(), name) + def iter_data(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: + """The rows it holds, unchanged (their meta columns included), as ``main``.""" + return iter(self._rows) def __iter__(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: - return iter(self.built().iter_data()) + return self.iter_data() + + async def async_iter_data( + self, + ) -> AsyncIterator[tuple[TagProtocol, DataProtocol]]: + """The rows it holds, unchanged.""" + for row in self._rows: + yield row + + def arrow_schema(self) -> pa.Schema: + """The node's declared description, from its Python schema; builds nothing. + + The rows decide the Arrow types (``arrow_types_declared`` is false): a + description with undeclared types gives the declared names, with no + guaranteed order. + """ + from orcapod.core.streams.base import stream_arrow_schema + + return stream_arrow_schema(self._node, from_table=False) + + @property + def arrow_types_declared(self) -> bool: + """False: the rows decide the types (see ``arrow_schema``).""" + return False + + def open_channel(self) -> Any: + """Open an input channel on this stream; its first read builds the table.""" + from orcapod.core.streams.base import CompleteStreamFeed + from orcapod.core.streams.record_batch_input import InputChannel + + return InputChannel( + cast(StreamProtocol, cast(object, self)), + CompleteStreamFeed(cast(StreamProtocol, cast(object, self))), + ) + + # The members that tell what the output is without reading it: the node's, which + # the built stream takes too (``_as_upstream_stream``), or the built stream's once + # it is built. A protocol check (``isinstance``) reads them and builds nothing. + @property + def producer(self) -> Any: + return self._node.producer + + @property + def upstreams(self) -> tuple[StreamProtocol, ...]: + return self._node.upstreams + + @property + def data_context_key(self) -> str: + return self._node.data_context_key + + @property + def label(self) -> Any: + source = self._stream if self._stream is not None else self._node + return getattr(source, "label", None) + + @property + def last_modified(self) -> Any: + source = self._stream if self._stream is not None else self._node + return getattr(source, "last_modified", None) + + def __getattr__(self, name: str) -> Any: + # Every other member (``join``, ``as_polars_df``, ...) is the built stream's. + return getattr(self.built(), name) def __repr__(self) -> str: return f"RowsOnRead({short_stream_repr(self._node)})" +def _stream_protocol_members() -> list[str]: + """The members ``StreamProtocol`` declares, its bases' included. + + What ``isinstance(x, StreamProtocol)`` looks for on the class: declaring each one + there lets ``RowsOnRead`` pass the check on every supported Python. + """ + names: set[str] = set() + for base in StreamProtocol.__mro__: + if base is object or base.__name__ in ("Protocol", "Generic"): + continue + names.update(name for name in vars(base) if not name.startswith("_")) + return sorted(names) + + +def _delegated(name: str) -> Any: + """A method of ``RowsOnRead`` that is the built stream's (``RowsOnRead.built``).""" + + def delegate(self: RowsOnRead, *args: Any, **kwargs: Any) -> Any: + return getattr(self.built(), name)(*args, **kwargs) + + delegate.__name__ = name + return delegate + + +for _name in _stream_protocol_members(): + if _name not in vars(RowsOnRead): + setattr(RowsOnRead, _name, _delegated(_name)) + + def rows_on_read( rows: Iterable[tuple[TagProtocol, DataProtocol]], node: StreamProtocol ) -> StreamProtocol: diff --git a/src/orcapod/core/record_batch_channels.py b/src/orcapod/core/record_batch_channels.py index b32a4e648..842e62a4a 100644 --- a/src/orcapod/core/record_batch_channels.py +++ b/src/orcapod/core/record_batch_channels.py @@ -191,9 +191,10 @@ def _check_schema(self, batch: pa.RecordBatch) -> None: 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. + # stream's, in no guaranteed order (an undeclared description gives names + # only). A refused batch sets nothing. names = batch.schema.names - if names != row_built_names(names, self._stream.keys()): + if set(names) != set(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 " diff --git a/src/orcapod/core/sources/arrow_table_source.py b/src/orcapod/core/sources/arrow_table_source.py index 460075915..5af85d506 100644 --- a/src/orcapod/core/sources/arrow_table_source.py +++ b/src/orcapod/core/sources/arrow_table_source.py @@ -89,6 +89,7 @@ class ArrowTableSource(RootSource): # The config type key; also the kind prefix of the default source id. SOURCE_KIND: ClassVar[str] = "arrow_table" + TABLE_IS_ROWS: ClassVar[bool] = True def __init__( self, diff --git a/src/orcapod/core/sources/base.py b/src/orcapod/core/sources/base.py index 1eed1f022..1f8eef123 100644 --- a/src/orcapod/core/sources/base.py +++ b/src/orcapod/core/sources/base.py @@ -93,6 +93,16 @@ class RootSource(StreamBase): identifier, config or stored path. """ + TABLE_IS_ROWS: ClassVar[bool] = False + """Whether ``as_table()`` and ``iter_data()`` read the same data, with no effect. + + Declared ``True`` only by the library source kinds that read one stream either way + (ITL-1347): a job node bound to one hands on F of its table, which equals the table + built from its rows. Any other bound stream (a side-effect or function pod stream, + an operator's result, a raw stream, a source kind that polls or delivers on a read) + hands on its rows (``RowsOnRead``), as ``main`` iterated them. + """ + def __init__( self, source_id: str | None = None, diff --git a/src/orcapod/core/sources/cached_source.py b/src/orcapod/core/sources/cached_source.py index 308a24fb6..98e531222 100644 --- a/src/orcapod/core/sources/cached_source.py +++ b/src/orcapod/core/sources/cached_source.py @@ -79,6 +79,7 @@ class CachedSource(RootSource): """ SOURCE_KIND: ClassVar[str] = "cached" + TABLE_IS_ROWS: ClassVar[bool] = True """Config type key and default source-id kind of this source (one vocabulary).""" HASH_COLUMN_NAME = "_record_hash" diff --git a/src/orcapod/core/sources/csv_source.py b/src/orcapod/core/sources/csv_source.py index cd780ab1e..bfd0b423d 100644 --- a/src/orcapod/core/sources/csv_source.py +++ b/src/orcapod/core/sources/csv_source.py @@ -276,6 +276,7 @@ class CSVSource(RootSource): """ SOURCE_KIND: ClassVar[str] = "csv" + TABLE_IS_ROWS: ClassVar[bool] = True """Config type key and default source-id kind of this source (one vocabulary).""" TAKES_TAG_ONLY_COLUMNS: ClassVar[bool] = True diff --git a/src/orcapod/core/sources/data_frame_source.py b/src/orcapod/core/sources/data_frame_source.py index 5db583ec2..f973c9647 100644 --- a/src/orcapod/core/sources/data_frame_source.py +++ b/src/orcapod/core/sources/data_frame_source.py @@ -44,6 +44,7 @@ class DataFrameSource(RootSource): # The config type key; also the kind prefix of the default source id. SOURCE_KIND: ClassVar[str] = "data_frame" + TABLE_IS_ROWS: ClassVar[bool] = True def __init__( self, diff --git a/src/orcapod/core/sources/db_table_source.py b/src/orcapod/core/sources/db_table_source.py index decdc09ea..721b2308d 100644 --- a/src/orcapod/core/sources/db_table_source.py +++ b/src/orcapod/core/sources/db_table_source.py @@ -80,6 +80,7 @@ class DBTableSource(RootSource): """ SOURCE_KIND: ClassVar[str] = "db_table" + TABLE_IS_ROWS: ClassVar[bool] = True """Config type key and default source-id kind of this source (one vocabulary).""" TAKES_TAG_ONLY_COLUMNS: ClassVar[bool] = True diff --git a/src/orcapod/core/sources/delta_table_source.py b/src/orcapod/core/sources/delta_table_source.py index ae623bdec..2a60e6304 100644 --- a/src/orcapod/core/sources/delta_table_source.py +++ b/src/orcapod/core/sources/delta_table_source.py @@ -49,6 +49,7 @@ class DeltaTableSource(RootSource): """ SOURCE_KIND: ClassVar[str] = "delta_table" + TABLE_IS_ROWS: ClassVar[bool] = True """Config type key and default source-id kind of this source (one vocabulary).""" TAKES_TAG_ONLY_COLUMNS: ClassVar[bool] = True diff --git a/src/orcapod/core/sources/derived_source.py b/src/orcapod/core/sources/derived_source.py index 1a7a58a93..1464e3f08 100644 --- a/src/orcapod/core/sources/derived_source.py +++ b/src/orcapod/core/sources/derived_source.py @@ -191,6 +191,7 @@ class DerivedSource(RootSource): # The config type key (names the class a saved config is rebuilt with) and # the kind prefix of the plain form's default source id. SOURCE_KIND: ClassVar[str] = "derived" + TABLE_IS_ROWS: ClassVar[bool] = True PROVISIONAL = True """Provisional in data context v1, both forms (ITL-1331, ``PROVISIONAL_SOURCES``).""" diff --git a/src/orcapod/core/sources/dict_source.py b/src/orcapod/core/sources/dict_source.py index bb99e1f9c..5a3935153 100644 --- a/src/orcapod/core/sources/dict_source.py +++ b/src/orcapod/core/sources/dict_source.py @@ -40,6 +40,7 @@ class DictSource(RootSource): # The config type key; also the kind prefix of the default source id. SOURCE_KIND: ClassVar[str] = "dict" + TABLE_IS_ROWS: ClassVar[bool] = True def __init__( self, diff --git a/src/orcapod/core/sources/list_source.py b/src/orcapod/core/sources/list_source.py index 48d8eae61..0b42e33ef 100644 --- a/src/orcapod/core/sources/list_source.py +++ b/src/orcapod/core/sources/list_source.py @@ -39,6 +39,7 @@ def _default_tag(element: Any, idx: int) -> dict[str, Any]: # The config type key; also the kind prefix of the default source id. SOURCE_KIND: ClassVar[str] = "list" + TABLE_IS_ROWS: ClassVar[bool] = True def __init__( self, diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index 8b022ff87..af04d5f34 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -374,6 +374,7 @@ class SpiralDBTableSource(RootSource): """ SOURCE_KIND: ClassVar[str] = "spiraldb_table" + TABLE_IS_ROWS: ClassVar[bool] = True """Config type key and default source-id kind of this source (one vocabulary).""" TAKES_TAG_ONLY_COLUMNS: ClassVar[bool] = True diff --git a/src/orcapod/pipeline/async_orchestrator.py b/src/orcapod/pipeline/async_orchestrator.py index a9f87691c..9edd1614e 100644 --- a/src/orcapod/pipeline/async_orchestrator.py +++ b/src/orcapod/pipeline/async_orchestrator.py @@ -209,7 +209,9 @@ async def _run_async( held_rows: Mapping[Any, list[tuple[TagProtocol, DataProtocol]]] | None = None, ) -> OrchestratorResult: """Core async logic: wire channels, launch tasks, collect results.""" - from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod + from orcapod.core.operators.static_output_pod import ( + rows_on_read, + ) from orcapod.pipeline.observer import NoOpObserver run_id = run_id or str(uuid.uuid4()) @@ -365,9 +367,7 @@ async def _run_async( return OrchestratorResult( node_outputs=( - StreamsOnRead( - collectors, StaticOutputOperatorPod._materialize_upstream - ) + StreamsOnRead(collectors, rows_on_read) if materialize_results else {} ) diff --git a/src/orcapod/protocols/core_protocols/streams.py b/src/orcapod/protocols/core_protocols/streams.py index 0ab5ecdf0..bf6272745 100644 --- a/src/orcapod/protocols/core_protocols/streams.py +++ b/src/orcapod/protocols/core_protocols/streams.py @@ -194,9 +194,11 @@ def arrow_schema(self) -> "pa.Schema": def arrow_types_declared(self) -> bool: """Whether ``arrow_schema()`` holds the rows' own Arrow types. - ``False`` only when the stream cannot type itself without rows (an unbound - slot, a ``PollingSource`` never polled; ITL-1089): its schema is then converted - from the Python schema. + ``False`` when the stream cannot type itself without rows (an unbound slot, a + ``PollingSource`` never polled; ITL-1089), or its rows decide its types (a + narrower bind, an output held as its rows): its schema is then converted from + the Python schema, and its names come in no guaranteed order; no consumer + relies on their order (ITL-1347). """ ... diff --git a/tests/test_pipeline/test_rows_on_read.py b/tests/test_pipeline/test_rows_on_read.py index 971969730..29c1f5f01 100644 --- a/tests/test_pipeline/test_rows_on_read.py +++ b/tests/test_pipeline/test_rows_on_read.py @@ -252,3 +252,184 @@ def test_replay_of_a_table_the_whole_table_build_cannot_use( else: replay.run(observer=observer) assert ("end", "selected") in observer.events + + +# ── round 4: the boundary of the eager route, and the lazy output itself ────── + + +DELIVERED: list[int] = [] + + +def _deliver(x: int, ctx: Any) -> None: + DELIVERED.append(x) + + +def _leaf_run(job: PipelineJob, label: str) -> _NodeEvents: + """Run only ``label`` (a source node), as a leaf of a direct sync DAG.""" + dag: OrcaDAG[Any] = OrcaDAG() + dag.add_node(job.nodes[label]) + observer = _NodeEvents() + SyncPipelineOrchestrator().run(dag, observer=observer, materialize_results=False) + return observer + + +def test_a_bound_tap_stream_delivers_every_row_as_main_does() -> None: + """A side-effect stream bound to a slot is not a library source kind: its rows. + + The node iterates it as ``main`` did, delivering every row, and a leaf completes + (Codex on PR #485, round 4: the eager route read ``as_table()`` instead). + """ + from orcapod.side_effects import tap_pod + + tap = tap_pod(_deliver) + DELIVERED.clear() + raw = _with_source_x([[None, [[]]], [None, [[]]]], _UNCONVERTIBLE) + tapped: Any = tap.process(raw) + job = PipelineJob(name="tap_bound", database=InMemoryArrowDatabase()) + with job: + _plain().select_data_columns(["x"], label="selected") + job.bind(sources={"s": tapped}) + observer = _leaf_run(job, "s") + assert DELIVERED == [1, 2] + assert observer.events == [("start", "s"), ("end", "s")] + + +@pytest.mark.parametrize( + "make", + [ + pytest.param(lambda: _plain().select_data_columns(["x"]), id="operator"), + pytest.param( + lambda: ArrowTableStream(_source_table(), tag_columns=["k"]), id="raw" + ), + ], +) +def test_a_bound_stream_that_is_not_a_source_kind_hands_on_its_rows(make: Any) -> None: + """Only a library source kind whose table is its rows (``TABLE_IS_ROWS``) is eager.""" + from orcapod.core.operators.static_output_pod import RowsOnRead + + job = PipelineJob(name="bound_kinds", database=InMemoryArrowDatabase()) + with job: + _plain().select_data_columns(["x"], label="selected") + job.bind(sources={"s": make()}) + assert isinstance(job.nodes["s"].execute(), RowsOnRead) + + +def test_a_library_source_kind_is_eager() -> None: + from orcapod.core.operators.static_output_pod import RowsOnRead + + job = PipelineJob(name="eager_kind", database=InMemoryArrowDatabase()) + with job: + _plain().select_data_columns(["x"], label="selected") + assert not isinstance(job.nodes["s"].execute(), RowsOnRead) + + +def test_an_empty_output_is_derived_at_the_edge() -> None: + """A source with no row: its zero-row output is derived where the successor reads. + + An observer that rebinds the source when it ends changes what the successor + receives, as on ``main`` (Codex on PR #485, round 4). + """ + + def empty(mark: str) -> ArrowTableSource: + field = pa.field("x", pa.int64(), nullable=False, metadata={"mark": mark}) + table = pa.table({"k": pa.array([], pa.int64()), "x": pa.array([], pa.int64())}) + table = pa.Table.from_arrays( + table.columns, + schema=pa.schema([pa.field("k", pa.int64(), nullable=False), field]), + ) + return ArrowTableSource(table, tag_columns=["k"], source_id="s") + + job = PipelineJob(name="empty_edge", database=InMemoryArrowDatabase()) + with job: + empty("before").select_data_columns(["x"], label="selected") + slot = next(label for label in job.nodes if label != "selected") + node = job.nodes[slot] + + class RebindsAtEnd(NoOpObserver): + def contextualize(self, *identity_path: str) -> RebindsAtEnd: + return self + + def on_node_end(self, node_label: str, node_hash: str) -> None: + if node_label == slot: + node.bound_source = empty("after") + + job.run(observer=RebindsAtEnd()) + kept = job.nodes["selected"].as_table() + assert kept.schema.field("x").metadata == {b"mark": b"after"} + + +def test_an_operator_with_an_empty_result_is_not_called_again() -> None: + """An empty result's zero-row form is derived at the edge, never by a second call. + + An operator that raises on empty input completes as a leaf, as on ``main`` + (Codex on PR #485, round 4). + """ + from orcapod.operators import SelectDataColumns + + calls: list[int] = [] + + class EmptyThenRaises(SelectDataColumns): + def unary_static_process(self, stream: Any) -> Any: + rows = stream.as_table().num_rows + calls.append(rows) + if rows == 0: + raise ValueError("cannot process empty input") + return super().unary_static_process(stream).polars_filter(x=-1) + + job = PipelineJob(name="empty_result", database=InMemoryArrowDatabase()) + with job: + EmptyThenRaises(["x"])(_plain(), label="emptied") + observer = _NodeEvents() + job.run(observer=observer) + assert ("end", "emptied") in observer.events + assert 0 not in calls + + +@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"]) +def test_returned_function_rows_keep_their_meta(asynchronous: bool) -> None: + """``node_outputs[node].iter_data()`` gives the node's own rows, meta included.""" + from orcapod import function_pod + from orcapod.pipeline import AsyncPipelineOrchestrator + + @function_pod(output_keys="y") + def plus(x: int) -> int: + return x + 1 + + job = PipelineJob(name="returned_rows", database=InMemoryArrowDatabase()) + with job: + plus.pod(_plain(), label="plus") + dag: OrcaDAG[Any] = OrcaDAG() + dag.add_edge(job.nodes["s"], job.nodes["plus"]) + orchestrator: Any = ( + AsyncPipelineOrchestrator() if asynchronous else SyncPipelineOrchestrator() + ) + result = orchestrator.run(dag) + rows = list(result.node_outputs[job.nodes["plus"]].iter_data()) + assert rows + assert all("__computed" in data.keys(columns={"meta": True}) for _, data in rows) + + +def test_a_lazy_output_is_described_and_opened_without_reading() -> None: + """Describing an unread output, or opening its channel, builds nothing. + + The first read of the channel raises what the rows' build raises (Codex on PR + #485, round 4). + """ + import asyncio + + from orcapod.core.operators.static_output_pod import RowsOnRead + from orcapod.protocols.core_protocols import StreamProtocol + + job = PipelineJob(name="lazy_out", database=InMemoryArrowDatabase()) + with job: + _plain().select_data_columns(["x"], label="selected") + job.bind(sources={"s": _unconvertible()}) + out: Any = job.nodes["s"].execute() + assert isinstance(out, RowsOnRead) + assert isinstance(out, StreamProtocol) + assert not out.arrow_types_declared + assert "x" in out.arrow_schema().names + channel = out.open_channel() + assert out._stream is None # pyright: ignore[reportPrivateUsage] # nothing built + with pytest.raises(pa.ArrowTypeError, match="Expected bytes"): + asyncio.run(channel.collect()) From 6844386531b682d5fc029c4034fea62d9aaa7161 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 09:40:38 -0800 Subject: [PATCH 49/86] fix(pipeline): type the protocol-member walk and round-4 tests (ITL-1360) Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/operators/static_output_pod.py | 3 ++- tests/test_pipeline/test_rows_on_read.py | 5 +++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index 5f51eb2a4..d6fc8e1bd 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -1496,7 +1496,8 @@ def _stream_protocol_members() -> list[str]: there lets ``RowsOnRead`` pass the check on every supported Python. """ names: set[str] = set() - for base in StreamProtocol.__mro__: + protocol = cast(type, cast(object, StreamProtocol)) + for base in protocol.__mro__: if base is object or base.__name__ in ("Protocol", "Generic"): continue names.update(name for name in vars(base) if not name.startswith("_")) diff --git a/tests/test_pipeline/test_rows_on_read.py b/tests/test_pipeline/test_rows_on_read.py index 29c1f5f01..97fa85171 100644 --- a/tests/test_pipeline/test_rows_on_read.py +++ b/tests/test_pipeline/test_rows_on_read.py @@ -281,7 +281,7 @@ def test_a_bound_tap_stream_delivers_every_row_as_main_does() -> None: """ from orcapod.side_effects import tap_pod - tap = tap_pod(_deliver) + tap: Any = tap_pod(_deliver) DELIVERED.clear() raw = _with_source_x([[None, [[]]], [None, [[]]]], _UNCONVERTIBLE) tapped: Any = tap.process(raw) @@ -374,7 +374,8 @@ def unary_static_process(self, stream: Any) -> Any: calls.append(rows) if rows == 0: raise ValueError("cannot process empty input") - return super().unary_static_process(stream).polars_filter(x=-1) + result: Any = super().unary_static_process(stream) + return result.polars_filter(x=-1) job = PipelineJob(name="empty_result", database=InMemoryArrowDatabase()) with job: From 60a9e84cb3ca7b51a779cddb85024b42848c4abb Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 09:42:36 -0800 Subject: [PATCH 50/86] fix(function_node): stage 3-4 outputs keep their rows, tables built when read (ITL-1361) Merges stage 2's round-4 rule. A function node's and a side-effect node's output is RowsOnRead of the rows main returned, unchanged (meta included): its table is built when first read, by the stored-table pieces (L3) or F at the passed rows (L4), and by main's row path where those cannot build. RowsOnRead takes that builder (build=). Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/nodes/function_node.py | 34 +++++++++++++------ .../core/operators/static_output_pod.py | 30 ++++++++++++---- 2 files changed, 47 insertions(+), 17 deletions(-) diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 922da6842..6f8b95f9d 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -358,11 +358,17 @@ def passed_rows_output_stream( table = input_stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS) if passed is not None: table = table.take(pa.array(passed, type=pa.int64())) - try: - return StaticOutputOperatorPod._output_stream(table, input_stream.keys(), node) # pyright: ignore[reportPrivateUsage] # F with the node's identity - except RowBuiltFormUnavailable: - # The rows decide, built where a successor reads them (``RowsOnRead``). - return rows_on_read(rows, node) + keys = input_stream.keys() + + def build() -> StreamProtocol: + try: + return StaticOutputOperatorPod._output_stream(table, keys, node) # pyright: ignore[reportPrivateUsage] # F with the node's identity + except RowBuiltFormUnavailable: + # The rows decide, by main's row path. + return StaticOutputOperatorPod._materialize_upstream(rows, node) # pyright: ignore[reportPrivateUsage] + + # The rows passed on, unchanged; the table built when read (``RowsOnRead``). + return rows_on_read(rows, node, build) class _LazyRows: @@ -2646,12 +2652,20 @@ def _output_stream( (``RowsOnRead``): the sync orchestrator builds it where a successor reads it, as ``main`` rebuilt the rows there, and a leaf's is never built (ITL-1347). """ - from orcapod.core.operators.static_output_pod import rows_on_read + from orcapod.core.operators.static_output_pod import ( + StaticOutputOperatorPod, + rows_on_read, + ) + + def build() -> StreamProtocol: + # The stored results' table where it serves (L3), else the row path. + output = self._output_from_stored_tables(rows) + if output is not None: + return output + return StaticOutputOperatorPod._materialize_upstream(rows, self) # pyright: ignore[reportPrivateUsage] # main's row path - output = self._output_from_stored_tables(rows) - if output is not None: - return output - return rows_on_read(rows, self) + # The rows themselves, unchanged, its table built when read (``RowsOnRead``). + return rows_on_read(rows, self, build) def _output_from_stored_tables( self, rows: list[tuple[TagProtocol, DataProtocol]] diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index d6fc8e1bd..c82628d7c 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -5,6 +5,7 @@ from abc import abstractmethod from collections.abc import ( AsyncIterator, + Callable, Collection, Coroutine, Iterable, @@ -1396,23 +1397,34 @@ class RowsOnRead: _orcapod_row_built_output = False def __init__( - self, rows: Iterable[tuple[TagProtocol, DataProtocol]], node: StreamProtocol + self, + rows: Iterable[tuple[TagProtocol, DataProtocol]], + node: StreamProtocol, + build: Callable[[], StreamProtocol] | None = None, ) -> None: """Hold ``node``'s rows; nothing is built. Args: rows: The rows ``main`` would hold, in order (read once, here). node: The node (or stream) whose output they are. + build: Builds the table another way that gives ``main``'s row path's + result (a function node's stored-table output, ITL-1361); default + the row path itself. """ self._rows: list[tuple[TagProtocol, DataProtocol]] = list(rows) self._node = node + self._build = build self._stream: StreamProtocol | None = None def built(self) -> StreamProtocol: - """The stream, built from the rows on the first call (``main``'s row path).""" + """The stream, built on the first call (``build``, or ``main``'s row path).""" if self._stream is None: - self._stream = StaticOutputOperatorPod._materialize_upstream( - self._rows, self._node + self._stream = ( + self._build() + if self._build is not None + else StaticOutputOperatorPod._materialize_upstream( + self._rows, self._node + ) ) return self._stream @@ -1520,20 +1532,24 @@ def delegate(self: RowsOnRead, *args: Any, **kwargs: Any) -> Any: def rows_on_read( - rows: Iterable[tuple[TagProtocol, DataProtocol]], node: StreamProtocol + rows: Iterable[tuple[TagProtocol, DataProtocol]], + node: StreamProtocol, + build: Callable[[], StreamProtocol] | None = None, ) -> StreamProtocol: """``RowsOnRead`` of ``rows`` as a stream (it delegates every member to the built one). Args: rows: The rows ``main`` would hold, in order (read once, here). node: The node (or stream) whose output they are. + build: Builds the table another way that gives ``main``'s row path's result; + default the row path itself. Returns: - The output, built from the rows when first read. + The output, built when first read. """ # ``RowsOnRead`` stands for the stream it builds; the checker cannot see that # through its delegation, so the cast goes through object. - return cast(StreamProtocol, cast(object, RowsOnRead(rows, node))) + return cast(StreamProtocol, cast(object, RowsOnRead(rows, node, build))) def at_edge(stream: StreamProtocol) -> StreamProtocol: From 0e357ee07e02b2de429f02b34ebffff0338f9463 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 09:59:53 -0800 Subject: [PATCH 51/86] fix(pipeline): eager only for a source kind's own reading; result order; channel checks (ITL-1360) Codex on PR #485, round 5. - table_is_rows(source): TABLE_IS_ROWS is honoured only when the declaring class reads the source, the source's own class or a subclass that overrides none of the row readers (iter_data, as_table, __iter__, async_iter_data, keys, output_schema); a filtering subclass hands on its rows, as main iterated them. - An operator node keeps, stores and hands on its result in the order the result's rows have (DynamicPodStream.result_keys), never re-placed by the prediction. - A channel without declared types compares names as a multiset (a duplicate column is refused), and each source-info column's token type must settle with the batches already accepted, refused at send with SourceInfoTypesDisagree otherwise. - A lazy output describes itself with its node's own description, and a description from declared types takes the Arrow schemas a slot states, never a conversion of Python types (time64[ns], decimal256). - Changelog corrected (no order promise where types are undeclared; when arrow_types_declared is false; what reading node_outputs builds). - Observer-only limit pinned: spec row e11 (open) and a strict xfail. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1360.md | 45 +++-- .../dev/specs/itl-1347-job-table-transport.md | 1 + src/orcapod/core/nodes/operator_node.py | 6 +- src/orcapod/core/nodes/source_node.py | 3 +- .../core/operators/static_output_pod.py | 25 ++- src/orcapod/core/record_batch_channels.py | 50 ++++- src/orcapod/core/sources/base.py | 34 ++++ src/orcapod/core/streams/base.py | 22 ++- .../test_record_batch_channels.py | 47 +++++ tests/test_pipeline/test_rows_on_read.py | 171 ++++++++++++++++++ 10 files changed, 374 insertions(+), 30 deletions(-) diff --git a/changelog.d/ITL-1360.md b/changelog.d/ITL-1360.md index 6579ccde7..dbe931f26 100644 --- a/changelog.d/ITL-1360.md +++ b/changelog.d/ITL-1360.md @@ -4,28 +4,33 @@ function and side-effect job node (and of the node protocols) returned the node's rows as a list of (tag, data) pairs, and the sync orchestrator rebuilt a table from them for each successor. It now returns the node's output stream, which the sync orchestrator hands to - every successor as it is: a source node gives its source's Arrow table, and an operator - node its result's table (REPLAY: its stored table), each in the form a table built from - the rows has, without making the rows. Where that is not provably the table its rows give - (a narrower bind, a table the whole-table build cannot use, a held node, a function or - side-effect node), the node hands on its rows, built into a table where a successor reads - them, as before. `OrchestratorResult.node_outputs` holds each - node's output stream (the async orchestrator builds it when it is first read), and - on the sync path a held node gives the stream of its held rows; the async path still - sends a held node's rows as the run's plan took them (`held_rows`). Every - successor's input is unchanged: columns, types, row order, system tags, source info, - pipeline and content hashes. No hash, stored table or output changes. An operator node's - table is built once, for what it keeps and for every successor, instead of once to keep - and once per successor. The first two stages of the table transport between job nodes - (`docs/dev/specs/itl-1347-job-table-transport.md`). (ITL-1347, ITL-1360) + every successor. A node bound to a library source kind whose table is its rows + (`TABLE_IS_ROWS`) gives its source's Arrow table, and an operator node its result's + table (REPLAY: its stored table), each in the form a table built from the rows has, + without making the rows. Every other output (a narrower bind, another kind of bound + stream, a table the whole-table build cannot use, a result with no row, a held node, a + function or side-effect node) is the node's rows, unchanged, whose table is built where + a successor reads it, as before. `OrchestratorResult.node_outputs` holds each node's + output stream: its rows (`iter_data()`) are the rows the node returned, and its table is + built when the table is first read (`as_table()`, a successor's edge); on the sync path + a held node gives the stream of its held rows, and the async path still sends a held + node's rows as the run's plan took them (`held_rows`). Every successor's input is + unchanged: columns, types, row order, system tags, source info, pipeline and content + hashes, and an error surfaces where and when it did. No hash, stored table or output + changes. An operator node's table is built once, for what it keeps and for every + successor, instead of once to keep and once per successor. The first two stages of the + table transport between job nodes (`docs/dev/specs/itl-1347-job-table-transport.md`). + (ITL-1347, ITL-1360) ### Added - **`arrow_schema()` and `arrow_types_declared` on every stream** — `StreamProtocol`, every stream and every source node state the Arrow schema of the columns a job node - passes on (user tags, system tags, data and source info, in row order), without reading, - computing or polling a row. System-tag and source-info fields are stated nullable, since - a table decides their flags from its values; a `null` column keeps the `null` type of a - table with no rows. `arrow_types_declared` is false only for a stream that cannot type - itself without rows (an unbound slot, a `PollingSource` not yet polled), whose schema is - converted from its Python schema. (ITL-1360) + passes on (user tags, system tags, data and source info), without reading, computing or + polling a row. System-tag and source-info fields are stated nullable and a source-info + field's type as the declared token type: a complete table decides both from its values, + so a consumer must not rely on them. A `null` column keeps the `null` type of a table + with no rows. `arrow_types_declared` is false where the rows decide the types: a stream + that cannot type itself without rows (an unbound slot, a `PollingSource` not yet + polled), a narrower bind, and an output held as its rows. Such a description gives the + declared names and types, in no guaranteed order. (ITL-1360) diff --git a/docs/dev/specs/itl-1347-job-table-transport.md b/docs/dev/specs/itl-1347-job-table-transport.md index 086097dc3..f81936af1 100644 --- a/docs/dev/specs/itl-1347-job-table-transport.md +++ b/docs/dev/specs/itl-1347-job-table-transport.md @@ -529,6 +529,7 @@ built from them by `main`'s row path where a successor reads them (`RowsOnRead`, | e6 | Async values that depend on an earlier validation of the same operator object | `SemiJoin._validated_common_keys` and `Index._element_arrow_type_fallback` hold the last validation's values (ITL-858, section 1.2). One operator object applied to two streams can use the other stream's keys or fallback type | Read from each input's description, with no state | The ITL-858 finding; filed as ITL-1358. Reproducer: one `SemiJoin` instance validated on stream B, then run async over stream A with other keys. To be confirmed in stage 5 | ITL-1358 (filed); fixed with stage 5 once a reproducer confirms it | | e7 | What a consumer does after its producer failed (async, failure path) | The producer closes its output in `finally`, so a consumer sees a normal end and may finish, and a `LOG` operator node may store, a partial result before the task group cancels it | Readers raise `UpstreamFailedError` at the failure point instead of seeing a normal end, so no consumer finishes, or stores its result, as if its input were complete. Batches a consumer processed before the failure are still processed, and a streaming node may already have passed them on or a function node stored results for them, as on `main`; there is no rollback. A barrier operator never computes over a partial input. The run raises the producer's own error, as today | A candidate race, to be confirmed with a reproducer in stage 5: a `fail_fast` function node raising on row 3 of 6, feeding a `Select` node in `LOG` mode; check the operator cache after the failed run. If `main` never stores in practice, this row is no difference | filed by the developer only once a test reproduces it | | e8 | Meta columns of an async side-effect node's rows | An async side-effect node passes on and holds the rows it receives as they are, so a computed row keeps its `__computed` meta column (from the cached function pod), and the node's `as_table(all_info=True)` shows it. On sync, its input is rebuilt from rows (`_rows_to_table` drops meta), so the column is absent | Async drops input meta columns as sync does. With table transport this follows from the transport columns, which hold no meta column | A `main` bug: the async and sync paths give the node different columns. Found by the stage 0 harness on `job-speed` 0e15d0db, which does not change side-effect nodes; the stage 0 differential checks it on pinned `main`. Reproducer: a function node (with a result store) feeding a `tap_pod`, async against sync, comparing the side-effect node's `as_table(all_info=True)` columns | approved (developer, 2026-11-22) | +| e11 | An empty source fanned out to two operators, with an observer that rebinds the source between the two edges | Each successor's input is rebuilt at its own edge, so the second sees the rebound source's zero-row form (its field metadata) | The output held as its rows (`RowsOnRead`) is built once, at the first edge, and the second edge reuses it, so the second successor sees the first edge's form | Not a `main` bug: an observer that mutates the graph mid-run (Codex on PR #485, round 5). Reproducer: `tests/test_pipeline/test_rows_on_read.py::test_a_fanned_out_empty_source_rebound_between_edges` (strict xfail) | open: not approved; the coordinator takes it to the developer as a documented limit (2026-11-22) | **Resolved: refusals after rows have flowed (was c, question 9).** The developer's `Rejoin` rule (ITL-1355) removes every data-dependent refusal from `Rejoin`: it checks only what its diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index c7b237fe3..b839bddf9 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -1711,9 +1711,11 @@ def execute( # The result's table, as the table built from its rows would be, without # making the rows (ITL-1347, stage 2). result_table = result_stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS) - keys = result_stream.keys() + # The order the result's rows have (``result_keys``), never the prediction. + result_keys = getattr(result_stream, "result_keys", None) + keys = result_keys() if callable(result_keys) else result_stream.keys() tag_keys = keys[0] - data_tags = stream_data_tags(result_stream) + data_tags = data_tag_names(*keys) # Cache, in row order with or without rows (ITL-1131, ITL-1133). if result_table.num_rows: diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index 8795c9702..5732b3142 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -26,6 +26,7 @@ from orcapod.core.base import TraceableBase from orcapod.core.datagrams import Data, Tag from orcapod.core.operators.drop_nulls import _without_none # pyright: ignore[reportPrivateUsage] # DropNulls' rule for removing None from a type, shared, never copied +from orcapod.core.sources.base import table_is_rows from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.core.streams.base import ( ZERO_ROW_INPUT_COLUMNS, @@ -1836,7 +1837,7 @@ def _rows_table( ) if self._declared_form is not None: return None - if not getattr(type(self._bound_source), "TABLE_IS_ROWS", False): + if not table_is_rows(self._bound_source): # Not a library source kind whose table is its rows (a side-effect or # function pod stream, an operator's result, a raw stream, a poller): its # rows, as main iterated them. diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index d6fc8e1bd..0816a1bb2 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -1431,12 +1431,15 @@ async def async_iter_data( yield row def arrow_schema(self) -> pa.Schema: - """The node's declared description, from its Python schema; builds nothing. + """The node's own description (``arrow_schema()``); builds nothing. - The rows decide the Arrow types (``arrow_types_declared`` is false): a - description with undeclared types gives the declared names, with no - guaranteed order. + The rows decide the Arrow types (``arrow_types_declared`` is false): the + description gives the node's names and declared types, with no guaranteed + order. """ + describe = getattr(self._node, "arrow_schema", None) + if callable(describe): + return cast(pa.Schema, describe()) from orcapod.core.streams.base import stream_arrow_schema return stream_arrow_schema(self._node, from_table=False) @@ -1837,6 +1840,20 @@ def iter_data( ) return self._cached_stream.iter_data() + def result_keys(self) -> tuple[tuple[str, ...], tuple[str, ...]]: + """The keys of the stream the operator returned: the order its rows have. + + The prediction (``keys``) never reorders a result: an operator node keeps, + stores and hands on its result in the order its rows have, as ``main`` built + it from them (ITL-1347). + """ + self._refresh() + assert self._cached_stream is not None, ( + "StreamProtocol has not been updated or is empty." + ) + tag_keys, data_keys = self._cached_stream.keys() + return tuple(tag_keys), tuple(data_keys) + def head( self, n: int = 10, diff --git a/src/orcapod/core/record_batch_channels.py b/src/orcapod/core/record_batch_channels.py index 842e62a4a..da5edeb08 100644 --- a/src/orcapod/core/record_batch_channels.py +++ b/src/orcapod/core/record_batch_channels.py @@ -22,6 +22,7 @@ from orcapod.channels import ChannelClosed from orcapod.core.operators.static_output_pod import ( + SourceInfoTypesDisagree, stream_from_batches, transport_schema, ) @@ -150,6 +151,9 @@ def __init__( # batch's when the stream cannot say its Arrow types without rows. self._schema: pa.Schema | None = None self._schema_known = False + # Each source-info column's token type as the batches accepted so far settle it + # (``_settled_token_types``): a later batch must settle with it. + self._token_types: dict[str, pa.DataType] = {} self._changed = asyncio.Event() @property @@ -194,7 +198,7 @@ def _check_schema(self, batch: pa.RecordBatch) -> None: # stream's, in no guaranteed order (an undeclared description gives names # only). A refused batch sets nothing. names = batch.schema.names - if set(names) != set(row_built_names(names, self._stream.keys())): + if sorted(names) != sorted(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 " @@ -207,7 +211,9 @@ def _check_schema(self, batch: pa.RecordBatch) -> None: f"A record batch sent as {_named(self._stream)} does not have that " + f"stream's columns: {mismatch}." ) + token_types = _settled_token_types(batch, self._token_types) self._schema = schema + self._token_types = token_types async def send(self, batch: pa.RecordBatch) -> None: """Send one Arrow record batch of the stream's transport columns. @@ -356,6 +362,48 @@ def _named(stream: Any) -> str: # pyright: ignore[reportExplicitAny] # any str return repr(label) if label else repr(stream) +def _settled_token_types( + batch: pa.RecordBatch, accepted: dict[str, pa.DataType] +) -> dict[str, pa.DataType]: + """Each source-info column's token type, settled with the batches already accepted. + + A source-info column's type follows its tokens over the complete table + (``StaticOutputOperatorPod._type_source_info_by_values``): the description leaves it + open, but the channel's batches must settle together, or their result could not be + built. A batch whose tokens give a column a type the accepted batches do not is + refused at send, with the error the complete table would raise. + + Args: + batch: The batch being sent. + accepted: Each column's token type from the batches accepted so far. + + Returns: + The token types with this batch accepted. + + Raises: + SourceInfoTypesDisagree: If the batch's tokens give a column two types, or a + type other than the accepted batches'. + """ + settled = dict(accepted) + for field, column in zip(batch.schema, batch.columns, strict=True): + if not field.name.startswith(constants.SOURCE_PREFIX): + continue + if pa.types.is_large_string(field.type): + kinds = {pa.large_string()} + else: + kinds = { + arrow_utils.source_info_arrow_type(value) + for value in column.to_pylist() + } + if field.name in settled: + kinds.add(settled[field.name]) + if len(kinds) > 1: + raise SourceInfoTypesDisagree(field.name) + if kinds: + (settled[field.name],) = kinds + return settled + + 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``. diff --git a/src/orcapod/core/sources/base.py b/src/orcapod/core/sources/base.py index 1f8eef123..4b62f45dd 100644 --- a/src/orcapod/core/sources/base.py +++ b/src/orcapod/core/sources/base.py @@ -47,6 +47,40 @@ def saved_tag_only_columns(config: dict[str, Any]) -> bool | list[str]: return config["tag_only_columns"] +_ROW_READERS = ( + "iter_data", + "as_table", + "__iter__", + "async_iter_data", + "keys", + "output_schema", +) +"""The members a source's rows and table are read through.""" + + +def table_is_rows(source: object) -> bool: + """Whether ``source``'s ``as_table()`` and ``iter_data()`` provably read the same data. + + True only when the class that declares ``TABLE_IS_ROWS = True`` (a library source + kind) reads ``source``: ``source``'s own class, or a subclass that overrides none of + the members the rows and the table are read through (``_ROW_READERS``). A subclass + that changes how it reads (a filtering ``iter_data``) is not that kind any more, and + a job node bound to it hands on its rows, as ``main`` iterated them (ITL-1347). + + Args: + source: The object bound to a source slot. + + Returns: + Whether F of its table is the table its rows give. + """ + for klass in type(source).__mro__: + if "TABLE_IS_ROWS" in vars(klass): + return bool(vars(klass)["TABLE_IS_ROWS"]) + if any(name in vars(klass) for name in _ROW_READERS): + return False + return False + + class RootSource(StreamBase): """Abstract base class for all root sources in Orcapod. diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py index c61c38c17..00fa55f40 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -415,8 +415,26 @@ def stream_arrow_schema( # reads). A source's tokens are strings, so each data column's source info is # a string field. tag_schema, data_schema = typed.output_schema(columns={"system_tags": True}) - converter = StaticOutputOperatorPod._upstream_context(typed).type_converter # pyright: ignore[reportPrivateUsage] # the one place that resolves an upstream's context - table = arrow_utils.make_empty_table({**tag_schema, **data_schema}, converter) + stated = getattr(stream, "arrow_schemas", None) + if isinstance(stated, tuple): + # The Arrow types the stream declares itself (a slot): never a conversion + # of its Python types, which may have no Arrow type of their own. + tag_arrow, data_arrow = cast("tuple[pa.Schema, pa.Schema]", stated) + fields = [ + *tag_arrow, + *( + pa.field(name, pa.large_string()) + for name in tag_schema + if name not in tag_arrow.names + ), + *(f for f in data_arrow if f.name not in tag_arrow.names), + ] + table = pa.schema(fields).empty_table() + else: + converter = StaticOutputOperatorPod._upstream_context(typed).type_converter # pyright: ignore[reportPrivateUsage] # the one place that resolves an upstream's context + table = arrow_utils.make_empty_table( + {**tag_schema, **data_schema}, converter + ) for name in data_schema: table = table.append_column( pa.field(f"{constants.SOURCE_PREFIX}{name}", pa.large_string()), diff --git a/tests/test_channels/test_record_batch_channels.py b/tests/test_channels/test_record_batch_channels.py index fe6767385..cf99ec808 100644 --- a/tests/test_channels/test_record_batch_channels.py +++ b/tests/test_channels/test_record_batch_channels.py @@ -1910,3 +1910,50 @@ def test_stream_from_batches_is_the_one_conversion() -> None: 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 + + +def test_a_batch_with_a_duplicate_column_is_refused() -> None: + """Without Arrow types the names are compared as a multiset: a duplicate is refused + (Codex on PR #485, round 5).""" + table = source().as_table(columns=ALL) + stream = _UntypedStream( + table, tag_columns=["subject", "trial"], data_tags=["trial"] + ) + (batch,) = batches_of(stream) + name = next(n for n in batch.schema.names if not n.startswith(("_", "subject"))) + doubled = batch.append_column(batch.schema.field(name), batch.column(name)) + + async def write() -> None: + output = OutputChannel(stream) + await output.send(doubled) + + with pytest.raises(ValueError, match="the stream's keys are"): + run(write) + + +def test_a_batch_whose_tokens_cannot_settle_with_accepted_ones_is_refused() -> None: + """A second batch with list tokens where the first had string tokens is refused at + send, with the error the complete table would raise (Codex on PR #485, round 5).""" + from orcapod.core.operators.static_output_pod import SourceInfoTypesDisagree + + stream = source() + (batch,) = batches_of(stream) + column = next(n for n in batch.schema.names if n.startswith("_source_")) + position = batch.schema.get_field_index(column) + tokens = pa.large_list(pa.large_string()) + listed = pa.RecordBatch.from_arrays( + [ + *batch.columns[:position], + pa.array([["t"]] * batch.num_rows, tokens), + *batch.columns[position + 1 :], + ], + schema=batch.schema.set(position, pa.field(column, tokens, nullable=True)), + ) + + async def write() -> None: + output = OutputChannel(stream) + await output.send(batch) + await output.send(listed) + + with pytest.raises(SourceInfoTypesDisagree, match=column): + run(write) diff --git a/tests/test_pipeline/test_rows_on_read.py b/tests/test_pipeline/test_rows_on_read.py index 97fa85171..b237f1987 100644 --- a/tests/test_pipeline/test_rows_on_read.py +++ b/tests/test_pipeline/test_rows_on_read.py @@ -434,3 +434,174 @@ def test_a_lazy_output_is_described_and_opened_without_reading() -> None: assert out._stream is None # pyright: ignore[reportPrivateUsage] # nothing built with pytest.raises(pa.ArrowTypeError, match="Expected bytes"): asyncio.run(channel.collect()) + + +# ── round 5 ────────────────────────────────────────────────────────────────── + + +def _subclass_overriding(member: str) -> type: + """An ``ArrowTableSource`` subclass that overrides ``member`` (reading as before).""" + from orcapod.core.sources import ArrowTableSource as Base + + def through(self: Any, *args: Any, **kwargs: Any) -> Any: + return getattr(super(cls, self), member)(*args, **kwargs) + + cls = type(f"Overrides_{member}", (Base,), {member: through}) + return cls + + +@pytest.mark.parametrize( + "member", + ["iter_data", "as_table", "__iter__", "async_iter_data", "keys", "output_schema"], +) +def test_a_subclass_that_overrides_a_reader_is_not_a_table_is_rows_kind( + member: str, +) -> None: + """``TABLE_IS_ROWS`` is not inherited past an override of how rows are read.""" + from orcapod.core.sources.base import table_is_rows + + table = _source_table().select(["k", "x"]) + cls = _subclass_overriding(member) + source = cls(table, tag_columns=["k"], tag_only_columns=True, source_id="s") + assert not table_is_rows(source) + plain = ArrowTableSource( + table, tag_columns=["k"], tag_only_columns=True, source_id="s" + ) + assert table_is_rows(plain) + subclass = type("Plain", (ArrowTableSource,), {}) + assert table_is_rows( + subclass(table, tag_columns=["k"], tag_only_columns=True, source_id="s") + ) + + +def test_a_filtering_subclass_delivers_only_its_rows() -> None: + """A subclass whose ``iter_data`` filters is read through it, as on ``main``.""" + + class AboveTen(ArrowTableSource): + def iter_data(self) -> Any: + return (row for row in super().iter_data() if row[1]["x"] > 10) + + table = pa.table({"k": pa.array([1, 2]), "x": pa.array([10, 20])}) + job = PipelineJob(name="filtering", database=InMemoryArrowDatabase()) + with job: + ArrowTableSource( + table, tag_columns=["k"], tag_only_columns=True, source_id="s" + ).select_data_columns(["x"], label="selected") + job.bind( + sources={ + "s": AboveTen( + table, tag_columns=["k"], tag_only_columns=True, source_id="s" + ) + } + ) + job.run() + assert job.nodes["selected"].as_table()["x"].to_pylist() == [20] + + +def test_an_operator_result_keeps_its_own_column_order() -> None: + """A result laid out ``y, x`` against a prediction ``x, y`` is kept, stored and + handed on as ``y, x``, as ``main`` built it from the result's rows.""" + from orcapod.operators import SelectDataColumns + + class Reordered(SelectDataColumns): + def unary_static_process(self, stream: Any) -> Any: + out: Any = super().unary_static_process(stream) + table = out.as_table(columns={"source": True, "system_tags": True}) + names = [n for n in table.column_names if n not in ("x", "y")] + plain = [n for n in names if not n.startswith("_source_")] + source = ["_source_y", "_source_x"] + rest = [n for n in names if n.startswith("_source_") and n not in source] + return ArrowTableStream( + table.select([*plain, "y", "x", *source, *rest]), tag_columns=["k"] + ) + + database = InMemoryArrowDatabase() + job = PipelineJob(name="reordered", database=database) + with job: + source = DictSource( + [{"k": 1, "x": 1, "y": 2}, {"k": 2, "x": 3, "y": 4}], + tag_columns=["k"], + tag_only_columns=True, + source_id="s", + ) + Batch(batch_size=2)(Reordered(["x", "y"])(source, label="reordered"), label="b") + job.nodes["reordered"].attach_databases( + pipeline_database=database.at("log"), cache_mode=CacheMode.LOG + ) + job.run() + expected = ["k", "y", "x", "_source_y", "_source_x"] + node = job.nodes["reordered"] + assert node.as_table(columns={"source": True}).column_names == expected + stored = node.get_all_records(columns={"source": True}) + assert stored is not None + assert [n for n in stored.column_names if not n.startswith("__")] == expected + assert job.nodes["b"].as_table(columns={"source": True}).column_names == expected + + +@pytest.mark.parametrize( + "kind", + [pa.time64("ns"), pa.decimal256(76, 40)], + ids=["time64ns", "decimal256"], +) +def test_a_lazy_output_describes_itself_without_converting_python_types( + kind: pa.DataType, +) -> None: + """Types with no Python type of their own are described from the node, never raised.""" + values = ( + pa.array([1, 2]).cast(kind) + if pa.types.is_decimal(kind) + else pa.array([1, 2], kind) + ) + base = pa.table({"k": pa.array([1, 2], pa.int64()), "x": values}) + base = base.cast(pa.schema([f.with_nullable(False) for f in base.schema])) + source = ArrowTableSource( + base, tag_columns=["k"], tag_only_columns=True, source_id="s" + ) + raw = ArrowTableStream( + source.as_table(columns={"source": True, "system_tags": True}), + tag_columns=["k"], + ) + job = PipelineJob(name="lazy_types", database=InMemoryArrowDatabase()) + with job: + source.select_data_columns(["x"], label="selected") + job.bind(sources={"s": raw}) + out: Any = job.nodes["s"].execute() + assert out.arrow_schema().field("x").type == kind + + +@pytest.mark.xfail( + strict=True, + raises=AssertionError, + reason="spec row e11: observer rebinds between two edges of one empty output (open)", +) +def test_a_fanned_out_empty_source_rebound_between_edges() -> None: + """Pinned limit (spec row e11): ``main`` rebuilds each edge, the branch builds once.""" + from orcapod.operators import SelectDataColumns + + def empty(mark: str) -> ArrowTableSource: + field = pa.field("x", pa.int64(), nullable=False, metadata={"mark": mark}) + table = pa.Table.from_arrays( + [pa.array([], pa.int64()), pa.array([], pa.int64())], + schema=pa.schema([pa.field("k", pa.int64(), nullable=False), field]), + ) + return ArrowTableSource(table, tag_columns=["k"], source_id="s") + + job = PipelineJob(name="fan_out_empty", database=InMemoryArrowDatabase()) + with job: + source = empty("initial") + SelectDataColumns(["x"])(source, label="first") + SelectDataColumns(["x"])(source, label="second") + slot = next(label for label in job.nodes if label not in ("first", "second")) + node = job.nodes[slot] + + class RebindsAfterFirst(NoOpObserver): + def contextualize(self, *identity_path: str) -> RebindsAfterFirst: + return self + + def on_node_end(self, node_label: str, node_hash: str) -> None: + if node_label == "first": + node.bound_source = empty("next") + + job.run(observer=RebindsAfterFirst()) + kept = job.nodes["second"].as_table() + assert kept.schema.field("x").metadata == {b"mark": b"next"} From 14b28b96d6391129be53665eddbbae089d83b0ba Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 10:13:57 -0800 Subject: [PATCH 52/86] fix(pipeline): type the result keys and token kinds for basedpyright (ITL-1360) Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/nodes/operator_node.py | 8 ++++++-- src/orcapod/core/record_batch_channels.py | 1 + 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index b839bddf9..dcfdfebdc 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -39,6 +39,7 @@ from orcapod.channels import Channel, ChannelClosed, ReadableChannel, WritableChannel from orcapod.config import OrcapodConfig from orcapod.core.operators.static_output_pod import ( + DynamicPodStream, RowBuiltFormUnavailable, StaticOutputOperatorPod, rows_on_read, @@ -1712,8 +1713,11 @@ def execute( # making the rows (ITL-1347, stage 2). result_table = result_stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS) # The order the result's rows have (``result_keys``), never the prediction. - result_keys = getattr(result_stream, "result_keys", None) - keys = result_keys() if callable(result_keys) else result_stream.keys() + keys: tuple[tuple[str, ...], tuple[str, ...]] = ( + result_stream.result_keys() + if isinstance(result_stream, DynamicPodStream) + else result_stream.keys() + ) tag_keys = keys[0] data_tags = data_tag_names(*keys) diff --git a/src/orcapod/core/record_batch_channels.py b/src/orcapod/core/record_batch_channels.py index da5edeb08..d744f3c22 100644 --- a/src/orcapod/core/record_batch_channels.py +++ b/src/orcapod/core/record_batch_channels.py @@ -388,6 +388,7 @@ def _settled_token_types( for field, column in zip(batch.schema, batch.columns, strict=True): if not field.name.startswith(constants.SOURCE_PREFIX): continue + kinds: set[pa.DataType] if pa.types.is_large_string(field.type): kinds = {pa.large_string()} else: From 352ce7b95bf698d14d594fa9ee7c89dd6bd27c6e Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 11:01:46 -0800 Subject: [PATCH 53/86] fix(pipeline): eager only for exactly a proven class; result order from the stream holding the rows (ITL-1360) Codex on PR #485, final check. - One precondition, positive and exact (reads_as_its_class): the stream that holds the rows is exactly a class whose whole-table read is its rows, and nothing on the instance shadows one of that class's methods or properties. No inspection of overrides. Applied in two places: - a bound source: its class itself declares TABLE_IS_ROWS (table_is_rows); a subclass, a mixin, an instance-replaced reader or a _stream property hands on its rows, as main iterated them. SQLiteTableSource and PostgreSQLTableSource now declare the flag on their own class. - an operator's result: followed through every DynamicPodStream (produced_stream) to the stream holding its rows; exactly an ArrowTableStream gives its own keys() (the keys iter_data reads its rows with), any other kind takes main's row path verbatim. - Spec and changelog state the rule. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1360.md | 16 +- .../dev/specs/itl-1347-job-table-transport.md | 12 ++ src/orcapod/core/nodes/operator_node.py | 89 +++++---- .../core/operators/static_output_pod.py | 31 ++- src/orcapod/core/sources/base.py | 43 ++-- src/orcapod/core/sources/cached_source.py | 2 +- src/orcapod/core/sources/csv_source.py | 2 +- src/orcapod/core/sources/db_table_source.py | 2 +- .../core/sources/delta_table_source.py | 2 +- .../core/sources/postgresql_table_source.py | 1 + .../core/sources/spiraldb_table_source.py | 2 +- .../core/sources/sqlite_table_source.py | 1 + src/orcapod/core/streams/base.py | 33 ++++ tests/test_pipeline/test_rows_on_read.py | 187 +++++++++++++++++- 14 files changed, 336 insertions(+), 87 deletions(-) diff --git a/changelog.d/ITL-1360.md b/changelog.d/ITL-1360.md index dbe931f26..51b12db1a 100644 --- a/changelog.d/ITL-1360.md +++ b/changelog.d/ITL-1360.md @@ -4,13 +4,15 @@ function and side-effect job node (and of the node protocols) returned the node's rows as a list of (tag, data) pairs, and the sync orchestrator rebuilt a table from them for each successor. It now returns the node's output stream, which the sync orchestrator hands to - every successor. A node bound to a library source kind whose table is its rows - (`TABLE_IS_ROWS`) gives its source's Arrow table, and an operator node its result's - table (REPLAY: its stored table), each in the form a table built from the rows has, - without making the rows. Every other output (a narrower bind, another kind of bound - stream, a table the whole-table build cannot use, a result with no row, a held node, a - function or side-effect node) is the node's rows, unchanged, whose table is built where - a successor reads it, as before. `OrchestratorResult.node_outputs` holds each node's + every successor. A node bound to an instance of exactly a library source kind whose + table is its rows (`TABLE_IS_ROWS`, never inherited by a subclass) gives its source's + Arrow table, and an operator node whose result yields its rows from exactly an + `ArrowTableStream` its result's table in that stream's row order (REPLAY: its stored + table), each in the form a table built from the rows has, without making the rows. + Every other output (a narrower bind, a subclass or another kind of bound stream, an + operator result of another stream kind, a table the whole-table build cannot use, a + result with no row, a held node, a function or side-effect node) is the node's rows, + unchanged, whose table is built where a successor reads it, as before. `OrchestratorResult.node_outputs` holds each node's output stream: its rows (`iter_data()`) are the rows the node returned, and its table is built when the table is first read (`as_table()`, a successor's edge); on the sync path a held node gives the stream of its held rows, and the async path still sends a held diff --git a/docs/dev/specs/itl-1347-job-table-transport.md b/docs/dev/specs/itl-1347-job-table-transport.md index f81936af1..dc60bc475 100644 --- a/docs/dev/specs/itl-1347-job-table-transport.md +++ b/docs/dev/specs/itl-1347-job-table-transport.md @@ -520,6 +520,18 @@ stage. Where building a node's output from its whole table is not provably `main node, a node whose output is still its rows), the node hands on its rows and the table is built from them by `main`'s row path where a successor reads them (`RowsOnRead`, `at_edge`): `main`'s order, error and moment by construction (Codex on PR #485, round 3). +"Provably" is one precondition, positive and exact, never an inspection of overrides +(Codex on PR #485, final check): **the stream that holds the rows is exactly a class whose +whole-table read is its rows, and nothing on the instance shadows one of that class's +methods or properties** (`reads_as_its_class`). It is applied in two places: + +- a bound source: its class is a library source kind that itself declares + `TABLE_IS_ROWS` (`table_is_rows`); +- an operator's result: the stream it yields its rows from, followed through every + `DynamicPodStream` (`produced_stream`), is `ArrowTableStream`, and its own `keys()` (the + keys `iter_data` reads its rows with, tags in its tag-column order) give the order. + +Any subclass, replaced reader or other stream kind takes `main`'s row path. | # | What differs | On `main` today | On the branch | Why `main` is wrong (bug, reproducer) | Approval needed | |---|---|---|---|---|---| diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index dcfdfebdc..4227c2cc8 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -39,9 +39,9 @@ from orcapod.channels import Channel, ChannelClosed, ReadableChannel, WritableChannel from orcapod.config import OrcapodConfig from orcapod.core.operators.static_output_pod import ( - DynamicPodStream, RowBuiltFormUnavailable, StaticOutputOperatorPod, + produced_stream, rows_on_read, ) from orcapod.core.streams.arrow_table_stream import ArrowTableStream @@ -49,6 +49,7 @@ ZERO_ROW_INPUT_COLUMNS, StreamBase, check_head_size, + reads_as_its_class, short_stream_repr, ) from orcapod.core.streams.view import ( @@ -1708,37 +1709,55 @@ def execute( # Compute result_stream = self._operator.process(*input_streams) - - # The result's table, as the table built from its rows would be, without - # making the rows (ITL-1347, stage 2). - result_table = result_stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS) - # The order the result's rows have (``result_keys``), never the prediction. - keys: tuple[tuple[str, ...], tuple[str, ...]] = ( - result_stream.result_keys() - if isinstance(result_stream, DynamicPodStream) - else result_stream.keys() - ) - tag_keys = keys[0] - data_tags = data_tag_names(*keys) - - # Cache, in row order with or without rows (ITL-1131, ITL-1133). - if result_table.num_rows: - try: - kept_table = StaticOutputOperatorPod._row_built_form( - result_table, keys - ) - except RowBuiltFormUnavailable as error: - StaticOutputOperatorPod._raise_as_rows_do( - result_stream.iter_data(), error - ) - self._cached_output_stream = ArrowTableStream( - kept_table, tag_columns=tag_keys, data_tags=data_tags + produced = produced_stream(result_stream) + + output: StreamProtocol + if not reads_as_its_class(produced, ArrowTableStream): + # A result that is not exactly a stream over its table (a custom + # stream kind, a replaced reader): main's own row path, its rows read + # once, its table built where a successor reads it (ITL-1347). + rows = list(result_stream.iter_data()) + self._cached_output_stream = StaticOutputOperatorPod._kept_output( + result_stream, rows ) + output = rows_on_read(rows, self) else: - kept_table = None - self._cached_output_stream = ( - StaticOutputOperatorPod._zero_rows_in_row_order(result_stream) - ) + # The result's table, as the table built from its rows would be, + # without making the rows (ITL-1347, stage 2). An exact + # ``ArrowTableStream``'s ``keys()`` are the keys its rows are read with + # (``iter_data``), so they are the order of the result's rows, to any + # depth of composition, never the prediction. + result_table = result_stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS) + keys = produced.keys() + tag_keys = keys[0] + data_tags = data_tag_names(*keys) + + # Cache, in row order with or without rows (ITL-1131, ITL-1133). + if result_table.num_rows: + try: + kept_table = StaticOutputOperatorPod._row_built_form( + result_table, keys + ) + except RowBuiltFormUnavailable as error: + StaticOutputOperatorPod._raise_as_rows_do( + result_stream.iter_data(), error + ) + self._cached_output_stream = ArrowTableStream( + kept_table, tag_columns=tag_keys, data_tags=data_tags + ) + # The output stream, built once the node holds its run (as the + # sync orchestrator built a successor's input after ``execute`` + # returned). + output = StaticOutputOperatorPod._as_upstream_stream( + kept_table, tag_keys, data_tags, self + ) + else: + self._cached_output_stream = ( + StaticOutputOperatorPod._zero_rows_in_row_order(result_stream) + ) + # Its zero-row form is derived where a successor reads it, as on + # main: the operator is not called again here (``RowsOnRead``). + output = rows_on_read([], self) self._update_modified_time() @@ -1751,16 +1770,6 @@ def execute( ): self._store_output_stream(self._cached_output_stream) - # The output stream, built once the node holds its run (as the sync - # orchestrator built a successor's input after ``execute`` returned). - if kept_table is not None: - output = StaticOutputOperatorPod._as_upstream_stream( - kept_table, tag_keys, data_tags, self - ) - else: - # Its zero-row form is derived where a successor reads it, as on main: - # the operator is not called again here (``RowsOnRead``). - output = rows_on_read([], self) ctx_obs.on_node_end(node_label, node_hash) return output except BaseException: diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index 0816a1bb2..90209a8a8 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -1612,6 +1612,25 @@ def pipeline_hash( return self._input_pipeline_hash +def produced_stream(stream: StreamProtocol) -> StreamProtocol: + """Return the stream whose rows ``stream`` yields, through any depth of composition. + + An operator's result is a ``DynamicPodStream`` whose rows are those of the stream + its ``static_process`` returned, which may itself be another operator's + ``DynamicPodStream``: this follows them all to the stream that holds the rows + (ITL-1347). + + Args: + stream: An operator's result, or any stream. + + Returns: + The stream that holds ``stream``'s rows. + """ + while isinstance(stream, DynamicPodStream): + stream = stream.produced_stream() + return stream + + class DynamicPodStream(StreamBase): """Recomputable stream wrapping a ``StaticOutputOperatorPod`` invocation.""" @@ -1840,19 +1859,17 @@ def iter_data( ) return self._cached_stream.iter_data() - def result_keys(self) -> tuple[tuple[str, ...], tuple[str, ...]]: - """The keys of the stream the operator returned: the order its rows have. + def produced_stream(self) -> StreamProtocol: + """The stream the operator returned for the current inputs (computed if stale). - The prediction (``keys``) never reorders a result: an operator node keeps, - stores and hands on its result in the order its rows have, as ``main`` built - it from them (ITL-1347). + Its rows are this stream's rows; ``produced_stream`` (the module function) + follows it through every ``DynamicPodStream`` to the stream that holds them. """ self._refresh() assert self._cached_stream is not None, ( "StreamProtocol has not been updated or is empty." ) - tag_keys, data_keys = self._cached_stream.keys() - return tuple(tag_keys), tuple(data_keys) + return self._cached_stream def head( self, diff --git a/src/orcapod/core/sources/base.py b/src/orcapod/core/sources/base.py index 4b62f45dd..fdaa3cdd1 100644 --- a/src/orcapod/core/sources/base.py +++ b/src/orcapod/core/sources/base.py @@ -6,6 +6,7 @@ from orcapod.config import OrcapodConfig from orcapod.core.streams.base import ( StreamBase, + reads_as_its_class, typed_arrow_schemas, typed_zero_row_table, ) @@ -47,25 +48,15 @@ def saved_tag_only_columns(config: dict[str, Any]) -> bool | list[str]: return config["tag_only_columns"] -_ROW_READERS = ( - "iter_data", - "as_table", - "__iter__", - "async_iter_data", - "keys", - "output_schema", -) -"""The members a source's rows and table are read through.""" - - def table_is_rows(source: object) -> bool: """Whether ``source``'s ``as_table()`` and ``iter_data()`` provably read the same data. - True only when the class that declares ``TABLE_IS_ROWS = True`` (a library source - kind) reads ``source``: ``source``'s own class, or a subclass that overrides none of - the members the rows and the table are read through (``_ROW_READERS``). A subclass - that changes how it reads (a filtering ``iter_data``) is not that kind any more, and - a job node bound to it hands on its rows, as ``main`` iterated them (ITL-1347). + Positive and exact (ITL-1347): true only when ``source``'s class itself declares + ``TABLE_IS_ROWS = True`` (a library source kind) and ``source`` reads as that class + (``reads_as_its_class``: its exact type, no member replaced on the instance). Any + subclass, a mixin, a replaced reader or a property that changes what the source + reads through is not proven, and a job node bound to it hands on its rows, as + ``main`` iterated them. Args: source: The object bound to a source slot. @@ -73,12 +64,8 @@ def table_is_rows(source: object) -> bool: Returns: Whether F of its table is the table its rows give. """ - for klass in type(source).__mro__: - if "TABLE_IS_ROWS" in vars(klass): - return bool(vars(klass)["TABLE_IS_ROWS"]) - if any(name in vars(klass) for name in _ROW_READERS): - return False - return False + kind = type(source) + return vars(kind).get("TABLE_IS_ROWS") is True and reads_as_its_class(source, kind) class RootSource(StreamBase): @@ -130,11 +117,13 @@ class RootSource(StreamBase): TABLE_IS_ROWS: ClassVar[bool] = False """Whether ``as_table()`` and ``iter_data()`` read the same data, with no effect. - Declared ``True`` only by the library source kinds that read one stream either way - (ITL-1347): a job node bound to one hands on F of its table, which equals the table - built from its rows. Any other bound stream (a side-effect or function pod stream, - an operator's result, a raw stream, a source kind that polls or delivers on a read) - hands on its rows (``RowsOnRead``), as ``main`` iterated them. + Declared ``True`` only by the library source kinds that read one stream either way, + each on its own class: it is read for the exact class only, never inherited + (``table_is_rows``; ITL-1347). A job node bound to an instance of exactly such a + class hands on F of its table, which equals the table built from its rows. Any + other bound stream (a subclass, a side-effect or function pod stream, an operator's + result, a raw stream, a source kind that polls or delivers on a read) hands on its + rows (``RowsOnRead``), as ``main`` iterated them. """ def __init__( diff --git a/src/orcapod/core/sources/cached_source.py b/src/orcapod/core/sources/cached_source.py index 98e531222..a9bfd8f08 100644 --- a/src/orcapod/core/sources/cached_source.py +++ b/src/orcapod/core/sources/cached_source.py @@ -79,8 +79,8 @@ class CachedSource(RootSource): """ SOURCE_KIND: ClassVar[str] = "cached" - TABLE_IS_ROWS: ClassVar[bool] = True """Config type key and default source-id kind of this source (one vocabulary).""" + TABLE_IS_ROWS: ClassVar[bool] = True HASH_COLUMN_NAME = "_record_hash" diff --git a/src/orcapod/core/sources/csv_source.py b/src/orcapod/core/sources/csv_source.py index bfd0b423d..9a0d99dcf 100644 --- a/src/orcapod/core/sources/csv_source.py +++ b/src/orcapod/core/sources/csv_source.py @@ -276,8 +276,8 @@ class CSVSource(RootSource): """ SOURCE_KIND: ClassVar[str] = "csv" - TABLE_IS_ROWS: ClassVar[bool] = True """Config type key and default source-id kind of this source (one vocabulary).""" + TABLE_IS_ROWS: ClassVar[bool] = True TAKES_TAG_ONLY_COLUMNS: ClassVar[bool] = True def __init__( diff --git a/src/orcapod/core/sources/db_table_source.py b/src/orcapod/core/sources/db_table_source.py index 721b2308d..a95c316f2 100644 --- a/src/orcapod/core/sources/db_table_source.py +++ b/src/orcapod/core/sources/db_table_source.py @@ -80,8 +80,8 @@ class DBTableSource(RootSource): """ SOURCE_KIND: ClassVar[str] = "db_table" - TABLE_IS_ROWS: ClassVar[bool] = True """Config type key and default source-id kind of this source (one vocabulary).""" + TABLE_IS_ROWS: ClassVar[bool] = True TAKES_TAG_ONLY_COLUMNS: ClassVar[bool] = True def __init__( diff --git a/src/orcapod/core/sources/delta_table_source.py b/src/orcapod/core/sources/delta_table_source.py index 2a60e6304..c744b3913 100644 --- a/src/orcapod/core/sources/delta_table_source.py +++ b/src/orcapod/core/sources/delta_table_source.py @@ -49,8 +49,8 @@ class DeltaTableSource(RootSource): """ SOURCE_KIND: ClassVar[str] = "delta_table" - TABLE_IS_ROWS: ClassVar[bool] = True """Config type key and default source-id kind of this source (one vocabulary).""" + TABLE_IS_ROWS: ClassVar[bool] = True TAKES_TAG_ONLY_COLUMNS: ClassVar[bool] = True def __init__( diff --git a/src/orcapod/core/sources/postgresql_table_source.py b/src/orcapod/core/sources/postgresql_table_source.py index 0f12aa372..bc2b437b2 100644 --- a/src/orcapod/core/sources/postgresql_table_source.py +++ b/src/orcapod/core/sources/postgresql_table_source.py @@ -172,6 +172,7 @@ class PostgreSQLTableSource(DBTableSource): SOURCE_KIND: ClassVar[str] = "postgresql_table" """Config type key and default source-id kind of this source (one vocabulary).""" + TABLE_IS_ROWS: ClassVar[bool] = True def __init__( self, diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index af04d5f34..c6c271657 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -374,8 +374,8 @@ class SpiralDBTableSource(RootSource): """ SOURCE_KIND: ClassVar[str] = "spiraldb_table" - TABLE_IS_ROWS: ClassVar[bool] = True """Config type key and default source-id kind of this source (one vocabulary).""" + TABLE_IS_ROWS: ClassVar[bool] = True TAKES_TAG_ONLY_COLUMNS: ClassVar[bool] = True # Whether a notebook display reads the first rows. False shows the schema and the diff --git a/src/orcapod/core/sources/sqlite_table_source.py b/src/orcapod/core/sources/sqlite_table_source.py index f4e753553..9353ea07c 100644 --- a/src/orcapod/core/sources/sqlite_table_source.py +++ b/src/orcapod/core/sources/sqlite_table_source.py @@ -101,6 +101,7 @@ class SQLiteTableSource(DBTableSource): SOURCE_KIND: ClassVar[str] = "sqlite_table" """Config type key and default source-id kind of this source (one vocabulary).""" + TABLE_IS_ROWS: ClassVar[bool] = True def __init__( self, diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py index 00fa55f40..26e05c0ce 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -1,5 +1,7 @@ from __future__ import annotations +import functools +import inspect import logging from abc import abstractmethod from collections import deque @@ -48,6 +50,37 @@ logger = logging.getLogger(__name__) +def reads_as_its_class(obj: object, cls: type) -> bool: + """Whether ``obj`` is exactly ``cls`` and reads only through ``cls``'s own members. + + Exact, never by inspection of what a subclass overrides: ``type(obj) is cls``, and + ``obj`` holds no attribute of its own that shadows a method or a property of + ``cls`` (an ``iter_data`` replaced on the instance). A ``functools.cached_property`` + keeps its value in the instance by design and is not a shadow. A subclass, however + small, is never ``cls`` here (ITL-1347). + + Args: + obj: The object to check. + cls: The class whose reading is proven. + + Returns: + Whether ``obj`` reads as ``cls`` does. + """ + if type(obj) is not cls: + return False + own = getattr(obj, "__dict__", None) + if not own: + return True + missing = object() + for name in own: + member = inspect.getattr_static(cls, name, missing) + if member is missing or isinstance(member, functools.cached_property): + continue + if callable(member) or hasattr(type(member), "__get__"): + return False + return True + + def schema_requires_io(stream: object, config: ColumnConfig) -> bool: """Whether reading ``stream``'s schema with ``config`` would read or poll a source. diff --git a/tests/test_pipeline/test_rows_on_read.py b/tests/test_pipeline/test_rows_on_read.py index b237f1987..68c9d3770 100644 --- a/tests/test_pipeline/test_rows_on_read.py +++ b/tests/test_pipeline/test_rows_on_read.py @@ -468,8 +468,9 @@ def test_a_subclass_that_overrides_a_reader_is_not_a_table_is_rows_kind( table, tag_columns=["k"], tag_only_columns=True, source_id="s" ) assert table_is_rows(plain) + # Exact, never by inspection: a subclass that overrides nothing is not proven. subclass = type("Plain", (ArrowTableSource,), {}) - assert table_is_rows( + assert not table_is_rows( subclass(table, tag_columns=["k"], tag_only_columns=True, source_id="s") ) @@ -538,6 +539,190 @@ def unary_static_process(self, stream: Any) -> Any: assert job.nodes["b"].as_table(columns={"source": True}).column_names == expected +# ── final check: the eager route is positive and exact ──────────────────────── + + +def _only_above_ten(rows: Any) -> Any: + return (row for row in rows if row[1]["x"] > 10) + + +class _FilteringStream(ArrowTableStream): + def iter_data(self) -> Any: + return _only_above_ten(super().iter_data()) + + +class _ReadsThroughAProperty(ArrowTableSource): + """Reads through a ``_stream`` property that hands on a filtering stream.""" + + @property + def _stream(self) -> Any: + return getattr(self, "saved_stream") + + @_stream.setter + def _stream(self, base: Any) -> None: + self.saved_stream = _FilteringStream( + base.as_table(columns={"source": True, "system_tags": True}), + tag_columns=["k"], + ) + + +def _bound_selection(source: Any) -> list[int]: + """Bind ``source`` to a slot feeding a selection; return what the sync run keeps.""" + table = pa.table({"k": pa.array([1, 2]), "x": pa.array([10, 20])}) + job = PipelineJob(name="exact", database=InMemoryArrowDatabase()) + with job: + ArrowTableSource( + table, tag_columns=["k"], tag_only_columns=True, source_id="s" + ).select_data_columns(["x"], label="selected") + job.bind(sources={"s": source}) + job.run() + return job.nodes["selected"].as_table()["x"].to_pylist() + + +@pytest.mark.parametrize("how", ["instance_reader", "property", "plain_subclass"]) +def test_only_an_exact_unshadowed_library_source_is_eager(how: str) -> None: + """An ``iter_data`` replaced on the instance and a ``_stream`` property both read + the rows the reader gives (``[20]``, as ``main``); a plain subclass is not proven + either, and gives ``main``'s rows (Codex on PR #485, final check).""" + from orcapod.core.sources.base import table_is_rows + + table = pa.table({"k": pa.array([1, 2]), "x": pa.array([10, 20])}) + kwargs: dict[str, Any] = { + "tag_columns": ["k"], + "tag_only_columns": True, + "source_id": "s", + } + if how == "instance_reader": + source: Any = ArrowTableSource(table, **kwargs) + read = source.iter_data + source.iter_data = lambda: _only_above_ten(read()) + expected = [20] + elif how == "property": + source = _ReadsThroughAProperty(table, **kwargs) + expected = [20] + else: + source = type("Plain", (ArrowTableSource,), {})(table, **kwargs) + expected = [10, 20] + assert not table_is_rows(source) + assert _bound_selection(source) == expected + + +def test_an_exact_library_source_is_eager() -> None: + """The exact class, with nothing replaced on the instance, takes the eager route.""" + from orcapod.core.sources.base import table_is_rows + + table = pa.table({"k": pa.array([1, 2]), "x": pa.array([10, 20])}) + source = ArrowTableSource( + table, tag_columns=["k"], tag_only_columns=True, source_id="s" + ) + source.as_table() + list(source.iter_data()) + assert table_is_rows(source) + assert _bound_selection(source) == [10, 20] + + +def _swapped(stream: Any, first: str, second: str, tags: list[str]) -> Any: + """``stream``'s table with ``first`` and ``second`` swapped, over ``tags``.""" + from orcapod.core.streams.base import ZERO_ROW_INPUT_COLUMNS + + table = stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS) + names = list(table.column_names) + a, b = names.index(first), names.index(second) + names[a], names[b] = names[b], names[a] + return ArrowTableStream(table.select(names), tag_columns=tags) + + +@pytest.mark.parametrize("replay", [False, True], ids=["log", "replay"]) +@pytest.mark.parametrize("layout", ["data", "tags"]) +def test_a_composed_operator_result_keeps_its_own_order( + layout: str, replay: bool +) -> None: + """An operator whose ``static_process`` returns ANOTHER operator's result keeps, + stores and hands on the order of the rows that result yields, to any depth: data + ``y, x`` (laid out so) and tags ``b, a`` (declared so), as ``main`` built them from + the rows; REPLAY of the stored table too (Codex on PR #485, final check).""" + from orcapod.operators import SelectDataColumns + + class Reordered(SelectDataColumns): + def unary_static_process(self, stream: Any) -> Any: + if layout == "data": + return _swapped(stream, "x", "y", ["a", "b"]) + return _swapped(stream, "x", "x", ["b", "a"]) + + class Composed(SelectDataColumns): + def unary_static_process(self, stream: Any) -> Any: + return Reordered(["x", "y"]).process(stream) + + database = InMemoryArrowDatabase() + job = PipelineJob(name="composed", database=database) + with job: + source = DictSource( + [{"a": 1, "b": 5, "x": 1, "y": 2}, {"a": 2, "b": 6, "x": 3, "y": 4}], + tag_columns=["a", "b"], + tag_only_columns=True, + source_id="s", + ) + Batch(batch_size=2)(Composed(["x", "y"])(source, label="composed"), label="b") + node: Any = job.nodes["composed"] + node.attach_databases( + pipeline_database=database.at("log"), cache_mode=CacheMode.LOG + ) + job.run() + if replay: + node.attach_databases( + pipeline_database=database.at("log"), cache_mode=CacheMode.REPLAY + ) + node.clear_cache() + job.run() + # ``main`` 321284ae, measured: the stored table keeps its tags in the slot's order, + # and REPLAY hands on the stored table's order. + data = ["a", "b", "y", "x", "_source_y", "_source_x"] + stored_tags = ["a", "b", "x", "y", "_source_x", "_source_y"] + result_tags = ["b", "a", "x", "y", "_source_x", "_source_y"] + if layout == "data": + kept, in_store = data, data + else: + kept, in_store = (stored_tags if replay else result_tags), stored_tags + assert node.as_table(columns={"source": True}).column_names == kept + stored = node.get_all_records(columns={"source": True}) + assert stored is not None + assert [n for n in stored.column_names if not n.startswith("__")] == in_store + assert job.nodes["b"].as_table(columns={"source": True}).column_names == kept + + +def test_a_result_of_another_stream_kind_takes_mains_row_path() -> None: + """A result that is not exactly an ``ArrowTableStream`` is read as ``main`` read + it: its rows (here, the ones its iterator yields), never its table.""" + from orcapod.core.streams.base import ZERO_ROW_INPUT_COLUMNS + from orcapod.operators import SelectDataColumns + + class Filtering(SelectDataColumns): + def unary_static_process(self, stream: Any) -> Any: + table = stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS) + return _FilteringStream(table, tag_columns=["k"]) + + database = InMemoryArrowDatabase() + job = PipelineJob(name="other_kind", database=database) + with job: + source = ArrowTableSource( + pa.table({"k": pa.array([1, 2]), "x": pa.array([10, 20])}), + tag_columns=["k"], + tag_only_columns=True, + source_id="s", + ) + Batch(batch_size=2)(Filtering(["x"])(source, label="filtered"), label="b") + node: Any = job.nodes["filtered"] + node.attach_databases( + pipeline_database=database.at("log"), cache_mode=CacheMode.LOG + ) + job.run() + assert node.as_table()["x"].to_pylist() == [20] + stored = node.get_all_records() + assert stored is not None + assert stored["x"].to_pylist() == [20] + assert job.nodes["b"].as_table()["x"].to_pylist() == [[20]] + + @pytest.mark.parametrize( "kind", [pa.time64("ns"), pa.decimal256(76, 40)], From 36fd78aacd08b8624f429d838021c5bc0050e89d Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 11:40:24 -0800 Subject: [PATCH 54/86] fix(pipeline): every wrapper in a result's chain proven; eager only in the node's data context (ITL-1360) CodeRabbit on PR #485 (352ce7b9). - produced_stream follows a DynamicPodStream only when it reads as DynamicPodStream itself (reads_as_its_class); a subclass, or a wrapper with iter_data replaced on the instance, stops the chain and the operator node takes main's row path (main read [20] through such a wrapper; 352ce7b9 gave [10, 20]). - An operator result whose rows report another data context than the node's takes main's row path: the rows execute hands on are main's rows, in their own context (the kept table is the node's context, as on main). Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1360.md | 2 +- .../dev/specs/itl-1347-job-table-transport.md | 4 +- src/orcapod/core/nodes/operator_node.py | 11 ++- .../core/operators/static_output_pod.py | 13 ++- tests/test_pipeline/test_rows_on_read.py | 96 +++++++++++++++++++ 5 files changed, 118 insertions(+), 8 deletions(-) diff --git a/changelog.d/ITL-1360.md b/changelog.d/ITL-1360.md index 51b12db1a..1f3892262 100644 --- a/changelog.d/ITL-1360.md +++ b/changelog.d/ITL-1360.md @@ -7,7 +7,7 @@ every successor. A node bound to an instance of exactly a library source kind whose table is its rows (`TABLE_IS_ROWS`, never inherited by a subclass) gives its source's Arrow table, and an operator node whose result yields its rows from exactly an - `ArrowTableStream` its result's table in that stream's row order (REPLAY: its stored + `ArrowTableStream` in the node's data context its result's table in that stream's row order (REPLAY: its stored table), each in the form a table built from the rows has, without making the rows. Every other output (a narrower bind, a subclass or another kind of bound stream, an operator result of another stream kind, a table the whole-table build cannot use, a diff --git a/docs/dev/specs/itl-1347-job-table-transport.md b/docs/dev/specs/itl-1347-job-table-transport.md index dc60bc475..27c9764ed 100644 --- a/docs/dev/specs/itl-1347-job-table-transport.md +++ b/docs/dev/specs/itl-1347-job-table-transport.md @@ -528,7 +528,9 @@ methods or properties** (`reads_as_its_class`). It is applied in two places: - a bound source: its class is a library source kind that itself declares `TABLE_IS_ROWS` (`table_is_rows`); - an operator's result: the stream it yields its rows from, followed through every - `DynamicPodStream` (`produced_stream`), is `ArrowTableStream`, and its own `keys()` (the + `DynamicPodStream` that is itself proven (`produced_stream`; a subclass or a wrapper + with a replaced member stops the chain), is `ArrowTableStream` in the node's data + context (its rows report that context, as `main`'s rows did), and its own `keys()` (the keys `iter_data` reads its rows with, tags in its tag-column order) give the order. Any subclass, replaced reader or other stream kind takes `main`'s row path. diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index 4227c2cc8..c5b94a773 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -1712,10 +1712,15 @@ def execute( produced = produced_stream(result_stream) output: StreamProtocol - if not reads_as_its_class(produced, ArrowTableStream): + if ( + not reads_as_its_class(produced, ArrowTableStream) + or produced.data_context_key != self.data_context_key + ): # A result that is not exactly a stream over its table (a custom - # stream kind, a replaced reader): main's own row path, its rows read - # once, its table built where a successor reads it (ITL-1347). + # stream kind, a replaced reader), or whose rows report another data + # context than the node's: main's own row path, its rows read once and + # handed on unchanged, its table built where a successor reads it + # (ITL-1347). rows = list(result_stream.iter_data()) self._cached_output_stream = StaticOutputOperatorPod._kept_output( result_stream, rows diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index 90209a8a8..2d7fd0347 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -44,6 +44,7 @@ ZERO_ROW_INPUT_COLUMNS, StreamBase, check_head_size, + reads_as_its_class, short_stream_repr, typed_zero_row_input, typed_zero_row_table, @@ -1618,15 +1619,21 @@ def produced_stream(stream: StreamProtocol) -> StreamProtocol: An operator's result is a ``DynamicPodStream`` whose rows are those of the stream its ``static_process`` returned, which may itself be another operator's ``DynamicPodStream``: this follows them all to the stream that holds the rows - (ITL-1347). + (ITL-1347). A wrapper is followed only when it reads as ``DynamicPodStream`` itself + (``reads_as_its_class``: its rows are then exactly those of the stream it holds); a + subclass or a wrapper with a member replaced on the instance is where the chain + stops, so the caller, which proves the stream it is given, takes the row path. Args: stream: An operator's result, or any stream. Returns: - The stream that holds ``stream``'s rows. + The stream that holds ``stream``'s rows, or the first wrapper not proven to + read through the stream it holds. """ - while isinstance(stream, DynamicPodStream): + while isinstance(stream, DynamicPodStream) and reads_as_its_class( + stream, DynamicPodStream + ): stream = stream.produced_stream() return stream diff --git a/tests/test_pipeline/test_rows_on_read.py b/tests/test_pipeline/test_rows_on_read.py index 68c9d3770..2113fb27d 100644 --- a/tests/test_pipeline/test_rows_on_read.py +++ b/tests/test_pipeline/test_rows_on_read.py @@ -723,6 +723,102 @@ def unary_static_process(self, stream: Any) -> Any: assert job.nodes["b"].as_table()["x"].to_pylist() == [[20]] +# ── CodeRabbit on 352ce7b9: every wrapper proven, and the rows' data context ───── + + +@pytest.mark.parametrize("how", ["subclass", "instance_reader"]) +def test_a_dynamic_stream_that_is_not_proven_stops_the_chain(how: str) -> None: + """A ``DynamicPodStream`` subclass, or one whose ``iter_data`` is replaced on the + instance, inside an operator's result is read through its own rows (``[20]``), + as ``main`` read them: the chain is followed only through proven wrappers.""" + from orcapod.core.operators.static_output_pod import DynamicPodStream + from orcapod.operators import SelectDataColumns + + class FilteringDynamic(DynamicPodStream): + def iter_data(self) -> Any: + return _only_above_ten(super().iter_data()) + + class Inner(SelectDataColumns): + pass + + class Outer(SelectDataColumns): + def unary_static_process(self, stream: Any) -> Any: + if how == "subclass": + return FilteringDynamic(Inner(["x", "y"]), (stream,)) + inner: Any = Inner(["x", "y"]).process(stream) + read = inner.iter_data + inner.iter_data = lambda: _only_above_ten(read()) + return inner + + database = InMemoryArrowDatabase() + job = PipelineJob(name="unproven", database=database) + with job: + source = ArrowTableSource( + pa.table({"k": [1, 2], "x": [10, 20], "y": [1, 2], "z": [5, 6]}), + tag_columns=["k"], + tag_only_columns=True, + source_id="s", + ) + Batch(batch_size=2)(Outer(["x", "y"])(source, label="outer"), label="b") + node: Any = job.nodes["outer"] + node.attach_databases( + pipeline_database=database.at("log"), cache_mode=CacheMode.LOG + ) + job.run() + assert node.as_table()["x"].to_pylist() == [20] + stored = node.get_all_records() + assert stored is not None + assert stored["x"].to_pylist() == [20] + assert job.nodes["b"].as_table()["x"].to_pylist() == [[20]] + + +OTHER_CONTEXT = "std:v1:test-rows-on-read-other" + + +def test_a_result_in_another_data_context_hands_on_its_own_rows( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """An operator node over a stream of another data context hands on the result's + rows as ``main`` returned them (in their own data context); what it keeps is in its + own data context, as on ``main``.""" + import dataclasses + + import orcapod.contexts as contexts + from orcapod.core.nodes.operator_node import OperatorJobNode + from orcapod.operators import SelectDataColumns + from orcapod.system_constants import constants + + other = dataclasses.replace( + contexts.get_default_context(), context_key=OTHER_CONTEXT + ) + registry = contexts._get_registry() # pyright: ignore[reportPrivateUsage] # the test registers a second context + original = registry.get_context + + def get_context(key: Any = None) -> contexts.DataContext: # pyright: ignore[reportExplicitAny] # the registry's own argument + return other if key == OTHER_CONTEXT else original(key) + + monkeypatch.setattr(registry, "get_context", get_context) + + def stream() -> ArrowTableStream: + table = pa.table( + { + "k": ["a", "b"], + "x": [1, 2], + "y": [3, 4], + constants.CONTEXT_KEY: pa.array([OTHER_CONTEXT] * 2, pa.large_string()), + } + ) + return ArrowTableStream(table, tag_columns=["k"], data_context=other) + + node = OperatorJobNode(SelectDataColumns(["x"]), [stream()]) + output: Any = node.execute(stream()) + assert [data.data_context_key for _, data in output.iter_data()] == [ + OTHER_CONTEXT + ] * 2 + kept = node.as_table(columns={"context": True})[constants.CONTEXT_KEY] + assert kept.to_pylist() == [node.data_context_key] * 2 + + @pytest.mark.parametrize( "kind", [pa.time64("ns"), pa.decimal256(76, 40)], From dd6b7cd40e8234cc3c599019201f4b8252749042 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 12:34:21 -0800 Subject: [PATCH 55/86] fix(pipeline): eager only in the node's data context with row-typed system tags; a retained output keeps its rows (ITL-1360) Codex on PR #485, round 7. - The one precondition gains two conditions, applied on both routes: the rows report the node's data context, and every system-tag field of the table is non-null large_string, what the rows give (system_tags_as_rows_give). An exact CachedSource with its own data context hands on its rows in that context (the edge table is built in the slot's context, as on main); a result with an int16 system tag takes main's row path (int64 non-null and main's record hashes; with a null, main's ArrowInvalid before the end event). - With results retained, the sync orchestrator drops a RowsOnRead's built stream once every successor has read it (release_built), so it holds only its rows, as main did; neighbours are taken before the run, since an observer may rebind a source. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1360.md | 39 ++-- .../dev/specs/itl-1347-job-table-transport.md | 13 +- src/orcapod/core/nodes/operator_node.py | 32 +-- src/orcapod/core/nodes/source_node.py | 15 +- .../core/operators/static_output_pod.py | 9 + src/orcapod/core/streams/base.py | 22 ++ src/orcapod/pipeline/sync_orchestrator.py | 41 ++++ tests/test_pipeline/test_rows_on_read.py | 204 ++++++++++++++++++ 8 files changed, 337 insertions(+), 38 deletions(-) diff --git a/changelog.d/ITL-1360.md b/changelog.d/ITL-1360.md index 1f3892262..8121d7e70 100644 --- a/changelog.d/ITL-1360.md +++ b/changelog.d/ITL-1360.md @@ -4,24 +4,27 @@ function and side-effect job node (and of the node protocols) returned the node's rows as a list of (tag, data) pairs, and the sync orchestrator rebuilt a table from them for each successor. It now returns the node's output stream, which the sync orchestrator hands to - every successor. A node bound to an instance of exactly a library source kind whose - table is its rows (`TABLE_IS_ROWS`, never inherited by a subclass) gives its source's - Arrow table, and an operator node whose result yields its rows from exactly an - `ArrowTableStream` in the node's data context its result's table in that stream's row order (REPLAY: its stored - table), each in the form a table built from the rows has, without making the rows. - Every other output (a narrower bind, a subclass or another kind of bound stream, an - operator result of another stream kind, a table the whole-table build cannot use, a - result with no row, a held node, a function or side-effect node) is the node's rows, - unchanged, whose table is built where a successor reads it, as before. `OrchestratorResult.node_outputs` holds each node's - output stream: its rows (`iter_data()`) are the rows the node returned, and its table is - built when the table is first read (`as_table()`, a successor's edge); on the sync path - a held node gives the stream of its held rows, and the async path still sends a held - node's rows as the run's plan took them (`held_rows`). Every successor's input is - unchanged: columns, types, row order, system tags, source info, pipeline and content - hashes, and an error surfaces where and when it did. No hash, stored table or output - changes. An operator node's table is built once, for what it keeps and for every - successor, instead of once to keep and once per successor. The first two stages of the - table transport between job nodes (`docs/dev/specs/itl-1347-job-table-transport.md`). + every successor. Where that table is provably the rows' own, the node gives it + without making the rows: a node bound to an instance of exactly a library source kind + whose table is its rows (`TABLE_IS_ROWS`, never inherited by a subclass), and an + operator node whose result yields its rows from exactly an `ArrowTableStream`, in that + stream's row order (REPLAY: its stored table), each only when the rows report the + node's data context and every system tag is non-null text, as rows give it. Every other + output (a narrower bind, a subclass or another kind of bound stream or result, rows of + another data context, system tags of another type, a table the whole-table build + cannot use, a result with no row, a held node, a function or side-effect node) is the + node's rows, unchanged, whose table is built where a successor reads it, as before; a + retained one keeps only its rows once every successor has read it. + `OrchestratorResult.node_outputs` holds each node's output stream: its rows + (`iter_data()`) are the rows the node returned, and its table is built when the table + is first read (`as_table()`, a successor's edge); on the sync path a held node gives + the stream of its held rows, and the async path still sends a held node's rows as the + run's plan took them (`held_rows`). Every successor's input is unchanged: columns, + types, row order, system tags, source info, pipeline and content hashes, and an error + surfaces where and when it did. No hash, stored table or output changes. An operator + node's table is built once, for what it keeps and for every successor, instead of once + to keep and once per successor. The first two stages of the table transport between + job nodes (`docs/dev/specs/itl-1347-job-table-transport.md`). (ITL-1347, ITL-1360) ### Added diff --git a/docs/dev/specs/itl-1347-job-table-transport.md b/docs/dev/specs/itl-1347-job-table-transport.md index 27c9764ed..082e7a042 100644 --- a/docs/dev/specs/itl-1347-job-table-transport.md +++ b/docs/dev/specs/itl-1347-job-table-transport.md @@ -521,9 +521,11 @@ node, a node whose output is still its rows), the node hands on its rows and the built from them by `main`'s row path where a successor reads them (`RowsOnRead`, `at_edge`): `main`'s order, error and moment by construction (Codex on PR #485, round 3). "Provably" is one precondition, positive and exact, never an inspection of overrides -(Codex on PR #485, final check): **the stream that holds the rows is exactly a class whose -whole-table read is its rows, and nothing on the instance shadows one of that class's -methods or properties** (`reads_as_its_class`). It is applied in two places: +(Codex on PR #485, final check and round 7): **the stream that holds the rows is exactly a +class whose whole-table read is its rows, nothing on the instance shadows one of that +class's methods or properties** (`reads_as_its_class`), **its rows report the node's data +context, and every system-tag field of its table is what the rows give, non-null +`large_string`** (`system_tags_as_rows_give`). It is applied in two places: - a bound source: its class is a library source kind that itself declares `TABLE_IS_ROWS` (`table_is_rows`); @@ -533,7 +535,10 @@ methods or properties** (`reads_as_its_class`). It is applied in two places: context (its rows report that context, as `main`'s rows did), and its own `keys()` (the keys `iter_data` reads its rows with, tags in its tag-column order) give the order. -Any subclass, replaced reader or other stream kind takes `main`'s row path. +Any subclass, replaced reader, other stream kind, other data context or other system-tag +type takes `main`'s row path. A retained output held as its rows (`RowsOnRead`) keeps +only its rows once every successor has read it (`release_built`), as `main` retained +only the rows. | # | What differs | On `main` today | On the branch | Why `main` is wrong (bug, reproducer) | Approval needed | |---|---|---|---|---|---| diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index c5b94a773..1e60993e9 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -51,6 +51,7 @@ check_head_size, reads_as_its_class, short_stream_repr, + system_tags_as_rows_give, ) from orcapod.core.streams.view import ( JOB_NODE_NOT_RUN_NOTE, @@ -1712,27 +1713,32 @@ def execute( produced = produced_stream(result_stream) output: StreamProtocol + # The result's table, as the table built from its rows would be, without + # making the rows (ITL-1347, stage 2), when it provably is its rows: the + # stream holding them is exactly an ``ArrowTableStream`` in the node's + # data context, whose system tags are what the rows give. + result_table: pa.Table | None = None if ( - not reads_as_its_class(produced, ArrowTableStream) - or produced.data_context_key != self.data_context_key + reads_as_its_class(produced, ArrowTableStream) + and produced.data_context_key == self.data_context_key ): - # A result that is not exactly a stream over its table (a custom - # stream kind, a replaced reader), or whose rows report another data - # context than the node's: main's own row path, its rows read once and - # handed on unchanged, its table built where a successor reads it - # (ITL-1347). + result_table = result_stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS) + if not system_tags_as_rows_give(result_table.schema): + result_table = None + if result_table is None: + # Otherwise (a custom stream kind, a replaced reader, rows of another + # data context, system tags the rows type otherwise): main's own row + # path, its rows read once and handed on unchanged, its table built + # where a successor reads it (ITL-1347). rows = list(result_stream.iter_data()) self._cached_output_stream = StaticOutputOperatorPod._kept_output( result_stream, rows ) output = rows_on_read(rows, self) else: - # The result's table, as the table built from its rows would be, - # without making the rows (ITL-1347, stage 2). An exact - # ``ArrowTableStream``'s ``keys()`` are the keys its rows are read with - # (``iter_data``), so they are the order of the result's rows, to any - # depth of composition, never the prediction. - result_table = result_stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS) + # An exact ``ArrowTableStream``'s ``keys()`` are the keys its rows are + # read with (``iter_data``), so they are the order of the result's + # rows, to any depth of composition, never the prediction. keys = produced.keys() tag_keys = keys[0] data_tags = data_tag_names(*keys) diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index 5732b3142..76736f987 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -31,6 +31,7 @@ from orcapod.core.streams.base import ( ZERO_ROW_INPUT_COLUMNS, keys_of_rows, + system_tags_as_rows_give, row_built_columns, stream_arrow_schema, schema_requires_io, @@ -1837,12 +1838,20 @@ def _rows_table( ) if self._declared_form is not None: return None - if not table_is_rows(self._bound_source): + if ( + not table_is_rows(self._bound_source) + or self._bound_source.data_context_key != self.data_context_key + ): # Not a library source kind whose table is its rows (a side-effect or - # function pod stream, an operator's result, a raw stream, a poller): its - # rows, as main iterated them. + # function pod stream, an operator's result, a raw stream, a poller), or + # one whose rows report another data context than the node's: its rows, + # as main iterated them (the edge table is built in the node's context). return None table = self._bound_source.as_table(columns=ZERO_ROW_INPUT_COLUMNS) + if not system_tags_as_rows_give(table.schema): + # System tags the rows would type otherwise (a narrow integer, a + # nullable field): the rows decide, as on main. + return None return table, keys_of_rows(table, self._bound_source.keys()) def iter_data(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index 2d7fd0347..1a214dffe 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -1417,6 +1417,15 @@ def built(self) -> StreamProtocol: ) return self._stream + def release_built(self) -> None: + """Drop the built stream and keep only the rows. + + The sync orchestrator calls this on an output it retains once every successor + has read it: ``main`` held only the rows, so the retained output holds one + representation, and a later read builds the same table again from them. + """ + self._stream = None + def iter_data(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: """The rows it holds, unchanged (their meta columns included), as ``main``.""" return iter(self._rows) diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py index 26e05c0ce..d2ec40632 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -81,6 +81,28 @@ def reads_as_its_class(obj: object, cls: type) -> bool: return True +def system_tags_as_rows_give(schema: pa.Schema) -> bool: + """Whether every system-tag field is what the row rebuild gives: non-null text. + + ``main`` rebuilt a node's table from its rows, whose system tags are typed from + their values: a ``large_string`` field, non-nullable (the only kind library code + makes). A whole table is its rows only when its system tags are already so; a + narrow integer, a nullable field or any other type is decided by the rows + (ITL-1347). + + Args: + schema: The table's schema. + + Returns: + Whether every system-tag field is non-nullable ``large_string``. + """ + return all( + field.type == pa.large_string() and not field.nullable + for field in schema + if field.name.startswith(constants.SYSTEM_TAG_PREFIX) + ) + + def schema_requires_io(stream: object, config: ColumnConfig) -> bool: """Whether reading ``stream``'s schema with ``config`` would read or poll a source. diff --git a/src/orcapod/pipeline/sync_orchestrator.py b/src/orcapod/pipeline/sync_orchestrator.py index 523322fa4..3286caab7 100644 --- a/src/orcapod/pipeline/sync_orchestrator.py +++ b/src/orcapod/pipeline/sync_orchestrator.py @@ -95,6 +95,16 @@ def run( current: Any = None try: topo_order = list(graph.topological_sort()) + # Taken before any node runs: an observer may rebind a source, which + # changes how the graph finds that node afterwards. + neighbours = ( + { + id(n): (list(graph.predecessors(n)), list(graph.successors(n))) + for n in topo_order + } + if materialize_results + else {} + ) outputs: dict[Any, StreamProtocol] = {} processed: set[Any] = set() @@ -137,6 +147,8 @@ def run( if not materialize_results: self._gc_outputs(node, graph, outputs, processed) + else: + self._release_built_inputs(node, neighbours, outputs, processed) if not materialize_results: outputs.clear() @@ -191,6 +203,35 @@ def _ordered_inputs( return [at_edge(outputs[p]) for p in sorted_preds] + @staticmethod + def _release_built_inputs( + current_node: Any, + neighbours: dict[int, tuple[list[Any], list[Any]]], + outputs: dict[Any, StreamProtocol], + processed: set[Any], + ) -> None: + """Keep a retained output read by all its successors as its rows only. + + A ``RowsOnRead`` output builds its table at each successor's edge; once every + successor has run, the retained output drops the built stream and keeps the + rows, which is all ``main`` retained (ITL-1347). A later read builds it again. + + Args: + current_node: The node that just ran. + neighbours: Each node's predecessors and successors, by ``id``, taken + before the run. + outputs: The retained outputs. + processed: The nodes that ran. + """ + from orcapod.core.operators.static_output_pod import RowsOnRead + + for pred in neighbours[id(current_node)][0]: + output = outputs.get(pred) + if isinstance(output, RowsOnRead) and all( + succ in processed for succ in neighbours[id(pred)][1] + ): + output.release_built() + @staticmethod def _gc_outputs( current_node: Any, diff --git a/tests/test_pipeline/test_rows_on_read.py b/tests/test_pipeline/test_rows_on_read.py index 2113fb27d..c99226060 100644 --- a/tests/test_pipeline/test_rows_on_read.py +++ b/tests/test_pipeline/test_rows_on_read.py @@ -819,6 +819,210 @@ def stream() -> ArrowTableStream: assert kept.to_pylist() == [node.data_context_key] * 2 +# ── Codex round 7: the source's data context, system tags, retained lifetime ─── + + +def test_a_source_in_another_data_context_hands_on_its_own_rows() -> None: + """An exact ``CachedSource`` with its own data context: the rows a sync run returns + report the source's context, as ``main`` returned them, and the edge table is built + in the slot's context, as ``main`` rebuilt it.""" + import dataclasses + + from orcapod.contexts import get_default_context + from orcapod.core.nodes.source_node import SourceJobNode + from orcapod.core.operators.static_output_pod import at_edge + from orcapod.sources import CachedSource + from orcapod.system_constants import constants + + custom = dataclasses.replace(get_default_context(), context_key="review:custom") + inner = DictSource( + [{"k": 1, "x": 10}, {"k": 2, "x": 20}], + tag_columns=["k"], + tag_only_columns=True, + source_id="s", + data_context=custom, + ) + source = CachedSource( + inner, + cache_database=InMemoryArrowDatabase(), + source_id="cached", + data_context=custom, + ) + slot = SourceJobNode.from_stream(source) + dag: OrcaDAG[Any] = OrcaDAG() + dag.add_node(slot) + output: Any = SyncPipelineOrchestrator().run(dag).node_outputs[slot] + assert [ + (tag.data_context_key, data.data_context_key) + for tag, data in output.iter_data() + ] == [("review:custom", "review:custom")] * 2 + edge = at_edge(output).as_table(columns={"context": True}) + assert edge[constants.CONTEXT_KEY].to_pylist() == [slot.data_context_key] * 2 + + +class _AddSystemTag: + """``SelectDataColumns`` whose result carries one more system tag, ``int16``.""" + + @staticmethod + def operator(values: list[int | None], exact: bool) -> Any: + from orcapod.operators import SelectDataColumns + from orcapod.system_constants import constants + + class Unproven(ArrowTableStream): + """Reads as ``ArrowTableStream``; not proven: ``main``'s row path.""" + + kind = ArrowTableStream if exact else Unproven + + class AddSystemTag(SelectDataColumns): + def unary_static_process(self, stream: Any) -> Any: + out: Any = super().unary_static_process(stream) + table = out.as_table(columns={"source": True, "system_tags": True}) + table = table.append_column( + f"{constants.SYSTEM_TAG_PREFIX}region", + pa.array(values[: table.num_rows], pa.int16()), + ) + return kind(table, tag_columns=["k"]) + + return AddSystemTag(["x"]) + + +def _system_tag_job(values: list[int | None], exact: bool) -> tuple[Any, Any]: + database = InMemoryArrowDatabase() + job = PipelineJob(name="system_tag", database=database) + with job: + source = DictSource( + [{"k": 1, "x": 1}, {"k": 2, "x": 2}], + tag_columns=["k"], + tag_only_columns=True, + source_id="s", + ) + _AddSystemTag.operator(values, exact)(source, label="marked") + job.nodes["marked"].attach_databases( + pipeline_database=database.at("log"), cache_mode=CacheMode.LOG + ) + return job, database + + +def test_a_narrow_system_tag_is_stored_as_the_rows_give() -> None: + """A result over an exact ``ArrowTableStream`` with an ``int16`` system tag: kept, + stored and record-hashed as ``main``'s rows give it (``int64``, non-null), the + same as ``main``'s own row path (an unproven stream) gives.""" + from orcapod.system_constants import constants + + name = f"{constants.SYSTEM_TAG_PREFIX}region" + stored: dict[bool, Any] = {} + for exact in (True, False): + job, database = _system_tag_job([1, 2], exact) + job.run() + node: Any = job.nodes["marked"] + kept = node.as_table(columns={"system_tags": True}).schema.field(name) + assert (kept.type, kept.nullable) == (pa.int64(), False) + stored[exact] = database.at("log").get_all_records( + node._stored_table_path, # pyright: ignore[reportPrivateUsage] # the raw LOG table + record_id_column="_record_hash", + ) + for table in stored.values(): + field = table.schema.field(name) + assert (field.type, field.nullable) == (pa.int64(), False) + assert ( + stored[True]["_record_hash"].to_pylist() + == stored[False]["_record_hash"].to_pylist() + ) + + +def test_a_null_system_tag_raises_at_the_operator_as_main_does() -> None: + """With a null among its values, ``main``'s rows cannot make one table: the + operator raises ``ArrowInvalid`` before its end event, as on ``main``.""" + job, _ = _system_tag_job([None, 2], exact=True) + observer = _NodeEvents() + with pytest.raises(pa.ArrowInvalid): + job.run(observer=observer) + assert ("start", "marked") in observer.events + assert ("end", "marked") not in observer.events + + +def test_a_source_table_with_other_system_tags_is_not_its_rows() -> None: + """The source route's guard: an exact ``ArrowTableSource`` whose system tag is a + narrow integer has a table that is not its rows (they give ``int64``); a stock + source's system tags are what the rows give.""" + from orcapod.core.streams.base import system_tags_as_rows_give + + schema = pa.schema( + [ + pa.field("k", pa.int64(), nullable=False), + pa.field("x", pa.int64(), nullable=False), + pa.field("region", pa.int16(), nullable=False), + ] + ) + narrow = ArrowTableSource( + pa.Table.from_pylist( + [{"k": 1, "x": 10, "region": 1}, {"k": 2, "x": 20, "region": 2}], + schema=schema, + ), + tag_columns=["k"], + tag_only_columns=True, + system_tag_columns=["region"], + source_id="s", + ) + assert not system_tags_as_rows_give( + narrow.as_table(columns={"system_tags": True}).schema + ) + stock = _plain() + assert system_tags_as_rows_give( + stock.as_table(columns={"system_tags": True}).schema + ) + + +def test_a_retained_output_keeps_only_its_rows_once_read( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """With results retained, an output held as its rows drops its built stream once + every successor has read it (``main`` retained only the rows): no built stream + outlives the run, its rows are its own, and a later read builds the table again.""" + import gc + import weakref + + from orcapod import function_pod + from orcapod.core.operators.static_output_pod import ( + RowsOnRead, + StaticOutputOperatorPod, + ) + + @function_pod(output_keys="y") + def plus_one(x: int) -> int: + return x + 1 + + job = PipelineJob(name="retained", database=InMemoryArrowDatabase()) + with job: + computed: Any = plus_one.pod( + _plain().select_data_columns(["x"]), label="computed" + ) + computed.select_data_columns(["y"], label="second") + computed.select_data_columns(["y"], label="third") + + built: list[weakref.ref[Any]] = [] + original = StaticOutputOperatorPod._materialize_upstream # pyright: ignore[reportPrivateUsage] # the row path, watched + + def watched(*args: Any, **kwargs: Any) -> Any: + stream = original(*args, **kwargs) + built.append(weakref.ref(stream)) + return stream + + monkeypatch.setattr( + StaticOutputOperatorPod, "_materialize_upstream", staticmethod(watched) + ) + graph = job._node_graph # pyright: ignore[reportPrivateUsage] # the job's graph + assert graph is not None + result = SyncPipelineOrchestrator().run(graph) + output: Any = result.node_outputs[job.nodes["computed"]] + assert isinstance(output, RowsOnRead) + gc.collect() + assert built + assert all(ref() is None for ref in built) + assert len(list(output.iter_data())) == 2 + assert output.as_table().num_rows == 2 + + @pytest.mark.parametrize( "kind", [pa.time64("ns"), pa.decimal256(76, 40)], From 1c5c0458abfec9eb3dbd4505d3c4aec4aab26bd5 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 12:51:10 -0800 Subject: [PATCH 56/86] docs(pipeline): an observer that changes the pipeline mid-run is unsupported (ITL-1360, ITL-1369) Developer decision, November 22, 2026: an observer only watches; one that changes the job, its nodes or its bound sources during a run is unsupported, and what the run then does is undefined and not part of the equality with main (ITL-1369 will prevent it). The open spec row e11 and its strict xfail are removed; the governing rule states it, and so do the pipeline-job concept page, CLAUDE.md and .zed/rules. No code changes. Co-Authored-By: Claude Opus 5.5 --- .zed/rules | 4 ++ CLAUDE.md | 4 ++ docs/concepts/pipeline-job.md | 4 +- .../dev/specs/itl-1347-job-table-transport.md | 4 +- tests/test_pipeline/test_rows_on_read.py | 38 ------------------- 5 files changed, 14 insertions(+), 40 deletions(-) diff --git a/.zed/rules b/.zed/rules index bbd720618..2e6101650 100644 --- a/.zed/rules +++ b/.zed/rules @@ -1499,6 +1499,10 @@ data. The rules: are not concerned. The refusal is for now: how an operator node logs and replays is to be redesigned to load its cache and then apply the restriction (TODO(ITL-1219)). - Empty data → ArrowTableSource raises ValueError("Table is empty"). +- An observer only watches (developer, November 22, 2026, ITL-1369): an observer or callback + that changes the job, its nodes or its bound sources during a run is unsupported; what the + run then does is undefined and is not part of the equality with main. Preventing it (a + guard, then a read-only view) is ITL-1369; never chase a case that needs such a change. - A side-effect job node delivers only when it runs (developer, November 13, 2026, ITL-1091): job.run(), node.run() (state-driven, ITL-1095: a node holding a current run delivers nothing, so clear_cache() it first to deliver again; otherwise the job run's work for that diff --git a/CLAUDE.md b/CLAUDE.md index 0c6d59591..6b760dd45 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1546,6 +1546,10 @@ data. The rules: are not concerned. The refusal is for now: how an operator node logs and replays is to be redesigned to load its cache and then apply the restriction (`TODO(ITL-1219)`). - Empty data → `ArrowTableSource` raises `ValueError("Table is empty")`. +- An observer only watches (developer, November 22, 2026, ITL-1369): an observer or callback + that changes the job, its nodes or its bound sources during a run is unsupported; what the + run then does is undefined and is not part of the equality with `main`. Preventing it (a + guard, then a read-only view) is ITL-1369; never chase a case that needs such a change. - A side-effect job node delivers only when it runs (developer, November 13, 2026, ITL-1091): `job.run()`, `node.run()` (state-driven, ITL-1095: a node holding a current run delivers nothing, so `clear_cache()` it first to deliver again; otherwise the job run's work for that diff --git a/docs/concepts/pipeline-job.md b/docs/concepts/pipeline-job.md index 625400b73..e234ac81b 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -62,7 +62,9 @@ Among `job.run()`'s optional arguments, the tutorial's [Part 9](../tutorial/09-when-things-go-wrong.md) demonstrates `orchestrator=` (for example `SyncPipelineOrchestrator(error_policy="fail_fast")` to stop at the first failing row; the default policy skips failed rows and continues) and `observer=` (`StatusObserver`, -`LoggingObserver`) to record what happened during the run. `load_only=True` fills the nodes +`LoggingObserver`) to record what happened during the run. An observer only watches: one +that changes the job, its nodes or its bound sources during a run is unsupported, and what +the run then does is undefined (ITL-1369). `load_only=True` fills the nodes from what is already stored and computes nothing; see [Loading without computing](function-pods.md#loading-without-computing-runload_onlytrue). diff --git a/docs/dev/specs/itl-1347-job-table-transport.md b/docs/dev/specs/itl-1347-job-table-transport.md index 082e7a042..21769a847 100644 --- a/docs/dev/specs/itl-1347-job-table-transport.md +++ b/docs/dev/specs/itl-1347-job-table-transport.md @@ -539,6 +539,9 @@ Any subclass, replaced reader, other stream kind, other data context or other sy type takes `main`'s row path. A retained output held as its rows (`RowsOnRead`) keeps only its rows once every successor has read it (`release_built`), as `main` retained only the rows. +An observer or callback that changes the job, its nodes or its bound sources during a run +is unsupported; what the run then does is undefined and is not part of the equality with +`main` (ITL-1369; developer, November 22, 2026). | # | What differs | On `main` today | On the branch | Why `main` is wrong (bug, reproducer) | Approval needed | |---|---|---|---|---|---| @@ -548,7 +551,6 @@ only the rows. | e6 | Async values that depend on an earlier validation of the same operator object | `SemiJoin._validated_common_keys` and `Index._element_arrow_type_fallback` hold the last validation's values (ITL-858, section 1.2). One operator object applied to two streams can use the other stream's keys or fallback type | Read from each input's description, with no state | The ITL-858 finding; filed as ITL-1358. Reproducer: one `SemiJoin` instance validated on stream B, then run async over stream A with other keys. To be confirmed in stage 5 | ITL-1358 (filed); fixed with stage 5 once a reproducer confirms it | | e7 | What a consumer does after its producer failed (async, failure path) | The producer closes its output in `finally`, so a consumer sees a normal end and may finish, and a `LOG` operator node may store, a partial result before the task group cancels it | Readers raise `UpstreamFailedError` at the failure point instead of seeing a normal end, so no consumer finishes, or stores its result, as if its input were complete. Batches a consumer processed before the failure are still processed, and a streaming node may already have passed them on or a function node stored results for them, as on `main`; there is no rollback. A barrier operator never computes over a partial input. The run raises the producer's own error, as today | A candidate race, to be confirmed with a reproducer in stage 5: a `fail_fast` function node raising on row 3 of 6, feeding a `Select` node in `LOG` mode; check the operator cache after the failed run. If `main` never stores in practice, this row is no difference | filed by the developer only once a test reproduces it | | e8 | Meta columns of an async side-effect node's rows | An async side-effect node passes on and holds the rows it receives as they are, so a computed row keeps its `__computed` meta column (from the cached function pod), and the node's `as_table(all_info=True)` shows it. On sync, its input is rebuilt from rows (`_rows_to_table` drops meta), so the column is absent | Async drops input meta columns as sync does. With table transport this follows from the transport columns, which hold no meta column | A `main` bug: the async and sync paths give the node different columns. Found by the stage 0 harness on `job-speed` 0e15d0db, which does not change side-effect nodes; the stage 0 differential checks it on pinned `main`. Reproducer: a function node (with a result store) feeding a `tap_pod`, async against sync, comparing the side-effect node's `as_table(all_info=True)` columns | approved (developer, 2026-11-22) | -| e11 | An empty source fanned out to two operators, with an observer that rebinds the source between the two edges | Each successor's input is rebuilt at its own edge, so the second sees the rebound source's zero-row form (its field metadata) | The output held as its rows (`RowsOnRead`) is built once, at the first edge, and the second edge reuses it, so the second successor sees the first edge's form | Not a `main` bug: an observer that mutates the graph mid-run (Codex on PR #485, round 5). Reproducer: `tests/test_pipeline/test_rows_on_read.py::test_a_fanned_out_empty_source_rebound_between_edges` (strict xfail) | open: not approved; the coordinator takes it to the developer as a documented limit (2026-11-22) | **Resolved: refusals after rows have flowed (was c, question 9).** The developer's `Rejoin` rule (ITL-1355) removes every data-dependent refusal from `Rejoin`: it checks only what its diff --git a/tests/test_pipeline/test_rows_on_read.py b/tests/test_pipeline/test_rows_on_read.py index c99226060..800fced83 100644 --- a/tests/test_pipeline/test_rows_on_read.py +++ b/tests/test_pipeline/test_rows_on_read.py @@ -1052,41 +1052,3 @@ def test_a_lazy_output_describes_itself_without_converting_python_types( job.bind(sources={"s": raw}) out: Any = job.nodes["s"].execute() assert out.arrow_schema().field("x").type == kind - - -@pytest.mark.xfail( - strict=True, - raises=AssertionError, - reason="spec row e11: observer rebinds between two edges of one empty output (open)", -) -def test_a_fanned_out_empty_source_rebound_between_edges() -> None: - """Pinned limit (spec row e11): ``main`` rebuilds each edge, the branch builds once.""" - from orcapod.operators import SelectDataColumns - - def empty(mark: str) -> ArrowTableSource: - field = pa.field("x", pa.int64(), nullable=False, metadata={"mark": mark}) - table = pa.Table.from_arrays( - [pa.array([], pa.int64()), pa.array([], pa.int64())], - schema=pa.schema([pa.field("k", pa.int64(), nullable=False), field]), - ) - return ArrowTableSource(table, tag_columns=["k"], source_id="s") - - job = PipelineJob(name="fan_out_empty", database=InMemoryArrowDatabase()) - with job: - source = empty("initial") - SelectDataColumns(["x"])(source, label="first") - SelectDataColumns(["x"])(source, label="second") - slot = next(label for label in job.nodes if label not in ("first", "second")) - node = job.nodes[slot] - - class RebindsAfterFirst(NoOpObserver): - def contextualize(self, *identity_path: str) -> RebindsAfterFirst: - return self - - def on_node_end(self, node_label: str, node_hash: str) -> None: - if node_label == "first": - node.bound_source = empty("next") - - job.run(observer=RebindsAfterFirst()) - kept = job.nodes["second"].as_table() - assert kept.schema.field("x").metadata == {b"mark": b"next"} From 1a915e76f5cf0c475fd7728f73a3a91d239dfd66 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 13:16:16 -0800 Subject: [PATCH 57/86] refactor(channels): to_stream() is a method of the input channel again, the builder imported in its body (ITL-1362) (#490) Developer decision: the spec's RecordBatchInput.to_stream() is restored. InputChannel.to_stream() carries everything channel_to_stream did: a plain method that reserves the channel when called and returns the conversion to await (one pass, every read error before an operator runs, a fixed snapshot through stream_from_batches, the shortcut only for an unread channel opened on a ROW_BUILT_OUTPUT stream, a conversion that never starts releases the reader). stream_from_batches and ROW_BUILT_OUTPUT are imported inside the method body, as StreamBase.join imports the operators; channel_to_stream is deleted (no alias). Co-authored-by: Edgar Y. Walker Co-authored-by: Claude Opus 5.5 --- .zed/rules | 24 +++--- CLAUDE.md | 14 +-- .../core/operators/static_output_pod.py | 67 ++------------- .../core/streams/record_batch_input.py | 59 ++++++++++++- .../protocols/core_protocols/streams.py | 21 ++++- .../test_record_batch_channels.py | 85 +++++++++---------- .../operators/test_record_batch_execution.py | 4 +- 7 files changed, 146 insertions(+), 128 deletions(-) diff --git a/.zed/rules b/.zed/rules index bbd720618..cfef12e6a 100644 --- a/.zed/rules +++ b/.zed/rules @@ -1308,17 +1308,19 @@ data. The rules: refers to its stream (stream.open_channel()), an output channel to the stream it produces, and OutputChannel.result() closes it into that stream. The conversions are in one place, core/operators/static_output_pod.py (stream_from_batches, transport_schema, and F, - _row_built_form); never build a stream from record batches elsewhere. - channel_to_stream(channel) is the one conversion from an input channel to a stream: it reads - the channel to its end (one pass, every read error raised before an operator runs) and - rebuilds a fixed snapshot through stream_from_batches; only an unread channel whose stream - _output_stream built (ROW_BUILT_OUTPUT, set there only) gives that stream as it is. An - operator's record-batch form (async_execute_batches, renamed async_execute when wired) - applies its one static_process body: per record batch when the class declares ROW_BY_ROW = - True (each output row comes from one input row), otherwise as a barrier over the whole input - (channel_to_stream); Batch with a size has its own form, grouping rows by arrival. A new - operator whose output rows each come from one input row declares ROW_BY_ROW; write no other - per-operator batch code. + _row_built_form); never build a stream from record batches elsewhere. channel.to_stream() is + the one conversion from an input channel to a stream (a plain method that reserves the + channel when called and returns the conversion to await; it imports the builder inside its + body, since the operators sit above the streams): it reads the channel to its end (one pass, + every read error raised before an operator runs) and rebuilds a fixed snapshot through + stream_from_batches; only an unread channel opened on a stream _output_stream built + (ROW_BUILT_OUTPUT, set there only) gives that stream as it is. An operator's record-batch + form (async_execute_batches, renamed async_execute when wired) applies its one + static_process body: per record batch when the class declares ROW_BY_ROW = True (each output + row comes from one input row), otherwise as a barrier over the whole input (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 0c6d59591..2a0616434 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1356,16 +1356,18 @@ data. The rules: and `OutputChannel.result()` closes it into that stream. The conversions are in one place, `core/operators/static_output_pod.py` (`stream_from_batches`, `transport_schema`, and F, `_row_built_form`); never build a stream from record batches elsewhere. - `channel_to_stream(channel)` is the one conversion from an input channel to a stream: it - reads the channel to its end (one pass, every read error raised before an operator runs) and - rebuilds a fixed snapshot through `stream_from_batches`; only an unread channel whose stream + `channel.to_stream()` is the one conversion from an input channel to a stream (a plain + method that reserves the channel when called and returns the conversion to await; it imports + the builder inside its body, since the operators sit above the streams): it reads the + channel to its end (one pass, every read error raised before an operator runs) and rebuilds + a fixed snapshot through `stream_from_batches`; only an unread channel opened on a stream `_output_stream` built (`ROW_BUILT_OUTPUT`, set there only) gives that stream as it is. An operator's record-batch form (`async_execute_batches`, renamed `async_execute` when wired) applies its one `static_process` body: per record batch when the class declares `ROW_BY_ROW = True` (each output row comes from one input row), otherwise as a barrier over the whole - input (`channel_to_stream`); `Batch` with a size has its own form, grouping rows by arrival. - A new operator whose output rows each come from one input row declares `ROW_BY_ROW`; write - no other per-operator batch code. + 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/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index 62b990060..f930515f4 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -3,7 +3,7 @@ import asyncio import logging from abc import abstractmethod -from collections.abc import Collection, Coroutine, Iterator, Sequence +from collections.abc import Collection, Iterator, Sequence from datetime import datetime, timezone from typing import TYPE_CHECKING, Any, ClassVar, cast @@ -557,7 +557,7 @@ def _output_stream( node, ) # The one place a stream is marked as a complete, immutable output in the - # row-built form (ITL-1347): ``channel_to_stream`` may give it as it is. + # row-built form (ITL-1347): ``InputChannel.to_stream`` may give it as it is. setattr(stream, ROW_BUILT_OUTPUT, True) return stream @@ -905,7 +905,7 @@ async def async_execute_batches( A row-by-row operator (``ROW_BY_ROW``) is applied to each record batch as it arrives and sends that batch's result at once. Every other operator reads - all of its inputs first (``channel_to_stream``) and then runs exactly + 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. @@ -1020,7 +1020,7 @@ async def _streams_of(inputs: Sequence[RecordBatchInput]) -> list[StreamProtocol tasks: list[asyncio.Future[StreamProtocol]] = [] try: for channel in inputs: - tasks.append(asyncio.ensure_future(channel_to_stream(channel))) + tasks.append(asyncio.ensure_future(channel.to_stream())) return list(await asyncio.gather(*tasks)) except BaseException: # Every conversion already started is cancelled and awaited: none is left @@ -1080,65 +1080,10 @@ def transport_schema(stream: StreamProtocol) -> pa.Schema | None: Set in that one place, never inferred from a class: such a stream is a complete, immutable output already in the row-built form, so a consumer of its record batches -would rebuild exactly it, and ``channel_to_stream`` may give it without reading. +would rebuild exactly it, and ``InputChannel.to_stream`` may give it without reading. """ -def channel_to_stream( - channel: RecordBatchInput, -) -> Coroutine[Any, Any, StreamProtocol]: - """Return what an input channel delivers, as a stream: the one such conversion. - - It reads the channel to its end (one pass; every error of the read, such as an - unbound source's or a failed producer's, is raised here, before any operator runs) - and builds a fixed snapshot of what was delivered through the one settlement path - (``stream_from_batches``). The only shortcut: a channel opened on a complete - stream that ``_output_stream`` built (``ROW_BUILT_OUTPUT``), not read yet, gives - that stream, which is exactly what its batches would rebuild; the channel is then - closed. A reader of an output channel always collects, whatever its description. - - The channel is reserved when this function is called, before the returned - coroutine is awaited, so nothing can read it in between; the task that runs the - coroutine takes the channel over, and any other task's read is refused. If the - coroutine never starts (its task is cancelled first, or it is never awaited), - the reservation's claim is freed with it and the channel is closed, so no - producer waits on it. - - Args: - channel: The input channel, not read yet. - - Returns: - The conversion to await: a complete, re-readable stream of the channel's - input. - - Raises: - RuntimeError: If a read of the channel was already called (a batch received, - its end reached, or another consumer still waiting): a stream of part of - an input is never made, and a channel is never read again. - ChannelClosed: If the channel was closed, before or during the read. - UpstreamFailedError: If the producer failed or was cancelled. - """ - claim = channel.reserve() # at call time: nothing can read it before the await - return _channel_to_stream(channel, claim) - - -async def _channel_to_stream( - channel: RecordBatchInput, claim: object -) -> StreamProtocol: - """Read a reserved channel and return its input as a stream (``channel_to_stream``). - - Args: - channel: The channel ``channel_to_stream`` reserved. - claim: Its claim, which the task running this conversion takes over. - """ - channel.reserve(claim) - opened_on = channel.opened_on - if opened_on is not None and getattr(opened_on, ROW_BUILT_OUTPUT, False): - await channel.close() - return opened_on - return stream_from_batches(channel.stream, await channel.collect()) - - def stream_from_batches( stream: StreamProtocol, batches: Sequence[pa.RecordBatch] ) -> StreamProtocol: @@ -1146,7 +1091,7 @@ def stream_from_batches( The one place a stream is made from Arrow record batches: what an output channel gives once closed (``OutputChannel.result``), what an input channel delivered - (``channel_to_stream``), and the record batches a row-by-row operator is + (``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 diff --git a/src/orcapod/core/streams/record_batch_input.py b/src/orcapod/core/streams/record_batch_input.py index 86dfe2947..f617b1409 100644 --- a/src/orcapod/core/streams/record_batch_input.py +++ b/src/orcapod/core/streams/record_batch_input.py @@ -17,7 +17,7 @@ import asyncio import weakref -from collections.abc import AsyncIterator +from collections.abc import AsyncIterator, Coroutine from typing import TYPE_CHECKING, Any, Protocol from orcapod.channels import ChannelClosed @@ -59,7 +59,7 @@ class InputChannel: delivers is its ``stream``, known before the first batch: the producing node, or the stream it was opened from. A channel has no identity of its own and is read once; to read again, go back to a stream (the one it was opened from, or the one - ``channel_to_stream`` makes of what it delivered). + ``to_stream`` makes of what it delivered). Made by ``stream.open_channel()`` or by ``OutputChannel.open_reader()``, never directly. @@ -282,6 +282,61 @@ def _closed_early(self) -> ChannelClosed: + "producer completed; it has no complete input to give." ) + def to_stream(self) -> Coroutine[Any, Any, StreamProtocol]: + """Return what the channel delivers, as a stream: the one such conversion. + + It reads the channel to its end (one pass; every error of the read, such as + an unbound source's or a failed producer's, is raised here, before any + operator runs) and builds a fixed snapshot of what was delivered through the + one settlement path (``stream_from_batches``). The only shortcut: a channel + opened on a complete stream that ``_output_stream`` built + (``ROW_BUILT_OUTPUT``), not read yet, gives that stream, which is exactly what + its batches would rebuild; the channel is then closed. A reader of an output + channel always collects, whatever its description. + + A plain method that returns the conversion to await: the channel is reserved + when it is called, before the conversion is awaited, so nothing can read it + in between; the task that runs the conversion takes the channel over, and + any other task's read is refused. If the conversion never starts (its task + is cancelled first, or it is never awaited), the reservation's claim is freed + with it and the channel is closed, so no producer waits on it. + + Returns: + The conversion to await: a complete, re-readable stream of the channel's + input. + + Raises: + RuntimeError: If a read of the channel was already called (a batch + received, its end reached, or another consumer still waiting): a + stream of part of an input is never made, and a channel is never read + again. + ChannelClosed: If the channel was closed, before or during the read. + UpstreamFailedError: If the producer failed or was cancelled. + """ + claim = self.reserve() # at call time: nothing can read it before the await + return self._to_stream(claim) + + async def _to_stream(self, claim: object) -> StreamProtocol: + """Read the reserved channel and return its input as a stream (``to_stream``). + + Args: + claim: The reservation's claim, which the task running this conversion + takes over. + """ + # Imported here: the operators sit above the streams, and this module is + # imported by core/streams/base.py (a module-level import would be circular). + from orcapod.core.operators.static_output_pod import ( + ROW_BUILT_OUTPUT, + stream_from_batches, + ) + + self.reserve(claim) + opened_on = self.opened_on + if opened_on is not None and getattr(opened_on, ROW_BUILT_OUTPUT, False): + await self.close() + return opened_on + return stream_from_batches(self._stream, await self.collect()) + async def collect(self) -> list[pa.RecordBatch]: """Read to the end and return every remaining record batch, in arrival order. diff --git a/src/orcapod/protocols/core_protocols/streams.py b/src/orcapod/protocols/core_protocols/streams.py index 2ee788b67..7cb868e90 100644 --- a/src/orcapod/protocols/core_protocols/streams.py +++ b/src/orcapod/protocols/core_protocols/streams.py @@ -2,6 +2,7 @@ from collections.abc import ( AsyncIterator, + Coroutine, Collection, Iterable, Iterator, @@ -188,8 +189,8 @@ def open_channel(self) -> RecordBatchInput: The channel delivers the stream's rows as Arrow record batches, read once and in order; its description is this stream. Several channels may be opened on - one stream, each with its own position (``channel_to_stream`` makes a stream of - what a channel delivers). + one stream, each with its own position (``to_stream()`` makes a stream of what + a channel delivers). Returns: The input channel. @@ -648,6 +649,22 @@ def reserve(self, claim: object | None = None) -> object: """ ... + def to_stream(self) -> Coroutine[Any, Any, StreamProtocol]: + """Return what the channel delivers, as a stream: the one such conversion. + + A plain method returning the conversion to await; it reserves the channel + when called. The conversion reads the channel to its end, raises every read + error before an operator runs, and builds a fixed snapshot through the one + settlement path; only an unread channel opened on a stream ``_output_stream`` + built gives that stream as it is. + + Raises: + RuntimeError: If a read of the channel was already called. + ChannelClosed: If the channel was closed. + UpstreamFailedError: If the producer failed or was cancelled. + """ + ... + async def close(self) -> None: """Stop reading. The producer no longer waits for this reader.""" ... diff --git a/tests/test_channels/test_record_batch_channels.py b/tests/test_channels/test_record_batch_channels.py index e12bc7d59..16d16b44d 100644 --- a/tests/test_channels/test_record_batch_channels.py +++ b/tests/test_channels/test_record_batch_channels.py @@ -5,7 +5,7 @@ complete stream (``stream.open_channel()``) or from an output channel (``OutputChannel.open_reader``); an output channel, once closed, gives its rows back as an ordinary stream (``result()``), and so does an input channel that is read to its end -(``channel_to_stream``). One test per rule of the design's table "The hard semantics". +(``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``). @@ -36,7 +36,6 @@ from orcapod.core.operators.static_output_pod import ( ROW_BUILT_OUTPUT, StaticOutputOperatorPod, - channel_to_stream, stream_from_batches, transport_schema, ) @@ -118,7 +117,7 @@ async def read() -> list[pa.RecordBatch]: def test_a_channel_opened_on_a_stream_delivers_its_rows_and_refers_to_it() -> None: """The record batches are the stream's rows in the row-built form; the description - is the stream, and ``channel_to_stream`` rebuilds what the channel delivered, with + is the stream, and ``to_stream()`` rebuilds what the channel delivered, with the stream's identity.""" stream = source() channel = stream.open_channel() @@ -129,7 +128,7 @@ def test_a_channel_opened_on_a_stream_delivers_its_rows_and_refers_to_it() -> No assert as_protocol.stream is stream batches = run(stream.open_channel().collect) assert same(pa.Table.from_batches(batches), R(stream)) - delivered = run(lambda: channel_to_stream(channel)) + delivered = run(lambda: channel.to_stream()) assert same(delivered.as_table(columns=ALL), R(stream)) assert delivered.keys() == stream.keys() assert delivered.data_context_key == stream.data_context_key @@ -140,14 +139,14 @@ def test_a_channel_opened_on_a_stream_delivers_its_rows_and_refers_to_it() -> No def test_a_source_node_opens_a_channel_on_its_rows() -> None: """A source node is a stream too. A job's source node delivers its source's rows in - the row-built form, which ``channel_to_stream`` rebuilds. An unbound slot opens a + the row-built form, which ``to_stream()`` rebuilds. An unbound slot opens a channel (opening reads nothing), and its first read raises.""" stream = source() node = SourceJobNode.from_stream(stream, name="events") assert isinstance(node, StreamProtocol) batches = run(node.open_channel().collect) assert same(pa.Table.from_batches(batches), R(node)) - rebuilt = run(lambda: channel_to_stream(node.open_channel())) + rebuilt = run(lambda: node.open_channel().to_stream()) assert same(rebuilt.as_table(columns=ALL), R(node)) slot = SourceNode.from_stream(stream, name="events") @@ -254,7 +253,7 @@ async def read() -> tuple[list[pa.RecordBatch], Any]: for batch in batches: await output.send(batch) # the node's description takes them await output.close() - return batches, await channel_to_stream(node.open_channel()) + return batches, await node.open_channel().to_stream() batches, rebuilt = run(read) assert same(pa.Table.from_batches(batches), R(expected)) @@ -275,7 +274,7 @@ def test_a_rebind_before_the_first_read_is_read_whole() -> None: def test_a_source_nodes_conversion_keeps_the_delivered_column_order() -> None: """Plain tags declared ``k, j`` over physical columns ``x, j, k, y``: the stream - ``channel_to_stream`` makes keeps the columns in the order they were delivered + ``to_stream()`` makes keeps the columns in the order they were delivered (the node's rows), though the node describes itself in the slot's order.""" stream = ArrowTableSource( pa.table( @@ -295,7 +294,7 @@ def test_a_source_nodes_conversion_keeps_the_delivered_column_order() -> None: async def read() -> tuple[list[str], list[str]]: batches = await node.open_channel().collect() - rebuilt = await channel_to_stream(node.open_channel()) + rebuilt = await node.open_channel().to_stream() return batches[0].schema.names, rebuilt.as_table(columns=ALL).column_names delivered, rebuilt = run(read) @@ -349,26 +348,26 @@ async def flagged_stream() -> Any: for batch in batches: await output.send(batch) await output.close() - return await channel_to_stream(output.open_reader()) + return await output.open_reader().to_stream() flagged = run(flagged_stream) assert getattr(flagged, ROW_BUILT_OUTPUT, False) async def read() -> None: direct = flagged.open_channel() - assert await channel_to_stream(direct) is flagged + assert await direct.to_stream() is flagged other = OutputChannel(flagged) reader = other.open_reader() await other.send(batches[0]) await other.close() - rebuilt = await channel_to_stream(reader) + rebuilt = await reader.to_stream() assert rebuilt is not flagged assert rebuilt.as_table().num_rows == 1 failed = OutputChannel(flagged) failing = failed.open_reader() failed.fail(OSError("disk gone")) with pytest.raises(UpstreamFailedError): - _ = await channel_to_stream(failing) + _ = await failing.to_stream() op = SemiJoin() semi_output = OutputChannel(op(stream, flagged)) broken = OutputChannel(flagged) @@ -397,7 +396,7 @@ async def read() -> int: await asyncio.sleep(0) assert not reader.unread with pytest.raises(RuntimeError, match="read already|another consumer"): - _ = await channel_to_stream(reader) + _ = await reader.to_stream() with pytest.raises(RuntimeError, match="another consumer"): _ = await reader.receive() await output.send(batch) @@ -484,7 +483,7 @@ async def owner() -> int: @pytest.mark.parametrize("retain", [True, False], ids=["retained", "bounded"]) def test_a_conversion_reserves_the_reader_when_it_is_created(retain: bool) -> None: - """``pending = channel_to_stream(reader)`` reserves at once: a receive before + """``pending = reader.to_stream()`` reserves at once: a receive before ``await pending`` is refused, and the conversion gets every batch.""" stream = source(2) batches = batches_of(stream, 1) @@ -495,7 +494,7 @@ async def read() -> int: for batch in batches: await output.send(batch) await output.close() - pending = channel_to_stream(reader) + pending = reader.to_stream() with pytest.raises(RuntimeError, match="held for a conversion"): _ = await reader.receive() return (await pending).as_table().num_rows @@ -595,7 +594,7 @@ async def read() -> None: with pytest.raises(RuntimeError, match="StopAsyncIteration"): _ = await InputChannel(stream, _StoppingFeed(first)).collect() with pytest.raises(RuntimeError, match="StopAsyncIteration"): - _ = await channel_to_stream(InputChannel(stream, _StoppingFeed(first))) + _ = await InputChannel(stream, _StoppingFeed(first)).to_stream() run(read) @@ -628,7 +627,7 @@ async def read() -> None: @pytest.mark.parametrize("never", ["cancelled", "dropped"]) def test_a_conversion_that_never_starts_releases_its_reader(never: str) -> None: - """``channel_to_stream`` reserves at call time. If its conversion never starts (its + """``to_stream()`` reserves at call time. If its conversion never starts (its task is cancelled before the first step, or it is dropped unawaited), the reservation is released: the reader is closed and a bounded producer no longer waits on it.""" @@ -639,12 +638,12 @@ async def read() -> None: output = OutputChannel(stream, retain=False, buffer_size=1) reader = output.open_reader() if never == "cancelled": - task = asyncio.ensure_future(channel_to_stream(reader)) + task = asyncio.ensure_future(reader.to_stream()) _ = task.cancel() _ = await asyncio.gather(task, return_exceptions=True) del task else: - pending = channel_to_stream(reader) + pending = reader.to_stream() pending.close() # what dropping an unawaited coroutine does del pending gc.collect() @@ -680,7 +679,7 @@ async def read() -> None: def test_a_closed_reader_cannot_be_converted() -> None: - """A reader closed before any read: ``channel_to_stream`` raises ``ChannelClosed``, + """A reader closed before any read: ``to_stream()`` raises ``ChannelClosed``, as documented, not the error of a channel already read.""" stream = source(1) @@ -688,7 +687,7 @@ async def read() -> None: reader = OutputChannel(stream).open_reader() await reader.close() with pytest.raises(ChannelClosed, match="closed before its producer"): - _ = await channel_to_stream(reader) + _ = await reader.to_stream() run(read) @@ -705,7 +704,7 @@ async def fetch(self, cursor: Any = None) -> Any: def test_a_channel_closed_inside_the_read_is_a_read_error() -> None: """A ``ChannelClosed`` raised by the feed's own read (the source's) is not the end - of the input: iteration, ``collect`` and ``channel_to_stream`` raise it, and a + of the input: iteration, ``collect`` and ``to_stream()`` raise it, and a barrier fails before its body.""" declared = Schema({"id": int, "val": int}) @@ -722,7 +721,7 @@ async def read() -> None: _ = await polling().open_channel().collect() channel = polling().open_channel() with pytest.raises(ChannelClosed, match="underlying input"): - _ = await channel_to_stream(channel) + _ = await channel.to_stream() assert not channel.unread left = source() right = polling() @@ -765,7 +764,7 @@ async def read() -> bool: def test_an_unbound_input_fails_a_barrier_before_it_runs() -> None: """``SemiJoin`` with no shared tag never reads its right input on the sync path, - but ``channel_to_stream`` reads every input first: an unbound right input (a slot, + but ``to_stream()`` reads every input first: an unbound right input (a slot, or a ``SourceProxy``) raises what reading it raises, before the operator runs.""" left = source() other = ArrowTableSource( @@ -816,14 +815,14 @@ async def before_run() -> Any: async def after_run() -> None: assert await channel.collect() == [] # single pass: nothing more with pytest.raises(RuntimeError, match="read already"): - _ = await channel_to_stream(channel) + _ = await channel.to_stream() run(after_run) def test_a_polling_source_is_read_once_through_a_channel() -> None: """A fresh ``PollingSource``: opening a channel fetches nothing; reading it fetches - once and the stream ``channel_to_stream`` gives is a fixed snapshot, read again + once and the stream ``to_stream()`` gives is a fixed snapshot, read again with no further fetch, also through ``collect``.""" fake = FakeDynamicSource(batches=[_batch(i, 10 * i) for i in range(1, 6)]) polling = PollingSource( @@ -834,7 +833,7 @@ async def read() -> None: channel = polling.open_channel() other = polling.open_channel() assert len(fake.fetch_cursors) == 0 # opening reads nothing - snapshot = await channel_to_stream(channel) + snapshot = await channel.to_stream() fetched = len(fake.fetch_cursors) assert fetched == 1 # exactly one fetch for the channel's first read assert len(await other.collect()) >= 1 @@ -909,8 +908,8 @@ async def read() -> tuple[int, int]: assert run(read) == (1, 0) -def test_channel_to_stream_is_everything_or_nothing() -> None: - """``channel_to_stream`` on a channel already read is refused: never part of an +def test_to_stream_is_everything_or_nothing() -> None: + """``to_stream()`` on a channel already read is refused: never part of an input, and a channel is never read again.""" batches = batches_of(source(), 2) @@ -923,7 +922,7 @@ async def read() -> None: channel = output.open_reader() _ = await channel.receive() with pytest.raises(RuntimeError, match="read already"): - _ = await channel_to_stream(channel) + _ = await channel.to_stream() run(read) @@ -963,7 +962,7 @@ async def write() -> OutputChannel: def test_the_identity_of_a_result_with_and_without_a_producer() -> None: - """``result()`` and ``channel_to_stream`` take the describing stream's identity: its + """``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) @@ -973,7 +972,7 @@ async def both(stream: Any, batches: list[pa.RecordBatch]) -> tuple[Any, Any]: for batch in batches: await output.send(batch) await output.close() - return output.result(), await channel_to_stream(output.open_reader()) + return output.result(), await output.open_reader().to_stream() for stream in (root, produced): batches = batches_of(stream, 3) @@ -986,7 +985,7 @@ async def both(stream: Any, batches: list[pa.RecordBatch]) -> tuple[Any, Any]: def test_a_close_with_no_batch_is_the_typed_zero_row_stream() -> None: - """Zero rows: ``result()`` and ``channel_to_stream`` are typed by the description, never + """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) @@ -996,7 +995,7 @@ async def empty() -> tuple[Any, Any]: reader = output.open_reader() await output.close() await output.close() # a second close does nothing - return output.result(), await channel_to_stream(reader) + return output.result(), await reader.to_stream() for made in run(empty): table = made.as_table(columns=ALL) @@ -1238,20 +1237,18 @@ async def write() -> tuple[type[object], list[int]]: assert rows == [1] -def test_channel_to_stream_of_a_channel_closed_before_its_end_raises() -> None: - """A reader closed while ``channel_to_stream`` (or ``collect()``) reads never makes part +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 ("channel_to_stream", "collect"): + for read in ("to_stream", "collect"): output = OutputChannel(stream, retain=False, buffer_size=4) reader = output.open_reader() reading = asyncio.ensure_future( - channel_to_stream(reader) - if read == "channel_to_stream" - else reader.collect() + reader.to_stream() if read == "to_stream" else reader.collect() ) await output.send(first) await asyncio.sleep(0) @@ -1755,7 +1752,7 @@ async def waiting_consumer() -> Any: blocked = asyncio.ensure_future(waiting_consumer()) await first_read.wait() - whole = asyncio.ensure_future(channel_to_stream(barrier)) + whole = asyncio.ensure_future(barrier.to_stream()) await asyncio.sleep(0) output.fail(boom) output.fail(RuntimeError("a second failure changes nothing")) @@ -1790,7 +1787,7 @@ async def write() -> int: await output.send(batch) await output.close() output.fail(OSError("too late")) - return (await channel_to_stream(output.open_reader())).as_table().num_rows + return (await output.open_reader().to_stream()).as_table().num_rows assert run(write) == 7 @@ -1899,7 +1896,7 @@ async def inputs() -> list[RecordBatchInput]: def test_stream_from_batches_is_the_one_conversion() -> None: - """``result()`` and ``channel_to_stream`` are ``stream_from_batches``: its table equals the + """``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): diff --git a/tests/test_core/operators/test_record_batch_execution.py b/tests/test_core/operators/test_record_batch_execution.py index 71e6b7cad..6615b8867 100644 --- a/tests/test_core/operators/test_record_batch_execution.py +++ b/tests/test_core/operators/test_record_batch_execution.py @@ -4,7 +4,7 @@ (``async_execute_batches``) reads input channels opened from streams and writes an output channel, which closes into a stream. An operator whose output rows each come from one input row is applied to every record batch as it arrives; every other -operator reads all of its inputs first (``channel_to_stream``) and then runs the +operator reads all of its inputs first (``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 @@ -398,7 +398,7 @@ 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, in - every layout: ``channel_to_stream`` rebuilds what the channel delivered. A + every layout: ``to_stream()`` rebuilds what the channel delivered. A predicate that reads a ``null`` column's type or the column order follows that form (documented behaviour, e5); in a job neither case reaches an operator: a source refuses a ``null`` column, and a job refuses an expression that selects From 392655e001583ace2863b573500f69514e6016d6 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 13:51:52 -0800 Subject: [PATCH 58/86] fix(pipeline): an operator node reads its result from the one computation it captured (ITL-1360) CodeRabbit on PR #485 (dd6b7cd4): after produced_stream had refreshed the result wrapper, the node read the table (eager route) and the rows (row path, the error rows) through the wrapper again; over an upstream with no modified time each such read runs the operator again, so the operator ran twice where main runs it once, and the table could come from a second computation. The node now reads the table, the rows and the error rows from the captured stream. With no row, main's own kept-output path reads the wrapper once more, and so does the branch (main's count, unchanged). Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/nodes/operator_node.py | 10 ++++-- tests/test_pipeline/test_rows_on_read.py | 46 ++++++++++++++++++++++++ 2 files changed, 53 insertions(+), 3 deletions(-) diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index 1e60993e9..9e28abc91 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -1722,7 +1722,10 @@ def execute( reads_as_its_class(produced, ArrowTableStream) and produced.data_context_key == self.data_context_key ): - result_table = result_stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS) + # From the captured stream: reading the wrapper again could run the + # operator again (an upstream with no modified time), so the table, + # the keys and the gate describe one computation. + result_table = produced.as_table(columns=ZERO_ROW_INPUT_COLUMNS) if not system_tags_as_rows_give(result_table.schema): result_table = None if result_table is None: @@ -1730,7 +1733,8 @@ def execute( # data context, system tags the rows type otherwise): main's own row # path, its rows read once and handed on unchanged, its table built # where a successor reads it (ITL-1347). - rows = list(result_stream.iter_data()) + # The rows of the computation already made (``produced``), read once. + rows = list(produced.iter_data()) self._cached_output_stream = StaticOutputOperatorPod._kept_output( result_stream, rows ) @@ -1751,7 +1755,7 @@ def execute( ) except RowBuiltFormUnavailable as error: StaticOutputOperatorPod._raise_as_rows_do( - result_stream.iter_data(), error + produced.iter_data(), error ) self._cached_output_stream = ArrowTableStream( kept_table, tag_columns=tag_keys, data_tags=data_tags diff --git a/tests/test_pipeline/test_rows_on_read.py b/tests/test_pipeline/test_rows_on_read.py index 800fced83..988d83f5a 100644 --- a/tests/test_pipeline/test_rows_on_read.py +++ b/tests/test_pipeline/test_rows_on_read.py @@ -1023,6 +1023,52 @@ def watched(*args: Any, **kwargs: Any) -> Any: assert output.as_table().num_rows == 2 +# ── CodeRabbit on dd6b7cd4: one computation per run ─────────────────────────── + + +@pytest.mark.parametrize("mode", [CacheMode.OFF, CacheMode.LOG], ids=["off", "log"]) +@pytest.mark.parametrize("route", ["eager", "rows"]) +def test_an_operator_runs_once_over_an_undated_upstream( + route: str, mode: CacheMode +) -> None: + """Over an upstream with no modified time, every read of the operator's result + wrapper runs the operator again; the node reads its table, keys and rows from the + one computation it captured, so the operator runs once, as on ``main``.""" + from orcapod.core.nodes.operator_node import OperatorJobNode + from orcapod.operators import SelectDataColumns + + calls: list[int] = [] + + class Undated(ArrowTableStream): + @property + def last_modified(self) -> Any: + return None + + class Unproven(ArrowTableStream): + """Not proven: ``main``'s row path.""" + + class Counting(SelectDataColumns): + def unary_static_process(self, stream: Any) -> Any: + calls.append(1) + out: Any = super().unary_static_process(stream) + if route == "eager": + return out + table = out.as_table(columns={"source": True, "system_tags": True}) + return Unproven(table, tag_columns=["k"]) + + table = pa.table({"k": [1, 2], "x": [10, 20], "y": [1, 2]}) + upstream = Undated(table, tag_columns=["k"]) + node = OperatorJobNode( + Counting(["x"]), + [upstream], + pipeline_database=InMemoryArrowDatabase(), + cache_mode=mode, + ) + output: Any = node.execute(upstream) + assert len(list(output.iter_data())) == 2 + assert len(calls) == 1 + + @pytest.mark.parametrize( "kind", [pa.time64("ns"), pa.decimal256(76, 40)], From 3ceed8a64200819e6d6632a10504ad45beeb82eb Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 14:27:39 -0800 Subject: [PATCH 59/86] test(pipeline): no deferred-read test rebinds a source mid-run; document an undeclared schema (ITL-1360) CodeRabbit on PR #485 (1ae78fbb): - test_a_fallback_source_reads_its_rows_once and test_an_empty_output_is_derived_at_the_edge no longer rebind a source from an observer (unsupported, ITL-1369): the first counts the source's row reads (once) and checks the edge's error comes after the source's end and before the successor starts; the second records the zero-row build between the source's end and the successor's start. - arrow_types_declared states what a False description can hold: an explicit Arrow declaration, a converted Python schema, or an empty schema for an unpolled poller; not guaranteed to hold the column names. Docstring and tests only. Co-Authored-By: Claude Opus 5.5 --- .../protocols/core_protocols/streams.py | 10 +- tests/test_pipeline/test_rows_on_read.py | 93 ++++++++++--------- 2 files changed, 55 insertions(+), 48 deletions(-) diff --git a/src/orcapod/protocols/core_protocols/streams.py b/src/orcapod/protocols/core_protocols/streams.py index ba68aa0da..c5d4e9d34 100644 --- a/src/orcapod/protocols/core_protocols/streams.py +++ b/src/orcapod/protocols/core_protocols/streams.py @@ -197,9 +197,13 @@ def arrow_types_declared(self) -> bool: ``False`` when the stream cannot type itself without rows (an unbound slot, a ``PollingSource`` never polled; ITL-1089), or its rows decide its types (a - narrower bind, an output held as its rows): its schema is then converted from - the Python schema, and its names come in no guaranteed order; no consumer - relies on their order (ITL-1347). + narrower bind, an output held as its rows). Its schema is then the best + description available without reading a row: a slot's or source's explicit + Arrow declaration when it states one, otherwise its Python schema converted; + a source whose schema is known only by polling, and which has not polled, has + an empty schema. So a ``False`` description is not guaranteed to hold the + stream's column names, and the names it holds come in no guaranteed order; no + consumer relies on either (ITL-1347). """ ... diff --git a/tests/test_pipeline/test_rows_on_read.py b/tests/test_pipeline/test_rows_on_read.py index 988d83f5a..2ffc76211 100644 --- a/tests/test_pipeline/test_rows_on_read.py +++ b/tests/test_pipeline/test_rows_on_read.py @@ -20,7 +20,6 @@ from orcapod.databases import InMemoryArrowDatabase from orcapod.operators import Batch from orcapod.pipeline.dag import OrcaDAG -from orcapod.pipeline.observer import NoOpObserver from orcapod.pipeline.sync_orchestrator import SyncPipelineOrchestrator from orcapod.sources import ArrowTableSource, DictSource from orcapod.types import CacheMode @@ -49,27 +48,30 @@ def _plain() -> DictSource: def test_a_fallback_source_reads_its_rows_once() -> None: - """A rebind after the source node ended does not change what it handed on. - - Its rows were read once, when it ran: the successor's edge raises the original - rows' ``ArrowTypeError``, as on ``main``. - """ + """A source whose whole-table build is unavailable: its rows are read once, when it + runs, and the successor's edge raises the rows' ``ArrowTypeError`` after the + source's end and before the successor starts, as on ``main``.""" job = PipelineJob(name="read_once", database=InMemoryArrowDatabase()) with job: - Batch(batch_size=2)(_plain().select_data_columns(["x"]), label="batched") - job.bind(sources={"s": _unconvertible()}) - node = job.nodes["s"] - - class RebindsAtEnd(NoOpObserver): - def contextualize(self, *identity_path: str) -> RebindsAtEnd: - return self + Batch(batch_size=2)( + _plain().select_data_columns(["x"], label="selected"), label="batched" + ) + source: Any = _unconvertible() + reads: list[int] = [] + read = source.iter_data - def on_node_end(self, node_label: str, node_hash: str) -> None: - if node_label == "s": - node.bound_source = _plain() + def counted() -> Any: + reads.append(1) + return read() + source.iter_data = counted + job.bind(sources={"s": source}) + observer = _NodeEvents() with pytest.raises(pa.ArrowTypeError, match="Expected bytes"): - job.run(observer=RebindsAtEnd()) + job.run(observer=observer) + assert len(reads) == 1 + assert ("end", "s") in observer.events + assert ("start", "selected") not in observer.events def test_a_fallback_source_nobody_reads_completes() -> None: @@ -323,39 +325,40 @@ def test_a_library_source_kind_is_eager() -> None: assert not isinstance(job.nodes["s"].execute(), RowsOnRead) -def test_an_empty_output_is_derived_at_the_edge() -> None: - """A source with no row: its zero-row output is derived where the successor reads. - - An observer that rebinds the source when it ends changes what the successor - receives, as on ``main`` (Codex on PR #485, round 4). - """ - - def empty(mark: str) -> ArrowTableSource: - field = pa.field("x", pa.int64(), nullable=False, metadata={"mark": mark}) - table = pa.table({"k": pa.array([], pa.int64()), "x": pa.array([], pa.int64())}) - table = pa.Table.from_arrays( - table.columns, - schema=pa.schema([pa.field("k", pa.int64(), nullable=False), field]), - ) - return ArrowTableSource(table, tag_columns=["k"], source_id="s") - +def test_an_empty_output_is_derived_at_the_edge( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A source with no row: its zero-row input is built where the successor reads it, + after the source has ended and before the successor starts, as ``main`` rebuilt + it (Codex on PR #485, round 4).""" + from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod + + field = pa.field("x", pa.int64(), nullable=False) + table = pa.Table.from_arrays( + [pa.array([], pa.int64()), pa.array([], pa.int64())], + schema=pa.schema([pa.field("k", pa.int64(), nullable=False), field]), + ) job = PipelineJob(name="empty_edge", database=InMemoryArrowDatabase()) with job: - empty("before").select_data_columns(["x"], label="selected") + ArrowTableSource(table, tag_columns=["k"], source_id="s").select_data_columns( + ["x"], label="selected" + ) slot = next(label for label in job.nodes if label != "selected") - node = job.nodes[slot] - - class RebindsAtEnd(NoOpObserver): - def contextualize(self, *identity_path: str) -> RebindsAtEnd: - return self + observer = _NodeEvents() + original = StaticOutputOperatorPod._materialize_upstream # pyright: ignore[reportPrivateUsage] # the row path, watched - def on_node_end(self, node_label: str, node_hash: str) -> None: - if node_label == slot: - node.bound_source = empty("after") + def watched(rows: Any, upstream: Any) -> Any: + observer.events.append(("build", str(upstream.label))) + return original(rows, upstream) - job.run(observer=RebindsAtEnd()) - kept = job.nodes["selected"].as_table() - assert kept.schema.field("x").metadata == {b"mark": b"after"} + monkeypatch.setattr( + StaticOutputOperatorPod, "_materialize_upstream", staticmethod(watched) + ) + job.run(observer=observer) + events = observer.events + built = events.index(("build", slot)) + assert events.index(("end", slot)) < built < events.index(("start", "selected")) + assert job.nodes["selected"].as_table().num_rows == 0 def test_an_operator_with_an_empty_result_is_not_called_again() -> None: From ca8c4ba6c2cc5fbc0c8e852ce8c3da9cb728da3a Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 15:27:47 -0800 Subject: [PATCH 60/86] perf(pipeline): job nodes hand on Arrow-backed streams on the sync path (ITL-1347 stages 1-2, ITL-1360) (#485) * perf(pipeline): an operator node hands the table it kept to the nodes after it (ITL-1347 stage 1) Co-Authored-By: Claude Opus 5.5 * wip(pipeline): ITL-1347 stage 2: nodes return output streams, arrow_schema(), equivalence tests (ITL-1360) Work in progress. Done: every node's execute returns its output stream (sources and operators from F of their Arrow table, function and side-effect nodes from their rows); sync orchestrator passes streams; held= streams; node_outputs are streams; arrow_schema()/arrow_types_declared on StreamBase and SourceNodeBase; L0/L1/L2/L5/L7 tests (36 passed). Open: tests that call the removed SyncPipelineOrchestrator._materialize_as_stream (5 files) and two baseline observer-type entries whose columns moved; the full targeted suites are not run. Co-Authored-By: Claude Opus 5.5 * perf(pipeline): F takes the stream's keys and flags system tags by value (ITL-1360) The row-built form F now equals the table built from rows in two more ways: source info follows the data keys (a data-tag's first, in tag order), and every system-tag field, like every source-info field, is nullable only when a value is null; no schema metadata is kept. F is split into the row-by-row steps (_row_built_columns, for a channel's record batches) and the whole-table flags (_flag_by_values). _output_stream takes the keys. A test checks F against the rows over the whole async-sync matrix. Tests that called the removed SyncPipelineOrchestrator._materialize_as_stream call StaticOutputOperatorPod._materialize_upstream; test observers take the protocol's signatures. Co-Authored-By: Claude Opus 5.5 * perf(pipeline): arrow_schema() lists F's columns in F's order (ITL-1360) arrow_schema() takes the columns and order of the row-built form from one statement (_row_built_names): source info in data-key order, a data-tag's first. System-tag fields, like source-info fields, are stated nullable: a table decides their flags from its values. A source node gives its rows' tag and data keys (_row_keys). Co-Authored-By: Claude Opus 5.5 * docs(changelog): ITL-1360 fragment Co-Authored-By: Claude Opus 5.5 * test(pipeline): L7 for a loaded job (ITL-1360) Co-Authored-By: Claude Opus 5.5 * refactor(streams): F's per-slice step as module functions of streams.base (ITL-1360) row_built_names and row_built_columns move, unchanged, from StaticOutputOperatorPod to core/streams/base.py, so a stream applies them without importing the operators. StaticOutputOperatorPod and stream_arrow_schema call them. Co-Authored-By: Claude Opus 5.5 * fix(pipeline): F equals the rows for narrower sources and raw streams (ITL-1360) A narrower source's output is F of its table given as the declared schema (_DeclaredForm.apply), with the declared keys: its data-tags keep their source info, as each declared row does. F leaves meta (__) columns and their source info out, and gives system-tag and source-info fields the form a row builds from their values (row_built_provenance: no field metadata; a source-info list of nullable 'item' fields), so F equals the rows on raw streams too (Codex on PR #483, findings 5 and 7). arrow_schema() states the same fields. The pre-ITL-845 test hook is defined once, and patches F as well. Co-Authored-By: Claude Opus 5.5 * fix(side_effects): cast the node to StreamProtocol through object (ITL-1360) Co-Authored-By: Claude Opus 5.5 * fix(function_node): a type disagreement fails the run with as_table's error (ITL-1360) A function node builds its output stream before its run commits. Rows that cannot make one table (rows of a store written before ITL-928 next to rows computed now) fail the run at the node with the InputValidationError its as_table() raises, naming the column and both types, never a bare ArrowInvalid. Named difference e9 in the spec (provisional, coordinator decision 2026-11-22, pending the developer). Stage 1's changelog text is folded into the ITL-1360 fragment: one fragment for the PR that carries both stages. Co-Authored-By: Claude Opus 5.5 * fix(streams): type the schema metadata row_built_provenance keeps (ITL-1360) Co-Authored-By: Claude Opus 5.5 * fix(function_node): a failed write is reported before e9 (ITL-1360) The output stream is built after the run's writes are committed, so a store write error keeps precedence as on main. Co-Authored-By: Claude Opus 5.5 * docs(operators): state F's domain; pin its one exception and the bind refusal (ITL-1360) Co-Authored-By: Claude Opus 5.5 * fix(pipeline): F types source info from its tokens, over the whole table (ITL-1360) Codex on PR #485, finding 1. A row types each source-info token from its value (arrow_utils.source_info_arrow_type); F now does the same on the complete table (_type_source_info_by_values, beside _flag_by_values), so a list of None or of empty lists is kept and stored as the rows give it. Tokens of two types (a list on one row, None on another) cannot make one table: F raises SourceInfoTypesDisagree and the node builds its rows, which raise main's ArrowInvalid; a source node ends its node first, as on main. The domain exception of F is gone; its test is an equality test. Co-Authored-By: Claude Opus 5.5 * fix(source_node): a source's rows keep their data order (ITL-1360) Codex on PR #485, finding 2. A PollingSource states its declared key order, but its rows (and a table built from them) list the data in the fetched table's order. The source node takes its rows' keys from the table by the rule its rows follow (_keys_of_rows), so an operator after it keeps and stores the columns as on main. L2 test with a poller fetching in another order. Co-Authored-By: Claude Opus 5.5 * fix(pipeline): async held rows as planned; async outputs built on read (ITL-1360) Codex on PR #485, findings 3 and 4. The run plan keeps the rows of each held node as it took them (RunPlan.held_rows) beside their output streams. The async orchestrator takes those rows again (held_rows, as on main) and sends them, instead of reading the node again; the sync orchestrator takes the streams. The async orchestrator's node_outputs builds each node's stream when it is first read (StreamsOnRead), so an async run over rows that cannot make one table (e9's store written before ITL-928) finishes and holds its rows, as on main; e9 stays a sync-only difference. Co-Authored-By: Claude Opus 5.5 * fix(streams): a description never polls; L7 compares column order (ITL-1360) Codex on PR #485, findings 5 and 6. stream_arrow_schema's fallback for a stream that cannot type itself without rows asks only for its tags and system tags and states a string source-info field for each data column: asking for its source-info columns made a PollingSource that had not polled fetch its first batch. L7 compares columns in order. The arrangements where a source's tag schema is in layout order while its keys and rows follow the declared order (ITL-1365, being fixed on main) are strict xfails naming it, as is the reviewer's plain operator stream. Co-Authored-By: Claude Opus 5.5 * fix(pipeline): channels check source-info types as tokens; no new import cycle (ITL-1360) A source-info column's type follows its tokens over the complete table, so a channel's batch check (record_batch_channels._schema_mismatch) takes any token type there, as it takes any nullability; the channels test that pinned F's old empty-list exception is an equality test. The side-effect node builds its output stream through function_node.rows_as_output_stream instead of importing the operator module, which closed a new import cycle with the record-batch protocol module. Co-Authored-By: Claude Opus 5.5 * test(pipeline): name ITL-1366's input as difference e10 (ITL-1360) A declared source slot over a narrower source with one data-tag among two tags: main raises ValueError when the source's rows are rebuilt for its successor; the sync path completes with the rows the bind describes; the async path raises as main does until stage 5. Spec row e10, provisional (coordinator decision 2026-11-22, pending the developer). Co-Authored-By: Claude Opus 5.5 * fix(source_node): a narrower bind's rows keep main's key order; descriptions follow the rows (ITL-1360) Codex on PR #485, round 2, findings 1 and 5. A narrower source's rows are given as the declared schema one by one, the tag and the data table each through _DeclaredForm.apply, where a tag that is also data takes its place from the declared data order. _row_keys derives the keys by that same apply over zero-row tag and data tables (repeats dropped, missing names appended, for ITL-1366's one data-tag of two: e10), and the bound table is only retyped (_DeclaredForm.retype), since F selects by the keys. L2 sweep over declared layouts, tag orders and data-tag roles against the row path, kept and raw stored. A stream's description takes its data order from its table (keys_of_rows, now in streams.base), so a poller that fetched in another order is described as its rows are. A source-info field's type, like its flag, is decided by the values of a complete table: said in arrow_schema()'s docstring and the spec; L7 leaves both out by name, and pins a poller after a fetch and a value-decided list depth. Co-Authored-By: Claude Opus 5.5 * fix(pipeline): held streams built when read and not kept; membership builds nothing (ITL-1360) Codex on PR #485, round 2, findings 2, 6 and 7. A run plan's held streams are StreamsOnRead (keep=False): built when the sync orchestrator reaches the node, never while planning (an async run over a held node whose rows cannot make one table then runs as on main), and released once the node's successors ran. Membership, length and iteration of StreamsOnRead never build a stream. Co-Authored-By: Claude Opus 5.5 * fix(streams): an undeclared poller that has not polled is described with no column (ITL-1360) Codex on PR #485, round 2, finding 3. A stream whose schema is known only by polling (schema_requires_io) is described with no column, as a head shows it: no fetch, no modified-time change, arrow_types_declared stays false. Co-Authored-By: Claude Opus 5.5 * fix(pipeline): any failure of F's whole-table build falls back to the rows (ITL-1360) Codex on PR #485, round 2, finding 4. RowBuiltFormUnavailable is the one signal that a node's output must come from its rows: raised by _row_built_form for tokens of two types (SourceInfoTypesDisagree, now its subclass) and for any Arrow error of the whole-table build. Source and operator nodes catch it and build their rows, which raise main's error after main's observer events. Co-Authored-By: Claude Opus 5.5 * test(pipeline): type the held-lifetime test's streams (ITL-1360) Co-Authored-By: Claude Opus 5.5 * fix(pipeline): rows built on read off the provably-equal routes (ITL-1360) Codex on PR #485, round 3. One rule closes the class of the last three rounds: the eager whole-table build is used only where it is provably main's result (a transparent bind, an operator's own result, REPLAY of a table F can build). On every other route a node hands on the rows main would hold, as RowsOnRead, whose table main's own row path (_materialize_upstream) builds where the sync orchestrator gives it to a successor (at_edge): a narrower bind (no key re-derivation; its description is its declared schema's, arrow_types_declared false), a whole-table build that is unavailable (the rows read once), REPLAY of a stored table F cannot build, a held node (built at the successor's edge, not kept by the plan), and a function or side-effect node's rows. main's order, error and moment follow by construction; a leaf nobody reads is never built. e9 and e10 are gone: a leaf function node over a store written before ITL-928 completes and its as_table() raises main's InputValidationError, with a successor main's ArrowInvalid surfaces at the edge; ITL-1366's input raises main's ValueError at the successor's edge, sync, async and channel alike. Their tests are equality-with-main tests. Co-Authored-By: Claude Opus 5.5 * fix(pipeline): RowsOnRead typed through rows_on_read (ITL-1360) Co-Authored-By: Claude Opus 5.5 * fix(pipeline): the eager route only for library source kinds; RowsOnRead is a stream (ITL-1360) Codex on PR #485, round 4. - TABLE_IS_ROWS, declared once on RootSource (False) and True on the library source kinds whose as_table() and iter_data() read the same data with no effect: only a node bound to one hands on F of its table. Any other bound stream (a side-effect or function pod stream, an operator's result, a raw stream, a poller) hands on its rows, as main iterated them. - No table is prepared before main prepares it: a result with no row (source or operator) is RowsOnRead too, so its zero-row form is derived at the successor's edge and the operator is never called a second time. - RowsOnRead satisfies StreamProtocol structurally on 3.11-3.13 (every protocol member declared on the class; producer, upstreams, context, label and modified time read without building); iter_data() gives the rows it holds unchanged (meta included), sync and async node_outputs alike; arrow_schema() is the node's declared one (arrow_types_declared false) and open_channel() builds only at its first read. - A description whose types are undeclared gives names in no guaranteed order: transport_schema returns None for it and the channel's name check compares names as a set. Co-Authored-By: Claude Opus 5.5 * fix(pipeline): type the protocol-member walk and round-4 tests (ITL-1360) Co-Authored-By: Claude Opus 5.5 * fix(pipeline): eager only for a source kind's own reading; result order; channel checks (ITL-1360) Codex on PR #485, round 5. - table_is_rows(source): TABLE_IS_ROWS is honoured only when the declaring class reads the source, the source's own class or a subclass that overrides none of the row readers (iter_data, as_table, __iter__, async_iter_data, keys, output_schema); a filtering subclass hands on its rows, as main iterated them. - An operator node keeps, stores and hands on its result in the order the result's rows have (DynamicPodStream.result_keys), never re-placed by the prediction. - A channel without declared types compares names as a multiset (a duplicate column is refused), and each source-info column's token type must settle with the batches already accepted, refused at send with SourceInfoTypesDisagree otherwise. - A lazy output describes itself with its node's own description, and a description from declared types takes the Arrow schemas a slot states, never a conversion of Python types (time64[ns], decimal256). - Changelog corrected (no order promise where types are undeclared; when arrow_types_declared is false; what reading node_outputs builds). - Observer-only limit pinned: spec row e11 (open) and a strict xfail. Co-Authored-By: Claude Opus 5.5 * fix(pipeline): type the result keys and token kinds for basedpyright (ITL-1360) Co-Authored-By: Claude Opus 5.5 * fix(pipeline): eager only for exactly a proven class; result order from the stream holding the rows (ITL-1360) Codex on PR #485, final check. - One precondition, positive and exact (reads_as_its_class): the stream that holds the rows is exactly a class whose whole-table read is its rows, and nothing on the instance shadows one of that class's methods or properties. No inspection of overrides. Applied in two places: - a bound source: its class itself declares TABLE_IS_ROWS (table_is_rows); a subclass, a mixin, an instance-replaced reader or a _stream property hands on its rows, as main iterated them. SQLiteTableSource and PostgreSQLTableSource now declare the flag on their own class. - an operator's result: followed through every DynamicPodStream (produced_stream) to the stream holding its rows; exactly an ArrowTableStream gives its own keys() (the keys iter_data reads its rows with), any other kind takes main's row path verbatim. - Spec and changelog state the rule. Co-Authored-By: Claude Opus 5.5 * fix(pipeline): every wrapper in a result's chain proven; eager only in the node's data context (ITL-1360) CodeRabbit on PR #485 (352ce7b9). - produced_stream follows a DynamicPodStream only when it reads as DynamicPodStream itself (reads_as_its_class); a subclass, or a wrapper with iter_data replaced on the instance, stops the chain and the operator node takes main's row path (main read [20] through such a wrapper; 352ce7b9 gave [10, 20]). - An operator result whose rows report another data context than the node's takes main's row path: the rows execute hands on are main's rows, in their own context (the kept table is the node's context, as on main). Co-Authored-By: Claude Opus 5.5 * fix(pipeline): eager only in the node's data context with row-typed system tags; a retained output keeps its rows (ITL-1360) Codex on PR #485, round 7. - The one precondition gains two conditions, applied on both routes: the rows report the node's data context, and every system-tag field of the table is non-null large_string, what the rows give (system_tags_as_rows_give). An exact CachedSource with its own data context hands on its rows in that context (the edge table is built in the slot's context, as on main); a result with an int16 system tag takes main's row path (int64 non-null and main's record hashes; with a null, main's ArrowInvalid before the end event). - With results retained, the sync orchestrator drops a RowsOnRead's built stream once every successor has read it (release_built), so it holds only its rows, as main did; neighbours are taken before the run, since an observer may rebind a source. Co-Authored-By: Claude Opus 5.5 * docs(pipeline): an observer that changes the pipeline mid-run is unsupported (ITL-1360, ITL-1369) Developer decision, November 22, 2026: an observer only watches; one that changes the job, its nodes or its bound sources during a run is unsupported, and what the run then does is undefined and not part of the equality with main (ITL-1369 will prevent it). The open spec row e11 and its strict xfail are removed; the governing rule states it, and so do the pipeline-job concept page, CLAUDE.md and .zed/rules. No code changes. Co-Authored-By: Claude Opus 5.5 * fix(pipeline): an operator node reads its result from the one computation it captured (ITL-1360) CodeRabbit on PR #485 (dd6b7cd4): after produced_stream had refreshed the result wrapper, the node read the table (eager route) and the rows (row path, the error rows) through the wrapper again; over an upstream with no modified time each such read runs the operator again, so the operator ran twice where main runs it once, and the table could come from a second computation. The node now reads the table, the rows and the error rows from the captured stream. With no row, main's own kept-output path reads the wrapper once more, and so does the branch (main's count, unchanged). Co-Authored-By: Claude Opus 5.5 * test(pipeline): no deferred-read test rebinds a source mid-run; document an undeclared schema (ITL-1360) CodeRabbit on PR #485 (1ae78fbb): - test_a_fallback_source_reads_its_rows_once and test_an_empty_output_is_derived_at_the_edge no longer rebind a source from an observer (unsupported, ITL-1369): the first counts the source's row reads (once) and checks the edge's error comes after the source's end and before the successor starts; the second records the zero-row build between the source's end and the successor's start. - arrow_types_declared states what a False description can hold: an explicit Arrow declaration, a converted Python schema, or an empty schema for an unpolled poller; not guaranteed to hold the column names. Docstring and tests only. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Edgar Y. Walker <> Co-authored-by: Claude Opus 5.5 Co-authored-by: Edgar Y. Walker --- .zed/rules | 4 + CLAUDE.md | 4 + changelog.d/ITL-1360.md | 41 + docs/concepts/pipeline-job.md | 4 +- .../dev/specs/itl-1347-job-table-transport.md | 38 +- src/orcapod/core/nodes/function_node.py | 46 +- src/orcapod/core/nodes/operator_node.py | 98 +- src/orcapod/core/nodes/source_node.py | 149 ++- .../core/operators/static_output_pod.py | 475 ++++++- src/orcapod/core/record_batch_channels.py | 79 +- .../core/sources/arrow_table_source.py | 1 + src/orcapod/core/sources/base.py | 33 + src/orcapod/core/sources/cached_source.py | 1 + src/orcapod/core/sources/csv_source.py | 1 + src/orcapod/core/sources/data_frame_source.py | 1 + src/orcapod/core/sources/db_table_source.py | 1 + .../core/sources/delta_table_source.py | 1 + src/orcapod/core/sources/derived_source.py | 1 + src/orcapod/core/sources/dict_source.py | 1 + src/orcapod/core/sources/list_source.py | 1 + .../core/sources/postgresql_table_source.py | 1 + .../core/sources/spiraldb_table_source.py | 1 + .../core/sources/sqlite_table_source.py | 1 + src/orcapod/core/streams/base.py | 183 +++ src/orcapod/pipeline/async_orchestrator.py | 27 +- src/orcapod/pipeline/job.py | 31 +- src/orcapod/pipeline/loaded_side_effects.py | 5 +- src/orcapod/pipeline/node_run.py | 33 +- src/orcapod/pipeline/result.py | 63 +- src/orcapod/pipeline/sync_orchestrator.py | 149 +-- .../protocols/core_protocols/streams.py | 35 + src/orcapod/protocols/node_protocols.py | 8 +- src/orcapod/side_effects.py | 32 +- .../test_record_batch_channels.py | 57 +- .../function_pod/test_ephemeral_result.py | 26 +- .../test_function_node_arrow_types.py | 135 +- .../function_pod/test_function_pod_ctx_arg.py | 4 +- .../nodes/test_function_node_iteration.py | 18 +- tests/test_core/nodes/test_node_execute.py | 6 +- .../operators/test_materialize_source_info.py | 29 +- .../operators/test_record_batch_execution.py | 22 +- .../operators/test_row_built_form.py | 409 ++++++ .../test_side_effect_function_pod.py | 4 +- .../side_effect_pod/test_side_effect_pod.py | 16 +- ...est_postgresql_table_source_integration.py | 4 +- .../test_spiraldb_table_source_where.py | 6 +- .../sources/test_sqlite_table_source.py | 4 +- tests/test_core/test_tracker.py | 2 +- .../test_declared_slot_one_data_tag.py | 87 ++ .../test_error_policy_continue.py | 3 +- .../test_held_streams_on_read.py | 112 ++ .../test_job_node_rows_after_run.py | 2 +- .../test_pipeline/test_narrower_bind_order.py | 124 ++ tests/test_pipeline/test_node_protocols.py | 62 +- .../test_operator_node_async_readback.py | 2 +- tests/test_pipeline/test_rows_on_read.py | 1103 +++++++++++++++++ .../test_stream_transport_equivalence.py | 645 ++++++++++ tests/test_pipeline/test_sync_orchestrator.py | 7 +- .../test_system_tag_run_stability.py | 10 +- .../test_tag_table_source_info.py | 23 +- 60 files changed, 4151 insertions(+), 320 deletions(-) create mode 100644 changelog.d/ITL-1360.md create mode 100644 tests/test_core/operators/test_row_built_form.py create mode 100644 tests/test_pipeline/test_declared_slot_one_data_tag.py create mode 100644 tests/test_pipeline/test_held_streams_on_read.py create mode 100644 tests/test_pipeline/test_narrower_bind_order.py create mode 100644 tests/test_pipeline/test_rows_on_read.py create mode 100644 tests/test_pipeline/test_stream_transport_equivalence.py diff --git a/.zed/rules b/.zed/rules index cfef12e6a..67c9e3496 100644 --- a/.zed/rules +++ b/.zed/rules @@ -1501,6 +1501,10 @@ data. The rules: are not concerned. The refusal is for now: how an operator node logs and replays is to be redesigned to load its cache and then apply the restriction (TODO(ITL-1219)). - Empty data → ArrowTableSource raises ValueError("Table is empty"). +- An observer only watches (developer, November 22, 2026, ITL-1369): an observer or callback + that changes the job, its nodes or its bound sources during a run is unsupported; what the + run then does is undefined and is not part of the equality with main. Preventing it (a + guard, then a read-only view) is ITL-1369; never chase a case that needs such a change. - A side-effect job node delivers only when it runs (developer, November 13, 2026, ITL-1091): job.run(), node.run() (state-driven, ITL-1095: a node holding a current run delivers nothing, so clear_cache() it first to deliver again; otherwise the job run's work for that diff --git a/CLAUDE.md b/CLAUDE.md index 2a0616434..84a08370b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1548,6 +1548,10 @@ data. The rules: are not concerned. The refusal is for now: how an operator node logs and replays is to be redesigned to load its cache and then apply the restriction (`TODO(ITL-1219)`). - Empty data → `ArrowTableSource` raises `ValueError("Table is empty")`. +- An observer only watches (developer, November 22, 2026, ITL-1369): an observer or callback + that changes the job, its nodes or its bound sources during a run is unsupported; what the + run then does is undefined and is not part of the equality with `main`. Preventing it (a + guard, then a read-only view) is ITL-1369; never chase a case that needs such a change. - A side-effect job node delivers only when it runs (developer, November 13, 2026, ITL-1091): `job.run()`, `node.run()` (state-driven, ITL-1095: a node holding a current run delivers nothing, so `clear_cache()` it first to deliver again; otherwise the job run's work for that diff --git a/changelog.d/ITL-1360.md b/changelog.d/ITL-1360.md new file mode 100644 index 000000000..8121d7e70 --- /dev/null +++ b/changelog.d/ITL-1360.md @@ -0,0 +1,41 @@ +### Changed + +- **A job node's `execute` returns its output stream** — `execute` of a source, operator, + function and side-effect job node (and of the node protocols) returned the node's rows as + a list of (tag, data) pairs, and the sync orchestrator rebuilt a table from them for each + successor. It now returns the node's output stream, which the sync orchestrator hands to + every successor. Where that table is provably the rows' own, the node gives it + without making the rows: a node bound to an instance of exactly a library source kind + whose table is its rows (`TABLE_IS_ROWS`, never inherited by a subclass), and an + operator node whose result yields its rows from exactly an `ArrowTableStream`, in that + stream's row order (REPLAY: its stored table), each only when the rows report the + node's data context and every system tag is non-null text, as rows give it. Every other + output (a narrower bind, a subclass or another kind of bound stream or result, rows of + another data context, system tags of another type, a table the whole-table build + cannot use, a result with no row, a held node, a function or side-effect node) is the + node's rows, unchanged, whose table is built where a successor reads it, as before; a + retained one keeps only its rows once every successor has read it. + `OrchestratorResult.node_outputs` holds each node's output stream: its rows + (`iter_data()`) are the rows the node returned, and its table is built when the table + is first read (`as_table()`, a successor's edge); on the sync path a held node gives + the stream of its held rows, and the async path still sends a held node's rows as the + run's plan took them (`held_rows`). Every successor's input is unchanged: columns, + types, row order, system tags, source info, pipeline and content hashes, and an error + surfaces where and when it did. No hash, stored table or output changes. An operator + node's table is built once, for what it keeps and for every successor, instead of once + to keep and once per successor. The first two stages of the table transport between + job nodes (`docs/dev/specs/itl-1347-job-table-transport.md`). + (ITL-1347, ITL-1360) + +### Added + +- **`arrow_schema()` and `arrow_types_declared` on every stream** — `StreamProtocol`, + every stream and every source node state the Arrow schema of the columns a job node + passes on (user tags, system tags, data and source info), without reading, computing or + polling a row. System-tag and source-info fields are stated nullable and a source-info + field's type as the declared token type: a complete table decides both from its values, + so a consumer must not rely on them. A `null` column keeps the `null` type of a table + with no rows. `arrow_types_declared` is false where the rows decide the types: a stream + that cannot type itself without rows (an unbound slot, a `PollingSource` not yet + polled), a narrower bind, and an output held as its rows. Such a description gives the + declared names and types, in no guaranteed order. (ITL-1360) diff --git a/docs/concepts/pipeline-job.md b/docs/concepts/pipeline-job.md index 625400b73..e234ac81b 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -62,7 +62,9 @@ Among `job.run()`'s optional arguments, the tutorial's [Part 9](../tutorial/09-when-things-go-wrong.md) demonstrates `orchestrator=` (for example `SyncPipelineOrchestrator(error_policy="fail_fast")` to stop at the first failing row; the default policy skips failed rows and continues) and `observer=` (`StatusObserver`, -`LoggingObserver`) to record what happened during the run. `load_only=True` fills the nodes +`LoggingObserver`) to record what happened during the run. An observer only watches: one +that changes the job, its nodes or its bound sources during a run is unsupported, and what +the run then does is undefined (ITL-1369). `load_only=True` fills the nodes from what is already stored and computes nothing; see [Loading without computing](function-pods.md#loading-without-computing-runload_onlytrue). diff --git a/docs/dev/specs/itl-1347-job-table-transport.md b/docs/dev/specs/itl-1347-job-table-transport.md index ce0097d17..21769a847 100644 --- a/docs/dev/specs/itl-1347-job-table-transport.md +++ b/docs/dev/specs/itl-1347-job-table-transport.md @@ -194,9 +194,13 @@ A run checks its sources first (ITL-1102), which polls them. **ITL-1307 later.** When `Schema` carries its Arrow schema, `arrow_schema()` reads the two schemas plus the system-tag and source-info fields, in one place (`StreamBase`). -Two exceptions keep today's bytes: -- **Source-info nullability** is decided by a complete Arrow table's values (F step 5). - `arrow_schema()` states those fields nullable (question 5). +Three exceptions keep today's bytes: +- **Source-info and system-tag nullability** is decided by a complete Arrow table's values + (F step 5). `arrow_schema()` states those fields nullable (question 5). +- **Source-info types** are decided by a complete Arrow table's tokens, as each row types + its tokens from their values (`_type_source_info_by_values`): a list of `None` or of + empty lists shows fewer list levels than its column declares. `arrow_schema()` states the + declared token type; consumers must not rely on it (Codex on PR #485). - **`null` columns.** Rows carry `large_string`, and a zero-row Arrow table carries `null`, as today (ITL-1319). @@ -511,7 +515,33 @@ rows; they are kept as `main` has them, and documented below. **No row changes a sync-path result.** On the sync path the branch equals `main` byte for byte. Stages 1–4 hold this by construction and by L0–L5, and a lemma that fails stops its -stage. +stage. Where building a node's output from its whole table is not provably `main`'s result +(a narrower bind, a whole-table build that is unavailable, an odd stored table, a held +node, a node whose output is still its rows), the node hands on its rows and the table is +built from them by `main`'s row path where a successor reads them (`RowsOnRead`, +`at_edge`): `main`'s order, error and moment by construction (Codex on PR #485, round 3). +"Provably" is one precondition, positive and exact, never an inspection of overrides +(Codex on PR #485, final check and round 7): **the stream that holds the rows is exactly a +class whose whole-table read is its rows, nothing on the instance shadows one of that +class's methods or properties** (`reads_as_its_class`), **its rows report the node's data +context, and every system-tag field of its table is what the rows give, non-null +`large_string`** (`system_tags_as_rows_give`). It is applied in two places: + +- a bound source: its class is a library source kind that itself declares + `TABLE_IS_ROWS` (`table_is_rows`); +- an operator's result: the stream it yields its rows from, followed through every + `DynamicPodStream` that is itself proven (`produced_stream`; a subclass or a wrapper + with a replaced member stops the chain), is `ArrowTableStream` in the node's data + context (its rows report that context, as `main`'s rows did), and its own `keys()` (the + keys `iter_data` reads its rows with, tags in its tag-column order) give the order. + +Any subclass, replaced reader, other stream kind, other data context or other system-tag +type takes `main`'s row path. A retained output held as its rows (`RowsOnRead`) keeps +only its rows once every successor has read it (`release_built`), as `main` retained +only the rows. +An observer or callback that changes the job, its nodes or its bound sources during a run +is unsupported; what the run then does is undefined and is not part of the equality with +`main` (ITL-1369; developer, November 22, 2026). | # | What differs | On `main` today | On the branch | Why `main` is wrong (bug, reproducer) | Approval needed | |---|---|---|---|---|---| diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 6b8ee6a3a..ebd445e5c 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -282,6 +282,27 @@ def _with_datagram_id(data: Data, datagram_id: uuid.UUID) -> Data: ) +def rows_as_output_stream( + rows: Sequence[tuple[TagProtocol, DataProtocol]], node: StreamProtocol +) -> StreamProtocol: + """Return ``rows`` as ``node``'s output stream: the rows, built when read. + + For the job nodes whose output is still their rows (function and side-effect + nodes, until ITL-1347 stages 3 and 4): ``RowsOnRead``, built by ``main``'s row path + where a successor reads it. One place imports the operator module for them. + + Args: + rows: The node's output rows, in order. + node: The node. + + Returns: + The node's output stream. + """ + from orcapod.core.operators.static_output_pod import rows_on_read + + return rows_on_read(rows, node) + + def _executor_supports_concurrent( data_function: DataFunctionProtocol, ) -> bool: @@ -2456,6 +2477,19 @@ def as_node(self) -> FunctionNode: # Data processing # ------------------------------------------------------------------ + def _output_stream( + self, rows: list[tuple[TagProtocol, DataProtocol]] + ) -> StreamProtocol: + """The output stream of a run whose output rows are ``rows``. + + The rows, their table built when read by ``main``'s row path + (``RowsOnRead``): the sync orchestrator builds it where a successor reads it, + as ``main`` rebuilt the rows there, and a leaf's is never built (ITL-1347). + """ + from orcapod.core.operators.static_output_pod import rows_on_read + + return rows_on_read(rows, self) + def execute_data( self, tag: TagProtocol, @@ -2485,7 +2519,7 @@ def execute( error_policy: Literal["continue", "fail_fast"] = "continue", run_id: str | None = None, load_only: bool = False, - ) -> list[tuple[TagProtocol, DataProtocol]]: + ) -> StreamProtocol: """Execute all data from a stream: compute, persist, and cache. For each data: fire ``on_data_start``, check the in-memory cache @@ -2511,8 +2545,10 @@ def execute( this way. Returns: - Materialized list of (tag, output_data) pairs, excluding - ``None`` outputs and failed data. + The node's output stream: its output rows (no row for a ``None`` output or + a failed row) as the table ``_rows_to_table`` builds from them, with this + node's identity (``StaticOutputOperatorPod._materialize_upstream``). The sync + orchestrator hands it to every successor (ITL-1347, stage 2). Raises: RuntimeError: If the node was loaded by ``PipelineJob.load`` and so @@ -2524,7 +2560,7 @@ def execute( from orcapod.pipeline.observer import NoOpObserver if load_only: - return self._execute_load_only(input_stream, observer) + return self._output_stream(self._execute_load_only(input_stream, observer)) if self._function_pod is None: raise self._cannot_compute_error() @@ -2653,7 +2689,7 @@ def execute( self.clear_cache() raise - return output + return self._output_stream(output) def _empty_data_cache_hit( self, tag: TagProtocol, data: EmptyData, base_entry_id: bytes diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index d66d479c6..9e28abc91 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -38,13 +38,20 @@ ) from orcapod.channels import Channel, ChannelClosed, ReadableChannel, WritableChannel from orcapod.config import OrcapodConfig -from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod +from orcapod.core.operators.static_output_pod import ( + RowBuiltFormUnavailable, + StaticOutputOperatorPod, + produced_stream, + rows_on_read, +) from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.core.streams.base import ( ZERO_ROW_INPUT_COLUMNS, StreamBase, check_head_size, + reads_as_its_class, short_stream_repr, + system_tags_as_rows_give, ) from orcapod.core.streams.view import ( JOB_NODE_NOT_RUN_NOTE, @@ -1645,7 +1652,7 @@ def execute( *input_streams: StreamProtocol, observer: ExecutionObserverProtocol | None = None, load_only: bool = False, - ) -> list[tuple[TagProtocol, DataProtocol]]: + ) -> StreamProtocol: """Execute input streams: compute, persist, and cache. Args: @@ -1657,7 +1664,10 @@ def execute( as in any run. Returns: - Materialized list of (tag, data) pairs. + The node's output stream: its rows as the table ``_rows_to_table`` builds + from them (``StaticOutputOperatorPod._output_stream``), with this node's + identity, built from the operator's result table without making rows + (ITL-1347, stage 2). The sync orchestrator hands it to every successor. Raises: ValueError: If the node caches (``LOG`` or ``REPLAY``) and a source @@ -1685,20 +1695,84 @@ def execute( # Check REPLAY cache first cached_output = self.get_cached_output() if cached_output is not None: - output = list(cached_output.iter_data()) + try: + output = StaticOutputOperatorPod._output_stream( + cached_output.as_table(columns=ZERO_ROW_INPUT_COLUMNS), + cached_output.keys(), + self, + ) + except RowBuiltFormUnavailable: + # A stored table F cannot build from: its rows, built when read, + # as main handed them on (ITL-1347). + output = rows_on_read(cached_output.iter_data(), self) ctx_obs.on_node_end(node_label, node_hash) return output # Compute result_stream = self._operator.process(*input_streams) - - # Materialize - output = list(result_stream.iter_data()) - - # Cache, in row order with or without rows (ITL-1131, ITL-1133) - self._cached_output_stream = StaticOutputOperatorPod._kept_output( - result_stream, output - ) + produced = produced_stream(result_stream) + + output: StreamProtocol + # The result's table, as the table built from its rows would be, without + # making the rows (ITL-1347, stage 2), when it provably is its rows: the + # stream holding them is exactly an ``ArrowTableStream`` in the node's + # data context, whose system tags are what the rows give. + result_table: pa.Table | None = None + if ( + reads_as_its_class(produced, ArrowTableStream) + and produced.data_context_key == self.data_context_key + ): + # From the captured stream: reading the wrapper again could run the + # operator again (an upstream with no modified time), so the table, + # the keys and the gate describe one computation. + result_table = produced.as_table(columns=ZERO_ROW_INPUT_COLUMNS) + if not system_tags_as_rows_give(result_table.schema): + result_table = None + if result_table is None: + # Otherwise (a custom stream kind, a replaced reader, rows of another + # data context, system tags the rows type otherwise): main's own row + # path, its rows read once and handed on unchanged, its table built + # where a successor reads it (ITL-1347). + # The rows of the computation already made (``produced``), read once. + rows = list(produced.iter_data()) + self._cached_output_stream = StaticOutputOperatorPod._kept_output( + result_stream, rows + ) + output = rows_on_read(rows, self) + else: + # An exact ``ArrowTableStream``'s ``keys()`` are the keys its rows are + # read with (``iter_data``), so they are the order of the result's + # rows, to any depth of composition, never the prediction. + keys = produced.keys() + tag_keys = keys[0] + data_tags = data_tag_names(*keys) + + # Cache, in row order with or without rows (ITL-1131, ITL-1133). + if result_table.num_rows: + try: + kept_table = StaticOutputOperatorPod._row_built_form( + result_table, keys + ) + except RowBuiltFormUnavailable as error: + StaticOutputOperatorPod._raise_as_rows_do( + produced.iter_data(), error + ) + self._cached_output_stream = ArrowTableStream( + kept_table, tag_columns=tag_keys, data_tags=data_tags + ) + # The output stream, built once the node holds its run (as the + # sync orchestrator built a successor's input after ``execute`` + # returned). + output = StaticOutputOperatorPod._as_upstream_stream( + kept_table, tag_keys, data_tags, self + ) + else: + self._cached_output_stream = ( + StaticOutputOperatorPod._zero_rows_in_row_order(result_stream) + ) + # Its zero-row form is derived where a successor reads it, as on + # main: the operator is not called again here (``RowsOnRead``). + output = rows_on_read([], self) self._update_modified_time() diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index 9bb629109..76736f987 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -26,12 +26,17 @@ from orcapod.core.base import TraceableBase from orcapod.core.datagrams import Data, Tag from orcapod.core.operators.drop_nulls import _without_none # pyright: ignore[reportPrivateUsage] # DropNulls' rule for removing None from a type, shared, never copied +from orcapod.core.sources.base import table_is_rows from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.core.streams.base import ( ZERO_ROW_INPUT_COLUMNS, + keys_of_rows, + system_tags_as_rows_give, row_built_columns, + stream_arrow_schema, schema_requires_io, typed_arrow_schemas, + typed_zero_row_input, typed_zero_row_table, ) from orcapod.core.streams.record_batch_input import SOURCE_BATCH_ROWS, InputChannel @@ -422,14 +427,11 @@ def _require_stream_arrow_types(stream: Any, slot: str) -> None: class _ExecuteOutputFeed: """The record batches of a source node's own ``execute()`` output. - Built at the first read from the rows ``execute()`` gives, rebuilt as a job does - (``StaticOutputOperatorPod._materialize_upstream``): slow, and correct by - definition. One binding is read, at that moment. A batch is dropped once - delivered. + Built at the first read from the output stream ``execute()`` gives (ITL-1347, + stage 2: the table a job hands on, already in the row-built form). One binding is + read, at that moment. A batch is dropped once delivered. """ - # TODO(ITL-1360): the channel of stage 2's ``execute()`` output stream. - def __init__(self, node: SourceNodeBase) -> None: """Make the feed; nothing is read until the first ``next``. @@ -442,12 +444,7 @@ def __init__(self, node: SourceNodeBase) -> None: async def next(self) -> pa.RecordBatch | None: """Return the next record batch of the node's output, or ``None`` at the end.""" if self._batches is None: - from orcapod.core.operators.static_output_pod import ( - StaticOutputOperatorPod, - ) - - rows = self._node.execute() - output = StaticOutputOperatorPod._materialize_upstream(rows, self._node) # pyright: ignore[reportPrivateUsage] # the job's rebuild of a node's rows + output = self._node.execute() table = row_built_columns( output.as_table(columns=ZERO_ROW_INPUT_COLUMNS), output.keys() ) @@ -1255,27 +1252,78 @@ def iter_data(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: """Yield ``(tag, data)`` pairs, or raise if data is unavailable.""" ... + def _rows_table( + self, + ) -> tuple[pa.Table, tuple[tuple[str, ...], tuple[str, ...]]] | None: + """The table of this node's rows (``iter_data``) and the rows' keys, or ``None``. + + ``None`` here: a node that carries no data of its own hands on its rows + (``RowsOnRead``), which raise what reading it raises. A bound job node gives + its bound source's table when F of it is provably the rows' own table. + """ + return None + + def arrow_schema(self) -> pa.Schema: + """The Arrow schema of the columns this stream passes between job nodes. + + See ``stream_arrow_schema`` (ITL-1347): never reads, computes or polls a row. + The columns are in the order of the node's rows (``_row_keys``). + """ + return stream_arrow_schema(self, self._row_keys()) + + def _row_keys(self) -> tuple[tuple[str, ...], tuple[str, ...]]: + """The tag and data keys of this node's rows: its own keys.""" + return self.keys() + + @property + def arrow_types_declared(self) -> bool: + """Whether ``arrow_schema()`` holds the rows' own Arrow types (ITL-1089, ITL-1347).""" + return typed_zero_row_table(self) is not None + def execute( self, *, observer: ExecutionObserverProtocol | None = None, - ) -> list[tuple[TagProtocol, DataProtocol]]: - """Execute this source node: materialize and return data. + ) -> StreamProtocol: + """Execute this source node: read its source once and return its output stream. + + The source's table, as the table built from its rows would be + (``StaticOutputOperatorPod._output_stream``), with this node's identity, built + without making rows (ITL-1347, stage 2). The sync orchestrator hands it to every + successor. Args: observer: Optional execution observer. Returns: - List of (tag, data) tuples. + The node's output stream. Raises: UnboundSourceError: When no concrete data is available. """ + from orcapod.core.operators.static_output_pod import ( + RowBuiltFormUnavailable, + StaticOutputOperatorPod, + rows_on_read, + ) + node_label = self.label node_hash = self.content_hash().to_string() if observer is not None: observer.on_node_start(node_label, node_hash) - result = list(self.iter_data()) + # The table and keys of this node's rows, when F of the table is provably the + # rows' own table; otherwise (a narrower bind) the rows, built when read. + rows_table = self._rows_table() + result: StreamProtocol + if rows_table is None: + result = rows_on_read(self.iter_data(), self) + else: + table, keys = rows_table + try: + result = StaticOutputOperatorPod._output_stream(table, keys, self) + except RowBuiltFormUnavailable: + # The rows decide (read once, here), built when read, as on main. + result = rows_on_read(self.iter_data(), self) if observer is not None: observer.on_node_end(node_label, node_hash) return result @@ -1737,6 +1785,75 @@ def identity_structure(self) -> Any: return self._bound_source.identity_structure() return super().identity_structure() + def _row_keys(self) -> tuple[tuple[str, ...], tuple[str, ...]]: + """The tag and data keys of this node's rows, known without reading a row. + + The bound source's rows have the keys of its table (``keys_of_rows``, over its + typed zero-row table, which reads no row). A narrower bind (``_DeclaredForm``) + and an unbound slot answer with the slot's own keys: their description reports + its types undeclared (``arrow_types_declared``). + """ + if self._bound_source is None or self._declared_form is not None: + return self.keys() + table = typed_zero_row_input(self._bound_source) + if table is None: + return self.keys() + return keys_of_rows(table, self._bound_source.keys()) + + def arrow_schema(self) -> pa.Schema: + """The Arrow schema of the columns this stream passes between job nodes. + + See ``stream_arrow_schema``. A narrower bind hands on its rows as ``main`` gives + them (``RowsOnRead``), so its description is the declared Python schema's + (``arrow_types_declared`` is false): no second placement rule. + """ + if self._declared_form is not None: + return stream_arrow_schema(self, self.keys(), from_table=False) + return stream_arrow_schema(self, self._row_keys()) + + @property + def arrow_types_declared(self) -> bool: + """False for a narrower bind (see ``arrow_schema``), else as every source node.""" + if self._declared_form is not None: + return False + return super().arrow_types_declared + + def _rows_table( + self, + ) -> tuple[pa.Table, tuple[tuple[str, ...], tuple[str, ...]]] | None: + """The bound source's table and the keys of its rows (``keys_of_rows``). + + ``None`` for a narrower bind (its rows are given as the declared schema one by + one, ``_declared_rows``) and for a bound stream that is not a library source + kind whose table is its rows (``TABLE_IS_ROWS``): the node then hands on those + rows (``RowsOnRead``). + + Raises: + UnboundSourceError: When no concrete source is attached. + """ + if self._bound_source is None: + raise UnboundSourceError( + f"SourceJobNode '{self._name}' has no concrete source bound. " + "Call job.bind(sources={'': source}) before running." + ) + if self._declared_form is not None: + return None + if ( + not table_is_rows(self._bound_source) + or self._bound_source.data_context_key != self.data_context_key + ): + # Not a library source kind whose table is its rows (a side-effect or + # function pod stream, an operator's result, a raw stream, a poller), or + # one whose rows report another data context than the node's: its rows, + # as main iterated them (the edge table is built in the node's context). + return None + table = self._bound_source.as_table(columns=ZERO_ROW_INPUT_COLUMNS) + if not system_tags_as_rows_give(table.schema): + # System tags the rows would type otherwise (a narrow integer, a + # nullable field): the rows decide, as on main. + return None + return table, keys_of_rows(table, self._bound_source.keys()) + def iter_data(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: """Delegate to concrete source, or raise if unbound. diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index f930515f4..fbc698435 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -3,9 +3,15 @@ import asyncio import logging from abc import abstractmethod -from collections.abc import Collection, Iterator, Sequence +from collections.abc import ( + AsyncIterator, + Collection, + Iterable, + Iterator, + Sequence, +) from datetime import datetime, timezone -from typing import TYPE_CHECKING, Any, ClassVar, cast +from typing import TYPE_CHECKING, Any, ClassVar, NoReturn, cast import pyarrow as pa @@ -37,6 +43,7 @@ ZERO_ROW_INPUT_COLUMNS, StreamBase, check_head_size, + reads_as_its_class, short_stream_repr, typed_zero_row_input, typed_zero_row_table, @@ -66,6 +73,23 @@ from orcapod.protocols.hashing_protocols import SemanticHasherProtocol +class RowBuiltFormUnavailable(ValueError): + """F cannot be built from the whole table (``_row_built_form``). + + The one signal that a node's output must come from its rows instead: the caller + builds the rows (``StaticOutputOperatorPod._rows_to_table``, through + ``_raise_as_rows_do``), which raises the error a table built from rows raises, so + the run fails as it does when rows are handed on, with the same observer events. + """ + + +class SourceInfoTypesDisagree(RowBuiltFormUnavailable): + """Two rows give one source-info column different types (``_row_built_form``). + + A table built from such rows cannot be concatenated. + """ + + class StaticOutputOperatorPod(TraceableBase): """Abstract base class for pods whose core logic yields a static output stream. @@ -493,27 +517,81 @@ def _flag_by_values(table: pa.Table) -> pa.Table: # 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 _type_source_info_by_values(table: pa.Table) -> pa.Table: + """Type each source-info column from its tokens, as the rows of a table built from rows do. + + A step of F (``_row_built_form``) on the complete table, beside + ``_flag_by_values``. A row's ``Data`` types each source-info token from its + value (``arrow_utils.source_info_arrow_type``, the one rule): a string or + ``None`` as ``large_string``, a list as ``large_list`` of its first informative + element's type, so a list of ``None`` or of empty lists shows fewer levels than + its column may declare. The rows' tables are then concatenated, which needs + every row to give a column one type. This step gives each column that type, + built from the same values. A ``large_string`` column is every row's type + already and is left as it is. + + Args: + table: A table of user tags, system tags, data and source info, after the + per-slice steps (``streams.base.row_built_columns``). + + Returns: + The table with each source-info column of the type its tokens give. + + Raises: + SourceInfoTypesDisagree: If two rows give one source-info column different + types, where the rows' tables cannot be concatenated. The caller builds + the rows (``_rows_to_table``), which raises the error a table built from + rows raises. + """ + from orcapod.system_constants import constants + from orcapod.utils import arrow_utils + + columns = list(table.columns) + fields = list(table.schema) + changed = False + for index, field in enumerate(fields): + if not field.name.startswith(constants.SOURCE_PREFIX): + continue + if pa.types.is_large_string(field.type): + continue + values = table.column(index).to_pylist() + kinds = {arrow_utils.source_info_arrow_type(value) for value in values} + if len(kinds) != 1: + raise SourceInfoTypesDisagree(field.name) + (kind,) = kinds + if kind == field.type: + continue + columns[index] = pa.chunked_array([pa.array(values, type=kind)]) + fields[index] = pa.field(field.name, kind, nullable=field.nullable) + changed = True + 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), + ), + ) + @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. + F in the ITL-1347 spec: the same table, without making the rows. Two steps: + + - per slice (``streams.base.row_built_columns``), what each row decides on its + own: the columns, their order, their large types, and the provenance fields' + form (no system-tag field metadata, source-info lists of nullable items); + - on the complete table, what depends on the values of every row: each + source-info column's type, from its tokens (``_type_source_info_by_values``), + then the system-tag and source-info field flags (``_flag_by_values``). + + The equality with ``_rows_to_table`` is tested over every operator, source kind, + column role and raw-stream provenance shape (ITL-1347, L0-L2). Args: table: A table of user tags, system tags, data and source info, with rows. @@ -522,8 +600,47 @@ def _row_built_form( Returns: The table ``_rows_to_table`` would build from its rows. + + Raises: + RowBuiltFormUnavailable: If the whole table cannot be built: the rows' + tokens give a source-info column two types + (``SourceInfoTypesDisagree``), or an Arrow conversion fails. The node + then builds its rows (``_raise_as_rows_do``). """ - return StaticOutputOperatorPod._flag_by_values(row_built_columns(table, keys)) + try: + return StaticOutputOperatorPod._flag_by_values( + StaticOutputOperatorPod._type_source_info_by_values( + row_built_columns(table, keys) + ) + ) + except RowBuiltFormUnavailable: + raise + except pa.ArrowException as error: + # Values the whole table cannot be built from (a token the rows' own + # conversion refuses too): the rows decide, as on ``main``. + raise RowBuiltFormUnavailable(str(error)) from error + + @staticmethod + def _raise_as_rows_do( + rows: Iterable[tuple[TagProtocol, DataProtocol]], + error: RowBuiltFormUnavailable, + ) -> NoReturn: + """Build ``rows`` into a table to raise the error a table built from them raises. + + Called when ``_row_built_form`` finds rows whose source-info tokens cannot make + one table (``RowBuiltFormUnavailable``): the rows' own concatenation + (``_rows_to_table``) raises exactly what a run that hands rows on raises. + + Args: + rows: The rows of the table F was given, in order. + error: The disagreement F found, raised if the rows do concatenate. + + Raises: + pyarrow.ArrowInvalid: As ``_rows_to_table`` raises it. + RowBuiltFormUnavailable: ``error``, if the rows build after all. + """ + StaticOutputOperatorPod._rows_to_table(list(rows)) + raise error @staticmethod def _output_stream( @@ -547,19 +664,16 @@ def _output_stream( The output stream, with ``node``'s identity. """ if table.num_rows == 0: - stream = StaticOutputOperatorPod._materialize_upstream([], node) - else: - tag_keys, data_keys = keys - stream = StaticOutputOperatorPod._as_upstream_stream( - StaticOutputOperatorPod._row_built_form(table, keys), - tag_keys, - data_tag_names(tag_keys, data_keys), - node, - ) - # The one place a stream is marked as a complete, immutable output in the - # row-built form (ITL-1347): ``InputChannel.to_stream`` may give it as it is. - setattr(stream, ROW_BUILT_OUTPUT, True) - return stream + # No row: the zero-row input is derived where a successor reads it, as on + # main (``RowsOnRead``): nothing is prepared before then. + return rows_on_read([], 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: @@ -674,7 +788,23 @@ def _materialize_to_stream( Raises: ValueError: If ``rows`` is empty. """ - table, tag_keys, data_tags = StaticOutputOperatorPod._rows_to_table(rows) + return StaticOutputOperatorPod._stream_over_row_table( + StaticOutputOperatorPod._rows_to_table(rows) + ) + + @staticmethod + def _stream_over_row_table( + row_table: tuple[pa.Table, tuple[str, ...], tuple[str, ...]], + ) -> StreamProtocol: + """The stream ``_materialize_to_stream`` builds, over ``_rows_to_table``'s result. + + Args: + row_table: The table, user tag keys and data-tags ``_rows_to_table`` returns. + + Returns: + A stream over the table's rows, in order. + """ + table, tag_keys, data_tags = row_table # No ``source_info`` argument: the table's own ``_source_*`` columns # pass through, one value per row. return ArrowTableStream(table, tag_columns=tag_keys, data_tags=data_tags) @@ -721,6 +851,8 @@ def _materialize_upstream( ) typed = StaticOutputOperatorPod._zero_row_input(upstream) if typed is not None: + # A complete output with no row, in the row-built form (``ROW_BUILT_OUTPUT``). + setattr(typed, ROW_BUILT_OUTPUT, True) return typed # Build an empty table preserving declared field nullability. tag_schema, data_schema = upstream.output_schema( @@ -779,7 +911,7 @@ def _as_upstream_stream( # otherwise it would fall back to a root's schema-only hash and an # operator would name its system tags after that. A source's pipeline # hash is that schema-only hash already. - return _RowsOfStream( + stream: StreamProtocol = _RowsOfStream( table, tag_columns=tag_keys, pipeline_hash=upstream.pipeline_hash(), @@ -787,16 +919,23 @@ def _as_upstream_stream( upstreams=upstream.upstreams, data_context=context, ) - # No ``source_info`` argument: the table's own ``_source_*`` columns - # pass through, one value per row. - return ArrowTableStream( - table, - tag_columns=tag_keys, - data_tags=data_tags, - producer=upstream.producer, - upstreams=upstream.upstreams, - data_context=context, - ) + else: + # No ``source_info`` argument: the table's own ``_source_*`` columns + # pass through, one value per row. + stream = ArrowTableStream( + table, + tag_columns=tag_keys, + data_tags=data_tags, + producer=upstream.producer, + upstreams=upstream.upstreams, + data_context=context, + ) + # Every complete node output in the row-built form ends here (the rows' + # rebuild, F's output, a stored-table output) or, with no row, in + # ``_materialize_upstream``'s zero-row input: the places that mark it + # (ITL-1347): ``InputChannel.to_stream`` may give it as it is. + setattr(stream, ROW_BUILT_OUTPUT, True) + return stream @staticmethod def _materialize_input_stream( @@ -1051,12 +1190,18 @@ def transport_schema(stream: StreamProtocol) -> pa.Schema | None: 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). + rows (an unbound input slot, a source that has not polled yet, a description + whose types are undeclared: ``arrow_types_declared`` false). """ # 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 + if not getattr(stream, "arrow_types_declared", True): + # The rows decide the types (and the column order) of a description whose + # types are undeclared (a narrower bind, ``RowsOnRead``): the first batch sets + # them. + return None typed = StaticOutputOperatorPod._zero_row_input(stream) # pyright: ignore[reportPrivateUsage] # the zero-row form of an input if typed is None: return None @@ -1076,11 +1221,13 @@ def transport_schema(stream: StreamProtocol) -> pa.Schema | None: ROW_BUILT_OUTPUT = "_orcapod_row_built_output" -"""The attribute that marks a stream ``_output_stream`` built (ITL-1347). +"""The attribute that marks a complete node output in the row-built form (ITL-1347). -Set in that one place, never inferred from a class: such a stream is a complete, -immutable output already in the row-built form, so a consumer of its record batches -would rebuild exactly it, and ``InputChannel.to_stream`` may give it without reading. +Set where every such output is made (``_as_upstream_stream``, and the zero-row input +of ``_materialize_upstream``), never inferred from a class: such a stream is a +complete, immutable output already in the row-built form, so a consumer of its record +batches would rebuild exactly it, and ``InputChannel.to_stream`` may give it without +reading. """ @@ -1169,6 +1316,201 @@ def with_open_provenance_flags(batch: pa.RecordBatch) -> pa.RecordBatch: return pa.RecordBatch.from_arrays(batch.columns, schema=schema) +class RowsOnRead: + """A node's output held as its rows, its table built on first read (ITL-1347). + + The one rule for every route where building the output from the whole table is + not provably ``main``'s result (a narrower bind, a bound stream that is not a + library source kind, a whole-table build that is unavailable, an odd stored table, + a held node, a result with no row, a node whose output is still its rows): the node + hands on the rows ``main`` would hold, and the table is built from them by + ``main``'s own row path (``StaticOutputOperatorPod._materialize_upstream``) when + the table is first read. The sync orchestrator reads each input of a node before + running it (``at_edge``), where ``main`` rebuilt it; a stream nobody reads is never + built, as ``main`` never rebuilt a leaf's rows. + + It is a stream (``StreamProtocol``), structurally: every member of the protocol is + the built stream's, except those that read nothing. Its rows (``iter_data``, + iteration) are the rows it holds, unchanged, as ``main`` returned them. Its + description (``arrow_schema``) is the node's declared one and builds nothing + (``arrow_types_declared`` is false). Opening a channel builds nothing; the + channel's first read does. + """ + + # Not a stream the row-built form already made: a channel opened on it reads it. + _orcapod_row_built_output = False + + def __init__( + self, rows: Iterable[tuple[TagProtocol, DataProtocol]], node: StreamProtocol + ) -> None: + """Hold ``node``'s rows; nothing is built. + + Args: + rows: The rows ``main`` would hold, in order (read once, here). + node: The node (or stream) whose output they are. + """ + self._rows: list[tuple[TagProtocol, DataProtocol]] = list(rows) + self._node = node + self._stream: StreamProtocol | None = None + + def built(self) -> StreamProtocol: + """The stream, built from the rows on the first call (``main``'s row path).""" + if self._stream is None: + self._stream = StaticOutputOperatorPod._materialize_upstream( + self._rows, self._node + ) + return self._stream + + def release_built(self) -> None: + """Drop the built stream and keep only the rows. + + The sync orchestrator calls this on an output it retains once every successor + has read it: ``main`` held only the rows, so the retained output holds one + representation, and a later read builds the same table again from them. + """ + self._stream = None + + def iter_data(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: + """The rows it holds, unchanged (their meta columns included), as ``main``.""" + return iter(self._rows) + + def __iter__(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: + return self.iter_data() + + async def async_iter_data( + self, + ) -> AsyncIterator[tuple[TagProtocol, DataProtocol]]: + """The rows it holds, unchanged.""" + for row in self._rows: + yield row + + def arrow_schema(self) -> pa.Schema: + """The node's own description (``arrow_schema()``); builds nothing. + + The rows decide the Arrow types (``arrow_types_declared`` is false): the + description gives the node's names and declared types, with no guaranteed + order. + """ + describe = getattr(self._node, "arrow_schema", None) + if callable(describe): + return cast(pa.Schema, describe()) + from orcapod.core.streams.base import stream_arrow_schema + + return stream_arrow_schema(self._node, from_table=False) + + @property + def arrow_types_declared(self) -> bool: + """False: the rows decide the types (see ``arrow_schema``).""" + return False + + def open_channel(self) -> Any: + """Open an input channel on this stream; its first read builds the table.""" + from orcapod.core.streams.base import CompleteStreamFeed + from orcapod.core.streams.record_batch_input import InputChannel + + return InputChannel( + cast(StreamProtocol, cast(object, self)), + CompleteStreamFeed(cast(StreamProtocol, cast(object, self))), + ) + + # The members that tell what the output is without reading it: the node's, which + # the built stream takes too (``_as_upstream_stream``), or the built stream's once + # it is built. A protocol check (``isinstance``) reads them and builds nothing. + @property + def producer(self) -> Any: + return self._node.producer + + @property + def upstreams(self) -> tuple[StreamProtocol, ...]: + return self._node.upstreams + + @property + def data_context_key(self) -> str: + return self._node.data_context_key + + @property + def label(self) -> Any: + source = self._stream if self._stream is not None else self._node + return getattr(source, "label", None) + + @property + def last_modified(self) -> Any: + source = self._stream if self._stream is not None else self._node + return getattr(source, "last_modified", None) + + def __getattr__(self, name: str) -> Any: + # Every other member (``join``, ``as_polars_df``, ...) is the built stream's. + return getattr(self.built(), name) + + def __repr__(self) -> str: + return f"RowsOnRead({short_stream_repr(self._node)})" + + +def _stream_protocol_members() -> list[str]: + """The members ``StreamProtocol`` declares, its bases' included. + + What ``isinstance(x, StreamProtocol)`` looks for on the class: declaring each one + there lets ``RowsOnRead`` pass the check on every supported Python. + """ + names: set[str] = set() + protocol = cast(type, cast(object, StreamProtocol)) + for base in protocol.__mro__: + if base is object or base.__name__ in ("Protocol", "Generic"): + continue + names.update(name for name in vars(base) if not name.startswith("_")) + return sorted(names) + + +def _delegated(name: str) -> Any: + """A method of ``RowsOnRead`` that is the built stream's (``RowsOnRead.built``).""" + + def delegate(self: RowsOnRead, *args: Any, **kwargs: Any) -> Any: + return getattr(self.built(), name)(*args, **kwargs) + + delegate.__name__ = name + return delegate + + +for _name in _stream_protocol_members(): + if _name not in vars(RowsOnRead): + setattr(RowsOnRead, _name, _delegated(_name)) + + +def rows_on_read( + rows: Iterable[tuple[TagProtocol, DataProtocol]], node: StreamProtocol +) -> StreamProtocol: + """``RowsOnRead`` of ``rows`` as a stream (it delegates every member to the built one). + + Args: + rows: The rows ``main`` would hold, in order (read once, here). + node: The node (or stream) whose output they are. + + Returns: + The output, built from the rows when first read. + """ + # ``RowsOnRead`` stands for the stream it builds; the checker cannot see that + # through its delegation, so the cast goes through object. + return cast(StreamProtocol, cast(object, RowsOnRead(rows, node))) + + +def at_edge(stream: StreamProtocol) -> StreamProtocol: + """``stream`` as a node's input: a ``RowsOnRead`` output is built here. + + The sync orchestrator reads every input of a node before it runs the node, where + ``main`` rebuilt the rows of the node before it, so an error of that build surfaces + at the same point, after the same observer events. + + Args: + stream: An output a node handed on. + + Returns: + The stream to give the node. + """ + if isinstance(stream, RowsOnRead): + return stream.built() + return stream + + class _RowsOfStream(ArrowTableStream): """Rows standing in for the stream they came from, with its pipeline hash. @@ -1224,6 +1566,31 @@ def pipeline_hash( return self._input_pipeline_hash +def produced_stream(stream: StreamProtocol) -> StreamProtocol: + """Return the stream whose rows ``stream`` yields, through any depth of composition. + + An operator's result is a ``DynamicPodStream`` whose rows are those of the stream + its ``static_process`` returned, which may itself be another operator's + ``DynamicPodStream``: this follows them all to the stream that holds the rows + (ITL-1347). A wrapper is followed only when it reads as ``DynamicPodStream`` itself + (``reads_as_its_class``: its rows are then exactly those of the stream it holds); a + subclass or a wrapper with a member replaced on the instance is where the chain + stops, so the caller, which proves the stream it is given, takes the row path. + + Args: + stream: An operator's result, or any stream. + + Returns: + The stream that holds ``stream``'s rows, or the first wrapper not proven to + read through the stream it holds. + """ + while isinstance(stream, DynamicPodStream) and reads_as_its_class( + stream, DynamicPodStream + ): + stream = stream.produced_stream() + return stream + + class DynamicPodStream(StreamBase): """Recomputable stream wrapping a ``StaticOutputOperatorPod`` invocation.""" @@ -1452,6 +1819,18 @@ def iter_data( ) return self._cached_stream.iter_data() + def produced_stream(self) -> StreamProtocol: + """The stream the operator returned for the current inputs (computed if stale). + + Its rows are this stream's rows; ``produced_stream`` (the module function) + follows it through every ``DynamicPodStream`` to the stream that holds them. + """ + self._refresh() + assert self._cached_stream is not None, ( + "StreamProtocol has not been updated or is empty." + ) + return self._cached_stream + def head( self, n: int = 10, diff --git a/src/orcapod/core/record_batch_channels.py b/src/orcapod/core/record_batch_channels.py index 66527f145..d744f3c22 100644 --- a/src/orcapod/core/record_batch_channels.py +++ b/src/orcapod/core/record_batch_channels.py @@ -22,6 +22,7 @@ from orcapod.channels import ChannelClosed from orcapod.core.operators.static_output_pod import ( + SourceInfoTypesDisagree, stream_from_batches, transport_schema, ) @@ -150,6 +151,9 @@ def __init__( # batch's when the stream cannot say its Arrow types without rows. self._schema: pa.Schema | None = None self._schema_known = False + # Each source-info column's token type as the batches accepted so far settle it + # (``_settled_token_types``): a later batch must settle with it. + self._token_types: dict[str, pa.DataType] = {} self._changed = asyncio.Event() @property @@ -191,9 +195,10 @@ def _check_schema(self, batch: pa.RecordBatch) -> None: 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. + # stream's, in no guaranteed order (an undeclared description gives names + # only). A refused batch sets nothing. names = batch.schema.names - if names != row_built_names(names, self._stream.keys()): + if sorted(names) != sorted(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 " @@ -206,7 +211,9 @@ def _check_schema(self, batch: pa.RecordBatch) -> None: f"A record batch sent as {_named(self._stream)} does not have that " + f"stream's columns: {mismatch}." ) + token_types = _settled_token_types(batch, self._token_types) self._schema = schema + self._token_types = token_types async def send(self, batch: pa.RecordBatch) -> None: """Send one Arrow record batch of the stream's transport columns. @@ -355,6 +362,49 @@ def _named(stream: Any) -> str: # pyright: ignore[reportExplicitAny] # any str return repr(label) if label else repr(stream) +def _settled_token_types( + batch: pa.RecordBatch, accepted: dict[str, pa.DataType] +) -> dict[str, pa.DataType]: + """Each source-info column's token type, settled with the batches already accepted. + + A source-info column's type follows its tokens over the complete table + (``StaticOutputOperatorPod._type_source_info_by_values``): the description leaves it + open, but the channel's batches must settle together, or their result could not be + built. A batch whose tokens give a column a type the accepted batches do not is + refused at send, with the error the complete table would raise. + + Args: + batch: The batch being sent. + accepted: Each column's token type from the batches accepted so far. + + Returns: + The token types with this batch accepted. + + Raises: + SourceInfoTypesDisagree: If the batch's tokens give a column two types, or a + type other than the accepted batches'. + """ + settled = dict(accepted) + for field, column in zip(batch.schema, batch.columns, strict=True): + if not field.name.startswith(constants.SOURCE_PREFIX): + continue + kinds: set[pa.DataType] + if pa.types.is_large_string(field.type): + kinds = {pa.large_string()} + else: + kinds = { + arrow_utils.source_info_arrow_type(value) + for value in column.to_pylist() + } + if field.name in settled: + kinds.add(settled[field.name]) + if len(kinds) > 1: + raise SourceInfoTypesDisagree(field.name) + if kinds: + (settled[field.name],) = kinds + return settled + + 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``. @@ -364,7 +414,10 @@ def _schema_mismatch(declared: pa.Schema, batch: pa.RecordBatch) -> str | None: ``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``). + follows the values of the complete table (``_flag_by_values``). Nor is a + source-info column's type, which follows its tokens over the complete table + (``_type_source_info_by_values``): it must only be a token type (``large_string``, + or ``large_list`` of a token type). """ sent = batch.schema if declared.names != sent.names: @@ -372,6 +425,14 @@ def _schema_mismatch(declared: pa.Schema, batch: pa.RecordBatch) -> str | None: 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.name.startswith(constants.SOURCE_PREFIX): + if not _is_token_type(column.type): + return f"column {column.name!r} is {column.type}, not a token type" + 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 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( @@ -404,6 +465,18 @@ def _schema_mismatch(declared: pa.Schema, batch: pa.RecordBatch) -> str | None: return None +def _is_token_type(kind: pa.DataType) -> bool: + """Whether ``kind`` is a source-info token type: ``large_string``, or a list of one. + + The types ``arrow_utils.source_info_arrow_type`` gives a token. + """ + if pa.types.is_large_string(kind): + return True + if isinstance(kind, pa.LargeListType): + return _is_token_type(kind.value_type) # pyright: ignore[reportUnknownArgumentType, reportUnknownMemberType] + return False + + def _without_metadata(kind: pa.DataType) -> pa.DataType: """``kind`` with the field metadata of every nested field removed.""" if isinstance(kind, pa.LargeListType): diff --git a/src/orcapod/core/sources/arrow_table_source.py b/src/orcapod/core/sources/arrow_table_source.py index 460075915..5af85d506 100644 --- a/src/orcapod/core/sources/arrow_table_source.py +++ b/src/orcapod/core/sources/arrow_table_source.py @@ -89,6 +89,7 @@ class ArrowTableSource(RootSource): # The config type key; also the kind prefix of the default source id. SOURCE_KIND: ClassVar[str] = "arrow_table" + TABLE_IS_ROWS: ClassVar[bool] = True def __init__( self, diff --git a/src/orcapod/core/sources/base.py b/src/orcapod/core/sources/base.py index 1eed1f022..fdaa3cdd1 100644 --- a/src/orcapod/core/sources/base.py +++ b/src/orcapod/core/sources/base.py @@ -6,6 +6,7 @@ from orcapod.config import OrcapodConfig from orcapod.core.streams.base import ( StreamBase, + reads_as_its_class, typed_arrow_schemas, typed_zero_row_table, ) @@ -47,6 +48,26 @@ def saved_tag_only_columns(config: dict[str, Any]) -> bool | list[str]: return config["tag_only_columns"] +def table_is_rows(source: object) -> bool: + """Whether ``source``'s ``as_table()`` and ``iter_data()`` provably read the same data. + + Positive and exact (ITL-1347): true only when ``source``'s class itself declares + ``TABLE_IS_ROWS = True`` (a library source kind) and ``source`` reads as that class + (``reads_as_its_class``: its exact type, no member replaced on the instance). Any + subclass, a mixin, a replaced reader or a property that changes what the source + reads through is not proven, and a job node bound to it hands on its rows, as + ``main`` iterated them. + + Args: + source: The object bound to a source slot. + + Returns: + Whether F of its table is the table its rows give. + """ + kind = type(source) + return vars(kind).get("TABLE_IS_ROWS") is True and reads_as_its_class(source, kind) + + class RootSource(StreamBase): """Abstract base class for all root sources in Orcapod. @@ -93,6 +114,18 @@ class RootSource(StreamBase): identifier, config or stored path. """ + TABLE_IS_ROWS: ClassVar[bool] = False + """Whether ``as_table()`` and ``iter_data()`` read the same data, with no effect. + + Declared ``True`` only by the library source kinds that read one stream either way, + each on its own class: it is read for the exact class only, never inherited + (``table_is_rows``; ITL-1347). A job node bound to an instance of exactly such a + class hands on F of its table, which equals the table built from its rows. Any + other bound stream (a subclass, a side-effect or function pod stream, an operator's + result, a raw stream, a source kind that polls or delivers on a read) hands on its + rows (``RowsOnRead``), as ``main`` iterated them. + """ + def __init__( self, source_id: str | None = None, diff --git a/src/orcapod/core/sources/cached_source.py b/src/orcapod/core/sources/cached_source.py index 308a24fb6..a9bfd8f08 100644 --- a/src/orcapod/core/sources/cached_source.py +++ b/src/orcapod/core/sources/cached_source.py @@ -80,6 +80,7 @@ class CachedSource(RootSource): SOURCE_KIND: ClassVar[str] = "cached" """Config type key and default source-id kind of this source (one vocabulary).""" + TABLE_IS_ROWS: ClassVar[bool] = True HASH_COLUMN_NAME = "_record_hash" diff --git a/src/orcapod/core/sources/csv_source.py b/src/orcapod/core/sources/csv_source.py index cd780ab1e..9a0d99dcf 100644 --- a/src/orcapod/core/sources/csv_source.py +++ b/src/orcapod/core/sources/csv_source.py @@ -277,6 +277,7 @@ class CSVSource(RootSource): SOURCE_KIND: ClassVar[str] = "csv" """Config type key and default source-id kind of this source (one vocabulary).""" + TABLE_IS_ROWS: ClassVar[bool] = True TAKES_TAG_ONLY_COLUMNS: ClassVar[bool] = True def __init__( diff --git a/src/orcapod/core/sources/data_frame_source.py b/src/orcapod/core/sources/data_frame_source.py index 5db583ec2..f973c9647 100644 --- a/src/orcapod/core/sources/data_frame_source.py +++ b/src/orcapod/core/sources/data_frame_source.py @@ -44,6 +44,7 @@ class DataFrameSource(RootSource): # The config type key; also the kind prefix of the default source id. SOURCE_KIND: ClassVar[str] = "data_frame" + TABLE_IS_ROWS: ClassVar[bool] = True def __init__( self, diff --git a/src/orcapod/core/sources/db_table_source.py b/src/orcapod/core/sources/db_table_source.py index decdc09ea..a95c316f2 100644 --- a/src/orcapod/core/sources/db_table_source.py +++ b/src/orcapod/core/sources/db_table_source.py @@ -81,6 +81,7 @@ class DBTableSource(RootSource): SOURCE_KIND: ClassVar[str] = "db_table" """Config type key and default source-id kind of this source (one vocabulary).""" + TABLE_IS_ROWS: ClassVar[bool] = True TAKES_TAG_ONLY_COLUMNS: ClassVar[bool] = True def __init__( diff --git a/src/orcapod/core/sources/delta_table_source.py b/src/orcapod/core/sources/delta_table_source.py index ae623bdec..c744b3913 100644 --- a/src/orcapod/core/sources/delta_table_source.py +++ b/src/orcapod/core/sources/delta_table_source.py @@ -50,6 +50,7 @@ class DeltaTableSource(RootSource): SOURCE_KIND: ClassVar[str] = "delta_table" """Config type key and default source-id kind of this source (one vocabulary).""" + TABLE_IS_ROWS: ClassVar[bool] = True TAKES_TAG_ONLY_COLUMNS: ClassVar[bool] = True def __init__( diff --git a/src/orcapod/core/sources/derived_source.py b/src/orcapod/core/sources/derived_source.py index 1a7a58a93..1464e3f08 100644 --- a/src/orcapod/core/sources/derived_source.py +++ b/src/orcapod/core/sources/derived_source.py @@ -191,6 +191,7 @@ class DerivedSource(RootSource): # The config type key (names the class a saved config is rebuilt with) and # the kind prefix of the plain form's default source id. SOURCE_KIND: ClassVar[str] = "derived" + TABLE_IS_ROWS: ClassVar[bool] = True PROVISIONAL = True """Provisional in data context v1, both forms (ITL-1331, ``PROVISIONAL_SOURCES``).""" diff --git a/src/orcapod/core/sources/dict_source.py b/src/orcapod/core/sources/dict_source.py index bb99e1f9c..5a3935153 100644 --- a/src/orcapod/core/sources/dict_source.py +++ b/src/orcapod/core/sources/dict_source.py @@ -40,6 +40,7 @@ class DictSource(RootSource): # The config type key; also the kind prefix of the default source id. SOURCE_KIND: ClassVar[str] = "dict" + TABLE_IS_ROWS: ClassVar[bool] = True def __init__( self, diff --git a/src/orcapod/core/sources/list_source.py b/src/orcapod/core/sources/list_source.py index 48d8eae61..0b42e33ef 100644 --- a/src/orcapod/core/sources/list_source.py +++ b/src/orcapod/core/sources/list_source.py @@ -39,6 +39,7 @@ def _default_tag(element: Any, idx: int) -> dict[str, Any]: # The config type key; also the kind prefix of the default source id. SOURCE_KIND: ClassVar[str] = "list" + TABLE_IS_ROWS: ClassVar[bool] = True def __init__( self, diff --git a/src/orcapod/core/sources/postgresql_table_source.py b/src/orcapod/core/sources/postgresql_table_source.py index 0f12aa372..bc2b437b2 100644 --- a/src/orcapod/core/sources/postgresql_table_source.py +++ b/src/orcapod/core/sources/postgresql_table_source.py @@ -172,6 +172,7 @@ class PostgreSQLTableSource(DBTableSource): SOURCE_KIND: ClassVar[str] = "postgresql_table" """Config type key and default source-id kind of this source (one vocabulary).""" + TABLE_IS_ROWS: ClassVar[bool] = True def __init__( self, diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index 8b022ff87..c6c271657 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -375,6 +375,7 @@ class SpiralDBTableSource(RootSource): SOURCE_KIND: ClassVar[str] = "spiraldb_table" """Config type key and default source-id kind of this source (one vocabulary).""" + TABLE_IS_ROWS: ClassVar[bool] = True TAKES_TAG_ONLY_COLUMNS: ClassVar[bool] = True # Whether a notebook display reads the first rows. False shows the schema and the diff --git a/src/orcapod/core/sources/sqlite_table_source.py b/src/orcapod/core/sources/sqlite_table_source.py index f4e753553..9353ea07c 100644 --- a/src/orcapod/core/sources/sqlite_table_source.py +++ b/src/orcapod/core/sources/sqlite_table_source.py @@ -101,6 +101,7 @@ class SQLiteTableSource(DBTableSource): SOURCE_KIND: ClassVar[str] = "sqlite_table" """Config type key and default source-id kind of this source (one vocabulary).""" + TABLE_IS_ROWS: ClassVar[bool] = True def __init__( self, diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py index 3d941e5cb..d2ec40632 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -1,5 +1,7 @@ from __future__ import annotations +import functools +import inspect import logging from abc import abstractmethod from collections import deque @@ -22,6 +24,7 @@ import pyarrow as pa from orcapod.core.base import TraceableBase +from orcapod.core.data_tags import data_tag_names from orcapod.core.streams.record_batch_input import SOURCE_BATCH_ROWS, InputChannel from orcapod.core.streams.view import ( SCHEMA_NEEDS_POLL_NOTE, @@ -47,6 +50,59 @@ logger = logging.getLogger(__name__) +def reads_as_its_class(obj: object, cls: type) -> bool: + """Whether ``obj`` is exactly ``cls`` and reads only through ``cls``'s own members. + + Exact, never by inspection of what a subclass overrides: ``type(obj) is cls``, and + ``obj`` holds no attribute of its own that shadows a method or a property of + ``cls`` (an ``iter_data`` replaced on the instance). A ``functools.cached_property`` + keeps its value in the instance by design and is not a shadow. A subclass, however + small, is never ``cls`` here (ITL-1347). + + Args: + obj: The object to check. + cls: The class whose reading is proven. + + Returns: + Whether ``obj`` reads as ``cls`` does. + """ + if type(obj) is not cls: + return False + own = getattr(obj, "__dict__", None) + if not own: + return True + missing = object() + for name in own: + member = inspect.getattr_static(cls, name, missing) + if member is missing or isinstance(member, functools.cached_property): + continue + if callable(member) or hasattr(type(member), "__get__"): + return False + return True + + +def system_tags_as_rows_give(schema: pa.Schema) -> bool: + """Whether every system-tag field is what the row rebuild gives: non-null text. + + ``main`` rebuilt a node's table from its rows, whose system tags are typed from + their values: a ``large_string`` field, non-nullable (the only kind library code + makes). A whole table is its rows only when its system tags are already so; a + narrow integer, a nullable field or any other type is decided by the rows + (ITL-1347). + + Args: + schema: The table's schema. + + Returns: + Whether every system-tag field is non-nullable ``large_string``. + """ + return all( + field.type == pa.large_string() and not field.nullable + for field in schema + if field.name.startswith(constants.SYSTEM_TAG_PREFIX) + ) + + def schema_requires_io(stream: object, config: ColumnConfig) -> bool: """Whether reading ``stream``'s schema with ``config`` would read or poll a source. @@ -336,6 +392,121 @@ def row_built_names( return [*tag_keys, *system_tags, *data, *source_info] +def keys_of_rows( + table: pa.Table, keys: tuple[Sequence[str], Sequence[str]] +) -> tuple[tuple[str, ...], tuple[str, ...]]: + """Return the tag and data keys a source's rows have, given its table and ``keys()``. + + A source's rows come from a stream over its table (``ArrowTableStream``), whose rows + list their tags in the stream's tag order and their data with the data-tags first, + in tag order, then the other data columns in the table's order. A source whose + ``keys()`` states its declared order (a ``PollingSource`` whose fetched table has + another column order) has rows in the table's order all the same, as a table built + from its rows does (Codex on PR #485). + + Args: + table: The source's table, as its rows are read from it. + keys: The source's ``keys()``. + + Returns: + The tag keys, and the data keys in the order of the rows. + """ + tag_keys, data_keys = (tuple(keys[0]), tuple(keys[1])) + data_tags = data_tag_names(tag_keys, data_keys) + data = set(data_keys) - set(tag_keys) + in_table = tuple(name for name in table.column_names if name in data) + return tag_keys, (*data_tags, *in_table) + + +def stream_arrow_schema( + stream: object, + keys: tuple[Sequence[str], Sequence[str]] | None = None, + *, + from_table: bool = True, +) -> pa.Schema: + """Return ``stream``'s declared Arrow schema: what ``arrow_schema()`` answers (ITL-1347). + + The schema of the columns a job node passes on, without reading, computing or + polling a row: the stream's zero-row input (``typed_zero_row_input``, the Arrow types + its rows have) with the columns of F, in F's order + (``row_built_names``: user tags, system tags, data, source + info, data and source info in data-key order), with no context and no meta column. A + stream that cannot type itself without rows answers with its Python schema + converted by its data context (``arrow_types_declared`` is then false), and one + whose schema is known only by polling (nothing declared, nothing polled: + ``schema_requires_io``) answers with no column. Each + system-tag and source-info field is stated nullable: a table decides its flag from + its values (F's last step). A source-info field's type is stated as the declared + token type; a complete table decides it from its tokens + (``StaticOutputOperatorPod._type_source_info_by_values``), so consumers must not + rely on it. A ``null`` column keeps the zero-row ``null`` type; rows + carry ``large_string`` (ITL-1319). ITL-1307 later reads it from ``Schema`` instead, + here. + + Args: + stream: The stream, source or node. + keys: The tag and data keys of the stream's rows, when they differ from + ``keys()`` (a source slot gives its bound source's rows); default ``keys()``. + from_table: Take the stream's typed zero-row table (``typed_zero_row_input``); + ``False`` describes it from its declared Python schema only (a narrower + bind, whose rows ``main``'s row path places). + + Returns: + The declared Arrow schema. + """ + from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod + + typed = cast(StreamProtocol, stream) + given_keys = keys + table = typed_zero_row_input(stream) if from_table else None + if table is None and schema_requires_io(stream, ColumnConfig(system_tags=True)): + # Nothing declared, nothing polled (a poller with no declared schema): the + # columns are known only from rows, and a description never polls. No column, + # as a head says (``SCHEMA_NEEDS_POLL_NOTE``); ``arrow_types_declared`` is false. + return pa.schema([]) + if table is None: + # Only what the stream declares: asking for its source-info columns would make + # a source that has not polled poll (a description never computes, polls or + # reads). A source's tokens are strings, so each data column's source info is + # a string field. + tag_schema, data_schema = typed.output_schema(columns={"system_tags": True}) + stated = getattr(stream, "arrow_schemas", None) + if isinstance(stated, tuple): + # The Arrow types the stream declares itself (a slot): never a conversion + # of its Python types, which may have no Arrow type of their own. + tag_arrow, data_arrow = cast("tuple[pa.Schema, pa.Schema]", stated) + fields = [ + *tag_arrow, + *( + pa.field(name, pa.large_string()) + for name in tag_schema + if name not in tag_arrow.names + ), + *(f for f in data_arrow if f.name not in tag_arrow.names), + ] + table = pa.schema(fields).empty_table() + else: + converter = StaticOutputOperatorPod._upstream_context(typed).type_converter # pyright: ignore[reportPrivateUsage] # the one place that resolves an upstream's context + table = arrow_utils.make_empty_table( + {**tag_schema, **data_schema}, converter + ) + for name in data_schema: + table = table.append_column( + pa.field(f"{constants.SOURCE_PREFIX}{name}", pa.large_string()), + pa.array([], pa.large_string()), + ) + # The rows' keys: the data in the order of the stream's table (a poller that + # fetched its columns in another order than it declares lists them so). + keys = given_keys if given_keys is not None else keys_of_rows(table, typed.keys()) + names = row_built_names(table.column_names, keys) + schema = row_built_provenance(table.select(names)).schema + prefixes = (constants.SYSTEM_TAG_PREFIX, constants.SOURCE_PREFIX) + for index, field in enumerate(schema): + if field.name.startswith(prefixes): + schema = schema.set(index, field.with_nullable(True)) # pyright: ignore[reportUnknownMemberType] # stubs leave Field unparametrized + return schema + + class CompleteStreamFeed: """The record batches of a complete stream, read at one reader's own position. @@ -1121,6 +1292,18 @@ def index( return Index(column, i, out=out, fail_on_miss=fail_on_miss)(self, label=label) + def arrow_schema(self) -> pa.Schema: + """The Arrow schema of the columns this stream passes between job nodes. + + See ``stream_arrow_schema`` (ITL-1347): never reads, computes or polls a row. + """ + return stream_arrow_schema(self) + + @property + def arrow_types_declared(self) -> bool: + """Whether ``arrow_schema()`` holds the rows' own Arrow types (ITL-1089, ITL-1347).""" + return typed_zero_row_table(self) is not None + @abstractmethod def keys( self, diff --git a/src/orcapod/pipeline/async_orchestrator.py b/src/orcapod/pipeline/async_orchestrator.py index 55cd52d5e..9edd1614e 100644 --- a/src/orcapod/pipeline/async_orchestrator.py +++ b/src/orcapod/pipeline/async_orchestrator.py @@ -24,7 +24,7 @@ OrcapodDatabaseWriteError, TypeIdentityError, ) -from orcapod.pipeline.result import OrchestratorResult +from orcapod.pipeline.result import OrchestratorResult, StreamsOnRead from orcapod.utils.database_errors import keep_database_error from orcapod.protocols.node_protocols import ( is_function_node, @@ -39,7 +39,10 @@ from orcapod.channels import WritableChannel from orcapod.pipeline.dag import GraphProtocol - from orcapod.protocols.core_protocols import DataProtocol, TagProtocol + from orcapod.protocols.core_protocols import ( + DataProtocol, + TagProtocol, + ) from orcapod.protocols.observability_protocols import ExecutionObserverProtocol logger = logging.getLogger(__name__) @@ -177,8 +180,9 @@ async def run_async( pipeline_uri: Opaque URI string identifying this pipeline run. Forwarded verbatim to ``observer.on_run_start``. load_only: As for ``SyncPipelineOrchestrator.run``. - held_rows: As for ``SyncPipelineOrchestrator.run``: nodes not run, whose - rows feed their successors. + held_rows: Nodes not run, with the rows of their current run as the run's + plan took them (``RunPlan.held_rows``): those rows feed their + successors. The async path carries rows until ITL-1347 stage 5. Returns: OrchestratorResult with node outputs. @@ -205,6 +209,9 @@ async def _run_async( held_rows: Mapping[Any, list[tuple[TagProtocol, DataProtocol]]] | None = None, ) -> OrchestratorResult: """Core async logic: wire channels, launch tasks, collect results.""" + from orcapod.core.operators.static_output_pod import ( + rows_on_read, + ) from orcapod.pipeline.observer import NoOpObserver run_id = run_id or str(uuid.uuid4()) @@ -271,7 +278,11 @@ async def _run_async( for upstream in in_edges.get(node, []): tg.create_task(_drain(edge_readers[(upstream, node)])) _start_node( - tg, failed_nodes, node, _send_held(held_rows[node], writer) + tg, + failed_nodes, + node, + # The rows the plan took (ITL-1347, stage 5 changes it). + _send_held(held_rows[node], writer), ) elif is_source_node(node): _start_node( @@ -355,7 +366,11 @@ async def _run_async( tg.create_task(ch.reader.collect()) return OrchestratorResult( - node_outputs=collectors if materialize_results else {} + node_outputs=( + StreamsOnRead(collectors, rows_on_read) + if materialize_results + else {} + ) ) except ExceptionGroup as group: # A failed database read or write stops the run. Raise it on its own, as the diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index ea3f5570f..e2b84a81a 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -990,15 +990,28 @@ def run( counter = RunCountingObserver() effective_orchestrator = orchestrator or SyncPipelineOrchestrator() with self._executing(prepared, plan, commit_every_rows, load_only=load_only): - _ = effective_orchestrator.run( - plan.dag, - observer=_with_counter(observer, counter), - run_id=prepared.run_id, - pipeline_uri=prepared.pipeline_uri, - materialize_results=materialize_results, - load_only=load_only, - held_rows=plan.held_rows, - ) + if isinstance(effective_orchestrator, SyncPipelineOrchestrator): + # Held nodes give their output streams on the sync path (ITL-1347). + _ = effective_orchestrator.run( + plan.dag, + observer=_with_counter(observer, counter), + run_id=prepared.run_id, + pipeline_uri=prepared.pipeline_uri, + materialize_results=materialize_results, + load_only=load_only, + held=plan.held, + ) + else: + # The async path sends the rows the plan took (until stage 5). + _ = effective_orchestrator.run( + plan.dag, + observer=_with_counter(observer, counter), + run_id=prepared.run_id, + pipeline_uri=prepared.pipeline_uri, + materialize_results=materialize_results, + load_only=load_only, + held_rows=plan.held_rows, + ) summary = self._finish_run( prepared, counter, diff --git a/src/orcapod/pipeline/loaded_side_effects.py b/src/orcapod/pipeline/loaded_side_effects.py index fc8d6ca79..aa5182742 100644 --- a/src/orcapod/pipeline/loaded_side_effects.py +++ b/src/orcapod/pipeline/loaded_side_effects.py @@ -263,7 +263,7 @@ def execute( observer: ExecutionObserverProtocol | None = None, run_id: str | None = None, load_only: bool = False, - ) -> list[tuple[TagProtocol, DataProtocol]]: + ) -> StreamProtocol: """Pass every row on in a load-only run, as every side-effect job node does. Args: @@ -273,7 +273,8 @@ def execute( load_only: Must be true: the node can only pass rows on. Returns: - The rows of ``input_stream``, which the node then holds as loaded only. + The output stream of the rows of ``input_stream``, which the node then holds + as loaded only. Raises: RuntimeError: If ``load_only`` is false; nothing is read then. diff --git a/src/orcapod/pipeline/node_run.py b/src/orcapod/pipeline/node_run.py index 44ae96fb9..88a0e5ffe 100644 --- a/src/orcapod/pipeline/node_run.py +++ b/src/orcapod/pipeline/node_run.py @@ -14,7 +14,7 @@ from __future__ import annotations -from collections.abc import Iterable, Iterator, Sequence +from collections.abc import Iterable, Iterator, Mapping, Sequence from dataclasses import dataclass from typing import TYPE_CHECKING, Any @@ -25,6 +25,7 @@ run_node_summaries, ) from orcapod.pipeline.restrictions import restrictions_in_force, source_name +from orcapod.pipeline.result import StreamsOnRead from orcapod.utils.database_errors import flush_best_effort if TYPE_CHECKING: @@ -242,6 +243,13 @@ def check_sources(streams: Iterable[Any]) -> tuple[str, ...]: return tuple(unchecked) +def _rows_on_read(rows: Sequence[Any], node: Any) -> Any: + """A held node's output: its rows, built where a successor reads them (``RowsOnRead``).""" + from orcapod.core.operators.static_output_pod import rows_on_read + + return rows_on_read(rows, node) + + @dataclass(frozen=True) class RunPlan: """What a run does with each node of its graph (ITL-1095). @@ -249,18 +257,22 @@ class RunPlan: Attributes: dag: The nodes the run touches: those it runs, and the predecessors that feed them (a source slot is read; any other one is held). - held_rows: The rows of each held node of ``dag``: the rows of its current run, - or of a stream outside the job; they feed the nodes after it as if it had - just run. + held: The output stream of each held node of ``dag``: of its current run, or + of a stream outside the job; it feeds the nodes after it as if the node had + just run (the sync orchestrator). Built when read (``RowsOnRead``). + held_rows: The rows of each held node, as the plan took them; ``held`` is + built from them. The async orchestrator sends them (it carries rows until + ITL-1347 stage 5). to_run: The nodes the run runs, in dependency order. held_counts: Every node of the whole graph that holds a current run, with its row count, for the summary. """ dag: Any - held_rows: dict[Any, list[Any]] + held: Mapping[Any, Any] to_run: list[Any] held_counts: dict[Any, int] + held_rows: dict[Any, list[Any]] def plan_run(graph: Any, *, load_only: bool, outside: Sequence[Any] = ()) -> RunPlan: @@ -332,15 +344,22 @@ def is_source(node: Any) -> bool: for node in to_run: for upstream in graph.predecessors(node): dag.add_edge(upstream, node) + # A held node's output stream: what the sync orchestrator built from its rows for + # the nodes after it, exactly (ITL-1347, stage 2). held_rows = { node: list(node.iter_data()) for node in included if not any(node is r for r in to_run) and not is_source(node) } + # The rows main held, built where a successor reads them (``RowsOnRead``, + # ``at_edge``), never while planning; an async run reads only the rows. + # The plan keeps no output it handed out (``keep=False``): the orchestrator drops + # each once the node's successors ran. + held = StreamsOnRead(held_rows, _rows_on_read, keep=False) # Counted from what each node holds: iterating an operator's rows would build a # (Tag, Data) pair per row only to count them (ITL-1351). held_counts = {node: node.held_row_count() for node in current} - return RunPlan(dag, held_rows, to_run, held_counts) + return RunPlan(dag, held, to_run, held_counts, held_rows) def commit_run(databases: Sequence[ArrowDatabaseProtocol], ran: Sequence[Any]) -> None: @@ -425,7 +444,7 @@ def visit(node: Any) -> None: counter = RunCountingObserver() try: _ = SyncPipelineOrchestrator().run( - plan.dag, observer=counter, load_only=load_only, held_rows=plan.held_rows + plan.dag, observer=counter, load_only=load_only, held=plan.held ) except BaseException as run_error: if isinstance(run_error, Exception) and not load_only: diff --git a/src/orcapod/pipeline/result.py b/src/orcapod/pipeline/result.py index 94d158184..c0a95a4a7 100644 --- a/src/orcapod/pipeline/result.py +++ b/src/orcapod/pipeline/result.py @@ -2,11 +2,62 @@ from __future__ import annotations +from collections.abc import Callable, Iterator, Mapping from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any if TYPE_CHECKING: - from orcapod.protocols.core_protocols import DataProtocol, TagProtocol + from orcapod.protocols.core_protocols import StreamProtocol + + +class StreamsOnRead(Mapping[Any, "StreamProtocol"]): + """Each node's output stream, built from its rows when it is read. + + The async orchestrator collects each node's rows as they are sent; a node's stream + is built from them (``build``) when it is read. A run whose rows cannot make one + table (rows of a store written before ITL-928) therefore finishes, as it does on + ``main``, and only reading that node's output raises, as reading its rows as a + table does (ITL-1360). Membership, length and iteration never build a stream. A run + plan's held streams are built the same way, when the sync orchestrator reaches the + node, and are not kept (``keep=False``): the orchestrator drops each one once its + successors have run. + """ + + def __init__( + self, + rows: Mapping[Any, Any], + build: Callable[[Any, Any], "StreamProtocol"], + *, + keep: bool = True, + ) -> None: + """Hold each node's rows and how a stream is built from them. + + Args: + rows: Each node's rows. + build: Builds a node's stream from its rows, given ``(rows, node)``. + keep: Keep a stream once built, so a second read returns it again. + """ + self._rows = dict(rows) + self._build = build + self._keep = keep + self._built: dict[Any, StreamProtocol] = {} + + def __getitem__(self, node: Any) -> "StreamProtocol": + if node in self._built: + return self._built[node] + stream = self._build(self._rows[node], node) + if self._keep: + self._built[node] = stream + return stream + + def __contains__(self, node: object) -> bool: + return node in self._rows + + def __iter__(self) -> Iterator[Any]: + return iter(self._rows) + + def __len__(self) -> int: + return len(self._rows) @dataclass @@ -14,10 +65,10 @@ class OrchestratorResult: """Result of an orchestrator run. Attributes: - node_outputs: Mapping from graph node to its computed (tag, data) - pairs. Empty when ``materialize_results=False``. + node_outputs: Mapping from graph node to its output stream (backed by an + Arrow table; ``as_table()`` gives it, ``iter_data()`` its rows). Empty when + ``materialize_results=False``. The async orchestrator builds each stream + when it is first read (``StreamsOnRead``). """ - node_outputs: dict[Any, list[tuple["TagProtocol", "DataProtocol"]]] = field( - default_factory=dict - ) + node_outputs: Mapping[Any, "StreamProtocol"] = field(default_factory=dict) diff --git a/src/orcapod/pipeline/sync_orchestrator.py b/src/orcapod/pipeline/sync_orchestrator.py index bf9708a39..3286caab7 100644 --- a/src/orcapod/pipeline/sync_orchestrator.py +++ b/src/orcapod/pipeline/sync_orchestrator.py @@ -26,7 +26,7 @@ from orcapod.pipeline.dag import GraphProtocol from orcapod.protocols.observability_protocols import ExecutionObserverProtocol - from orcapod.protocols.core_protocols import DataProtocol, TagProtocol + from orcapod.protocols.core_protocols import StreamProtocol logger = logging.getLogger(__name__) @@ -38,8 +38,9 @@ class SyncPipelineOrchestrator: to ``node.execute(observer=...)`` which owns all per-data logic, cache lookups, and observer hooks internally. - The orchestrator is responsible only for topological ordering, - buffer management, and stream materialization between nodes. + The orchestrator is responsible only for topological ordering and for handing + each node's output stream to its successors: a node's ``execute`` returns the + stream every successor reads (ITL-1347, stage 2). """ def __init__( @@ -57,16 +58,16 @@ def run( run_id: str | None = None, pipeline_uri: str = "", load_only: bool = False, - held_rows: Mapping[Any, list[tuple[TagProtocol, DataProtocol]]] | None = None, + held: Mapping[Any, StreamProtocol] | None = None, ) -> OrchestratorResult: """Execute the node graph synchronously. Args: graph: A ``GraphProtocol`` DAG with GraphNode objects as vertices. observer: Optional execution observer forwarded to nodes. - materialize_results: If True, keep all node outputs in memory - and return them. If False, discard buffers after downstream - consumption (only DB-persisted results survive). + materialize_results: If True, keep every node's output stream and return + them. If False, drop each one once its successors have run (only + DB-persisted results survive). run_id: Optional run identifier. If not provided, a UUID is generated automatically. pipeline_uri: Opaque URI string identifying this pipeline run @@ -76,13 +77,13 @@ def run( (ITL-1095): function nodes load their inputs' stored results and skip the others, operators run without storing, and a side-effect node passes its rows on and delivers nothing. - held_rows: Nodes of ``graph`` that are not run: each one's rows (the rows - of its current run, or of a stream outside the job) feed its - successors as if it had just run. Used by ``node.run()``, which runs - only the nodes it depends on that hold no current run (ITL-1095). + held: Nodes of ``graph`` that are not run: each one's output stream (of + its current run, or of a stream outside the job) feeds its successors + as if it had just run. Used by ``node.run()``, which runs only the + nodes it depends on that hold no current run (ITL-1095). Returns: - OrchestratorResult with node outputs. + OrchestratorResult with each node's output stream. """ from orcapod.pipeline.observer import NoOpObserver @@ -94,23 +95,29 @@ def run( current: Any = None try: topo_order = list(graph.topological_sort()) - buffers: dict[Any, list[tuple[TagProtocol, DataProtocol]]] = {} + # Taken before any node runs: an observer may rebind a source, which + # changes how the graph finds that node afterwards. + neighbours = ( + { + id(n): (list(graph.predecessors(n)), list(graph.successors(n))) + for n in topo_order + } + if materialize_results + else {} + ) + outputs: dict[Any, StreamProtocol] = {} processed: set[Any] = set() - held = held_rows if held_rows is not None else {} + held_streams = held if held is not None else {} for node in topo_order: current = node - if node in held: - buffers[node] = list(held[node]) + if node in held_streams: + outputs[node] = held_streams[node] elif is_source_node(node): - buffers[node] = node.execute(observer=effective_observer) + outputs[node] = node.execute(observer=effective_observer) elif is_function_node(node) or is_side_effect_function_node(node): - upstream_buf = self._gather_upstream(node, graph, buffers) - upstream_node = list(graph.predecessors(node))[0] - input_stream = self._materialize_as_stream( - upstream_buf, upstream_node - ) - buffers[node] = node.execute( + input_stream = self._single_input(node, graph, outputs) + outputs[node] = node.execute( input_stream, observer=effective_observer, error_policy=self._error_policy, @@ -118,22 +125,14 @@ def run( load_only=load_only, ) elif is_operator_node(node): - upstream_buffers = self._gather_upstream_multi(node, graph, buffers) - input_streams = [ - self._materialize_as_stream(buf, upstream_node) - for buf, upstream_node in upstream_buffers - ] - buffers[node] = node.execute( + input_streams = self._ordered_inputs(node, graph, outputs) + outputs[node] = node.execute( *input_streams, observer=effective_observer, load_only=load_only ) elif is_side_effect_node(node): - upstream_buf = self._gather_upstream(node, graph, buffers) - upstream_node = list(graph.predecessors(node))[0] - input_stream = self._materialize_as_stream( - upstream_buf, upstream_node - ) + input_stream = self._single_input(node, graph, outputs) # In a load-only run the node passes its rows on and delivers nothing. - buffers[node] = node.execute( + outputs[node] = node.execute( input_stream, observer=effective_observer, run_id=run_id, @@ -147,12 +146,14 @@ def run( processed.add(node) if not materialize_results: - self._gc_buffers(node, graph, buffers, processed) + self._gc_outputs(node, graph, outputs, processed) + else: + self._release_built_inputs(node, neighbours, outputs, processed) if not materialize_results: - buffers.clear() + outputs.clear() - return OrchestratorResult(node_outputs=buffers) + return OrchestratorResult(node_outputs=outputs) except OrcapodDatabaseError as exc: # Name the node the failure belongs to, if the raising site did not. if current is not None: @@ -170,70 +171,80 @@ def run( effective_observer.on_run_end(run_id) @staticmethod - def _gather_upstream( + def _single_input( node: Any, graph: "GraphProtocol[Any]", - buffers: dict[Any, list[tuple[Any, Any]]], - ) -> list[tuple[Any, Any]]: - """Gather a single upstream buffer (for function nodes).""" + outputs: dict[Any, StreamProtocol], + ) -> StreamProtocol: + """The output stream of a node's one predecessor (function and side-effect nodes).""" predecessors = list(graph.predecessors(node)) if len(predecessors) != 1: raise ValueError( f"FunctionNode expects exactly 1 upstream, got {len(predecessors)}" ) - return buffers[predecessors[0]] + from orcapod.core.operators.static_output_pod import at_edge + + return at_edge(outputs[predecessors[0]]) @staticmethod - def _gather_upstream_multi( + def _ordered_inputs( node: Any, graph: "GraphProtocol[Any]", - buffers: dict[Any, list[tuple[Any, Any]]], - ) -> list[tuple[list[tuple[Any, Any]], Any]]: - """Gather multiple upstream buffers with their nodes (for operators). - - Returns list of (buffer, upstream_node) tuples preserving the - order that matches the operator's input_streams order. - """ + outputs: dict[Any, StreamProtocol], + ) -> list[StreamProtocol]: + """The output streams of an operator node's predecessors, in ``node.upstreams`` order.""" predecessors = list(graph.predecessors(node)) upstream_order = {id(upstream): i for i, upstream in enumerate(node.upstreams)} sorted_preds = sorted( predecessors, key=lambda p: upstream_order.get(id(p), 0), ) - return [(buffers[p], p) for p in sorted_preds] + from orcapod.core.operators.static_output_pod import at_edge + + return [at_edge(outputs[p]) for p in sorted_preds] @staticmethod - def _materialize_as_stream(buf: list[tuple[Any, Any]], upstream_node: Any) -> Any: - """Wrap a (tag, data) buffer as the upstream node's stream. + def _release_built_inputs( + current_node: Any, + neighbours: dict[int, tuple[list[Any], list[Any]]], + outputs: dict[Any, StreamProtocol], + processed: set[Any], + ) -> None: + """Keep a retained output read by all its successors as its rows only. - ``StaticOutputOperatorPod._materialize_upstream`` builds it, the one - definition an async operator node shares when it rebuilds its inputs - for a run that produced no row. + A ``RowsOnRead`` output builds its table at each successor's edge; once every + successor has run, the retained output drops the built stream and keeps the + rows, which is all ``main`` retained (ITL-1347). A later read builds it again. Args: - buf: List of (tag, data) tuples. - upstream_node: The node that produced this buffer. - - Returns: - An ArrowTableStream. + current_node: The node that just ran. + neighbours: Each node's predecessors and successors, by ``id``, taken + before the run. + outputs: The retained outputs. + processed: The nodes that ran. """ - from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod + from orcapod.core.operators.static_output_pod import RowsOnRead - return StaticOutputOperatorPod._materialize_upstream(buf, upstream_node) + for pred in neighbours[id(current_node)][0]: + output = outputs.get(pred) + if isinstance(output, RowsOnRead) and all( + succ in processed for succ in neighbours[id(pred)][1] + ): + output.release_built() @staticmethod - def _gc_buffers( + def _gc_outputs( current_node: Any, graph: "GraphProtocol[Any]", - buffers: dict[Any, list[tuple[Any, Any]]], + outputs: dict[Any, StreamProtocol], processed: set[Any], ) -> None: - """Discard buffers no longer needed by any unprocessed downstream.""" + """Drop output streams no unprocessed successor still needs.""" for pred in graph.predecessors(current_node): - if pred not in buffers: + if pred not in outputs: continue all_successors_done = all( succ in processed for succ in graph.successors(pred) ) if all_successors_done: - del buffers[pred] + del outputs[pred] diff --git a/src/orcapod/protocols/core_protocols/streams.py b/src/orcapod/protocols/core_protocols/streams.py index 7cb868e90..c5d4e9d34 100644 --- a/src/orcapod/protocols/core_protocols/streams.py +++ b/src/orcapod/protocols/core_protocols/streams.py @@ -172,6 +172,41 @@ def output_schema( """ ... + def arrow_schema(self) -> "pa.Schema": + """The Arrow schema of the columns the stream passes between job nodes. + + The user tags, system tags, data and source-info columns, in row order (user + tags, system tags, data, source info; data and source info in data-key order), + with the Arrow types, nullability and field metadata of the rows; no context and + no meta column (ITL-1347). Known without reading, computing or polling a row. + Three properties are decided by the values of a complete table, not by the + description: whether a system-tag or source-info field is nullable (stated + nullable here), and a source-info field's type (stated as the declared token + type; a list of ``None`` or of empty lists shows fewer levels, so consumers must + not rely on it). And a ``null`` column keeps the ``null`` type a zero-row table + has (rows carry ``large_string``; ITL-1319). + + Returns: + The declared Arrow schema. + """ + ... + + @property + def arrow_types_declared(self) -> bool: + """Whether ``arrow_schema()`` holds the rows' own Arrow types. + + ``False`` when the stream cannot type itself without rows (an unbound slot, a + ``PollingSource`` never polled; ITL-1089), or its rows decide its types (a + narrower bind, an output held as its rows). Its schema is then the best + description available without reading a row: a slot's or source's explicit + Arrow declaration when it states one, otherwise its Python schema converted; + a source whose schema is known only by polling, and which has not polled, has + an empty schema. So a ``False`` description is not guaranteed to hold the + stream's column names, and the names it holds come in no guaranteed order; no + consumer relies on either (ITL-1347). + """ + ... + def iter_data(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: """ Generates explicit iterator over (tag, data) pairs in the stream. diff --git a/src/orcapod/protocols/node_protocols.py b/src/orcapod/protocols/node_protocols.py index 499c74b53..cf1080c53 100644 --- a/src/orcapod/protocols/node_protocols.py +++ b/src/orcapod/protocols/node_protocols.py @@ -46,7 +46,7 @@ def execute( self, *, observer: ExecutionObserverProtocol | None = None, - ) -> list[tuple[TagProtocol, DataProtocol]]: ... + ) -> StreamProtocol: ... async def async_execute( self, @@ -89,7 +89,7 @@ def execute( error_policy: Literal["continue", "fail_fast"] = "continue", run_id: str | None = None, load_only: bool = False, - ) -> list[tuple[TagProtocol, DataProtocol]]: ... + ) -> StreamProtocol: ... async def async_execute( self, @@ -129,7 +129,7 @@ def execute( *input_streams: StreamProtocol, observer: ExecutionObserverProtocol | None = None, load_only: bool = False, - ) -> list[tuple[TagProtocol, DataProtocol]]: ... + ) -> StreamProtocol: ... async def async_execute( self, @@ -162,7 +162,7 @@ def execute( observer: "ExecutionObserverProtocol | None" = None, run_id: str | None = None, load_only: bool = False, - ) -> "list[tuple[TagProtocol, DataProtocol]]": ... + ) -> "StreamProtocol": ... async def async_execute( self, diff --git a/src/orcapod/side_effects.py b/src/orcapod/side_effects.py index de75192ef..071aa82ac 100644 --- a/src/orcapod/side_effects.py +++ b/src/orcapod/side_effects.py @@ -13,14 +13,18 @@ import datetime import logging from collections.abc import Callable, Collection, Iterator, Sequence -from typing import TYPE_CHECKING, Any, Literal +from typing import TYPE_CHECKING, Any, Literal, cast import pyarrow as pa from typing_extensions import override from orcapod.core.base import TraceableBase from orcapod.core.nodes.staleness import RunHoldingNode -from orcapod.core.nodes.function_node import _build_record_id_preimage, run_job_node +from orcapod.core.nodes.function_node import ( + _build_record_id_preimage, + rows_as_output_stream, + run_job_node, +) from orcapod.core.streams.base import ( StreamBase, check_head_size, @@ -1225,7 +1229,7 @@ def execute( observer: ExecutionObserverProtocol | None = None, run_id: str | None = None, load_only: bool = False, - ) -> list[tuple[TagProtocol, DataProtocol]]: + ) -> StreamProtocol: """Execute side-effect delivery for all rows in ``input_stream``. Args: @@ -1239,7 +1243,10 @@ def execute( delivering (ITL-1091). A run that raises leaves the node with no rows. Returns: - List of ``(tag, data)`` tuples — the pass-through rows. + The node's output stream: the rows it passed on, as the table + ``_rows_to_table`` builds from them, with this node's identity + (``StaticOutputOperatorPod._materialize_upstream``). The sync orchestrator + hands it to every successor (ITL-1347, stage 2). Raises: SideEffectLogDataContextError: If the invocation log holds deliveries @@ -1254,7 +1261,7 @@ def execute( self.clear_cache() raise self._hold(rows, load_only=True) - return rows + return self._output_stream(rows) try: results = self._deliver_rows(input_stream, run_id=run_id) except BaseException: @@ -1263,7 +1270,20 @@ def execute( self.clear_cache() raise self._hold(results) - return results + return self._output_stream(results) + + def _output_stream( + self, rows: list[tuple[TagProtocol, DataProtocol]] + ) -> StreamProtocol: + """The output stream of a run that passed ``rows`` on. + + What the sync orchestrator built from a node's rows for its successors + (``StaticOutputOperatorPod._materialize_upstream``, through + ``rows_as_output_stream``). + """ + # A side-effect job node is a ``StreamBase``; the checker cannot match its + # mixin members against ``StreamProtocol``, so the cast goes through object. + return rows_as_output_stream(rows, cast("StreamProtocol", cast(object, self))) def _deliver_rows( self, input_stream: StreamProtocol, *, run_id: str | None diff --git a/tests/test_channels/test_record_batch_channels.py b/tests/test_channels/test_record_batch_channels.py index 16d16b44d..e2836eddf 100644 --- a/tests/test_channels/test_record_batch_channels.py +++ b/tests/test_channels/test_record_batch_channels.py @@ -175,7 +175,7 @@ def test_a_bound_source_node_sends_its_rows_in_their_own_column_order() -> None: ) node = SourceJobNode.from_stream(stream, name="ordered") assert node.keys()[0] != stream.keys()[0] # the slot's order is another - rows = node.execute() + rows = list(node.iter_data()) # the rows execute() returned before ITL-1347 stage 2 expected = StaticOutputOperatorPod._rows_to_table(rows)[0] batches = run(node.open_channel().collect) assert pa.Table.from_batches(batches).schema.names == expected.schema.names @@ -240,7 +240,9 @@ def test_a_source_nodes_channel_carries_its_execute_output( if bind == "transparent" else _declared_node(source) ) - expected = StaticOutputOperatorPod._materialize_upstream(node.execute(), node) # pyright: ignore[reportPrivateUsage] # the job's rebuild of the rows + expected = StaticOutputOperatorPod._materialize_upstream( + list(node.iter_data()), node + ) # pyright: ignore[reportPrivateUsage] # the job's rebuild of the rows wanted = expected.as_table(columns=ALL) assert any( name.startswith("_source_") and name.removeprefix("_source_") in ("j", "k") @@ -267,7 +269,9 @@ def test_a_rebind_before_the_first_read_is_read_whole() -> None: node = SourceJobNode.from_stream(_keyed_source(()), name="keyed") channel = node.open_channel() node.bound_source = _keyed_source((), source_id="other", offset=10) - expected = StaticOutputOperatorPod._materialize_upstream(node.execute(), node) # pyright: ignore[reportPrivateUsage] # the job's rebuild of the rows + expected = StaticOutputOperatorPod._materialize_upstream( + list(node.iter_data()), node + ) # pyright: ignore[reportPrivateUsage] # the job's rebuild of the rows batches = run(channel.collect) assert same(pa.Table.from_batches(batches), R(expected)) @@ -1903,3 +1907,50 @@ def test_stream_from_batches_is_the_one_conversion() -> None: 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 + + +def test_a_batch_with_a_duplicate_column_is_refused() -> None: + """Without Arrow types the names are compared as a multiset: a duplicate is refused + (Codex on PR #485, round 5).""" + table = source().as_table(columns=ALL) + stream = _UntypedStream( + table, tag_columns=["subject", "trial"], data_tags=["trial"] + ) + (batch,) = batches_of(stream) + name = next(n for n in batch.schema.names if not n.startswith(("_", "subject"))) + doubled = batch.append_column(batch.schema.field(name), batch.column(name)) + + async def write() -> None: + output = OutputChannel(stream) + await output.send(doubled) + + with pytest.raises(ValueError, match="the stream's keys are"): + run(write) + + +def test_a_batch_whose_tokens_cannot_settle_with_accepted_ones_is_refused() -> None: + """A second batch with list tokens where the first had string tokens is refused at + send, with the error the complete table would raise (Codex on PR #485, round 5).""" + from orcapod.core.operators.static_output_pod import SourceInfoTypesDisagree + + stream = source() + (batch,) = batches_of(stream) + column = next(n for n in batch.schema.names if n.startswith("_source_")) + position = batch.schema.get_field_index(column) + tokens = pa.large_list(pa.large_string()) + listed = pa.RecordBatch.from_arrays( + [ + *batch.columns[:position], + pa.array([["t"]] * batch.num_rows, tokens), + *batch.columns[position + 1 :], + ], + schema=batch.schema.set(position, pa.field(column, tokens, nullable=True)), + ) + + async def write() -> None: + output = OutputChannel(stream) + await output.send(batch) + await output.send(listed) + + with pytest.raises(SourceInfoTypesDisagree, match=column): + run(write) diff --git a/tests/test_core/function_pod/test_ephemeral_result.py b/tests/test_core/function_pod/test_ephemeral_result.py index 799c83bc1..2d0e6cfd1 100644 --- a/tests/test_core/function_pod/test_ephemeral_result.py +++ b/tests/test_core/function_pod/test_ephemeral_result.py @@ -152,7 +152,7 @@ def test_is_ephemeral_false_written_to_pipeline_db(self): stream = _make_stream([{"id": 0, "x": 10}]) node, db = _make_node(stream) - results = node.execute(stream) + results = list(node.execute(stream).iter_data()) assert len(results) == 1 all_records = db.get_all_records(node._versioned_pipeline_path) @@ -171,7 +171,7 @@ def test_is_ephemeral_true_written_to_pipeline_db(self): node, _ = _make_node(stream, pipeline_db=pipeline_db, is_result_ephemeral=True) node.set_ephemeral_database(ephemeral_store) - results = node.execute(stream) + results = list(node.execute(stream).iter_data()) assert len(results) == 1 all_records = pipeline_db.get_all_records(node._versioned_pipeline_path) @@ -191,7 +191,7 @@ def test_ephemeral_false_unchanged(self): """is_result_ephemeral=False: execute() behaves identically to current implementation.""" stream = _make_stream([{"id": 0, "x": 10}, {"id": 1, "x": 20}]) node, _ = _make_node(stream) - results = node.execute(stream) + results = list(node.execute(stream).iter_data()) assert len(results) == 2 vals = {tag.as_dict()["id"]: data.as_dict()["result"] for tag, data in results} assert vals == {0: 20, 1: 40} @@ -211,7 +211,7 @@ def test_ephemeral_result_written_to_memory_not_persistent_db(self): ) node.node_config = NodeConfig(is_result_ephemeral=True) node.set_ephemeral_database(ephemeral_store) - results = node.execute(stream) + results = list(node.execute(stream).iter_data()) assert len(results) == 1 assert results[0][1].as_dict()["result"] == 20 @@ -311,7 +311,7 @@ def counting_double(x: int) -> int: node.set_ephemeral_database(InMemoryArrowDatabase()) # Run 1: writes to persistent DB (is_result_ephemeral=False) - results = node.execute(stream) + results = list(node.execute(stream).iter_data()) assert len(results) == 1 assert results[0][1].as_dict()["result"] == 20 assert call_count["n"] == 1 @@ -320,7 +320,7 @@ def counting_double(x: int) -> int: node._cached_output_datas.clear() # Run 2: Phase 1 must find persistent result — no recompute - results2 = node.execute(stream) + results2 = list(node.execute(stream).iter_data()) assert len(results2) == 1 assert results2[0][1].as_dict()["result"] == 20 assert call_count["n"] == 1 # NOT recomputed @@ -374,7 +374,7 @@ def counting_double(x: int) -> int: node_both.set_ephemeral_database(ephemeral_store) node_both._cached_output_datas.clear() - results = node_both.execute(stream_both) + results = list(node_both.execute(stream_both).iter_data()) assert len(results) == 2 vals = {tag.as_dict()["id"]: data.as_dict()["result"] for tag, data in results} assert vals == {0: 20, 1: 40} @@ -482,7 +482,7 @@ def counting_double(x: int) -> int: # The anti-join should exclude the ephemeral row (entry_id clash with persistent row), # returning only the persistent result. No recomputation. - results = node.execute(stream) + results = list(node.execute(stream).iter_data()) assert len(results) == 1 assert results[0][1].as_dict()["result"] == 20 # call_count did not increase — persistent hit from anti-join merge, no recomputation @@ -524,7 +524,7 @@ def test_ephemeral_only_node(self): ) node.node_config = NodeConfig(is_result_ephemeral=True) node.set_ephemeral_database(ephemeral_store) - results = node.execute(stream) + results = list(node.execute(stream).iter_data()) assert len(results) == 1 assert results[0][1].as_dict()["result"] == 20 @@ -740,7 +740,7 @@ def test_persistent_miss_warns_and_recomputes(self, caplog): with caplog.at_level( logging.WARNING, logger="orcapod.core.nodes.function_node" ): - results = node2.execute(stream) + results = list(node2.execute(stream).iter_data()) assert len(results) == 1 # recomputed assert any( @@ -818,7 +818,7 @@ def test_ephemeral_only_node_no_persistent_db(self): ) node.node_config = NodeConfig(is_result_ephemeral=True) node.set_ephemeral_database(ephemeral_store) - results = node.execute(stream) + results = list(node.execute(stream).iter_data()) assert len(results) == 2 vals = {tag.as_dict()["id"]: data.as_dict()["result"] for tag, data in results} @@ -1021,7 +1021,7 @@ def test_legacy_records_without_ephemeral_col_treated_as_persistent(self): pipeline_database=pipeline_db, result_database=result_db, ) - results = node2.execute(stream) + results = list(node2.execute(stream).iter_data()) # Result must be served (from result DB cache or recomputed) assert len(results) == 1 @@ -1082,7 +1082,7 @@ def counting_double(x: int) -> int: result_database=result_db, ) count_before_session2 = call_count["n"] - results = node2.execute(stream) + results = list(node2.execute(stream).iter_data()) assert len(results) == 1 assert results[0][1].as_dict()["result"] == 20 assert call_count["n"] == count_before_session2 # NOT recomputed diff --git a/tests/test_core/function_pod/test_function_node_arrow_types.py b/tests/test_core/function_pod/test_function_node_arrow_types.py index 3dc4e70e8..195d72133 100644 --- a/tests/test_core/function_pod/test_function_node_arrow_types.py +++ b/tests/test_core/function_pod/test_function_node_arrow_types.py @@ -303,7 +303,8 @@ def test_new_rows_over_a_store_written_before_the_fix_raise_naming_the_column( A Delta database written before ITL-928 gives a ``uint32`` tag back as ``int32``: rows served from it and rows computed now disagree, and the node says so instead - of picking a type. Such a database must be rebuilt. + of picking a type. Such a database must be rebuilt. A leaf's run completes (its + rows are never built into one table, ``RowsOnRead``), as on ``main``. """ _build(DeltaTableDatabase(tmp_path), _source_table("uint32").slice(0, 2)).run() _as_written_before_the_fix(tmp_path) @@ -319,6 +320,30 @@ def test_new_rows_over_a_store_written_before_the_fix_raise_naming_the_column( assert "uint32" in message +def test_rows_over_a_store_written_before_the_fix_fail_at_the_successor( + tmp_path: pathlib.Path, +) -> None: + """With a successor, the run fails where the rows are built for it, as on ``main``. + + The node's rows are built into one table where its successor reads them + (``at_edge``): the concatenation raises ``ArrowInvalid`` there, as ``main``'s row + rebuild does. The computed row is stored, as on ``main``. + """ + _build( + DeltaTableDatabase(tmp_path), _source_table("uint32").slice(0, 2), chained=True + ).run() + _as_written_before_the_fix(tmp_path) + job = _build(DeltaTableDatabase(tmp_path), _source_table("uint32"), chained=True) + + with pytest.raises(pa.ArrowInvalid): + job.run() + + stored = _build(DeltaTableDatabase(tmp_path), _source_table("uint32")) + records = stored.nodes["double"].get_all_records() + assert records is not None + assert records.num_rows == 3 + + def test_new_rows_over_a_store_written_after_the_fix_keep_the_tag_type( tmp_path: pathlib.Path, ) -> None: @@ -376,3 +401,111 @@ def test_a_null_typed_row_is_compared_as_null() -> None: with pytest.raises(InputValidationError, match="'k': null and int64"): _concat_row_tables(rows) + + +@pytest.mark.parametrize("materialize_results", [True, False]) +def test_an_async_run_over_a_store_written_before_the_fix_finishes( + materialize_results: bool, tmp_path: pathlib.Path +) -> None: + """e9 is sync only: an async run over such a store finishes and holds its rows. + + The async orchestrator builds a node's output stream when it is read + (``StreamsOnRead``), so the run finishes as on ``main`` with either value of + ``materialize_results``; reading the node's rows as one table raises, as it does + on ``main``. + """ + from orcapod.pipeline import AsyncPipelineOrchestrator + + _build(DeltaTableDatabase(tmp_path), _source_table("uint32").slice(0, 2)).run() + _as_written_before_the_fix(tmp_path) + job = _build(DeltaTableDatabase(tmp_path), _source_table("uint32")) + job.run( + orchestrator=AsyncPipelineOrchestrator(), + materialize_results=materialize_results, + ) + + node = job.nodes["double"] + assert len(list(node.iter_data())) == 3 + with pytest.raises(InputValidationError, match="'k'"): + node.as_table() + + +def test_a_second_async_run_holds_the_node_and_sends_its_rows( + tmp_path: pathlib.Path, +) -> None: + """The plan builds no held stream for an async run: it sends the held rows as on main. + + Over a store written before ITL-928, the held ``double`` holds rows that cannot + make one table; a second async run (``increment`` cleared) holds it and sends its + three rows on, as on ``main`` (Codex on PR #485, round 2). + """ + from orcapod.pipeline import AsyncPipelineOrchestrator + from orcapod.pipeline.observer import NoOpObserver + + class DataStarts(NoOpObserver): + def __init__(self) -> None: + self.count = 0 + + def contextualize(self, *identity_path: str) -> DataStarts: + return self + + def on_data_start(self, node_label: str, tag: Any, data: Any) -> None: + if node_label == "increment": + self.count += 1 + + _build( + DeltaTableDatabase(tmp_path), _source_table("uint32").slice(0, 2), chained=True + ).run() + _as_written_before_the_fix(tmp_path) + job = _build(DeltaTableDatabase(tmp_path), _source_table("uint32"), chained=True) + job.run(orchestrator=AsyncPipelineOrchestrator()) + job.nodes["increment"].clear_cache() + observer = DataStarts() + summary = job.run(orchestrator=AsyncPipelineOrchestrator(), observer=observer) + assert summary.nodes["double"].held == 3 + assert observer.count == 3 + + +def test_a_held_nodes_rows_are_built_at_its_successors_edge( + tmp_path: pathlib.Path, +) -> None: + """A held node's rows are built where its successor reads them, as on ``main``. + + A direct sync run: ``double`` held (its rows cannot make one table), an independent + source, then ``increment`` after ``double``. The independent source runs before + ``increment``'s input is built and raises (Codex on PR #485, round 3). + """ + from orcapod.core.operators.static_output_pod import rows_on_read + from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator + from orcapod.pipeline.dag import OrcaDAG + from orcapod.pipeline.observer import NoOpObserver + + _build( + DeltaTableDatabase(tmp_path), _source_table("uint32").slice(0, 2), chained=True + ).run() + _as_written_before_the_fix(tmp_path) + job = _build(DeltaTableDatabase(tmp_path), _source_table("uint32"), chained=True) + job.run(orchestrator=AsyncPipelineOrchestrator()) + double, increment = job.nodes["double"], job.nodes["increment"] + increment.clear_cache() + independent = _build(InMemoryArrowDatabase(), _source_table("uint32")).nodes["src"] + + starts: list[str] = [] + + class Starts(NoOpObserver): + def contextualize(self, *identity_path: str) -> Starts: + return self + + def on_node_start( + self, node_label: str, node_hash: str, tag_schema: Any = None + ) -> None: + starts.append(node_label) + + dag: OrcaDAG[Any] = OrcaDAG() + dag.add_node(double) + dag.add_node(independent) + dag.add_edge(double, increment) + held = {double: rows_on_read(double.iter_data(), double)} + with pytest.raises(pa.ArrowInvalid): + SyncPipelineOrchestrator().run(dag, observer=Starts(), held=held) + assert starts == ["src"] diff --git a/tests/test_core/function_pod/test_function_pod_ctx_arg.py b/tests/test_core/function_pod/test_function_pod_ctx_arg.py index 9a4460448..4ab26113a 100644 --- a/tests/test_core/function_pod/test_function_pod_ctx_arg.py +++ b/tests/test_core/function_pod/test_function_pod_ctx_arg.py @@ -156,14 +156,14 @@ def my_fn(value: int, ctx: InvocationContext) -> str: node1 = FunctionJobNode(function_pod=pod, input_stream=stream) node1.attach_databases(pipeline_database=pipeline_db) - results1 = node1.execute(stream) + results1 = list(node1.execute(stream).iter_data()) assert len(results1) == 2 assert call_count == 2 # Second run — same pod, same data, same DB — must NOT call fn again node2 = FunctionJobNode(function_pod=pod, input_stream=stream) node2.attach_databases(pipeline_database=pipeline_db) - results2 = node2.execute(stream) + results2 = list(node2.execute(stream).iter_data()) assert len(results2) == 2 assert call_count == 2 # NOT incremented diff --git a/tests/test_core/nodes/test_function_node_iteration.py b/tests/test_core/nodes/test_function_node_iteration.py index 29b5123eb..d5b79758e 100644 --- a/tests/test_core/nodes/test_function_node_iteration.py +++ b/tests/test_core/nodes/test_function_node_iteration.py @@ -9,6 +9,8 @@ from unittest.mock import patch +from typing import Any + import pyarrow as pa import pytest @@ -171,11 +173,17 @@ def sometimes_fail(x: int) -> int: from orcapod.pipeline.observer import NoOpObserver class CapturingObserver(NoOpObserver): - def on_data_crash(self, node_label, tag, data, exc): - errors.append(exc) - - results = node.execute( - node._input_stream, observer=CapturingObserver(), error_policy="continue" + def on_data_crash( + self, node_label: str, tag: Any, data: Any, error: Exception + ) -> None: + errors.append(error) + + results = list( + node.execute( + node._input_stream, + observer=CapturingObserver(), + error_policy="continue", + ).iter_data() ) assert len(errors) == 1 assert isinstance(errors[0], ValueError) diff --git a/tests/test_core/nodes/test_node_execute.py b/tests/test_core/nodes/test_node_execute.py index 447ad1c1e..b34401b7e 100644 --- a/tests/test_core/nodes/test_node_execute.py +++ b/tests/test_core/nodes/test_node_execute.py @@ -101,7 +101,7 @@ def test_caches_internally(self, function_node_with_db): class TestFunctionNodeExecute: def test_returns_materialized_results(self, function_node_with_db): node, _, _ = function_node_with_db - results = node.execute(node._input_stream) + results = list(node.execute(node._input_stream).iter_data()) assert isinstance(results, list) assert len(results) == 2 values = sorted([pkt.as_dict()["result"] for _, pkt in results]) @@ -162,7 +162,7 @@ def operator_no_db(): class TestOperatorNodeExecute: def test_returns_materialized_results(self, operator_no_db): node, src = operator_no_db - results = node.execute(src) + results = list(node.execute(src).iter_data()) assert isinstance(results, list) assert len(results) == 2 @@ -181,6 +181,6 @@ def test_caches_internally(self, operator_no_db): def test_noop_db_in_off_mode(self, operator_no_db): node, src = operator_no_db - results = node.execute(src) + results = list(node.execute(src).iter_data()) assert len(results) == 2 assert node.get_all_records() is None diff --git a/tests/test_core/operators/test_materialize_source_info.py b/tests/test_core/operators/test_materialize_source_info.py index c6fee9a91..51368151b 100644 --- a/tests/test_core/operators/test_materialize_source_info.py +++ b/tests/test_core/operators/test_materialize_source_info.py @@ -1,7 +1,7 @@ """Every materialized row keeps its own source info (ITL-845). ``StaticOutputOperatorPod._materialize_to_stream`` and -``SyncPipelineOrchestrator._materialize_as_stream`` turn collected (Tag, Data) +``StaticOutputOperatorPod._materialize_upstream`` turn collected (Tag, Data) pairs back into a stream. They used to read row 0's source info and stamp it on every row, so rows from index 1 onward were attributed to row 0. These tests send rows with distinct source-info tokens through every path that materializes @@ -42,7 +42,6 @@ from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod from orcapod.core.sources import ArrowTableSource, DictSource from orcapod.databases import DeltaTableDatabase, InMemoryArrowDatabase -from orcapod.pipeline.sync_orchestrator import SyncPipelineOrchestrator from orcapod.protocols.database_protocols import ArrowDatabaseProtocol from orcapod.protocols.core_protocols import DataProtocol, StreamProtocol, TagProtocol from orcapod.system_constants import constants @@ -136,9 +135,9 @@ def _materialize(rows: Sequence[Row]) -> StreamProtocol: def _materialize_buffer(buf: Sequence[Row], node: Any) -> StreamProtocol: - """Call ``SyncPipelineOrchestrator._materialize_as_stream``, the helper under test.""" + """Call ``StaticOutputOperatorPod._materialize_upstream``, the helper under test.""" # Non-public on purpose: these tests are about this helper itself. - return SyncPipelineOrchestrator._materialize_as_stream(list(buf), node) # pyright: ignore[reportPrivateUsage] + return StaticOutputOperatorPod._materialize_upstream(list(buf), node) # pyright: ignore[reportPrivateUsage] def _broadcast_row_zero(monkeypatch: pytest.MonkeyPatch) -> None: @@ -155,9 +154,29 @@ def broadcasting( [(tag, data.with_source_info(**row_zero)) for tag, data in rows] ) + original_form = StaticOutputOperatorPod._row_built_form # pyright: ignore[reportPrivateUsage] + + def broadcasting_form( + table: pa.Table, keys: tuple[Sequence[str], Sequence[str]] + ) -> pa.Table: + """Stamp row 0's source info on every row of the row-built form (ITL-1347).""" + formed = original_form(table, keys) + for i, name in enumerate(formed.column_names): + if name.startswith(constants.SOURCE_PREFIX): + column = formed.column(i) + first = column.slice(0, 1).combine_chunks() + repeated = pa.concat_arrays([first] * formed.num_rows) + formed = formed.set_column(i, formed.schema.field(i), repeated) + return formed + monkeypatch.setattr( StaticOutputOperatorPod, "_rows_to_table", staticmethod(broadcasting) ) + # An operator node keeps the row-built form of its result's table, without + # making the rows (ITL-1347, stage 2). + monkeypatch.setattr( + StaticOutputOperatorPod, "_row_built_form", staticmethod(broadcasting_form) + ) def _stored_source(node: OperatorJobNode, column: str = "x") -> list[Any]: @@ -688,7 +707,7 @@ def test_rerun_after_pre_fix_store(self, monkeypatch: pytest.MonkeyPatch): assert _stored_source(old) == [tokens[0]] * 3 new = self._node(db) - out = new.execute(_pin_source()) + out = list(new.execute(_pin_source()).iter_data()) # The run itself emits the corrected rows. assert _source_info_tokens(out) == tokens diff --git a/tests/test_core/operators/test_record_batch_execution.py b/tests/test_core/operators/test_record_batch_execution.py index 6615b8867..61f08be7e 100644 --- a/tests/test_core/operators/test_record_batch_execution.py +++ b/tests/test_core/operators/test_record_batch_execution.py @@ -603,15 +603,11 @@ def _schema_outcome(make: Callable[[], StreamProtocol]) -> tuple[str, Any]: @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.""" +def test_empty_source_info_lists_are_typed_from_their_tokens(layout: str) -> None: + """A raw stream whose source-info column is a nested list type holding only empty + lists: the channel's result equals the job's sync path, both typing the tokens from + their values over the complete table (``_type_source_info_by_values``), as the rows + do: one list level, not the column's two.""" raw = ArrowTableStream( pa.table( { @@ -629,11 +625,9 @@ def test_empty_source_info_lists_are_outside_the_row_built_forms_domain( 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()) + assert got.to_pylist() == rebuilt.to_pylist() + assert got.schema.equals(rebuilt.schema) + assert got.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: diff --git a/tests/test_core/operators/test_row_built_form.py b/tests/test_core/operators/test_row_built_form.py new file mode 100644 index 000000000..c511d1b5c --- /dev/null +++ b/tests/test_core/operators/test_row_built_form.py @@ -0,0 +1,409 @@ +"""F, the row-built form of a table, equals the table built from its rows (ITL-1347, L0). + +``StaticOutputOperatorPod._row_built_form`` (F in the spec, +``docs/dev/specs/itl-1347-job-table-transport.md``) gives a node's output table as +``_rows_to_table`` (R) builds it from the node's rows, without making the rows. Every +operator, column role and arrangement of the async-sync matrix is checked: the column +names and their order, every field (type, nullability, field metadata), the schema +metadata, and every value (floats by their bits). + +Two properties each case covers by construction: + +- A data-tag's source info comes first among the source info, in tag order, whatever + its column's place in the table (``source_mid``, ``tag_by``): a row lists its source + info in the order of its data keys. +- A system-tag field is nullable only when a value is null: a join over inputs tied on + pipeline hash (``ref_join_3_tied``) declares its system tags nullable, a table built + from rows does not. +""" + +from __future__ import annotations + +from typing import Any + +import pyarrow as pa +import pyarrow.compute as pc +import pytest + +from orcapod import PipelineJob +from orcapod.core.operators import Batch, DropNulls, SelectDataColumns +from orcapod.core.operators.static_output_pod import ( + SourceInfoTypesDisagree, + StaticOutputOperatorPod, +) +from orcapod.databases import InMemoryArrowDatabase +from orcapod.pipeline.observer import NoOpObserver +from orcapod.types import CacheMode +from orcapod.core.streams import ArrowTableStream +from orcapod.core.streams.base import ZERO_ROW_INPUT_COLUMNS, row_built_columns +from orcapod.system_constants import constants +from tests.test_core.operators.test_async_sync_equivalence import ( + AFTER_OPERATOR_CASES, + CASES, + FUNCTION_POD_CASES, + Case, +) + + +_FLOAT_BITS = {16: pa.uint16(), 32: pa.uint32(), 64: pa.uint64()} + + +def _as_bits(array: Any) -> Any: # pyright: ignore[reportExplicitAny] # any Arrow array kind + """``array``'s values, with every float, at any depth, as its bit pattern. + + Arrow's ``equals`` holds NaN unequal to itself, so floats are compared as unsigned + integers of their width. Lists and structs are taken apart into their validity, their + lengths and their children's values, so the physical layout (a list's first offset, + the bytes behind a null) does not count. + """ + kind = array.type + if isinstance(array, pa.ExtensionArray): + return ("extension", _as_bits(array.storage)) + if pa.types.is_floating(kind): + filled = pc.if_else(pc.is_null(array), pa.scalar(0, kind), array) + return ("float", array.is_null(), filled.view(_FLOAT_BITS[kind.bit_width])) + if pa.types.is_map(kind): + return ( + "map", + array.is_null(), + pc.list_value_length(array), + _as_bits(array.keys), + _as_bits(array.items), + ) + if ( + pa.types.is_list(kind) + or pa.types.is_large_list(kind) + or pa.types.is_fixed_size_list(kind) + ): + return ( + "list", + array.is_null(), + pc.list_value_length(array), + _as_bits(array.flatten()), + ) + if pa.types.is_struct(kind): + return ( + "struct", + array.is_null(), + tuple(_as_bits(child) for child in array.flatten()), + ) + return ("value", array) + + +def assert_same_values(formed: pa.Table, built: pa.Table) -> None: + """Every column of ``formed`` holds the values of ``built``, floats by their bits. + + The physical layout (a list's first offset, the bytes behind a null) is not a + value and may differ. + """ + for name in built.column_names: + expected, got = built.column(name), formed.column(name) + assert got.type == expected.type, name + assert _as_bits(got.combine_chunks()) == _as_bits(expected.combine_chunks()), ( + name + ) + + +def _all_cases() -> list[Any]: + cases: list[Any] = [pytest.param(c, id=c.label) for c in CASES] + cases += list(AFTER_OPERATOR_CASES) + cases += [pytest.param(c, id=f"fp-{c.label}") for c in FUNCTION_POD_CASES] + return cases + + +@pytest.mark.parametrize("case", _all_cases()) +def test_row_built_form_equals_the_table_built_from_rows(case: Case) -> None: + """F of an operator's result table equals R of its rows, field and bit for bit.""" + result = case.make_op()(*case.make_sources()) + rows = list(result.iter_data()) + if not rows: + pytest.skip("no rows: F is defined on a table with rows") + built, _, _ = StaticOutputOperatorPod._rows_to_table(rows) # pyright: ignore[reportPrivateUsage] # R, the oracle + formed = StaticOutputOperatorPod._row_built_form( # pyright: ignore[reportPrivateUsage] # F, under test + result.as_table(columns=ZERO_ROW_INPUT_COLUMNS), result.keys() + ) + assert formed.column_names == built.column_names + assert formed.schema.equals(built.schema, check_metadata=True) + assert_same_values(formed, built) + + +def test_row_built_columns_is_the_same_on_every_slice() -> None: + """The row-by-row steps of F give the same columns on a slice as on the whole.""" + case = next(c for c in CASES if c.label == "ref_join_3_tied") + result = case.make_op()(*case.make_sources()) + table = result.as_table(columns=ZERO_ROW_INPUT_COLUMNS) + keys = result.keys() + whole = row_built_columns(table, keys) + for start in range(table.num_rows): + part = row_built_columns(table.slice(start, 1), keys) + assert part.schema.equals(whole.schema, check_metadata=True) + assert part.equals(whole.slice(start, 1)) + + +def _raw_stream() -> ArrowTableStream: + """A raw stream with provenance fields no source writes (Codex on PR #483). + + A system-tag field with field metadata, a list-valued source-info column whose item + field is named ``member`` and non-nullable, and a meta (``__``) data column with + its own source info. + """ + system_tag = f"{constants.SYSTEM_TAG_PREFIX}source_id::abc" + member = pa.field("member", pa.large_string(), nullable=False) + table = pa.table( + { + "k": pa.array([1, 2], pa.int64()), + "j": pa.array(["a", "b"], pa.large_string()), + system_tag: pa.array(["s1", "s2"], pa.large_string()), + "x": pa.array([1.0, float("nan")]), + "z": pa.array([3, None], pa.int8()), + "__note": pa.array(["a", "b"]), + "_source_x": pa.array([["a", "b"], ["c"]], pa.large_list(member)), + "_source_z": pa.array(["t1", "t2"], pa.large_string()), + "_source___note": pa.array(["n1", "n2"], pa.large_string()), + } + ) + position = table.schema.get_field_index(system_tag) + schema = table.schema.set( + position, table.schema.field(position).with_metadata({b"m": b"v"}) + ) + return ArrowTableStream( + pa.Table.from_arrays(table.columns, schema=schema), tag_columns=["k", "j"] + ) + + +@pytest.mark.parametrize( + "make", + [ + pytest.param(_raw_stream, id="raw"), + pytest.param( + lambda: SelectDataColumns(["z", "x"])(_raw_stream()), id="select-z-x" + ), + pytest.param(lambda: DropNulls(["j", "k"])(_raw_stream()), id="drop-nulls"), + ], +) +def test_row_built_form_of_a_raw_stream(make: Any) -> None: + """F equals R on a raw stream: provenance fields as rows build them, no meta. + + R takes a system tag and a source-info token from its values, so the system-tag + field has no metadata and a list token's item field is nullable ``item``; a meta + column is not data, so neither it nor its source info is passed on. + """ + stream = make() + built, _, _ = StaticOutputOperatorPod._rows_to_table(list(stream.iter_data())) # pyright: ignore[reportPrivateUsage] # R, the oracle + formed = StaticOutputOperatorPod._row_built_form( # pyright: ignore[reportPrivateUsage] # F, under test + stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS), stream.keys() + ) + assert "__note" not in formed.column_names + assert "_source___note" not in formed.column_names + assert formed.column_names == built.column_names + assert formed.schema.equals(built.schema, check_metadata=True) + assert_same_values(formed, built) + + +def _source_table() -> pa.Table: + """A source's table with its system tags and source info (one tag, one data).""" + from orcapod.sources import DictSource + + source = DictSource( + [{"k": 1, "x": 1}, {"k": 2, "x": 2}], + tag_columns=["k"], + tag_only_columns=True, + source_id="s", + ) + return source.as_table(columns={"source": True, "system_tags": True}) + + +def _with_source_x(values: list[Any], kind: pa.DataType) -> ArrowTableStream: + """A source's rows as a raw stream, ``_source_x`` replaced by ``values`` of ``kind``. + + It keeps the source's system-tag pair, so a job slot accepts it (Codex on PR #485). + """ + table = _source_table() + position = table.schema.get_field_index("_source_x") + return ArrowTableStream( + table.set_column( + position, + pa.field("_source_x", kind, nullable=True), + pa.array(values, kind), + ), + tag_columns=["k"], + ) + + +_STRINGS = pa.large_list(pa.large_string()) +_NESTED = pa.large_list(_STRINGS) + + +@pytest.mark.parametrize( + "make", + [ + pytest.param(lambda: _with_source_x([[], []], _NESTED), id="empty-lists"), + pytest.param(lambda: _with_source_x([None, None], _STRINGS), id="null-lists"), + pytest.param( + lambda: _with_source_x([[None], [None]], _NESTED), id="lists-of-null" + ), + pytest.param( + lambda: Batch(batch_size=1)( + _with_source_x([None, None], pa.large_string()) + ), + id="batch-1-of-null-tokens", + ), + pytest.param( + lambda: Batch(batch_size=2)(_with_source_x([None, None], _STRINGS)), + id="batch-2-of-null-lists", + ), + pytest.param(lambda: _with_source_x([None, None], pa.null()), id="null-type"), + ], +) +def test_source_info_types_follow_the_tokens(make: Any) -> None: + """F types each source-info column from its tokens, as the rows do. + + A list of ``None`` or of empty lists shows fewer levels than its column declares; + the rows type it from the tokens (``arrow_utils.source_info_arrow_type``), and so + does F, over the whole table. + """ + stream = make() + built, _, _ = StaticOutputOperatorPod._rows_to_table(list(stream.iter_data())) # pyright: ignore[reportPrivateUsage] # R, the oracle + formed = StaticOutputOperatorPod._row_built_form( # pyright: ignore[reportPrivateUsage] # F, under test + stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS), stream.keys() + ) + assert formed.column_names == built.column_names + assert formed.schema.equals(built.schema, check_metadata=True) + assert_same_values(formed, built) + + +def test_tokens_of_two_types_raise_as_the_rows_do() -> None: + """A list token on one row and ``None`` on another: no table holds both rows. + + The rows' tables cannot be concatenated (``ArrowInvalid``); F says so + (``SourceInfoTypesDisagree``), and a node then builds the rows, which raise. + """ + stream = _with_source_x([["s"], None], _STRINGS) + with pytest.raises(pa.ArrowInvalid, match="Schema at index 1 was different"): + StaticOutputOperatorPod._rows_to_table(list(stream.iter_data())) # pyright: ignore[reportPrivateUsage] # R, the oracle + with pytest.raises(SourceInfoTypesDisagree, match="_source_x"): + StaticOutputOperatorPod._row_built_form( # pyright: ignore[reportPrivateUsage] # F, under test + stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS), stream.keys() + ) + + +class _NodeEvents(NoOpObserver): + """Records node starts and ends.""" + + def __init__(self) -> None: + self.events: list[tuple[str, str]] = [] + + def contextualize(self, *identity_path: str) -> _NodeEvents: + return self + + def on_node_start( + self, node_label: str, node_hash: str, tag_schema: Any = None + ) -> None: + self.events.append(("start", node_label)) + + def on_node_end(self, node_label: str, node_hash: str) -> None: + self.events.append(("end", node_label)) + + +def _batched_job(database: InMemoryArrowDatabase) -> PipelineJob: + """``source -> select x -> Batch(2)``, the batch node in ``LOG`` mode.""" + from orcapod.sources import DictSource + + source = DictSource( + [{"k": 1, "x": 1}, {"k": 2, "x": 2}], + tag_columns=["k"], + tag_only_columns=True, + source_id="s", + ) + job = PipelineJob(name="source_info_types", database=database) + with job: + Batch(batch_size=2)(source.select_data_columns(["x"]), label="batched") + job.nodes["batched"].attach_databases( + pipeline_database=database.at("log"), cache_mode=CacheMode.LOG + ) + return job + + +def test_a_job_keeps_and_stores_the_token_type_the_rows_give() -> None: + """A bound raw source with null list tokens, through ``Batch(2)`` in ``LOG`` mode. + + The rows type ``[None, None]`` as ``large_list``: kept and stored so, + as on ``main``, not as the list of the input's declared list type. + """ + database = InMemoryArrowDatabase() + job = _batched_job(database) + job.bind(sources={"s": _with_source_x([None, None], _STRINGS)}) + job.run() + node = job.nodes["batched"] + kept = node.as_table(columns={"source": True}) + assert kept.schema.field("_source_x").type == _STRINGS + stored = node.get_all_records(columns={"source": True}) + assert stored is not None + assert stored.schema.field("_source_x").type == _STRINGS + + +def test_a_job_over_tokens_of_two_types_fails_as_main_does() -> None: + """The run raises the rows' ``ArrowInvalid`` after the source node has ended. + + On ``main`` the source node hands its rows on, and the run fails where they are + concatenated for its successor: the same error, after the same events. + """ + job = _batched_job(InMemoryArrowDatabase()) + job.bind(sources={"s": _with_source_x([["s"], None], _STRINGS)}) + observer = _NodeEvents() + with pytest.raises(pa.ArrowInvalid, match="Schema at index 1 was different"): + job.run(observer=observer) + assert observer.events == [("start", "s"), ("end", "s")] + + +def test_a_source_with_a_nullable_system_tag_is_not_bound() -> None: + """A system-tag field with a null never reaches a job: a slot refuses the source. + + So F never meets one; ``_rows_to_table`` could not build its rows (two rows would + give the field two nullability flags). + """ + from orcapod import PipelineJob + from orcapod.databases import InMemoryArrowDatabase + from orcapod.errors import SourceSpecMismatchError + from orcapod.sources import DictSource + + source = DictSource( + [{"k": 1, "x": 1}, {"k": 2, "x": 2}], + tag_columns=["k"], + tag_only_columns=True, + source_id="s", + ) + job = PipelineJob(name="nullable_system_tag", database=InMemoryArrowDatabase()) + with job: + source.select_data_columns(["x"], label="selected") + table = _source_table() + record_id = next( + name + for name in table.column_names + if name.startswith(constants.SYSTEM_TAG_PREFIX) and "record_id" in name + ) + position = table.schema.get_field_index(record_id) + with_null = table.set_column( + position, + pa.field(record_id, pa.large_string(), nullable=True), + pa.array(["row_0", None], pa.large_string()), + ) + slot = next(label for label in job.nodes if label != "selected") + with pytest.raises(SourceSpecMismatchError, match="record_id"): + job.bind(sources={slot: ArrowTableStream(with_null, tag_columns=["k"])}) + + +def test_a_token_the_rows_cannot_convert_fails_as_main_does() -> None: + """A conversion failure of F's whole-table build falls back to the rows, as on main. + + Each row's token ``[None, [[]]]`` gives one list level (``source_info_arrow_type``), + whose conversion fails (``ArrowTypeError``). The node builds its rows, which raise + the same error, after the source node has ended (Codex on PR #485, round 2). + """ + nested = pa.large_list(_NESTED) + job = _batched_job(InMemoryArrowDatabase()) + job.bind(sources={"s": _with_source_x([[None, [[]]], [None, [[]]]], nested)}) + observer = _NodeEvents() + with pytest.raises(pa.ArrowTypeError, match="Expected bytes"): + job.run(observer=observer) + assert observer.events == [("start", "s"), ("end", "s")] diff --git a/tests/test_core/side_effect_function/test_side_effect_function_pod.py b/tests/test_core/side_effect_function/test_side_effect_function_pod.py index ae7d470d1..0543c1ab7 100644 --- a/tests/test_core/side_effect_function/test_side_effect_function_pod.py +++ b/tests/test_core/side_effect_function/test_side_effect_function_pod.py @@ -176,14 +176,14 @@ def my_fn(value: int, ctx: InvocationContext) -> str: node1 = FunctionJobNode(function_pod=pod, input_stream=stream) node1.attach_databases(pipeline_database=pipeline_db) - results1 = node1.execute(stream) + results1 = list(node1.execute(stream).iter_data()) assert len(results1) == 2 assert call_count == 2 # Second run — same pod, same data, same DB — fn must NOT be called again node2 = FunctionJobNode(function_pod=pod, input_stream=stream) node2.attach_databases(pipeline_database=pipeline_db) - results2 = node2.execute(stream) + results2 = list(node2.execute(stream).iter_data()) assert len(results2) == 2 assert call_count == 2 # NOT incremented — cache hit diff --git a/tests/test_core/side_effect_pod/test_side_effect_pod.py b/tests/test_core/side_effect_pod/test_side_effect_pod.py index 18be593e4..f5eb4487d 100644 --- a/tests/test_core/side_effect_pod/test_side_effect_pod.py +++ b/tests/test_core/side_effect_pod/test_side_effect_pod.py @@ -320,7 +320,7 @@ def fn(value, ctx): calls.append(True) node, stream, db = self._make_node_with_db(fn) - results = node.execute(stream) + results = list(node.execute(stream).iter_data()) assert len(results) == 3 assert len(calls) == 3 @@ -356,14 +356,14 @@ def fn(value, ctx): node1 = SideEffectJobNode(side_effect_pod=pod, input_stream=stream) node1.attach_databases(pipeline_database=db) - results1 = node1.execute(stream) + results1 = list(node1.execute(stream).iter_data()) assert len(results1) == 2 assert len(calls) == 2 # Second run with same DB node2 = SideEffectJobNode(side_effect_pod=pod, input_stream=stream) node2.attach_databases(pipeline_database=db) - results2 = node2.execute(stream) + results2 = list(node2.execute(stream).iter_data()) assert len(results2) == 2 # rows still emitted (pass-through) assert len(calls) == 2 # fn NOT called again — completion check triggered @@ -441,7 +441,7 @@ def fn(value, ctx): # Run 1: fn raises → nothing written to DB. node1 = SideEffectJobNode(side_effect_pod=pod, input_stream=stream) node1.attach_databases(pipeline_database=db) - results1 = node1.execute(stream) + results1 = list(node1.execute(stream).iter_data()) assert len(results1) == 1 # row still emitted (drop_on_failure=False) assert call_count == 1 # fn was invoked @@ -451,7 +451,7 @@ def fn(value, ctx): # Run 2: no record found → fn is called again, still fails. node2 = SideEffectJobNode(side_effect_pod=pod, input_stream=stream) node2.attach_databases(pipeline_database=db) - results2 = node2.execute(stream) + results2 = list(node2.execute(stream).iter_data()) assert len(results2) == 1 assert call_count == 2 # retried — fn called a second time @@ -490,7 +490,7 @@ def fn(value, ctx): # Run 1: fn raises → no DB record. node1 = SideEffectJobNode(side_effect_pod=pod, input_stream=stream) node1.attach_databases(pipeline_database=db) - results1 = node1.execute(stream) + results1 = list(node1.execute(stream).iter_data()) assert len(results1) == 1 # emitted despite failure assert call_count == 1 @@ -500,7 +500,7 @@ def fn(value, ctx): # Run 2: no record → fn retried → succeeds → record written. node2 = SideEffectJobNode(side_effect_pod=pod, input_stream=stream) node2.attach_databases(pipeline_database=db) - results2 = node2.execute(stream) + results2 = list(node2.execute(stream).iter_data()) assert len(results2) == 1 assert call_count == 2 # fn called exactly once more @@ -512,7 +512,7 @@ def fn(value, ctx): # Run 3: record found → fn NOT called → row re-emitted from cache. node3 = SideEffectJobNode(side_effect_pod=pod, input_stream=stream) node3.attach_databases(pipeline_database=db) - results3 = node3.execute(stream) + results3 = list(node3.execute(stream).iter_data()) assert len(results3) == 1 assert call_count == 2 # still 2 — fn was skipped entirely diff --git a/tests/test_core/sources/test_postgresql_table_source_integration.py b/tests/test_core/sources/test_postgresql_table_source_integration.py index 46592b213..8dca286db 100644 --- a/tests/test_core/sources/test_postgresql_table_source_integration.py +++ b/tests/test_core/sources/test_postgresql_table_source_integration.py @@ -253,7 +253,9 @@ def double_response(trial: int, response: float) -> float: result = orch.run(exec_dag) fn_outputs = [ - v for k, v in result.node_outputs.items() if k.node_type == "function" + list(v.iter_data()) + for k, v in result.node_outputs.items() + if k.node_type == "function" ] assert len(fn_outputs) == 1 assert len(fn_outputs[0]) == 3 diff --git a/tests/test_core/sources/test_spiraldb_table_source_where.py b/tests/test_core/sources/test_spiraldb_table_source_where.py index db78b7787..05a84a55f 100644 --- a/tests/test_core/sources/test_spiraldb_table_source_where.py +++ b/tests/test_core/sources/test_spiraldb_table_source_where.py @@ -1933,7 +1933,9 @@ def test_execute_over_unrestricted_streams_still_caches( (("m2", 5), 5.5, 1), ] - logged = node.execute(_source(source_id="events", tag_only_columns=True)) + logged = list( + node.execute(_source(source_id="events", tag_only_columns=True)).iter_data() + ) assert self._keyed(logged) == expected stored = node.as_source().as_table().to_pylist() @@ -1952,7 +1954,7 @@ def test_execute_over_unrestricted_streams_still_caches( ) scans = len(fake_pyspiral.scan_log) - replayed = node.execute(other) + replayed = list(node.execute(other).iter_data()) assert self._keyed(replayed) == expected assert len(fake_pyspiral.scan_log) == scans diff --git a/tests/test_core/sources/test_sqlite_table_source.py b/tests/test_core/sources/test_sqlite_table_source.py index fe74de6ce..91008dc35 100644 --- a/tests/test_core/sources/test_sqlite_table_source.py +++ b/tests/test_core/sources/test_sqlite_table_source.py @@ -611,7 +611,9 @@ def double_response(trial: int, response: float) -> float: result = orch.run(exec_dag) fn_outputs = [ - v for k, v in result.node_outputs.items() if k.node_type == "function" + list(v.iter_data()) + for k, v in result.node_outputs.items() + if k.node_type == "function" ] assert len(fn_outputs) == 1 assert len(fn_outputs[0]) == 3 diff --git a/tests/test_core/test_tracker.py b/tests/test_core/test_tracker.py index 8f28798be..046239abb 100644 --- a/tests/test_core/test_tracker.py +++ b/tests/test_core/test_tracker.py @@ -251,7 +251,7 @@ def test_run_equivalent(self): """execute() on SourceJobNode returns all data rows.""" stream = _make_source() node = self._make_job_node(stream) - result = node.execute() + result = list(node.execute().iter_data()) assert len(result) == stream.as_table().num_rows def test_data_context_key(self): diff --git a/tests/test_pipeline/test_declared_slot_one_data_tag.py b/tests/test_pipeline/test_declared_slot_one_data_tag.py new file mode 100644 index 000000000..88fcc4045 --- /dev/null +++ b/tests/test_pipeline/test_declared_slot_one_data_tag.py @@ -0,0 +1,87 @@ +"""A declared slot over a narrower source with one data-tag among two tags (ITL-1366). + +A source slot declared from a source whose ``x`` is ``int | None``, bound to the same +table with ``x: int`` (a narrower source, given as the declared schema), feeding an +operator. On ``main`` the run raises ``ValueError`` ("Duplicate column name") where the +source's rows are rebuilt for its successor, when exactly one of the two tags is a +data-tag and the tags are declared ``j, k`` (ITL-1366, a ``main`` bug fixed there +separately). A narrower bind hands on its rows as ``main`` gives them (``RowsOnRead``), +built where the successor reads them: the branch raises the same error at the same +point, on the sync and the async path, and completes every other arrangement. +""" + +from __future__ import annotations + +from typing import Any + +import pyarrow as pa +import pytest + +from orcapod import PipelineJob +from orcapod.databases import InMemoryArrowDatabase +from orcapod.pipeline import AsyncPipelineOrchestrator +from orcapod.sources import ArrowTableSource + +ROWS = [ + {"j": 3, "k": 5, "x": 1, "y": 7.5}, + {"j": 4, "k": 6, "x": 2, "y": 8.5}, +] + +ROLES: dict[str, bool | tuple[str, ...]] = { + "no_data_tag": True, + "k_data_tag": ("j",), + "j_data_tag": ("k",), + "both_data_tags": (), +} + + +def _source(nullable_x: bool, order: tuple[str, str], roles: Any) -> ArrowTableSource: + table = pa.table( + { + "x": pa.array([1, 2], pa.int64()), + "k": pa.array([5, 6], pa.int64()), + "j": pa.array([3, 4], pa.int64()), + "y": pa.array([7.5, 8.5], pa.float64()), + } + ) + table = table.cast( + pa.schema([f.with_nullable(f.name == "x" and nullable_x) for f in table.schema]) + ) + return ArrowTableSource( + table, tag_columns=list(order), tag_only_columns=roles, source_id="s" + ) + + +def _bound_job(order: tuple[str, str], roles: Any) -> PipelineJob: + """The slot declared with ``x: int | None``, bound to the table with ``x: int``.""" + job = PipelineJob(name="declared_one_data_tag", database=InMemoryArrowDatabase()) + with job: + _source(True, order, roles).select_data_columns(["y", "x"], label="selected") + slot = next(label for label in job.nodes if label != "selected") + job.bind(sources={slot: _source(False, order, roles)}) + return job + + +def _rows(job: PipelineJob) -> list[dict[str, Any]]: + table = job.nodes["selected"].as_table() + return sorted(table.to_pylist(), key=lambda row: row["j"]) + + +@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"]) +@pytest.mark.parametrize("roles", list(ROLES), ids=list(ROLES)) +@pytest.mark.parametrize("order", [("j", "k"), ("k", "j")], ids=["j-k", "k-j"]) +def test_the_run_is_as_on_main( + order: tuple[str, str], roles: str, asynchronous: bool +) -> None: + """Raises where ``main`` raises (ITL-1366), else gives the bound table's rows.""" + job = _bound_job(order, ROLES[roles]) + kwargs: dict[str, Any] = ( + {"orchestrator": AsyncPipelineOrchestrator()} if asynchronous else {} + ) + raises_on_main = order == ("j", "k") and roles in ("k_data_tag", "j_data_tag") + if raises_on_main: + with pytest.raises(ValueError, match="Duplicate column name"): + job.run(**kwargs) + else: + job.run(**kwargs) + assert _rows(job) == ROWS diff --git a/tests/test_pipeline/test_error_policy_continue.py b/tests/test_pipeline/test_error_policy_continue.py index 31ad95450..88e99241c 100644 --- a/tests/test_pipeline/test_error_policy_continue.py +++ b/tests/test_pipeline/test_error_policy_continue.py @@ -14,6 +14,7 @@ from orcapod.core.sources import ArrowTableSource from orcapod.databases import InMemoryArrowDatabase from orcapod.pipeline.job import PipelineJob +from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod from orcapod.pipeline.sync_orchestrator import SyncPipelineOrchestrator @@ -80,7 +81,7 @@ def identity(value: int) -> int: # Don't run — buffer will be empty node = job.nodes["fn"] - stream = SyncPipelineOrchestrator._materialize_as_stream([], node) + stream = StaticOutputOperatorPod._materialize_upstream([], node) tag_schema, data_schema = stream.output_schema() # "result" is declared as int (required), must NOT become int | None diff --git a/tests/test_pipeline/test_held_streams_on_read.py b/tests/test_pipeline/test_held_streams_on_read.py new file mode 100644 index 000000000..daed771fc --- /dev/null +++ b/tests/test_pipeline/test_held_streams_on_read.py @@ -0,0 +1,112 @@ +"""Held streams and async outputs are built when read (ITL-1360; Codex on PR #485). + +A run plan's held streams (``RunPlan.held``) and the async orchestrator's +``node_outputs`` are ``StreamsOnRead``: a node's stream is built from its rows when it +is read. Membership, length and iteration never build one; the plan keeps no held +stream it has built, so the sync orchestrator releases it once its successors ran. +""" + +from __future__ import annotations + +import gc +import weakref +from typing import Any + +import pytest + +from orcapod import PipelineJob, function_pod +from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod +from orcapod.databases import InMemoryArrowDatabase +from orcapod.pipeline.observer import NoOpObserver +from orcapod.pipeline.result import StreamsOnRead +from orcapod.sources import DictSource + + +def test_membership_length_and_iteration_build_nothing() -> None: + """``in``, ``len`` and iteration read the nodes only; reading a value builds it.""" + + def build(rows: Any, node: Any) -> Any: + raise AssertionError(f"built {node}") + + outputs = StreamsOnRead({"a": [], "b": []}, build) + assert "a" in outputs + assert "c" not in outputs + assert len(outputs) == 2 + assert list(outputs) == ["a", "b"] + with pytest.raises(AssertionError, match="built a"): + _ = outputs["a"] + + +def test_a_kept_stream_is_built_once_and_an_unkept_one_each_read() -> None: + built: list[Any] = [] + + def build(rows: Any, node: Any) -> Any: + built.append(node) + return object() + + kept = StreamsOnRead({"a": []}, build) + assert kept["a"] is kept["a"] + unkept = StreamsOnRead({"a": []}, build, keep=False) + _ = unkept["a"] + _ = unkept["a"] + assert built == ["a", "a", "a"] + + +@function_pod(output_keys="y") +def step(x: int) -> int: + return x + 1 + + +def test_a_held_stream_is_released_once_its_successors_ran( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """``source -> a -> b -> c -> d`` with ``a`` held: its stream is gone when ``c`` starts.""" + job = PipelineJob(name="held_lifetime", database=InMemoryArrowDatabase()) + with job: + source = DictSource( + [{"k": i, "x": i} for i in range(3)], + tag_columns=["k"], + tag_only_columns=True, + source_id="s", + ) + a: Any = step.pod(source, label="a") + b: Any = step.pod(a.map_data({"y": "x"}), label="b") + c: Any = step.pod(b.map_data({"y": "x"}), label="c") + step.pod(c.map_data({"y": "x"}), label="d") + job.run() + for label in ("b", "c", "d"): + job.nodes[label].clear_cache() + for node in job.nodes.values(): + if node.label.startswith("MapData"): + node.clear_cache() + + held: list[weakref.ref[Any]] = [] + original = StaticOutputOperatorPod._materialize_upstream # pyright: ignore[reportPrivateUsage] # the held stream's build + + def materialize(rows: Any, upstream: Any, **kwargs: Any) -> Any: + stream = original(rows, upstream, **kwargs) + if getattr(upstream, "label", None) == "a": + held.append(weakref.ref(stream)) + return stream + + monkeypatch.setattr( + StaticOutputOperatorPod, "_materialize_upstream", staticmethod(materialize) + ) + + alive_at_c: list[bool] = [] + + class AtC(NoOpObserver): + def contextualize(self, *identity_path: str) -> AtC: + return self + + def on_node_start( + self, node_label: str, node_hash: str, tag_schema: Any = None + ) -> None: + if node_label == "c": + gc.collect() + alive_at_c.append(any(ref() is not None for ref in held)) + + summary = job.run(observer=AtC(), materialize_results=False) + assert summary.nodes["a"].held == 3 + assert held + assert alive_at_c == [False] diff --git a/tests/test_pipeline/test_job_node_rows_after_run.py b/tests/test_pipeline/test_job_node_rows_after_run.py index 6d00c1154..04ba3867a 100644 --- a/tests/test_pipeline/test_job_node_rows_after_run.py +++ b/tests/test_pipeline/test_job_node_rows_after_run.py @@ -422,7 +422,7 @@ def test_sync_one_of_two_equal_inputs_fails(self) -> None: node = self._node(self._flaky_pod()) received = sorted( (tag.as_dict()["k"], data.as_dict()["y"]) - for tag, data in node.execute(node.upstreams[0]) + for tag, data in list(node.execute(node.upstreams[0]).iter_data()) ) assert received == [(0, 6), (2, 8)] assert self._held(node) == received diff --git a/tests/test_pipeline/test_narrower_bind_order.py b/tests/test_pipeline/test_narrower_bind_order.py new file mode 100644 index 000000000..45bca4160 --- /dev/null +++ b/tests/test_pipeline/test_narrower_bind_order.py @@ -0,0 +1,124 @@ +"""A narrower bind hands on its rows in their order (ITL-1360, L2; Codex on PR #485). + +A source slot declared from a source whose ``x`` is ``int | None``, bound to the same +columns with ``x: int`` (a narrower source, given as the declared schema), feeding a +``Batch`` node in ``LOG`` mode. The source node hands on its rows as ``main`` gives +them (``_declared_rows``), built where the successor reads them (``RowsOnRead``). +Every pairing of declared layout, tag +order and data-tag roles must keep and store what the row path keeps and stores: the +same run with the source's output built from its rows +(``StaticOutputOperatorPod._materialize_upstream``), as on ``main``, also where the +row path raises (one data-tag of two, ITL-1366). +""" + +from __future__ import annotations + +import itertools +from typing import Any + +import pyarrow as pa +import pytest + +from orcapod import PipelineJob +from orcapod.core.nodes.source_node import SourceNodeBase +from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod +from orcapod.databases import InMemoryArrowDatabase +from orcapod.operators import Batch +from orcapod.sources import ArrowTableSource +from orcapod.types import CacheMode + +ROLES: dict[str, bool | tuple[str, ...]] = { + "no_data_tag": True, + "a_data_tag": ("b",), + "b_data_tag": ("a",), + "both_data_tags": (), +} + + +def _source( + nullable_x: bool, layout: tuple[str, ...], tag_order: tuple[str, str], roles: Any +) -> ArrowTableSource: + columns = { + "x": pa.array([1, 2], pa.int64()), + "a": pa.array([5, 6], pa.int64()), + "b": pa.array([3, 4], pa.int64()), + } + table = pa.table({name: columns[name] for name in layout}) + table = table.cast( + pa.schema([f.with_nullable(f.name == "x" and nullable_x) for f in table.schema]) + ) + return ArrowTableSource( + table, tag_columns=list(tag_order), tag_only_columns=roles, source_id="s" + ) + + +def _run( + layout: tuple[str, ...], tag_order: tuple[str, str], roles: Any +) -> tuple[list[str], pa.Schema]: + """Run the job; return the batch node's kept columns and its raw stored schema.""" + database = InMemoryArrowDatabase() + job = PipelineJob(name="narrower_bind_order", database=database) + with job: + Batch(batch_size=2)(_source(True, layout, tag_order, roles), label="batched") + job.nodes["batched"].attach_databases( + pipeline_database=database.at("log"), cache_mode=CacheMode.LOG + ) + slot = next(label for label in job.nodes if label != "batched") + job.bind(sources={slot: _source(False, ("x", "a", "b"), tag_order, roles)}) + job.run() + node = job.nodes["batched"] + kept = node.as_table(columns={"source": True}).column_names + stored = node.get_all_records(columns={"source": True}) + assert stored is not None + return kept, stored.schema + + +def _row_path(monkeypatch: pytest.MonkeyPatch) -> None: + """Make every source node hand on its rows rebuilt, as on ``main``.""" + + def execute(self: Any, *, observer: Any = None) -> Any: + if observer is not None: + observer.on_node_start(self.label, self.content_hash().to_string()) + out = StaticOutputOperatorPod._materialize_upstream( + list(self.iter_data()), self + ) # pyright: ignore[reportPrivateUsage] # the row path + if observer is not None: + observer.on_node_end(self.label, self.content_hash().to_string()) + return out + + monkeypatch.setattr(SourceNodeBase, "execute", execute) + + +def _outcome(layout: tuple[str, ...], tag_order: tuple[str, str], roles: Any) -> Any: + """The run's kept columns and raw stored schema, or the error it raised.""" + try: + return _run(layout, tag_order, roles) + except ValueError as error: + return (type(error), str(error)) + + +@pytest.mark.parametrize("roles", list(ROLES), ids=list(ROLES)) +@pytest.mark.parametrize("tag_order", [("a", "b"), ("b", "a")], ids=["a-b", "b-a"]) +@pytest.mark.parametrize( + "layout", list(itertools.permutations(("a", "b", "x"))), ids="".join +) +def test_a_narrower_bind_keeps_and_stores_as_the_row_path( + layout: tuple[str, ...], + tag_order: tuple[str, str], + roles: str, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Kept columns and the raw stored schema equal the row path's, in order. + + Where the row path raises (one data-tag of two, ITL-1366, a ``main`` bug), the + branch raises the same error. + """ + got = _outcome(layout, tag_order, ROLES[roles]) + with monkeypatch.context() as patch: + _row_path(patch) + expected = _outcome(layout, tag_order, ROLES[roles]) + if isinstance(expected[1], str): + assert got == expected + return + assert got[0] == expected[0] + assert got[1].equals(expected[1], check_metadata=True) diff --git a/tests/test_pipeline/test_node_protocols.py b/tests/test_pipeline/test_node_protocols.py index fbd08b867..23482ce18 100644 --- a/tests/test_pipeline/test_node_protocols.py +++ b/tests/test_pipeline/test_node_protocols.py @@ -3,6 +3,8 @@ from __future__ import annotations +from typing import Any + import pytest from unittest.mock import MagicMock @@ -15,6 +17,7 @@ is_operator_node, ) import pyarrow as pa +from orcapod.pipeline.observer import NoOpObserver from orcapod.core.sources import ArrowTableSource from orcapod.core.nodes.source_node import SourceJobNode from orcapod.channels import Channel @@ -200,14 +203,14 @@ def _make_source_node(self): def test_execute_returns_list(self): node = self._make_source_node() - result = node.execute() + result = list(node.execute().iter_data()) assert isinstance(result, list) assert len(result) == 3 def test_execute_populates_cached_results(self): """execute() on SourceJobNode returns correct data (no caching field).""" node = self._make_source_node() - result = node.execute() + result = list(node.execute().iter_data()) assert len(result) == 3 def test_execute_with_observer(self): @@ -234,7 +237,7 @@ def on_data_end(self, node_label, t, ip, op, cached): def test_execute_without_observer(self): """execute() works fine with no observer.""" node = self._make_source_node() - result = node.execute() + result = list(node.execute().iter_data()) assert len(result) == 3 @@ -312,32 +315,33 @@ def test_execute_with_observer(self): node = self._make_function_node() events = [] - class Obs: - def contextualize(self, *identity_path): + class Obs(NoOpObserver): + def contextualize(self, *identity_path: str) -> Obs: return self - def on_node_start(self, node_label, node_hash, **kwargs): + def on_node_start( + self, node_label: str, node_hash: str, tag_schema: Any = None + ) -> None: events.append(("node_start", node_label)) - def on_node_end(self, node_label, node_hash, **kwargs): + def on_node_end(self, node_label: str, node_hash: str) -> None: events.append(("node_end", node_label)) - def on_data_start(self, node_label, t, p): + def on_data_start(self, node_label: str, tag: Any, data: Any) -> None: events.append(("data_start",)) - def on_data_end(self, node_label, t, ip, op, cached): + def on_data_end( + self, + node_label: str, + tag: Any, + input_data: Any, + output_data: Any, + cached: bool, + ) -> None: events.append(("data_end", cached)) - def on_data_crash(self, node_label, t, p, exc): - pass - - def create_data_logger(self, t, p, **kwargs): - from orcapod.pipeline.observer import _NOOP_LOGGER - - return _NOOP_LOGGER - input_stream = node._input_stream - result = node.execute(input_stream, observer=Obs()) + result = list(node.execute(input_stream, observer=Obs()).iter_data()) assert len(result) == 2 assert events[0][0] == "node_start" @@ -348,7 +352,7 @@ def create_data_logger(self, t, p, **kwargs): def test_execute_without_observer(self): node = self._make_function_node() input_stream = node._input_stream - result = node.execute(input_stream) + result = list(node.execute(input_stream).iter_data()) assert len(result) == 2 values = sorted([pkt.as_dict()["result"] for _, pkt in result]) assert values == [2, 4] @@ -472,30 +476,26 @@ def test_execute_with_observer(self): node = self._make_join_node() events = [] - class Obs: - def contextualize(self, *identity_path): + class Obs(NoOpObserver): + def contextualize(self, *identity_path: str) -> Obs: return self - def on_node_start(self, node_label, node_hash, **kwargs): + def on_node_start( + self, node_label: str, node_hash: str, tag_schema: Any = None + ) -> None: events.append(("node_start", node_label)) - def on_node_end(self, node_label, node_hash, **kwargs): + def on_node_end(self, node_label: str, node_hash: str) -> None: events.append(("node_end", node_label)) - def on_data_start(self, node_label, t, p): - pass - - def on_data_end(self, node_label, t, ip, op, cached): - pass - - result = node.execute(*node._input_streams, observer=Obs()) + result = list(node.execute(*node._input_streams, observer=Obs()).iter_data()) assert len(result) == 2 assert events[0][0] == "node_start" assert events[1][0] == "node_end" def test_execute_without_observer(self): node = self._make_join_node() - result = node.execute(*node._input_streams) + result = list(node.execute(*node._input_streams).iter_data()) assert len(result) == 2 diff --git a/tests/test_pipeline/test_operator_node_async_readback.py b/tests/test_pipeline/test_operator_node_async_readback.py index 7e7189be4..345d738a6 100644 --- a/tests/test_pipeline/test_operator_node_async_readback.py +++ b/tests/test_pipeline/test_operator_node_async_readback.py @@ -287,7 +287,7 @@ def make_node() -> OperatorJobNode: ) sync_node, async_node = make_node(), make_node() - sync_rows = sync_node.execute(source) + sync_rows = list(sync_node.execute(source).iter_data()) async def run() -> list[tuple[TagProtocol, DataProtocol]]: """Drive the node's public channel interface and collect forwarded rows.""" diff --git a/tests/test_pipeline/test_rows_on_read.py b/tests/test_pipeline/test_rows_on_read.py new file mode 100644 index 000000000..2ffc76211 --- /dev/null +++ b/tests/test_pipeline/test_rows_on_read.py @@ -0,0 +1,1103 @@ +"""Outputs held as rows, built where a successor reads them (ITL-1347; Codex on PR #485). + +On every route where building a node's output from its whole table is not provably +``main``'s result, the node hands on its rows (``RowsOnRead``), built by ``main``'s row +path where the sync orchestrator gives them to a successor (``at_edge``). So the +order, the error and the moment it surfaces are ``main``'s: a narrower bind, a source +whose whole-table build is unavailable (its rows read once), a held node. A leaf +nobody reads is never built. +""" + +from __future__ import annotations + +from typing import Any + +import pyarrow as pa +import pytest + +from orcapod import PipelineJob +from orcapod.core.streams import ArrowTableStream +from orcapod.databases import InMemoryArrowDatabase +from orcapod.operators import Batch +from orcapod.pipeline.dag import OrcaDAG +from orcapod.pipeline.sync_orchestrator import SyncPipelineOrchestrator +from orcapod.sources import ArrowTableSource, DictSource +from orcapod.types import CacheMode +from tests.test_core.operators.test_row_built_form import ( + _NESTED, # pyright: ignore[reportPrivateUsage] # the shared provenance fixtures + _NodeEvents, # pyright: ignore[reportPrivateUsage] + _source_table, # pyright: ignore[reportPrivateUsage] + _with_source_x, # pyright: ignore[reportPrivateUsage] +) + +_UNCONVERTIBLE = pa.large_list(_NESTED) + + +def _unconvertible() -> ArrowTableStream: + """Tokens ``[None, [[]]]``: the whole-table build is unavailable, the rows raise.""" + return _with_source_x([[None, [[]]], [None, [[]]]], _UNCONVERTIBLE) + + +def _plain() -> DictSource: + return DictSource( + [{"k": 1, "x": 1}, {"k": 2, "x": 2}], + tag_columns=["k"], + tag_only_columns=True, + source_id="s", + ) + + +def test_a_fallback_source_reads_its_rows_once() -> None: + """A source whose whole-table build is unavailable: its rows are read once, when it + runs, and the successor's edge raises the rows' ``ArrowTypeError`` after the + source's end and before the successor starts, as on ``main``.""" + job = PipelineJob(name="read_once", database=InMemoryArrowDatabase()) + with job: + Batch(batch_size=2)( + _plain().select_data_columns(["x"], label="selected"), label="batched" + ) + source: Any = _unconvertible() + reads: list[int] = [] + read = source.iter_data + + def counted() -> Any: + reads.append(1) + return read() + + source.iter_data = counted + job.bind(sources={"s": source}) + observer = _NodeEvents() + with pytest.raises(pa.ArrowTypeError, match="Expected bytes"): + job.run(observer=observer) + assert len(reads) == 1 + assert ("end", "s") in observer.events + assert ("start", "selected") not in observer.events + + +def test_a_fallback_source_nobody_reads_completes() -> None: + """A source whose rows cannot be built, as a leaf of a direct sync run: it completes. + + ``main`` never rebuilt a leaf's rows; neither does the branch (``RowsOnRead``). + """ + job = PipelineJob(name="leaf", database=InMemoryArrowDatabase()) + with job: + _plain().select_data_columns(["x"], label="selected") + job.bind(sources={"s": _unconvertible()}) + dag: OrcaDAG[Any] = OrcaDAG() + dag.add_node(job.nodes["s"]) + observer = _NodeEvents() + SyncPipelineOrchestrator().run(dag, observer=observer, materialize_results=False) + assert observer.events == [("start", "s"), ("end", "s")] + + +def test_a_narrower_raw_bind_keeps_the_slots_system_tag_order() -> None: + """A raw stream whose system tags are record id then source id, bound narrower. + + ``main`` gives each row the slot's order (source id, then record id); so do the + kept and the raw stored tables (Codex on PR #485, round 3). + """ + from orcapod.system_constants import constants + + table = _source_table() + source_id = next(n for n in table.column_names if "source_id" in n) + record_id = next(n for n in table.column_names if "record_id" in n) + others = [n for n in table.column_names if n not in (source_id, record_id)] + reversed_pair = table.select([*others, record_id, source_id]) + raw = ArrowTableStream(reversed_pair, tag_columns=["k"]) + + database = InMemoryArrowDatabase() + job = PipelineJob(name="reversed_pair", database=database) + with job: + declared = DictSource( + [{"k": 1, "x": 1}, {"k": 2, "x": None}], + tag_columns=["k"], + tag_only_columns=True, + source_id="s", + ) + Batch(batch_size=2)(declared, label="batched") + job.nodes["batched"].attach_databases( + pipeline_database=database.at("log"), cache_mode=CacheMode.LOG + ) + job.bind(sources={"s": raw}) + job.run() + node = job.nodes["batched"] + kept = node.as_table(columns={"system_tags": True}).column_names + system_tags = [n for n in kept if n.startswith(constants.SYSTEM_TAG_PREFIX)] + assert ["source_id" in n for n in system_tags] == [True, False] + stored = node.get_all_records(columns={"system_tags": True}) + assert stored is not None + stored_tags = [ + n for n in stored.column_names if n.startswith(constants.SYSTEM_TAG_PREFIX) + ] + assert ["source_id" in n for n in stored_tags] == [True, False] + + +def test_a_narrower_bind_is_described_from_its_declared_schema() -> None: + """A narrower bind's description never places columns: its types are undeclared. + + With one data-tag among two tags (ITL-1366's input), the description does not + raise; ``arrow_types_declared`` is false (Codex on PR #485, round 3). + """ + table = pa.table( + { + "x": pa.array([1, 2], pa.int64()), + "k": pa.array([5, 6], pa.int64()), + "j": pa.array([3, 4], pa.int64()), + "y": pa.array([7.5, 8.5], pa.float64()), + } + ) + + def source(nullable_x: bool) -> ArrowTableSource: + fields = [f.with_nullable(f.name == "x" and nullable_x) for f in table.schema] + return ArrowTableSource( + table.cast(pa.schema(fields)), + tag_columns=["j", "k"], + tag_only_columns=("j",), + source_id="s", + ) + + job = PipelineJob(name="narrower_description", database=InMemoryArrowDatabase()) + with job: + source(True).select_data_columns(["y", "x"], label="selected") + slot = next(label for label in job.nodes if label != "selected") + job.bind(sources={slot: source(False)}) + node = job.nodes[slot] + schema = node.arrow_schema() + assert not node.arrow_types_declared + assert set(node.keys()[0]) <= set(schema.names) + + +def test_a_narrower_bind_channel_raises_as_its_rows_do() -> None: + """The source node's channel carries its rows: ITL-1366's input raises as on main. + + ``open_channel()`` reads the node's output, the rows built when read, which raise + the duplicate-column error ``main``'s row path raises. + """ + import asyncio + + table = pa.table( + { + "x": pa.array([1, 2], pa.int64()), + "k": pa.array([5, 6], pa.int64()), + "j": pa.array([3, 4], pa.int64()), + "y": pa.array([7.5, 8.5], pa.float64()), + } + ) + + def source(nullable_x: bool) -> ArrowTableSource: + fields = [f.with_nullable(f.name == "x" and nullable_x) for f in table.schema] + return ArrowTableSource( + table.cast(pa.schema(fields)), + tag_columns=["j", "k"], + tag_only_columns=("j",), + source_id="s", + ) + + job = PipelineJob(name="narrower_channel", database=InMemoryArrowDatabase()) + with job: + source(True).select_data_columns(["y", "x"], label="selected") + slot = next(label for label in job.nodes if label != "selected") + job.bind(sources={slot: source(False)}) + node: Any = job.nodes[slot] + with pytest.raises(ValueError, match="Duplicate column name"): + asyncio.run(node.open_channel().collect()) + + +def _replay_job(database: InMemoryArrowDatabase, *, with_successor: bool) -> Any: + """``source -> select x`` with the select node replaying from ``database``.""" + job = PipelineJob(name="replay_odd", database=InMemoryArrowDatabase()) + with job: + selected = _plain().select_data_columns(["x"], label="selected") + if with_successor: + Batch(batch_size=2)(selected, label="batched") + job.nodes["selected"].attach_databases( + pipeline_database=database, cache_mode=CacheMode.REPLAY + ) + return job + + +@pytest.mark.parametrize("with_successor", [False, True], ids=["leaf", "successor"]) +def test_replay_of_a_table_the_whole_table_build_cannot_use( + with_successor: bool, +) -> None: + """REPLAY of a stored table with unconvertible tokens hands on its rows. + + The node ends as usual; a leaf completes; a successor's edge raises the rows' + ``ArrowTypeError``, as ``main``'s row rebuild does (Codex on PR #485, round 3). + """ + logged = InMemoryArrowDatabase() + job = PipelineJob(name="replay_odd", database=InMemoryArrowDatabase()) + with job: + _plain().select_data_columns(["x"], label="selected") + node: Any = job.nodes["selected"] + node.attach_databases(pipeline_database=logged, cache_mode=CacheMode.LOG) + job.run() + path = node._stored_table_path # pyright: ignore[reportPrivateUsage] # the table to seed + stored = logged.get_all_records(path, record_id_column="__record_id") + assert stored is not None + position = stored.schema.get_field_index("_source_x") + odd = stored.set_column( + position, + pa.field("_source_x", _UNCONVERTIBLE, nullable=True), + pa.array([[None, [[]]]] * stored.num_rows, _UNCONVERTIBLE), + ) + seeded = InMemoryArrowDatabase() + seeded.add_records(path, odd, record_id_column="__record_id") + + replay = _replay_job(seeded, with_successor=with_successor) + observer = _NodeEvents() + if with_successor: + with pytest.raises(pa.ArrowTypeError, match="Expected bytes"): + replay.run(observer=observer) + assert ("end", "selected") in observer.events + assert ("start", "batched") not in observer.events + else: + replay.run(observer=observer) + assert ("end", "selected") in observer.events + + +# ── round 4: the boundary of the eager route, and the lazy output itself ────── + + +DELIVERED: list[int] = [] + + +def _deliver(x: int, ctx: Any) -> None: + DELIVERED.append(x) + + +def _leaf_run(job: PipelineJob, label: str) -> _NodeEvents: + """Run only ``label`` (a source node), as a leaf of a direct sync DAG.""" + dag: OrcaDAG[Any] = OrcaDAG() + dag.add_node(job.nodes[label]) + observer = _NodeEvents() + SyncPipelineOrchestrator().run(dag, observer=observer, materialize_results=False) + return observer + + +def test_a_bound_tap_stream_delivers_every_row_as_main_does() -> None: + """A side-effect stream bound to a slot is not a library source kind: its rows. + + The node iterates it as ``main`` did, delivering every row, and a leaf completes + (Codex on PR #485, round 4: the eager route read ``as_table()`` instead). + """ + from orcapod.side_effects import tap_pod + + tap: Any = tap_pod(_deliver) + DELIVERED.clear() + raw = _with_source_x([[None, [[]]], [None, [[]]]], _UNCONVERTIBLE) + tapped: Any = tap.process(raw) + job = PipelineJob(name="tap_bound", database=InMemoryArrowDatabase()) + with job: + _plain().select_data_columns(["x"], label="selected") + job.bind(sources={"s": tapped}) + observer = _leaf_run(job, "s") + assert DELIVERED == [1, 2] + assert observer.events == [("start", "s"), ("end", "s")] + + +@pytest.mark.parametrize( + "make", + [ + pytest.param(lambda: _plain().select_data_columns(["x"]), id="operator"), + pytest.param( + lambda: ArrowTableStream(_source_table(), tag_columns=["k"]), id="raw" + ), + ], +) +def test_a_bound_stream_that_is_not_a_source_kind_hands_on_its_rows(make: Any) -> None: + """Only a library source kind whose table is its rows (``TABLE_IS_ROWS``) is eager.""" + from orcapod.core.operators.static_output_pod import RowsOnRead + + job = PipelineJob(name="bound_kinds", database=InMemoryArrowDatabase()) + with job: + _plain().select_data_columns(["x"], label="selected") + job.bind(sources={"s": make()}) + assert isinstance(job.nodes["s"].execute(), RowsOnRead) + + +def test_a_library_source_kind_is_eager() -> None: + from orcapod.core.operators.static_output_pod import RowsOnRead + + job = PipelineJob(name="eager_kind", database=InMemoryArrowDatabase()) + with job: + _plain().select_data_columns(["x"], label="selected") + assert not isinstance(job.nodes["s"].execute(), RowsOnRead) + + +def test_an_empty_output_is_derived_at_the_edge( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A source with no row: its zero-row input is built where the successor reads it, + after the source has ended and before the successor starts, as ``main`` rebuilt + it (Codex on PR #485, round 4).""" + from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod + + field = pa.field("x", pa.int64(), nullable=False) + table = pa.Table.from_arrays( + [pa.array([], pa.int64()), pa.array([], pa.int64())], + schema=pa.schema([pa.field("k", pa.int64(), nullable=False), field]), + ) + job = PipelineJob(name="empty_edge", database=InMemoryArrowDatabase()) + with job: + ArrowTableSource(table, tag_columns=["k"], source_id="s").select_data_columns( + ["x"], label="selected" + ) + slot = next(label for label in job.nodes if label != "selected") + observer = _NodeEvents() + original = StaticOutputOperatorPod._materialize_upstream # pyright: ignore[reportPrivateUsage] # the row path, watched + + def watched(rows: Any, upstream: Any) -> Any: + observer.events.append(("build", str(upstream.label))) + return original(rows, upstream) + + monkeypatch.setattr( + StaticOutputOperatorPod, "_materialize_upstream", staticmethod(watched) + ) + job.run(observer=observer) + events = observer.events + built = events.index(("build", slot)) + assert events.index(("end", slot)) < built < events.index(("start", "selected")) + assert job.nodes["selected"].as_table().num_rows == 0 + + +def test_an_operator_with_an_empty_result_is_not_called_again() -> None: + """An empty result's zero-row form is derived at the edge, never by a second call. + + An operator that raises on empty input completes as a leaf, as on ``main`` + (Codex on PR #485, round 4). + """ + from orcapod.operators import SelectDataColumns + + calls: list[int] = [] + + class EmptyThenRaises(SelectDataColumns): + def unary_static_process(self, stream: Any) -> Any: + rows = stream.as_table().num_rows + calls.append(rows) + if rows == 0: + raise ValueError("cannot process empty input") + result: Any = super().unary_static_process(stream) + return result.polars_filter(x=-1) + + job = PipelineJob(name="empty_result", database=InMemoryArrowDatabase()) + with job: + EmptyThenRaises(["x"])(_plain(), label="emptied") + observer = _NodeEvents() + job.run(observer=observer) + assert ("end", "emptied") in observer.events + assert 0 not in calls + + +@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"]) +def test_returned_function_rows_keep_their_meta(asynchronous: bool) -> None: + """``node_outputs[node].iter_data()`` gives the node's own rows, meta included.""" + from orcapod import function_pod + from orcapod.pipeline import AsyncPipelineOrchestrator + + @function_pod(output_keys="y") + def plus(x: int) -> int: + return x + 1 + + job = PipelineJob(name="returned_rows", database=InMemoryArrowDatabase()) + with job: + plus.pod(_plain(), label="plus") + dag: OrcaDAG[Any] = OrcaDAG() + dag.add_edge(job.nodes["s"], job.nodes["plus"]) + orchestrator: Any = ( + AsyncPipelineOrchestrator() if asynchronous else SyncPipelineOrchestrator() + ) + result = orchestrator.run(dag) + rows = list(result.node_outputs[job.nodes["plus"]].iter_data()) + assert rows + assert all("__computed" in data.keys(columns={"meta": True}) for _, data in rows) + + +def test_a_lazy_output_is_described_and_opened_without_reading() -> None: + """Describing an unread output, or opening its channel, builds nothing. + + The first read of the channel raises what the rows' build raises (Codex on PR + #485, round 4). + """ + import asyncio + + from orcapod.core.operators.static_output_pod import RowsOnRead + from orcapod.protocols.core_protocols import StreamProtocol + + job = PipelineJob(name="lazy_out", database=InMemoryArrowDatabase()) + with job: + _plain().select_data_columns(["x"], label="selected") + job.bind(sources={"s": _unconvertible()}) + out: Any = job.nodes["s"].execute() + assert isinstance(out, RowsOnRead) + assert isinstance(out, StreamProtocol) + assert not out.arrow_types_declared + assert "x" in out.arrow_schema().names + channel = out.open_channel() + assert out._stream is None # pyright: ignore[reportPrivateUsage] # nothing built + with pytest.raises(pa.ArrowTypeError, match="Expected bytes"): + asyncio.run(channel.collect()) + + +# ── round 5 ────────────────────────────────────────────────────────────────── + + +def _subclass_overriding(member: str) -> type: + """An ``ArrowTableSource`` subclass that overrides ``member`` (reading as before).""" + from orcapod.core.sources import ArrowTableSource as Base + + def through(self: Any, *args: Any, **kwargs: Any) -> Any: + return getattr(super(cls, self), member)(*args, **kwargs) + + cls = type(f"Overrides_{member}", (Base,), {member: through}) + return cls + + +@pytest.mark.parametrize( + "member", + ["iter_data", "as_table", "__iter__", "async_iter_data", "keys", "output_schema"], +) +def test_a_subclass_that_overrides_a_reader_is_not_a_table_is_rows_kind( + member: str, +) -> None: + """``TABLE_IS_ROWS`` is not inherited past an override of how rows are read.""" + from orcapod.core.sources.base import table_is_rows + + table = _source_table().select(["k", "x"]) + cls = _subclass_overriding(member) + source = cls(table, tag_columns=["k"], tag_only_columns=True, source_id="s") + assert not table_is_rows(source) + plain = ArrowTableSource( + table, tag_columns=["k"], tag_only_columns=True, source_id="s" + ) + assert table_is_rows(plain) + # Exact, never by inspection: a subclass that overrides nothing is not proven. + subclass = type("Plain", (ArrowTableSource,), {}) + assert not table_is_rows( + subclass(table, tag_columns=["k"], tag_only_columns=True, source_id="s") + ) + + +def test_a_filtering_subclass_delivers_only_its_rows() -> None: + """A subclass whose ``iter_data`` filters is read through it, as on ``main``.""" + + class AboveTen(ArrowTableSource): + def iter_data(self) -> Any: + return (row for row in super().iter_data() if row[1]["x"] > 10) + + table = pa.table({"k": pa.array([1, 2]), "x": pa.array([10, 20])}) + job = PipelineJob(name="filtering", database=InMemoryArrowDatabase()) + with job: + ArrowTableSource( + table, tag_columns=["k"], tag_only_columns=True, source_id="s" + ).select_data_columns(["x"], label="selected") + job.bind( + sources={ + "s": AboveTen( + table, tag_columns=["k"], tag_only_columns=True, source_id="s" + ) + } + ) + job.run() + assert job.nodes["selected"].as_table()["x"].to_pylist() == [20] + + +def test_an_operator_result_keeps_its_own_column_order() -> None: + """A result laid out ``y, x`` against a prediction ``x, y`` is kept, stored and + handed on as ``y, x``, as ``main`` built it from the result's rows.""" + from orcapod.operators import SelectDataColumns + + class Reordered(SelectDataColumns): + def unary_static_process(self, stream: Any) -> Any: + out: Any = super().unary_static_process(stream) + table = out.as_table(columns={"source": True, "system_tags": True}) + names = [n for n in table.column_names if n not in ("x", "y")] + plain = [n for n in names if not n.startswith("_source_")] + source = ["_source_y", "_source_x"] + rest = [n for n in names if n.startswith("_source_") and n not in source] + return ArrowTableStream( + table.select([*plain, "y", "x", *source, *rest]), tag_columns=["k"] + ) + + database = InMemoryArrowDatabase() + job = PipelineJob(name="reordered", database=database) + with job: + source = DictSource( + [{"k": 1, "x": 1, "y": 2}, {"k": 2, "x": 3, "y": 4}], + tag_columns=["k"], + tag_only_columns=True, + source_id="s", + ) + Batch(batch_size=2)(Reordered(["x", "y"])(source, label="reordered"), label="b") + job.nodes["reordered"].attach_databases( + pipeline_database=database.at("log"), cache_mode=CacheMode.LOG + ) + job.run() + expected = ["k", "y", "x", "_source_y", "_source_x"] + node = job.nodes["reordered"] + assert node.as_table(columns={"source": True}).column_names == expected + stored = node.get_all_records(columns={"source": True}) + assert stored is not None + assert [n for n in stored.column_names if not n.startswith("__")] == expected + assert job.nodes["b"].as_table(columns={"source": True}).column_names == expected + + +# ── final check: the eager route is positive and exact ──────────────────────── + + +def _only_above_ten(rows: Any) -> Any: + return (row for row in rows if row[1]["x"] > 10) + + +class _FilteringStream(ArrowTableStream): + def iter_data(self) -> Any: + return _only_above_ten(super().iter_data()) + + +class _ReadsThroughAProperty(ArrowTableSource): + """Reads through a ``_stream`` property that hands on a filtering stream.""" + + @property + def _stream(self) -> Any: + return getattr(self, "saved_stream") + + @_stream.setter + def _stream(self, base: Any) -> None: + self.saved_stream = _FilteringStream( + base.as_table(columns={"source": True, "system_tags": True}), + tag_columns=["k"], + ) + + +def _bound_selection(source: Any) -> list[int]: + """Bind ``source`` to a slot feeding a selection; return what the sync run keeps.""" + table = pa.table({"k": pa.array([1, 2]), "x": pa.array([10, 20])}) + job = PipelineJob(name="exact", database=InMemoryArrowDatabase()) + with job: + ArrowTableSource( + table, tag_columns=["k"], tag_only_columns=True, source_id="s" + ).select_data_columns(["x"], label="selected") + job.bind(sources={"s": source}) + job.run() + return job.nodes["selected"].as_table()["x"].to_pylist() + + +@pytest.mark.parametrize("how", ["instance_reader", "property", "plain_subclass"]) +def test_only_an_exact_unshadowed_library_source_is_eager(how: str) -> None: + """An ``iter_data`` replaced on the instance and a ``_stream`` property both read + the rows the reader gives (``[20]``, as ``main``); a plain subclass is not proven + either, and gives ``main``'s rows (Codex on PR #485, final check).""" + from orcapod.core.sources.base import table_is_rows + + table = pa.table({"k": pa.array([1, 2]), "x": pa.array([10, 20])}) + kwargs: dict[str, Any] = { + "tag_columns": ["k"], + "tag_only_columns": True, + "source_id": "s", + } + if how == "instance_reader": + source: Any = ArrowTableSource(table, **kwargs) + read = source.iter_data + source.iter_data = lambda: _only_above_ten(read()) + expected = [20] + elif how == "property": + source = _ReadsThroughAProperty(table, **kwargs) + expected = [20] + else: + source = type("Plain", (ArrowTableSource,), {})(table, **kwargs) + expected = [10, 20] + assert not table_is_rows(source) + assert _bound_selection(source) == expected + + +def test_an_exact_library_source_is_eager() -> None: + """The exact class, with nothing replaced on the instance, takes the eager route.""" + from orcapod.core.sources.base import table_is_rows + + table = pa.table({"k": pa.array([1, 2]), "x": pa.array([10, 20])}) + source = ArrowTableSource( + table, tag_columns=["k"], tag_only_columns=True, source_id="s" + ) + source.as_table() + list(source.iter_data()) + assert table_is_rows(source) + assert _bound_selection(source) == [10, 20] + + +def _swapped(stream: Any, first: str, second: str, tags: list[str]) -> Any: + """``stream``'s table with ``first`` and ``second`` swapped, over ``tags``.""" + from orcapod.core.streams.base import ZERO_ROW_INPUT_COLUMNS + + table = stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS) + names = list(table.column_names) + a, b = names.index(first), names.index(second) + names[a], names[b] = names[b], names[a] + return ArrowTableStream(table.select(names), tag_columns=tags) + + +@pytest.mark.parametrize("replay", [False, True], ids=["log", "replay"]) +@pytest.mark.parametrize("layout", ["data", "tags"]) +def test_a_composed_operator_result_keeps_its_own_order( + layout: str, replay: bool +) -> None: + """An operator whose ``static_process`` returns ANOTHER operator's result keeps, + stores and hands on the order of the rows that result yields, to any depth: data + ``y, x`` (laid out so) and tags ``b, a`` (declared so), as ``main`` built them from + the rows; REPLAY of the stored table too (Codex on PR #485, final check).""" + from orcapod.operators import SelectDataColumns + + class Reordered(SelectDataColumns): + def unary_static_process(self, stream: Any) -> Any: + if layout == "data": + return _swapped(stream, "x", "y", ["a", "b"]) + return _swapped(stream, "x", "x", ["b", "a"]) + + class Composed(SelectDataColumns): + def unary_static_process(self, stream: Any) -> Any: + return Reordered(["x", "y"]).process(stream) + + database = InMemoryArrowDatabase() + job = PipelineJob(name="composed", database=database) + with job: + source = DictSource( + [{"a": 1, "b": 5, "x": 1, "y": 2}, {"a": 2, "b": 6, "x": 3, "y": 4}], + tag_columns=["a", "b"], + tag_only_columns=True, + source_id="s", + ) + Batch(batch_size=2)(Composed(["x", "y"])(source, label="composed"), label="b") + node: Any = job.nodes["composed"] + node.attach_databases( + pipeline_database=database.at("log"), cache_mode=CacheMode.LOG + ) + job.run() + if replay: + node.attach_databases( + pipeline_database=database.at("log"), cache_mode=CacheMode.REPLAY + ) + node.clear_cache() + job.run() + # ``main`` 321284ae, measured: the stored table keeps its tags in the slot's order, + # and REPLAY hands on the stored table's order. + data = ["a", "b", "y", "x", "_source_y", "_source_x"] + stored_tags = ["a", "b", "x", "y", "_source_x", "_source_y"] + result_tags = ["b", "a", "x", "y", "_source_x", "_source_y"] + if layout == "data": + kept, in_store = data, data + else: + kept, in_store = (stored_tags if replay else result_tags), stored_tags + assert node.as_table(columns={"source": True}).column_names == kept + stored = node.get_all_records(columns={"source": True}) + assert stored is not None + assert [n for n in stored.column_names if not n.startswith("__")] == in_store + assert job.nodes["b"].as_table(columns={"source": True}).column_names == kept + + +def test_a_result_of_another_stream_kind_takes_mains_row_path() -> None: + """A result that is not exactly an ``ArrowTableStream`` is read as ``main`` read + it: its rows (here, the ones its iterator yields), never its table.""" + from orcapod.core.streams.base import ZERO_ROW_INPUT_COLUMNS + from orcapod.operators import SelectDataColumns + + class Filtering(SelectDataColumns): + def unary_static_process(self, stream: Any) -> Any: + table = stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS) + return _FilteringStream(table, tag_columns=["k"]) + + database = InMemoryArrowDatabase() + job = PipelineJob(name="other_kind", database=database) + with job: + source = ArrowTableSource( + pa.table({"k": pa.array([1, 2]), "x": pa.array([10, 20])}), + tag_columns=["k"], + tag_only_columns=True, + source_id="s", + ) + Batch(batch_size=2)(Filtering(["x"])(source, label="filtered"), label="b") + node: Any = job.nodes["filtered"] + node.attach_databases( + pipeline_database=database.at("log"), cache_mode=CacheMode.LOG + ) + job.run() + assert node.as_table()["x"].to_pylist() == [20] + stored = node.get_all_records() + assert stored is not None + assert stored["x"].to_pylist() == [20] + assert job.nodes["b"].as_table()["x"].to_pylist() == [[20]] + + +# ── CodeRabbit on 352ce7b9: every wrapper proven, and the rows' data context ───── + + +@pytest.mark.parametrize("how", ["subclass", "instance_reader"]) +def test_a_dynamic_stream_that_is_not_proven_stops_the_chain(how: str) -> None: + """A ``DynamicPodStream`` subclass, or one whose ``iter_data`` is replaced on the + instance, inside an operator's result is read through its own rows (``[20]``), + as ``main`` read them: the chain is followed only through proven wrappers.""" + from orcapod.core.operators.static_output_pod import DynamicPodStream + from orcapod.operators import SelectDataColumns + + class FilteringDynamic(DynamicPodStream): + def iter_data(self) -> Any: + return _only_above_ten(super().iter_data()) + + class Inner(SelectDataColumns): + pass + + class Outer(SelectDataColumns): + def unary_static_process(self, stream: Any) -> Any: + if how == "subclass": + return FilteringDynamic(Inner(["x", "y"]), (stream,)) + inner: Any = Inner(["x", "y"]).process(stream) + read = inner.iter_data + inner.iter_data = lambda: _only_above_ten(read()) + return inner + + database = InMemoryArrowDatabase() + job = PipelineJob(name="unproven", database=database) + with job: + source = ArrowTableSource( + pa.table({"k": [1, 2], "x": [10, 20], "y": [1, 2], "z": [5, 6]}), + tag_columns=["k"], + tag_only_columns=True, + source_id="s", + ) + Batch(batch_size=2)(Outer(["x", "y"])(source, label="outer"), label="b") + node: Any = job.nodes["outer"] + node.attach_databases( + pipeline_database=database.at("log"), cache_mode=CacheMode.LOG + ) + job.run() + assert node.as_table()["x"].to_pylist() == [20] + stored = node.get_all_records() + assert stored is not None + assert stored["x"].to_pylist() == [20] + assert job.nodes["b"].as_table()["x"].to_pylist() == [[20]] + + +OTHER_CONTEXT = "std:v1:test-rows-on-read-other" + + +def test_a_result_in_another_data_context_hands_on_its_own_rows( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """An operator node over a stream of another data context hands on the result's + rows as ``main`` returned them (in their own data context); what it keeps is in its + own data context, as on ``main``.""" + import dataclasses + + import orcapod.contexts as contexts + from orcapod.core.nodes.operator_node import OperatorJobNode + from orcapod.operators import SelectDataColumns + from orcapod.system_constants import constants + + other = dataclasses.replace( + contexts.get_default_context(), context_key=OTHER_CONTEXT + ) + registry = contexts._get_registry() # pyright: ignore[reportPrivateUsage] # the test registers a second context + original = registry.get_context + + def get_context(key: Any = None) -> contexts.DataContext: # pyright: ignore[reportExplicitAny] # the registry's own argument + return other if key == OTHER_CONTEXT else original(key) + + monkeypatch.setattr(registry, "get_context", get_context) + + def stream() -> ArrowTableStream: + table = pa.table( + { + "k": ["a", "b"], + "x": [1, 2], + "y": [3, 4], + constants.CONTEXT_KEY: pa.array([OTHER_CONTEXT] * 2, pa.large_string()), + } + ) + return ArrowTableStream(table, tag_columns=["k"], data_context=other) + + node = OperatorJobNode(SelectDataColumns(["x"]), [stream()]) + output: Any = node.execute(stream()) + assert [data.data_context_key for _, data in output.iter_data()] == [ + OTHER_CONTEXT + ] * 2 + kept = node.as_table(columns={"context": True})[constants.CONTEXT_KEY] + assert kept.to_pylist() == [node.data_context_key] * 2 + + +# ── Codex round 7: the source's data context, system tags, retained lifetime ─── + + +def test_a_source_in_another_data_context_hands_on_its_own_rows() -> None: + """An exact ``CachedSource`` with its own data context: the rows a sync run returns + report the source's context, as ``main`` returned them, and the edge table is built + in the slot's context, as ``main`` rebuilt it.""" + import dataclasses + + from orcapod.contexts import get_default_context + from orcapod.core.nodes.source_node import SourceJobNode + from orcapod.core.operators.static_output_pod import at_edge + from orcapod.sources import CachedSource + from orcapod.system_constants import constants + + custom = dataclasses.replace(get_default_context(), context_key="review:custom") + inner = DictSource( + [{"k": 1, "x": 10}, {"k": 2, "x": 20}], + tag_columns=["k"], + tag_only_columns=True, + source_id="s", + data_context=custom, + ) + source = CachedSource( + inner, + cache_database=InMemoryArrowDatabase(), + source_id="cached", + data_context=custom, + ) + slot = SourceJobNode.from_stream(source) + dag: OrcaDAG[Any] = OrcaDAG() + dag.add_node(slot) + output: Any = SyncPipelineOrchestrator().run(dag).node_outputs[slot] + assert [ + (tag.data_context_key, data.data_context_key) + for tag, data in output.iter_data() + ] == [("review:custom", "review:custom")] * 2 + edge = at_edge(output).as_table(columns={"context": True}) + assert edge[constants.CONTEXT_KEY].to_pylist() == [slot.data_context_key] * 2 + + +class _AddSystemTag: + """``SelectDataColumns`` whose result carries one more system tag, ``int16``.""" + + @staticmethod + def operator(values: list[int | None], exact: bool) -> Any: + from orcapod.operators import SelectDataColumns + from orcapod.system_constants import constants + + class Unproven(ArrowTableStream): + """Reads as ``ArrowTableStream``; not proven: ``main``'s row path.""" + + kind = ArrowTableStream if exact else Unproven + + class AddSystemTag(SelectDataColumns): + def unary_static_process(self, stream: Any) -> Any: + out: Any = super().unary_static_process(stream) + table = out.as_table(columns={"source": True, "system_tags": True}) + table = table.append_column( + f"{constants.SYSTEM_TAG_PREFIX}region", + pa.array(values[: table.num_rows], pa.int16()), + ) + return kind(table, tag_columns=["k"]) + + return AddSystemTag(["x"]) + + +def _system_tag_job(values: list[int | None], exact: bool) -> tuple[Any, Any]: + database = InMemoryArrowDatabase() + job = PipelineJob(name="system_tag", database=database) + with job: + source = DictSource( + [{"k": 1, "x": 1}, {"k": 2, "x": 2}], + tag_columns=["k"], + tag_only_columns=True, + source_id="s", + ) + _AddSystemTag.operator(values, exact)(source, label="marked") + job.nodes["marked"].attach_databases( + pipeline_database=database.at("log"), cache_mode=CacheMode.LOG + ) + return job, database + + +def test_a_narrow_system_tag_is_stored_as_the_rows_give() -> None: + """A result over an exact ``ArrowTableStream`` with an ``int16`` system tag: kept, + stored and record-hashed as ``main``'s rows give it (``int64``, non-null), the + same as ``main``'s own row path (an unproven stream) gives.""" + from orcapod.system_constants import constants + + name = f"{constants.SYSTEM_TAG_PREFIX}region" + stored: dict[bool, Any] = {} + for exact in (True, False): + job, database = _system_tag_job([1, 2], exact) + job.run() + node: Any = job.nodes["marked"] + kept = node.as_table(columns={"system_tags": True}).schema.field(name) + assert (kept.type, kept.nullable) == (pa.int64(), False) + stored[exact] = database.at("log").get_all_records( + node._stored_table_path, # pyright: ignore[reportPrivateUsage] # the raw LOG table + record_id_column="_record_hash", + ) + for table in stored.values(): + field = table.schema.field(name) + assert (field.type, field.nullable) == (pa.int64(), False) + assert ( + stored[True]["_record_hash"].to_pylist() + == stored[False]["_record_hash"].to_pylist() + ) + + +def test_a_null_system_tag_raises_at_the_operator_as_main_does() -> None: + """With a null among its values, ``main``'s rows cannot make one table: the + operator raises ``ArrowInvalid`` before its end event, as on ``main``.""" + job, _ = _system_tag_job([None, 2], exact=True) + observer = _NodeEvents() + with pytest.raises(pa.ArrowInvalid): + job.run(observer=observer) + assert ("start", "marked") in observer.events + assert ("end", "marked") not in observer.events + + +def test_a_source_table_with_other_system_tags_is_not_its_rows() -> None: + """The source route's guard: an exact ``ArrowTableSource`` whose system tag is a + narrow integer has a table that is not its rows (they give ``int64``); a stock + source's system tags are what the rows give.""" + from orcapod.core.streams.base import system_tags_as_rows_give + + schema = pa.schema( + [ + pa.field("k", pa.int64(), nullable=False), + pa.field("x", pa.int64(), nullable=False), + pa.field("region", pa.int16(), nullable=False), + ] + ) + narrow = ArrowTableSource( + pa.Table.from_pylist( + [{"k": 1, "x": 10, "region": 1}, {"k": 2, "x": 20, "region": 2}], + schema=schema, + ), + tag_columns=["k"], + tag_only_columns=True, + system_tag_columns=["region"], + source_id="s", + ) + assert not system_tags_as_rows_give( + narrow.as_table(columns={"system_tags": True}).schema + ) + stock = _plain() + assert system_tags_as_rows_give( + stock.as_table(columns={"system_tags": True}).schema + ) + + +def test_a_retained_output_keeps_only_its_rows_once_read( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """With results retained, an output held as its rows drops its built stream once + every successor has read it (``main`` retained only the rows): no built stream + outlives the run, its rows are its own, and a later read builds the table again.""" + import gc + import weakref + + from orcapod import function_pod + from orcapod.core.operators.static_output_pod import ( + RowsOnRead, + StaticOutputOperatorPod, + ) + + @function_pod(output_keys="y") + def plus_one(x: int) -> int: + return x + 1 + + job = PipelineJob(name="retained", database=InMemoryArrowDatabase()) + with job: + computed: Any = plus_one.pod( + _plain().select_data_columns(["x"]), label="computed" + ) + computed.select_data_columns(["y"], label="second") + computed.select_data_columns(["y"], label="third") + + built: list[weakref.ref[Any]] = [] + original = StaticOutputOperatorPod._materialize_upstream # pyright: ignore[reportPrivateUsage] # the row path, watched + + def watched(*args: Any, **kwargs: Any) -> Any: + stream = original(*args, **kwargs) + built.append(weakref.ref(stream)) + return stream + + monkeypatch.setattr( + StaticOutputOperatorPod, "_materialize_upstream", staticmethod(watched) + ) + graph = job._node_graph # pyright: ignore[reportPrivateUsage] # the job's graph + assert graph is not None + result = SyncPipelineOrchestrator().run(graph) + output: Any = result.node_outputs[job.nodes["computed"]] + assert isinstance(output, RowsOnRead) + gc.collect() + assert built + assert all(ref() is None for ref in built) + assert len(list(output.iter_data())) == 2 + assert output.as_table().num_rows == 2 + + +# ── CodeRabbit on dd6b7cd4: one computation per run ─────────────────────────── + + +@pytest.mark.parametrize("mode", [CacheMode.OFF, CacheMode.LOG], ids=["off", "log"]) +@pytest.mark.parametrize("route", ["eager", "rows"]) +def test_an_operator_runs_once_over_an_undated_upstream( + route: str, mode: CacheMode +) -> None: + """Over an upstream with no modified time, every read of the operator's result + wrapper runs the operator again; the node reads its table, keys and rows from the + one computation it captured, so the operator runs once, as on ``main``.""" + from orcapod.core.nodes.operator_node import OperatorJobNode + from orcapod.operators import SelectDataColumns + + calls: list[int] = [] + + class Undated(ArrowTableStream): + @property + def last_modified(self) -> Any: + return None + + class Unproven(ArrowTableStream): + """Not proven: ``main``'s row path.""" + + class Counting(SelectDataColumns): + def unary_static_process(self, stream: Any) -> Any: + calls.append(1) + out: Any = super().unary_static_process(stream) + if route == "eager": + return out + table = out.as_table(columns={"source": True, "system_tags": True}) + return Unproven(table, tag_columns=["k"]) + + table = pa.table({"k": [1, 2], "x": [10, 20], "y": [1, 2]}) + upstream = Undated(table, tag_columns=["k"]) + node = OperatorJobNode( + Counting(["x"]), + [upstream], + pipeline_database=InMemoryArrowDatabase(), + cache_mode=mode, + ) + output: Any = node.execute(upstream) + assert len(list(output.iter_data())) == 2 + assert len(calls) == 1 + + +@pytest.mark.parametrize( + "kind", + [pa.time64("ns"), pa.decimal256(76, 40)], + ids=["time64ns", "decimal256"], +) +def test_a_lazy_output_describes_itself_without_converting_python_types( + kind: pa.DataType, +) -> None: + """Types with no Python type of their own are described from the node, never raised.""" + values = ( + pa.array([1, 2]).cast(kind) + if pa.types.is_decimal(kind) + else pa.array([1, 2], kind) + ) + base = pa.table({"k": pa.array([1, 2], pa.int64()), "x": values}) + base = base.cast(pa.schema([f.with_nullable(False) for f in base.schema])) + source = ArrowTableSource( + base, tag_columns=["k"], tag_only_columns=True, source_id="s" + ) + raw = ArrowTableStream( + source.as_table(columns={"source": True, "system_tags": True}), + tag_columns=["k"], + ) + job = PipelineJob(name="lazy_types", database=InMemoryArrowDatabase()) + with job: + source.select_data_columns(["x"], label="selected") + job.bind(sources={"s": raw}) + out: Any = job.nodes["s"].execute() + assert out.arrow_schema().field("x").type == kind diff --git a/tests/test_pipeline/test_stream_transport_equivalence.py b/tests/test_pipeline/test_stream_transport_equivalence.py new file mode 100644 index 000000000..7b9ff4193 --- /dev/null +++ b/tests/test_pipeline/test_stream_transport_equivalence.py @@ -0,0 +1,645 @@ +"""ITL-1347 stage 2: a node's output stream equals the stream built from its rows. + +Every job node's ``execute`` now returns its output stream, which the sync orchestrator +hands to every successor. Sources build it from their Arrow table and operators from +their result's Arrow table, with no rows made (the row-built form F, +``StaticOutputOperatorPod._row_built_form``). The governing rule of the spec +(``docs/dev/specs/itl-1347-job-table-transport.md``) is that nothing a run shows may +change. So each output stream must equal, in identity and byte for byte, the stream the +orchestrator built before stage 2 from the same node's rows +(``_materialize_upstream(rows, node)``): + +- L2 (sources): rows are the source node's ``iter_data()``; +- L1 (operators): rows are the operator's result's ``iter_data()``, or the stored + stream's under ``REPLAY``; +- L0 (function and side-effect nodes): rows are the output stream's own rows; +- L5 (held nodes): a held node's stream equals the one built from its rows; +- L7: every node's declared ``arrow_schema()`` equals the schema of its output. + +The job uses every operator kind over several tag orders, table layouts and tag roles. +These tests are about the hand-off between nodes, so they wrap the nodes' ``execute``. +""" + +from __future__ import annotations + +import subprocess +import sys +import warnings +from collections.abc import Iterator +from pathlib import Path +from typing import Any + +import pyarrow as pa +import pytest + +from orcapod import PipelineJob, function_pod, tap_pod +from orcapod.core.nodes.function_node import FunctionJobNode +from orcapod.core.nodes.operator_node import OperatorJobNode +from orcapod.core.nodes.source_node import SourceNodeBase +from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod, at_edge +from orcapod.core.streams.base import ZERO_ROW_INPUT_COLUMNS +from orcapod.databases import InMemoryArrowDatabase +from orcapod.errors import ProvisionalHashWarning +from orcapod.pipeline import AsyncPipelineOrchestrator +from orcapod.pipeline.observer import NoOpObserver +from orcapod.operators import Batch, MergeJoin, Rejoin, SelectDataColumns +from orcapod.side_effects import SideEffectJobNode +from orcapod.system_constants import constants +from orcapod.types import CacheMode +from tests.test_core.operators.several_items import ( + MAIN, + P, + Q, + Arrangement, + arrangements, + make_source, +) + +ALL_COLUMNS = { + "meta": True, + "source": True, + "system_tags": True, + "context": True, + "content_hash": True, +} + + +@function_pod(output_keys="d1_doubled") +def doubled(d1: int) -> int: + return 2 * d1 + + +@tap_pod +def noted(d1_doubled: int, ctx: Any) -> None: + return None + + +def build_job(arrangement: Arrangement, database: Any = None) -> Any: + """A job in which every operator kind, a function node and a side effect run.""" + main = make_source(MAIN, arrangement) + partner_p = make_source(P) + partner_q = make_source(Q) + job = PipelineJob( + name="stream_transport", database=database or InMemoryArrowDatabase() + ) + with job: + joined = main.join(partner_p, label="joined") + mapped = joined.map_data({"p1": "p1_renamed"}, label="mapped") + no_nulls = mapped.drop_nulls(["d2"], label="no_nulls") + no_nulls.select_data_columns(["d1", "p1_renamed"], label="after_no_nulls") + main.group_by(["t1"], label="grouped").select_data_columns( + ["d1"], label="after_grouped" + ) + main.select_data_columns(["d1"]).batch(batch_size=2, label="batched") + tagged = main.add_tags(k=1, label="tagged") + twice = doubled.pod(tagged.select_data_columns(["d1"]), label="doubled") + noted_stream: Any = noted + noted_stream(twice, label="noted") + main.semi_join(partner_q, label="semi").select_data_columns( + ["d3"], label="after_semi" + ) + MergeJoin()( + main.select_data_columns(["d1"]), + partner_p.map_data({"p1": "d1"}).select_data_columns(["d1"]), + ).select_data_columns(["d1"], label="after_merged") + Rejoin()( + main.select_data_columns(["d1"]), main.select_data_columns(["d3"]) + ).select_data_columns(["d1"], label="after_rejoined") + main.polars_filter(d1=999, label="nothing").select_data_columns( + ["d1"], label="after_nothing" + ) + return job + + +def _identity(stream: Any) -> tuple[Any, ...]: + return ( + type(stream), + stream.producer, + tuple(id(u) for u in stream.upstreams), + stream.pipeline_hash(), + stream.content_hash(), + stream.keys(), + stream.output_schema(), + stream.data_context_key, + ) + + +def assert_same_stream(got: Any, expected: Any) -> None: + """Equal identity, and equal tables byte for byte (every column group). + + ``got`` is taken as a successor receives it (``at_edge``: an output held as its rows + is built there). + """ + got = at_edge(got) + expected = at_edge(expected) + assert _identity(got) == _identity(expected) + got_table = got.as_table(columns=ALL_COLUMNS).combine_chunks() + expected_table = expected.as_table(columns=ALL_COLUMNS).combine_chunks() + assert got_table.schema.equals(expected_table.schema, check_metadata=True) + assert got_table.equals(expected_table, check_metadata=True) + + +def _rebuilt(rows: list[Any], node: Any) -> Any: + return StaticOutputOperatorPod._materialize_upstream(rows, node) # pyright: ignore[reportPrivateUsage] # the path before stage 2 + + +@pytest.fixture +def outputs(monkeypatch: pytest.MonkeyPatch) -> Iterator[dict[str, Any]]: + """Wrap every node kind's ``execute``; check each output against the row path.""" + seen: dict[str, Any] = {} + + source_execute = SourceNodeBase.execute + + def source(self: Any, **kwargs: Any) -> Any: + out = source_execute(self, **kwargs) + assert_same_stream(out, _rebuilt(list(self.iter_data()), self)) # L2 + seen[self.label] = out + return out + + operator_execute = OperatorJobNode.execute + + def operator(self: Any, *inputs: Any, **kwargs: Any) -> Any: + cached = self.get_cached_output() + if cached is not None: + rows = list(cached.iter_data()) + else: + rows = list(self._operator.process(*inputs).iter_data()) # pyright: ignore[reportPrivateUsage] # the operator's own result, as before stage 2 + out = operator_execute(self, *inputs, **kwargs) + assert_same_stream(out, _rebuilt(rows, self)) # L1 + seen[self.label] = out + return out + + def by_construction(original: Any) -> Any: + def execute(self: Any, *args: Any, **kwargs: Any) -> Any: + out = original(self, *args, **kwargs) + assert_same_stream(out, _rebuilt(list(out.iter_data()), self)) # L0 + seen[self.label] = out + return out + + return execute + + monkeypatch.setattr(SourceNodeBase, "execute", source) + monkeypatch.setattr(OperatorJobNode, "execute", operator) + monkeypatch.setattr( + FunctionJobNode, "execute", by_construction(FunctionJobNode.execute) + ) + monkeypatch.setattr( + SideEffectJobNode, "execute", by_construction(SideEffectJobNode.execute) + ) + yield seen + + +def _run(job: Any) -> None: + with warnings.catch_warnings(): + warnings.simplefilter("ignore", ProvisionalHashWarning) + job.run() + + +@pytest.mark.parametrize("arrangement", arrangements(MAIN), ids=lambda a: a.id) +def test_every_output_stream_equals_the_row_rebuild( + arrangement: Arrangement, outputs: dict[str, Any] +) -> None: + with warnings.catch_warnings(): + warnings.simplefilter("ignore", ProvisionalHashWarning) + job = build_job(arrangement) + _run(job) + assert {"joined", "nothing", "doubled", "noted", "semi", "batched"} <= set(outputs) + + +def test_a_replayed_operator_output_equals_the_row_rebuild( + outputs: dict[str, Any], +) -> None: + """REPLAY hands on the stored rows' stream, equal to the one built from them.""" + store = InMemoryArrowDatabase() + with warnings.catch_warnings(): + warnings.simplefilter("ignore", ProvisionalHashWarning) + job = build_job(arrangements(MAIN)[0], store) + node = job.nodes["joined"] + node.attach_databases( + pipeline_database=store.at("replay"), cache_mode=CacheMode.LOG + ) + _run(job) + node.attach_databases( + pipeline_database=store.at("replay"), cache_mode=CacheMode.REPLAY + ) + node.clear_cache() + outputs.clear() + _run(job) + assert "joined" in outputs + + +def test_a_held_node_hands_on_the_stream_built_from_its_rows( + outputs: dict[str, Any], +) -> None: + """L5: a second run holds every node but one; held streams feed it as before.""" + with warnings.catch_warnings(): + warnings.simplefilter("ignore", ProvisionalHashWarning) + job = build_job(arrangements(MAIN)[0]) + _run(job) + job.nodes["noted"].clear_cache() + outputs.clear() + _run(job) + # Only the cleared side effect ran; its input came from the held function node. + assert set(outputs) == {"noted"} + + +def _without_exceptions(schema: pa.Schema) -> list[tuple[str, Any, bool, Any]]: + """Fields in order as (name, type, nullable, metadata), the spec's exceptions applied. + + Decided by the values of a complete table, not by the description: a system-tag or + source-info field's flag (stated nullable) and a source-info field's type (left out). + A ``null`` column is ``large_string`` in rows (ITL-1319). Column order counts on the + sync path (Codex on PR #485). + """ + prefixes = (constants.SYSTEM_TAG_PREFIX, constants.SOURCE_PREFIX) + return [ + ( + field.name, + None + if field.name.startswith(constants.SOURCE_PREFIX) + else pa.large_string() + if pa.types.is_null(field.type) + else field.type, + True if field.name.startswith(prefixes) else field.nullable, + field.metadata, + ) + for field in schema + ] + + +def _tag_schema_out_of_key_order(arrangement: Arrangement) -> bool: + """Whether the source's tag schema lists its tags in another order than its keys. + + ITL-1365: ``ArrowTableStream`` builds its tag schema in the table's layout order, + while its keys and rows follow the declared tag order; an operator predicts its + keys from that schema, so its ``arrow_schema()`` lists the tags in the layout + order and its rows do not. + """ + source = make_source(MAIN, arrangement) + return tuple(source.output_schema()[0]) != tuple(source.keys()[0]) + + +def _l7_arrangements() -> list[Any]: + return [ + pytest.param( + arrangement, + id=arrangement.id, + marks=pytest.mark.xfail( + strict=True, + raises=AssertionError, + reason="ITL-1365: a tag schema in layout order, keys in declared order", + ), + ) + if _tag_schema_out_of_key_order(arrangement) + else pytest.param(arrangement, id=arrangement.id) + for arrangement in arrangements(MAIN)[::4] + ] + + +@pytest.mark.parametrize("arrangement", _l7_arrangements()) +def test_declared_arrow_schema_equals_the_output( + arrangement: Arrangement, outputs: dict[str, Any] +) -> None: + """L7: ``arrow_schema()`` of every node equals the schema of its output stream.""" + with warnings.catch_warnings(): + warnings.simplefilter("ignore", ProvisionalHashWarning) + job = build_job(arrangement) + _run(job) + for label, stream in outputs.items(): + node = job.nodes[label] + output = stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS) + assert _without_exceptions(node.arrow_schema()) == _without_exceptions( + output.schema + ), label + assert node.arrow_types_declared, label + + +def test_a_loaded_job_describes_its_nodes( + tmp_path: Path, outputs: dict[str, Any] +) -> None: + """L7 for a loaded job: each loaded node's ``arrow_schema()`` equals its output. + + A loaded node describes itself from the Arrow type texts its saved file holds + (ITL-640). The job is run and saved in another process, so that the loaded job + holds no run of this process. + """ + script = ( + "import sys, warnings\n" + "from pathlib import Path\n" + "from orcapod.databases import DeltaTableDatabase\n" + "from tests.test_core.operators.several_items import MAIN, arrangements\n" + "from tests.test_pipeline.test_stream_transport_equivalence import build_job\n" + "warnings.simplefilter('ignore')\n" + "root = Path(sys.argv[1])\n" + "job = build_job(arrangements(MAIN)[0], DeltaTableDatabase(root / 'store'))\n" + "job.run()\n" + "job.save(root / 'job.json')\n" + ) + repository = Path(__file__).resolve().parents[2] + subprocess.run( + [sys.executable, "-c", script, str(tmp_path)], check=True, cwd=repository + ) + with warnings.catch_warnings(): + warnings.simplefilter("ignore", ProvisionalHashWarning) + loaded = PipelineJob.load(tmp_path / "job.json") + # In-memory sources are not saved: bind them again. + loaded.bind( + sources={ + "s": make_source(MAIN, arrangements(MAIN)[0]), + "p": make_source(P), + "q": make_source(Q), + } + ) + loaded.run(load_only=True) + assert {"joined", "doubled", "noted", "semi", "batched"} <= set(outputs) + for label, stream in outputs.items(): + node = loaded.nodes[label] + output = stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS) + assert _without_exceptions(node.arrow_schema()) == _without_exceptions( + output.schema + ), label + assert node.arrow_types_declared, label + + +def _poller(fetched_order: tuple[str, ...]) -> Any: + """A ``PollingSource`` declaring tags ``k, j`` and data ``b, a``. + + It fetches a table with its columns in ``fetched_order``: a valid source whose + declared order is not its rows' (Codex on PR #485). + """ + from orcapod.core.sources import PollingSource + from tests.test_hashing.test_logical_type_forms import ( + _TableImpl, # pyright: ignore[reportPrivateUsage] # the one test polling implementation + ) + + columns = { + "k": pa.array(["1", "2"], pa.large_string()), + "j": pa.array(["x", "y"], pa.large_string()), + "a": pa.array([1, 2], pa.int64()), + "b": pa.array([3, 4], pa.int64()), + } + declared = pa.schema( + [pa.field(name, columns[name].type, False) for name in ("k", "j", "b", "a")] + ) + fetched = pa.table({name: columns[name] for name in fetched_order}) + fetched = fetched.cast(pa.schema([f.with_nullable(False) for f in fetched.schema])) + return PollingSource( + _TableImpl(fetched, declared), + tag_columns=["k", "j"], + record_id_columns=["k", "j"], + source_id="poller", + ) + + +@pytest.mark.filterwarnings("ignore::orcapod.errors.ProvisionalHashWarning") +@pytest.mark.parametrize( + "fetched_order", + [("j", "k", "a", "b"), ("k", "j", "b", "a"), ("k", "b", "j", "a")], + ids="-".join, +) +def test_a_poller_fetching_in_another_order_hands_on_its_rows( + fetched_order: tuple[str, ...], outputs: dict[str, Any] +) -> None: + """L2 for a poller whose fetched column order differs from its declared order. + + The source node's output equals its rows rebuilt (checked by ``outputs``), and the + operator after it keeps and stores its columns in the rows' order, as on ``main``. + """ + # Built before the job captures: importing the polling implementation's module + # inside ``with job`` would capture the sources that module builds. + poller = _poller(fetched_order) + database = InMemoryArrowDatabase() + job = PipelineJob(name="poller_order", database=database) + with job: + SelectDataColumns(["a", "b"])(poller, label="selected") + job.nodes["selected"].attach_databases( + pipeline_database=database.at("log"), cache_mode=CacheMode.LOG + ) + _run(job) + node = job.nodes["selected"] + rows_order = [ + *job.nodes["selected"].keys()[0], + *(name for name in fetched_order if name in ("a", "b")), + ] + source_order = [f"{constants.SOURCE_PREFIX}{n}" for n in rows_order[2:]] + kept = node.as_table(columns={"source": True}).column_names + assert kept == [*rows_order, *source_order] + stored = node.get_all_records(columns={"source": True}) + assert stored is not None + assert [name for name in stored.column_names if not name.startswith("__")] == [ + *rows_order, + *source_order, + ] + assert "poller" in outputs + + +@function_pod(output_keys="z") +def plus_one(d1_doubled: int) -> int: + return d1_doubled + 1 + + +class _ClearsOnRunStart(NoOpObserver): + """Clears ``node`` when the run starts and counts ``label``'s data starts.""" + + def __init__(self, node: Any, label: str) -> None: + self._node = node + self._label = label + self.data_starts = 0 + + def contextualize(self, *identity_path: str) -> _ClearsOnRunStart: + return self + + def on_run_start(self, run_id: str, pipeline_uri: str = "") -> None: + self._node.clear_cache() + + def on_data_start(self, node_label: str, tag: Any, data: Any) -> None: + if node_label == self._label: + self.data_starts += 1 + + +def test_an_async_held_node_sends_the_rows_the_plan_took() -> None: + """The async run sends a held node's rows as planned, not as read again later. + + An observer clears the held node when the run starts; the rows the plan took still + feed the node after it, as on ``main`` (Codex on PR #485). + """ + from orcapod.sources import DictSource + + job = PipelineJob(name="held_snapshot", database=InMemoryArrowDatabase()) + with job: + source = DictSource( + [{"k": i, "d1": i} for i in range(3)], + tag_columns=["k"], + tag_only_columns=True, + source_id="s", + ) + plus_one.pod(doubled.pod(source, label="twice"), label="plus") + job.run() + job.nodes["plus"].clear_cache() + observer = _ClearsOnRunStart(job.nodes["twice"], "plus") + summary = job.run(orchestrator=AsyncPipelineOrchestrator(), observer=observer) + assert summary.nodes["twice"].held == 3 + assert observer.data_starts == 3 + + +@pytest.mark.filterwarnings("ignore::orcapod.errors.ProvisionalHashWarning") +def test_describing_a_poller_that_has_not_polled_reads_nothing() -> None: + """L7: ``arrow_schema()`` of a poller that has not polled never fetches. + + It answers from the declared schema, the same every time, with each data column's + source info, and ``arrow_types_declared`` stays false (Codex on PR #485). + """ + from orcapod.core.sources import PollingSource + from orcapod.types import Schema + from tests.test_hashing.test_logical_type_forms import ( + _TableImpl, # pyright: ignore[reportPrivateUsage] # the one test polling implementation + ) + + fetches: list[int] = [] + + class Counting(_TableImpl): + async def fetch(self, cursor: Any = None) -> Any: + fetches.append(1) + return await super().fetch(cursor) + + def schema(self) -> Any: + return Schema({"k": str, "a": int, "b": int}) + + table = pa.table( + { + "k": pa.array(["1"], pa.large_string()), + "a": pa.array([1]), + "b": pa.array([2]), + } + ) + poller = PollingSource( + Counting(table, table.schema), + tag_columns=["k"], + record_id_columns=["k"], + source_id="unpolled", + ) + first = poller.arrow_schema() + second = poller.arrow_schema() + assert fetches == [] + assert first.equals(second, check_metadata=True) + assert [n for n in first.names if n.startswith(constants.SOURCE_PREFIX)] == [ + "_source_a", + "_source_b", + ] + assert not poller.arrow_types_declared + + +@pytest.mark.xfail( + strict=True, + raises=AssertionError, + reason="ITL-1365: a tag schema in layout order, keys in declared order", +) +def test_an_operator_stream_declares_its_tags_in_its_rows_order() -> None: + """A plain operator stream's ``arrow_schema()`` lists its tags as its rows do. + + Tags declared ``b, a`` over a table laid out ``a, b`` (Codex on PR #485). + """ + from orcapod.core.sources import ArrowTableSource + + table = pa.table( + { + "a": pa.array([1, 2]), + "b": pa.array([3, 4]), + "w": pa.array([5, 6]), + "x": pa.array([7, 8]), + } + ) + source = ArrowTableSource( + table, tag_columns=["b", "a"], tag_only_columns=True, source_id="s" + ) + stream = SelectDataColumns(["x"])(source) + built, _, _ = StaticOutputOperatorPod._rows_to_table(list(stream.iter_data())) # pyright: ignore[reportPrivateUsage] # the rows' order + assert stream.arrow_schema().names[:2] == built.column_names[:2] + + +@pytest.mark.filterwarnings("ignore::orcapod.errors.ProvisionalHashWarning") +def test_a_poller_that_fetched_describes_its_rows_order() -> None: + """L7: after a fetch in another order than declared, the description follows the rows. + + A poller declaring ``k, j, b, a`` that fetched ``j, k, a, b`` lists its data as its + rows do (Codex on PR #485). + """ + poller = _poller(("j", "k", "a", "b")) + rows = list(poller.iter_data()) + built, _, _ = StaticOutputOperatorPod._rows_to_table(rows) # pyright: ignore[reportPrivateUsage] # the rows' order + assert poller.arrow_types_declared + assert _without_exceptions(poller.arrow_schema()) == _without_exceptions( + built.schema + ) + + +def test_a_value_decided_source_info_depth_is_a_named_exception() -> None: + """L7: ``Batch`` over null list tokens; the description and the rows agree but for it. + + The rows give ``[None, None]`` one list level (``large_list``); the + description states the declared token type. A source-info type is decided by the + values of a complete table and is one of the description's named exceptions. + """ + from orcapod.core.streams import ArrowTableStream + from orcapod.sources import DictSource + + table = DictSource( + [{"k": 1, "x": 1}, {"k": 2, "x": 2}], + tag_columns=["k"], + tag_only_columns=True, + source_id="s", + ).as_table(columns={"source": True, "system_tags": True}) + position = table.schema.get_field_index("_source_x") + strings = pa.large_list(pa.large_string()) + raw = ArrowTableStream( + table.set_column( + position, + pa.field("_source_x", strings, nullable=True), + pa.array([None, None], strings), + ), + tag_columns=["k"], + ) + batched = Batch(batch_size=2)(raw) + built, _, _ = StaticOutputOperatorPod._rows_to_table(list(batched.iter_data())) # pyright: ignore[reportPrivateUsage] # the rows + declared = batched.arrow_schema() + assert declared.field("_source_x").type != built.schema.field("_source_x").type + assert _without_exceptions(declared) == _without_exceptions(built.schema) + + +@pytest.mark.filterwarnings("ignore::orcapod.errors.ProvisionalHashWarning") +def test_describing_an_undeclared_poller_that_has_not_polled_reads_nothing() -> None: + """L7: a poller with no declared schema is described with no column, and not polled. + + Its columns are known only from rows; the description never fetches, its modified + time does not move and ``arrow_types_declared`` stays false (Codex on PR #485). + """ + from orcapod.core.sources import PollingSource + from tests.test_hashing.test_logical_type_forms import ( + _TableImpl, # pyright: ignore[reportPrivateUsage] # the one test polling implementation + ) + + fetches: list[int] = [] + + class Undeclared(_TableImpl): + async def fetch(self, cursor: Any = None) -> Any: + fetches.append(1) + return await super().fetch(cursor) + + def schema(self) -> Any: + return None + + table = pa.table( + {"k": pa.array(["1"], pa.large_string()), "a": pa.array([1], pa.int64())} + ) + poller = PollingSource( + Undeclared(table, table.schema), + tag_columns=["k"], + record_id_columns=["k"], + source_id="undeclared", + ) + modified = poller.last_modified + assert poller.arrow_schema() == pa.schema([]) + assert poller.arrow_schema() == pa.schema([]) + assert fetches == [] + assert poller.last_modified == modified + assert not poller.arrow_types_declared diff --git a/tests/test_pipeline/test_sync_orchestrator.py b/tests/test_pipeline/test_sync_orchestrator.py index 4f334c709..ffd2c7907 100644 --- a/tests/test_pipeline/test_sync_orchestrator.py +++ b/tests/test_pipeline/test_sync_orchestrator.py @@ -12,6 +12,7 @@ from orcapod.core.sources import ArrowTableSource from orcapod.databases import InMemoryArrowDatabase from orcapod.pipeline import AsyncPipelineOrchestrator +from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod from orcapod.pipeline.sync_orchestrator import SyncPipelineOrchestrator from orcapod.pipeline.job import PipelineJob @@ -337,7 +338,7 @@ def test_materialized_stream_has_same_pipeline_hash(self): ) buf = list(node.iter_data()) - stream = SyncPipelineOrchestrator._materialize_as_stream(buf, node) + stream = StaticOutputOperatorPod._materialize_upstream(buf, node) assert stream.pipeline_hash() == node.pipeline_hash() def test_materialized_stream_has_same_content_hash(self): @@ -356,7 +357,7 @@ def test_materialized_stream_has_same_content_hash(self): op_node.run() buf = list(op_node.iter_data()) - stream = SyncPipelineOrchestrator._materialize_as_stream(buf, op_node) + stream = StaticOutputOperatorPod._materialize_upstream(buf, op_node) assert stream.content_hash() == op_node.content_hash() def test_materialized_stream_preserves_system_tags(self): @@ -371,7 +372,7 @@ def test_materialized_stream_preserves_system_tags(self): op_node.run() buf = list(op_node.iter_data()) - stream = SyncPipelineOrchestrator._materialize_as_stream(buf, op_node) + stream = StaticOutputOperatorPod._materialize_upstream(buf, op_node) expected_tag_schema = op_node.output_schema(columns={"system_tags": True})[0] actual_tag_schema = stream.output_schema(columns={"system_tags": True})[0] diff --git a/tests/test_pipeline/test_system_tag_run_stability.py b/tests/test_pipeline/test_system_tag_run_stability.py index 48c50565c..19a757caf 100644 --- a/tests/test_pipeline/test_system_tag_run_stability.py +++ b/tests/test_pipeline/test_system_tag_run_stability.py @@ -27,7 +27,6 @@ from orcapod.core.sources.arrow_table_source import ArrowTableSource from orcapod.databases import DeltaTableDatabase from orcapod.pipeline.job import PipelineJob -from orcapod.pipeline.sync_orchestrator import SyncPipelineOrchestrator from orcapod.side_effects import SideEffectPod, sink_pod Key = tuple[tuple[str, Any], ...] @@ -148,8 +147,8 @@ def test_operator_materialize_to_stream(self) -> None: rows = stream.as_table().to_pylist() assert rows == [{"a": 1, "b": 2, "v": 10}, {"a": 3, "b": 4, "v": 20}] - def test_orchestrator_materialize_as_stream(self) -> None: - """The orchestrator materializer emits rows in the first row's column order.""" + def test_materialize_upstream_keeps_first_row_column_order(self) -> None: + """The upstream materializer emits rows in the first row's column order.""" rows = _rows_with_swapped_tag_order() # The rebuilt stream takes the upstream's data context (ITL-1080) and, for an # upstream with no producer, its pipeline hash (ITL-1094): here a plain @@ -162,7 +161,10 @@ def test_orchestrator_materialize_as_stream(self) -> None: rows ).pipeline_hash, ) - stream = SyncPipelineOrchestrator._materialize_as_stream(rows, upstream) + stream = StaticOutputOperatorPod._materialize_upstream( + rows, + upstream, # pyright: ignore[reportArgumentType] # a stand-in upstream: the attributes the materializer reads + ) rows = stream.as_table().to_pylist() assert rows == [{"a": 1, "b": 2, "v": 10}, {"a": 3, "b": 4, "v": 20}] diff --git a/tests/test_pipeline/test_tag_table_source_info.py b/tests/test_pipeline/test_tag_table_source_info.py index 094b66702..048b4d47d 100644 --- a/tests/test_pipeline/test_tag_table_source_info.py +++ b/tests/test_pipeline/test_tag_table_source_info.py @@ -32,12 +32,13 @@ from orcapod.core.function_pod import FunctionPod from orcapod.core.nodes.function_node import FunctionJobNode from orcapod.core.operators import SelectDataColumns -from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod +from tests.test_core.operators.test_materialize_source_info import ( + _broadcast_row_zero, # pyright: ignore[reportPrivateUsage] # the one re-creation of the pre-fix broadcast +) from orcapod.core.sources import ArrowTableSource from orcapod.databases import DeltaTableDatabase, InMemoryArrowDatabase from orcapod.pipeline import AsyncPipelineOrchestrator from orcapod.pipeline.job import PipelineJob -from orcapod.protocols.core_protocols import DataProtocol, TagProtocol from orcapod.protocols.database_protocols import ArrowDatabaseProtocol from orcapod.system_constants import PIPELINE_DB_SCHEMA_VERSION @@ -160,24 +161,6 @@ def _output_source_info_tokens(job: PipelineJob, label: str, column: str) -> lis return [data.source_info()[column] for _, data in rows] -def _broadcast_row_zero(monkeypatch: pytest.MonkeyPatch) -> None: - """Make every materialization stamp row 0's source info, as before ITL-845.""" - original = StaticOutputOperatorPod._rows_to_table # pyright: ignore[reportPrivateUsage] # re-creating the pre-fix behaviour - - def broadcasting( - rows: Sequence[tuple[TagProtocol, DataProtocol]], - ) -> tuple[pa.Table, tuple[str, ...], tuple[str, ...]]: - """Stamp row 0's source info on every row, then build the table.""" - row_zero = rows[0][1].source_info() - return original( - [(tag, data.with_source_info(**row_zero)) for tag, data in rows] - ) - - monkeypatch.setattr( - StaticOutputOperatorPod, "_rows_to_table", staticmethod(broadcasting) - ) - - @pytest.mark.parametrize("orchestrator", ["sync", "async"]) class TestFreshRunStoresPerRowSourceInfo: def test_source_into_function(self, orchestrator: str): From 6b2ffa3808a684785bd38dd5c99cefce041d3e6f Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 16:18:43 -0800 Subject: [PATCH 61/86] refactor(channels): stage 2's description and settlement in the channel layer; send accepts only what can be assembled (ITL-1362) (#495) Part 2 of ITL-1362, first step (no wiring yet): - the send check reads stream.arrow_schema() and arrow_types_declared; transport_schema is deleted - a complete-stream feed orders data by keys_of_rows; a source node's feed is the channel of its execute() output stream (opened_on, so to_stream() gives a complete row-built output as it is) - send refuses a batch with a column more than once, settles nothing from a batch with no rows, and refuses a token its column's settled type cannot hold - concatenate_batches (stream_from_batches and Batch's arrivals) brings each source-info column to its settled token type before putting batches under one another, so what send accepts can be assembled - the ITL-1365 strict xfail on a source node's own description passes now (stage 2's arrow_schema takes the rows' keys) and is a plain test Co-authored-by: Edgar Y. Walker Co-authored-by: Claude Opus 5.5 --- src/orcapod/core/nodes/source_node.py | 53 +++--- src/orcapod/core/operators/batch.py | 11 +- .../core/operators/static_output_pod.py | 169 +++++++++++------- src/orcapod/core/record_batch_channels.py | 75 +++----- src/orcapod/core/streams/base.py | 4 +- .../test_record_batch_channels.py | 168 +++++++++++++++-- 6 files changed, 333 insertions(+), 147 deletions(-) diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index 76736f987..2ecc0262b 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -7,7 +7,6 @@ from __future__ import annotations -from collections import deque import contextlib import dataclasses @@ -30,16 +29,16 @@ from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.core.streams.base import ( ZERO_ROW_INPUT_COLUMNS, + CompleteStreamFeed, keys_of_rows, system_tags_as_rows_give, - row_built_columns, stream_arrow_schema, schema_requires_io, typed_arrow_schemas, typed_zero_row_input, typed_zero_row_table, ) -from orcapod.core.streams.record_batch_input import SOURCE_BATCH_ROWS, InputChannel +from orcapod.core.streams.record_batch_input import InputChannel from orcapod.core.streams.view import ( ViewStatus, StreamView, @@ -427,42 +426,52 @@ def _require_stream_arrow_types(stream: Any, slot: str) -> None: class _ExecuteOutputFeed: """The record batches of a source node's own ``execute()`` output. - Built at the first read from the output stream ``execute()`` gives (ITL-1347, - stage 2: the table a job hands on, already in the row-built form). One binding is - read, at that moment. A batch is dropped once delivered. + The channel of the output stream ``execute()`` gives (ITL-1347, stage 2: the table + a job hands on, already in the row-built form), built at the first read: one + binding is read, at that moment. A batch is dropped once delivered. """ def __init__(self, node: SourceNodeBase) -> None: - """Make the feed; nothing is read until the first ``next``. + """Make the feed; nothing is read until the first read. Args: node: The source node whose output it delivers. """ self._node = node - self._batches: deque[pa.RecordBatch] | None = None + self._output: StreamProtocol | None = None + self._feed: CompleteStreamFeed | None = None + + def _output_feed(self) -> CompleteStreamFeed: + """The feed of the node's output stream, made on the first read.""" + if self._feed is None: + self._output = self._node.execute() + self._feed = CompleteStreamFeed(self._output) + return self._feed async def next(self) -> pa.RecordBatch | None: """Return the next record batch of the node's output, or ``None`` at the end.""" - if self._batches is None: - output = self._node.execute() - table = row_built_columns( - output.as_table(columns=ZERO_ROW_INPUT_COLUMNS), output.keys() - ) - self._batches = deque( - batch - for batch in table.to_batches(max_chunksize=SOURCE_BATCH_ROWS) - if batch.num_rows - ) - return self._batches.popleft() if self._batches else None + return await self._output_feed().next() def close(self) -> None: """Stop reading: the batches not read are dropped.""" - self._batches = deque() + if self._feed is not None: + self._feed.close() + else: + self._feed = _closed_feed(self._node) @property def opened_on(self) -> StreamProtocol | None: - """``None``: the node is not the stream its batches rebuild.""" - return None + """The node's output stream, read on this first access (a conversion's first + read): a channel not read yet gives it as it is when it is a complete output + in the row-built form.""" + return self._output_feed().opened_on + + +def _closed_feed(node: SourceNodeBase) -> CompleteStreamFeed: + """A feed closed before its first read: it reads nothing and delivers nothing.""" + feed = CompleteStreamFeed(node) + feed.close() + return feed class SourceNodeBase(TraceableBase, ABC): diff --git a/src/orcapod/core/operators/batch.py b/src/orcapod/core/operators/batch.py index e17e28fd4..59b970577 100644 --- a/src/orcapod/core/operators/batch.py +++ b/src/orcapod/core/operators/batch.py @@ -18,7 +18,7 @@ from orcapod.core.operators.base import UnaryOperator from orcapod.core.operators.static_output_pod import ( close_inputs, - with_open_provenance_flags, + concatenate_batches, ) from orcapod.core.data_tags import stream_data_tags from orcapod.core.streams import ArrowTableStream @@ -301,14 +301,15 @@ async def async_execute_batches( 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)) + waiting.append(batch) rows += batch.num_rows full = rows - rows % self.batch_size if not full: continue - arrived = pa.Table.from_batches(waiting) + # Arrived batches may differ in their provenance fields: put them + # under one another as a complete table settles them. + arrived = concatenate_batches(waiting) + assert arrived is not None # they hold rows await self._send_processed( arrived.slice(0, full).to_batches(), channel.stream, output ) diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index fbc698435..2764dfca2 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -8,6 +8,7 @@ Collection, Iterable, Iterator, + Mapping, Sequence, ) from datetime import datetime, timezone @@ -1175,51 +1176,6 @@ async def _streams_of(inputs: Sequence[RecordBatchInput]) -> list[StreamProtocol # --------------------------------------------------------------------------- -def transport_schema(stream: StreamProtocol) -> pa.Schema | None: - """Return the schema ``stream``'s record batches have, from its description. - - Never computes, reads or polls a row: 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, a description - whose types are undeclared: ``arrow_types_declared`` false). - """ - # 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 - - if not getattr(stream, "arrow_types_declared", True): - # The rows decide the types (and the column order) of a description whose - # types are undeclared (a narrower bind, ``RowsOnRead``): the first batch sets - # them. - return None - 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 - - ROW_BUILT_OUTPUT = "_orcapod_row_built_output" """The attribute that marks a complete node output in the row-built form (ITL-1347). @@ -1256,7 +1212,9 @@ def stream_from_batches( """ if not batches: return StaticOutputOperatorPod._materialize_upstream([], stream) # pyright: ignore[reportPrivateUsage] # the zero-row input of an operator - table = pa.Table.from_batches([with_open_provenance_flags(b) for b in batches]) + table = concatenate_batches(batches) + if table is None: + return StaticOutputOperatorPod._materialize_upstream([], stream) # pyright: ignore[reportPrivateUsage] # the zero-row input of an operator return StaticOutputOperatorPod._output_stream( # pyright: ignore[reportPrivateUsage] # F and the identity, stage 2's table, _keys_in_delivered_order(stream.keys(), table.column_names), stream ) @@ -1292,28 +1250,119 @@ def _keys_in_delivered_order( return ordered_tags, data_tags + plain -def with_open_provenance_flags(batch: pa.RecordBatch) -> pa.RecordBatch: - """Flag every system-tag and source-info field of ``batch`` nullable. +def settle_token_types( + batch: pa.RecordBatch, accepted: Mapping[str, pa.DataType] +) -> dict[str, pa.DataType]: + """Each source-info column's token type, settled with the batches accepted so far. - 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. + A source-info column's type follows its tokens over the complete table, as a row + types each token from its value (``arrow_utils.source_info_arrow_type``, the one + rule ``_type_source_info_by_values`` applies). A batch with no rows has no token + and settles nothing. Every token of the batch must then be representable in its + column's settled type, so that the complete table can be built. Args: batch: A record batch of a stream's rows. + accepted: Each column's token type from the batches accepted so far. + + Returns: + The token types with this batch accepted. + + Raises: + SourceInfoTypesDisagree: If the batch's tokens give a column two types, or a + type other than the accepted batches'. + RowBuiltFormUnavailable: If a token cannot be represented in its column's + settled type. + """ + from orcapod.utils import arrow_utils + + settled = dict(accepted) + if not batch.num_rows: + return settled # no token: nothing to learn + for field, column in zip(batch.schema, batch.columns, strict=True): + if not field.name.startswith(constants.SOURCE_PREFIX): + continue + kinds: set[pa.DataType] + if pa.types.is_large_string(field.type): + kinds = {pa.large_string()} + else: + kinds = { + arrow_utils.source_info_arrow_type(value) + for value in column.to_pylist() + } + if field.name in settled: + kinds.add(settled[field.name]) + if len(kinds) > 1: + raise SourceInfoTypesDisagree(field.name) + (kind,) = kinds + _ = _tokens_as(column, kind, field.name) # representable, or refused + settled[field.name] = kind + return settled + + +def _tokens_as( + column: pa.Array[Any], + kind: pa.DataType, + name: str, # pyright: ignore[reportExplicitAny] # any column +) -> pa.Array[Any]: # pyright: ignore[reportExplicitAny] # any column + """``column``'s tokens as an array of ``kind``: the same array when it has that type. + + Raises: + RowBuiltFormUnavailable: If a token cannot be represented as ``kind``. + """ + if column.type == kind: + return column + try: + return pa.array(column.to_pylist(), type=kind) + except (pa.ArrowInvalid, pa.ArrowTypeError, TypeError, ValueError) as error: + raise RowBuiltFormUnavailable( + f"{name}: a token cannot be represented as {kind} ({error})" + ) from error + + +def concatenate_batches(batches: Sequence[pa.RecordBatch]) -> pa.Table | None: + """Put a stream's record batches under one another, or ``None`` with no row. + + Batches built from different rows may differ in their provenance fields: a + system-tag or source-info field's nullability, and a source-info column's token + type, follow each batch's own values. Each source-info column is brought to the + type its tokens settle over all the batches (``settle_token_types``), and every + provenance field is flagged nullable, so that the batches have one schema; the + complete table's flags and types are then set by its values (``_row_built_form``). + A batch with no rows is left out. The values are unchanged. + + Args: + batches: Record batches of one stream's rows, in order. Returns: - The batch with those fields nullable. + The table, or ``None`` when no batch has a row. + + Raises: + SourceInfoTypesDisagree: If the tokens give a source-info column two types. + RowBuiltFormUnavailable: If a token cannot be represented in its column's + settled type. """ + rows = [batch for batch in batches if batch.num_rows] + if not rows: + return None + settled: dict[str, pa.DataType] = {} + for batch in rows: + settled = settle_token_types(batch, settled) 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) + opened: list[pa.RecordBatch] = [] + for batch in rows: + columns: list[Any] = [] # pyright: ignore[reportExplicitAny] # any column + fields: list[pa.Field[Any]] = [] # pyright: ignore[reportExplicitAny] # any field + for field, column in zip(batch.schema, batch.columns, strict=True): + if field.name in settled: + column = _tokens_as(column, settled[field.name], field.name) + field = pa.field(field.name, settled[field.name]) + if field.name.startswith(prefixes): + field = field.with_nullable(True) + columns.append(column) + fields.append(field) + opened.append(pa.RecordBatch.from_arrays(columns, schema=pa.schema(fields))) + return pa.Table.from_batches(opened) class RowsOnRead: diff --git a/src/orcapod/core/record_batch_channels.py b/src/orcapod/core/record_batch_channels.py index d744f3c22..3135f3f15 100644 --- a/src/orcapod/core/record_batch_channels.py +++ b/src/orcapod/core/record_batch_channels.py @@ -22,9 +22,8 @@ from orcapod.channels import ChannelClosed from orcapod.core.operators.static_output_pod import ( - SourceInfoTypesDisagree, + settle_token_types, stream_from_batches, - transport_schema, ) from orcapod.core.streams.base import row_built_names from orcapod.core.streams.record_batch_input import InputChannel @@ -152,7 +151,7 @@ def __init__( self._schema: pa.Schema | None = None self._schema_known = False # Each source-info column's token type as the batches accepted so far settle it - # (``_settled_token_types``): a later batch must settle with it. + # (``settle_token_types``): a later batch must settle with it. self._token_types: dict[str, pa.DataType] = {} self._changed = asyncio.Event() @@ -188,8 +187,15 @@ def _raise_if_ended(self) -> None: def _check_schema(self, batch: pa.RecordBatch) -> None: """Raise unless ``batch`` has the schema of this channel's record batches.""" + names = batch.schema.names + if len(set(names)) != len(names): + repeated = sorted({name for name in names if names.count(name) > 1}) + raise ValueError( + f"A record batch sent as {_named(self._stream)} has a column more than " + + f"once: {repeated}." + ) if not self._schema_known: - self._schema = transport_schema(self._stream) + self._schema = _description(self._stream) self._schema_known = True schema = self._schema if schema is None: @@ -211,7 +217,7 @@ def _check_schema(self, batch: pa.RecordBatch) -> None: f"A record batch sent as {_named(self._stream)} does not have that " + f"stream's columns: {mismatch}." ) - token_types = _settled_token_types(batch, self._token_types) + token_types = settle_token_types(batch, self._token_types) self._schema = schema self._token_types = token_types @@ -356,53 +362,28 @@ def result(self) -> StreamProtocol: return self._result -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 _description(stream: StreamProtocol) -> pa.Schema | None: + """The Arrow schema the stream declares for its record batches, or ``None``. -def _settled_token_types( - batch: pa.RecordBatch, accepted: dict[str, pa.DataType] -) -> dict[str, pa.DataType]: - """Each source-info column's token type, settled with the batches already accepted. - - A source-info column's type follows its tokens over the complete table - (``StaticOutputOperatorPod._type_source_info_by_values``): the description leaves it - open, but the channel's batches must settle together, or their result could not be - built. A batch whose tokens give a column a type the accepted batches do not is - refused at send, with the error the complete table would raise. + ``stream.arrow_schema()``: never computes, reads or polls a row. ``None`` when its + types are not declared (``arrow_types_declared`` is false: an unbound slot, a + source not polled yet, a narrower bind whose rows decide), or when its columns + are known only from rows (an empty schema): the first batch then sets the types, + and the names are checked against the stream's keys. Args: - batch: The batch being sent. - accepted: Each column's token type from the batches accepted so far. + stream: The describing stream. + """ + if not stream.arrow_types_declared: + return None + schema = stream.arrow_schema() + return schema if len(schema) else None - Returns: - The token types with this batch accepted. - Raises: - SourceInfoTypesDisagree: If the batch's tokens give a column two types, or a - type other than the accepted batches'. - """ - settled = dict(accepted) - for field, column in zip(batch.schema, batch.columns, strict=True): - if not field.name.startswith(constants.SOURCE_PREFIX): - continue - kinds: set[pa.DataType] - if pa.types.is_large_string(field.type): - kinds = {pa.large_string()} - else: - kinds = { - arrow_utils.source_info_arrow_type(value) - for value in column.to_pylist() - } - if field.name in settled: - kinds.add(settled[field.name]) - if len(kinds) > 1: - raise SourceInfoTypesDisagree(field.name) - if kinds: - (settled[field.name],) = kinds - return settled +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: diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py index d2ec40632..3fc99d3ca 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -537,7 +537,9 @@ async def next(self) -> pa.RecordBatch | None: # The table first: reading it is the stream's one read (an unpolled # source polls here), and its keys are then known without another. table = self._stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS) - table = row_built_columns(table, self._stream.keys()) + # The rows' keys: a source whose keys() states its declared order has + # rows in its table's order (``keys_of_rows``). + table = row_built_columns(table, keys_of_rows(table, self._stream.keys())) self._batches = deque( batch for batch in table.to_batches(max_chunksize=SOURCE_BATCH_ROWS) diff --git a/tests/test_channels/test_record_batch_channels.py b/tests/test_channels/test_record_batch_channels.py index e2836eddf..c9aafc50d 100644 --- a/tests/test_channels/test_record_batch_channels.py +++ b/tests/test_channels/test_record_batch_channels.py @@ -32,12 +32,18 @@ ReadableChannel, WritableChannel, ) -from orcapod.core.operators import MapData, PolarsFilter, SelectDataColumns, SemiJoin +from orcapod.core.operators import ( + Batch, + MapData, + PolarsFilter, + SelectDataColumns, + SemiJoin, +) from orcapod.core.operators.static_output_pod import ( ROW_BUILT_OUTPUT, + RowBuiltFormUnavailable, StaticOutputOperatorPod, stream_from_batches, - transport_schema, ) from orcapod.core.record_batch_channels import ( BATCH_BUFFER_SIZE, @@ -306,14 +312,6 @@ async def read() -> tuple[list[str], list[str]]: assert rebuilt == delivered -@pytest.mark.xfail( - strict=True, - raises=ValueError, - reason="ITL-1365: a source node whose plain tags are declared in another order " - "than their columns (x, j, k, y with tags k, j) describes itself in the slot's " - "order (keys() j, k; its zero-row input too, as on main), while its rows are in " - "the bound source's order, so its own description refuses its batches", -) def test_a_source_nodes_description_takes_its_rows_in_their_own_order() -> None: """Plain tags declared ``k, j`` over physical columns ``x, j, k, y``: the node's own output channel takes the batches its channel delivers.""" @@ -1432,7 +1430,7 @@ def test_without_arrow_types_the_names_are_still_the_streams() -> None: stream = _UntypedStream( table, tag_columns=["subject", "trial"], data_tags=["trial"] ) - assert transport_schema(stream) is None + assert not stream.arrow_types_declared # no Arrow types without rows (batch,) = batches_of(stream) renamed = batch.rename_columns( ["other" if name == "note" else name for name in batch.schema.names] @@ -1924,7 +1922,7 @@ async def write() -> None: output = OutputChannel(stream) await output.send(doubled) - with pytest.raises(ValueError, match="the stream's keys are"): + with pytest.raises(ValueError, match="a column more than once"): run(write) @@ -1954,3 +1952,149 @@ async def write() -> None: with pytest.raises(SourceInfoTypesDisagree, match=column): run(write) + + +# --- Batches that settle together (Codex on PR #485, final check, findings 3-5) ------------ + +TOKEN = pa.large_string() +TOKENS = pa.large_list(TOKEN) +TOKEN_LISTS = pa.large_list(TOKENS) + + +def _with_amplitude_tokens( + batch: pa.RecordBatch, start: int, values: list[Any], kind: pa.DataType +) -> pa.RecordBatch: + """Rows ``start ...`` of ``batch`` with ``_source_amplitude`` carried as ``kind`` + holding ``values`` (tokens of one row each).""" + part = batch.slice(start, len(values)) + index = part.schema.get_field_index("_source_amplitude") + return pa.RecordBatch.from_arrays( + [ + *part.columns[:index], + pa.array(values, type=kind), + *part.columns[index + 1 :], + ], + schema=part.schema.set(index, pa.field("_source_amplitude", kind)), + ) + + +SETTLING_CASES: dict[ + str, tuple[list[tuple[int, list[Any], pa.DataType]], pa.DataType, list[Any]] +] = { + # An empty token list carried two levels deep, then a token list: both settle as + # one level of tokens. + "list_depth": ([(0, [[]], TOKEN_LISTS), (1, [["b"]], TOKENS)], TOKENS, [[], ["b"]]), + # A null token carried as a list, then a string token: both settle as strings. + "null_then_string": ([(0, [None], TOKENS), (1, ["b"], TOKEN)], TOKEN, [None, "b"]), + # Lists that differ only in their item field's nullability. + "item_nullability": ( + [ + (0, [["a"]], pa.large_list(pa.field("item", TOKEN, nullable=False))), + (1, [["b"]], TOKENS), + ], + TOKENS, + [["a"], ["b"]], + ), + # A batch with no rows has no token and fixes no type. + "zero_rows_first": ( + [(0, [], TOKEN), (0, [["a"]], TOKENS), (1, [["b"]], TOKENS)], + TOKENS, + [["a"], ["b"]], + ), +} + + +@pytest.mark.parametrize("case", list(SETTLING_CASES)) +def test_batches_send_accepts_are_assembled(case: str) -> None: + """What ``send`` accepts can be assembled: ``result()`` and ``to_stream()`` build + the complete table, each source-info column of the type its tokens settle.""" + stream = source(2) + (batch,) = batches_of(stream) + parts, settled, tokens = SETTLING_CASES[case] + + async def write() -> tuple[Any, Any]: + output = OutputChannel(stream) + reader = output.open_reader() + for start, values, kind in parts: + await output.send(_with_amplitude_tokens(batch, start, values, kind)) + await output.close() + return output.result(), await reader.to_stream() + + result, converted = run(write) + for assembled in (result, converted): + table = assembled.as_table(columns=ALL) + assert table.schema.field("_source_amplitude").type == settled + assert table.column("_source_amplitude").to_pylist() == tokens + + +def test_a_token_that_cannot_be_represented_is_refused_at_send() -> None: + """A token that has no place in its column's settled type (``[[], [[]]]`` carried + three levels deep) is refused at send; the channel takes valid batches after it.""" + stream = source(2) + (batch,) = batches_of(stream) + deep = pa.large_list(TOKEN_LISTS) + + async def write() -> list[Any]: + output = OutputChannel(stream) + with pytest.raises(RowBuiltFormUnavailable, match="cannot be represented"): + await output.send(_with_amplitude_tokens(batch, 0, [[[], [[]]]], deep)) + await output.send(_with_amplitude_tokens(batch, 0, [["a"]], TOKENS)) + await output.close() + return ( + output.result() + .as_table(columns=ALL) + .column("_source_amplitude") + .to_pylist() + ) + + assert run(write) == [["a"]] + + +def test_a_duplicate_system_tag_column_is_refused_on_a_declared_stream() -> None: + """A batch with a system-tag column twice is refused, whatever the description.""" + stream = source(2) + (batch,) = batches_of(stream) + name = next(n for n in batch.schema.names if n.startswith("_tag")) + doubled = batch.append_column(batch.schema.field(name), batch.column(name)) + + async def write() -> None: + await OutputChannel(stream).send(doubled) + + with pytest.raises(ValueError, match="a column more than once"): + run(write) + + +def test_batch_puts_arrivals_with_differing_token_types_together() -> None: + """``Batch(2)`` over arrivals whose source-info tokens are carried in two types (an + empty list two levels deep, then a token list): it groups them, as a complete table + settles them.""" + stream = source(2) + (batch,) = batches_of(stream) + op = Batch(batch_size=2) + + async def go() -> Any: + feed = OutputChannel(stream) + reader = feed.open_reader() + await feed.send(_with_amplitude_tokens(batch, 0, [[]], TOKEN_LISTS)) + await feed.send(_with_amplitude_tokens(batch, 1, [["b"]], TOKENS)) + await feed.close() + output = OutputChannel(op(stream)) + await op.async_execute_batches([reader], output) + return output.result() + + table = run(go).as_table(columns=ALL) + assert table.num_rows == 1 + assert table.column("_source_amplitude").to_pylist() == [[[], ["b"]]] + + +def test_a_source_nodes_channel_gives_its_output_stream_as_it_is() -> None: + """A source node's channel reads its ``execute()`` output stream, a complete output + in the row-built form, which ``to_stream()`` gives as it is.""" + node = SourceJobNode.from_stream(source(2), name="events") + + async def read() -> Any: + return await node.open_channel().to_stream() + + output = run(read) + assert getattr(output, ROW_BUILT_OUTPUT, False) + assert same(output.as_table(columns=ALL), R(node)) From a6b0a4d4434a6cb0787ce266a6ac0cd51f505bf9 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 16:21:24 -0800 Subject: [PATCH 62/86] fix(function_node, side_effects): one precondition for every fast path; one definition per digest; observers get real rows (ITL-1361) Codex review of PR #494 (round 1) and the hash-site inventory failure. - One precondition for every stage 3-4 fast path (entry ids from the input table's slices, the output's stored-result rows from their stored table, a side-effect pass-through as F of its input table): the stream is exactly an ArrowTableStream or the row-built stream a job hands a node, with no member replaced on the instance, in the node's data context, with system tags that are non-null large_string and no column a datagram would retype (_reads_as_a_table_stream, _slices_are_rows). Anything else takes main's row path: main's ids (an int32 or nullable system tag, an untyped null column), main's types and main's error at a side-effect edge. - One definition per digest: the input data hash is data_table_content_hash (core/datagrams/datagram.py, a data datagram's content hash) on both paths, the preimage's last column _with_input_data_hash; both new sites are in the hash site inventory. - Observers: only the library's row-blind observers (READS_NO_ROWS on their own class: NoOpObserver, RunCountingObserver, a CompositeObserver of such; utils/observer_rows.reads_no_rows) get row views, which now declare every TagProtocol / DataProtocol member; any other observer receives the real Tag and Data, as on main. - Tests: test_function_node_entry_id_definitions.py (several-items family, list columns after Batch/GroupBy, nested source info, logical, numpy and nullable values, the raw cases, stores written by one path hit by the other, observers, pass-through). docs/dev/scripts/itl_1347/ cross_version_entry_ids.py: Delta stores written by main hit by the branch and the reverse, 87 inputs. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1361.md | 18 +- .../itl_1347/cross_version_entry_ids.py | 177 ++++++++ .../dev/specs/itl-1347-job-table-transport.md | 21 +- docs/reference/hashing.md | 17 +- src/orcapod/core/datagrams/datagram.py | 32 +- src/orcapod/core/nodes/function_node.py | 222 ++++++++-- src/orcapod/pipeline/composite_observer.py | 6 + src/orcapod/pipeline/observer.py | 5 +- src/orcapod/pipeline/run_summary.py | 5 +- src/orcapod/utils/observer_rows.py | 27 ++ ...test_function_node_entry_id_definitions.py | 389 ++++++++++++++++++ .../test_pipeline/test_job_batched_commits.py | 6 +- 12 files changed, 870 insertions(+), 55 deletions(-) create mode 100644 docs/dev/scripts/itl_1347/cross_version_entry_ids.py create mode 100644 src/orcapod/utils/observer_rows.py create mode 100644 tests/test_core/nodes/test_function_node_entry_id_definitions.py diff --git a/changelog.d/ITL-1361.md b/changelog.d/ITL-1361.md index c3e6fee0e..623b6e87b 100644 --- a/changelog.d/ITL-1361.md +++ b/changelog.d/ITL-1361.md @@ -1,12 +1,16 @@ ### Changed - **Function and side-effect job nodes work on their input's Arrow table** — on the sync - path, a function job node takes each input row's entry id from slices of its input's - table (the tag side with its system tags, and the hash of the data columns) instead of - tables built from the row's values; shows its observers views of its input rows, made - only when read; gives a stored result the id it was stored under by a shallow copy; - and builds its output with the rows of stored results taken from the stored table. A - side-effect job node hands on its input's table at the rows it passed on. Every - output, stored row, entry id, observer event and error is as before. Third and fourth + path, where its input's table is provably its rows' (exactly a table stream, in the + node's data context, with system tags and columns its rows would not retype), a + function job node takes each input row's entry id from slices of that table instead of + tables built from the row's values, by the same definitions (one preimage statement, + one input data hash, `data_table_content_hash`); hands the library's row-blind + observers views of its input rows, made only when read (any other observer receives + the rows themselves); gives a stored result the id it was stored under by a shallow + copy; and builds its output with the rows of stored results taken from the stored + table. A side-effect job node hands on its input's table at the rows it passed on, + under the same condition. Any other input takes the row path as before. Every output, + stored row, entry id, observer event and error is as before. Third and fourth stages of the table transport between job nodes (`docs/dev/specs/itl-1347-job-table-transport.md`). (ITL-1361) diff --git a/docs/dev/scripts/itl_1347/cross_version_entry_ids.py b/docs/dev/scripts/itl_1347/cross_version_entry_ids.py new file mode 100644 index 000000000..decd76448 --- /dev/null +++ b/docs/dev/scripts/itl_1347/cross_version_entry_ids.py @@ -0,0 +1,177 @@ +"""Cross-version check of a function node's entry ids (ITL-1361). + +Run once per Orcapod version, each with its own environment, over the same inputs: + + /bin/python -I cross_version_entry_ids.py write + /bin/python -I cross_version_entry_ids.py load + +``write`` runs a function job node over each input and stores its results in a Delta +store; ``load`` runs the same node load-only over the same store. A store written by one +version must be hit, row for row, by the other: same stored base entry ids, every row +from the store, no call of the function. The inputs cover the several-items family +(tag order, layout, tag roles), list-valued columns after ``Batch`` and ``GroupBy``, +nested source info, nullable and logical values, and raw streams whose rows type their +system tags or columns otherwise (an ``int32`` system tag, a nullable one, an untyped +``null`` data column), each as a job hands it on and as a raw ``ArrowTableStream``. +Needs the repository root on ``PYTHONPATH`` (for ``tests.test_core.operators.several_items``). +""" + +from __future__ import annotations + +import json +import sys +import warnings +from pathlib import Path +from typing import Any + +import pyarrow as pa + +from orcapod import function_pod +from orcapod.core.data_tags import stream_data_tags +from orcapod.core.nodes.function_node import FunctionJobNode +from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod +from orcapod.core.streams import ArrowTableStream +from orcapod.databases import DeltaTableDatabase +from orcapod.operators import Batch, GroupBy +from orcapod.pipeline.observer import NoOpObserver +from orcapod.sources import DictSource +from tests.test_core.operators.several_items import MAIN, arrangements, make_source + +warnings.simplefilter("ignore") +CALLS: list[Any] = [] + + +@function_pod(output_keys="y") +def flat(d1: int | None) -> int: + CALLS.append(d1) + return -1 if d1 is None else d1 + 1 + + +@function_pod(output_keys="y") +def listed(d1: list[int | None] | None) -> int: + CALLS.append(d1) + return -1 if d1 is None else len(d1) + + +@function_pod(output_keys="y") +def nullable(i: int | None) -> int: + CALLS.append(i) + return -1 if i is None else i + + +@function_pod(output_keys="y") +def untyped(x: Any) -> int: + CALLS.append(x) + return -1 if x is None else x + + +class Cached(NoOpObserver): + def __init__(self) -> None: + self.cached: list[bool] = [] + + def contextualize(self, *identity_path: str) -> Cached: + return self + + def on_data_end(self, *args: Any, **kwargs: Any) -> None: + self.cached.append(bool(kwargs["cached"] if "cached" in kwargs else args[-1])) + + +def forms(stream: Any) -> dict[str, Any]: + rows = list(stream.iter_data()) + handed_on = StaticOutputOperatorPod._materialize_upstream(rows, stream) + raw = ArrowTableStream( + stream.as_table(columns={"system_tags": True, "source": True}), + tag_columns=stream.keys()[0], + data_tags=stream_data_tags(stream), + ) + return {"handed_on": handed_on, "raw": raw} + + +def cases() -> dict[str, tuple[Any, Any]]: + out: dict[str, tuple[Any, Any]] = {} + for arrangement in arrangements(MAIN): + stream = make_source(MAIN, arrangement).select_data_columns(["d1"]) + for name, form in forms(stream).items(): + out[f"family/{arrangement.id}/{name}"] = (flat, form) + for arrangement in arrangements(MAIN)[::4]: + source = make_source(MAIN, arrangement) + for kind, stream in ( + ("batch", Batch(batch_size=2)(source)), + ("group_by", GroupBy(by=[arrangement.tag_order[0]])(source)), + ): + selected = stream.select_data_columns(["d1"]) + for name, form in forms(selected).items(): + out[f"{kind}/{arrangement.id}/{name}"] = (listed, form) + values = DictSource( + [{"a": 1, "b": "x", "i": 1}, {"a": 2, "b": "y", "i": None}], + tag_columns=["a", "b"], + tag_only_columns=True, + source_id="values", + ) + for name, form in forms(values).items(): + out[f"nullable/{name}"] = (nullable, form) + raw_tables = { + "int32_system_tag": pa.table( + {"k": ["a", "b"], "d1": [1, 2], "e": pa.array([10, 11], pa.int32())} + ), + "nullable_system_tag": pa.table( + { + "k": ["a", "b"], + "d1": [1, 2], + "e": pa.array(["s", None], pa.large_string()), + } + ), + } + for name, table in raw_tables.items(): + out[f"raw/{name}"] = ( + flat, + ArrowTableStream(table, tag_columns=["k"], system_tag_columns=["e"]), + ) + out["raw/null_data_column"] = ( + untyped, + ArrowTableStream( + pa.table({"k": ["a", "b"], "x": pa.nulls(2)}), tag_columns=["k"] + ), + ) + return out + + +def main() -> None: + store, mode, report = Path(sys.argv[1]), sys.argv[2], Path(sys.argv[3]) + results: dict[str, Any] = {} + for index, (label, (pod, stream)) in enumerate(sorted(cases().items())): + database = DeltaTableDatabase(store / f"case_{index:03d}") + observer = Cached() + CALLS.clear() + try: + node = FunctionJobNode(pod.pod, stream, pipeline_database=database) + node.execute(stream, observer=observer, load_only=(mode == "load")) + database.flush() + ids: list[str] = [] + for path in database.list_table_paths(): + records = database.get_all_records(path) + if ( + records is None + or "__pipeline_base_entry_id" not in records.column_names + ): + continue + ids += [ + value.hex() + for value in records["__pipeline_base_entry_id"].to_pylist() + if isinstance(value, bytes) + ] + ids.sort() + results[label] = { + "ids": ids, + "cached": observer.cached, + "calls": len(CALLS), + "rows": len(list(node.iter_data())), + } + except Exception as error: # noqa: BLE001 # the outcome is compared across versions + results[label] = {"error": f"{type(error).__name__}: {error}"} + report.write_text(json.dumps(results, indent=1, sort_keys=True)) + print(len(results), "cases") + + +if __name__ == "__main__": + main() diff --git a/docs/dev/specs/itl-1347-job-table-transport.md b/docs/dev/specs/itl-1347-job-table-transport.md index 21769a847..2c417e6b6 100644 --- a/docs/dev/specs/itl-1347-job-table-transport.md +++ b/docs/dev/specs/itl-1347-job-table-transport.md @@ -816,6 +816,18 @@ Counted on `origin/main`, by file, excluding database cursors' own `execute`: The function is still called once per row. Everything around the call is Arrow data. +**The one precondition (stage 2's, ITL-1361 review).** Every fast path of stages 3 and 4 +(the entry ids from the input table's slices, the output's rows of stored results taken +from their stored table, a side-effect node's pass-through as F of its input table) is +used only where the table is provably its rows': the stream is exactly an +`ArrowTableStream` (or the row-built stream a job hands a node), with no member replaced on +the instance, in the node's data context, with system tags that are non-null +`large_string` (`system_tags_as_rows_give`) and no column a datagram would retype +(`_slices_are_rows`; a stored table is checked the same way). Anything else takes +`main`'s row path. The entry id has one definition on both paths: the preimage's last +column is `_with_input_data_hash`, and the input data hash is `data_table_content_hash`, a +data datagram's content hash. + 1. **Input as Arrow data.** For each input row, the node computes the base entry id from that row's slice of the Arrow table or record batch: the tag side with system tags, plus the input data hash. This is the same one-row preimage `_build_record_id_preimage` builds @@ -872,10 +884,11 @@ view**: one internal class, `RowView`, that satisfies `TagProtocol` or `DataProt Arrow table or record batch and a row index. It builds the datagram only when it is first read. -- `RunCountingObserver` reads only the label and the `cached` flag, so it makes no row. -- The status and logging observers read tag values, so they make the tag datagram of the - rows they report. -- A user's observer gets what it gets today. +- Only the library observers that read no input row (`READS_NO_ROWS` declared on their own + class: `NoOpObserver`, `RunCountingObserver`, and a `CompositeObserver` of only such; + `reads_no_rows`) receive row views (`_TagView`, `_DataView`, every protocol member + declared on the class). Every other observer, a subclass included, receives the rows + themselves, as on `main` (ITL-1361 review: a view is not a `Tag`). Event order stays as today: - sync: input order; diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index ce12e65d7..eb3421c9a 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -325,7 +325,7 @@ test session with `-p tests.test_hashing.hash_site_trace`. | schema identity | the `arrow_schema_v1` hashes of a source's or slot's Arrow tag and data schemas, or of a function's output Arrow schema | a source's content and pipeline identity, system-tag column names, the function `uri` | the `ContentHash` objects, nested | `utils/schema_utils.py:arrow_schema_identity`, `utils/schema_utils.py:compute_schema_hash`, `core/data_function.py:DataFunctionBase.output_data_schema_hash` | | union and generic alias arguments | argument type hashes, sorted by digest, then label (ordering only) | the type hash, via the nested form | as above | `hashing/semantic_hashing/builtin_handlers.py:_sorted_hashes`, `hashing/semantic_hashing/builtin_handlers.py:_sorted_hashes..` | | logical-type cell, scalar and container | a value-hashed cell's value hash | the Arrow table hash | `::