From 6babb8ea4458cb157a8e14fce6a136a70eba99f9 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Mon, 23 Nov 2026 03:08:18 -0800 Subject: [PATCH] fix(channels): CodeRabbit's final pass on PR 510: settled token types across MergeJoin inputs, map keys, abandoned readers, cancelled closes (ITL-1362) CodeRabbit's review of PR 510 at 365f2a08, on the record-batch channels and kernels (no wired job path: nothing in a node, pipeline module or orchestrator calls them on job-speed). Each source fix has a regression test that fails with only the fix reverted. - StreamingMergeJoin compares the two inputs' settled source-info token types for every shared source-info column (require_shared_arrow_type), as MergeJoin refuses two Arrow types of one column after rebuilding each input from its rows: before any match, whether keys match or not; inputs that settle to one type still join. - The send check follows map keys too (a struct key with a non-nullable child), reading entries from the map's offsets (a cast refuses the very nulls looked for). - A reader dropped before its first read (no owner, no claim) closes its feed when it is freed, so a bounded producer never waits for it. - close_inputs attempts every close when one is cancelled, raising the cancellation afterwards; an operator error in flight keeps precedence (the cancellation noted). - A row-by-row operator settles its input's token types across batches and refuses a batch that cannot make one input table with the earlier ones, as the sync path refuses the input. Tests: fixtures state their tag roles (tag_only_columns=()), the all-null join pushes emit nothing, the rejoin schedule asserts the alternate pairing and an exact held-row peak sampled after every push, float columns compared by their bits, the _check helper and a barrier test documented. Co-Authored-By: Claude Opus 5.5 --- .../core/operators/static_output_pod.py | 21 ++ src/orcapod/core/operators/streaming_joins.py | 41 +++- src/orcapod/core/record_batch_channels.py | 41 +++- .../core/streams/record_batch_input.py | 6 + .../test_record_batch_channels.py | 14 +- .../test_record_batch_review_findings.py | 223 ++++++++++++++++++ .../operators/test_record_batch_execution.py | 10 + .../operators/test_streaming_joins.py | 36 ++- .../operators/test_streaming_rejoin.py | 19 +- 9 files changed, 389 insertions(+), 22 deletions(-) diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index 622fcf7d0..572e4b1a0 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -1122,7 +1122,12 @@ async def async_execute_batches( try: if self.ROW_BY_ROW: (channel,) = inputs + # The input's token types across its batches: a batch whose tokens + # cannot make one table with the earlier ones is refused, as the sync + # path refuses the whole input, never processed alone. + settled: dict[str, pa.DataType] = {} async for batch in channel: + settled = settle_token_types(batch, settled) await self._send_processed([batch], channel.stream, output) else: streams = await _streams_of(inputs) @@ -1209,18 +1214,34 @@ async def close_inputs( inputs: The operator's input channels. error: The error the operator is failing with, if any. + A cancellation that arrives during one close does not stop the others: every + input's close is attempted, then the cancellation is raised (before any ordinary + close error); when the operator already failed, its error keeps precedence and + the cancellation is added to it as a note. + Raises: + asyncio.CancelledError: If a close was cancelled, when ``error`` is ``None``. Exception: The first error of a close, when ``error`` is ``None``. """ first: Exception | None = None + cancelled: asyncio.CancelledError | None = None for channel in inputs: try: await channel.close() + except asyncio.CancelledError as cancellation: + if error is not None: + error.add_note( + f"Closing an input channel was cancelled: {cancellation!r}" + ) + elif cancelled is None: + cancelled = cancellation except Exception as failure: # noqa: BLE001 # every input is closed first if error is not None: error.add_note(f"Closing an input channel also failed: {failure!r}") elif first is None: first = failure + if cancelled is not None: + raise cancelled if first is not None: raise first diff --git a/src/orcapod/core/operators/streaming_joins.py b/src/orcapod/core/operators/streaming_joins.py index 5099269ef..16e93f458 100644 --- a/src/orcapod/core/operators/streaming_joins.py +++ b/src/orcapod/core/operators/streaming_joins.py @@ -78,7 +78,7 @@ from __future__ import annotations from abc import ABC, abstractmethod -from collections.abc import Callable, Sequence +from collections.abc import Callable, Mapping, Sequence from typing import Any, ClassVar import numpy as np @@ -95,6 +95,7 @@ _matched_pairs, # pyright: ignore[reportPrivateUsage] # Join's one rule _with_common_key, # pyright: ignore[reportPrivateUsage] # Join's one rule ) +from orcapod.core.operators.base import require_shared_arrow_type from orcapod.core.operators.key_nullability import key_nullable from orcapod.core.operators.merge_join import ( MergeJoin, @@ -611,11 +612,27 @@ def _as_input_table(self, input_index: int, batch: pa.RecordBatch) -> pa.Table: + f"{input_index} is {actual.type} in a batch, but " + f"{field.type} in its stream" ) + self._check_settled_token_types(input_index, token_types) self._token_types[input_index] = token_types if not table.num_rows: return layout.empty_table() return pa.Table.from_arrays(columns, schema=layout) + def _check_settled_token_types( + self, input_index: int, token_types: Mapping[str, pa.DataType] + ) -> None: + """Refuse a batch whose settled source-info token types this operator refuses. + + Called before the batch changes anything, with the token types its input + settles to with it (``settle_token_types``). The kernels whose sync path + accepts any token types (the plain join, the semi-join) accept every batch. + + Args: + input_index: The batch's input, in call order. + token_types: The input's source-info token types, this batch included. + """ + del input_index, token_types + def _emitted(self, tables: list[pa.Table]) -> list[pa.RecordBatch]: """The record batches of the output tables, holding ``output_columns``. @@ -840,6 +857,28 @@ def __init__(self, operator: MergeJoin, inputs: Sequence[StreamProtocol]) -> Non ).type_converter self._link = _BinaryLink(sorted(self._shared_tags), self._finish) + def _check_settled_token_types( + self, input_index: int, token_types: Mapping[str, pa.DataType] + ) -> None: + """Refuse a batch when a source-info column both inputs carry settles to two + token types, as ``MergeJoin`` refuses inputs whose Arrow types for one column + disagree (``require_shared_arrow_type``). + + The sync path types each input's tokens over its complete table before it + joins, so it refuses the run before any match, whether keys match or not. + A kernel learns an input's token type from its first batch with a token and + refuses at the batch that makes the two inputs disagree. + + Raises: + InputValidationError: If the two inputs' token types for a shared + source-info column differ. + """ + other = self._token_types[1 - input_index] + for name in sorted(token_types.keys() & other.keys()): + mine, theirs = token_types[name], other[name] + left, right = (mine, theirs) if input_index == 0 else (theirs, mine) + _ = require_shared_arrow_type("MergeJoin", name, left, right) + @property def held_rows(self) -> int: return self._link.held_rows diff --git a/src/orcapod/core/record_batch_channels.py b/src/orcapod/core/record_batch_channels.py index 4493f3dd7..3e94bbe12 100644 --- a/src/orcapod/core/record_batch_channels.py +++ b/src/orcapod/core/record_batch_channels.py @@ -486,7 +486,7 @@ def _null_under_non_nullable( Judged on the values the array carries: a struct child under a null struct row, and the items of a null list, are not values. Struct children, list items (of - every list kind) and map items are followed to any depth. + every list kind), map keys and map items are followed to any depth. Args: array: A column as sent. @@ -494,7 +494,8 @@ def _null_under_non_nullable( path: The path of ``array`` inside the column, for the answer. Returns: - The path of the first such field (``.a``, ``[]``, ``{}``), or ``None``. + The path of the first such field (``.a``, ``[]``, ``{key}``, ``{}``), or + ``None``. """ if isinstance(kind, pa.StructType): children = cast("pa.StructArray", array).flatten() # pyright: ignore[reportUnknownMemberType, reportUnknownVariableType] @@ -519,14 +520,14 @@ def _null_under_non_nullable( return None if isinstance(kind, pa.MapType): item = kind.item_field - # A map's entries as a list of structs, which list_flatten reads. - entries = array.cast(pa.large_list(pa.struct([kind.key_field, item]))) # pyright: ignore[reportUnknownMemberType, reportUnknownVariableType, reportUnknownArgumentType] - items = pc.list_flatten(entries) # pyright: ignore[reportUnknownMemberType, reportUnknownVariableType, reportCallIssue, reportArgumentType] # a list array - values = cast("pa.StructArray", items).flatten()[1] # pyright: ignore[reportUnknownMemberType, reportUnknownVariableType] + keys, values = _map_entries(cast("pa.MapArray[Any, Any]", array)) # pyright: ignore[reportExplicitAny] # any map + # A key is never null; what it holds may be (a struct key's children). + if inner := _null_under_non_nullable(keys, kind.key_type, f"{path}{{key}}"): + return inner where = f"{path}{{}}" - if not item.nullable and values.null_count: # pyright: ignore[reportUnknownMemberType] + if not item.nullable and values.null_count: return where - return _null_under_non_nullable(values, item.type, where) # pyright: ignore[reportUnknownArgumentType] + return _null_under_non_nullable(values, item.type, where) if isinstance(kind, (pa.ListType, pa.LargeListType, pa.FixedSizeListType)): item = kind.value_field values = pc.list_flatten(array) # pyright: ignore[reportUnknownMemberType, reportUnknownVariableType] @@ -537,6 +538,30 @@ def _null_under_non_nullable( return None +def _map_entries(array: pa.MapArray) -> tuple[pa.Array[Any], pa.Array[Any]]: # pyright: ignore[reportExplicitAny, reportMissingTypeArgument] # any map + """The keys and the items of ``array``'s maps: of its valid rows, in its slice. + + Read from the map's offsets, never by casting the entries (a cast refuses the + very nulls under a non-nullable field that are looked for). + + Args: + array: A map column, possibly a slice. + + Returns: + The keys and the items of the entries of the rows that are not null. + """ + offsets = array.offsets.to_numpy(zero_copy_only=False) # pyright: ignore[reportUnknownMemberType, reportUnknownVariableType] + valid = array.is_valid().to_numpy(zero_copy_only=False) # pyright: ignore[reportUnknownMemberType, reportUnknownVariableType] + indices = [ + position + for row, ok in enumerate(valid) # pyright: ignore[reportUnknownArgumentType, reportUnknownVariableType] + if ok + for position in range(int(offsets[row]), int(offsets[row + 1])) # pyright: ignore[reportUnknownArgumentType] + ] + taken = pa.array(indices, pa.int64()) + return array.keys.take(taken), array.items.take(taken) # pyright: ignore[reportUnknownMemberType, reportUnknownVariableType] + + def _is_token_type(kind: pa.DataType) -> bool: """Whether ``kind`` is a source-info token type: ``large_string``, or a list of one. diff --git a/src/orcapod/core/streams/record_batch_input.py b/src/orcapod/core/streams/record_batch_input.py index 4cb57ec64..c7919638b 100644 --- a/src/orcapod/core/streams/record_batch_input.py +++ b/src/orcapod/core/streams/record_batch_input.py @@ -92,6 +92,12 @@ def __init__(self, stream: StreamProtocol, feed: BatchFeed) -> None: self._owner: asyncio.Task[Any] | None = None self._claim: weakref.ref[_Claim] | None = None self._claim_release: weakref.finalize[Any, Any] | None = None + # A reader dropped before anyone reads it (no owner task, no claim): when it + # is freed, its feed is closed, so a bounded producer never waits for it. A + # feed never refers to its channel, so this holds nothing alive; a live + # unread reader stays registered and gets the first batch. + self._release_when_freed = weakref.finalize(self, feed.close) + self._release_when_freed.atexit = False @property def stream(self) -> StreamProtocol: diff --git a/tests/test_channels/test_record_batch_channels.py b/tests/test_channels/test_record_batch_channels.py index da1bd5450..d4416e6db 100644 --- a/tests/test_channels/test_record_batch_channels.py +++ b/tests/test_channels/test_record_batch_channels.py @@ -79,7 +79,8 @@ async def bounded() -> T: def source(n: int = 7, source_id: str = "events") -> ArrowTableSource: - """``n`` rows: tags ``subject`` and ``trial`` (a data-tag too), three data columns.""" + """``n`` rows: tags ``subject`` and ``trial``, both data-tags too (stated: no + tag-only column), three data columns.""" return ArrowTableSource( pa.table( { @@ -93,6 +94,7 @@ def source(n: int = 7, source_id: str = "events") -> ArrowTableSource: } ), tag_columns=["subject", "trial"], + tag_only_columns=(), source_id=source_id, ) @@ -602,10 +604,12 @@ async def read() -> None: def test_a_barrier_leaves_no_conversion_behind_when_an_input_was_read() -> None: - """A barrier whose second input was read already: its setup fails, and the first - input's conversion, already started and waiting for more of its producer's - batches, is cancelled and awaited before the barrier raises: its reader is closed - and the producer released, so no task fails later with nobody to hear it.""" + """A barrier whose second input was read already: the second input's setup fails + synchronously, before the first input's conversion (already scheduled) has begun. + That conversion is cancelled and awaited before the barrier raises, its reader is + closed and the producer released, so no task fails later with nobody to hear it. + A failure after a barrier has taken a batch is + ``test_a_barrier_that_read_part_of_a_failed_input_never_computes``.""" left = source(2) right = source(2, source_id="other") left_batches = batches_of(left, 1) diff --git a/tests/test_channels/test_record_batch_review_findings.py b/tests/test_channels/test_record_batch_review_findings.py index dba84b35e..4b775ff11 100644 --- a/tests/test_channels/test_record_batch_review_findings.py +++ b/tests/test_channels/test_record_batch_review_findings.py @@ -813,6 +813,14 @@ def test_tokens_that_cannot_make_one_input_table_are_refused( [[("a", None)], [("b", 2)]], [None, [("b", 2)]], ), + "map_key": ( + pa.map_( + pa.field("key", pa.struct([NON_NULLABLE]), nullable=False), # pyright: ignore[reportArgumentType] # pyarrow takes a field for the key + pa.int64(), + ), + [[({"required": None}, 1)], [({"required": 2}, 3)]], + [None, [({"required": 2}, 3)]], + ), "struct_in_struct": ( pa.struct([pa.field("s", pa.struct([NON_NULLABLE]))]), [{"s": {"required": None}}, {"s": None}], @@ -846,3 +854,218 @@ async def write() -> None: await output.send(batch) asyncio.run(write()) + + +# --- CodeRabbit on PR 510, final pass (365f2a08) ------------------------------------ + + +def _deep_token_stream(tokens: list[Any], keys: list[int]) -> ArrowTableStream: # pyright: ignore[reportExplicitAny] # tokens of any shape + """Tag ``k``, data ``x`` and ``y``, ``x``'s source info declared two list levels + deep.""" + return ArrowTableStream( + pa.table( + { + "k": pa.array(keys, pa.int64()), + "x": pa.array([10 * k for k in keys], pa.int64()), + "y": pa.array([k + 0.5 for k in keys], pa.float64()), + "_source_x": pa.array(tokens, DEEP_TOKENS), + } + ), + tag_columns=["k"], + ) + + +@pytest.mark.parametrize( + "matching", [True, False], ids=["keys_match", "no_key_matches"] +) +@pytest.mark.parametrize("shallow", ["left", "right"]) +def test_merge_join_inputs_whose_tokens_settle_to_two_types_are_refused( + shallow: str, matching: bool +) -> None: + """CodeRabbit on PR 510 (major): both inputs declare ``_source_x`` two list levels + deep, but one delivers ``[]`` (one level, as its rows type it) and the other + ``[["b"]]``. The sync path rebuilds each input from its rows and ``MergeJoin`` + refuses the two types of one column; the kernel compares the inputs' settled token + types and refuses too, with the same error, whether or not a key matches.""" + from orcapod.core.operators import MergeJoin + from orcapod.core.operators.streaming_joins import ( + TRANSPORT_COLUMNS, + StreamingMergeJoin, + ) + from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod + from orcapod.errors import InputValidationError + + right_keys = [1, 2] if matching else [7, 8] + empty = _deep_token_stream([[], []], [1, 2]) + deep = _deep_token_stream([[["b"]], [["c"]]], right_keys) + left, right = (empty, deep) if shallow == "left" else (deep, empty) + + def rebuilt(stream: ArrowTableStream) -> Any: # pyright: ignore[reportExplicitAny] + return StaticOutputOperatorPod._materialize_upstream( # pyright: ignore[reportPrivateUsage] # the rows as a job hands them on + list(stream.iter_data()), stream + ) + + with pytest.raises(InputValidationError) as sync_error: + _ = MergeJoin().static_process(rebuilt(left), rebuilt(right)) + kernel = StreamingMergeJoin(MergeJoin(), (left, right)) + batches = [ + rebuilt(s).as_table(columns=TRANSPORT_COLUMNS).combine_chunks().to_batches()[0] + for s in (left, right) + ] + assert kernel.push(0, batches[0]) == [] + with pytest.raises(InputValidationError) as kernel_error: + _ = kernel.push(1, batches[1]) + assert str(kernel_error.value) == str(sync_error.value) + + +def test_merge_join_inputs_whose_tokens_settle_to_one_type_are_joined() -> None: + """CodeRabbit on PR 510: both inputs settle to one list level: they join.""" + from orcapod.core.operators import MergeJoin + from orcapod.core.operators.streaming_joins import ( + TRANSPORT_COLUMNS, + StreamingMergeJoin, + ) + from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod + + left = _deep_token_stream([[], []], [1, 2]) + right = _deep_token_stream([[], []], [1, 2]) + kernel = StreamingMergeJoin(MergeJoin(), (left, right)) + out: list[pa.RecordBatch] = [] + for index, stream in enumerate((left, right)): + table = StaticOutputOperatorPod._materialize_upstream( # pyright: ignore[reportPrivateUsage] # the rows as a job hands them on + list(stream.iter_data()), stream + ).as_table(columns=TRANSPORT_COLUMNS) + out += kernel.push(index, table.combine_chunks().to_batches()[0]) + out += kernel.close(0) + kernel.close(1) + assert sum(batch.num_rows for batch in out) == 2 + + +@pytest.mark.parametrize( + "queued", [False, True], ids=["nothing_queued", "a_batch_queued"] +) +def test_a_bounded_reader_dropped_before_its_first_read_releases_its_producer( + queued: bool, +) -> None: + """CodeRabbit on PR 510 (major): a reader opened on a bounded output and dropped + before any read (no owner task, no claim) is closed when it is freed, so the + producer does not wait for it; a live reader still gets every batch.""" + stream = source(3) + batches = batches_of(stream, 1) + + async def go() -> list[int]: + output = OutputChannel(stream, retain=False, buffer_size=1) + live = output.open_reader() + dropped = output.open_reader() + if queued: + await output.send(batches[0]) # queued for both readers, never read + got = [_trial(await live.receive())] + else: + got = [] + del dropped + gc.collect() + for batch in batches[1:] if queued else batches: + async with asyncio.timeout(TIMEOUT): + await output.send(batch) # nothing waits for the dropped reader + got.append(_trial(await live.receive())) + return got + + assert asyncio.run(go()) == [0, 1, 2] + + +class _CancelledClose: + """An input channel whose close is cancelled.""" + + def __init__(self) -> None: + self.closed = False + + async def close(self) -> None: + self.closed = True + raise asyncio.CancelledError() + + +@pytest.mark.parametrize("failing", [False, True], ids=["succeeding", "failing"]) +def test_a_cancelled_close_still_closes_every_other_input(failing: bool) -> None: + """CodeRabbit on PR 510 (outside the diff): a close cancelled while an operator + closes its inputs does not stop the others; the cancellation is raised once every + input is closed, and an operator error in flight keeps precedence (the + cancellation is noted on it).""" + stream = source(3) + first, second, _ = batches_of(stream, 1) + + async def go() -> BaseException | None: + producer = OutputChannel(stream, retain=False, buffer_size=1) + reader = producer.open_reader() + await producer.send(first) + waiting = asyncio.ensure_future(producer.send(second)) + await asyncio.sleep(0) + assert not waiting.done() + cancelled = _CancelledClose() + error = RuntimeError("the operator failed") if failing else None + raised: BaseException | None = None + try: + await close_inputs([cancelled, reader], error) # pyright: ignore[reportArgumentType] # a stand-in input + except asyncio.CancelledError as cancellation: + raised = cancellation + assert cancelled.closed + async with asyncio.timeout(TIMEOUT): + await waiting # the second input was closed all the same + if error is not None: + assert any("cancelled" in note for note in error.__notes__) + return raised + + raised = asyncio.run(go()) + assert (raised is None) == failing + + +class _ListFeed: + """A feed that delivers the given record batches, then ends.""" + + def __init__(self, batches: list[pa.RecordBatch]) -> None: + self._batches = list(batches) + + async def next(self) -> pa.RecordBatch | None: + return self._batches.pop(0) if self._batches else None + + def close(self) -> None: + self._batches.clear() + + @property + def opened_on(self) -> Any: # pyright: ignore[reportExplicitAny] + return None + + +def test_batches_whose_tokens_cannot_make_one_input_table_fail_the_operator() -> None: + """CodeRabbit on PR 510: a row-by-row operator processes batches as they arrive; + a later batch whose source-info tokens cannot make one table with the earlier + ones (``[]``, then ``[["b"]]``) is refused, as the sync path refuses the whole + input, and the output fails instead of completing with part of the rows. The + operator drops the column, so its own output (whose send check settles token + types too) would not see the conflict.""" + from orcapod.core.operators import SelectDataColumns + from orcapod.core.operators.static_output_pod import SourceInfoTypesDisagree + from orcapod.core.streams.record_batch_input import InputChannel + + stream = _deep_token_stream([[], [["b"]]], [1, 2]) # its rows: sync refuses + clean = _deep_token_stream([[["a"]], [["b"]]], [1, 2]) # one schema, buildable + shallow = _token_batch(clean, [[], []], SHALLOW_TOKENS).slice(0, 1) + deep = _token_batch(clean, [[["a"]], [["b"]]], DEEP_TOKENS).slice(1, 1) + op = SelectDataColumns(["y"]) + from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod + + with pytest.raises((pa.ArrowInvalid, ValueError)): + # A job's sync path rebuilds the input from its rows first, and refuses. + _ = StaticOutputOperatorPod._materialize_upstream( # pyright: ignore[reportPrivateUsage] # the job's sync form + list(stream.iter_data()), stream + ) + + async def go() -> OutputChannel: + output = OutputChannel(op(clean)) + with pytest.raises(SourceInfoTypesDisagree): + await op.async_execute_batches( + [InputChannel(clean, _ListFeed([shallow, deep]))], output + ) + return output + + output = asyncio.run(go()) + with pytest.raises(RuntimeError, match="has no result"): + _ = output.result() diff --git a/tests/test_core/operators/test_record_batch_execution.py b/tests/test_core/operators/test_record_batch_execution.py index 0f29c9b45..ac5cfc211 100644 --- a/tests/test_core/operators/test_record_batch_execution.py +++ b/tests/test_core/operators/test_record_batch_execution.py @@ -154,6 +154,16 @@ def assert_same_table(table: pa.Table, expected: pa.Table) -> None: # The storage of a logical type: its values as stored, not as decoded. column, wanted = (t.column(name).combine_chunks() for t in (table, expected)) assert _same_value(column.to_pylist(), wanted.to_pylist()), name + # A float column is compared by its bits too, as stored: a NaN payload or a + # signed zero changed on the way is a different value (``_same_value`` reads + # Python values, which cannot tell NaN payloads apart). + if pa.types.is_floating(column.type): + bits = ( + pa.uint16() + if pa.types.is_float16(column.type) + else (pa.uint32() if pa.types.is_float32(column.type) else pa.uint64()) + ) + assert column.view(bits).equals(wanted.view(bits)), name def assert_equals_sync(case: Case, sizes: tuple[int, ...] | None) -> None: diff --git a/tests/test_core/operators/test_streaming_joins.py b/tests/test_core/operators/test_streaming_joins.py index 8c219eb7a..4aad0842d 100644 --- a/tests/test_core/operators/test_streaming_joins.py +++ b/tests/test_core/operators/test_streaming_joins.py @@ -249,6 +249,21 @@ def _check( inputs: Sequence[StreamProtocol], seeds: Sequence[int] = SEEDS, ) -> None: + """Check a kernel against its operator's sync path over the same inputs. + + The inputs are given to the oracle as a job's edges carry them, each rebuilt from + its rows (``_row_built``), and to the kernel cut into batches of random sizes in + random interleavings (one per seed). The kernel's constructor-time behaviour (its + zero-row result, its output columns) is checked separately from the rows. The + rows are compared as a multiset, with the oracle's columns and Arrow types: row + order and column order are not results on the async path. + + Args: + make_kernel: Builds the kernel from the input streams. + sync: The operator's sync body (``static_process``). + inputs: The input streams, in call order. + seeds: The interleavings to run. + """ 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 @@ -465,9 +480,11 @@ def test_join_inputs_of_one_pipeline_hash_sort_their_system_tags() -> None: # 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: + # ``k`` is a data-tag (no tag-only column): only data-tags can be joined here. return ArrowTableSource( pa.table({"k": pa.array(values, pa.large_string())}), tag_columns=["k"], + tag_only_columns=(), source_id=source_id, ) @@ -818,6 +835,8 @@ def tied(source_id: str, keys: list[int], groups: list[str]) -> ArrowTableSource } ), tag_columns=["k", "g"], + # Both tags are data-tags (no tag-only column), stated, not the default. + tag_only_columns=(), source_id=source_id, ) @@ -1103,15 +1122,22 @@ def keyed(source_id: str, keys: list[int | None], data: str) -> ArrowTableSource for i, name in enumerate("abc") ] kernel = StreamingJoin(Join(), sources) - kernel.push( - null_input, _sent(sources[null_input]).combine_chunks().to_batches()[0] + # A null key matches nothing: no push emits a row. + assert ( + 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.push( + index, _sent(sources[index]).combine_chunks().to_batches()[0] + ) + == [] + ), (null_input, index) assert kernel.held_rows == 0, null_input diff --git a/tests/test_core/operators/test_streaming_rejoin.py b/tests/test_core/operators/test_streaming_rejoin.py index 6021355f5..7c1ae7ede 100644 --- a/tests/test_core/operators/test_streaming_rejoin.py +++ b/tests/test_core/operators/test_streaming_rejoin.py @@ -199,10 +199,12 @@ def test_alternating_repeats_keep_only_unmatched_rows() -> None: rights = _sent(right).combine_chunks().to_batches(max_chunksize=1) for index in range(n): out += kernel.push(0, lefts[index]) + largest = max(largest, kernel.held_rows) # sampled after every push if index < len(rights): out += kernel.push(1, rights[index]) - largest = max(largest, kernel.held_rows) - assert largest <= 8 + largest = max(largest, kernel.held_rows) + # The peak: the seven left rows the right input never pairs, held as they wait. + assert largest == 7 assert sum(batch.num_rows for batch in out) == n - 7 assert kernel.held_rows == 7 kernel.close(1) @@ -534,8 +536,19 @@ def plain(data: str) -> ArrowTableStream: 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 + # One row at a time, k=2 arrives first and pairs with the third branch's first + # value: the alternate pairing, every other value as it was. + (third,) = [stream for stream in inputs if not stream.keys()[0]] + value = third.keys()[1][0] + + def pairs(table: pa.Table) -> set[tuple[Any, Any]]: + return set(zip(table.column("k").to_pylist(), table.column(value).to_pylist())) + + assert pairs(whole) == {(1, 10), (2, 20)} + assert pairs(one_by_one) == {(2, 10), (1, 20)} + others = [name for name in whole.column_names if name not in ("k", value)] + assert _rows(one_by_one.select(others)) == _rows(whole.select(others)) def test_the_warning_for_repeats_of_two_inputs_can_depend_on_arrival() -> None: