diff --git a/changelog.d/ITL-1360.md b/changelog.d/ITL-1360.md index 8121d7e70..b45908a24 100644 --- a/changelog.d/ITL-1360.md +++ b/changelog.d/ITL-1360.md @@ -1,3 +1,12 @@ +### Breaking changes and migration + +- **`SyncPipelineOrchestrator.run` takes `held` instead of `held_rows`** — a job's sync run + passes the held nodes' output streams (`held: Mapping[node, StreamProtocol] | None`); a + subclass that overrides `run` with the old `held_rows` parameter fails with `TypeError` + before the override runs: rename the parameter to `held` and read each held node's rows + from its stream (`iter_data()`). The async orchestrator still takes `held_rows`. + (ITL-1347, ITL-1360) + ### Changed - **A job node's `execute` returns its output stream** — `execute` of a source, operator, diff --git a/docs/dev/scripts/itl_1347/compare.py b/docs/dev/scripts/itl_1347/compare.py index 484d25b7e..d6e541c1b 100644 --- a/docs/dev/scripts/itl_1347/compare.py +++ b/docs/dev/scripts/itl_1347/compare.py @@ -128,17 +128,22 @@ def _without(table: pa.Table, volatile: set[str]) -> pa.Table: return table.drop_columns([c for c in table.column_names if c in volatile]) -def _rows_as_multiset(table: pa.Table) -> list[str]: - """The rows as a sorted list of their serialized values, duplicates kept. - - Floats are taken by their bits (``_bitwise``), so NaN payloads stay distinct. +def _rows_as_multiset(table: pa.Table) -> list[bytes]: + """The rows as a sorted list of their raw Arrow values, duplicates kept. + + Each row is taken alone, its columns in name order and through ``_bits`` (so + NaN payloads and ``-0.0`` stay distinct), and written in the Arrow IPC format: + two rows are equal exactly when their Arrow values are. Never Python objects, + which lose what Arrow holds (``time64[ns]`` 1 and 2 become one microsecond + ``time``; CodeRabbit on PR #510). """ table = _bitwise(table) names = sorted(table.column_names) - return sorted( - json.dumps([repr(row[n]) for n in names]) - for row in table.select(names).to_pylist() - ) + keys: list[bytes] = [] + for batch in table.select(names).to_batches(): + for index in range(batch.num_rows): + keys.append(batch.take(pa.array([index])).serialize().to_pybytes()) + return sorted(keys) def compare( diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index 87cdcbf66..4359027fd 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -491,10 +491,14 @@ def close(self) -> None: @property def opened_on(self) -> StreamProtocol | None: - """The node's output stream, read on this first access (a conversion's first - read): a channel not read yet gives it as it is when it is a complete output - in the row-built form.""" - return self._output_feed().opened_on + """The node's output stream once the channel's first read made it, else + ``None``. + + Inspecting it never runs the node or takes its binding: the first read does + (``open_channel``'s guarantee). An unread source-node channel so answers + ``None``, and a conversion (``to_stream``) reads it like any other. + """ + return self._feed.opened_on if self._feed is not None else None def _closed_feed(node: SourceNodeBase) -> CompleteStreamFeed: @@ -1881,6 +1885,12 @@ def _rows_table( Raises: UnboundSourceError: When no concrete source is attached. """ + if not reads_as_its_class(self, SourceJobNode): + # A subclass, or a node with a member replaced on the instance, may read + # its rows its own way (an ``iter_data`` that filters, or rows of its own + # without a bound source): its rows, as main iterated them (ITL-1347, the + # one rule). + return None if self._bound_source is None: raise UnboundSourceError( f"SourceJobNode '{self._name}' has no concrete source bound. " @@ -1888,11 +1898,6 @@ def _rows_table( ) if self._declared_form is not None: return None - if not reads_as_its_class(self, SourceJobNode): - # A subclass, or a node with a member replaced on the instance, may read - # its rows its own way (an ``iter_data`` that filters): its rows, as main - # iterated them (ITL-1347, the one rule). - return None if ( not table_is_rows(self._bound_source) or self._bound_source.data_context_key != self.data_context_key diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index 622fcf7d0..609b2c026 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -518,8 +518,6 @@ def _flag_by_values(table: pa.Table) -> pa.Table: Returns: The same arrays under the new field flags, with no schema metadata. """ - from orcapod.system_constants import constants - prefixes = (constants.SYSTEM_TAG_PREFIX, constants.SOURCE_PREFIX) fields = [ field.with_nullable(table.column(i).null_count > 0) @@ -557,7 +555,6 @@ def _type_source_info_by_values(table: pa.Table) -> pa.Table: the rows (``_rows_to_table``), which raises the error a table built from rows raises. """ - from orcapod.system_constants import constants from orcapod.utils import arrow_utils columns = list(table.columns) diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py index 7db176363..9f8b731f7 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -534,6 +534,7 @@ def __init__(self, stream: StreamProtocol) -> None: """ self._stream = stream self._batches: deque[pa.RecordBatch] | None = None + self._failure: BaseException | None = None async def next(self) -> pa.RecordBatch | None: """Return the stream's next record batch, or ``None`` at the end. @@ -541,20 +542,48 @@ async def next(self) -> pa.RecordBatch | None: The stream's table is read on the first call, not when the channel is opened; batches with no rows are skipped. """ + if self._failure is not None: + # The stream was read once and preparing its batches failed: the same + # error again, never a second read of the stream. + raise self._failure if self._batches is None: - # The table first: reading it is the stream's one read (an unpolled - # source polls here), and its keys are then known without another. - table = self._stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS) - # The rows' keys: a source whose keys() states its declared order has - # rows in its table's order (``keys_of_rows``). - table = row_built_columns(table, keys_of_rows(table, self._stream.keys())) - self._batches = deque( - batch - for batch in table.to_batches(max_chunksize=SOURCE_BATCH_ROWS) - if batch.num_rows - ) + try: + self._batches = deque( + batch + for batch in self._row_built_table().to_batches( + max_chunksize=SOURCE_BATCH_ROWS + ) + if batch.num_rows + ) + except BaseException as failure: + self._failure = failure + raise return self._batches.popleft() if self._batches else None + def _row_built_table(self) -> pa.Table: + """The stream's table in the row-built form: its one read. + + The table first: reading it is the stream's one read (an unpolled source polls + here), and its keys are then known without another. Its system tags must be + what rows give (``system_tags_as_rows_give``: non-null text, no field + metadata); otherwise, as on the eager routes of a job, the table is the one + its rows build (``main``'s row path), so a narrow or nullable system tag is + retyped as a row retypes it. Only a stream that holds such a column (a raw + ``ArrowTableStream``) is read that way, and its reads have no effect. + """ + table = self._stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS) + if not system_tags_as_rows_give(table): + from orcapod.core.operators.static_output_pod import ( + StaticOutputOperatorPod, + ) + + rows = list(self._stream.iter_data()) + built = StaticOutputOperatorPod._materialize_upstream(rows, self._stream) # pyright: ignore[reportPrivateUsage] # main's row path + table = built.as_table(columns=ZERO_ROW_INPUT_COLUMNS) + # The rows' keys: a source whose keys() states its declared order has rows in + # its table's order (``keys_of_rows``). + return row_built_columns(table, keys_of_rows(table, self._stream.keys())) + def close(self) -> None: """Stop reading: the batches not read are dropped.""" self._batches = deque() diff --git a/src/orcapod/protocols/core_protocols/streams.py b/src/orcapod/protocols/core_protocols/streams.py index d55c526d0..c8c72abd6 100644 --- a/src/orcapod/protocols/core_protocols/streams.py +++ b/src/orcapod/protocols/core_protocols/streams.py @@ -203,9 +203,11 @@ def arrow_schema(self) -> "pa.Schema": def arrow_types_declared(self) -> bool: """Whether ``arrow_schema()`` holds the rows' own Arrow types. - ``False`` when the stream cannot type itself without rows (an unbound slot, a - ``PollingSource`` never polled; ITL-1089), or its rows decide its types (a - narrower bind, an output held as its rows). Its schema is then the best + ``False`` when the stream cannot type itself without rows (an unbound slot + declared in Python types, a ``PollingSource`` never polled; ITL-1089), or its + rows decide its types (a narrower bind, an output held as its rows). An unbound + slot declared with explicit Arrow schemas answers ``True``: its rows will have + exactly those types, since a bind refuses a source of any other. Its schema is then the best description available without reading a row: a slot's or source's explicit Arrow declaration when it states one, otherwise its Python schema converted; a source whose schema is known only by polling, and which has not polled, has diff --git a/tests/test_core/operators/test_record_batch_execution.py b/tests/test_core/operators/test_record_batch_execution.py index 0f29c9b45..9097bbcf7 100644 --- a/tests/test_core/operators/test_record_batch_execution.py +++ b/tests/test_core/operators/test_record_batch_execution.py @@ -653,7 +653,8 @@ def test_empty_source_info_lists_are_typed_from_their_tokens(layout: str) -> Non def test_a_system_tag_with_a_null_is_refused_by_the_job_sync_path() -> None: """Pins a stream no job can run: a raw stream whose system-tag column holds a string and a null. The job's sync path refuses it (the rows' system-tag fields differ in - their flags), while the channel gives both rows; a job never sees such a stream, + their flags), and so does the channel, which builds such a stream from + its rows (CodeRabbit on PR #510); a job never sees such a stream, because a source with a nullable system tag cannot be bound to a slot (``SourceSpecMismatchError``).""" raw = ArrowTableStream( @@ -671,8 +672,8 @@ def test_a_system_tag_with_a_null_is_refused_by_the_job_sync_path() -> None: "refused", "ArrowInvalid", ) - channel = run_on_channels(SelectDataColumns(["x"]), [raw], None) - assert channel.as_table(columns=ALL).column(SYSTEM_TAG).to_pylist() == ["s", None] + with pytest.raises(pa.ArrowInvalid): + run_on_channels(SelectDataColumns(["x"]), [raw], None) # --- Ending the output and closing the inputs ------------------------------------------------ diff --git a/tests/test_pipeline/test_review_findings_510.py b/tests/test_pipeline/test_review_findings_510.py new file mode 100644 index 000000000..8ff4a1769 --- /dev/null +++ b/tests/test_pipeline/test_review_findings_510.py @@ -0,0 +1,273 @@ +"""CodeRabbit's final pass on PR #510 (head 365f2a08): one regression test per finding. + +Stages 1-2 and the differential harness (ITL-1347). Each test fails without its fix. +""" + +from __future__ import annotations + +import asyncio +import decimal +import importlib.util +from pathlib import Path +from typing import Any + +import pyarrow as pa +import pytest + +from orcapod.core.streams import ArrowTableStream +from orcapod.sources import ArrowTableSource, DictSource +from orcapod.types import Schema + + +def _plain(values: tuple[int, int] = (1, 2), source_id: str = "s") -> DictSource: + return DictSource( + [{"k": 1, "x": values[0]}, {"k": 2, "x": values[1]}], + tag_columns=["k"], + tag_only_columns=True, + source_id=source_id, + ) + + +# ── compare.py:140: set mode compares raw Arrow values ───────────────────────── + +_SCRIPT = ( + Path(__file__).resolve().parents[2] + / "docs" + / "dev" + / "scripts" + / "itl_1347" + / "compare.py" +) + + +def _compare_module() -> Any: + spec = importlib.util.spec_from_file_location("itl_1347_compare_510", _SCRIPT) + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +compare = _compare_module() + +_SET_KINDS = [ + ("time64_ns", pa.time64("ns"), [1, 9], [2, 9]), + ("timestamp_ns", pa.timestamp("ns"), [1, 9], [2, 9]), + ( + "decimal256", + pa.decimal256(76, 40), + [decimal.Decimal("1." + "0" * 39 + "1"), None], + [decimal.Decimal("1." + "0" * 39 + "2"), None], + ), + ("negative_zero", pa.float64(), [0.0, 1.0], [-0.0, 1.0]), + ( + "long_string", + pa.large_string(), + ["x" * 5000 + "a", "b"], + ["x" * 5000 + "c", "b"], + ), +] + + +@pytest.mark.parametrize( + ("kind", "before", "after"), + [case[1:] for case in _SET_KINDS], + ids=[case[0] for case in _SET_KINDS], +) +def test_set_mode_tells_raw_values_apart( + kind: Any, before: list[Any], after: list[Any] +) -> None: + """Rows differing in one raw value are different rows in set mode, also where + Python loses precision; the same rows in another order, with their duplicates, + are the same multiset.""" + first = pa.table({"v": pa.array(before, kind), "k": [1, 2]}) + second = pa.table({"v": pa.array(after, kind), "k": [1, 2]}) + assert compare._rows_as_multiset(first) != compare._rows_as_multiset(second) + reordered = first.take([1, 0]) + assert compare._rows_as_multiset(first) == compare._rows_as_multiset(reordered) + doubled = pa.concat_tables([first, first]) + assert compare._rows_as_multiset(doubled) != compare._rows_as_multiset(first) + + +# ── source_node.py:497: inspecting opened_on takes no binding ───────────────── + + +def test_inspecting_a_source_channel_s_origin_takes_no_binding() -> None: + """Reading ``opened_on`` of an unread source-node channel runs nothing: a rebind + before the first read is what the channel delivers (``open_channel``'s + first-read guarantee).""" + from orcapod.core.nodes.source_node import SourceJobNode + + node: Any = SourceJobNode.from_stream(_plain((1, 2))) + channel = node.open_channel() + assert channel.opened_on is None + node.bound_source = _plain((7, 8)) + batches = asyncio.run(channel.collect()) + assert pa.Table.from_batches(batches)["x"].to_pylist() == [7, 8] + + +# ── source_node.py:1330: an unbound slot declared in Arrow types ────────────── + + +@pytest.mark.parametrize("declared", ["arrow", "python"]) +def test_an_unbound_slot_states_its_types_as_the_protocol_says(declared: str) -> None: + """An unbound slot declared with explicit Arrow schemas answers + ``arrow_types_declared`` ``True`` (its rows will have those types: a bind refuses + any other); one declared in Python types answers ``False``.""" + from orcapod.core.nodes.source_node import SourceNode + + if declared == "arrow": + node = SourceNode( + "slot", + tag_schema=pa.schema([pa.field("k", pa.int64(), nullable=False)]), + data_schema=pa.schema([pa.field("x", pa.int64(), nullable=False)]), + ) + else: + node = SourceNode( + "slot", tag_schema=Schema({"k": int}), data_schema=Schema({"x": int}) + ) + assert node.arrow_types_declared is (declared == "arrow") + + +# ── source_node.py:1884: a subclass reads its rows without a bound source ───── + + +def test_a_source_job_node_subclass_with_rows_of_its_own_needs_no_binding() -> None: + """A ``SourceJobNode`` subclass that yields its own rows, with no bound source, + hands them on from ``execute``, as ``main`` iterated them; the unbound error is + for an exact ``SourceJobNode``.""" + from orcapod.core.nodes.source_node import SourceJobNode, UnboundSourceError + from orcapod.core.operators.static_output_pod import at_edge + + rows = list(_plain((5, 6)).iter_data()) + + class OwnRows(SourceJobNode): + def iter_data(self) -> Any: + return iter(rows) + + template: Any = SourceJobNode.from_stream(_plain()) + node: Any = OwnRows.from_stream(_plain()) + node._bound_source = None # pyright: ignore[reportPrivateUsage] # no binding + assert at_edge(node.execute()).as_table()["x"].to_pylist() == [5, 6] + template._bound_source = None # pyright: ignore[reportPrivateUsage] # no binding + with pytest.raises(UnboundSourceError): + template.execute() + + +# ── streams/base.py:550 (1): no second read after a failed preparation ──────── + + +def test_a_failed_batch_preparation_is_raised_again_without_a_second_read() -> None: + """``keys()`` fails after the table was read: a later read raises the same error + and never reads the stream again.""" + from orcapod.core.streams.base import CompleteStreamFeed + + reads: list[int] = [] + base = _plain() + + class Failing: + def as_table(self, **kwargs: Any) -> Any: + reads.append(1) + return base.as_table(**kwargs) + + def keys(self, **kwargs: Any) -> Any: + raise RuntimeError("keys failed") + + feed = CompleteStreamFeed(Failing()) # pyright: ignore[reportArgumentType] + for _ in range(2): + with pytest.raises(RuntimeError, match="keys failed"): + asyncio.run(feed.next()) + assert reads == [1] + + +# ── streams/base.py:550 (2): system tags the rows retype take the row path ──── + + +def _with_system_tag(column: pa.Array[Any]) -> ArrowTableStream: + table = pa.table({"k": [1, 2], "x": [10, 20], "e": column}) + return ArrowTableStream(table, tag_columns=["k"], system_tag_columns=["e"]) + + +@pytest.mark.parametrize( + "column", + [ + pa.array([1, 2], pa.int16()), + pa.array([1, 2], pa.int32()), + pa.array(["a", "b"], pa.string()), + ], + ids=["int16", "int32", "string"], +) +def test_a_channel_on_a_stream_gives_the_rows_system_tag_types( + column: pa.Array[Any], +) -> None: + """A channel opened on an exact ``ArrowTableStream`` whose system tag rows would + retype delivers what the rows build (``main``'s row path), e.g. ``int16`` as + ``int64``.""" + from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod + from orcapod.core.streams.base import ZERO_ROW_INPUT_COLUMNS + + stream = _with_system_tag(column) + delivered = pa.Table.from_batches(asyncio.run(stream.open_channel().collect())) + built = StaticOutputOperatorPod._materialize_upstream( # pyright: ignore[reportPrivateUsage] # main's row path + list(stream.iter_data()), stream + ).as_table(columns=ZERO_ROW_INPUT_COLUMNS) + (name,) = [n for n in delivered.column_names if n.startswith("_tag")] + assert delivered.schema.field(name).type == built.schema.field(name).type + assert delivered[name].to_pylist() == built[name].to_pylist() + + +def test_a_channel_on_a_stream_whose_rows_cannot_make_one_table_raises() -> None: + """A string system tag holding a null and a value: the rows cannot make one + table; the channel raises what ``main``'s row build raises.""" + stream = _with_system_tag(pa.array(["a", None], pa.large_string())) + with pytest.raises(pa.ArrowInvalid): + asyncio.run(stream.open_channel().collect()) + + +def test_an_arrow_table_source_channel_takes_the_whole_table() -> None: + """The ordinary case keeps the fast path: a source's own system tags are what the + rows give.""" + source = ArrowTableSource( + pa.table({"k": [1, 2], "x": [10, 20]}), + tag_columns=["k"], + tag_only_columns=True, + source_id="s", + ) + delivered = pa.Table.from_batches(asyncio.run(source.open_channel().collect())) + assert delivered["x"].to_pylist() == [10, 20] + + +# ── job.py:1003 (declined): no route for the old ``run(held_rows=)`` override ─ + + +def test_a_sync_orchestrator_override_of_the_old_signature_is_not_supported() -> None: + """Declined: no compatibility shim (pre-v0.1.0). A ``SyncPipelineOrchestrator`` + subclass whose ``run`` takes the old ``held_rows`` and not ``held`` fails with + ``TypeError`` before it runs; the override is updated instead.""" + from orcapod import PipelineJob + from orcapod.databases import InMemoryArrowDatabase + from orcapod.pipeline.sync_orchestrator import SyncPipelineOrchestrator + + calls: list[int] = [] + + class OldSignature(SyncPipelineOrchestrator): + def run( # pyright: ignore[reportIncompatibleMethodOverride] # the old contract + self, + graph: Any, + *, + observer: Any = None, + materialize_results: bool = True, + run_id: str | None = None, + pipeline_uri: str = "", + load_only: bool = False, + held_rows: Any = None, + ) -> Any: + calls.append(1) + return super().run(graph, observer=observer) + + job = PipelineJob(name="old_override", database=InMemoryArrowDatabase()) + with job: + _plain().select_data_columns(["x"], label="selected") + with pytest.raises(TypeError, match="held"): + job.run(orchestrator=OldSignature()) + assert calls == [] diff --git a/tests/test_pipeline/test_rows_on_read.py b/tests/test_pipeline/test_rows_on_read.py index 9ef02718f..7b96841e7 100644 --- a/tests/test_pipeline/test_rows_on_read.py +++ b/tests/test_pipeline/test_rows_on_read.py @@ -346,9 +346,9 @@ def test_an_empty_output_is_derived_at_the_edge( ) job = PipelineJob(name="empty_edge", database=InMemoryArrowDatabase()) with job: - ArrowTableSource(table, tag_columns=["k"], source_id="s").select_data_columns( - ["x"], label="selected" - ) + ArrowTableSource( + table, tag_columns=["k"], tag_only_columns=True, source_id="s" + ).select_data_columns(["x"], label="selected") slot = next(label for label in job.nodes if label != "selected") observer = _NodeEvents() original = StaticOutputOperatorPod._materialize_upstream # pyright: ignore[reportPrivateUsage] # the row path, watched