From 68435afe19c21254193f09d2b0d00c0139665fa2 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" <> Date: Sun, 22 Nov 2026 01:46:19 -0800 Subject: [PATCH 1/9] 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 --- src/orcapod/core/operators/streaming_joins.py | 792 ++++++++++++++++++ .../operators/test_streaming_joins.py | 481 +++++++++++ 2 files changed, 1273 insertions(+) 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/streaming_joins.py b/src/orcapod/core/operators/streaming_joins.py new file mode 100644 index 000000000..629261e5d --- /dev/null +++ b/src/orcapod/core/operators/streaming_joins.py @@ -0,0 +1,792 @@ +"""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. + +How a kernel stays equal to the sync path: + +- **Checks before the first batch.** The constructor applies the operator's own + ``static_process`` to the inputs' zero-row streams + (``StaticOutputOperatorPod._materialize_upstream`` with no rows: the description's + Arrow types, or its Python schema when it cannot type itself), which processes no data + and raises exactly the sync path's errors (ITL-856, e1 of the ITL-1347 spec). The + zero-row result is also the output's description: its columns are what every emitted + batch holds (``output_columns``). +- **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``, + as ``_inner_join`` builds it). An arriving batch's key frame is joined with the other + side's accumulated key frame in one vectorized join, never per row; 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 description's, except source info, which a + complete table decides (``_flag_source_info_nullability``, step 5 of the spec's + row-built form F): a kernel declares every source-info 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. +""" + +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 ( + _MERGED_SOURCE_PREFIX, # pyright: ignore[reportPrivateUsage] # Join's one rule + Join, +) +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 +from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod +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 _key_frame( + table: pa.Table, keys: Sequence[str], row: str, offset: int +) -> pl.DataFrame: + """Return the prepared keys of ``table`` and its row numbers, counted from ``offset``. + + Args: + table: The rows. + keys: The key columns (``arrow_keys.polars_key_frame``). + row: The row-number column. + offset: The number of the first row. + + Returns: + The key frame. + """ + frame = polars_key_frame(table, keys, row) + if offset: + frame = frame.with_columns(pl.col(row) + offset) + return frame + + +def _match( + arriving: pl.DataFrame, held: pl.DataFrame, keys: Sequence[str] +) -> pl.DataFrame: + """Join two key frames as the sync join does: inner on ``keys``, every pair if none. + + The sync path joins on its keys plus a constant column (``Join.static_process``), so + inputs that share no key give every pair; that is a cross join. + + Args: + arriving: The arriving batch's key frame. + held: The other side's accumulated key frame. + keys: The key columns. + + Returns: + One row per matched pair, holding both row-number columns. + """ + if not keys: + return arriving.join(held, how="cross") + return arriving.join(held, on=list(keys), how="inner") + + +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, 0) + + 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 closed(self) -> bool: + """Whether both sides have closed.""" + return self.sides[0].closed and self.sides[1].closed + + 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 + 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 it with no rows: its description. + self._zero_rows: tuple[StreamProtocol, ...] = tuple( + StaticOutputOperatorPod._materialize_upstream([], stream) # pyright: ignore[reportPrivateUsage] # the operators' one form of an input + for stream in self.inputs + ) + self._layouts: tuple[pa.Schema, ...] = tuple( + stream.as_table(columns=TRANSPORT_COLUMNS).schema + for stream in self._zero_rows + ) + self._schemas: list[pa.Schema | None] = [None] * len(self.inputs) + self._closed: list[bool] = [False] * len(self.inputs) + # 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 [] + 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. + """ + self._require_open(input_index) + self._closed[input_index] = True + return self._emitted(self._close(input_index)) + + @abstractmethod + def _push(self, input_index: int, table: pa.Table) -> list[pa.Table]: + """Take an input's rows (in its layout, never empty); return output tables.""" + + @abstractmethod + def _close(self, input_index: int) -> list[pa.Table]: + """Note an input's end; return output tables.""" + + def _require_open(self, input_index: int) -> None: + 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 description's: its column order, its Arrow types and flags, + except that every source-info field is nullable (a complete table decides + those) and a column the description types ``null`` takes the batch's type + (rows carry ``large_string`` there, ITL-1319). + """ + 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) + schema = self._schemas[input_index] + if schema is None: + fields: list[pa.Field[Any]] = [] + for field, actual in zip(layout, table.schema): + arrow_type = field.type + if pa.types.is_null(arrow_type): + arrow_type = actual.type + nullable = field.nullable or field.name.startswith( + constants.SOURCE_PREFIX + ) + fields.append( + pa.field(field.name, arrow_type, nullable, metadata=field.metadata) + ) + schema = pa.schema(fields) + self._schemas[input_index] = schema + for field, actual in zip(schema, table.schema): + if field.type != 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" + ) + return pa.Table.from_arrays(table.columns, schema=schema) + + def _emitted(self, tables: list[pa.Table]) -> list[pa.RecordBatch]: + """The record batches of the output tables, holding ``output_columns``.""" + batches: list[pa.RecordBatch] = [] + for table in tables: + if table.num_rows: + batches.extend( + table.select(list(self.output_columns)) + .combine_chunks() + .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] = [] + 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)) + ) + 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]: + 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: + 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]: + 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) + # A step whose two sides have closed ends the next step's left side. + while step < len(self._links) - 1 and self._links[step].closed: + step += 1 + self._links[step].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 sync path flags the columns it does not capture (system tags and source + # info) by their null count over the whole result; a batch of it cannot, so a + # system tag keeps its input's flag (a provenance value is never null) and + # source info is nullable, settled on the complete table (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 + if field.name.startswith(constants.SOURCE_PREFIX) + else field.nullable, + ) + 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]: + undecided = table.filter(pc.invert(kept)) + 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 null (the + # sync path drops those: a null key never matches). + keys = table.select(self._keys) + valid = keys.column(0).is_valid() + for index in range(1, keys.num_columns): + valid = pc.and_(valid, keys.column(index).is_valid()) + keys = keys.filter(valid) + 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..875eb1f03 --- /dev/null +++ b/tests/test_core/operators/test_streaming_joins.py @@ -0,0 +1,481 @@ +"""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. These tests feed each kernel its 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: every flag +is the sync result's, except source info, which a complete table decides (step 5 of the +spec's row-built form F, ``_flag_source_info_nullability``) and is compared after it. +""" + +from __future__ import annotations + +import itertools +import random +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 .several_items import MAIN, MIXED, P, PLAIN, Q, R, DATA_TAGS, Arrangement +from .several_items import TAGS_FIRST, make_source + +SEEDS = range(12) +# 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: + """An input's rows as the channel layer sends them: its transport columns.""" + return stream.as_table(columns=TRANSPORT_COLUMNS) + + +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(" Counter[tuple[Any, ...]]: + names = sorted(table.column_names) + return Counter( + tuple(_value(row[name]) for name in names) for row in table.to_pylist() + ) + + +def _settled(table: pa.Table) -> pa.Table: + return StaticOutputOperatorPod._flag_source_info_nullability(table) # pyright: ignore[reportPrivateUsage] + + +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.""" + for batch in batches: + assert batch.schema.names == list(kernel.output_columns) + got = ( + pa.Table.from_batches(batches) + if batches + else expected.slice(0, 0).select(list(kernel.output_columns)) + ) + assert sorted(got.column_names) == sorted(expected.column_names) + got = _settled(got.select(expected.column_names)) + want = _settled(expected) + if got.num_rows or not want.num_rows: + 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 + if got.num_rows: + assert other.nullable == field.nullable, field.name + assert _rows(got) == _rows(want) + + +def _check( + make_kernel: Callable[[Sequence[StreamProtocol]], StreamingJoinKernel], + sync: Callable[..., StreamProtocol], + inputs: Sequence[StreamProtocol], + seeds: Sequence[int] = SEEDS, +) -> None: + expected = _transport(sync(*inputs)) + tables = [_transport(stream) for stream in inputs] + for seed in seeds: + kernel = make_kernel(inputs) + 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), + ], + ), + "struct": ( + pa.struct([("a", pa.int64()), ("b", pa.large_string())]), + [{"a": 1, "b": "x"}, {"a": 1, "b": "y"}, {"a": 2, "b": "x"}], + ), + "list": (pa.large_list(pa.int64()), [[1, 2], [2], [], [1, 2]]), +} + + +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("pool", sorted(KEY_POOLS)) +def test_join_two_inputs_every_key_type(pool: str) -> None: + left = _keyed_source( + "a", pool, 9, {"x": pa.int64(), "x2": pa.float64()}, 1, extra_tag="g" + ) + right = _keyed_source("b", pool, 7, {"y": pa.int64(), "y2": pa.large_string()}, 2) + for inputs in ((left, right), (right, left)): + _check(_join_kernel, Join().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("roles", [PLAIN, DATA_TAGS, MIXED]) +def test_join_four_inputs_in_each_tag_role(roles: 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 = [ + make_source(spec, Arrangement(spec.tags, TAGS_FIRST, 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("pool", ["int", "nullable_int", "float", "struct", "list"]) +def test_merge_join_colliding_columns_in_both_argument_orders(pool: str) -> None: + left = _keyed_source( + "a", pool, 8, {"x": pa.int64(), "c": pa.float64()}, 6, extra_tag="g" + ) + right = _keyed_source("b", pool, 6, {"c": pa.float64(), "y": pa.int64()}, 7) + for inputs in ((left, right), (right, left)): + _check(_merge_kernel, MergeJoin().static_process, inputs) + + +@pytest.mark.parametrize("roles", [PLAIN, DATA_TAGS, MIXED]) +def test_merge_join_in_each_tag_role(roles: str) -> None: + main = make_source(MAIN, Arrangement(MAIN.tags, TAGS_FIRST, roles)) + partner = make_source(P, Arrangement(P.tags, TAGS_FIRST, 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("pool", sorted(KEY_POOLS)) +def test_semi_join_every_key_type(pool: str) -> None: + left = _keyed_source("a", pool, 9, {"x": pa.int64()}, 8, extra_tag="g") + right = _keyed_source("b", pool, 4, {"y": pa.int64()}, 9) + _check(_semi_kernel, SemiJoin().static_process, (left, right)) + + +@pytest.mark.parametrize("roles", [PLAIN, DATA_TAGS, MIXED]) +def test_semi_join_in_each_tag_role(roles: str) -> None: + main = make_source(MAIN, Arrangement(MAIN.tags, TAGS_FIRST, 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_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 From fe3f3214d613574fe40f754646e11aab579a5387 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 02:54:03 -0800 Subject: [PATCH 2/9] 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 --- 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 | 351 ++++++++++---- .../operators/test_streaming_joins.py | 428 ++++++++++++++++-- 5 files changed, 728 insertions(+), 159 deletions(-) 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 index 629261e5d..b1775ec78 100644 --- a/src/orcapod/core/operators/streaming_joins.py +++ b/src/orcapod/core/operators/streaming_joins.py @@ -8,34 +8,54 @@ 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. + How a kernel stays equal to the sync path: -- **Checks before the first batch.** The constructor applies the operator's own - ``static_process`` to the inputs' zero-row streams - (``StaticOutputOperatorPod._materialize_upstream`` with no rows: the description's - Arrow types, or its Python schema when it cannot type itself), which processes no data - and raises exactly the sync path's errors (ITL-856, e1 of the ITL-1347 spec). The - zero-row result is also the output's description: its columns are what every emitted +- **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 when the offending batch arrives; rows already emitted belong to a run that then + fails. +- **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. An input with no rows makes every join's + result empty, so no row was emitted before. - **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``, - as ``_inner_join`` builds it). An arriving batch's key frame is joined with the other - side's accumulated key frame in one vectorized join, never per row; 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. + 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 description's, except source info, which a - complete table decides (``_flag_source_info_nullability``, step 5 of the spec's - row-built form F): a kernel declares every source-info field nullable, and the stream - made from its batches settles them. +- **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 (``_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. +other side has closed. A step of a ``Join`` chain that can never emit again (a side +closed holding no row) releases its successor's other side and every earlier step, and +``SemiJoin`` never keeps a left row whose key holds a top-level null. """ from __future__ import annotations @@ -52,8 +72,11 @@ 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 ( @@ -61,8 +84,12 @@ _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 +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 from orcapod.protocols.core_protocols import StreamProtocol from orcapod.system_constants import constants from orcapod.utils import arrow_utils @@ -76,45 +103,142 @@ _ROW = ("__streaming_left_row", "__streaming_right_row") -def _key_frame( - table: pa.Table, keys: Sequence[str], row: str, offset: int -) -> pl.DataFrame: - """Return the prepared keys of ``table`` and its row numbers, counted from ``offset``. +# TODO(ITL-1360): ``_row_built_columns`` and ``_flag_by_values`` are interim copies of +# stage 2's ``StaticOutputOperatorPod._row_built_columns`` and ``_flag_by_values`` (the +# row-built form F, same names and behaviour); call those once stage 2 is on job-speed. +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. + + The steps of F that each row decides on its own: user tags in tag order, system tags + in table order, the data columns that are not data-tags and the source info of every + data column, both in data-key order, normalized to the large types without keeping + ``null`` (a row's datagram stores a ``null`` column as ``large_string``). + + Args: + table: A table of user tags, system tags, data and source info. + keys: The tag keys and the data keys of its stream (``stream.keys()``). + + Returns: + The same arrays, selected and ordered, in their large types. + """ + 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]) + ) + + +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, on a complete table only. No schema metadata is kept. + + Args: + table: A table of user tags, system tags, data and source info. + + Returns: + The same arrays under the new field flags. + """ + 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) + ] + return pa.Table.from_arrays(table.columns, schema=pa.schema(fields)) + + +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 + (``_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 = _flag_by_values(_row_built_columns(table, stream.keys())) + 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 key columns (``arrow_keys.polars_key_frame``). + keys: The shared tag columns. row: The row-number column. - offset: The number of the first row. Returns: The key frame. """ - frame = polars_key_frame(table, keys, row) - if offset: - frame = frame.with_columns(pl.col(row) + offset) - return 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 as the sync join does: inner on ``keys``, every pair if none. + """Join two key frames by the sync join's rule (``join._matched_pairs``). - The sync path joins on its keys plus a constant column (``Join.static_process``), so - inputs that share no key give every pair; that is a cross join. + 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 key columns. + keys: The shared tag columns. Returns: One row per matched pair, holding both row-number columns. """ - if not keys: - return arriving.join(held, how="cross") - return arriving.join(held, on=list(keys), how="inner") + return _matched_pairs(arriving, held, [*keys, _COMMON_JOIN_KEY]) def _joined_by_rows( @@ -173,7 +297,7 @@ def __init__(self, keys: Sequence[str], row: str) -> None: 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, 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``.""" @@ -230,9 +354,20 @@ def held_rows(self) -> int: return self.sides[0].rows + self.sides[1].rows @property - def closed(self) -> bool: - """Whether both sides have closed.""" - return self.sides[0].closed and self.sides[1].closed + def exhausted(self) -> bool: + """Whether the link can never emit again: a side closed holding no row. + + 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. @@ -307,17 +442,19 @@ def __init__( ) self.operator: StaticOutputOperatorPod = operator self.inputs: tuple[StreamProtocol, ...] = tuple(inputs) - # Each input as the sync path reads it with no rows: its description. - self._zero_rows: tuple[StreamProtocol, ...] = tuple( - StaticOutputOperatorPod._materialize_upstream([], stream) # pyright: ignore[reportPrivateUsage] # the operators' one form of an input - for stream in self.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( - stream.as_table(columns=TRANSPORT_COLUMNS).schema + _settled_by_values(stream.as_table(columns=TRANSPORT_COLUMNS).schema) for stream in self._zero_rows ) - self._schemas: list[pa.Schema | None] = [None] * len(self.inputs) self._closed: list[bool] = [False] * len(self.inputs) + self._received: list[bool] = [False] * len(self.inputs) # 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( @@ -347,6 +484,7 @@ def push(self, input_index: int, batch: pa.RecordBatch) -> list[pa.RecordBatch]: 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]: @@ -360,10 +498,40 @@ def close(self, input_index: int) -> list[pa.RecordBatch]: 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 - return self._emitted(self._close(input_index)) + emitted = self._emitted(self._close(input_index)) + if all(self._closed): + self._check_empty_inputs() + return emitted + + def _check_empty_inputs(self) -> 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. + """ + empty = [ + not received and null_typed + for received, null_typed in zip(self._received, self._null_typed) + ] + if not any(empty): + return + pod = StaticOutputOperatorPod + 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]: @@ -387,10 +555,10 @@ def _require_open(self, input_index: int) -> None: 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 description's: its column order, its Arrow types and flags, - except that every source-info field is nullable (a complete table decides - those) and a column the description types ``null`` takes the batch's type - (rows carry ``large_string`` there, ITL-1319). + 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) @@ -400,40 +568,33 @@ def _as_input_table(self, input_index: int, batch: pa.RecordBatch) -> pa.Table: + f"the column(s) {missing} its stream describes" ) table = pa.Table.from_batches([batch]).select(layout.names) - schema = self._schemas[input_index] - if schema is None: - fields: list[pa.Field[Any]] = [] - for field, actual in zip(layout, table.schema): - arrow_type = field.type - if pa.types.is_null(arrow_type): - arrow_type = actual.type - nullable = field.nullable or field.name.startswith( - constants.SOURCE_PREFIX - ) - fields.append( - pa.field(field.name, arrow_type, nullable, metadata=field.metadata) - ) - schema = pa.schema(fields) - self._schemas[input_index] = schema - for field, actual in zip(schema, table.schema): - if field.type != actual.type: + 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" ) - return pa.Table.from_arrays(table.columns, schema=schema) + 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``.""" + """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 (``_flag_by_values``). + """ batches: list[pa.RecordBatch] = [] for table in tables: if table.num_rows: - batches.extend( - table.select(list(self.output_columns)) - .combine_chunks() - .to_batches() + 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: @@ -544,10 +705,18 @@ def _close(self, input_index: int) -> list[pa.Table]: position = self._position[input_index] step, side = (0, 0) if position == 0 else (position - 1, 1) self._links[step].close(side) - # A step whose two sides have closed ends the next step's left side. - while step < len(self._links) - 1 and self._links[step].closed: - step += 1 - self._links[step].close(0) + # A step that can never emit again ends the next step's left side, and no + # earlier step's rows are needed any more (they could only reach this one). + 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) return [] @@ -617,19 +786,13 @@ def _finish( source_name = f"{constants.SOURCE_PREFIX}{name}" if source_name in output_nullable: output_nullable[source_name] = False - # The sync path flags the columns it does not capture (system tags and source - # info) by their null count over the whole result; a batch of it cannot, so a - # system tag keeps its input's flag (a provenance value is never null) and - # source info is nullable, settled on the complete table (module docstring). + # 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 - if field.name.startswith(constants.SOURCE_PREFIX) - else field.nullable, - ) + 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(): @@ -753,7 +916,10 @@ def _push(self, input_index: int, table: pa.Table) -> list[pa.Table]: else: kept = self._kept(table, right_keys) if not self._closed[1]: - undecided = table.filter(pc.invert(kept)) + # 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 @@ -761,13 +927,10 @@ def _push(self, input_index: int, table: pa.Table) -> list[pa.Table]: else pa.concat_tables([self._waiting, undecided]) ) return [table.filter(kept)] - # A right batch: only its keys, and only rows whose keys hold no null (the - # sync path drops those: a null key never matches). + # 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) - valid = keys.column(0).is_valid() - for index in range(1, keys.num_columns): - valid = pc.and_(valid, keys.column(index).is_valid()) - keys = keys.filter(valid) + keys = keys.filter(_has_whole_key(keys, self._keys)) if not keys.num_rows: return [] frame = polars_key_frame(keys, self._keys) diff --git a/tests/test_core/operators/test_streaming_joins.py b/tests/test_core/operators/test_streaming_joins.py index 875eb1f03..c63178305 100644 --- a/tests/test_core/operators/test_streaming_joins.py +++ b/tests/test_core/operators/test_streaming_joins.py @@ -4,13 +4,18 @@ 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. These tests feed each kernel its 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: every flag -is the sync result's, except source info, which a complete table decides (step 5 of the -spec's row-built form F, ``_flag_source_info_nullability``) and is compared after it. +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 @@ -32,6 +37,7 @@ from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod from orcapod.core.operators.streaming_joins import ( TRANSPORT_COLUMNS, + _flag_by_values, # pyright: ignore[reportPrivateUsage] # F's last step StreamingJoin, StreamingJoinKernel, StreamingMergeJoin, @@ -41,11 +47,14 @@ 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 TAGS_FIRST, make_source 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) @@ -58,10 +67,22 @@ def _quiet_provisional() -> Any: def _transport(stream: StreamProtocol) -> pa.Table: - """An input's rows as the channel layer sends them: its transport columns.""" + """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] = [] @@ -123,32 +144,40 @@ def _rows(table: pa.Table) -> Counter[tuple[Any, ...]]: ) -def _settled(table: pa.Table) -> pa.Table: - return StaticOutputOperatorPod._flag_source_info_nullability(table) # pyright: ignore[reportPrivateUsage] +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 = _flag_by_values(got.select(want.column_names)) + want = _flag_by_values(want) + 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.""" + """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 expected.slice(0, 0).select(list(kernel.output_columns)) + else _transport(kernel.zero_row_result).select(list(kernel.output_columns)) ) - assert sorted(got.column_names) == sorted(expected.column_names) - got = _settled(got.select(expected.column_names)) - want = _settled(expected) - if got.num_rows or not want.num_rows: - 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 - if got.num_rows: - assert other.nullable == field.nullable, field.name - assert _rows(got) == _rows(want) + assert_same_fields(got, expected) + assert _rows(got.select(expected.column_names)) == _rows(expected) def _check( @@ -157,10 +186,21 @@ def _check( inputs: Sequence[StreamProtocol], seeds: Sequence[int] = SEEDS, ) -> None: - expected = _transport(sync(*inputs)) - tables = [_transport(stream) for stream in inputs] + 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) + 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 @@ -184,12 +224,20 @@ def _check( datetime(2026, 1, 2, tzinfo=timezone.utc), ], ), + "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"}], + [{"a": 1, "b": "x"}, {"a": 1, "b": "y"}, {"a": 2, "b": "x"}, None], ), - "list": (pa.large_list(pa.int64()), [[1, 2], [2], [], [1, 2]]), + "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") def _keyed_source( @@ -242,16 +290,73 @@ 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) -> None: +def test_join_two_inputs_every_key_type(pool: str, shared: str) -> None: left = _keyed_source( - "a", pool, 9, {"x": pa.int64(), "x2": pa.float64()}, 1, extra_tag="g" + "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, ) - right = _keyed_source("b", pool, 7, {"y": pa.int64(), "y2": pa.large_string()}, 2) 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 = [ @@ -317,12 +422,24 @@ def _merge_kernel(inputs: Sequence[StreamProtocol]) -> StreamingJoinKernel: return StreamingMergeJoin(MergeJoin(), inputs) -@pytest.mark.parametrize("pool", ["int", "nullable_int", "float", "struct", "list"]) -def test_merge_join_colliding_columns_in_both_argument_orders(pool: str) -> None: +@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, 8, {"x": pa.int64(), "c": pa.float64()}, 6, extra_tag="g" + "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, ) - right = _keyed_source("b", pool, 6, {"c": pa.float64(), "y": pa.int64()}, 7) for inputs in ((left, right), (right, left)): _check(_merge_kernel, MergeJoin().static_process, inputs) @@ -344,10 +461,18 @@ 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) -> None: - left = _keyed_source("a", pool, 9, {"x": pa.int64()}, 8, extra_tag="g") - right = _keyed_source("b", pool, 4, {"y": pa.int64()}, 9) +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)) @@ -479,3 +604,232 @@ def test_kernels_change_no_sync_result() -> None: 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) == [] From 91313691575320b9768f608220c2a72a8c07b9b9 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 02:59:07 -0800 Subject: [PATCH 3/9] 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 --- src/orcapod/core/operators/streaming_joins.py | 52 ++++++++++++++- .../operators/test_streaming_joins.py | 66 +++++++++++++++---- 2 files changed, 105 insertions(+), 13 deletions(-) diff --git a/src/orcapod/core/operators/streaming_joins.py b/src/orcapod/core/operators/streaming_joins.py index b1775ec78..0516d57b5 100644 --- a/src/orcapod/core/operators/streaming_joins.py +++ b/src/orcapod/core/operators/streaming_joins.py @@ -535,13 +535,36 @@ def _check_empty_inputs(self) -> None: @abstractmethod def _push(self, input_index: int, table: pa.Table) -> list[pa.Table]: - """Take an input's rows (in its layout, never empty); return output tables.""" + """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 output tables.""" + """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} " @@ -684,6 +707,19 @@ def finish( 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] @@ -700,6 +736,18 @@ def _push(self, input_index: int, table: pa.Table) -> list[pa.Table]: 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, and releases every earlier step, whose rows could only + reach it. 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] diff --git a/tests/test_core/operators/test_streaming_joins.py b/tests/test_core/operators/test_streaming_joins.py index c63178305..f19bf7ee4 100644 --- a/tests/test_core/operators/test_streaming_joins.py +++ b/tests/test_core/operators/test_streaming_joins.py @@ -50,7 +50,29 @@ from orcapod.system_constants import constants from .several_items import MAIN, MIXED, P, PLAIN, Q, R, DATA_TAGS, Arrangement -from .several_items import TAGS_FIRST, make_source +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. @@ -368,14 +390,12 @@ def test_join_three_inputs_every_argument_order(order: tuple[int, ...]) -> None: _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) -> None: +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 = [ - make_source(spec, Arrangement(spec.tags, TAGS_FIRST, roles)) - for spec in (MAIN, P, Q, R) - ] + 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)) @@ -444,10 +464,11 @@ def test_merge_join_colliding_columns_in_both_argument_orders( _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) -> None: - main = make_source(MAIN, Arrangement(MAIN.tags, TAGS_FIRST, roles)) - partner = make_source(P, Arrangement(P.tags, TAGS_FIRST, roles)) +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) @@ -476,9 +497,10 @@ def test_semi_join_every_key_type(pool: str, shared: str) -> 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) -> None: - main = make_source(MAIN, Arrangement(MAIN.tags, TAGS_FIRST, roles)) +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)) @@ -544,6 +566,28 @@ def test_a_batch_must_hold_its_inputs_columns_and_types() -> None: ) +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)) From 45eae5652968e5b2ab5db91ab3a102e74e667257 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 04:39:04 -0800 Subject: [PATCH 4/9] 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 --- src/orcapod/core/operators/streaming_joins.py | 27 ++++++++-- .../operators/test_streaming_joins.py | 53 +++++++++++++++++++ 2 files changed, 75 insertions(+), 5 deletions(-) diff --git a/src/orcapod/core/operators/streaming_joins.py b/src/orcapod/core/operators/streaming_joins.py index 0516d57b5..54852ecca 100644 --- a/src/orcapod/core/operators/streaming_joins.py +++ b/src/orcapod/core/operators/streaming_joins.py @@ -651,6 +651,12 @@ def __init__(self, operator: Join, inputs: Sequence[StreamProtocol]) -> None: 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 @@ -675,6 +681,7 @@ def __init__(self, operator: Join, inputs: Sequence[StreamProtocol]) -> None: 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 @@ -731,6 +738,8 @@ def _push(self, input_index: int, table: pa.Table) -> list[pa.Table]: 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] @@ -739,8 +748,12 @@ 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, and releases every earlier step, whose rows could only - reach it. Closing never emits a row. + 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. @@ -753,12 +766,16 @@ def _close(self, input_index: int) -> list[pa.Table]: position = self._position[input_index] step, side = (0, 0) if position == 0 else (position - 1, 1) self._links[step].close(side) - # A step that can never emit again ends the next step's left side, and no - # earlier step's rows are needed any more (they could only reach this one). for step, link in enumerate(self._links): if not link.exhausted: continue - for earlier in self._links[:step]: + # 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) diff --git a/tests/test_core/operators/test_streaming_joins.py b/tests/test_core/operators/test_streaming_joins.py index f19bf7ee4..586ea0905 100644 --- a/tests/test_core/operators/test_streaming_joins.py +++ b/tests/test_core/operators/test_streaming_joins.py @@ -219,6 +219,10 @@ def _check( 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 @@ -877,3 +881,52 @@ def test_semi_join_never_holds_a_left_row_with_a_null_key(pool: str) -> None: 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"]]), + ] + 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"], + ) From 251bb52530417b4a886302b05aff04115c9acfd9 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 04:58:03 -0800 Subject: [PATCH 5/9] 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 --- src/orcapod/core/operators/streaming_joins.py | 123 ++++++-------- .../operators/test_streaming_joins.py | 150 +++++++++++++++++- 2 files changed, 194 insertions(+), 79 deletions(-) diff --git a/src/orcapod/core/operators/streaming_joins.py b/src/orcapod/core/operators/streaming_joins.py index 54852ecca..ba86c1aa3 100644 --- a/src/orcapod/core/operators/streaming_joins.py +++ b/src/orcapod/core/operators/streaming_joins.py @@ -13,6 +13,14 @@ 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 @@ -26,13 +34,19 @@ 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 when the offending batch arrives; rows already emitted belong to a run that then - fails. + 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. An input with no rows makes every join's - result empty, so no row was emitted before. + 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 @@ -47,15 +61,16 @@ 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 (``_flag_by_values``, + 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 step of a ``Join`` chain that can never emit again (a side -closed holding no row) releases its successor's other side and every earlier step, and -``SemiJoin`` never keeps a left row whose key holds a top-level null. +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 @@ -89,7 +104,7 @@ _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 +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 @@ -103,69 +118,11 @@ _ROW = ("__streaming_left_row", "__streaming_right_row") -# TODO(ITL-1360): ``_row_built_columns`` and ``_flag_by_values`` are interim copies of -# stage 2's ``StaticOutputOperatorPod._row_built_columns`` and ``_flag_by_values`` (the -# row-built form F, same names and behaviour); call those once stage 2 is on job-speed. -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. - - The steps of F that each row decides on its own: user tags in tag order, system tags - in table order, the data columns that are not data-tags and the source info of every - data column, both in data-key order, normalized to the large types without keeping - ``null`` (a row's datagram stores a ``null`` column as ``large_string``). - - Args: - table: A table of user tags, system tags, data and source info. - keys: The tag keys and the data keys of its stream (``stream.keys()``). - - Returns: - The same arrays, selected and ordered, in their large types. - """ - 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]) - ) - - -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, on a complete table only. No schema metadata is kept. - - Args: - table: A table of user tags, system tags, data and source info. - - Returns: - The same arrays under the new field flags. - """ - 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) - ] - return pa.Table.from_arrays(table.columns, schema=pa.schema(fields)) - - 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 - (``_flag_by_values``): one record batch of many cannot. + (``StaticOutputOperatorPod._flag_by_values``): one record batch of many cannot. """ prefixes = (constants.SYSTEM_TAG_PREFIX, constants.SOURCE_PREFIX) return pa.schema( @@ -193,7 +150,7 @@ def _row_built_zero_rows(stream: StreamProtocol) -> tuple[StreamProtocol, bool]: 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 = _flag_by_values(_row_built_columns(table, stream.keys())) + 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 ) @@ -357,6 +314,8 @@ def held_rows(self) -> int: 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). @@ -382,6 +341,12 @@ def push(self, side: int, table: pa.Table) -> pa.Table | None: this, other = self.sides[side], self.sides[1 - side] if this.schema is None: this.schema = table.schema + 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: @@ -455,6 +420,7 @@ def __init__( ) 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( @@ -506,23 +472,31 @@ def close(self, input_index: int) -> list[pa.RecordBatch]: self._closed[input_index] = True emitted = self._emitted(self._close(input_index)) if all(self._closed): - self._check_empty_inputs() + 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) -> None: + 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 + return None pod = StaticOutputOperatorPod - self.operator.static_process( + return self.operator.static_process( *( pod._materialize_upstream([], stream) # pyright: ignore[reportPrivateUsage] # the operators' one form of an input if is_empty @@ -608,11 +582,12 @@ 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 (``_flag_by_values``). + 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) diff --git a/tests/test_core/operators/test_streaming_joins.py b/tests/test_core/operators/test_streaming_joins.py index 586ea0905..a402e21e8 100644 --- a/tests/test_core/operators/test_streaming_joins.py +++ b/tests/test_core/operators/test_streaming_joins.py @@ -37,7 +37,6 @@ from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod from orcapod.core.operators.streaming_joins import ( TRANSPORT_COLUMNS, - _flag_by_values, # pyright: ignore[reportPrivateUsage] # F's last step StreamingJoin, StreamingJoinKernel, StreamingMergeJoin, @@ -159,18 +158,32 @@ def _value(value: Any) -> Any: return value +def _exact(column: pa.ChunkedArray[Any]) -> pa.ChunkedArray[Any]: + """A temporal column as its integer storage: Python values drop nanoseconds.""" + arrow_type = column.type + if pa.types.is_timestamp(arrow_type) or pa.types.is_time64(arrow_type): + return column.cast(pa.int64()) + if pa.types.is_duration(arrow_type) or pa.types.is_date64(arrow_type): + return column.cast(pa.int64()) + if pa.types.is_time32(arrow_type) or pa.types.is_date32(arrow_type): + return column.cast(pa.int32()) + return column + + 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 table.to_pylist() + 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 = _flag_by_values(got.select(want.column_names)) - want = _flag_by_values(want) + 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 @@ -250,6 +263,10 @@ def _check( 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")], @@ -263,7 +280,7 @@ def _check( "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") +NULL_POOLS = ("decimal", "decimal256", "list", "nullable_int", "struct", "timestamp_ns") def _keyed_source( @@ -930,3 +947,126 @@ def _empty_data_tag_stream(data: str) -> ArrowTableStream: 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): + instance.push(1 - whole, first_row.to_batches()[0]) + + +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 From fc6b3721129f68a85c619e00a96d02510a253f26 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 05:24:25 -0800 Subject: [PATCH 6/9] 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 --- src/orcapod/core/operators/streaming_joins.py | 436 +++++++++++++++++- .../operators/test_streaming_rejoin.py | 430 +++++++++++++++++ 2 files changed, 864 insertions(+), 2 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 ba86c1aa3..b9a717045 100644 --- a/src/orcapod/core/operators/streaming_joins.py +++ b/src/orcapod/core/operators/streaming_joins.py @@ -1,7 +1,7 @@ """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 async path of ``Join``, ``MergeJoin``, ``SemiJoin`` and ``Rejoin`` (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 @@ -99,6 +99,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 @@ -993,3 +997,431 @@ 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 (never an input column). +_OCCURRENCE = "__streaming_occurrence" + + +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 _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 work stays linear in the rows. + """ + 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.""" + left_take = pa.array(left_rows, pa.int64()) + right_take = pa.array(right_rows, pa.int64()) + names: list[str] = [] + arrays: list[Any] = [] + for name in left.column_names: + names.append(name) + arrays.append(left.column(name).combine_chunks().take(left_take)) + for name in right.column_names: + if name not in left.column_names: + names.append(name) + arrays.append(right.column(name).combine_chunks().take(right_take)) + 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. + + A second join of the arriving rows that matched nothing, on the system tags only, + against the other side's remaining rows finds the rows of one origin row (their + repeats paired in arrival order); for each other shared column, one join on the + system tags and that column, nulls equal (``Join``'s equality otherwise), tells + which of those pairs agree in it. + """ + row, other_row = _ROW[side], _ROW[1 - side] + mine = _occurrences(polars_key_frame(rest, self.shared, row), self.system) + theirs = _occurrences(other.frame(), self.system) + origin = [*self.system, _OCCURRENCE] + pairs = mine.select([*origin, row]).join( + theirs.select([*origin, other_row]), on=origin, how="inner" + ) + if not pairs.height: + return + for name in self.others: + if name in self.differing: + continue + agree = mine.select([*origin, name, row]).join( + theirs.select([*origin, name, other_row]), + on=[*origin, name], + how="inner", + nulls_equal=True, + ) + if agree.height < pairs.height: + self.differing.add(name) + + +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. + + 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; 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. With + two inputs the columns are the sync path's. A difference from the sync path + (accepted provisionally, November 22, 2026): with three or more inputs the warning + is detected per link, the rows rejoined so far against the next input, so a + difference between two inputs that are not adjacent in the chain, for an origin row + the input between them lacks, is not warned about; the sync path compares every pair + of inputs. The rows are identical either way. The alternative 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, so every refusal is raised before the + first batch. + + 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) + return [] if result is None else [result] + + 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) + 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) + 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..28411830d --- /dev/null +++ b/tests/test_core/operators/test_streaming_rejoin.py @@ -0,0 +1,430 @@ +"""The streaming Rejoin kernel gives the sync Rejoin's rows, whatever the arrivals. + +ITL-1362 (ITL-1347, stage 5): ``Rejoin`` runs on the async path as symmetric matches on +every shared column over Arrow record batches (``StreamingRejoin``), with 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. 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 random +import warnings +from collections.abc import Sequence +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 + _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)) From cf44c43b928fe628f36bfe11fcf645aaf7dcfff7 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 05:45:41 -0800 Subject: [PATCH 7/9] 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 --- src/orcapod/core/operators/streaming_joins.py | 3 + .../operators/test_streaming_joins.py | 69 +++++++++++++++---- 2 files changed, 60 insertions(+), 12 deletions(-) diff --git a/src/orcapod/core/operators/streaming_joins.py b/src/orcapod/core/operators/streaming_joins.py index ba86c1aa3..6b9d64e7c 100644 --- a/src/orcapod/core/operators/streaming_joins.py +++ b/src/orcapod/core/operators/streaming_joins.py @@ -341,6 +341,9 @@ def push(self, side: int, table: pa.Table) -> pa.Table | 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. diff --git a/tests/test_core/operators/test_streaming_joins.py b/tests/test_core/operators/test_streaming_joins.py index a402e21e8..35ee15176 100644 --- a/tests/test_core/operators/test_streaming_joins.py +++ b/tests/test_core/operators/test_streaming_joins.py @@ -22,6 +22,7 @@ import itertools import random +import re import struct import warnings from collections import Counter @@ -158,16 +159,41 @@ def _value(value: Any) -> Any: return value +def _integer_type(arrow_type: pa.DataType) -> 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 temporal column as its integer storage: Python values drop nanoseconds.""" - arrow_type = column.type - if pa.types.is_timestamp(arrow_type) or pa.types.is_time64(arrow_type): - return column.cast(pa.int64()) - if pa.types.is_duration(arrow_type) or pa.types.is_date64(arrow_type): - return column.cast(pa.int64()) - if pa.types.is_time32(arrow_type) or pa.types.is_date32(arrow_type): - return column.cast(pa.int32()) - return column + """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, ...]]: @@ -914,7 +940,7 @@ def stream(data: str, tokens: list[list[str]]) -> ArrowTableStream: 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"]]), + stream("z", [] if name == "z" else [["f"], ["g", "h", "i"]]), ] for name in ("v", "w", "z") } @@ -1018,7 +1044,7 @@ def test_with_several_offending_pairs_the_first_observed_is_refused( # 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+\]" + 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) @@ -1026,8 +1052,14 @@ def test_with_several_offending_pairs_the_first_observed_is_refused( 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): + 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: @@ -1070,3 +1102,16 @@ def keyed(source_id: str, keys: list[int | None], data: str) -> ArrowTableSource 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 4f7e3516b06e2ee6ab718f69865b3a708996cd7b Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 05:56:40 -0800 Subject: [PATCH 8/9] 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 --- src/orcapod/core/operators/streaming_joins.py | 136 ++++++++--- .../operators/test_streaming_rejoin.py | 216 ++++++++++++++++++ 2 files changed, 323 insertions(+), 29 deletions(-) diff --git a/src/orcapod/core/operators/streaming_joins.py b/src/orcapod/core/operators/streaming_joins.py index ca10d4cf1..c06673631 100644 --- a/src/orcapod/core/operators/streaming_joins.py +++ b/src/orcapod/core/operators/streaming_joins.py @@ -1026,12 +1026,46 @@ def _with_system_tags(table: pa.Table, keys: Sequence[str]) -> pa.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 work stays linear in the rows. + 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) @@ -1213,18 +1247,22 @@ def _pairs( 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.""" - left_take = pa.array(left_rows, pa.int64()) - right_take = pa.array(right_rows, pa.int64()) + """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.column(name).combine_chunks().take(left_take)) + 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.column(name).combine_chunks().take(right_take)) + 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( @@ -1281,26 +1319,54 @@ class StreamingRejoin(StreamingJoinKernel): - once one side closes, the other side's remaining rows are dropped, and an arriving row either matches at once or is dropped. + Cost: one vectorized join per arriving batch against the other side's remaining rows + (and their occurrence numbers), so O(held rows) per batch, as in the ``Join`` + kernels; values are taken from the held tables' chunks by row number, never by + copying a whole held table. 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; when the last input closes, the kernel issues + 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. With - two inputs the columns are the sync path's. A difference from the sync path - (accepted provisionally, November 22, 2026): with three or more inputs the warning - is detected per link, the rows rejoined so far against the next input, so a - difference between two inputs that are not adjacent in the chain, for an origin row - the input between them lacks, is not warned about; the sync path compares every pair - of inputs. The rows are identical either way. The alternative 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, so every refusal is raised before the - first batch. + (``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``. @@ -1389,8 +1455,29 @@ def _push(self, input_index: int, table: pa.Table) -> list[pa.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. @@ -1409,16 +1496,7 @@ def _close(self, input_index: int) -> list[pa.Table]: 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 - 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) + self._release_exhausted() if all(self._closed): differing = {name for link in self._links for name in link.differing} if differing: diff --git a/tests/test_core/operators/test_streaming_rejoin.py b/tests/test_core/operators/test_streaming_rejoin.py index 28411830d..338bb4b15 100644 --- a/tests/test_core/operators/test_streaming_rejoin.py +++ b/tests/test_core/operators/test_streaming_rejoin.py @@ -14,6 +14,7 @@ import dataclasses import itertools +import math import random import warnings from collections.abc import Sequence @@ -37,6 +38,7 @@ 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 @@ -428,3 +430,217 @@ def test_three_inputs_miss_a_difference_the_middle_input_lacks() -> None: 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 From a407142f40dada8b18b0db93c5b185a285722f08 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 06:41:58 -0800 Subject: [PATCH 9/9] 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 --- src/orcapod/core/operators/streaming_joins.py | 68 ++++---- .../operators/test_streaming_rejoin.py | 151 ++++++++++++++++-- 2 files changed, 179 insertions(+), 40 deletions(-) diff --git a/src/orcapod/core/operators/streaming_joins.py b/src/orcapod/core/operators/streaming_joins.py index c06673631..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``, ``SemiJoin`` and ``Rejoin`` (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 +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. @@ -1002,8 +1004,10 @@ def _close(self, input_index: int) -> list[pa.Table]: return [] -# The occurrence-number column of a Rejoin key frame (never an input column). +# 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: @@ -1274,32 +1278,31 @@ def _pairs( 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. - A second join of the arriving rows that matched nothing, on the system tags only, - against the other side's remaining rows finds the rows of one origin row (their - repeats paired in arrival order); for each other shared column, one join on the - system tags and that column, nulls equal (``Join``'s equality otherwise), tells - which of those pairs agree in it. + 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, other_row = _ROW[side], _ROW[1 - side] - mine = _occurrences(polars_key_frame(rest, self.shared, row), self.system) - theirs = _occurrences(other.frame(), self.system) + row = _ROW[side] + names = [name for name in self.others if name not in self.differing] + if not names: + return origin = [*self.system, _OCCURRENCE] - pairs = mine.select([*origin, row]).join( - theirs.select([*origin, other_row]), on=origin, how="inner" + 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 - for name in self.others: - if name in self.differing: - continue - agree = mine.select([*origin, name, row]).join( - theirs.select([*origin, name, other_row]), - on=[*origin, name], - how="inner", - nulls_equal=True, - ) - if agree.height < pairs.height: - self.differing.add(name) + 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): @@ -1319,10 +1322,15 @@ class StreamingRejoin(StreamingJoinKernel): - once one side closes, the other side's remaining rows are dropped, and an arriving row either matches at once or is dropped. - Cost: one vectorized join per arriving batch against the other side's remaining rows - (and their occurrence numbers), so O(held rows) per batch, as in the ``Join`` - kernels; values are taken from the held tables' chunks by row number, never by - copying a whole held table. A long run of one-row batches against a large buffer is + 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 diff --git a/tests/test_core/operators/test_streaming_rejoin.py b/tests/test_core/operators/test_streaming_rejoin.py index 338bb4b15..f33819534 100644 --- a/tests/test_core/operators/test_streaming_rejoin.py +++ b/tests/test_core/operators/test_streaming_rejoin.py @@ -1,13 +1,18 @@ -"""The streaming Rejoin kernel gives the sync Rejoin's rows, whatever the arrivals. - -ITL-1362 (ITL-1347, stage 5): ``Rejoin`` runs on the async path as symmetric matches on -every shared column over Arrow record batches (``StreamingRejoin``), with 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. 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. +"""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 @@ -18,6 +23,7 @@ import random import warnings from collections.abc import Sequence +from pathlib import Path from typing import Any import polars as pl @@ -644,3 +650,128 @@ def counted(self: pl.DataFrame, *args: Any, **kwargs: Any) -> pl.DataFrame: # 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