From a1bd4af5e51ab5b6063017879f9e440083e9d1ac Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 20:20:53 -0800 Subject: [PATCH 1/2] test(channels): every review finding on the record-batch channel PRs has a test that fails without its fix (ITL-1362) An audit of every Codex and CodeRabbit finding on PRs 483, 488 and 495 reverted each fix alone and ran its tests. Two tests still passed with their fix reverted, two fixes had no test, and six tests covered only the reported case of a wider class. The new tests, each checked to fail with only its fix reverted: - overlapping sends on a bounded output, in the reviewer's schedule; - close_inputs with a second input still open, on success and on failure; - Batch holds no zero-row arrival; - arrivals whose system-tag or source-info flags differ; - binary, list and nested non-large representations refused at send; - field metadata on a struct child, a map item and source-info fields; - a token into a null-typed source-info column is taken (declined finding, pinned); - a column twice, declared and undeclared, for data, system-tag and source-info; - a ChannelClosed from a fetch after a successful one, through iteration, collect and to_stream. Co-Authored-By: Claude Opus 5.5 --- .../test_record_batch_review_findings.py | 541 ++++++++++++++++++ 1 file changed, 541 insertions(+) create mode 100644 tests/test_channels/test_record_batch_review_findings.py diff --git a/tests/test_channels/test_record_batch_review_findings.py b/tests/test_channels/test_record_batch_review_findings.py new file mode 100644 index 000000000..f58c1d13e --- /dev/null +++ b/tests/test_channels/test_record_batch_review_findings.py @@ -0,0 +1,541 @@ +"""Regression tests for review findings on the record-batch channels (ITL-1362). + +Each test captures a finding a reviewer reported on the channel PRs (#483, #488, #495) +whose fix had no test that fails without it, or a test that covered only the reported +case of a wider class. The finding is named in each test's docstring. +""" + +from __future__ import annotations + +import asyncio +import gc +import weakref +from typing import Any + +import pyarrow as pa +import pytest + +from orcapod.core.operators import SemiJoin +from orcapod.core.operators.static_output_pod import close_inputs +from orcapod.core.record_batch_channels import OutputChannel +from orcapod.core.streams import ArrowTableStream +from orcapod.errors import UpstreamFailedError +from tests.test_channels.test_record_batch_channels import ALL, R, batches_of, source + +TIMEOUT = 5.0 + + +def _trial(batch: pa.RecordBatch) -> int: + return batch.column("trial")[0].as_py() + + +# --- Overlapping sends on a bounded output (CodeRabbit, PR 483) ---------------------- + + +def test_a_send_started_while_another_waits_reaches_every_reader_after_it() -> None: + """CodeRabbit on PR 483 (thread 4657988055): overlapping sends on an output that + does not retain must reach every reader in one order. + + The reviewer's schedule, one task reading both readers of a one-slot output: the + fast reader takes A; the send of X queues X for the fast reader and waits for the + slow reader's room; the send of Y is started; the slow reader takes A and the fast + reader takes X, waking the send of X after Y's has been scheduled. Without one + send at a time, Y reaches the slow reader before X does.""" + stream = source(3) + a, x, y = batches_of(stream, 1) + + async def schedule() -> tuple[list[int], list[int]]: + output = OutputChannel(stream, retain=False, buffer_size=1) + fast, slow = output.open_reader(), output.open_reader() + await output.send(a) + got_fast = [_trial(await fast.receive())] + sending_x = asyncio.ensure_future(output.send(x)) + await asyncio.sleep(0) # X queued for the fast reader, waiting for the slow one + # Y's send is scheduled now, so it runs before X's send wakes up. + sending_y = asyncio.ensure_future(output.send(y)) + got_slow = [_trial(await slow.receive())] # A, without suspending + got_fast.append(_trial(await fast.receive())) # X, without suspending + async with asyncio.timeout(TIMEOUT): + got_slow.append(_trial(await slow.receive())) + got_slow.append(_trial(await slow.receive())) + got_fast.append(_trial(await fast.receive())) + await sending_x + await sending_y + return got_fast, got_slow + + got_fast, got_slow = asyncio.run(schedule()) + assert got_fast == got_slow == [0, 1, 2] + + +# --- Closing every input (CodeRabbit, PR 483) ----------------------------------------- + + +class _FailingClose: + """An input channel whose close raises; it delivers nothing.""" + + def __init__(self) -> None: + self.closed = False + + async def close(self) -> None: + self.closed = True + raise OSError("cannot close") + + +@pytest.mark.parametrize("failing", [False, True], ids=["succeeding", "failing"]) +def test_every_input_is_closed_when_one_close_fails_with_another_still_open( + failing: bool, +) -> None: + """CodeRabbit on PR 483 (review 6012081355): an operator closes every input even + when one close raises, so no producer is left waiting on a reader nobody reads. + + The second input is an open reader of a one-slot output whose producer waits for + its room. After ``close_inputs``, that send no longer waits. When the operator + succeeded, the first close error is raised once every input is closed; when it + failed, the close error is a note on the operator's error, which is not replaced.""" + stream = source(3) + first_batch, second_batch, _ = 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_batch) + waiting = asyncio.ensure_future(producer.send(second_batch)) + await asyncio.sleep(0) + assert not waiting.done() # the reader's slot is full + broken = _FailingClose() + inputs: list[Any] = [broken, reader] + error = RuntimeError("the operator failed") if failing else None + raised: BaseException | None = None + try: + await close_inputs(inputs, error) + except OSError as close_error: + raised = close_error + assert broken.closed + async with asyncio.timeout(TIMEOUT): + await waiting # the closed reader is no longer waited for + if error is not None: + assert raised is None + assert any("cannot close" in note for note in error.__notes__) + return None + return raised + + raised = asyncio.run(go()) + if not failing: + assert isinstance(raised, OSError) + + +def test_a_failing_operator_releases_an_input_it_never_read() -> None: + """CodeRabbit on PR 483 (review 6012081355), through an operator: a barrier whose + first input fails while its second input's producer waits for room closes the + second input, so that producer is released, and the output fails.""" + left, right = source(3), source(3, source_id="other") + right_batches = batches_of(right, 1) + op = SemiJoin() + + async def go() -> None: + left_out = OutputChannel(left, retain=False, buffer_size=1) + right_out = OutputChannel(right, retain=False, buffer_size=1) + inputs = [left_out.open_reader(), right_out.open_reader()] + output = OutputChannel(op(left, right)) + for batch in right_batches[:1]: + await right_out.send(batch) + waiting = asyncio.ensure_future(right_out.send(right_batches[1])) + left_out.fail(OSError("left producer failed")) + with pytest.raises(UpstreamFailedError, match="left producer failed"): + async with asyncio.timeout(TIMEOUT): + await op.async_execute_batches(inputs, output) + async with asyncio.timeout(TIMEOUT): + await waiting # released: the operator closed the right input + with pytest.raises(RuntimeError, match="no result"): + _ = output.result() + + asyncio.run(go()) + + +# --- Batch holds no batch without rows (Codex on PR 483, round 1, finding 2) --------- + + +class _PausingFeed: + """A feed that delivers some record batches, waits for ``resume``, then the rest.""" + + def __init__( + self, + before: list[pa.RecordBatch], + after: list[pa.RecordBatch], + resume: asyncio.Event, + paused: asyncio.Event, + ) -> None: + self._before, self._after = list(before), list(after) + self._resume, self._paused = resume, paused + + async def next(self) -> pa.RecordBatch | None: + if self._before: + return self._before.pop(0) + if not self._resume.is_set(): + self._paused.set() + await self._resume.wait() + return self._after.pop(0) if self._after else None + + def close(self) -> None: + self._before.clear() + self._after.clear() + + @property + def opened_on(self) -> Any: # pyright: ignore[reportExplicitAny] + return None + + +@pytest.mark.parametrize("size", [2, 3]) +def test_batch_holds_no_arrival_without_rows(size: int) -> None: + """Codex on PR 483, round 1, finding 2: ``Batch`` with a size keeps the rows that + have arrived until a batch is full, and must not keep the record batches with no + row among them (a producer could grow that list without limit). Many zero-row + batches arrive while a row waits; none is held.""" + from orcapod.core.operators import Batch + from orcapod.core.streams.record_batch_input import InputChannel + + stream = source(4) + rows = batches_of(stream, 1) + empties = [rows[0].slice(0, 0) for _ in range(50)] + held = [weakref.ref(empty) for empty in empties] + resume, paused = asyncio.Event(), asyncio.Event() + feed = _PausingFeed([rows[0], *empties], rows[1:], resume, paused) + del empties + op = Batch(batch_size=size) + + async def go() -> Any: # pyright: ignore[reportExplicitAny] + output = OutputChannel(op(stream)) + task = asyncio.ensure_future( + op.async_execute_batches([InputChannel(stream, feed)], output) + ) + async with asyncio.timeout(TIMEOUT): + await paused.wait() + gc.collect() + # The last one may still be the loop's current batch; no other is held. + alive = sum(ref() is not None for ref in held[:-1]) + resume.set() + async with asyncio.timeout(TIMEOUT): + await task + return alive, output.result() + + alive, result = asyncio.run(go()) + assert alive == 0 + expected = R(op(stream)) + assert result.as_table(columns=ALL).num_rows == expected.num_rows + + +# --- Arrivals whose provenance flags differ (Codex on PR 483, round 1, finding 2) ---- + + +@pytest.mark.parametrize("kind", ["system_tag", "source_info"]) +def test_batch_takes_arrivals_whose_provenance_field_flags_differ(kind: str) -> None: + """Codex on PR 483, round 1, finding 2: arrivals built from their own rows may + flag a provenance field nullable in one and not in the next (the send check does + not compare those flags). ``Batch(2)`` puts them together and gives the sync + result, for a system-tag field as for a source-info field.""" + from orcapod.core.operators import Batch + + stream = source(2) + first, second = batches_of(stream, 1) + prefix = "_tag" if kind == "system_tag" else "_source_" + index = next(i for i, n in enumerate(first.schema.names) if n.startswith(prefix)) + field = first.schema.field(index) + flagged = pa.RecordBatch.from_arrays( + first.columns, + schema=first.schema.set(index, field.with_nullable(not field.nullable)), + ) + assert flagged.schema.field(index).nullable != second.schema.field(index).nullable + op = Batch(batch_size=2) + + async def go() -> Any: # pyright: ignore[reportExplicitAny] + middle = OutputChannel(stream) + output = OutputChannel(op(stream)) + reader = middle.open_reader() + await middle.send(flagged) + await middle.send(second) + await middle.close() + async with asyncio.timeout(TIMEOUT): + await op.async_execute_batches([reader], output) + return output.result() + + result = asyncio.run(go()) + expected = R(op(stream)) + table = result.as_table(columns=ALL) + assert table.num_rows == expected.num_rows == 1 + assert table.select(expected.column_names).to_pylist() == expected.to_pylist() + + +# --- Representations other than the large variant (Codex on PR 483, round 1, 4) ------ + + +def _typed_stream() -> ArrowTableStream: + return ArrowTableStream( + pa.table( + { + "k": pa.array([1, 2], pa.int64()), + "b": pa.array([b"x", b"y"], pa.large_binary()), + "l": pa.array([[1], [2, 3]], pa.large_list(pa.int64())), + "s": pa.array( + [{"a": "p"}, {"a": "q"}], pa.struct([("a", pa.large_string())]) + ), + "ls": pa.array([["p"], ["q"]], pa.large_list(pa.large_string())), + } + ), + tag_columns=["k"], + ) + + +@pytest.mark.parametrize( + ("column", "other"), + [ + ("b", pa.binary()), + ("l", pa.list_(pa.int64())), + ("s", pa.struct([("a", pa.string())])), + ("ls", pa.large_list(pa.string())), + ], + ids=["binary", "list", "string_in_struct", "string_in_list"], +) +def test_a_column_in_another_representation_is_refused( + column: str, other: pa.DataType +) -> None: + """Codex on PR 483, round 1, finding 4: a batch passes only with the description's + types in their large variants, at every depth; another representation that the + result could not be assembled from is refused at send, never converted.""" + stream = _typed_stream() + (batch,) = batches_of(stream) + index = batch.schema.get_field_index(column) + narrow = batch.set_column( + index, + batch.schema.field(index).with_type(other), + batch.column(index).cast(other), + ) + + async def write() -> None: + output = OutputChannel(stream) + with pytest.raises(ValueError, match=f"column '{column}' is"): + await output.send(narrow) + await output.send(batch) + + asyncio.run(write()) + + +# --- Field metadata at every depth (Codex on PR 483, round 2, finding 3) ------------- + + +def _with_metadata_inside(kind: pa.DataType) -> pa.DataType: + """``kind`` with metadata on its first nested field.""" + if isinstance(kind, pa.StructType): + child = kind.field(0) + return pa.struct( + [ + child.with_metadata({"units": "b"}), + *(kind.field(i) for i in range(1, kind.num_fields)), + ] + ) + if isinstance(kind, pa.MapType): + item = kind.item_field.with_metadata({"units": "b"}) + return pa.map_(kind.key_type, item) # pyright: ignore[reportArgumentType] # pyarrow takes a field for the item; the stubs say a type + assert isinstance(kind, pa.LargeListType) + return pa.large_list(kind.value_field.with_metadata({"units": "b"})) + + +@pytest.mark.parametrize( + "column", ["s", "m", "ls"], ids=["struct_child", "map_item", "list_item"] +) +def test_nested_field_metadata_must_be_the_descriptions(column: str) -> None: + """Codex on PR 483, round 2, finding 3: a user field's nested field metadata + (a struct child, a map item, a list item) must be the description's.""" + stream = ArrowTableStream( + pa.table( + { + "k": pa.array([1, 2], pa.int64()), + "s": pa.array( + [{"a": "p"}, {"a": "q"}], pa.struct([("a", pa.large_string())]) + ), + "m": pa.array( + [[("a", 1)], [("b", 2)]], pa.map_(pa.large_string(), pa.int64()) + ), + "ls": pa.array([["p"], ["q"]], pa.large_list(pa.large_string())), + } + ), + tag_columns=["k"], + ) + (batch,) = batches_of(stream) + index = batch.schema.get_field_index(column) + tagged_type = _with_metadata_inside(batch.schema.field(index).type) + tagged = batch.set_column( + index, + batch.schema.field(index).with_type(tagged_type), + batch.column(index).cast(tagged_type), + ) + + async def write() -> None: + output = OutputChannel(stream) + with pytest.raises(ValueError, match=f"column '{column}' has field metadata"): + await output.send(tagged) + await output.send(batch) + + asyncio.run(write()) + + +def _list_token_stream() -> ArrowTableStream: + """A raw stream whose source-info column holds list tokens.""" + return ArrowTableStream( + pa.table( + { + "k": pa.array([1, 2], pa.int64()), + "x": pa.array([1.5, 2.5], pa.float64()), + "_source_x": pa.array( + [["s::r0::x"], ["s::r1::x"]], pa.large_list(pa.large_string()) + ), + } + ), + tag_columns=["k"], + ) + + +@pytest.mark.parametrize("where", ["top_level", "list_item"]) +def test_a_source_info_field_carries_no_metadata(where: str) -> None: + """Codex on PR 483, round 2, finding 3: a source-info field carries no field + metadata, at its own level or on a list item, as a row builds it.""" + stream = source() if where == "top_level" else _list_token_stream() + (batch,) = batches_of(stream) + index = next( + i for i, n in enumerate(batch.schema.names) if n.startswith("_source_") + ) + field = batch.schema.field(index) + if where == "top_level": + tagged = pa.RecordBatch.from_arrays( + batch.columns, + schema=batch.schema.set(index, field.with_metadata({"m": "1"})), + ) + else: + tagged_type = _with_metadata_inside(field.type) + tagged = batch.set_column( + index, field.with_type(tagged_type), batch.column(index).cast(tagged_type) + ) + + async def write() -> None: + output = OutputChannel(stream) + with pytest.raises(ValueError, match="carries field metadata"): + await output.send(tagged) + await output.send(batch) + + asyncio.run(write()) + + +# --- A null-typed source-info column (Codex on PR 483, round 2, finding 5: declined) -- + + +def test_a_token_sent_into_a_null_typed_source_info_column_is_taken() -> None: + """Codex on PR 483, round 2, finding 5 (declined): a source-info column whose raw + type is ``null`` is described by its tokens' type, as a row types a token, so a + batch with a real token is accepted at send, and the result's column is + ``large_string``. This pins the declined behaviour.""" + stream = ArrowTableStream( + pa.table( + { + "k": pa.array([1, 2], pa.int64()), + "x": pa.array([1.5, 2.5], pa.float64()), + "_source_x": pa.array([None, None], pa.null()), + } + ), + tag_columns=["k"], + ) + (batch,) = batches_of(stream) + index = batch.schema.get_field_index("_source_x") + tokened = batch.set_column( + index, + pa.field("_source_x", pa.large_string()), + pa.array(["s::r0::x", None], pa.large_string()), + ) + + async def write() -> Any: # pyright: ignore[reportExplicitAny] + output = OutputChannel(stream) + await output.send(tokened) + await output.close() + return output.result() + + table = asyncio.run(write()).as_table(columns=ALL) + assert table.schema.field("_source_x").type == pa.large_string() + assert table.column("_source_x").to_pylist() == ["s::r0::x", None] + + +# --- Duplicate columns (Codex on PR 485, final round, finding 3) --------------------- + + +@pytest.mark.parametrize("kind", ["data", "system_tag", "source_info"]) +@pytest.mark.parametrize("declared", [True, False], ids=["declared", "undeclared"]) +def test_a_batch_with_a_column_twice_is_refused(declared: bool, kind: str) -> None: + """Codex on PR 485's final round, finding 3: a batch holding a column twice is + refused whatever the description says; the undeclared system-tag case is the one + only the duplicate check refuses.""" + from tests.test_channels.test_record_batch_channels import _UntypedStream # pyright: ignore[reportPrivateUsage] + + table = source().as_table(columns=ALL) + stream = ( + source() + if declared + else _UntypedStream( + table, tag_columns=["subject", "trial"], data_tags=["trial"] + ) + ) + (batch,) = batches_of(stream) + prefix = {"data": None, "system_tag": "_tag", "source_info": "_source_"}[kind] + name = next( + n + for n in batch.schema.names + if (n.startswith(prefix) if prefix else n == "amplitude") + ) + doubled = batch.append_column(batch.schema.field(name), batch.column(name)) + + async def write() -> None: + await OutputChannel(stream).send(doubled) + + with pytest.raises(ValueError, match="a column more than once"): + asyncio.run(write()) + + +# --- A read error after a successful read (Codex on PR 488, round 2, finding 5) ------ + + +@pytest.mark.parametrize("read", ["iteration", "collect", "to_stream"]) +def test_a_channel_closed_raised_by_a_later_fetch_is_a_read_error(read: str) -> None: + """Codex on PR 488, round 2, finding 5: a source whose first fetch succeeds and a + later fetch raises ``ChannelClosed`` (its own input closed early): the channel read + that meets it raises it, through iteration, ``collect`` and ``to_stream``; it is + never taken for the end of the input.""" + from orcapod.channels import ChannelClosed + from orcapod.core.sources import PollingSource + from orcapod.types import Schema + from tests.test_channels.test_polling_source import FakeDynamicSource, _batch + + class _ClosingLater(FakeDynamicSource): + async def fetch(self, cursor: Any = None) -> Any: # pyright: ignore[reportExplicitAny] + if self.fetch_cursors: + self.fetch_cursors.append(cursor) + raise ChannelClosed("underlying input closed early") + return await super().fetch(cursor) + + fake = _ClosingLater( + batches=[_batch(1, 10), _batch(2, 20)], + schema_override=Schema({"id": int, "val": int}), + ) + polling = PollingSource( + fake, tag_columns="id", record_id_columns="id", source_id="later" + ) + + async def go() -> None: + first = await polling.open_channel().collect() # the first fetch succeeds + assert sum(batch.num_rows for batch in first) == 1 + channel = polling.open_channel() + with pytest.raises(ChannelClosed, match="underlying input"): + if read == "iteration": + async for _ in channel: + pass + elif read == "collect": + _ = await channel.collect() + else: + _ = await channel.to_stream() + + asyncio.run(go()) From 730deeeae33a3c4c9eed82e0e7916de9c8986015 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 21:21:52 -0800 Subject: [PATCH 2/2] fix(channels): CodeRabbit on PR 510: nulls under a non-nullable field, map metadata, shallower tokens, meta columns, reader release, close order (ITL-1362) CodeRabbit's review of PR 510 (job-speed into main), on the record-batch channels and kernels; none of this code is on a wired path yet. Each fix has a test that fails with only the fix reverted. - send refuses a batch whose column is flagged non-nullable but holds a null (major). - the provenance metadata check strips the key and item fields of a map too. - a join kernel takes a batch whose source-info tokens have fewer list levels than its input's layout (nulls, empty lists), every token kept; tokens_as converts level by level and never reads a string as a list of characters. - StreamingMergeJoin counts as colliding only data columns its batches carry: a raw stream's meta column (__note) raised KeyError (18 cases, every arrangement). - an input channel whose consumer task finishes between reads is closed, so its producer never waits for it. - an operator closes its inputs before its output (finish_operator): a failing close fails the output instead of leaving readers a normal end. Tests: the empty-result fields are compared with the job's zero-row form (types, flags, metadata), signed zeros are told apart, one deadline covers the Batch arrival test, the cleanup test counts the second input's close, batch schemas are compared with metadata, the release schedule with held rows, the barrier tests wait on a started conversion and on a partly read failing input, the streaming-join module docstring, and a rename in test_streaming_rejoin. Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/operators/batch.py | 4 +- .../core/operators/static_output_pod.py | 118 +++++++++++--- src/orcapod/core/operators/streaming_joins.py | 43 +++-- src/orcapod/core/record_batch_channels.py | 13 +- .../core/streams/record_batch_input.py | 46 +++++- .../test_record_batch_channels.py | 49 +++++- .../test_record_batch_review_findings.py | 129 +++++++++++++++ .../operators/test_record_batch_execution.py | 73 ++++++--- .../operators/test_streaming_joins.py | 147 +++++++++++++++++- .../operators/test_streaming_rejoin.py | 2 +- 10 files changed, 561 insertions(+), 63 deletions(-) diff --git a/src/orcapod/core/operators/batch.py b/src/orcapod/core/operators/batch.py index 59b970577..e82aadee6 100644 --- a/src/orcapod/core/operators/batch.py +++ b/src/orcapod/core/operators/batch.py @@ -19,6 +19,7 @@ from orcapod.core.operators.static_output_pod import ( close_inputs, concatenate_batches, + finish_operator, ) from orcapod.core.data_tags import stream_data_tags from orcapod.core.streams import ArrowTableStream @@ -319,12 +320,11 @@ async def async_execute_batches( # whether they make a last one. if rows: await self._send_processed(waiting, channel.stream, output) - await output.close() except BaseException as error: output.fail(error) await close_inputs(inputs, error) raise - await close_inputs(inputs) + await finish_operator(inputs, output) def to_config(self) -> dict[str, Any]: """Serialize this Batch operator to a config dict. diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index 7da1ecf72..a5b1e399b 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -15,6 +15,7 @@ from typing import TYPE_CHECKING, Any, ClassVar, NoReturn, cast import pyarrow as pa +import pyarrow.compute as pc from orcapod.protocols.core_protocols.streams import ( RecordBatchInput, @@ -1055,9 +1056,10 @@ async def async_execute_batches( came from. A predicate that reads a ``null`` column's type or the column order follows that form (documented behaviour, e5). - The output is closed when the operator is done. If it fails or is cancelled, - the output fails instead, so no reader takes it for complete; every input is - closed in either case. + When the operator is done its inputs are closed, then its output + (``finish_operator``), so a failing close fails the output. If the operator + fails or is cancelled, the output fails instead, so no reader takes it for + complete; every input is closed in either case. Args: inputs: One input channel per input stream, in the operator's order. @@ -1071,12 +1073,11 @@ async def async_execute_batches( else: streams = await _streams_of(inputs) await self._send_result(self.static_process(*streams), output) - await output.close() except BaseException as error: output.fail(error) await close_inputs(inputs, error) raise - await close_inputs(inputs) + await finish_operator(inputs, output) async def _send_processed( self, @@ -1114,6 +1115,32 @@ async def _send_result(result: StreamProtocol, output: RecordBatchOutput) -> Non await output.send(batch) +async def finish_operator( + inputs: Sequence[RecordBatchInput], output: RecordBatchOutput +) -> None: + """End an operator that has sent its result: close its inputs, then its output. + + The inputs are closed first, so a failing close fails the output instead of + completing it: readers see the normal end only when the operator ended cleanly. + + Args: + inputs: The operator's input channels. + output: Its output channel. + + Raises: + Exception: The first error of an input's close, or the output's close; the + output then fails with it. + """ + try: + await close_inputs(inputs) + await output.close() + except BaseException as error: + # A failing close of an input, or of the output itself: no reader takes the + # output for complete. + output.fail(error) + raise + + async def close_inputs( inputs: Sequence[RecordBatchInput], error: BaseException | None = None ) -> None: @@ -1295,29 +1322,84 @@ def settle_token_types( if len(kinds) > 1: raise SourceInfoTypesDisagree(field.name) (kind,) = kinds - _ = _tokens_as(column, kind, field.name) # representable, or refused + _ = _named_tokens_as(column, kind, field.name) # representable, or refused settled[field.name] = kind return settled -def _tokens_as( - column: pa.Array[Any], - kind: pa.DataType, - name: str, # pyright: ignore[reportExplicitAny] # any column -) -> pa.Array[Any]: # pyright: ignore[reportExplicitAny] # any column - """``column``'s tokens as an array of ``kind``: the same array when it has that type. +def tokens_as(column: pa.Array[Any], kind: pa.DataType) -> pa.Array[Any]: # pyright: ignore[reportExplicitAny] # any column + """``column``'s source-info tokens as an array of ``kind``, every value kept. + + The same array when it has that type. A token type that one batch's values give + (``arrow_utils.source_info_arrow_type``) can be shallower than another's (a null + or an empty list fixes fewer list levels); converting keeps every token, and a + token that ``kind`` cannot hold is refused, never changed. + + Args: + column: Source-info tokens. + kind: A token type (``large_string``, or ``large_list`` of a token type). + + Returns: + The tokens as ``kind``. + + Raises: + RowBuiltFormUnavailable: If a token cannot be represented as ``kind``. + """ + return _tokens_into(column, kind) + + +def _tokens_into(column: pa.Array[Any], kind: pa.DataType) -> pa.Array[Any]: # pyright: ignore[reportExplicitAny] # any column + """``tokens_as``, level by level, never reading a value as another shape. + + A level whose values are all null (or that has none) takes ``kind`` as it is; two + list levels convert their values; any other difference is refused. A value is + never re-read in another type (pyarrow reads a string as a list of characters). Raises: RowBuiltFormUnavailable: If a token cannot be represented as ``kind``. """ if column.type == kind: return column + if column.null_count == len(column): + return pa.nulls(len(column), kind) # pyright: ignore[reportCallIssue, reportArgumentType] # pyarrow takes any type; the stubs say an extension type + lists = (pa.ListType, pa.LargeListType) + if isinstance(column.type, lists) and isinstance(kind, lists): + # The slice's own lists: its values, and offsets from its lists' lengths (a + # null list holds none), so a sliced array converts as its rows say. + values = _tokens_into(pc.list_flatten(column), kind.value_type) # pyright: ignore[reportUnknownMemberType, reportUnknownArgumentType] + lengths = pc.fill_null(pc.list_value_length(column), 0) # pyright: ignore[reportUnknownMemberType, reportUnknownVariableType, reportArgumentType] # pyarrow takes a Python fill value + offset_type = pa.int64() if isinstance(kind, pa.LargeListType) else pa.int32() + offsets = pa.concat_arrays( + [ + pa.array([0], offset_type), + pc.cumulative_sum(lengths).cast(offset_type), # pyright: ignore[reportUnknownMemberType, reportUnknownArgumentType] + ] + ) + build = ( + pa.LargeListArray.from_arrays + if isinstance(kind, pa.LargeListType) + else pa.ListArray.from_arrays + ) + return build(offsets, values, type=kind, mask=column.is_null()) # pyright: ignore[reportUnknownVariableType, reportCallIssue, reportArgumentType] # the offsets' width follows ``kind`` + raise RowBuiltFormUnavailable( + f"a token of type {column.type} cannot be represented as {kind}" + ) + + +def _named_tokens_as( + column: pa.Array[Any], # pyright: ignore[reportExplicitAny] # any column + kind: pa.DataType, + name: str, +) -> pa.Array[Any]: # pyright: ignore[reportExplicitAny] # any column + """``tokens_as`` for the source-info column ``name``, whose name a refusal gives. + + Raises: + RowBuiltFormUnavailable: If a token cannot be represented as ``kind``. + """ try: - return pa.array(column.to_pylist(), type=kind) - except (pa.ArrowInvalid, pa.ArrowTypeError, TypeError, ValueError) as error: - raise RowBuiltFormUnavailable( - f"{name}: a token cannot be represented as {kind} ({error})" - ) from error + return tokens_as(column, kind) + except RowBuiltFormUnavailable as error: + raise RowBuiltFormUnavailable(f"{name}: {error}") from error def concatenate_batches(batches: Sequence[pa.RecordBatch]) -> pa.Table | None: @@ -1355,7 +1437,7 @@ def concatenate_batches(batches: Sequence[pa.RecordBatch]) -> pa.Table | None: fields: list[pa.Field[Any]] = [] # pyright: ignore[reportExplicitAny] # any field for field, column in zip(batch.schema, batch.columns, strict=True): if field.name in settled: - column = _tokens_as(column, settled[field.name], field.name) + column = _named_tokens_as(column, settled[field.name], field.name) field = pa.field(field.name, settled[field.name]) if field.name.startswith(prefixes): field = field.with_nullable(True) diff --git a/src/orcapod/core/operators/streaming_joins.py b/src/orcapod/core/operators/streaming_joins.py index ab8ef14d9..ccf406449 100644 --- a/src/orcapod/core/operators/streaming_joins.py +++ b/src/orcapod/core/operators/streaming_joins.py @@ -109,7 +109,11 @@ SemiJoin, _has_whole_key, # pyright: ignore[reportPrivateUsage] # SemiJoin's one rule ) -from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod +from orcapod.core.operators.static_output_pod import ( + RowBuiltFormUnavailable, + StaticOutputOperatorPod, + tokens_as, +) 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 @@ -574,18 +578,31 @@ 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) - 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" - ) + columns = list(table.columns) + for index, (field, actual) in enumerate(zip(layout, table.schema)): + if field.type == actual.type: + continue + if not table.num_rows and pa.types.is_null(actual.type): + continue + if table.num_rows and field.name.startswith(constants.SOURCE_PREFIX): + # A batch's token type follows its own tokens and can be shallower + # than the layout's (a null or an empty list fixes fewer list + # levels): the tokens are converted, every value kept. + try: + columns[index] = pa.chunked_array( + [tokens_as(table.column(index).combine_chunks(), field.type)] + ) + continue + except RowBuiltFormUnavailable: + pass + raise ValueError( + f"{type(self).__name__}: column {field.name!r} of input " + + f"{input_index} is {actual.type} in a batch, but " + + f"{field.type} in its stream" + ) if not table.num_rows: return layout.empty_table() - return pa.Table.from_arrays(table.columns, schema=layout) + return pa.Table.from_arrays(columns, schema=layout) def _emitted(self, tables: list[pa.Table]) -> list[pa.RecordBatch]: """The record batches of the output tables, holding ``output_columns``. @@ -787,6 +804,10 @@ def __init__(self, operator: MergeJoin, inputs: Sequence[StreamProtocol]) -> Non left, right = inputs left_tags, left_data = left.keys() right_tags, right_data = right.keys() + # The data columns the batches carry: a raw stream lists its meta columns + # as data, and no operator carries them (they are not in the layouts). + left_data = [n for n in left_data if n in self._layouts[0].names] + right_data = [n for n in right_data if n in self._layouts[1].names] 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) diff --git a/src/orcapod/core/record_batch_channels.py b/src/orcapod/core/record_batch_channels.py index 7134795d9..fa8c030dc 100644 --- a/src/orcapod/core/record_batch_channels.py +++ b/src/orcapod/core/record_batch_channels.py @@ -411,7 +411,8 @@ def _schema_mismatch(declared: pa.Schema, batch: pa.RecordBatch) -> str | None: The batch must have the description's columns, compared by name (their order is not compared: the channel keeps one order of its own), each with exactly the description's type in its large variant (no other representation is taken and - converted: type strictness), the same nullability and the same field metadata. A + converted: type strictness), the same nullability (and no null where the + description's field is not nullable) and the same field metadata. A ``null`` type of the description (anywhere in a column's type) is carried as ``large_string``, as a row's datagram stores it, and only null values are taken there. Whether a system-tag or source-info field is nullable is not compared: it @@ -457,6 +458,10 @@ def _schema_mismatch(declared: pa.Schema, batch: pa.RecordBatch) -> str | None: f"column {column.name!r} is {flags[column.nullable]}, the stream's is " + flags[expected.nullable] ) + if not expected.nullable and batch.column(index).null_count: + # The flag says nothing about the values: a field marked non-nullable + # may still hold nulls, which a reader of the stream never expects. + return f"column {column.name!r} holds nulls, the stream's is not nullable" if (expected.metadata or None) != (column.metadata or None) or not ( column.type.equals(carried, check_metadata=True) ): @@ -491,6 +496,12 @@ def _without_metadata(kind: pa.DataType) -> pa.DataType: return pa.struct( [_field_without_metadata(kind.field(i)) for i in range(kind.num_fields)] ) # pyright: ignore[reportUnknownArgumentType, reportUnknownMemberType] + if isinstance(kind, pa.MapType): + return pa.map_( # pyright: ignore[reportCallIssue] # pyarrow takes fields for the key and item; the stubs say types + _field_without_metadata(kind.key_field), # pyright: ignore[reportUnknownArgumentType, reportUnknownMemberType] + _field_without_metadata(kind.item_field), # pyright: ignore[reportUnknownArgumentType, reportUnknownMemberType] + keys_sorted=kind.keys_sorted, + ) return kind diff --git a/src/orcapod/core/streams/record_batch_input.py b/src/orcapod/core/streams/record_batch_input.py index f617b1409..dbc57db46 100644 --- a/src/orcapod/core/streams/record_batch_input.py +++ b/src/orcapod/core/streams/record_batch_input.py @@ -16,6 +16,7 @@ from __future__ import annotations import asyncio +import functools import weakref from collections.abc import AsyncIterator, Coroutine from typing import TYPE_CHECKING, Any, Protocol @@ -143,7 +144,7 @@ def reserve(self, claim: object | None = None) -> object: f"The input channel of {_named(self._stream)} is claimed by " + "another consumer." ) - self._owner = _current_task() + self._bind_owner(_current_task()) self._drop_claim() # redeemed: a later reserve(claim) is refused return claim if self._started or self._ended or self._owner is not None: @@ -184,6 +185,29 @@ def _abandon(self) -> None: self._ended = True self._owner = None + def _bind_owner(self, task: asyncio.Task[Any] | None) -> None: # pyright: ignore[reportExplicitAny] # any task + """Make ``task`` the channel's one consumer. + + When the task finishes (or is cancelled) while it still owns the channel, + before the end and without closing it, the channel is closed: its consumer is + gone, and no producer may wait for it. + """ + self._owner = task + if task is not None: + task.add_done_callback( + functools.partial(_owner_finished, weakref.ref(self)) + ) + + def _owner_gone(self, task: asyncio.Task[Any]) -> None: # pyright: ignore[reportExplicitAny] # any task + """Close the channel if ``task`` still owns it: the consumer finished.""" + if self._owner is not task or self._ended: + return + self._closed = True + self._ended = True + self._owner = None + self._drop_claim() + self._feed.close() + def _belong_to_caller(self) -> None: """Bind the channel to the calling task on its first read; refuse any other. @@ -197,7 +221,7 @@ def _belong_to_caller(self) -> None: + "conversion that has not started; no other read is taken." ) if self._owner is None: - self._owner = task + self._bind_owner(task) elif self._owner is not task: raise RuntimeError( f"The input channel of {_named(self._stream)} belongs to another " @@ -368,6 +392,24 @@ class _Claim: """ +def _owner_finished( + channel_ref: weakref.ref[InputChannel], + task: asyncio.Task[Any], # pyright: ignore[reportExplicitAny] # any task +) -> None: + """Release a reader whose consumer task finished between reads. + + A done callback of the owning task: the channel, if it still exists and the task + still owns it before its end, is closed (``InputChannel._owner_gone``). + + Args: + channel_ref: The channel, held weakly. + task: The finished task. + """ + channel = channel_ref() + if channel is not None: + channel._owner_gone(task) # pyright: ignore[reportPrivateUsage] # the task's release + + def _release_claim(feed: BatchFeed, channel_ref: weakref.ref[InputChannel]) -> None: """Release a reader whose claim was freed before any task took it over. diff --git a/tests/test_channels/test_record_batch_channels.py b/tests/test_channels/test_record_batch_channels.py index 0148fa1ee..da1bd5450 100644 --- a/tests/test_channels/test_record_batch_channels.py +++ b/tests/test_channels/test_record_batch_channels.py @@ -603,22 +603,34 @@ 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, is cancelled and awaited, so no task fails - later with nobody to hear it.""" + 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.""" left = source(2) right = source(2, source_id="other") + left_batches = batches_of(left, 1) unheard: list[Any] = [] async def read() -> None: asyncio.get_running_loop().set_exception_handler( lambda _loop, context: unheard.append(context) ) - first, second = left.open_channel(), right.open_channel() + producer = OutputChannel(left, retain=False, buffer_size=1) + first = producer.open_reader() + second = right.open_channel() _ = await second.receive() + await producer.send(left_batches[0]) # the conversion takes it and waits op = SemiJoin() output = OutputChannel(op(left, right)) with pytest.raises(RuntimeError, match="read already"): await op.async_execute_batches([first, second], output) + # The conversion is done: its reader is closed and its producer no longer + # waits for it. + async with asyncio.timeout(TIMEOUT): + await producer.send(left_batches[1]) + await producer.send(left_batches[1]) + with pytest.raises(ChannelClosed): + _ = await first.receive() gc.collect() await asyncio.sleep(0.01) @@ -1972,6 +1984,37 @@ async def downstream() -> None: _ = output.result() +def test_a_barrier_that_read_part_of_a_failed_input_never_computes() -> None: + """CodeRabbit on PR 510: the barrier has started and taken the first batch when + its producer fails; it never computes over the part it received, and its output + fails.""" + stream = source() + batches = batches_of(stream, 2) + op = PolarsFilter(constraints={}) + + async def go() -> None: + feed = OutputChannel(stream, retain=False, buffer_size=1) + reader = feed.open_reader() + output = OutputChannel(op(stream)) + task = asyncio.ensure_future(op.async_execute_batches([reader], output)) + await feed.send(batches[0]) + # With one slot, this send returns once the barrier has taken the first + # batch: the barrier is running and holds part of its input. + await feed.send(batches[1]) + feed.fail(OSError("disk gone")) + with pytest.raises(UpstreamFailedError): + async with asyncio.timeout(TIMEOUT): + await task + with pytest.raises(RuntimeError, match="has no result"): + _ = output.result() + + with mock.patch.object( + type(op), "static_process", autospec=True, side_effect=type(op).static_process + ) as computed: + run(go) + assert computed.call_count == 0 + + def test_a_cancelled_operator_fails_its_output_and_closes_its_input() -> None: """Cancellation is a failure for the readers downstream, and the operator's input channel is closed, so its producer no longer waits for it.""" diff --git a/tests/test_channels/test_record_batch_review_findings.py b/tests/test_channels/test_record_batch_review_findings.py index f58c1d13e..577c19bd4 100644 --- a/tests/test_channels/test_record_batch_review_findings.py +++ b/tests/test_channels/test_record_batch_review_findings.py @@ -539,3 +539,132 @@ async def go() -> None: _ = await channel.to_stream() asyncio.run(go()) + + +# --- CodeRabbit on PR 510 ------------------------------------------------------------- + + +def _non_nullable_stream() -> ArrowTableStream: + """Tags ``k`` and ``g``, data ``x`` and ``y``, every field non-nullable.""" + schema = pa.schema( + [ + pa.field("k", pa.int64(), nullable=False), + pa.field("g", pa.large_string(), nullable=False), + pa.field("x", pa.float64(), nullable=False), + pa.field("y", pa.int64(), nullable=False), + ] + ) + table = pa.table( + { + "k": pa.array([1, 2], pa.int64()), + "g": pa.array(["a", "b"], pa.large_string()), + "x": pa.array([1.5, 2.5], pa.float64()), + "y": pa.array([3, 4], pa.int64()), + }, + schema=schema, + ) + return ArrowTableStream(table, tag_columns=["k", "g"]) + + +@pytest.mark.parametrize("column", ["k", "g", "x", "y"]) +def test_a_null_in_a_column_declared_non_nullable_is_refused(column: str) -> None: + """CodeRabbit on PR 510 (major): the send check compared the nullability flag + only, so a batch whose field is also flagged non-nullable but holds a null passed + and reached readers of a stream that declares no null there. Tags and data.""" + stream = _non_nullable_stream() + (batch,) = batches_of(stream) + assert not stream.arrow_schema().field(column).nullable + index = batch.schema.get_field_index(column) + values = batch.column(index).to_pylist() + values[0] = None + nulled = pa.RecordBatch.from_arrays( + [ + *batch.columns[:index], + pa.array(values, batch.schema.field(index).type), + *batch.columns[index + 1 :], + ], + schema=batch.schema, # the field still says non-nullable + ) + assert not nulled.schema.field(column).nullable + + async def write() -> None: + output = OutputChannel(stream) + with pytest.raises(ValueError, match=f"column '{column}' holds nulls"): + await output.send(nulled) + await output.send(batch) + + asyncio.run(write()) + + +@pytest.mark.parametrize("where", ["key", "item"]) +def test_a_map_typed_system_tag_column_carries_no_nested_metadata(where: str) -> None: + """CodeRabbit on PR 510: the provenance check strips field metadata at every depth + to compare, and missed the key and item fields of a map: a system-tag column of + map type with metadata on its key or item passed. A map-typed source-info column + is not a token type at all and is refused.""" + from orcapod.core.record_batch_channels import _schema_mismatch # pyright: ignore[reportPrivateUsage] + + plain = pa.map_(pa.large_string(), pa.large_string()) + key = plain.key_field + item = plain.item_field + if where == "key": + tagged = pa.map_(key.with_metadata({"m": "1"}), item) # pyright: ignore[reportArgumentType] # a field for the key + else: + tagged = pa.map_(key, item.with_metadata({"m": "1"})) # pyright: ignore[reportArgumentType] # a field for the item + values = [[("a", "b")]] + declared = pa.schema([pa.field("k", pa.int64()), pa.field("_tag_m", plain)]) + good = pa.RecordBatch.from_arrays( + [pa.array([1], pa.int64()), pa.array(values, plain)], schema=declared + ) + assert _schema_mismatch(declared, good) is None + bad = pa.RecordBatch.from_arrays( + [pa.array([1], pa.int64()), pa.array(values, plain).cast(tagged)], + names=["k", "_tag_m"], + ) + assert "carries field metadata" in str(_schema_mismatch(declared, bad)) + source_declared = pa.schema( + [pa.field("k", pa.int64()), pa.field("_source_x", plain)] + ) + source_batch = pa.RecordBatch.from_arrays( + [pa.array([1], pa.int64()), pa.array(values, plain)], schema=source_declared + ) + assert "not a token type" in str(_schema_mismatch(source_declared, source_batch)) + + +@pytest.mark.parametrize("ending", ["returns", "raises", "cancelled"]) +def test_a_reader_whose_task_finishes_between_reads_releases_its_producer( + ending: str, +) -> None: + """CodeRabbit on PR 510: a reader belongs to the task that first reads it. When + that task finishes between reads (returns, raises or is cancelled) without + reaching the end or closing it, the reader is closed, so the producer of a + bounded output does not wait for it; another task cannot read it either.""" + from orcapod.channels import ChannelClosed + + stream = source(3) + first, second, third = batches_of(stream, 1) + + async def go() -> None: + output = OutputChannel(stream, retain=False, buffer_size=1) + reader = output.open_reader() + await output.send(first) + + async def consume_one() -> None: + _ = await reader.receive() + if ending == "raises": + raise RuntimeError("the consumer failed") + if ending == "cancelled": + await asyncio.Event().wait() # cancelled below + + task = asyncio.ensure_future(consume_one()) + await output.send(second) # fills the reader's slot after the first is taken + if ending == "cancelled": + await asyncio.sleep(0) + _ = task.cancel() + _ = await asyncio.gather(task, return_exceptions=True) + async with asyncio.timeout(TIMEOUT): + await output.send(third) # the reader is gone: nothing waits for it + with pytest.raises(ChannelClosed): + _ = await reader.receive() + + asyncio.run(go()) diff --git a/tests/test_core/operators/test_record_batch_execution.py b/tests/test_core/operators/test_record_batch_execution.py index 497126db9..0f29c9b45 100644 --- a/tests/test_core/operators/test_record_batch_execution.py +++ b/tests/test_core/operators/test_record_batch_execution.py @@ -124,9 +124,14 @@ def R(stream: StreamProtocol) -> pa.Table | None: def _same_value(value: Any, expected: Any) -> bool: - """Equality of two Python values of a cell, a NaN equal to a NaN.""" + """Equality of two Python values of a cell: a NaN equal to a NaN, and ``0.0`` + and ``-0.0`` told apart (a cell's value is the input's, bit for bit).""" if isinstance(value, float) and isinstance(expected, float): - return value == expected or (math.isnan(value) and math.isnan(expected)) + if math.isnan(value) or math.isnan(expected): + return math.isnan(value) and math.isnan(expected) + if value == 0.0 and expected == 0.0: + return math.copysign(1.0, value) == math.copysign(1.0, expected) + return value == expected if isinstance(value, dict) and isinstance(expected, dict): return value.keys() == expected.keys() and all( _same_value(value[key], expected[key]) for key in value @@ -203,11 +208,21 @@ def test_inputs_with_no_rows_give_the_typed_zero_row_result(case: Case) -> None: # same Arrow types (``large_list`` predicted ``list[int | None]``, read # ``list[int]``), with rows as without them; a stream rebuilt from Arrow reads them. assert result.pipeline_hash() == sync.pipeline_hash() - # The Arrow types are those of the sync result with no rows, column for column. - sync_table = sync.as_table(columns=ALL) + # The fields (Arrow types, nullability and metadata) are those of the sync result + # with no rows as a job hands it on (its zero-row input, ``_materialize_upstream`` + # with no row), matched by name: column order is not compared. + sync_table = StaticOutputOperatorPod._materialize_upstream([], sync).as_table( # pyright: ignore[reportPrivateUsage] # the job's zero-row form + columns=ALL + ) assert sorted(table.column_names) == sorted(sync_table.column_names) - for name in table.column_names: - assert table.schema.field(name).type == sync_table.schema.field(name).type, name + assert pa.schema( + [table.schema.field(name) for name in sorted(table.column_names)] + ).equals( + pa.schema( + [sync_table.schema.field(name) for name in sorted(sync_table.column_names)] + ), + check_metadata=True, + ) def test_every_operator_is_in_the_matrix() -> None: @@ -329,19 +344,24 @@ async def go() -> tuple[int, int]: reader = feed.open_reader() output = OutputChannel(op(source)) results = output.open_reader() - task = asyncio.ensure_future(op.async_execute_batches([reader], output)) rows = pa.Table.from_batches(await source.open_channel().collect()) one_row = _cut(rows, (1,)) - await feed.send(one_row[0]) - await feed.send(one_row[1]) - async with asyncio.timeout(TIMEOUT): - first = await results.receive() - assert not task.done() - await feed.send(one_row[2]) - await feed.close() - async with asyncio.timeout(TIMEOUT): - rest = await results.collect() - await task + task = asyncio.ensure_future(op.async_execute_batches([reader], output)) + try: + # One deadline for the whole sequence: sends, reads and the join. + async with asyncio.timeout(TIMEOUT): + await feed.send(one_row[0]) + await feed.send(one_row[1]) + first = await results.receive() + assert not task.done() + await feed.send(one_row[2]) + await feed.close() + rest = await results.collect() + await task + finally: + if not task.done(): + _ = task.cancel() + _ = await asyncio.gather(task, return_exceptions=True) return first.num_rows, sum(batch.num_rows for batch in rest) assert asyncio.run(go()) == (1, 1) @@ -685,23 +705,38 @@ async def go() -> None: def test_every_input_is_closed_when_one_close_fails() -> None: """A barrier operator over two inputs whose first close raises: the second input - is still closed, and the close error is raised once both are closed.""" + is still closed (exactly once), the close error is raised once both are closed, + and the output fails with it: its inputs are closed before the output, so a + failing close never leaves a reader with a normal end (CodeRabbit on PR 510).""" left, right = source_a(), source_a() op = operators.SemiJoin() async def go() -> None: first, second = left.open_channel(), right.open_channel() + second_close = second.close + closes: list[None] = [] async def failing_close() -> None: raise OSError("cannot close") + async def counted_close() -> None: + closes.append(None) + await second_close() + first.close = failing_close # a failing input + second.close = counted_close output = OutputChannel(op(left, right)) + results = output.open_reader() with pytest.raises(OSError, match="cannot close"): await op.async_execute_batches([first, second], output) + assert len(closes) == 1 # the second input was closed, once with pytest.raises(ChannelClosed): _ = await second.receive() # closed - assert output.result().as_table().num_rows > 0 # the output completed first + with pytest.raises(UpstreamFailedError, match="cannot close"): + async with asyncio.timeout(TIMEOUT): + _ = await results.collect() # the output failed, not completed + with pytest.raises(RuntimeError, match="no result"): + _ = output.result() asyncio.run(go()) diff --git a/tests/test_core/operators/test_streaming_joins.py b/tests/test_core/operators/test_streaming_joins.py index 35ee15176..8c219eb7a 100644 --- a/tests/test_core/operators/test_streaming_joins.py +++ b/tests/test_core/operators/test_streaming_joins.py @@ -1,10 +1,12 @@ """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. +ITL-1362 (ITL-1347, stage 5): the streaming kernels of ``Join``, ``MergeJoin`` and +``SemiJoin`` (``core/operators/streaming_joins``: symmetric hash joins over Arrow record +batches) are exercised here directly, through ``push()`` and ``close()``, before they +are wired into job execution. Row order is not a result on the async path (developer, +November 22, 2026), so a kernel must give the rows of the operator's sync +``static_process`` over the same inputs as a multiset, with the same columns and Arrow +types. The oracle is the sync operator over its inputs as a job's edges carry them: each input rebuilt from its rows (``StaticOutputOperatorPod._materialize_upstream``, the row-built @@ -228,7 +230,7 @@ def assert_same_rows( 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 + assert batch.schema.equals(batches[0].schema, check_metadata=True) for field in batch.schema: if field.name.startswith(SETTLED_PREFIXES): assert field.nullable, field.name @@ -899,11 +901,20 @@ def test_join_releases_the_steps_before_one_that_cannot_emit() -> None: # 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()) + # The last input ends first: later arrivals of the others are not kept. 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 + # The others' rows arrive first and are held; the last input then ends with no + # row, and every held row is released (CodeRabbit on PR 510). + kernel = StreamingJoin(Join(), sources) + for index in order[:2]: + kernel.push(index, _sent(sources[index]).combine_chunks().to_batches()[0]) + assert kernel.held_rows > 0 + assert kernel.close(order[2]) == [] + assert kernel.held_rows == 0 @pytest.mark.parametrize("pool", NULL_POOLS) @@ -1115,3 +1126,127 @@ def test_the_oracle_tells_nested_temporal_values_apart() -> None: 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)})) + + +# --------------------------------------------------------------------------- +# CodeRabbit on PR 510 +# --------------------------------------------------------------------------- + + +def _with_meta(spec: Spec, arrangement: Arrangement) -> ArrowTableStream: + """``spec`` in ``arrangement`` as a raw stream over its source's table, with a + meta (``__``) column, which a raw stream lists as data.""" + from orcapod.core.data_tags import stream_data_tags + + source = make_source(spec, arrangement) + table = source.as_table(columns={"system_tags": True, "source": True}) + table = table.append_column( + "__note", pa.array([f"n{i}" for i in range(table.num_rows)], pa.large_string()) + ) + return ArrowTableStream( + table, + tag_columns=list(arrangement.tag_order), + data_tags=stream_data_tags(source), + ) + + +def _meta_arrangements() -> list[Any]: + from .several_items import arrangements + + params = [] + for arrangement in arrangements(P): + declared = arrangement.tag_order == P.tags + q_order = Q.tags if declared else tuple(reversed(Q.tags)) + paired = Arrangement(q_order, arrangement.layout, arrangement.roles) + label = f"{'-'.join(arrangement.tag_order)}:{arrangement.layout}:{arrangement.roles}" + params.append(pytest.param(arrangement, paired, id=label)) + return params + + +@pytest.mark.parametrize(("left", "right"), _meta_arrangements()) +def test_merge_join_over_inputs_with_a_meta_column( + left: Arrangement, right: Arrangement +) -> None: + """CodeRabbit on PR 510: a raw stream lists its meta columns as data, and both + inputs carry ``__note``; no operator carries a meta column, so it is not a + colliding data column (the kernel raised ``KeyError``). Every tag order, layout + and role.""" + inputs = (_with_meta(P, left), _with_meta(Q, right)) + _check(_merge_kernel, MergeJoin(), inputs, seeds=range(3)) + + +def _token_stream(tokens: list[Any], token_type: pa.DataType) -> ArrowTableStream: + """Tag ``k``, data ``x``, and ``x``'s source info as the given tokens.""" + return ArrowTableStream( + pa.table( + { + "k": pa.array([1, 2], pa.int64()), + "x": pa.array([10, 20], pa.int64()), + "_source_x": pa.array(tokens, token_type), + } + ), + tag_columns=["k"], + ) + + +DEEP = pa.large_list(pa.large_list(pa.large_string())) +SHALLOW = pa.large_list(pa.large_string()) + + +@pytest.mark.parametrize( + ("tokens", "token_type"), + [ + ([None, None], pa.large_string()), + ([[], []], SHALLOW), + ([[None], []], SHALLOW), + ], + ids=["all_null", "empty_lists", "null_item_and_empty"], +) +@pytest.mark.parametrize( + "make_kernel", + [_join_kernel, _merge_kernel, _semi_kernel], + ids=["join", "merge_join", "semi_join"], +) +def test_shallower_source_info_tokens_are_taken_with_every_value( + tokens: list[Any], + token_type: pa.DataType, + make_kernel: Callable[[Sequence[StreamProtocol]], StreamingJoinKernel], +) -> None: + """CodeRabbit on PR 510: a batch's source-info token type follows its own tokens, + so nulls and empty lists can give fewer list levels than the input's layout. Such + a batch is taken, every token kept; a token the layout cannot hold is refused.""" + left = _token_stream([[["a"]], [["b"]]], DEEP) + right = ArrowTableStream( + pa.table( + {"k": pa.array([1, 2], pa.int64()), "y": pa.array([5, 6], pa.int64())} + ), + tag_columns=["k"], + ) + kernel = make_kernel((left, right)) + # The left input's rows as sent, with the tokens in their own, shallower type. + sent = _sent(left).combine_chunks() + index = sent.schema.get_field_index("_source_x") + batch = sent.set_column( + index, pa.field("_source_x", token_type), pa.array(tokens, token_type) + ).to_batches()[0] + assert batch.schema.field("_source_x").type != DEEP + out = kernel.push(0, batch) + out += kernel.push(1, _sent(right).combine_chunks().to_batches()[0]) + out += kernel.close(0) + kernel.close(1) + from orcapod.core.operators.static_output_pod import concatenate_batches + + # Emitted batches type their source info by their own tokens; the complete + # table settles them (``concatenate_batches``). + got = concatenate_batches(out) + assert got is not None + assert got.num_rows == 2 + by_key = dict(zip(got.column("k").to_pylist(), got.column("_source_x").to_pylist())) + assert by_key == {1: tokens[0], 2: tokens[1]} + # A token the layout's type cannot hold is still refused. + refused = sent.set_column( + index, + pa.field("_source_x", pa.large_string()), + pa.array(["s::r0::x", "s::r1::x"], pa.large_string()), + ).to_batches()[0] + with pytest.raises(ValueError, match="_source_x"): + make_kernel((left, right)).push(0, refused) diff --git a/tests/test_core/operators/test_streaming_rejoin.py b/tests/test_core/operators/test_streaming_rejoin.py index f33819534..6021355f5 100644 --- a/tests/test_core/operators/test_streaming_rejoin.py +++ b/tests/test_core/operators/test_streaming_rejoin.py @@ -186,7 +186,7 @@ def test_repeats_of_an_origin_row_pair_one_to_one_in_arrival_order() -> None: _check(_kernel, Rejoin().static_process, inputs) -def test_thousands_of_repeats_stay_linear() -> None: +def test_alternating_repeats_keep_only_unmatched_rows() -> 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.