diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index 2764dfca2..7da1ecf72 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -1735,6 +1735,24 @@ def _typed_zero_row_table(self) -> pa.Table | None: table = typed_zero_row_table(upstream) if table is None: return None + context = StaticOutputOperatorPod._upstream_context(upstream) + if upstream.producer is None: + # An upstream with no producer (a raw stream, a source) states its own + # pipeline hash, which a stream rebuilt from its zero-row table would + # not (a raw stream's meta columns enter its hash, and its zero-row + # table has none): the system-tag names then follow the upstream's + # hash, as on the sync path (``_as_upstream_stream``'s rule). + inputs.append( + _RowsOfStream( + table, + tag_columns=upstream.keys()[0], + pipeline_hash=upstream.pipeline_hash(), + data_tags=stream_data_tags(upstream), + upstreams=upstream.upstreams, + data_context=context, + ) + ) + continue inputs.append( ArrowTableStream( table, @@ -1742,7 +1760,7 @@ def _typed_zero_row_table(self) -> pa.Table | None: data_tags=stream_data_tags(upstream), producer=upstream.producer, upstreams=upstream.upstreams, - data_context=StaticOutputOperatorPod._upstream_context(upstream), + data_context=context, ) ) pod = cast(StaticOutputOperatorPod, self._pod) diff --git a/src/orcapod/core/record_batch_channels.py b/src/orcapod/core/record_batch_channels.py index 3135f3f15..7134795d9 100644 --- a/src/orcapod/core/record_batch_channels.py +++ b/src/orcapod/core/record_batch_channels.py @@ -153,6 +153,8 @@ def __init__( # Each source-info column's token type as the batches accepted so far settle it # (``settle_token_types``): a later batch must settle with it. self._token_types: dict[str, pa.DataType] = {} + # The column order of the channel's batches: the first batch with rows'. + self._order: list[str] | None = None self._changed = asyncio.Event() @property @@ -185,8 +187,19 @@ def _raise_if_ended(self) -> None: if self._closed: raise ChannelClosed("Cannot send to a closed channel") - def _check_schema(self, batch: pa.RecordBatch) -> None: - """Raise unless ``batch`` has the schema of this channel's record batches.""" + def _check_schema(self, batch: pa.RecordBatch) -> pa.RecordBatch: + """Check ``batch`` against the channel's description; return it in the + channel's column order. + + The columns are compared by name, not by position: a result's column order + may follow its input's arrangement where the description follows another + (an order-only difference, which no stored table depends on). The first batch + with rows fixes the channel's column order, and a later batch is put into it, + so that the batches can be put under one another. + + Raises: + ValueError: If the batch's columns are not the stream's. + """ names = batch.schema.names if len(set(names)) != len(names): repeated = sorted({name for name in names if names.count(name) > 1}) @@ -220,6 +233,12 @@ def _check_schema(self, batch: pa.RecordBatch) -> None: token_types = settle_token_types(batch, self._token_types) self._schema = schema self._token_types = token_types + if batch.num_rows: + if self._order is None: + self._order = names + elif names != self._order: + batch = batch.select(self._order) + return batch async def send(self, batch: pa.RecordBatch) -> None: """Send one Arrow record batch of the stream's transport columns. @@ -242,7 +261,7 @@ async def send(self, batch: pa.RecordBatch) -> None: ValueError: If the batch's schema is not the stream's. """ self._raise_if_ended() - self._check_schema(batch) + batch = self._check_schema(batch) if not batch.num_rows: return self._sent += 1 @@ -389,7 +408,8 @@ def _named(stream: Any) -> str: # pyright: ignore[reportExplicitAny] # any str def _schema_mismatch(declared: pa.Schema, batch: pa.RecordBatch) -> str | None: """Say how a record batch's columns differ from a channel's, or ``None``. - The batch must have the description's columns in the same order, each with exactly + The 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 ``null`` type of the description (anywhere in a column's type) is carried as @@ -401,10 +421,11 @@ def _schema_mismatch(declared: pa.Schema, batch: pa.RecordBatch) -> str | None: or ``large_list`` of a token type). """ sent = batch.schema - if declared.names != sent.names: + if sorted(declared.names) != sorted(sent.names): return f"it has {sent.names}, the stream has {declared.names}" provenance = (constants.SYSTEM_TAG_PREFIX, constants.SOURCE_PREFIX) - for index, (expected, column) in enumerate(zip(declared, sent)): + for index, column in enumerate(sent): + expected = declared.field(column.name) carried = arrow_utils.normalize_to_large_types(expected.type) if column.name.startswith(constants.SOURCE_PREFIX): if not _is_token_type(column.type): diff --git a/tests/test_channels/test_record_batch_channels.py b/tests/test_channels/test_record_batch_channels.py index c9aafc50d..0913666a9 100644 --- a/tests/test_channels/test_record_batch_channels.py +++ b/tests/test_channels/test_record_batch_channels.py @@ -1062,6 +1062,125 @@ async def write() -> None: run(write) +def _in_order(batch: pa.RecordBatch, names: Sequence[str]) -> pa.RecordBatch: + return batch.select(list(names)) + + +@pytest.mark.parametrize("retain", [True, False], ids=["retained", "bounded"]) +@pytest.mark.parametrize("declared", [True, False], ids=["declared", "undeclared"]) +def test_the_first_batch_fixes_the_column_order(retain: bool, declared: bool) -> None: + """Columns are compared by name: a batch whose columns are the stream's in another + order is taken (a column order is not a result). The first batch with rows fixes + the channel's order, and every later batch is put into it, never the other way + round.""" + table = source().as_table(columns=ALL) + stream = ( + source() + if declared + else _UntypedStream( + table, tag_columns=["subject", "trial"], data_tags=["trial"] + ) + ) + assert stream.arrow_types_declared is declared + first, second, third = batches_of(stream, 3) + names = first.schema.names + reversed_names = list(reversed(names)) + shuffled = names[1::2] + names[::2] + assert len({tuple(names), tuple(reversed_names), tuple(shuffled)}) == 3 + sent = [ + _in_order(first, reversed_names), + second, # the description's order + _in_order(third, shuffled), + ] + + def names_of(batch: pa.RecordBatch) -> list[str]: + return batch.schema.names + + async def through_reader() -> tuple[list[list[str]], Any]: + output = OutputChannel(stream, retain=retain, buffer_size=4) + reader = output.open_reader() + received: list[list[str]] = [] + for batch in sent: + await output.send(batch) + received.append(names_of(await reader.receive())) + await output.close() + return received, output.result() if retain else None + + received, result = run(through_reader) + assert received == [reversed_names] * 3 + if result is not None: + rows = result.as_table(columns=ALL) + assert rows.num_rows == 7 + assert sorted(rows.column_names) == sorted(names) + + async def in_description_order() -> Any: + output = OutputChannel(stream) + for batch in (first, second, third): + await output.send(batch) + await output.close() + return output.result() + + expected = run(in_description_order).as_table(columns=ALL) + assert same(rows.select(expected.column_names), expected) + + +@pytest.mark.parametrize("declared", [True, False], ids=["declared", "undeclared"]) +def test_a_reordered_batch_must_still_have_the_streams_columns(declared: bool) -> None: + """Order aside, the check is unchanged: names match exactly (case counts), and each + column's type and nullability are the description's (or the first batch's, without + Arrow types). A refused batch fixes no order.""" + table = source().as_table(columns=ALL) + stream = ( + source() + if declared + else _UntypedStream( + table, tag_columns=["subject", "trial"], data_tags=["trial"] + ) + ) + first, second = batches_of(stream, 4) + reversed_names = list(reversed(first.schema.names)) + + def reordered(batch: pa.RecordBatch) -> pa.RecordBatch: + return _in_order(batch, reversed_names) + + recased = reordered(second).rename_columns( + ["Note" if name == "note" else name for name in reversed_names] + ) + retyped = reordered(second) + retyped = retyped.set_column( + retyped.schema.get_field_index("amplitude"), + "amplitude", + retyped.column("amplitude").cast(pa.float64()), + ) + reflagged = reordered(second) + reflagged = pa.RecordBatch.from_arrays( + reflagged.columns, + schema=pa.schema( + [ + f.with_nullable(not f.nullable) if f.name == "trial" else f + for f in reflagged.schema + ] + ), + ) + + async def write() -> list[str]: + output = OutputChannel(stream) + reader = output.open_reader() + await output.send(first) # fixes the description's order + for wrong, said in ( + (recased, "'Note'"), + (retyped, "column 'amplitude' is double"), + (reflagged, "column 'trial' is (not )?nullable"), + ): + with pytest.raises(ValueError, match=said): + await output.send(wrong) + await output.send(reordered(second)) + _ = await reader.receive() + return (await reader.receive()).schema.names + + assert run(write) == first.schema.names + + def test_what_a_description_does_not_say_is_accepted() -> None: """A ``null`` column travels as ``large_string``, and a source-info field's nullability is set over the complete table: neither is a mismatch.""" diff --git a/tests/test_core/operators/test_description_system_tags.py b/tests/test_core/operators/test_description_system_tags.py new file mode 100644 index 000000000..57350544c --- /dev/null +++ b/tests/test_core/operators/test_description_system_tags.py @@ -0,0 +1,184 @@ +"""An operator's description names its system-tag columns as its rows do (ITL-1347). + +``arrow_schema()`` is typed from the inputs' zero-row tables, without reading a row. An +input with no producer (a raw ``ArrowTableStream``) states its own pipeline hash, and the +operators that rename system tags (joins, folds) name them after it. A raw stream's meta +(``__``) columns enter that hash while its zero-row table has none, so the description +must take the input's own pipeline hash, never one re-derived from the zero-row table: +its system-tag names then equal those of the operator's sync table, and of its async +result, whose record batches are checked against the description. + +Inputs come from the shared several-items family (``several_items``): two or more tags +and two or more data columns, in every tag order and table layout, with plain, data-tag +and mixed roles, with and without a meta column. +""" + +from __future__ import annotations + +import asyncio +from collections.abc import Callable, Sequence + +import pyarrow as pa +import pytest + +from orcapod.core.data_tags import stream_data_tags +from orcapod.core.operators import Batch, GroupBy, Join, MergeJoin, SemiJoin +from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod +from orcapod.core.record_batch_channels import OutputChannel +from orcapod.core.streams import ArrowTableStream +from orcapod.core.streams.base import typed_zero_row_table +from orcapod.errors import InputValidationError +from orcapod.protocols.core_protocols import StreamProtocol +from tests.test_core.operators.several_items import ( + MAIN, + P, + Q, + Arrangement, + Spec, + arrangements, + make_source, +) + +pytestmark = pytest.mark.filterwarnings( + "ignore::orcapod.errors.ProvisionalHashWarning", + "ignore::orcapod.errors.SemiJoinIgnoredColumnWarning", +) + +SYSTEM_TAGS = {"system_tags": True} + + +def _raw(spec: Spec, arrangement: Arrangement, *, meta: bool) -> ArrowTableStream: + """``spec`` in ``arrangement`` as a raw stream over its source's table (system tags + and source info), with a meta column when ``meta``.""" + source = make_source(spec, arrangement) + table = source.as_table(columns={"system_tags": True, "source": True}) + if meta: + 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 _paired(arrangement: Arrangement) -> Arrangement: + """The arrangement of Q matching ``arrangement`` of P: the same layout and roles, + Q's tags in the same direction (declared or reversed).""" + declared = arrangement.tag_order == P.tags + order = Q.tags if declared else tuple(reversed(Q.tags)) + return Arrangement(order, arrangement.layout, arrangement.roles) + + +def _id(arrangement: Arrangement) -> str: + return f"{'-'.join(arrangement.tag_order)}:{arrangement.layout}:{arrangement.roles}" + + +# One operator over raw inputs built in one arrangement. +Case = tuple[ + Callable[[], StaticOutputOperatorPod], + Callable[[Arrangement, bool], Sequence[StreamProtocol]], +] + + +def _binary(arrangement: Arrangement, meta: bool) -> Sequence[StreamProtocol]: + return ( + _raw(P, arrangement, meta=meta), + _raw(Q, _paired(arrangement), meta=meta), + ) + + +def _unary(arrangement: Arrangement, meta: bool) -> Sequence[StreamProtocol]: + return (_raw(MAIN, arrangement, meta=meta),) + + +BINARY: dict[str, Callable[[], StaticOutputOperatorPod]] = { + "join": Join, + "merge_join": MergeJoin, + "semi_join": SemiJoin, +} +UNARY: dict[str, Callable[[], StaticOutputOperatorPod]] = { + "batch": lambda: Batch(batch_size=2), + "group_by_t1_t2": lambda: GroupBy(["t1", "t2"]), + "group_by_t2_t1": lambda: GroupBy(["t2", "t1"]), +} + +CASES: list[tuple[str, Case, Arrangement]] = [ + (name, (make_op, _binary), arrangement) + for name, make_op in BINARY.items() + for arrangement in arrangements(P) +] + [ + (name, (make_op, _unary), arrangement) + for name, make_op in UNARY.items() + for arrangement in arrangements(MAIN) +] + +PARAMS = [ + pytest.param(case, arrangement, id=f"{name}[{_id(arrangement)}]") + for name, case, arrangement in CASES +] + + +def _system_tags(names: Sequence[str]) -> list[str]: + return sorted(name for name in names if name.startswith("_tag")) + + +def _sync_names(stream: StreamProtocol) -> list[str] | None: + """The sync table's system-tag names, or ``None`` when the sync path refuses.""" + try: + return _system_tags(stream.as_table(columns=SYSTEM_TAGS).column_names) + except InputValidationError: + return None + + +@pytest.mark.parametrize("meta", [True, False], ids=["with_meta", "without_meta"]) +@pytest.mark.parametrize(("case", "arrangement"), PARAMS) +def test_the_description_names_system_tags_as_the_sync_rows_do( + case: Case, arrangement: Arrangement, meta: bool +) -> None: + """``arrow_schema()`` and the typed zero-row table (a head or a run with no rows) + name the system-tag columns as the sync table does; where the sync path refuses + the inputs, so does the description.""" + make_op, make_inputs = case + stream = make_op()(*make_inputs(arrangement, meta)) + actual = _sync_names(stream) + if actual is None: + with pytest.raises(InputValidationError): + _ = stream.arrow_schema() + return + assert actual + assert _system_tags(stream.arrow_schema().names) == actual + zero_rows = typed_zero_row_table(stream) + assert zero_rows is not None + assert _system_tags(zero_rows.column_names) == actual + + +@pytest.mark.parametrize(("case", "arrangement"), PARAMS) +def test_the_async_result_names_system_tags_as_the_description_does( + case: Case, arrangement: Arrangement +) -> None: + """The async path, where the description is used: the operator's record batches + pass the output channel's check against ``arrow_schema()``, and the result names + the system-tag columns as the description and the sync table do (inputs with a + meta column).""" + make_op, make_inputs = case + inputs = make_inputs(arrangement, True) + stream = make_op()(*inputs) + expected = _sync_names(stream) + if expected is None: + pytest.skip("the sync path refuses these inputs (checked above)") + op = make_op() + + async def run() -> StreamProtocol: + output = OutputChannel(op(*inputs)) + await op.async_execute_batches( + [stream_input.open_channel() for stream_input in inputs], output + ) + return output.result() + + result = asyncio.run(run()) + names = _system_tags(result.as_table(columns=SYSTEM_TAGS).column_names) + assert names == expected + assert _system_tags(stream.arrow_schema().names) == names diff --git a/tests/test_core/operators/test_record_batch_execution.py b/tests/test_core/operators/test_record_batch_execution.py index 61f08be7e..431963bd9 100644 --- a/tests/test_core/operators/test_record_batch_execution.py +++ b/tests/test_core/operators/test_record_batch_execution.py @@ -706,19 +706,14 @@ async def failing_close() -> None: asyncio.run(go()) -# --- A prediction bug that refuses a valid result (ITL-1365) --------------------------------- +# --- A description whose column order differs from its result's (ITL-1365) ----------------- -@pytest.mark.xfail( - strict=True, - raises=ValueError, - reason="ITL-1365: DropTagColumns predicts its tags in another order than its result " - "has them (pre-existing on main), so the result's batches do not match the " - "description and send() refuses them; the result should be sent", -) def test_drop_tag_columns_over_three_tags_sends_its_result() -> None: """Tags c, b, a with data-tags a and b; ``DropTagColumns(["a"])``: the channel - result is the table built from the sync rows.""" + result is the table built from the sync rows. The operator predicts its tags in + another order than its result has them (ITL-1365); the send check compares + columns by name, so the order-only difference does not refuse the result.""" stream = ArrowTableStream( pa.table( {