From 522f6428581be38388dc761b5afb0c89e1b0633b Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" <> Date: Sun, 22 Nov 2026 00:36:23 -0800 Subject: [PATCH 01/36] perf(pipeline): an operator node hands the table it kept to the nodes after it (ITL-1347 stage 1) Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1347.md | 11 ++ src/orcapod/core/nodes/operator_node.py | 9 +- .../core/operators/static_output_pod.py | 80 +++++++- .../test_operator_kept_table_reuse.py | 181 ++++++++++++++++++ 4 files changed, 275 insertions(+), 6 deletions(-) create mode 100644 changelog.d/ITL-1347.md create mode 100644 tests/test_pipeline/test_operator_kept_table_reuse.py diff --git a/changelog.d/ITL-1347.md b/changelog.d/ITL-1347.md new file mode 100644 index 000000000..1396fe682 --- /dev/null +++ b/changelog.d/ITL-1347.md @@ -0,0 +1,11 @@ +### Changed + +- **A job run hands an operator node's kept table to the nodes after it** — an operator node + in a job keeps its run's output as a table built from its rows, and the sync orchestrator + then built the same table again from the same rows for each node that reads it. The node + now returns its rows carrying the table it built (`RowsWithTable`), and the orchestrator + wraps that table for each successor (`_materialize_upstream`). The table is built once + instead of once per successor plus once to keep. Every successor's input is the same: + columns, types, row order, system tags, source info, pipeline and content hashes. No hash, + stored table or output changes. First stage of the table transport between job nodes + (`docs/dev/specs/itl-1347-job-table-transport.md`). (ITL-1347) diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index d66d479c6..e51c19e50 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -1695,9 +1695,12 @@ def execute( # Materialize output = list(result_stream.iter_data()) - # Cache, in row order with or without rows (ITL-1131, ITL-1133) - self._cached_output_stream = StaticOutputOperatorPod._kept_output( - result_stream, output + # Cache, in row order with or without rows (ITL-1131, ITL-1133). The rows + # returned carry the table the kept stream is built over, so the sync + # orchestrator gives it to each successor without building it again + # (ITL-1347, stage 1). + self._cached_output_stream, output = ( + StaticOutputOperatorPod._kept_output_with_rows(result_stream, output) ) self._update_modified_time() diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index a669ecf9b..d0750405e 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -441,9 +441,35 @@ def _kept_output( Returns: A stream over the rows, in row order. """ + return StaticOutputOperatorPod._kept_output_with_rows(result, rows)[0] + + @staticmethod + def _kept_output_with_rows( + result: StreamProtocol, + rows: Sequence[tuple[TagProtocol, DataProtocol]], + ) -> tuple[StreamProtocol, list[tuple[TagProtocol, DataProtocol]]]: + """Return what ``_kept_output`` returns, and ``rows`` with the table built from them. + + With rows, the second value is a ``RowsWithTable``: the same rows, carrying the + table ``_rows_to_table(rows)`` the kept stream is built over. An operator node's + ``execute`` returns it, so the sync orchestrator gives each successor that table + (``_materialize_upstream``) instead of building it from the rows again (ITL-1347, + stage 1). Without rows, the rows are returned as a plain list. + + Args: + result: The operator's result of the run. + rows: ``result``'s rows, in order. + + Returns: + The kept stream, and the rows. + """ if rows: - return StaticOutputOperatorPod._materialize_to_stream(rows) - return StaticOutputOperatorPod._zero_rows_in_row_order(result) + row_table = StaticOutputOperatorPod._rows_to_table(rows) + return ( + StaticOutputOperatorPod._stream_over_row_table(row_table), + RowsWithTable(rows, row_table), + ) + return StaticOutputOperatorPod._zero_rows_in_row_order(result), list(rows) @staticmethod def _flag_source_info_nullability(table: pa.Table) -> pa.Table: @@ -558,7 +584,23 @@ def _materialize_to_stream( Raises: ValueError: If ``rows`` is empty. """ - table, tag_keys, data_tags = StaticOutputOperatorPod._rows_to_table(rows) + return StaticOutputOperatorPod._stream_over_row_table( + StaticOutputOperatorPod._rows_to_table(rows) + ) + + @staticmethod + def _stream_over_row_table( + row_table: tuple[pa.Table, tuple[str, ...], tuple[str, ...]], + ) -> StreamProtocol: + """The stream ``_materialize_to_stream`` builds, over ``_rows_to_table``'s result. + + Args: + row_table: The table, user tag keys and data-tags ``_rows_to_table`` returns. + + Returns: + A stream over the table's rows, in order. + """ + table, tag_keys, data_tags = row_table # No ``source_info`` argument: the table's own ``_source_*`` columns # pass through, one value per row. return ArrowTableStream(table, tag_columns=tag_keys, data_tags=data_tags) @@ -596,6 +638,13 @@ def _materialize_upstream( """ from orcapod.utils import arrow_utils + if rows and not zero_rows and isinstance(rows, RowsWithTable): + # The rows' own table, built once by the node that returned them: the + # same ``_rows_to_table(rows)`` as below, not built again (ITL-1347). + table, tag_keys, data_tags = rows.row_table + return StaticOutputOperatorPod._as_upstream_stream( + table, tag_keys, data_tags, upstream + ) if rows: table, tag_keys, data_tags = StaticOutputOperatorPod._rows_to_table(rows) if zero_rows: @@ -773,6 +822,31 @@ async def async_execute( await output.close() +class RowsWithTable(list[tuple[TagProtocol, DataProtocol]]): + """Rows of an operator node's run, carrying the table built from them. + + ``row_table`` is ``StaticOutputOperatorPod._rows_to_table`` of exactly these rows: the + table, the user tag keys and the data-tags. An operator node builds it once for the + output it keeps and returns its rows in this form, so whoever rebuilds the rows as a + stream (``_materialize_upstream``) takes the table instead of building it again + (ITL-1347, stage 1). It is a list in every other respect. + + Args: + rows: The rows, in order. + row_table: ``_rows_to_table(rows)``. + """ + + __slots__ = ("row_table",) + + def __init__( + self, + rows: Sequence[tuple[TagProtocol, DataProtocol]], + row_table: tuple[pa.Table, tuple[str, ...], tuple[str, ...]], + ) -> None: + super().__init__(rows) + self.row_table = row_table + + class _RowsOfStream(ArrowTableStream): """Rows standing in for the stream they came from, with its pipeline hash. diff --git a/tests/test_pipeline/test_operator_kept_table_reuse.py b/tests/test_pipeline/test_operator_kept_table_reuse.py new file mode 100644 index 000000000..ea0e46eed --- /dev/null +++ b/tests/test_pipeline/test_operator_kept_table_reuse.py @@ -0,0 +1,181 @@ +"""ITL-1347 stage 1: a successor's input reuses the table its operator node kept. + +An operator node's ``execute`` returns its rows as ``RowsWithTable``, carrying the table +``_rows_to_table`` built for the output the node keeps. The sync orchestrator rebuilds a +successor's input with ``_materialize_upstream``, which now takes that table instead of +building it from the rows again. The governing rule of the spec +(``docs/dev/specs/itl-1347-job-table-transport.md``) is that nothing a run shows may change. +So every successor's input must equal, byte for byte and in identity, the input built from +the same rows as a plain list (the path before stage 1). The test checks that on every +edge of a job that uses every operator kind, over several tag orders, table layouts and tag +roles. These tests are about the orchestrator's internal hand-off, so they wrap it. +""" + +from __future__ import annotations + +import warnings +from collections.abc import Iterator +from typing import Any + +import pytest + +from orcapod import PipelineJob, function_pod +from orcapod.core.operators.static_output_pod import ( + RowsWithTable, + StaticOutputOperatorPod, +) +from orcapod.databases import InMemoryArrowDatabase +from orcapod.errors import ProvisionalHashWarning +from orcapod.operators import MergeJoin, Rejoin +from orcapod.pipeline import SyncPipelineOrchestrator +from tests.test_core.operators.several_items import ( + MAIN, + P, + Q, + Arrangement, + arrangements, + make_source, +) + +ALL_COLUMNS = { + "meta": True, + "source": True, + "system_tags": True, + "context": True, + "content_hash": True, +} + + +@function_pod(output_keys="d1_doubled") +def doubled(d1: int) -> int: + return 2 * d1 + + +def build_job(arrangement: Arrangement) -> Any: + """A job in which every operator kind feeds a successor.""" + main = make_source(MAIN, arrangement) + partner_p = make_source(P) + partner_q = make_source(Q) + job = PipelineJob(name="kept_table_reuse", database=InMemoryArrowDatabase()) + with job: + joined = main.join(partner_p, label="joined") + mapped = joined.map_data({"p1": "p1_renamed"}, label="mapped") + no_nulls = mapped.drop_nulls(["d2"], label="no_nulls") + no_nulls.select_data_columns(["d1", "p1_renamed"], label="after_no_nulls") + grouped = main.group_by(["t1"], label="grouped") + grouped.select_data_columns(["d1"], label="after_grouped") + batched = main.select_data_columns(["d1"]).batch(batch_size=2, label="batched") + batched.select_data_columns(["d1"], label="after_batched") + tagged = main.add_tags(k=1, label="tagged") + doubled.pod(tagged.select_data_columns(["d1"]), label="doubled") + semi = main.semi_join(partner_q, label="semi") + semi.select_data_columns(["d3"], label="after_semi") + merged = MergeJoin()( + main.select_data_columns(["d1"]), + partner_p.map_data({"p1": "d1"}).select_data_columns(["d1"]), + ) + merged.select_data_columns(["d1"], label="after_merged") + rejoined = Rejoin()( + main.select_data_columns(["d1"]), main.select_data_columns(["d3"]) + ) + rejoined.select_data_columns(["d1"], label="after_rejoined") + nothing = main.polars_filter(d1=999, label="nothing") + nothing.select_data_columns(["d1"], label="after_nothing") + return job + + +def _identity(stream: Any) -> tuple[Any, ...]: + return ( + type(stream), + stream.producer, + tuple(id(u) for u in stream.upstreams), + stream.pipeline_hash(), + stream.content_hash(), + stream.keys(), + stream.output_schema(), + stream.data_context_key, + ) + + +@pytest.fixture +def recorded_edges(monkeypatch: pytest.MonkeyPatch) -> Iterator[list[str]]: + """Wrap the orchestrator's input rebuild; check each input against the old path.""" + original = SyncPipelineOrchestrator._materialize_as_stream + reused: list[str] = [] + + def checked(buf: Any, upstream_node: Any) -> Any: + built = original(buf, upstream_node) + plain = StaticOutputOperatorPod._materialize_upstream( # pyright: ignore[reportPrivateUsage] # the path before stage 1 + list(buf), upstream_node + ) + assert _identity(built) == _identity(plain) + built_table = built.as_table(columns=ALL_COLUMNS).combine_chunks() + plain_table = plain.as_table(columns=ALL_COLUMNS).combine_chunks() + assert built_table.schema.equals(plain_table.schema, check_metadata=True) + assert built_table.equals(plain_table, check_metadata=True) + if isinstance(buf, RowsWithTable): + reused.append(upstream_node.label) + return built + + monkeypatch.setattr( + SyncPipelineOrchestrator, "_materialize_as_stream", staticmethod(checked) + ) + yield reused + + +@pytest.mark.parametrize("arrangement", arrangements(MAIN), ids=lambda a: a.id) +def test_every_successor_input_equals_the_rebuilt_one( + arrangement: Arrangement, recorded_edges: list[str] +) -> None: + with warnings.catch_warnings(): + warnings.simplefilter("ignore", ProvisionalHashWarning) + job = build_job(arrangement) + job.run() + # Every operator node with rows handed its kept table on; the one with no rows + # (``nothing``) took the plain path, which gives its zero-row input as before. + assert { + "joined", + "mapped", + "no_nulls", + "grouped", + "batched", + "tagged", + "semi", + } <= set(recorded_edges) + assert "nothing" not in recorded_edges + + +def test_a_held_operator_node_takes_the_plain_path( + recorded_edges: list[str], +) -> None: + """A second run holds every node: buffers are plain lists, inputs as before.""" + with warnings.catch_warnings(): + warnings.simplefilter("ignore", ProvisionalHashWarning) + job = build_job(arrangements(MAIN)[0]) + job.run() + recorded_edges.clear() + # Clear one function node so the second run has something to run, fed by a + # held operator node. + job.nodes["doubled"].clear_cache() + job.run() + assert recorded_edges == [] + + +def test_execute_returns_rows_equal_to_the_plain_list() -> None: + """The rows an operator node returns compare equal to the plain list of its rows.""" + with warnings.catch_warnings(): + warnings.simplefilter("ignore", ProvisionalHashWarning) + job = build_job(arrangements(MAIN)[0]) + job.run() + node = job.nodes["joined"] + upstreams = [ + StaticOutputOperatorPod._materialize_upstream(list(u.iter_data()), u) # pyright: ignore[reportPrivateUsage] # the orchestrator's input form + for u in node.upstreams + ] + rows = node.execute(*upstreams) + assert isinstance(rows, RowsWithTable) + assert rows == list(rows) + table, tag_keys, data_tags = rows.row_table + assert table.num_rows == len(rows) + assert tag_keys == node.keys()[0] + assert isinstance(data_tags, tuple) From 22bbca8d85f57c0b71704dd567d589da89cd95de Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" <> Date: Sun, 22 Nov 2026 01:46:24 -0800 Subject: [PATCH 02/36] wip(pipeline): ITL-1347 stage 2: nodes return output streams, arrow_schema(), equivalence tests (ITL-1360) Work in progress. Done: every node's execute returns its output stream (sources and operators from F of their Arrow table, function and side-effect nodes from their rows); sync orchestrator passes streams; held= streams; node_outputs are streams; arrow_schema()/arrow_types_declared on StreamBase and SourceNodeBase; L0/L1/L2/L5/L7 tests (36 passed). Open: tests that call the removed SyncPipelineOrchestrator._materialize_as_stream (5 files) and two baseline observer-type entries whose columns moved; the full targeted suites are not run. Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/nodes/function_node.py | 25 +- src/orcapod/core/nodes/operator_node.py | 49 +++- src/orcapod/core/nodes/source_node.py | 86 +++++- .../core/operators/static_output_pod.py | 107 +++---- src/orcapod/core/streams/base.py | 56 ++++ src/orcapod/pipeline/async_orchestrator.py | 39 ++- src/orcapod/pipeline/job.py | 4 +- src/orcapod/pipeline/loaded_side_effects.py | 5 +- src/orcapod/pipeline/node_run.py | 20 +- src/orcapod/pipeline/result.py | 11 +- src/orcapod/pipeline/sync_orchestrator.py | 118 +++----- .../protocols/core_protocols/streams.py | 26 ++ src/orcapod/protocols/node_protocols.py | 8 +- src/orcapod/side_effects.py | 27 +- .../function_pod/test_ephemeral_result.py | 26 +- .../function_pod/test_function_pod_ctx_arg.py | 4 +- .../nodes/test_function_node_iteration.py | 8 +- tests/test_core/nodes/test_node_execute.py | 6 +- .../operators/test_materialize_source_info.py | 2 +- .../test_side_effect_function_pod.py | 4 +- .../side_effect_pod/test_side_effect_pod.py | 16 +- ...est_postgresql_table_source_integration.py | 4 +- .../test_spiraldb_table_source_where.py | 6 +- .../sources/test_sqlite_table_source.py | 4 +- tests/test_core/test_tracker.py | 2 +- .../test_current_run_review_fixes.py | 10 +- .../test_job_node_rows_after_run.py | 2 +- tests/test_pipeline/test_node_protocols.py | 14 +- .../test_operator_kept_table_reuse.py | 181 ------------ .../test_operator_node_async_readback.py | 2 +- .../test_stream_transport_equivalence.py | 269 ++++++++++++++++++ 31 files changed, 725 insertions(+), 416 deletions(-) delete mode 100644 tests/test_pipeline/test_operator_kept_table_reuse.py create mode 100644 tests/test_pipeline/test_stream_transport_equivalence.py diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 6b8ee6a3a..3b2b2e1da 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -2456,6 +2456,19 @@ def as_node(self) -> FunctionNode: # Data processing # ------------------------------------------------------------------ + def _output_stream( + self, rows: list[tuple[TagProtocol, DataProtocol]] + ) -> StreamProtocol: + """The output stream of a run whose output rows are ``rows``. + + What the sync orchestrator built from a node's rows for its successors + (``StaticOutputOperatorPod._materialize_upstream``): the rows' table with this + node's identity, or the node's zero-row input when there is no row. + """ + from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod + + return StaticOutputOperatorPod._materialize_upstream(rows, self) + def execute_data( self, tag: TagProtocol, @@ -2485,7 +2498,7 @@ def execute( error_policy: Literal["continue", "fail_fast"] = "continue", run_id: str | None = None, load_only: bool = False, - ) -> list[tuple[TagProtocol, DataProtocol]]: + ) -> StreamProtocol: """Execute all data from a stream: compute, persist, and cache. For each data: fire ``on_data_start``, check the in-memory cache @@ -2511,8 +2524,10 @@ def execute( this way. Returns: - Materialized list of (tag, output_data) pairs, excluding - ``None`` outputs and failed data. + The node's output stream: its output rows (no row for a ``None`` output or + a failed row) as the table ``_rows_to_table`` builds from them, with this + node's identity (``StaticOutputOperatorPod._materialize_upstream``). The sync + orchestrator hands it to every successor (ITL-1347, stage 2). Raises: RuntimeError: If the node was loaded by ``PipelineJob.load`` and so @@ -2524,7 +2539,7 @@ def execute( from orcapod.pipeline.observer import NoOpObserver if load_only: - return self._execute_load_only(input_stream, observer) + return self._output_stream(self._execute_load_only(input_stream, observer)) if self._function_pod is None: raise self._cannot_compute_error() @@ -2653,7 +2668,7 @@ def execute( self.clear_cache() raise - return output + return self._output_stream(output) def _empty_data_cache_hit( self, tag: TagProtocol, data: EmptyData, base_entry_id: bytes diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index e51c19e50..ae33d7716 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -1645,7 +1645,7 @@ def execute( *input_streams: StreamProtocol, observer: ExecutionObserverProtocol | None = None, load_only: bool = False, - ) -> list[tuple[TagProtocol, DataProtocol]]: + ) -> StreamProtocol: """Execute input streams: compute, persist, and cache. Args: @@ -1657,7 +1657,10 @@ def execute( as in any run. Returns: - Materialized list of (tag, data) pairs. + The node's output stream: its rows as the table ``_rows_to_table`` builds + from them (``StaticOutputOperatorPod._output_stream``), with this node's + identity, built from the operator's result table without making rows + (ITL-1347, stage 2). The sync orchestrator hands it to every successor. Raises: ValueError: If the node caches (``LOG`` or ``REPLAY``) and a source @@ -1685,23 +1688,37 @@ def execute( # Check REPLAY cache first cached_output = self.get_cached_output() if cached_output is not None: - output = list(cached_output.iter_data()) + output = StaticOutputOperatorPod._output_stream( + cached_output.as_table(columns=ZERO_ROW_INPUT_COLUMNS), + cached_output.keys()[0], + stream_data_tags(cached_output), + self, + ) ctx_obs.on_node_end(node_label, node_hash) return output # Compute result_stream = self._operator.process(*input_streams) - # Materialize - output = list(result_stream.iter_data()) + # The result's table, as the table built from its rows would be, without + # making the rows (ITL-1347, stage 2). + result_table = result_stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS) + tag_keys = result_stream.keys()[0] + data_tags = stream_data_tags(result_stream) - # Cache, in row order with or without rows (ITL-1131, ITL-1133). The rows - # returned carry the table the kept stream is built over, so the sync - # orchestrator gives it to each successor without building it again - # (ITL-1347, stage 1). - self._cached_output_stream, output = ( - StaticOutputOperatorPod._kept_output_with_rows(result_stream, output) - ) + # Cache, in row order with or without rows (ITL-1131, ITL-1133). + if result_table.num_rows: + kept_table = StaticOutputOperatorPod._row_built_form( + result_table, tag_keys + ) + self._cached_output_stream = ArrowTableStream( + kept_table, tag_columns=tag_keys, data_tags=data_tags + ) + else: + kept_table = None + self._cached_output_stream = ( + StaticOutputOperatorPod._zero_rows_in_row_order(result_stream) + ) self._update_modified_time() @@ -1714,6 +1731,14 @@ def execute( ): self._store_output_stream(self._cached_output_stream) + # The output stream, built once the node holds its run (as the sync + # orchestrator built a successor's input after ``execute`` returned). + if kept_table is not None: + output = StaticOutputOperatorPod._as_upstream_stream( + kept_table, tag_keys, data_tags, self + ) + else: + output = StaticOutputOperatorPod._materialize_upstream([], self) ctx_obs.on_node_end(node_label, node_hash) return output except BaseException: diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index b522c117f..1688881c8 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -15,7 +15,7 @@ from abc import ABC, abstractmethod from collections.abc import AsyncIterator, Collection, Iterator, Mapping from datetime import datetime -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING, Any, cast import pyarrow as pa @@ -23,10 +23,12 @@ from orcapod.config import OrcapodConfig from orcapod.core.base import TraceableBase from orcapod.core.datagrams import Data, Tag +from orcapod.core.data_tags import stream_data_tags from orcapod.core.operators.drop_nulls import _without_none # pyright: ignore[reportPrivateUsage] # DropNulls' rule for removing None from a type, shared, never copied from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.core.streams.base import ( ZERO_ROW_INPUT_COLUMNS, + stream_arrow_schema, schema_requires_io, typed_arrow_schemas, typed_zero_row_table, @@ -1185,27 +1187,61 @@ def iter_data(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: """Yield ``(tag, data)`` pairs, or raise if data is unavailable.""" ... + def _rows_stream(self) -> "StreamProtocol": + """The stream whose rows are this node's rows (``iter_data``): this node itself.""" + return cast("StreamProtocol", self) + + def arrow_schema(self) -> pa.Schema: + """The Arrow schema of the columns this stream passes between job nodes. + + See ``stream_arrow_schema`` (ITL-1347): never reads, computes or polls a row. + The user tags are in the order of the node's rows (``_row_tag_keys``). + """ + return stream_arrow_schema(self, self._row_tag_keys()) + + def _row_tag_keys(self) -> tuple[str, ...]: + """The order of the user tags in this node's rows: its own key order.""" + return self.keys()[0] + + @property + def arrow_types_declared(self) -> bool: + """Whether ``arrow_schema()`` holds the rows' own Arrow types (ITL-1089, ITL-1347).""" + return typed_zero_row_table(self) is not None + def execute( self, *, observer: ExecutionObserverProtocol | None = None, - ) -> list[tuple[TagProtocol, DataProtocol]]: - """Execute this source node: materialize and return data. + ) -> StreamProtocol: + """Execute this source node: read its source once and return its output stream. + + The source's table, as the table built from its rows would be + (``StaticOutputOperatorPod._output_stream``), with this node's identity, built + without making rows (ITL-1347, stage 2). The sync orchestrator hands it to every + successor. Args: observer: Optional execution observer. Returns: - List of (tag, data) tuples. + The node's output stream. Raises: UnboundSourceError: When no concrete data is available. """ + from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod + node_label = self.label node_hash = self.content_hash().to_string() if observer is not None: observer.on_node_start(node_label, node_hash) - result = list(self.iter_data()) + # The stream this node's rows come from: its table and its tag order are the + # rows' (a slot's own key order can differ from its source's). + rows_stream = self._rows_stream() + table = rows_stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS) + result = StaticOutputOperatorPod._output_stream( + table, rows_stream.keys()[0], stream_data_tags(rows_stream), self + ) if observer is not None: observer.on_node_end(node_label, node_hash) return result @@ -1667,6 +1703,46 @@ def identity_structure(self) -> Any: return self._bound_source.identity_structure() return super().identity_structure() + def _row_tag_keys(self) -> tuple[str, ...]: + """The order of the user tags in this node's rows, known without reading a row. + + The bound source's key order; the declared order for a narrower source given + as the declared schema (``_DeclaredForm``); the slot's own when unbound. + """ + if self._bound_source is None: + return self.keys()[0] + if self._declared_form is not None: + return self._declared_form.tag_order + return self._bound_source.keys()[0] + + def _rows_stream(self) -> StreamProtocol: + """The stream whose rows are this node's rows (``iter_data``). + + The bound source, or, for a narrower source, the source's table given as the + declared schema (``_declared_stream``), whose rows are those ``_declared_rows`` + gives one by one. + + Raises: + UnboundSourceError: When no concrete source is attached. + """ + if self._bound_source is None: + raise UnboundSourceError( + f"SourceJobNode '{self._name}' has no concrete source bound. " + "Call job.bind(sources={'': source}) before running." + ) + if self._declared_form is None: + return self._bound_source + table = self._bound_source.as_table( + columns={ + "meta": True, + "source": True, + "system_tags": True, + "context": True, + "sort_by_tags": False, + } + ) + return self._declared_stream(self._bound_source, self._declared_form, table) + def iter_data(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: """Delegate to concrete source, or raise if unbound. diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index d0750405e..41007dc44 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -441,35 +441,68 @@ def _kept_output( Returns: A stream over the rows, in row order. """ - return StaticOutputOperatorPod._kept_output_with_rows(result, rows)[0] + if rows: + return StaticOutputOperatorPod._materialize_to_stream(rows) + return StaticOutputOperatorPod._zero_rows_in_row_order(result) @staticmethod - def _kept_output_with_rows( - result: StreamProtocol, - rows: Sequence[tuple[TagProtocol, DataProtocol]], - ) -> tuple[StreamProtocol, list[tuple[TagProtocol, DataProtocol]]]: - """Return what ``_kept_output`` returns, and ``rows`` with the table built from them. + def _row_built_form(table: pa.Table, tag_keys: Sequence[str]) -> pa.Table: + """Return ``table`` as ``_rows_to_table`` builds it from the table's own rows. + + F in the ITL-1347 spec: the same table, without making the rows. ``table`` holds + the user tags, system tags, data and source info (``ZERO_ROW_INPUT_COLUMNS``: no + context, meta or content-hash column, and each data-tag once, among the tags). + Each row's datagram normalizes its table to the large types without keeping + ``null`` (``Datagram._init_from_table``), so a ``null`` column becomes + ``large_string``. The columns then go in row order and each source-info field is + flagged nullable only when a token is null (``_as_row_built_table``). The + equality with ``_rows_to_table`` is tested over every operator, source kind and + column role (ITL-1347, L0-L2). + + Args: + table: A table of user tags, system tags, data and source info, with rows. + tag_keys: The user tag columns, in order. - With rows, the second value is a ``RowsWithTable``: the same rows, carrying the - table ``_rows_to_table(rows)`` the kept stream is built over. An operator node's - ``execute`` returns it, so the sync orchestrator gives each successor that table - (``_materialize_upstream``) instead of building it from the rows again (ITL-1347, - stage 1). Without rows, the rows are returned as a plain list. + Returns: + The table ``_rows_to_table`` would build from its rows. + """ + from orcapod.utils import arrow_utils + + return StaticOutputOperatorPod._as_row_built_table( + arrow_utils.normalize_table_to_large_types(table), tag_keys + ) + + @staticmethod + def _output_stream( + table: pa.Table, + tag_keys: Sequence[str], + data_tags: Sequence[str], + node: StreamProtocol, + ) -> StreamProtocol: + """Return the stream a node hands its successors, given the table of its rows. + + Exactly what ``_materialize_upstream`` builds from the node's rows: with rows, + ``_row_built_form`` of ``table`` as ``node``'s stream (``_as_upstream_stream``); + without, ``node``'s zero-row input. A node's ``execute`` returns it, and the sync + orchestrator gives it to every successor as it is (ITL-1347, stage 2). Args: - result: The operator's result of the run. - rows: ``result``'s rows, in order. + table: The node's rows: user tags, system tags, data and source info. + tag_keys: The user tag columns of the rows, in order. + data_tags: The data-tags among ``tag_keys``. + node: The node (or stream) whose output this is. Returns: - The kept stream, and the rows. + The output stream, with ``node``'s identity. """ - if rows: - row_table = StaticOutputOperatorPod._rows_to_table(rows) - return ( - StaticOutputOperatorPod._stream_over_row_table(row_table), - RowsWithTable(rows, row_table), - ) - return StaticOutputOperatorPod._zero_rows_in_row_order(result), list(rows) + if table.num_rows == 0: + return StaticOutputOperatorPod._materialize_upstream([], node) + return StaticOutputOperatorPod._as_upstream_stream( + StaticOutputOperatorPod._row_built_form(table, tag_keys), + tag_keys, + data_tags, + node, + ) @staticmethod def _flag_source_info_nullability(table: pa.Table) -> pa.Table: @@ -638,13 +671,6 @@ def _materialize_upstream( """ from orcapod.utils import arrow_utils - if rows and not zero_rows and isinstance(rows, RowsWithTable): - # The rows' own table, built once by the node that returned them: the - # same ``_rows_to_table(rows)`` as below, not built again (ITL-1347). - table, tag_keys, data_tags = rows.row_table - return StaticOutputOperatorPod._as_upstream_stream( - table, tag_keys, data_tags, upstream - ) if rows: table, tag_keys, data_tags = StaticOutputOperatorPod._rows_to_table(rows) if zero_rows: @@ -822,31 +848,6 @@ async def async_execute( await output.close() -class RowsWithTable(list[tuple[TagProtocol, DataProtocol]]): - """Rows of an operator node's run, carrying the table built from them. - - ``row_table`` is ``StaticOutputOperatorPod._rows_to_table`` of exactly these rows: the - table, the user tag keys and the data-tags. An operator node builds it once for the - output it keeps and returns its rows in this form, so whoever rebuilds the rows as a - stream (``_materialize_upstream``) takes the table instead of building it again - (ITL-1347, stage 1). It is a list in every other respect. - - Args: - rows: The rows, in order. - row_table: ``_rows_to_table(rows)``. - """ - - __slots__ = ("row_table",) - - def __init__( - self, - rows: Sequence[tuple[TagProtocol, DataProtocol]], - row_table: tuple[pa.Table, tuple[str, ...], tuple[str, ...]], - ) -> None: - super().__init__(rows) - self.row_table = row_table - - class _RowsOfStream(ArrowTableStream): """Rows standing in for the stream they came from, with its pipeline hash. diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py index 0f8a5cb33..e8dbb149b 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -184,6 +184,50 @@ def typed_zero_row_input(stream: object) -> pa.Table | None: ) +def stream_arrow_schema( + stream: object, tag_keys: Sequence[str] | None = None +) -> pa.Schema: + """Return ``stream``'s declared Arrow schema: what ``arrow_schema()`` answers (ITL-1347). + + The schema of the columns a job node passes on, without reading, computing or + polling a row: the stream's zero-row input (``typed_zero_row_input``, the Arrow types + its rows have) in row order (user tags, system tags, data, source info; + ``StaticOutputOperatorPod._in_row_order``), with no context and no meta column. A + stream that cannot type itself without rows answers with its Python schema + converted by its data context (``arrow_types_declared`` is then false). Each + source-info field is stated nullable: a table decides its flag from its tokens. A + ``null`` column keeps the zero-row ``null`` type; rows carry ``large_string`` + (ITL-1319). ITL-1307 later reads it from ``Schema`` instead, here. + + Args: + stream: The stream, source or node. + tag_keys: The order of the user tags in the stream's rows, when it differs from + ``keys()`` (a source slot gives its bound source's rows); default + ``keys()``. + + Returns: + The declared Arrow schema. + """ + from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod + from orcapod.system_constants import constants + + typed = cast(StreamProtocol, stream) + if tag_keys is None: + tag_keys = typed.keys()[0] + table = typed_zero_row_input(stream) + if table is None: + tag_schema, data_schema = typed.output_schema( + columns={"system_tags": True, "source": True} + ) + converter = StaticOutputOperatorPod._upstream_context(typed).type_converter # pyright: ignore[reportPrivateUsage] # the one place that resolves an upstream's context + table = arrow_utils.make_empty_table({**tag_schema, **data_schema}, converter) + schema = StaticOutputOperatorPod._in_row_order(table, tag_keys).schema # pyright: ignore[reportPrivateUsage] # the one statement of the row order + for index, field in enumerate(schema): + if field.name.startswith(constants.SOURCE_PREFIX): + schema = schema.set(index, field.with_nullable(True)) # pyright: ignore[reportUnknownMemberType] # stubs leave Field unparametrized + return schema + + def typed_arrow_schemas( stream: object, *, own: bool = True ) -> tuple[pa.Schema, pa.Schema]: @@ -919,6 +963,18 @@ def index( return Index(column, i, out=out, fail_on_miss=fail_on_miss)(self, label=label) + def arrow_schema(self) -> pa.Schema: + """The Arrow schema of the columns this stream passes between job nodes. + + See ``stream_arrow_schema`` (ITL-1347): never reads, computes or polls a row. + """ + return stream_arrow_schema(self) + + @property + def arrow_types_declared(self) -> bool: + """Whether ``arrow_schema()`` holds the rows' own Arrow types (ITL-1089, ITL-1347).""" + return typed_zero_row_table(self) is not None + @abstractmethod def keys( self, diff --git a/src/orcapod/pipeline/async_orchestrator.py b/src/orcapod/pipeline/async_orchestrator.py index 55cd52d5e..061616cba 100644 --- a/src/orcapod/pipeline/async_orchestrator.py +++ b/src/orcapod/pipeline/async_orchestrator.py @@ -39,7 +39,11 @@ from orcapod.channels import WritableChannel from orcapod.pipeline.dag import GraphProtocol - from orcapod.protocols.core_protocols import DataProtocol, TagProtocol + from orcapod.protocols.core_protocols import ( + DataProtocol, + StreamProtocol, + TagProtocol, + ) from orcapod.protocols.observability_protocols import ExecutionObserverProtocol logger = logging.getLogger(__name__) @@ -83,7 +87,7 @@ def run( run_id: str | None = None, pipeline_uri: str = "", load_only: bool = False, - held_rows: Mapping[Any, list[tuple[TagProtocol, DataProtocol]]] | None = None, + held: Mapping[Any, StreamProtocol] | None = None, ) -> OrchestratorResult: """Synchronous entry point — runs the async pipeline to completion. @@ -128,7 +132,7 @@ def run( run_id=run_id, pipeline_uri=pipeline_uri, load_only=load_only, - held_rows=held_rows, + held=held, ) ) @@ -150,7 +154,7 @@ def make_run() -> Coroutine[Any, Any, OrchestratorResult]: run_id=run_id, pipeline_uri=pipeline_uri, load_only=load_only, - held_rows=held_rows, + held=held, ) return _run_on_own_thread(make_run, rows_in_flight) @@ -164,7 +168,7 @@ async def run_async( run_id: str | None = None, pipeline_uri: str = "", load_only: bool = False, - held_rows: Mapping[Any, list[tuple[TagProtocol, DataProtocol]]] | None = None, + held: Mapping[Any, StreamProtocol] | None = None, ) -> OrchestratorResult: """Async entry point for callers already inside an event loop. @@ -177,7 +181,7 @@ async def run_async( pipeline_uri: Opaque URI string identifying this pipeline run. Forwarded verbatim to ``observer.on_run_start``. load_only: As for ``SyncPipelineOrchestrator.run``. - held_rows: As for ``SyncPipelineOrchestrator.run``: nodes not run, whose + held: As for ``SyncPipelineOrchestrator.run``: nodes not run, whose rows feed their successors. Returns: @@ -190,7 +194,7 @@ async def run_async( run_id=run_id, pipeline_uri=pipeline_uri, load_only=load_only, - held_rows=held_rows, + held=held, ) async def _run_async( @@ -202,9 +206,10 @@ async def _run_async( run_id: str | None = None, pipeline_uri: str = "", load_only: bool = False, - held_rows: Mapping[Any, list[tuple[TagProtocol, DataProtocol]]] | None = None, + held: Mapping[Any, StreamProtocol] | None = None, ) -> OrchestratorResult: """Core async logic: wire channels, launch tasks, collect results.""" + from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod from orcapod.pipeline.observer import NoOpObserver run_id = run_id or str(uuid.uuid4()) @@ -264,14 +269,19 @@ async def _run_async( collector = collectors[node] writer = _CollectingWriter(writer, collector) - if held_rows is not None and node in held_rows: + if held is not None and node in held: # Not run: the rows of its current run feed its successors. Its # own inputs are read and discarded, so no producer blocks on # a channel nobody reads. for upstream in in_edges.get(node, []): tg.create_task(_drain(edge_readers[(upstream, node)])) _start_node( - tg, failed_nodes, node, _send_held(held_rows[node], writer) + tg, + failed_nodes, + node, + # The held node's own rows, as before stage 2: the async + # path still carries rows (ITL-1347, stage 5 changes it). + _send_held(list(node.iter_data()), writer), ) elif is_source_node(node): _start_node( @@ -355,7 +365,14 @@ async def _run_async( tg.create_task(ch.reader.collect()) return OrchestratorResult( - node_outputs=collectors if materialize_results else {} + node_outputs=( + { + node: StaticOutputOperatorPod._materialize_upstream(rows, node) + for node, rows in collectors.items() + } + if materialize_results + else {} + ) ) except ExceptionGroup as group: # A failed database read or write stops the run. Raise it on its own, as the diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index ea3f5570f..1443d4f43 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -997,7 +997,7 @@ def run( pipeline_uri=prepared.pipeline_uri, materialize_results=materialize_results, load_only=load_only, - held_rows=plan.held_rows, + held=plan.held, ) summary = self._finish_run( prepared, @@ -1068,7 +1068,7 @@ async def run_async( pipeline_uri=prepared.pipeline_uri, materialize_results=materialize_results, load_only=load_only, - held_rows=plan.held_rows, + held=plan.held, ) summary = self._finish_run( prepared, diff --git a/src/orcapod/pipeline/loaded_side_effects.py b/src/orcapod/pipeline/loaded_side_effects.py index fc8d6ca79..aa5182742 100644 --- a/src/orcapod/pipeline/loaded_side_effects.py +++ b/src/orcapod/pipeline/loaded_side_effects.py @@ -263,7 +263,7 @@ def execute( observer: ExecutionObserverProtocol | None = None, run_id: str | None = None, load_only: bool = False, - ) -> list[tuple[TagProtocol, DataProtocol]]: + ) -> StreamProtocol: """Pass every row on in a load-only run, as every side-effect job node does. Args: @@ -273,7 +273,8 @@ def execute( load_only: Must be true: the node can only pass rows on. Returns: - The rows of ``input_stream``, which the node then holds as loaded only. + The output stream of the rows of ``input_stream``, which the node then holds + as loaded only. Raises: RuntimeError: If ``load_only`` is false; nothing is read then. diff --git a/src/orcapod/pipeline/node_run.py b/src/orcapod/pipeline/node_run.py index 44ae96fb9..9e67317fb 100644 --- a/src/orcapod/pipeline/node_run.py +++ b/src/orcapod/pipeline/node_run.py @@ -249,8 +249,8 @@ class RunPlan: Attributes: dag: The nodes the run touches: those it runs, and the predecessors that feed them (a source slot is read; any other one is held). - held_rows: The rows of each held node of ``dag``: the rows of its current run, - or of a stream outside the job; they feed the nodes after it as if it had + held: The output stream of each held node of ``dag``: of its current run, or + of a stream outside the job; it feeds the nodes after it as if the node had just run. to_run: The nodes the run runs, in dependency order. held_counts: Every node of the whole graph that holds a current run, with its @@ -258,7 +258,7 @@ class RunPlan: """ dag: Any - held_rows: dict[Any, list[Any]] + held: dict[Any, Any] to_run: list[Any] held_counts: dict[Any, int] @@ -332,15 +332,21 @@ def is_source(node: Any) -> bool: for node in to_run: for upstream in graph.predecessors(node): dag.add_edge(upstream, node) - held_rows = { - node: list(node.iter_data()) + from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod + + # A held node's output stream: what the sync orchestrator built from its rows for + # the nodes after it, exactly (ITL-1347, stage 2). + held = { + node: StaticOutputOperatorPod._materialize_upstream( + list(node.iter_data()), node + ) for node in included if not any(node is r for r in to_run) and not is_source(node) } # Counted from what each node holds: iterating an operator's rows would build a # (Tag, Data) pair per row only to count them (ITL-1351). held_counts = {node: node.held_row_count() for node in current} - return RunPlan(dag, held_rows, to_run, held_counts) + return RunPlan(dag, held, to_run, held_counts) def commit_run(databases: Sequence[ArrowDatabaseProtocol], ran: Sequence[Any]) -> None: @@ -425,7 +431,7 @@ def visit(node: Any) -> None: counter = RunCountingObserver() try: _ = SyncPipelineOrchestrator().run( - plan.dag, observer=counter, load_only=load_only, held_rows=plan.held_rows + plan.dag, observer=counter, load_only=load_only, held=plan.held ) except BaseException as run_error: if isinstance(run_error, Exception) and not load_only: diff --git a/src/orcapod/pipeline/result.py b/src/orcapod/pipeline/result.py index 94d158184..12448df8c 100644 --- a/src/orcapod/pipeline/result.py +++ b/src/orcapod/pipeline/result.py @@ -6,7 +6,7 @@ from typing import TYPE_CHECKING, Any if TYPE_CHECKING: - from orcapod.protocols.core_protocols import DataProtocol, TagProtocol + from orcapod.protocols.core_protocols import StreamProtocol @dataclass @@ -14,10 +14,9 @@ class OrchestratorResult: """Result of an orchestrator run. Attributes: - node_outputs: Mapping from graph node to its computed (tag, data) - pairs. Empty when ``materialize_results=False``. + node_outputs: Mapping from graph node to its output stream (backed by an + Arrow table; ``as_table()`` gives it, ``iter_data()`` its rows). Empty when + ``materialize_results=False``. """ - node_outputs: dict[Any, list[tuple["TagProtocol", "DataProtocol"]]] = field( - default_factory=dict - ) + node_outputs: dict[Any, "StreamProtocol"] = field(default_factory=dict) diff --git a/src/orcapod/pipeline/sync_orchestrator.py b/src/orcapod/pipeline/sync_orchestrator.py index bf9708a39..553307bfa 100644 --- a/src/orcapod/pipeline/sync_orchestrator.py +++ b/src/orcapod/pipeline/sync_orchestrator.py @@ -26,7 +26,7 @@ from orcapod.pipeline.dag import GraphProtocol from orcapod.protocols.observability_protocols import ExecutionObserverProtocol - from orcapod.protocols.core_protocols import DataProtocol, TagProtocol + from orcapod.protocols.core_protocols import StreamProtocol logger = logging.getLogger(__name__) @@ -38,8 +38,9 @@ class SyncPipelineOrchestrator: to ``node.execute(observer=...)`` which owns all per-data logic, cache lookups, and observer hooks internally. - The orchestrator is responsible only for topological ordering, - buffer management, and stream materialization between nodes. + The orchestrator is responsible only for topological ordering and for handing + each node's output stream to its successors: a node's ``execute`` returns the + stream every successor reads (ITL-1347, stage 2). """ def __init__( @@ -57,16 +58,16 @@ def run( run_id: str | None = None, pipeline_uri: str = "", load_only: bool = False, - held_rows: Mapping[Any, list[tuple[TagProtocol, DataProtocol]]] | None = None, + held: Mapping[Any, StreamProtocol] | None = None, ) -> OrchestratorResult: """Execute the node graph synchronously. Args: graph: A ``GraphProtocol`` DAG with GraphNode objects as vertices. observer: Optional execution observer forwarded to nodes. - materialize_results: If True, keep all node outputs in memory - and return them. If False, discard buffers after downstream - consumption (only DB-persisted results survive). + materialize_results: If True, keep every node's output stream and return + them. If False, drop each one once its successors have run (only + DB-persisted results survive). run_id: Optional run identifier. If not provided, a UUID is generated automatically. pipeline_uri: Opaque URI string identifying this pipeline run @@ -76,13 +77,13 @@ def run( (ITL-1095): function nodes load their inputs' stored results and skip the others, operators run without storing, and a side-effect node passes its rows on and delivers nothing. - held_rows: Nodes of ``graph`` that are not run: each one's rows (the rows - of its current run, or of a stream outside the job) feed its - successors as if it had just run. Used by ``node.run()``, which runs - only the nodes it depends on that hold no current run (ITL-1095). + held: Nodes of ``graph`` that are not run: each one's output stream (of + its current run, or of a stream outside the job) feeds its successors + as if it had just run. Used by ``node.run()``, which runs only the + nodes it depends on that hold no current run (ITL-1095). Returns: - OrchestratorResult with node outputs. + OrchestratorResult with each node's output stream. """ from orcapod.pipeline.observer import NoOpObserver @@ -94,23 +95,19 @@ def run( current: Any = None try: topo_order = list(graph.topological_sort()) - buffers: dict[Any, list[tuple[TagProtocol, DataProtocol]]] = {} + outputs: dict[Any, StreamProtocol] = {} processed: set[Any] = set() - held = held_rows if held_rows is not None else {} + held_streams = held if held is not None else {} for node in topo_order: current = node - if node in held: - buffers[node] = list(held[node]) + if node in held_streams: + outputs[node] = held_streams[node] elif is_source_node(node): - buffers[node] = node.execute(observer=effective_observer) + outputs[node] = node.execute(observer=effective_observer) elif is_function_node(node) or is_side_effect_function_node(node): - upstream_buf = self._gather_upstream(node, graph, buffers) - upstream_node = list(graph.predecessors(node))[0] - input_stream = self._materialize_as_stream( - upstream_buf, upstream_node - ) - buffers[node] = node.execute( + input_stream = self._single_input(node, graph, outputs) + outputs[node] = node.execute( input_stream, observer=effective_observer, error_policy=self._error_policy, @@ -118,22 +115,14 @@ def run( load_only=load_only, ) elif is_operator_node(node): - upstream_buffers = self._gather_upstream_multi(node, graph, buffers) - input_streams = [ - self._materialize_as_stream(buf, upstream_node) - for buf, upstream_node in upstream_buffers - ] - buffers[node] = node.execute( + input_streams = self._ordered_inputs(node, graph, outputs) + outputs[node] = node.execute( *input_streams, observer=effective_observer, load_only=load_only ) elif is_side_effect_node(node): - upstream_buf = self._gather_upstream(node, graph, buffers) - upstream_node = list(graph.predecessors(node))[0] - input_stream = self._materialize_as_stream( - upstream_buf, upstream_node - ) + input_stream = self._single_input(node, graph, outputs) # In a load-only run the node passes its rows on and delivers nothing. - buffers[node] = node.execute( + outputs[node] = node.execute( input_stream, observer=effective_observer, run_id=run_id, @@ -147,12 +136,12 @@ def run( processed.add(node) if not materialize_results: - self._gc_buffers(node, graph, buffers, processed) + self._gc_outputs(node, graph, outputs, processed) if not materialize_results: - buffers.clear() + outputs.clear() - return OrchestratorResult(node_outputs=buffers) + return OrchestratorResult(node_outputs=outputs) except OrcapodDatabaseError as exc: # Name the node the failure belongs to, if the raising site did not. if current is not None: @@ -170,70 +159,47 @@ def run( effective_observer.on_run_end(run_id) @staticmethod - def _gather_upstream( + def _single_input( node: Any, graph: "GraphProtocol[Any]", - buffers: dict[Any, list[tuple[Any, Any]]], - ) -> list[tuple[Any, Any]]: - """Gather a single upstream buffer (for function nodes).""" + outputs: dict[Any, StreamProtocol], + ) -> StreamProtocol: + """The output stream of a node's one predecessor (function and side-effect nodes).""" predecessors = list(graph.predecessors(node)) if len(predecessors) != 1: raise ValueError( f"FunctionNode expects exactly 1 upstream, got {len(predecessors)}" ) - return buffers[predecessors[0]] + return outputs[predecessors[0]] @staticmethod - def _gather_upstream_multi( + def _ordered_inputs( node: Any, graph: "GraphProtocol[Any]", - buffers: dict[Any, list[tuple[Any, Any]]], - ) -> list[tuple[list[tuple[Any, Any]], Any]]: - """Gather multiple upstream buffers with their nodes (for operators). - - Returns list of (buffer, upstream_node) tuples preserving the - order that matches the operator's input_streams order. - """ + outputs: dict[Any, StreamProtocol], + ) -> list[StreamProtocol]: + """The output streams of an operator node's predecessors, in ``node.upstreams`` order.""" predecessors = list(graph.predecessors(node)) upstream_order = {id(upstream): i for i, upstream in enumerate(node.upstreams)} sorted_preds = sorted( predecessors, key=lambda p: upstream_order.get(id(p), 0), ) - return [(buffers[p], p) for p in sorted_preds] - - @staticmethod - def _materialize_as_stream(buf: list[tuple[Any, Any]], upstream_node: Any) -> Any: - """Wrap a (tag, data) buffer as the upstream node's stream. - - ``StaticOutputOperatorPod._materialize_upstream`` builds it, the one - definition an async operator node shares when it rebuilds its inputs - for a run that produced no row. - - Args: - buf: List of (tag, data) tuples. - upstream_node: The node that produced this buffer. - - Returns: - An ArrowTableStream. - """ - from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod - - return StaticOutputOperatorPod._materialize_upstream(buf, upstream_node) + return [outputs[p] for p in sorted_preds] @staticmethod - def _gc_buffers( + def _gc_outputs( current_node: Any, graph: "GraphProtocol[Any]", - buffers: dict[Any, list[tuple[Any, Any]]], + outputs: dict[Any, StreamProtocol], processed: set[Any], ) -> None: - """Discard buffers no longer needed by any unprocessed downstream.""" + """Drop output streams no unprocessed successor still needs.""" for pred in graph.predecessors(current_node): - if pred not in buffers: + if pred not in outputs: continue all_successors_done = all( succ in processed for succ in graph.successors(pred) ) if all_successors_done: - del buffers[pred] + del outputs[pred] diff --git a/src/orcapod/protocols/core_protocols/streams.py b/src/orcapod/protocols/core_protocols/streams.py index 010d29232..1ebc044f8 100644 --- a/src/orcapod/protocols/core_protocols/streams.py +++ b/src/orcapod/protocols/core_protocols/streams.py @@ -171,6 +171,32 @@ def output_schema( """ ... + def arrow_schema(self) -> "pa.Schema": + """The Arrow schema of the columns the stream passes between job nodes. + + The user tags, system tags, data and source-info columns, in row order (user + tags, system tags, data, source info), with the Arrow types, nullability and + field metadata of the rows; no context and no meta column (ITL-1347). Known + without reading, computing or polling a row. Two exceptions keep today's + bytes: source-info fields are stated nullable (a table decides their flags + from its tokens), and a ``null`` column keeps the ``null`` type a zero-row table + has (rows carry ``large_string``; ITL-1319). + + Returns: + The declared Arrow schema. + """ + ... + + @property + def arrow_types_declared(self) -> bool: + """Whether ``arrow_schema()`` holds the rows' own Arrow types. + + ``False`` only when the stream cannot type itself without rows (an unbound + slot, a ``PollingSource`` never polled; ITL-1089): its schema is then converted + from the Python schema. + """ + ... + def iter_data(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: """ Generates explicit iterator over (tag, data) pairs in the stream. diff --git a/src/orcapod/protocols/node_protocols.py b/src/orcapod/protocols/node_protocols.py index 499c74b53..cf1080c53 100644 --- a/src/orcapod/protocols/node_protocols.py +++ b/src/orcapod/protocols/node_protocols.py @@ -46,7 +46,7 @@ def execute( self, *, observer: ExecutionObserverProtocol | None = None, - ) -> list[tuple[TagProtocol, DataProtocol]]: ... + ) -> StreamProtocol: ... async def async_execute( self, @@ -89,7 +89,7 @@ def execute( error_policy: Literal["continue", "fail_fast"] = "continue", run_id: str | None = None, load_only: bool = False, - ) -> list[tuple[TagProtocol, DataProtocol]]: ... + ) -> StreamProtocol: ... async def async_execute( self, @@ -129,7 +129,7 @@ def execute( *input_streams: StreamProtocol, observer: ExecutionObserverProtocol | None = None, load_only: bool = False, - ) -> list[tuple[TagProtocol, DataProtocol]]: ... + ) -> StreamProtocol: ... async def async_execute( self, @@ -162,7 +162,7 @@ def execute( observer: "ExecutionObserverProtocol | None" = None, run_id: str | None = None, load_only: bool = False, - ) -> "list[tuple[TagProtocol, DataProtocol]]": ... + ) -> "StreamProtocol": ... async def async_execute( self, diff --git a/src/orcapod/side_effects.py b/src/orcapod/side_effects.py index de75192ef..95f4c922e 100644 --- a/src/orcapod/side_effects.py +++ b/src/orcapod/side_effects.py @@ -13,7 +13,7 @@ import datetime import logging from collections.abc import Callable, Collection, Iterator, Sequence -from typing import TYPE_CHECKING, Any, Literal +from typing import TYPE_CHECKING, Any, Literal, cast import pyarrow as pa from typing_extensions import override @@ -1225,7 +1225,7 @@ def execute( observer: ExecutionObserverProtocol | None = None, run_id: str | None = None, load_only: bool = False, - ) -> list[tuple[TagProtocol, DataProtocol]]: + ) -> StreamProtocol: """Execute side-effect delivery for all rows in ``input_stream``. Args: @@ -1239,7 +1239,10 @@ def execute( delivering (ITL-1091). A run that raises leaves the node with no rows. Returns: - List of ``(tag, data)`` tuples — the pass-through rows. + The node's output stream: the rows it passed on, as the table + ``_rows_to_table`` builds from them, with this node's identity + (``StaticOutputOperatorPod._materialize_upstream``). The sync orchestrator + hands it to every successor (ITL-1347, stage 2). Raises: SideEffectLogDataContextError: If the invocation log holds deliveries @@ -1254,7 +1257,7 @@ def execute( self.clear_cache() raise self._hold(rows, load_only=True) - return rows + return self._output_stream(rows) try: results = self._deliver_rows(input_stream, run_id=run_id) except BaseException: @@ -1263,7 +1266,21 @@ def execute( self.clear_cache() raise self._hold(results) - return results + return self._output_stream(results) + + def _output_stream( + self, rows: list[tuple[TagProtocol, DataProtocol]] + ) -> StreamProtocol: + """The output stream of a run that passed ``rows`` on. + + What the sync orchestrator built from a node's rows for its successors + (``StaticOutputOperatorPod._materialize_upstream``). + """ + from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod + + return StaticOutputOperatorPod._materialize_upstream( + rows, cast("StreamProtocol", self) + ) def _deliver_rows( self, input_stream: StreamProtocol, *, run_id: str | None diff --git a/tests/test_core/function_pod/test_ephemeral_result.py b/tests/test_core/function_pod/test_ephemeral_result.py index 799c83bc1..2d0e6cfd1 100644 --- a/tests/test_core/function_pod/test_ephemeral_result.py +++ b/tests/test_core/function_pod/test_ephemeral_result.py @@ -152,7 +152,7 @@ def test_is_ephemeral_false_written_to_pipeline_db(self): stream = _make_stream([{"id": 0, "x": 10}]) node, db = _make_node(stream) - results = node.execute(stream) + results = list(node.execute(stream).iter_data()) assert len(results) == 1 all_records = db.get_all_records(node._versioned_pipeline_path) @@ -171,7 +171,7 @@ def test_is_ephemeral_true_written_to_pipeline_db(self): node, _ = _make_node(stream, pipeline_db=pipeline_db, is_result_ephemeral=True) node.set_ephemeral_database(ephemeral_store) - results = node.execute(stream) + results = list(node.execute(stream).iter_data()) assert len(results) == 1 all_records = pipeline_db.get_all_records(node._versioned_pipeline_path) @@ -191,7 +191,7 @@ def test_ephemeral_false_unchanged(self): """is_result_ephemeral=False: execute() behaves identically to current implementation.""" stream = _make_stream([{"id": 0, "x": 10}, {"id": 1, "x": 20}]) node, _ = _make_node(stream) - results = node.execute(stream) + results = list(node.execute(stream).iter_data()) assert len(results) == 2 vals = {tag.as_dict()["id"]: data.as_dict()["result"] for tag, data in results} assert vals == {0: 20, 1: 40} @@ -211,7 +211,7 @@ def test_ephemeral_result_written_to_memory_not_persistent_db(self): ) node.node_config = NodeConfig(is_result_ephemeral=True) node.set_ephemeral_database(ephemeral_store) - results = node.execute(stream) + results = list(node.execute(stream).iter_data()) assert len(results) == 1 assert results[0][1].as_dict()["result"] == 20 @@ -311,7 +311,7 @@ def counting_double(x: int) -> int: node.set_ephemeral_database(InMemoryArrowDatabase()) # Run 1: writes to persistent DB (is_result_ephemeral=False) - results = node.execute(stream) + results = list(node.execute(stream).iter_data()) assert len(results) == 1 assert results[0][1].as_dict()["result"] == 20 assert call_count["n"] == 1 @@ -320,7 +320,7 @@ def counting_double(x: int) -> int: node._cached_output_datas.clear() # Run 2: Phase 1 must find persistent result — no recompute - results2 = node.execute(stream) + results2 = list(node.execute(stream).iter_data()) assert len(results2) == 1 assert results2[0][1].as_dict()["result"] == 20 assert call_count["n"] == 1 # NOT recomputed @@ -374,7 +374,7 @@ def counting_double(x: int) -> int: node_both.set_ephemeral_database(ephemeral_store) node_both._cached_output_datas.clear() - results = node_both.execute(stream_both) + results = list(node_both.execute(stream_both).iter_data()) assert len(results) == 2 vals = {tag.as_dict()["id"]: data.as_dict()["result"] for tag, data in results} assert vals == {0: 20, 1: 40} @@ -482,7 +482,7 @@ def counting_double(x: int) -> int: # The anti-join should exclude the ephemeral row (entry_id clash with persistent row), # returning only the persistent result. No recomputation. - results = node.execute(stream) + results = list(node.execute(stream).iter_data()) assert len(results) == 1 assert results[0][1].as_dict()["result"] == 20 # call_count did not increase — persistent hit from anti-join merge, no recomputation @@ -524,7 +524,7 @@ def test_ephemeral_only_node(self): ) node.node_config = NodeConfig(is_result_ephemeral=True) node.set_ephemeral_database(ephemeral_store) - results = node.execute(stream) + results = list(node.execute(stream).iter_data()) assert len(results) == 1 assert results[0][1].as_dict()["result"] == 20 @@ -740,7 +740,7 @@ def test_persistent_miss_warns_and_recomputes(self, caplog): with caplog.at_level( logging.WARNING, logger="orcapod.core.nodes.function_node" ): - results = node2.execute(stream) + results = list(node2.execute(stream).iter_data()) assert len(results) == 1 # recomputed assert any( @@ -818,7 +818,7 @@ def test_ephemeral_only_node_no_persistent_db(self): ) node.node_config = NodeConfig(is_result_ephemeral=True) node.set_ephemeral_database(ephemeral_store) - results = node.execute(stream) + results = list(node.execute(stream).iter_data()) assert len(results) == 2 vals = {tag.as_dict()["id"]: data.as_dict()["result"] for tag, data in results} @@ -1021,7 +1021,7 @@ def test_legacy_records_without_ephemeral_col_treated_as_persistent(self): pipeline_database=pipeline_db, result_database=result_db, ) - results = node2.execute(stream) + results = list(node2.execute(stream).iter_data()) # Result must be served (from result DB cache or recomputed) assert len(results) == 1 @@ -1082,7 +1082,7 @@ def counting_double(x: int) -> int: result_database=result_db, ) count_before_session2 = call_count["n"] - results = node2.execute(stream) + results = list(node2.execute(stream).iter_data()) assert len(results) == 1 assert results[0][1].as_dict()["result"] == 20 assert call_count["n"] == count_before_session2 # NOT recomputed diff --git a/tests/test_core/function_pod/test_function_pod_ctx_arg.py b/tests/test_core/function_pod/test_function_pod_ctx_arg.py index 9a4460448..4ab26113a 100644 --- a/tests/test_core/function_pod/test_function_pod_ctx_arg.py +++ b/tests/test_core/function_pod/test_function_pod_ctx_arg.py @@ -156,14 +156,14 @@ def my_fn(value: int, ctx: InvocationContext) -> str: node1 = FunctionJobNode(function_pod=pod, input_stream=stream) node1.attach_databases(pipeline_database=pipeline_db) - results1 = node1.execute(stream) + results1 = list(node1.execute(stream).iter_data()) assert len(results1) == 2 assert call_count == 2 # Second run — same pod, same data, same DB — must NOT call fn again node2 = FunctionJobNode(function_pod=pod, input_stream=stream) node2.attach_databases(pipeline_database=pipeline_db) - results2 = node2.execute(stream) + results2 = list(node2.execute(stream).iter_data()) assert len(results2) == 2 assert call_count == 2 # NOT incremented diff --git a/tests/test_core/nodes/test_function_node_iteration.py b/tests/test_core/nodes/test_function_node_iteration.py index 29b5123eb..1364f648b 100644 --- a/tests/test_core/nodes/test_function_node_iteration.py +++ b/tests/test_core/nodes/test_function_node_iteration.py @@ -174,8 +174,12 @@ class CapturingObserver(NoOpObserver): def on_data_crash(self, node_label, tag, data, exc): errors.append(exc) - results = node.execute( - node._input_stream, observer=CapturingObserver(), error_policy="continue" + results = list( + node.execute( + node._input_stream, + observer=CapturingObserver(), + error_policy="continue", + ).iter_data() ) assert len(errors) == 1 assert isinstance(errors[0], ValueError) diff --git a/tests/test_core/nodes/test_node_execute.py b/tests/test_core/nodes/test_node_execute.py index 447ad1c1e..b34401b7e 100644 --- a/tests/test_core/nodes/test_node_execute.py +++ b/tests/test_core/nodes/test_node_execute.py @@ -101,7 +101,7 @@ def test_caches_internally(self, function_node_with_db): class TestFunctionNodeExecute: def test_returns_materialized_results(self, function_node_with_db): node, _, _ = function_node_with_db - results = node.execute(node._input_stream) + results = list(node.execute(node._input_stream).iter_data()) assert isinstance(results, list) assert len(results) == 2 values = sorted([pkt.as_dict()["result"] for _, pkt in results]) @@ -162,7 +162,7 @@ def operator_no_db(): class TestOperatorNodeExecute: def test_returns_materialized_results(self, operator_no_db): node, src = operator_no_db - results = node.execute(src) + results = list(node.execute(src).iter_data()) assert isinstance(results, list) assert len(results) == 2 @@ -181,6 +181,6 @@ def test_caches_internally(self, operator_no_db): def test_noop_db_in_off_mode(self, operator_no_db): node, src = operator_no_db - results = node.execute(src) + results = list(node.execute(src).iter_data()) assert len(results) == 2 assert node.get_all_records() is None diff --git a/tests/test_core/operators/test_materialize_source_info.py b/tests/test_core/operators/test_materialize_source_info.py index c6fee9a91..190c6ddec 100644 --- a/tests/test_core/operators/test_materialize_source_info.py +++ b/tests/test_core/operators/test_materialize_source_info.py @@ -688,7 +688,7 @@ def test_rerun_after_pre_fix_store(self, monkeypatch: pytest.MonkeyPatch): assert _stored_source(old) == [tokens[0]] * 3 new = self._node(db) - out = new.execute(_pin_source()) + out = list(new.execute(_pin_source()).iter_data()) # The run itself emits the corrected rows. assert _source_info_tokens(out) == tokens diff --git a/tests/test_core/side_effect_function/test_side_effect_function_pod.py b/tests/test_core/side_effect_function/test_side_effect_function_pod.py index ae7d470d1..0543c1ab7 100644 --- a/tests/test_core/side_effect_function/test_side_effect_function_pod.py +++ b/tests/test_core/side_effect_function/test_side_effect_function_pod.py @@ -176,14 +176,14 @@ def my_fn(value: int, ctx: InvocationContext) -> str: node1 = FunctionJobNode(function_pod=pod, input_stream=stream) node1.attach_databases(pipeline_database=pipeline_db) - results1 = node1.execute(stream) + results1 = list(node1.execute(stream).iter_data()) assert len(results1) == 2 assert call_count == 2 # Second run — same pod, same data, same DB — fn must NOT be called again node2 = FunctionJobNode(function_pod=pod, input_stream=stream) node2.attach_databases(pipeline_database=pipeline_db) - results2 = node2.execute(stream) + results2 = list(node2.execute(stream).iter_data()) assert len(results2) == 2 assert call_count == 2 # NOT incremented — cache hit diff --git a/tests/test_core/side_effect_pod/test_side_effect_pod.py b/tests/test_core/side_effect_pod/test_side_effect_pod.py index 18be593e4..f5eb4487d 100644 --- a/tests/test_core/side_effect_pod/test_side_effect_pod.py +++ b/tests/test_core/side_effect_pod/test_side_effect_pod.py @@ -320,7 +320,7 @@ def fn(value, ctx): calls.append(True) node, stream, db = self._make_node_with_db(fn) - results = node.execute(stream) + results = list(node.execute(stream).iter_data()) assert len(results) == 3 assert len(calls) == 3 @@ -356,14 +356,14 @@ def fn(value, ctx): node1 = SideEffectJobNode(side_effect_pod=pod, input_stream=stream) node1.attach_databases(pipeline_database=db) - results1 = node1.execute(stream) + results1 = list(node1.execute(stream).iter_data()) assert len(results1) == 2 assert len(calls) == 2 # Second run with same DB node2 = SideEffectJobNode(side_effect_pod=pod, input_stream=stream) node2.attach_databases(pipeline_database=db) - results2 = node2.execute(stream) + results2 = list(node2.execute(stream).iter_data()) assert len(results2) == 2 # rows still emitted (pass-through) assert len(calls) == 2 # fn NOT called again — completion check triggered @@ -441,7 +441,7 @@ def fn(value, ctx): # Run 1: fn raises → nothing written to DB. node1 = SideEffectJobNode(side_effect_pod=pod, input_stream=stream) node1.attach_databases(pipeline_database=db) - results1 = node1.execute(stream) + results1 = list(node1.execute(stream).iter_data()) assert len(results1) == 1 # row still emitted (drop_on_failure=False) assert call_count == 1 # fn was invoked @@ -451,7 +451,7 @@ def fn(value, ctx): # Run 2: no record found → fn is called again, still fails. node2 = SideEffectJobNode(side_effect_pod=pod, input_stream=stream) node2.attach_databases(pipeline_database=db) - results2 = node2.execute(stream) + results2 = list(node2.execute(stream).iter_data()) assert len(results2) == 1 assert call_count == 2 # retried — fn called a second time @@ -490,7 +490,7 @@ def fn(value, ctx): # Run 1: fn raises → no DB record. node1 = SideEffectJobNode(side_effect_pod=pod, input_stream=stream) node1.attach_databases(pipeline_database=db) - results1 = node1.execute(stream) + results1 = list(node1.execute(stream).iter_data()) assert len(results1) == 1 # emitted despite failure assert call_count == 1 @@ -500,7 +500,7 @@ def fn(value, ctx): # Run 2: no record → fn retried → succeeds → record written. node2 = SideEffectJobNode(side_effect_pod=pod, input_stream=stream) node2.attach_databases(pipeline_database=db) - results2 = node2.execute(stream) + results2 = list(node2.execute(stream).iter_data()) assert len(results2) == 1 assert call_count == 2 # fn called exactly once more @@ -512,7 +512,7 @@ def fn(value, ctx): # Run 3: record found → fn NOT called → row re-emitted from cache. node3 = SideEffectJobNode(side_effect_pod=pod, input_stream=stream) node3.attach_databases(pipeline_database=db) - results3 = node3.execute(stream) + results3 = list(node3.execute(stream).iter_data()) assert len(results3) == 1 assert call_count == 2 # still 2 — fn was skipped entirely diff --git a/tests/test_core/sources/test_postgresql_table_source_integration.py b/tests/test_core/sources/test_postgresql_table_source_integration.py index 46592b213..8dca286db 100644 --- a/tests/test_core/sources/test_postgresql_table_source_integration.py +++ b/tests/test_core/sources/test_postgresql_table_source_integration.py @@ -253,7 +253,9 @@ def double_response(trial: int, response: float) -> float: result = orch.run(exec_dag) fn_outputs = [ - v for k, v in result.node_outputs.items() if k.node_type == "function" + list(v.iter_data()) + for k, v in result.node_outputs.items() + if k.node_type == "function" ] assert len(fn_outputs) == 1 assert len(fn_outputs[0]) == 3 diff --git a/tests/test_core/sources/test_spiraldb_table_source_where.py b/tests/test_core/sources/test_spiraldb_table_source_where.py index db78b7787..05a84a55f 100644 --- a/tests/test_core/sources/test_spiraldb_table_source_where.py +++ b/tests/test_core/sources/test_spiraldb_table_source_where.py @@ -1933,7 +1933,9 @@ def test_execute_over_unrestricted_streams_still_caches( (("m2", 5), 5.5, 1), ] - logged = node.execute(_source(source_id="events", tag_only_columns=True)) + logged = list( + node.execute(_source(source_id="events", tag_only_columns=True)).iter_data() + ) assert self._keyed(logged) == expected stored = node.as_source().as_table().to_pylist() @@ -1952,7 +1954,7 @@ def test_execute_over_unrestricted_streams_still_caches( ) scans = len(fake_pyspiral.scan_log) - replayed = node.execute(other) + replayed = list(node.execute(other).iter_data()) assert self._keyed(replayed) == expected assert len(fake_pyspiral.scan_log) == scans diff --git a/tests/test_core/sources/test_sqlite_table_source.py b/tests/test_core/sources/test_sqlite_table_source.py index fe74de6ce..91008dc35 100644 --- a/tests/test_core/sources/test_sqlite_table_source.py +++ b/tests/test_core/sources/test_sqlite_table_source.py @@ -611,7 +611,9 @@ def double_response(trial: int, response: float) -> float: result = orch.run(exec_dag) fn_outputs = [ - v for k, v in result.node_outputs.items() if k.node_type == "function" + list(v.iter_data()) + for k, v in result.node_outputs.items() + if k.node_type == "function" ] assert len(fn_outputs) == 1 assert len(fn_outputs[0]) == 3 diff --git a/tests/test_core/test_tracker.py b/tests/test_core/test_tracker.py index 8f28798be..046239abb 100644 --- a/tests/test_core/test_tracker.py +++ b/tests/test_core/test_tracker.py @@ -251,7 +251,7 @@ def test_run_equivalent(self): """execute() on SourceJobNode returns all data rows.""" stream = _make_source() node = self._make_job_node(stream) - result = node.execute() + result = list(node.execute().iter_data()) assert len(result) == stream.as_table().num_rows def test_data_context_key(self): diff --git a/tests/test_pipeline/test_current_run_review_fixes.py b/tests/test_pipeline/test_current_run_review_fixes.py index 25f266174..7ad949768 100644 --- a/tests/test_pipeline/test_current_run_review_fixes.py +++ b/tests/test_pipeline/test_current_run_review_fixes.py @@ -17,6 +17,8 @@ import pyarrow as pa import pytest +from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod + from orcapod import PipelineJob, function_pod from orcapod.core.nodes import OperatorJobNode from orcapod.core.nodes.source_node import SourceJobNode @@ -750,14 +752,18 @@ def test_a_direct_async_run_drains_the_inputs_of_a_held_node( (grouped, summed), ): dag.add_edge(upstream, downstream) - held = {rowwise: list(rowwise.iter_data())} + held = { + rowwise: StaticOutputOperatorPod._materialize_upstream( # pyright: ignore[reportPrivateUsage] # a held node's output stream, as the run plan builds it + list(rowwise.iter_data()), rowwise + ) + } summed.clear_cache() grouped.clear_cache() orchestrator = AsyncPipelineOrchestrator(buffer_size=2, error_policy=error_policy) async def run() -> None: """Run the whole graph with ``rowwise`` held, under a time limit.""" - await asyncio.wait_for(orchestrator.run_async(dag, held_rows=held), timeout=30) + await asyncio.wait_for(orchestrator.run_async(dag, held=held), timeout=30) asyncio.run(run()) assert summed.as_table().num_rows == 2 diff --git a/tests/test_pipeline/test_job_node_rows_after_run.py b/tests/test_pipeline/test_job_node_rows_after_run.py index 6d00c1154..04ba3867a 100644 --- a/tests/test_pipeline/test_job_node_rows_after_run.py +++ b/tests/test_pipeline/test_job_node_rows_after_run.py @@ -422,7 +422,7 @@ def test_sync_one_of_two_equal_inputs_fails(self) -> None: node = self._node(self._flaky_pod()) received = sorted( (tag.as_dict()["k"], data.as_dict()["y"]) - for tag, data in node.execute(node.upstreams[0]) + for tag, data in list(node.execute(node.upstreams[0]).iter_data()) ) assert received == [(0, 6), (2, 8)] assert self._held(node) == received diff --git a/tests/test_pipeline/test_node_protocols.py b/tests/test_pipeline/test_node_protocols.py index fbd08b867..b59428341 100644 --- a/tests/test_pipeline/test_node_protocols.py +++ b/tests/test_pipeline/test_node_protocols.py @@ -200,14 +200,14 @@ def _make_source_node(self): def test_execute_returns_list(self): node = self._make_source_node() - result = node.execute() + result = list(node.execute().iter_data()) assert isinstance(result, list) assert len(result) == 3 def test_execute_populates_cached_results(self): """execute() on SourceJobNode returns correct data (no caching field).""" node = self._make_source_node() - result = node.execute() + result = list(node.execute().iter_data()) assert len(result) == 3 def test_execute_with_observer(self): @@ -234,7 +234,7 @@ def on_data_end(self, node_label, t, ip, op, cached): def test_execute_without_observer(self): """execute() works fine with no observer.""" node = self._make_source_node() - result = node.execute() + result = list(node.execute().iter_data()) assert len(result) == 3 @@ -337,7 +337,7 @@ def create_data_logger(self, t, p, **kwargs): return _NOOP_LOGGER input_stream = node._input_stream - result = node.execute(input_stream, observer=Obs()) + result = list(node.execute(input_stream, observer=Obs()).iter_data()) assert len(result) == 2 assert events[0][0] == "node_start" @@ -348,7 +348,7 @@ def create_data_logger(self, t, p, **kwargs): def test_execute_without_observer(self): node = self._make_function_node() input_stream = node._input_stream - result = node.execute(input_stream) + result = list(node.execute(input_stream).iter_data()) assert len(result) == 2 values = sorted([pkt.as_dict()["result"] for _, pkt in result]) assert values == [2, 4] @@ -488,14 +488,14 @@ def on_data_start(self, node_label, t, p): def on_data_end(self, node_label, t, ip, op, cached): pass - result = node.execute(*node._input_streams, observer=Obs()) + result = list(node.execute(*node._input_streams, observer=Obs()).iter_data()) assert len(result) == 2 assert events[0][0] == "node_start" assert events[1][0] == "node_end" def test_execute_without_observer(self): node = self._make_join_node() - result = node.execute(*node._input_streams) + result = list(node.execute(*node._input_streams).iter_data()) assert len(result) == 2 diff --git a/tests/test_pipeline/test_operator_kept_table_reuse.py b/tests/test_pipeline/test_operator_kept_table_reuse.py deleted file mode 100644 index ea0e46eed..000000000 --- a/tests/test_pipeline/test_operator_kept_table_reuse.py +++ /dev/null @@ -1,181 +0,0 @@ -"""ITL-1347 stage 1: a successor's input reuses the table its operator node kept. - -An operator node's ``execute`` returns its rows as ``RowsWithTable``, carrying the table -``_rows_to_table`` built for the output the node keeps. The sync orchestrator rebuilds a -successor's input with ``_materialize_upstream``, which now takes that table instead of -building it from the rows again. The governing rule of the spec -(``docs/dev/specs/itl-1347-job-table-transport.md``) is that nothing a run shows may change. -So every successor's input must equal, byte for byte and in identity, the input built from -the same rows as a plain list (the path before stage 1). The test checks that on every -edge of a job that uses every operator kind, over several tag orders, table layouts and tag -roles. These tests are about the orchestrator's internal hand-off, so they wrap it. -""" - -from __future__ import annotations - -import warnings -from collections.abc import Iterator -from typing import Any - -import pytest - -from orcapod import PipelineJob, function_pod -from orcapod.core.operators.static_output_pod import ( - RowsWithTable, - StaticOutputOperatorPod, -) -from orcapod.databases import InMemoryArrowDatabase -from orcapod.errors import ProvisionalHashWarning -from orcapod.operators import MergeJoin, Rejoin -from orcapod.pipeline import SyncPipelineOrchestrator -from tests.test_core.operators.several_items import ( - MAIN, - P, - Q, - Arrangement, - arrangements, - make_source, -) - -ALL_COLUMNS = { - "meta": True, - "source": True, - "system_tags": True, - "context": True, - "content_hash": True, -} - - -@function_pod(output_keys="d1_doubled") -def doubled(d1: int) -> int: - return 2 * d1 - - -def build_job(arrangement: Arrangement) -> Any: - """A job in which every operator kind feeds a successor.""" - main = make_source(MAIN, arrangement) - partner_p = make_source(P) - partner_q = make_source(Q) - job = PipelineJob(name="kept_table_reuse", database=InMemoryArrowDatabase()) - with job: - joined = main.join(partner_p, label="joined") - mapped = joined.map_data({"p1": "p1_renamed"}, label="mapped") - no_nulls = mapped.drop_nulls(["d2"], label="no_nulls") - no_nulls.select_data_columns(["d1", "p1_renamed"], label="after_no_nulls") - grouped = main.group_by(["t1"], label="grouped") - grouped.select_data_columns(["d1"], label="after_grouped") - batched = main.select_data_columns(["d1"]).batch(batch_size=2, label="batched") - batched.select_data_columns(["d1"], label="after_batched") - tagged = main.add_tags(k=1, label="tagged") - doubled.pod(tagged.select_data_columns(["d1"]), label="doubled") - semi = main.semi_join(partner_q, label="semi") - semi.select_data_columns(["d3"], label="after_semi") - merged = MergeJoin()( - main.select_data_columns(["d1"]), - partner_p.map_data({"p1": "d1"}).select_data_columns(["d1"]), - ) - merged.select_data_columns(["d1"], label="after_merged") - rejoined = Rejoin()( - main.select_data_columns(["d1"]), main.select_data_columns(["d3"]) - ) - rejoined.select_data_columns(["d1"], label="after_rejoined") - nothing = main.polars_filter(d1=999, label="nothing") - nothing.select_data_columns(["d1"], label="after_nothing") - return job - - -def _identity(stream: Any) -> tuple[Any, ...]: - return ( - type(stream), - stream.producer, - tuple(id(u) for u in stream.upstreams), - stream.pipeline_hash(), - stream.content_hash(), - stream.keys(), - stream.output_schema(), - stream.data_context_key, - ) - - -@pytest.fixture -def recorded_edges(monkeypatch: pytest.MonkeyPatch) -> Iterator[list[str]]: - """Wrap the orchestrator's input rebuild; check each input against the old path.""" - original = SyncPipelineOrchestrator._materialize_as_stream - reused: list[str] = [] - - def checked(buf: Any, upstream_node: Any) -> Any: - built = original(buf, upstream_node) - plain = StaticOutputOperatorPod._materialize_upstream( # pyright: ignore[reportPrivateUsage] # the path before stage 1 - list(buf), upstream_node - ) - assert _identity(built) == _identity(plain) - built_table = built.as_table(columns=ALL_COLUMNS).combine_chunks() - plain_table = plain.as_table(columns=ALL_COLUMNS).combine_chunks() - assert built_table.schema.equals(plain_table.schema, check_metadata=True) - assert built_table.equals(plain_table, check_metadata=True) - if isinstance(buf, RowsWithTable): - reused.append(upstream_node.label) - return built - - monkeypatch.setattr( - SyncPipelineOrchestrator, "_materialize_as_stream", staticmethod(checked) - ) - yield reused - - -@pytest.mark.parametrize("arrangement", arrangements(MAIN), ids=lambda a: a.id) -def test_every_successor_input_equals_the_rebuilt_one( - arrangement: Arrangement, recorded_edges: list[str] -) -> None: - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ProvisionalHashWarning) - job = build_job(arrangement) - job.run() - # Every operator node with rows handed its kept table on; the one with no rows - # (``nothing``) took the plain path, which gives its zero-row input as before. - assert { - "joined", - "mapped", - "no_nulls", - "grouped", - "batched", - "tagged", - "semi", - } <= set(recorded_edges) - assert "nothing" not in recorded_edges - - -def test_a_held_operator_node_takes_the_plain_path( - recorded_edges: list[str], -) -> None: - """A second run holds every node: buffers are plain lists, inputs as before.""" - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ProvisionalHashWarning) - job = build_job(arrangements(MAIN)[0]) - job.run() - recorded_edges.clear() - # Clear one function node so the second run has something to run, fed by a - # held operator node. - job.nodes["doubled"].clear_cache() - job.run() - assert recorded_edges == [] - - -def test_execute_returns_rows_equal_to_the_plain_list() -> None: - """The rows an operator node returns compare equal to the plain list of its rows.""" - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ProvisionalHashWarning) - job = build_job(arrangements(MAIN)[0]) - job.run() - node = job.nodes["joined"] - upstreams = [ - StaticOutputOperatorPod._materialize_upstream(list(u.iter_data()), u) # pyright: ignore[reportPrivateUsage] # the orchestrator's input form - for u in node.upstreams - ] - rows = node.execute(*upstreams) - assert isinstance(rows, RowsWithTable) - assert rows == list(rows) - table, tag_keys, data_tags = rows.row_table - assert table.num_rows == len(rows) - assert tag_keys == node.keys()[0] - assert isinstance(data_tags, tuple) diff --git a/tests/test_pipeline/test_operator_node_async_readback.py b/tests/test_pipeline/test_operator_node_async_readback.py index 7e7189be4..345d738a6 100644 --- a/tests/test_pipeline/test_operator_node_async_readback.py +++ b/tests/test_pipeline/test_operator_node_async_readback.py @@ -287,7 +287,7 @@ def make_node() -> OperatorJobNode: ) sync_node, async_node = make_node(), make_node() - sync_rows = sync_node.execute(source) + sync_rows = list(sync_node.execute(source).iter_data()) async def run() -> list[tuple[TagProtocol, DataProtocol]]: """Drive the node's public channel interface and collect forwarded rows.""" diff --git a/tests/test_pipeline/test_stream_transport_equivalence.py b/tests/test_pipeline/test_stream_transport_equivalence.py new file mode 100644 index 000000000..a6965a366 --- /dev/null +++ b/tests/test_pipeline/test_stream_transport_equivalence.py @@ -0,0 +1,269 @@ +"""ITL-1347 stage 2: a node's output stream equals the stream built from its rows. + +Every job node's ``execute`` now returns its output stream, which the sync orchestrator +hands to every successor. Sources build it from their Arrow table and operators from +their result's Arrow table, with no rows made (the row-built form F, +``StaticOutputOperatorPod._row_built_form``). The governing rule of the spec +(``docs/dev/specs/itl-1347-job-table-transport.md``) is that nothing a run shows may +change. So each output stream must equal, in identity and byte for byte, the stream the +orchestrator built before stage 2 from the same node's rows +(``_materialize_upstream(rows, node)``): + +- L2 (sources): rows are the source node's ``iter_data()``; +- L1 (operators): rows are the operator's result's ``iter_data()``, or the stored + stream's under ``REPLAY``; +- L0 (function and side-effect nodes): rows are the output stream's own rows; +- L5 (held nodes): a held node's stream equals the one built from its rows; +- L7: every node's declared ``arrow_schema()`` equals the schema of its output. + +The job uses every operator kind over several tag orders, table layouts and tag roles. +These tests are about the hand-off between nodes, so they wrap the nodes' ``execute``. +""" + +from __future__ import annotations + +import warnings +from collections.abc import Iterator +from typing import Any + +import pyarrow as pa +import pytest + +from orcapod import PipelineJob, function_pod, tap_pod +from orcapod.core.nodes.function_node import FunctionJobNode +from orcapod.core.nodes.operator_node import OperatorJobNode +from orcapod.core.nodes.source_node import SourceNodeBase +from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod +from orcapod.core.streams.base import ZERO_ROW_INPUT_COLUMNS +from orcapod.databases import InMemoryArrowDatabase +from orcapod.errors import ProvisionalHashWarning +from orcapod.operators import MergeJoin, Rejoin +from orcapod.side_effects import SideEffectJobNode +from orcapod.system_constants import constants +from orcapod.types import CacheMode +from tests.test_core.operators.several_items import ( + MAIN, + P, + Q, + Arrangement, + arrangements, + make_source, +) + +ALL_COLUMNS = { + "meta": True, + "source": True, + "system_tags": True, + "context": True, + "content_hash": True, +} + + +@function_pod(output_keys="d1_doubled") +def doubled(d1: int) -> int: + return 2 * d1 + + +@tap_pod +def noted(d1_doubled: int, ctx: Any) -> None: + return None + + +def build_job(arrangement: Arrangement, database: Any = None) -> Any: + """A job in which every operator kind, a function node and a side effect run.""" + main = make_source(MAIN, arrangement) + partner_p = make_source(P) + partner_q = make_source(Q) + job = PipelineJob( + name="stream_transport", database=database or InMemoryArrowDatabase() + ) + with job: + joined = main.join(partner_p, label="joined") + mapped = joined.map_data({"p1": "p1_renamed"}, label="mapped") + no_nulls = mapped.drop_nulls(["d2"], label="no_nulls") + no_nulls.select_data_columns(["d1", "p1_renamed"], label="after_no_nulls") + main.group_by(["t1"], label="grouped").select_data_columns( + ["d1"], label="after_grouped" + ) + main.select_data_columns(["d1"]).batch(batch_size=2, label="batched") + tagged = main.add_tags(k=1, label="tagged") + twice = doubled.pod(tagged.select_data_columns(["d1"]), label="doubled") + noted_stream: Any = noted + noted_stream(twice, label="noted") + main.semi_join(partner_q, label="semi").select_data_columns( + ["d3"], label="after_semi" + ) + MergeJoin()( + main.select_data_columns(["d1"]), + partner_p.map_data({"p1": "d1"}).select_data_columns(["d1"]), + ).select_data_columns(["d1"], label="after_merged") + Rejoin()( + main.select_data_columns(["d1"]), main.select_data_columns(["d3"]) + ).select_data_columns(["d1"], label="after_rejoined") + main.polars_filter(d1=999, label="nothing").select_data_columns( + ["d1"], label="after_nothing" + ) + return job + + +def _identity(stream: Any) -> tuple[Any, ...]: + return ( + type(stream), + stream.producer, + tuple(id(u) for u in stream.upstreams), + stream.pipeline_hash(), + stream.content_hash(), + stream.keys(), + stream.output_schema(), + stream.data_context_key, + ) + + +def assert_same_stream(got: Any, expected: Any) -> None: + """Equal identity, and equal tables byte for byte (every column group).""" + assert _identity(got) == _identity(expected) + got_table = got.as_table(columns=ALL_COLUMNS).combine_chunks() + expected_table = expected.as_table(columns=ALL_COLUMNS).combine_chunks() + assert got_table.schema.equals(expected_table.schema, check_metadata=True) + assert got_table.equals(expected_table, check_metadata=True) + + +def _rebuilt(rows: list[Any], node: Any) -> Any: + return StaticOutputOperatorPod._materialize_upstream(rows, node) # pyright: ignore[reportPrivateUsage] # the path before stage 2 + + +@pytest.fixture +def outputs(monkeypatch: pytest.MonkeyPatch) -> Iterator[dict[str, Any]]: + """Wrap every node kind's ``execute``; check each output against the row path.""" + seen: dict[str, Any] = {} + + source_execute = SourceNodeBase.execute + + def source(self: Any, **kwargs: Any) -> Any: + out = source_execute(self, **kwargs) + assert_same_stream(out, _rebuilt(list(self.iter_data()), self)) # L2 + seen[self.label] = out + return out + + operator_execute = OperatorJobNode.execute + + def operator(self: Any, *inputs: Any, **kwargs: Any) -> Any: + cached = self.get_cached_output() + if cached is not None: + rows = list(cached.iter_data()) + else: + rows = list(self._operator.process(*inputs).iter_data()) # pyright: ignore[reportPrivateUsage] # the operator's own result, as before stage 2 + out = operator_execute(self, *inputs, **kwargs) + assert_same_stream(out, _rebuilt(rows, self)) # L1 + seen[self.label] = out + return out + + def by_construction(original: Any) -> Any: + def execute(self: Any, *args: Any, **kwargs: Any) -> Any: + out = original(self, *args, **kwargs) + assert_same_stream(out, _rebuilt(list(out.iter_data()), self)) # L0 + seen[self.label] = out + return out + + return execute + + monkeypatch.setattr(SourceNodeBase, "execute", source) + monkeypatch.setattr(OperatorJobNode, "execute", operator) + monkeypatch.setattr( + FunctionJobNode, "execute", by_construction(FunctionJobNode.execute) + ) + monkeypatch.setattr( + SideEffectJobNode, "execute", by_construction(SideEffectJobNode.execute) + ) + yield seen + + +def _run(job: Any) -> None: + with warnings.catch_warnings(): + warnings.simplefilter("ignore", ProvisionalHashWarning) + job.run() + + +@pytest.mark.parametrize("arrangement", arrangements(MAIN), ids=lambda a: a.id) +def test_every_output_stream_equals_the_row_rebuild( + arrangement: Arrangement, outputs: dict[str, Any] +) -> None: + with warnings.catch_warnings(): + warnings.simplefilter("ignore", ProvisionalHashWarning) + job = build_job(arrangement) + _run(job) + assert {"joined", "nothing", "doubled", "noted", "semi", "batched"} <= set(outputs) + + +def test_a_replayed_operator_output_equals_the_row_rebuild( + outputs: dict[str, Any], +) -> None: + """REPLAY hands on the stored rows' stream, equal to the one built from them.""" + store = InMemoryArrowDatabase() + with warnings.catch_warnings(): + warnings.simplefilter("ignore", ProvisionalHashWarning) + job = build_job(arrangements(MAIN)[0], store) + node = job.nodes["joined"] + node.attach_databases( + pipeline_database=store.at("replay"), cache_mode=CacheMode.LOG + ) + _run(job) + node.attach_databases( + pipeline_database=store.at("replay"), cache_mode=CacheMode.REPLAY + ) + node.clear_cache() + outputs.clear() + _run(job) + assert "joined" in outputs + + +def test_a_held_node_hands_on_the_stream_built_from_its_rows( + outputs: dict[str, Any], +) -> None: + """L5: a second run holds every node but one; held streams feed it as before.""" + with warnings.catch_warnings(): + warnings.simplefilter("ignore", ProvisionalHashWarning) + job = build_job(arrangements(MAIN)[0]) + _run(job) + job.nodes["noted"].clear_cache() + outputs.clear() + _run(job) + # Only the cleared side effect ran; its input came from the held function node. + assert set(outputs) == {"noted"} + + +def _without_exceptions(schema: pa.Schema) -> dict[str, tuple[Any, bool, Any]]: + """Fields by name as (type, nullable, metadata), the spec's two exceptions applied. + + A source-info field's flag is decided by a table's tokens (stated nullable), and a + ``null`` column is ``large_string`` in rows (ITL-1319). Columns are matched by name: + the declared (zero-row) form can list them in another order than the rows do (a + data-tag's source info, an operator's tags under another layout), as on ``main``, + and column order is not a result (developer, 2026-11-22). + """ + fields: dict[str, tuple[Any, bool, Any]] = {} + for field in schema: + kind = pa.large_string() if pa.types.is_null(field.type) else field.type + nullable = ( + True if field.name.startswith(constants.SOURCE_PREFIX) else field.nullable + ) + fields[field.name] = (kind, nullable, field.metadata) + return fields + + +@pytest.mark.parametrize("arrangement", arrangements(MAIN)[::4], ids=lambda a: a.id) +def test_declared_arrow_schema_equals_the_output( + arrangement: Arrangement, outputs: dict[str, Any] +) -> None: + """L7: ``arrow_schema()`` of every node equals the schema of its output stream.""" + with warnings.catch_warnings(): + warnings.simplefilter("ignore", ProvisionalHashWarning) + job = build_job(arrangement) + _run(job) + for label, stream in outputs.items(): + node = job.nodes[label] + output = stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS) + assert _without_exceptions(node.arrow_schema()) == _without_exceptions( + output.schema + ), label + assert node.arrow_types_declared, label From 303902ad1862ce89686a1fd64941389dea90fd72 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 02:41:56 -0800 Subject: [PATCH 03/36] perf(pipeline): F takes the stream's keys and flags system tags by value (ITL-1360) The row-built form F now equals the table built from rows in two more ways: source info follows the data keys (a data-tag's first, in tag order), and every system-tag field, like every source-info field, is nullable only when a value is null; no schema metadata is kept. F is split into the row-by-row steps (_row_built_columns, for a channel's record batches) and the whole-table flags (_flag_by_values). _output_stream takes the keys. A test checks F against the rows over the whole async-sync matrix. Tests that called the removed SyncPipelineOrchestrator._materialize_as_stream call StaticOutputOperatorPod._materialize_upstream; test observers take the protocol's signatures. Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/nodes/operator_node.py | 10 +- src/orcapod/core/nodes/source_node.py | 5 +- .../core/operators/static_output_pod.py | 119 +++++++++++++--- .../nodes/test_function_node_iteration.py | 8 +- .../operators/test_materialize_source_info.py | 27 +++- .../operators/test_row_built_form.py | 130 ++++++++++++++++++ .../test_error_policy_continue.py | 3 +- tests/test_pipeline/test_node_protocols.py | 48 +++---- tests/test_pipeline/test_sync_orchestrator.py | 7 +- .../test_system_tag_run_stability.py | 10 +- 10 files changed, 298 insertions(+), 69 deletions(-) create mode 100644 tests/test_core/operators/test_row_built_form.py diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index ae33d7716..34b600658 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -1690,8 +1690,7 @@ def execute( if cached_output is not None: output = StaticOutputOperatorPod._output_stream( cached_output.as_table(columns=ZERO_ROW_INPUT_COLUMNS), - cached_output.keys()[0], - stream_data_tags(cached_output), + cached_output.keys(), self, ) ctx_obs.on_node_end(node_label, node_hash) @@ -1703,14 +1702,13 @@ def execute( # The result's table, as the table built from its rows would be, without # making the rows (ITL-1347, stage 2). result_table = result_stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS) - tag_keys = result_stream.keys()[0] + keys = result_stream.keys() + tag_keys = keys[0] data_tags = stream_data_tags(result_stream) # Cache, in row order with or without rows (ITL-1131, ITL-1133). if result_table.num_rows: - kept_table = StaticOutputOperatorPod._row_built_form( - result_table, tag_keys - ) + kept_table = StaticOutputOperatorPod._row_built_form(result_table, keys) self._cached_output_stream = ArrowTableStream( kept_table, tag_columns=tag_keys, data_tags=data_tags ) diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index 1688881c8..d403eb081 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -23,7 +23,6 @@ from orcapod.config import OrcapodConfig from orcapod.core.base import TraceableBase from orcapod.core.datagrams import Data, Tag -from orcapod.core.data_tags import stream_data_tags from orcapod.core.operators.drop_nulls import _without_none # pyright: ignore[reportPrivateUsage] # DropNulls' rule for removing None from a type, shared, never copied from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.core.streams.base import ( @@ -1239,9 +1238,7 @@ def execute( # rows' (a slot's own key order can differ from its source's). rows_stream = self._rows_stream() table = rows_stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS) - result = StaticOutputOperatorPod._output_stream( - table, rows_stream.keys()[0], stream_data_tags(rows_stream), self - ) + result = StaticOutputOperatorPod._output_stream(table, rows_stream.keys(), self) if observer is not None: observer.on_node_end(node_label, node_hash) return result diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index 41007dc44..4b8fd9cc8 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -446,37 +446,114 @@ def _kept_output( return StaticOutputOperatorPod._zero_rows_in_row_order(result) @staticmethod - def _row_built_form(table: pa.Table, tag_keys: Sequence[str]) -> pa.Table: + def _row_built_columns( + table: pa.Table, keys: tuple[Sequence[str], Sequence[str]] + ) -> pa.Table: + """Return ``table``'s columns as ``_rows_to_table`` lays out the table's rows. + + Every step of F (``_row_built_form``) that each row decides on its own, so it + gives the same result on a whole table and on each slice of it: + + 1. The columns a row-built table holds: the user tags, the system tags, the data + columns that are not data-tags, and the source info of every data column (a + data-tag's included). ``table`` holds no context, meta or content-hash column + (``ZERO_ROW_INPUT_COLUMNS``). + 2. In row order: user tags in tag order, system tags in table order, then the data + columns and their source info, both in the order of the data keys. A row's + ``Data`` lists its source info in the order of its data keys, data-tags first + in tag order (``Data._ensure_source_info_table``), so a data-tag's source info + comes before the other data columns' even when the data-tag is not the first + column of ``table``. + 3. Normalized to the large types without keeping ``null``: each row's datagram + stores a ``null`` column as ``large_string`` (``Datagram._init_from_table``). + + Whether a system-tag or source-info field is nullable depends on its values over + the complete table (``_flag_by_values``), so it is not decided here. + + Args: + table: A table of user tags, system tags, data and source info. + keys: The tag keys and the data keys of the stream ``table`` belongs to + (``stream.keys()``). + + Returns: + The same arrays, selected and ordered, in their large types. + """ + from orcapod.system_constants import constants + from orcapod.utils import arrow_utils + + tag_keys, data_keys = keys + names = set(table.column_names) + tags = set(tag_keys) + system_tags = [ + n for n in table.column_names if n.startswith(constants.SYSTEM_TAG_PREFIX) + ] + data = [n for n in data_keys if n not in tags] + source_info = [ + f"{constants.SOURCE_PREFIX}{n}" + for n in data_keys + if f"{constants.SOURCE_PREFIX}{n}" in names + ] + return arrow_utils.normalize_table_to_large_types( + table.select([*tag_keys, *system_tags, *data, *source_info]) + ) + + @staticmethod + def _flag_by_values(table: pa.Table) -> pa.Table: + """Flag each system-tag and source-info field nullable only when it holds a null. + + The last step of F (``_row_built_form``), which needs the complete table. A table + built from rows takes its system tags and source-info tokens from each row's + values, so those fields are non-nullable unless a value is missing, whatever + flags the table the rows came from had (a join over inputs tied on pipeline hash + declares its system tags nullable). The table built from rows also carries no + schema metadata (``arrow_utils.hstack_tables``), so none is kept. + + Args: + table: A table of user tags, system tags, data and source info. + + 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) + if field.name.startswith(prefixes) + else field + for i, field in enumerate(table.schema) + ] + # Same arrays, new field flags: no cast, so no value or type can change. + return pa.Table.from_arrays(table.columns, schema=pa.schema(fields)) + + @staticmethod + def _row_built_form( + table: pa.Table, keys: tuple[Sequence[str], Sequence[str]] + ) -> pa.Table: """Return ``table`` as ``_rows_to_table`` builds it from the table's own rows. - F in the ITL-1347 spec: the same table, without making the rows. ``table`` holds - the user tags, system tags, data and source info (``ZERO_ROW_INPUT_COLUMNS``: no - context, meta or content-hash column, and each data-tag once, among the tags). - Each row's datagram normalizes its table to the large types without keeping - ``null`` (``Datagram._init_from_table``), so a ``null`` column becomes - ``large_string``. The columns then go in row order and each source-info field is - flagged nullable only when a token is null (``_as_row_built_table``). The - equality with ``_rows_to_table`` is tested over every operator, source kind and - column role (ITL-1347, L0-L2). + F in the ITL-1347 spec: the same table, without making the rows. The columns, + their order and their types are decided row by row (``_row_built_columns``), the + system-tag and source-info field flags by their values over the whole table + (``_flag_by_values``). The equality with ``_rows_to_table`` is tested over every + operator, source kind and column role (ITL-1347, L0-L2). Args: table: A table of user tags, system tags, data and source info, with rows. - tag_keys: The user tag columns, in order. + keys: The tag keys and the data keys of the stream ``table`` belongs to + (``stream.keys()``). Returns: The table ``_rows_to_table`` would build from its rows. """ - from orcapod.utils import arrow_utils - - return StaticOutputOperatorPod._as_row_built_table( - arrow_utils.normalize_table_to_large_types(table), tag_keys + return StaticOutputOperatorPod._flag_by_values( + StaticOutputOperatorPod._row_built_columns(table, keys) ) @staticmethod def _output_stream( table: pa.Table, - tag_keys: Sequence[str], - data_tags: Sequence[str], + keys: tuple[Sequence[str], Sequence[str]], node: StreamProtocol, ) -> StreamProtocol: """Return the stream a node hands its successors, given the table of its rows. @@ -488,8 +565,7 @@ def _output_stream( Args: table: The node's rows: user tags, system tags, data and source info. - tag_keys: The user tag columns of the rows, in order. - data_tags: The data-tags among ``tag_keys``. + keys: The tag keys and the data keys of the stream the rows come from. node: The node (or stream) whose output this is. Returns: @@ -497,10 +573,11 @@ def _output_stream( """ if table.num_rows == 0: return StaticOutputOperatorPod._materialize_upstream([], node) + tag_keys, data_keys = keys return StaticOutputOperatorPod._as_upstream_stream( - StaticOutputOperatorPod._row_built_form(table, tag_keys), + StaticOutputOperatorPod._row_built_form(table, keys), tag_keys, - data_tags, + data_tag_names(tag_keys, data_keys), node, ) diff --git a/tests/test_core/nodes/test_function_node_iteration.py b/tests/test_core/nodes/test_function_node_iteration.py index 1364f648b..d5b79758e 100644 --- a/tests/test_core/nodes/test_function_node_iteration.py +++ b/tests/test_core/nodes/test_function_node_iteration.py @@ -9,6 +9,8 @@ from unittest.mock import patch +from typing import Any + import pyarrow as pa import pytest @@ -171,8 +173,10 @@ def sometimes_fail(x: int) -> int: from orcapod.pipeline.observer import NoOpObserver class CapturingObserver(NoOpObserver): - def on_data_crash(self, node_label, tag, data, exc): - errors.append(exc) + def on_data_crash( + self, node_label: str, tag: Any, data: Any, error: Exception + ) -> None: + errors.append(error) results = list( node.execute( diff --git a/tests/test_core/operators/test_materialize_source_info.py b/tests/test_core/operators/test_materialize_source_info.py index 190c6ddec..51368151b 100644 --- a/tests/test_core/operators/test_materialize_source_info.py +++ b/tests/test_core/operators/test_materialize_source_info.py @@ -1,7 +1,7 @@ """Every materialized row keeps its own source info (ITL-845). ``StaticOutputOperatorPod._materialize_to_stream`` and -``SyncPipelineOrchestrator._materialize_as_stream`` turn collected (Tag, Data) +``StaticOutputOperatorPod._materialize_upstream`` turn collected (Tag, Data) pairs back into a stream. They used to read row 0's source info and stamp it on every row, so rows from index 1 onward were attributed to row 0. These tests send rows with distinct source-info tokens through every path that materializes @@ -42,7 +42,6 @@ from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod from orcapod.core.sources import ArrowTableSource, DictSource from orcapod.databases import DeltaTableDatabase, InMemoryArrowDatabase -from orcapod.pipeline.sync_orchestrator import SyncPipelineOrchestrator from orcapod.protocols.database_protocols import ArrowDatabaseProtocol from orcapod.protocols.core_protocols import DataProtocol, StreamProtocol, TagProtocol from orcapod.system_constants import constants @@ -136,9 +135,9 @@ def _materialize(rows: Sequence[Row]) -> StreamProtocol: def _materialize_buffer(buf: Sequence[Row], node: Any) -> StreamProtocol: - """Call ``SyncPipelineOrchestrator._materialize_as_stream``, the helper under test.""" + """Call ``StaticOutputOperatorPod._materialize_upstream``, the helper under test.""" # Non-public on purpose: these tests are about this helper itself. - return SyncPipelineOrchestrator._materialize_as_stream(list(buf), node) # pyright: ignore[reportPrivateUsage] + return StaticOutputOperatorPod._materialize_upstream(list(buf), node) # pyright: ignore[reportPrivateUsage] def _broadcast_row_zero(monkeypatch: pytest.MonkeyPatch) -> None: @@ -155,9 +154,29 @@ def broadcasting( [(tag, data.with_source_info(**row_zero)) for tag, data in rows] ) + original_form = StaticOutputOperatorPod._row_built_form # pyright: ignore[reportPrivateUsage] + + def broadcasting_form( + table: pa.Table, keys: tuple[Sequence[str], Sequence[str]] + ) -> pa.Table: + """Stamp row 0's source info on every row of the row-built form (ITL-1347).""" + formed = original_form(table, keys) + for i, name in enumerate(formed.column_names): + if name.startswith(constants.SOURCE_PREFIX): + column = formed.column(i) + first = column.slice(0, 1).combine_chunks() + repeated = pa.concat_arrays([first] * formed.num_rows) + formed = formed.set_column(i, formed.schema.field(i), repeated) + return formed + monkeypatch.setattr( StaticOutputOperatorPod, "_rows_to_table", staticmethod(broadcasting) ) + # An operator node keeps the row-built form of its result's table, without + # making the rows (ITL-1347, stage 2). + monkeypatch.setattr( + StaticOutputOperatorPod, "_row_built_form", staticmethod(broadcasting_form) + ) def _stored_source(node: OperatorJobNode, column: str = "x") -> list[Any]: diff --git a/tests/test_core/operators/test_row_built_form.py b/tests/test_core/operators/test_row_built_form.py new file mode 100644 index 000000000..69ad9fca0 --- /dev/null +++ b/tests/test_core/operators/test_row_built_form.py @@ -0,0 +1,130 @@ +"""F, the row-built form of a table, equals the table built from its rows (ITL-1347, L0). + +``StaticOutputOperatorPod._row_built_form`` (F in the spec, +``docs/dev/specs/itl-1347-job-table-transport.md``) gives a node's output table as +``_rows_to_table`` (R) builds it from the node's rows, without making the rows. Every +operator, column role and arrangement of the async-sync matrix is checked: the column +names and their order, every field (type, nullability, field metadata), the schema +metadata, and every value (floats by their bits). + +Two properties each case covers by construction: + +- A data-tag's source info comes first among the source info, in tag order, whatever + its column's place in the table (``source_mid``, ``tag_by``): a row lists its source + info in the order of its data keys. +- A system-tag field is nullable only when a value is null: a join over inputs tied on + pipeline hash (``ref_join_3_tied``) declares its system tags nullable, a table built + from rows does not. +""" + +from __future__ import annotations + +from typing import Any + +import pyarrow as pa +import pyarrow.compute as pc +import pytest + +from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod +from orcapod.core.streams.base import ZERO_ROW_INPUT_COLUMNS +from tests.test_core.operators.test_async_sync_equivalence import ( + AFTER_OPERATOR_CASES, + CASES, + FUNCTION_POD_CASES, + Case, +) + + +_FLOAT_BITS = {16: pa.uint16(), 32: pa.uint32(), 64: pa.uint64()} + + +def _as_bits(array: Any) -> Any: # pyright: ignore[reportExplicitAny] # any Arrow array kind + """``array``'s values, with every float, at any depth, as its bit pattern. + + Arrow's ``equals`` holds NaN unequal to itself, so floats are compared as unsigned + integers of their width. Lists and structs are taken apart into their validity, their + lengths and their children's values, so the physical layout (a list's first offset, + the bytes behind a null) does not count. + """ + kind = array.type + if isinstance(array, pa.ExtensionArray): + return ("extension", _as_bits(array.storage)) + if pa.types.is_floating(kind): + filled = pc.if_else(pc.is_null(array), pa.scalar(0, kind), array) + return ("float", array.is_null(), filled.view(_FLOAT_BITS[kind.bit_width])) + if pa.types.is_map(kind): + return ( + "map", + array.is_null(), + pc.list_value_length(array), + _as_bits(array.keys), + _as_bits(array.items), + ) + if ( + pa.types.is_list(kind) + or pa.types.is_large_list(kind) + or pa.types.is_fixed_size_list(kind) + ): + return ( + "list", + array.is_null(), + pc.list_value_length(array), + _as_bits(array.flatten()), + ) + if pa.types.is_struct(kind): + return ( + "struct", + array.is_null(), + tuple(_as_bits(child) for child in array.flatten()), + ) + return ("value", array) + + +def assert_same_values(formed: pa.Table, built: pa.Table) -> None: + """Every column of ``formed`` holds the values of ``built``, floats by their bits. + + The physical layout (a list's first offset, the bytes behind a null) is not a + value and may differ. + """ + for name in built.column_names: + expected, got = built.column(name), formed.column(name) + assert got.type == expected.type, name + assert _as_bits(got.combine_chunks()) == _as_bits(expected.combine_chunks()), ( + name + ) + + +def _all_cases() -> list[Any]: + cases: list[Any] = [pytest.param(c, id=c.label) for c in CASES] + cases += list(AFTER_OPERATOR_CASES) + cases += [pytest.param(c, id=f"fp-{c.label}") for c in FUNCTION_POD_CASES] + return cases + + +@pytest.mark.parametrize("case", _all_cases()) +def test_row_built_form_equals_the_table_built_from_rows(case: Case) -> None: + """F of an operator's result table equals R of its rows, field and bit for bit.""" + result = case.make_op()(*case.make_sources()) + rows = list(result.iter_data()) + if not rows: + pytest.skip("no rows: F is defined on a table with rows") + built, _, _ = StaticOutputOperatorPod._rows_to_table(rows) # pyright: ignore[reportPrivateUsage] # R, the oracle + formed = StaticOutputOperatorPod._row_built_form( # pyright: ignore[reportPrivateUsage] # F, under test + result.as_table(columns=ZERO_ROW_INPUT_COLUMNS), result.keys() + ) + assert formed.column_names == built.column_names + assert formed.schema.equals(built.schema, check_metadata=True) + assert_same_values(formed, built) + + +def test_row_built_columns_is_the_same_on_every_slice() -> None: + """The row-by-row steps of F give the same columns on a slice as on the whole.""" + case = next(c for c in CASES if c.label == "ref_join_3_tied") + result = case.make_op()(*case.make_sources()) + table = result.as_table(columns=ZERO_ROW_INPUT_COLUMNS) + keys = result.keys() + whole = StaticOutputOperatorPod._row_built_columns(table, keys) # pyright: ignore[reportPrivateUsage] # under test + for start in range(table.num_rows): + part = StaticOutputOperatorPod._row_built_columns(table.slice(start, 1), keys) # pyright: ignore[reportPrivateUsage] # under test + assert part.schema.equals(whole.schema, check_metadata=True) + assert part.equals(whole.slice(start, 1)) diff --git a/tests/test_pipeline/test_error_policy_continue.py b/tests/test_pipeline/test_error_policy_continue.py index 31ad95450..88e99241c 100644 --- a/tests/test_pipeline/test_error_policy_continue.py +++ b/tests/test_pipeline/test_error_policy_continue.py @@ -14,6 +14,7 @@ from orcapod.core.sources import ArrowTableSource from orcapod.databases import InMemoryArrowDatabase from orcapod.pipeline.job import PipelineJob +from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod from orcapod.pipeline.sync_orchestrator import SyncPipelineOrchestrator @@ -80,7 +81,7 @@ def identity(value: int) -> int: # Don't run — buffer will be empty node = job.nodes["fn"] - stream = SyncPipelineOrchestrator._materialize_as_stream([], node) + stream = StaticOutputOperatorPod._materialize_upstream([], node) tag_schema, data_schema = stream.output_schema() # "result" is declared as int (required), must NOT become int | None diff --git a/tests/test_pipeline/test_node_protocols.py b/tests/test_pipeline/test_node_protocols.py index b59428341..23482ce18 100644 --- a/tests/test_pipeline/test_node_protocols.py +++ b/tests/test_pipeline/test_node_protocols.py @@ -3,6 +3,8 @@ from __future__ import annotations +from typing import Any + import pytest from unittest.mock import MagicMock @@ -15,6 +17,7 @@ is_operator_node, ) import pyarrow as pa +from orcapod.pipeline.observer import NoOpObserver from orcapod.core.sources import ArrowTableSource from orcapod.core.nodes.source_node import SourceJobNode from orcapod.channels import Channel @@ -312,30 +315,31 @@ def test_execute_with_observer(self): node = self._make_function_node() events = [] - class Obs: - def contextualize(self, *identity_path): + class Obs(NoOpObserver): + def contextualize(self, *identity_path: str) -> Obs: return self - def on_node_start(self, node_label, node_hash, **kwargs): + def on_node_start( + self, node_label: str, node_hash: str, tag_schema: Any = None + ) -> None: events.append(("node_start", node_label)) - def on_node_end(self, node_label, node_hash, **kwargs): + def on_node_end(self, node_label: str, node_hash: str) -> None: events.append(("node_end", node_label)) - def on_data_start(self, node_label, t, p): + def on_data_start(self, node_label: str, tag: Any, data: Any) -> None: events.append(("data_start",)) - def on_data_end(self, node_label, t, ip, op, cached): + def on_data_end( + self, + node_label: str, + tag: Any, + input_data: Any, + output_data: Any, + cached: bool, + ) -> None: events.append(("data_end", cached)) - def on_data_crash(self, node_label, t, p, exc): - pass - - def create_data_logger(self, t, p, **kwargs): - from orcapod.pipeline.observer import _NOOP_LOGGER - - return _NOOP_LOGGER - input_stream = node._input_stream result = list(node.execute(input_stream, observer=Obs()).iter_data()) @@ -472,22 +476,18 @@ def test_execute_with_observer(self): node = self._make_join_node() events = [] - class Obs: - def contextualize(self, *identity_path): + class Obs(NoOpObserver): + def contextualize(self, *identity_path: str) -> Obs: return self - def on_node_start(self, node_label, node_hash, **kwargs): + def on_node_start( + self, node_label: str, node_hash: str, tag_schema: Any = None + ) -> None: events.append(("node_start", node_label)) - def on_node_end(self, node_label, node_hash, **kwargs): + def on_node_end(self, node_label: str, node_hash: str) -> None: events.append(("node_end", node_label)) - def on_data_start(self, node_label, t, p): - pass - - def on_data_end(self, node_label, t, ip, op, cached): - pass - result = list(node.execute(*node._input_streams, observer=Obs()).iter_data()) assert len(result) == 2 assert events[0][0] == "node_start" diff --git a/tests/test_pipeline/test_sync_orchestrator.py b/tests/test_pipeline/test_sync_orchestrator.py index 4f334c709..ffd2c7907 100644 --- a/tests/test_pipeline/test_sync_orchestrator.py +++ b/tests/test_pipeline/test_sync_orchestrator.py @@ -12,6 +12,7 @@ from orcapod.core.sources import ArrowTableSource from orcapod.databases import InMemoryArrowDatabase from orcapod.pipeline import AsyncPipelineOrchestrator +from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod from orcapod.pipeline.sync_orchestrator import SyncPipelineOrchestrator from orcapod.pipeline.job import PipelineJob @@ -337,7 +338,7 @@ def test_materialized_stream_has_same_pipeline_hash(self): ) buf = list(node.iter_data()) - stream = SyncPipelineOrchestrator._materialize_as_stream(buf, node) + stream = StaticOutputOperatorPod._materialize_upstream(buf, node) assert stream.pipeline_hash() == node.pipeline_hash() def test_materialized_stream_has_same_content_hash(self): @@ -356,7 +357,7 @@ def test_materialized_stream_has_same_content_hash(self): op_node.run() buf = list(op_node.iter_data()) - stream = SyncPipelineOrchestrator._materialize_as_stream(buf, op_node) + stream = StaticOutputOperatorPod._materialize_upstream(buf, op_node) assert stream.content_hash() == op_node.content_hash() def test_materialized_stream_preserves_system_tags(self): @@ -371,7 +372,7 @@ def test_materialized_stream_preserves_system_tags(self): op_node.run() buf = list(op_node.iter_data()) - stream = SyncPipelineOrchestrator._materialize_as_stream(buf, op_node) + stream = StaticOutputOperatorPod._materialize_upstream(buf, op_node) expected_tag_schema = op_node.output_schema(columns={"system_tags": True})[0] actual_tag_schema = stream.output_schema(columns={"system_tags": True})[0] diff --git a/tests/test_pipeline/test_system_tag_run_stability.py b/tests/test_pipeline/test_system_tag_run_stability.py index 48c50565c..19a757caf 100644 --- a/tests/test_pipeline/test_system_tag_run_stability.py +++ b/tests/test_pipeline/test_system_tag_run_stability.py @@ -27,7 +27,6 @@ from orcapod.core.sources.arrow_table_source import ArrowTableSource from orcapod.databases import DeltaTableDatabase from orcapod.pipeline.job import PipelineJob -from orcapod.pipeline.sync_orchestrator import SyncPipelineOrchestrator from orcapod.side_effects import SideEffectPod, sink_pod Key = tuple[tuple[str, Any], ...] @@ -148,8 +147,8 @@ def test_operator_materialize_to_stream(self) -> None: rows = stream.as_table().to_pylist() assert rows == [{"a": 1, "b": 2, "v": 10}, {"a": 3, "b": 4, "v": 20}] - def test_orchestrator_materialize_as_stream(self) -> None: - """The orchestrator materializer emits rows in the first row's column order.""" + def test_materialize_upstream_keeps_first_row_column_order(self) -> None: + """The upstream materializer emits rows in the first row's column order.""" rows = _rows_with_swapped_tag_order() # The rebuilt stream takes the upstream's data context (ITL-1080) and, for an # upstream with no producer, its pipeline hash (ITL-1094): here a plain @@ -162,7 +161,10 @@ def test_orchestrator_materialize_as_stream(self) -> None: rows ).pipeline_hash, ) - stream = SyncPipelineOrchestrator._materialize_as_stream(rows, upstream) + stream = StaticOutputOperatorPod._materialize_upstream( + rows, + upstream, # pyright: ignore[reportArgumentType] # a stand-in upstream: the attributes the materializer reads + ) rows = stream.as_table().to_pylist() assert rows == [{"a": 1, "b": 2, "v": 10}, {"a": 3, "b": 4, "v": 20}] From 840267db0a35ff8e7a954e579ac56b11803bf17c Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 02:44:21 -0800 Subject: [PATCH 04/36] perf(pipeline): arrow_schema() lists F's columns in F's order (ITL-1360) arrow_schema() takes the columns and order of the row-built form from one statement (_row_built_names): source info in data-key order, a data-tag's first. System-tag fields, like source-info fields, are stated nullable: a table decides their flags from its values. A source node gives its rows' tag and data keys (_row_keys). Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/nodes/source_node.py | 33 +++++++++------ .../core/operators/static_output_pod.py | 40 ++++++++++++++----- src/orcapod/core/streams/base.py | 29 ++++++++------ .../protocols/core_protocols/streams.py | 13 +++--- .../test_stream_transport_equivalence.py | 27 +++++++------ 5 files changed, 88 insertions(+), 54 deletions(-) diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index d403eb081..7c999a49d 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -23,6 +23,7 @@ from orcapod.config import OrcapodConfig from orcapod.core.base import TraceableBase from orcapod.core.datagrams import Data, Tag +from orcapod.core.data_tags import data_tag_names from orcapod.core.operators.drop_nulls import _without_none # pyright: ignore[reportPrivateUsage] # DropNulls' rule for removing None from a type, shared, never copied from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.core.streams.base import ( @@ -1194,13 +1195,13 @@ def arrow_schema(self) -> pa.Schema: """The Arrow schema of the columns this stream passes between job nodes. See ``stream_arrow_schema`` (ITL-1347): never reads, computes or polls a row. - The user tags are in the order of the node's rows (``_row_tag_keys``). + The columns are in the order of the node's rows (``_row_keys``). """ - return stream_arrow_schema(self, self._row_tag_keys()) + return stream_arrow_schema(self, self._row_keys()) - def _row_tag_keys(self) -> tuple[str, ...]: - """The order of the user tags in this node's rows: its own key order.""" - return self.keys()[0] + def _row_keys(self) -> tuple[tuple[str, ...], tuple[str, ...]]: + """The tag and data keys of this node's rows: its own keys.""" + return self.keys() @property def arrow_types_declared(self) -> bool: @@ -1700,17 +1701,23 @@ def identity_structure(self) -> Any: return self._bound_source.identity_structure() return super().identity_structure() - def _row_tag_keys(self) -> tuple[str, ...]: - """The order of the user tags in this node's rows, known without reading a row. + def _row_keys(self) -> tuple[tuple[str, ...], tuple[str, ...]]: + """The tag and data keys of this node's rows, known without reading a row. - The bound source's key order; the declared order for a narrower source given - as the declared schema (``_DeclaredForm``); the slot's own when unbound. + The bound source's keys; for a narrower source given as the declared schema + (``_DeclaredForm``), the declared order with the data-tags first among the data + keys, as the stream over its table lists them (``_declared_stream``); the slot's + own when unbound. """ if self._bound_source is None: - return self.keys()[0] - if self._declared_form is not None: - return self._declared_form.tag_order - return self._bound_source.keys()[0] + return self.keys() + form = self._declared_form + if form is not None: + data_tags = data_tag_names(form.tag_order, form.data_order) + others = tuple(n for n in form.data_order if n not in data_tags) + return form.tag_order, (*data_tags, *others) + tag_keys, data_keys = self._bound_source.keys() + return tuple(tag_keys), tuple(data_keys) def _rows_stream(self) -> StreamProtocol: """The stream whose rows are this node's rows (``iter_data``). diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index 4b8fd9cc8..0e70690f3 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -478,24 +478,46 @@ def _row_built_columns( Returns: The same arrays, selected and ordered, in their large types. """ - from orcapod.system_constants import constants from orcapod.utils import arrow_utils + return arrow_utils.normalize_table_to_large_types( + table.select( + StaticOutputOperatorPod._row_built_names(table.column_names, keys) + ) + ) + + @staticmethod + def _row_built_names( + names: Sequence[str], keys: tuple[Sequence[str], Sequence[str]] + ) -> list[str]: + """Return the columns of a table built from rows, in row order (F steps 1-2). + + The user tags in tag order, the system tags in the order of ``names``, the data + columns that are not data-tags, then the source info of every data column; data + and source info in the order of the data keys (a row's ``Data`` lists its source + info so, data-tags first in tag order: ``Data._ensure_source_info_table``). + + Args: + names: The column names of a table of user tags, system tags, data and + source info. + keys: The tag keys and the data keys of the stream the table belongs to. + + Returns: + The names a table built from rows holds, in its order. + """ + from orcapod.system_constants import constants + tag_keys, data_keys = keys - names = set(table.column_names) + present = set(names) tags = set(tag_keys) - system_tags = [ - n for n in table.column_names if n.startswith(constants.SYSTEM_TAG_PREFIX) - ] + system_tags = [n for n in names if n.startswith(constants.SYSTEM_TAG_PREFIX)] data = [n for n in data_keys if n not in tags] source_info = [ f"{constants.SOURCE_PREFIX}{n}" for n in data_keys - if f"{constants.SOURCE_PREFIX}{n}" in names + if f"{constants.SOURCE_PREFIX}{n}" in present ] - return arrow_utils.normalize_table_to_large_types( - table.select([*tag_keys, *system_tags, *data, *source_info]) - ) + return [*tag_keys, *system_tags, *data, *source_info] @staticmethod def _flag_by_values(table: pa.Table) -> pa.Table: diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py index e8dbb149b..54bbaee86 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -185,25 +185,26 @@ def typed_zero_row_input(stream: object) -> pa.Table | None: def stream_arrow_schema( - stream: object, tag_keys: Sequence[str] | None = None + stream: object, keys: tuple[Sequence[str], Sequence[str]] | None = None ) -> pa.Schema: """Return ``stream``'s declared Arrow schema: what ``arrow_schema()`` answers (ITL-1347). The schema of the columns a job node passes on, without reading, computing or polling a row: the stream's zero-row input (``typed_zero_row_input``, the Arrow types - its rows have) in row order (user tags, system tags, data, source info; - ``StaticOutputOperatorPod._in_row_order``), with no context and no meta column. A + its rows have) with the columns of F, in F's order + (``StaticOutputOperatorPod._row_built_names``: user tags, system tags, data, source + info, data and source info in data-key order), with no context and no meta column. A stream that cannot type itself without rows answers with its Python schema converted by its data context (``arrow_types_declared`` is then false). Each - source-info field is stated nullable: a table decides its flag from its tokens. A - ``null`` column keeps the zero-row ``null`` type; rows carry ``large_string`` - (ITL-1319). ITL-1307 later reads it from ``Schema`` instead, here. + system-tag and source-info field is stated nullable: a table decides its flag from + its values (F's last step). A ``null`` column keeps the zero-row ``null`` type; rows + carry ``large_string`` (ITL-1319). ITL-1307 later reads it from ``Schema`` instead, + here. Args: stream: The stream, source or node. - tag_keys: The order of the user tags in the stream's rows, when it differs from - ``keys()`` (a source slot gives its bound source's rows); default - ``keys()``. + keys: The tag and data keys of the stream's rows, when they differ from + ``keys()`` (a source slot gives its bound source's rows); default ``keys()``. Returns: The declared Arrow schema. @@ -212,8 +213,8 @@ def stream_arrow_schema( from orcapod.system_constants import constants typed = cast(StreamProtocol, stream) - if tag_keys is None: - tag_keys = typed.keys()[0] + if keys is None: + keys = typed.keys() table = typed_zero_row_input(stream) if table is None: tag_schema, data_schema = typed.output_schema( @@ -221,9 +222,11 @@ def stream_arrow_schema( ) converter = StaticOutputOperatorPod._upstream_context(typed).type_converter # pyright: ignore[reportPrivateUsage] # the one place that resolves an upstream's context table = arrow_utils.make_empty_table({**tag_schema, **data_schema}, converter) - schema = StaticOutputOperatorPod._in_row_order(table, tag_keys).schema # pyright: ignore[reportPrivateUsage] # the one statement of the row order + names = StaticOutputOperatorPod._row_built_names(table.column_names, keys) # pyright: ignore[reportPrivateUsage] # the one statement of F's columns + schema = table.select(names).schema + prefixes = (constants.SYSTEM_TAG_PREFIX, constants.SOURCE_PREFIX) for index, field in enumerate(schema): - if field.name.startswith(constants.SOURCE_PREFIX): + if field.name.startswith(prefixes): schema = schema.set(index, field.with_nullable(True)) # pyright: ignore[reportUnknownMemberType] # stubs leave Field unparametrized return schema diff --git a/src/orcapod/protocols/core_protocols/streams.py b/src/orcapod/protocols/core_protocols/streams.py index 1ebc044f8..5dff04d96 100644 --- a/src/orcapod/protocols/core_protocols/streams.py +++ b/src/orcapod/protocols/core_protocols/streams.py @@ -175,12 +175,13 @@ def arrow_schema(self) -> "pa.Schema": """The Arrow schema of the columns the stream passes between job nodes. The user tags, system tags, data and source-info columns, in row order (user - tags, system tags, data, source info), with the Arrow types, nullability and - field metadata of the rows; no context and no meta column (ITL-1347). Known - without reading, computing or polling a row. Two exceptions keep today's - bytes: source-info fields are stated nullable (a table decides their flags - from its tokens), and a ``null`` column keeps the ``null`` type a zero-row table - has (rows carry ``large_string``; ITL-1319). + tags, system tags, data, source info; data and source info in data-key order), + with the Arrow types, nullability and field metadata of the rows; no context and + no meta column (ITL-1347). Known without reading, computing or polling a row. + Two exceptions keep today's bytes: system-tag and source-info fields are stated + nullable (a table decides their flags from its values), and a ``null`` column + keeps the ``null`` type a zero-row table has (rows carry ``large_string``; + ITL-1319). Returns: The declared Arrow schema. diff --git a/tests/test_pipeline/test_stream_transport_equivalence.py b/tests/test_pipeline/test_stream_transport_equivalence.py index a6965a366..77e6c6491 100644 --- a/tests/test_pipeline/test_stream_transport_equivalence.py +++ b/tests/test_pipeline/test_stream_transport_equivalence.py @@ -233,22 +233,23 @@ def test_a_held_node_hands_on_the_stream_built_from_its_rows( def _without_exceptions(schema: pa.Schema) -> dict[str, tuple[Any, bool, Any]]: - """Fields by name as (type, nullable, metadata), the spec's two exceptions applied. + """Fields by name as (type, nullable, metadata), the spec's exceptions applied. - A source-info field's flag is decided by a table's tokens (stated nullable), and a - ``null`` column is ``large_string`` in rows (ITL-1319). Columns are matched by name: - the declared (zero-row) form can list them in another order than the rows do (a - data-tag's source info, an operator's tags under another layout), as on ``main``, - and column order is not a result (developer, 2026-11-22). + A system-tag or source-info field's flag is decided by a table's values (stated + nullable), and a ``null`` column is ``large_string`` in rows (ITL-1319). Columns are + matched by name: an operator node's declared tag order can differ from its rows' + under another physical layout, as on ``main``, and column order is not a result + (developer, 2026-11-22). """ - fields: dict[str, tuple[Any, bool, Any]] = {} - for field in schema: - kind = pa.large_string() if pa.types.is_null(field.type) else field.type - nullable = ( - True if field.name.startswith(constants.SOURCE_PREFIX) else field.nullable + prefixes = (constants.SYSTEM_TAG_PREFIX, constants.SOURCE_PREFIX) + return { + field.name: ( + pa.large_string() if pa.types.is_null(field.type) else field.type, + True if field.name.startswith(prefixes) else field.nullable, + field.metadata, ) - fields[field.name] = (kind, nullable, field.metadata) - return fields + for field in schema + } @pytest.mark.parametrize("arrangement", arrangements(MAIN)[::4], ids=lambda a: a.id) From e8d5851771ed6fae1b4d128e0ba23d56938cdcc6 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 02:44:45 -0800 Subject: [PATCH 05/36] docs(changelog): ITL-1360 fragment Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1360.md | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 changelog.d/ITL-1360.md diff --git a/changelog.d/ITL-1360.md b/changelog.d/ITL-1360.md new file mode 100644 index 000000000..5e6886038 --- /dev/null +++ b/changelog.d/ITL-1360.md @@ -0,0 +1,26 @@ +### Changed + +- **A job node's `execute` returns its output stream** — `execute` of a source, operator, + function and side-effect job node (and of the node protocols) returned the node's rows as + a list of (tag, data) pairs, and the sync orchestrator rebuilt a table from them for each + successor. It now returns the node's output stream, which the sync orchestrator hands to + every successor as it is: a source node gives its source's Arrow table, and an operator + node its result's table (REPLAY: its stored table), each in the form a table built from + the rows has, without making the rows. `OrchestratorResult.node_outputs` holds each + node's output stream, and a held node gives the stream of its held rows. Every + successor's input is unchanged: columns, types, row order, system tags, source info, + pipeline and content hashes. No hash, stored table or output changes. This replaces the + rows that carried their table (`RowsWithTable`) of the first stage. Second stage of the + table transport between job nodes (`docs/dev/specs/itl-1347-job-table-transport.md`). + (ITL-1360) + +### Added + +- **`arrow_schema()` and `arrow_types_declared` on every stream** — `StreamProtocol`, + every stream and every source node state the Arrow schema of the columns a job node + passes on (user tags, system tags, data and source info, in row order), without reading, + computing or polling a row. System-tag and source-info fields are stated nullable, since + a table decides their flags from its values; a `null` column keeps the `null` type of a + table with no rows. `arrow_types_declared` is false only for a stream that cannot type + itself without rows (an unbound slot, a `PollingSource` not yet polled), whose schema is + converted from its Python schema. (ITL-1360) From ab0bd08ba1e882d5ee709fc874efc42ecf171376 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 02:46:16 -0800 Subject: [PATCH 06/36] test(pipeline): L7 for a loaded job (ITL-1360) Co-Authored-By: Claude Opus 5.5 --- .../test_stream_transport_equivalence.py | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/tests/test_pipeline/test_stream_transport_equivalence.py b/tests/test_pipeline/test_stream_transport_equivalence.py index 77e6c6491..68f608d1c 100644 --- a/tests/test_pipeline/test_stream_transport_equivalence.py +++ b/tests/test_pipeline/test_stream_transport_equivalence.py @@ -22,8 +22,11 @@ from __future__ import annotations +import subprocess +import sys import warnings from collections.abc import Iterator +from pathlib import Path from typing import Any import pyarrow as pa @@ -268,3 +271,50 @@ def test_declared_arrow_schema_equals_the_output( output.schema ), label assert node.arrow_types_declared, label + + +def test_a_loaded_job_describes_its_nodes( + tmp_path: Path, outputs: dict[str, Any] +) -> None: + """L7 for a loaded job: each loaded node's ``arrow_schema()`` equals its output. + + A loaded node describes itself from the Arrow type texts its saved file holds + (ITL-640). The job is run and saved in another process, so that the loaded job + holds no run of this process. + """ + script = ( + "import sys, warnings\n" + "from pathlib import Path\n" + "from orcapod.databases import DeltaTableDatabase\n" + "from tests.test_core.operators.several_items import MAIN, arrangements\n" + "from tests.test_pipeline.test_stream_transport_equivalence import build_job\n" + "warnings.simplefilter('ignore')\n" + "root = Path(sys.argv[1])\n" + "job = build_job(arrangements(MAIN)[0], DeltaTableDatabase(root / 'store'))\n" + "job.run()\n" + "job.save(root / 'job.json')\n" + ) + repository = Path(__file__).resolve().parents[2] + subprocess.run( + [sys.executable, "-c", script, str(tmp_path)], check=True, cwd=repository + ) + with warnings.catch_warnings(): + warnings.simplefilter("ignore", ProvisionalHashWarning) + loaded = PipelineJob.load(tmp_path / "job.json") + # In-memory sources are not saved: bind them again. + loaded.bind( + sources={ + "s": make_source(MAIN, arrangements(MAIN)[0]), + "p": make_source(P), + "q": make_source(Q), + } + ) + loaded.run(load_only=True) + assert {"joined", "doubled", "noted", "semi", "batched"} <= set(outputs) + for label, stream in outputs.items(): + node = loaded.nodes[label] + output = stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS) + assert _without_exceptions(node.arrow_schema()) == _without_exceptions( + output.schema + ), label + assert node.arrow_types_declared, label From 3ab16e543f10c28e475dbc6525b221e742fd092e Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 02:52:50 -0800 Subject: [PATCH 07/36] refactor(streams): F's per-slice step as module functions of streams.base (ITL-1360) row_built_names and row_built_columns move, unchanged, from StaticOutputOperatorPod to core/streams/base.py, so a stream applies them without importing the operators. StaticOutputOperatorPod and stream_arrow_schema call them. Co-Authored-By: Claude Opus 5.5 --- .../core/operators/static_output_pod.py | 81 +------------------ src/orcapod/core/streams/base.py | 78 +++++++++++++++++- .../operators/test_row_built_form.py | 6 +- 3 files changed, 81 insertions(+), 84 deletions(-) diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index 0e70690f3..c46ec8786 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -33,6 +33,7 @@ short_stream_repr, typed_zero_row_input, typed_zero_row_table, + row_built_columns, ) from orcapod.core.streams.view import ( STALE_NOTE, @@ -445,80 +446,6 @@ def _kept_output( return StaticOutputOperatorPod._materialize_to_stream(rows) return StaticOutputOperatorPod._zero_rows_in_row_order(result) - @staticmethod - def _row_built_columns( - table: pa.Table, keys: tuple[Sequence[str], Sequence[str]] - ) -> pa.Table: - """Return ``table``'s columns as ``_rows_to_table`` lays out the table's rows. - - Every step of F (``_row_built_form``) that each row decides on its own, so it - gives the same result on a whole table and on each slice of it: - - 1. The columns a row-built table holds: the user tags, the system tags, the data - columns that are not data-tags, and the source info of every data column (a - data-tag's included). ``table`` holds no context, meta or content-hash column - (``ZERO_ROW_INPUT_COLUMNS``). - 2. In row order: user tags in tag order, system tags in table order, then the data - columns and their source info, both in the order of the data keys. A row's - ``Data`` lists its source info in the order of its data keys, data-tags first - in tag order (``Data._ensure_source_info_table``), so a data-tag's source info - comes before the other data columns' even when the data-tag is not the first - column of ``table``. - 3. Normalized to the large types without keeping ``null``: each row's datagram - stores a ``null`` column as ``large_string`` (``Datagram._init_from_table``). - - Whether a system-tag or source-info field is nullable depends on its values over - the complete table (``_flag_by_values``), so it is not decided here. - - Args: - table: A table of user tags, system tags, data and source info. - keys: The tag keys and the data keys of the stream ``table`` belongs to - (``stream.keys()``). - - Returns: - The same arrays, selected and ordered, in their large types. - """ - from orcapod.utils import arrow_utils - - return arrow_utils.normalize_table_to_large_types( - table.select( - StaticOutputOperatorPod._row_built_names(table.column_names, keys) - ) - ) - - @staticmethod - def _row_built_names( - names: Sequence[str], keys: tuple[Sequence[str], Sequence[str]] - ) -> list[str]: - """Return the columns of a table built from rows, in row order (F steps 1-2). - - The user tags in tag order, the system tags in the order of ``names``, the data - columns that are not data-tags, then the source info of every data column; data - and source info in the order of the data keys (a row's ``Data`` lists its source - info so, data-tags first in tag order: ``Data._ensure_source_info_table``). - - Args: - names: The column names of a table of user tags, system tags, data and - source info. - keys: The tag keys and the data keys of the stream the table belongs to. - - Returns: - The names a table built from rows holds, in its order. - """ - from orcapod.system_constants import constants - - tag_keys, data_keys = keys - present = set(names) - tags = set(tag_keys) - system_tags = [n for n in names if n.startswith(constants.SYSTEM_TAG_PREFIX)] - data = [n for n in data_keys if n not in tags] - source_info = [ - f"{constants.SOURCE_PREFIX}{n}" - for n in data_keys - if f"{constants.SOURCE_PREFIX}{n}" in present - ] - return [*tag_keys, *system_tags, *data, *source_info] - @staticmethod def _flag_by_values(table: pa.Table) -> pa.Table: """Flag each system-tag and source-info field nullable only when it holds a null. @@ -555,7 +482,7 @@ def _row_built_form( """Return ``table`` as ``_rows_to_table`` builds it from the table's own rows. F in the ITL-1347 spec: the same table, without making the rows. The columns, - their order and their types are decided row by row (``_row_built_columns``), the + their order and their types are decided row by row (``streams.base.row_built_columns``), the system-tag and source-info field flags by their values over the whole table (``_flag_by_values``). The equality with ``_rows_to_table`` is tested over every operator, source kind and column role (ITL-1347, L0-L2). @@ -568,9 +495,7 @@ def _row_built_form( Returns: The table ``_rows_to_table`` would build from its rows. """ - return StaticOutputOperatorPod._flag_by_values( - StaticOutputOperatorPod._row_built_columns(table, keys) - ) + return StaticOutputOperatorPod._flag_by_values(row_built_columns(table, keys)) @staticmethod def _output_stream( diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py index 54bbaee86..d97faf142 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -34,6 +34,7 @@ StreamProtocol, TagProtocol, ) +from orcapod.system_constants import constants from orcapod.types import ColumnConfig, Schema from orcapod.utils import arrow_utils @@ -184,6 +185,78 @@ def typed_zero_row_input(stream: object) -> pa.Table | None: ) +def row_built_columns( + table: pa.Table, keys: tuple[Sequence[str], Sequence[str]] +) -> pa.Table: + """Return ``table``'s columns as a table built from its rows lays them out. + + Every step of F (``StaticOutputOperatorPod._row_built_form``) that each row decides on its own, so it + gives the same result on a whole table and on each slice of it: + + 1. The columns a row-built table holds: the user tags, the system tags, the data + columns that are not data-tags, and the source info of every data column (a + data-tag's included). ``table`` holds no context, meta or content-hash column + (``ZERO_ROW_INPUT_COLUMNS``). + 2. In row order: user tags in tag order, system tags in table order, then the data + columns and their source info, both in the order of the data keys. A row's + ``Data`` lists its source info in the order of its data keys, data-tags first + in tag order (``Data._ensure_source_info_table``), so a data-tag's source info + comes before the other data columns' even when the data-tag is not the first + column of ``table``. + 3. Normalized to the large types without keeping ``null``: each row's datagram + stores a ``null`` column as ``large_string`` (``Datagram._init_from_table``). + + Whether a system-tag or source-info field is nullable depends on its values over + the complete table (``StaticOutputOperatorPod._flag_by_values``), so it is not decided here. + + Args: + table: A table of user tags, system tags, data and source info. + keys: The tag keys and the data keys of the stream ``table`` belongs to + (``stream.keys()``). + + Returns: + The same arrays, selected and ordered, in their large types. + """ + return arrow_utils.normalize_table_to_large_types( + table.select(row_built_names(table.column_names, keys)) + ) + + +def row_built_names( + names: Sequence[str], keys: tuple[Sequence[str], Sequence[str]] +) -> list[str]: + """Return the columns of a table built from rows, in row order (F steps 1-2). + + The table built from rows is ``StaticOutputOperatorPod._rows_to_table``'s; this and + ``row_built_columns`` are module functions so that a stream applies them without + importing the operators (ITL-1347). + + The user tags in tag order, the system tags in the order of ``names``, the data + columns that are not data-tags, then the source info of every data column; data + and source info in the order of the data keys (a row's ``Data`` lists its source + info so, data-tags first in tag order: ``Data._ensure_source_info_table``). + + Args: + names: The column names of a table of user tags, system tags, data and + source info. + keys: The tag keys and the data keys of the stream the table belongs to. + + Returns: + The names a table built from rows holds, in its order. + """ + tag_keys, data_keys = keys + present = set(names) + tags = set(tag_keys) + system_tags = [n for n in names if n.startswith(constants.SYSTEM_TAG_PREFIX)] + data = [n for n in data_keys if n not in tags] + source_info = [ + f"{constants.SOURCE_PREFIX}{n}" + for n in data_keys + if f"{constants.SOURCE_PREFIX}{n}" in present + ] + return [*tag_keys, *system_tags, *data, *source_info] + + def stream_arrow_schema( stream: object, keys: tuple[Sequence[str], Sequence[str]] | None = None ) -> pa.Schema: @@ -192,7 +265,7 @@ def stream_arrow_schema( The schema of the columns a job node passes on, without reading, computing or polling a row: the stream's zero-row input (``typed_zero_row_input``, the Arrow types its rows have) with the columns of F, in F's order - (``StaticOutputOperatorPod._row_built_names``: user tags, system tags, data, source + (``row_built_names``: user tags, system tags, data, source info, data and source info in data-key order), with no context and no meta column. A stream that cannot type itself without rows answers with its Python schema converted by its data context (``arrow_types_declared`` is then false). Each @@ -210,7 +283,6 @@ def stream_arrow_schema( The declared Arrow schema. """ from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod - from orcapod.system_constants import constants typed = cast(StreamProtocol, stream) if keys is None: @@ -222,7 +294,7 @@ def stream_arrow_schema( ) converter = StaticOutputOperatorPod._upstream_context(typed).type_converter # pyright: ignore[reportPrivateUsage] # the one place that resolves an upstream's context table = arrow_utils.make_empty_table({**tag_schema, **data_schema}, converter) - names = StaticOutputOperatorPod._row_built_names(table.column_names, keys) # pyright: ignore[reportPrivateUsage] # the one statement of F's columns + names = row_built_names(table.column_names, keys) schema = table.select(names).schema prefixes = (constants.SYSTEM_TAG_PREFIX, constants.SOURCE_PREFIX) for index, field in enumerate(schema): diff --git a/tests/test_core/operators/test_row_built_form.py b/tests/test_core/operators/test_row_built_form.py index 69ad9fca0..b421bd843 100644 --- a/tests/test_core/operators/test_row_built_form.py +++ b/tests/test_core/operators/test_row_built_form.py @@ -26,7 +26,7 @@ import pytest from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod -from orcapod.core.streams.base import ZERO_ROW_INPUT_COLUMNS +from orcapod.core.streams.base import ZERO_ROW_INPUT_COLUMNS, row_built_columns from tests.test_core.operators.test_async_sync_equivalence import ( AFTER_OPERATOR_CASES, CASES, @@ -123,8 +123,8 @@ def test_row_built_columns_is_the_same_on_every_slice() -> None: result = case.make_op()(*case.make_sources()) table = result.as_table(columns=ZERO_ROW_INPUT_COLUMNS) keys = result.keys() - whole = StaticOutputOperatorPod._row_built_columns(table, keys) # pyright: ignore[reportPrivateUsage] # under test + whole = row_built_columns(table, keys) for start in range(table.num_rows): - part = StaticOutputOperatorPod._row_built_columns(table.slice(start, 1), keys) # pyright: ignore[reportPrivateUsage] # under test + part = row_built_columns(table.slice(start, 1), keys) assert part.schema.equals(whole.schema, check_metadata=True) assert part.equals(whole.slice(start, 1)) From a425c84fb562e5365ce862fa929810fbf0de4d20 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 03:05:23 -0800 Subject: [PATCH 08/36] fix(pipeline): F equals the rows for narrower sources and raw streams (ITL-1360) A narrower source's output is F of its table given as the declared schema (_DeclaredForm.apply), with the declared keys: its data-tags keep their source info, as each declared row does. F leaves meta (__) columns and their source info out, and gives system-tag and source-info fields the form a row builds from their values (row_built_provenance: no field metadata; a source-info list of nullable 'item' fields), so F equals the rows on raw streams too (Codex on PR #483, findings 5 and 7). arrow_schema() states the same fields. The pre-ITL-845 test hook is defined once, and patches F as well. Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/nodes/source_node.py | 48 +++++------ src/orcapod/core/streams/base.py | 85 +++++++++++++++++-- .../operators/test_row_built_form.py | 63 ++++++++++++++ .../test_tag_table_source_info.py | 23 +---- 4 files changed, 169 insertions(+), 50 deletions(-) diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index 7c999a49d..7644f1703 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -1187,9 +1187,15 @@ def iter_data(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: """Yield ``(tag, data)`` pairs, or raise if data is unavailable.""" ... - def _rows_stream(self) -> "StreamProtocol": - """The stream whose rows are this node's rows (``iter_data``): this node itself.""" - return cast("StreamProtocol", self) + def _rows_table(self) -> tuple[pa.Table, tuple[tuple[str, ...], tuple[str, ...]]]: + """The table of this node's rows (``iter_data``) and the rows' keys. + + Here this node's own table (``ZERO_ROW_INPUT_COLUMNS``) and keys. + """ + stream = cast("StreamProtocol", self) + tag_keys, data_keys = stream.keys() + table = stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS) + return table, (tuple(tag_keys), tuple(data_keys)) def arrow_schema(self) -> pa.Schema: """The Arrow schema of the columns this stream passes between job nodes. @@ -1235,11 +1241,10 @@ def execute( node_hash = self.content_hash().to_string() if observer is not None: observer.on_node_start(node_label, node_hash) - # The stream this node's rows come from: its table and its tag order are the - # rows' (a slot's own key order can differ from its source's). - rows_stream = self._rows_stream() - table = rows_stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS) - result = StaticOutputOperatorPod._output_stream(table, rows_stream.keys(), self) + # The table and keys of this node's rows: a slot's own key order can differ + # from its source's. + table, keys = self._rows_table() + result = StaticOutputOperatorPod._output_stream(table, keys, self) if observer is not None: observer.on_node_end(node_label, node_hash) return result @@ -1719,12 +1724,14 @@ def _row_keys(self) -> tuple[tuple[str, ...], tuple[str, ...]]: tag_keys, data_keys = self._bound_source.keys() return tuple(tag_keys), tuple(data_keys) - def _rows_stream(self) -> StreamProtocol: - """The stream whose rows are this node's rows (``iter_data``). + def _rows_table(self) -> tuple[pa.Table, tuple[tuple[str, ...], tuple[str, ...]]]: + """The table of this node's rows (``iter_data``) and the rows' keys. - The bound source, or, for a narrower source, the source's table given as the - declared schema (``_declared_stream``), whose rows are those ``_declared_rows`` - gives one by one. + The bound source's table and keys; for a narrower source, the source's table + given as the declared schema (``_DeclaredForm.apply``, which serves a whole + table as it serves each row in ``_declared_rows``) with the declared keys + (``_row_keys``). Its data-tags keep their source info, as each declared row + does. Raises: UnboundSourceError: When no concrete source is attached. @@ -1734,18 +1741,11 @@ def _rows_stream(self) -> StreamProtocol: f"SourceJobNode '{self._name}' has no concrete source bound. " "Call job.bind(sources={'': source}) before running." ) + table = self._bound_source.as_table(columns=ZERO_ROW_INPUT_COLUMNS) if self._declared_form is None: - return self._bound_source - table = self._bound_source.as_table( - columns={ - "meta": True, - "source": True, - "system_tags": True, - "context": True, - "sort_by_tags": False, - } - ) - return self._declared_stream(self._bound_source, self._declared_form, table) + tag_keys, data_keys = self._bound_source.keys() + return table, (tuple(tag_keys), tuple(data_keys)) + return self._declared_form.apply(table), self._row_keys() def iter_data(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: """Delegate to concrete source, or raise if unbound. diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py index d97faf142..3610e05ac 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -205,9 +205,13 @@ def row_built_columns( column of ``table``. 3. Normalized to the large types without keeping ``null``: each row's datagram stores a ``null`` column as ``large_string`` (``Datagram._init_from_table``). + 4. The system-tag and source-info fields as a row builds them from its values + (``row_built_provenance``): no field metadata, and a source-info list of the + form its tokens give. Whether a system-tag or source-info field is nullable depends on its values over - the complete table (``StaticOutputOperatorPod._flag_by_values``), so it is not decided here. + the complete table (``StaticOutputOperatorPod._flag_by_values``), so it is not + decided here. Args: table: A table of user tags, system tags, data and source info. @@ -215,10 +219,75 @@ def row_built_columns( (``stream.keys()``). Returns: - The same arrays, selected and ordered, in their large types. + The same values, selected and ordered, in their large types. """ - return arrow_utils.normalize_table_to_large_types( - table.select(row_built_names(table.column_names, keys)) + return row_built_provenance( + arrow_utils.normalize_table_to_large_types( + table.select(row_built_names(table.column_names, keys)) + ) + ) + + +def _source_info_value_type(kind: pa.DataType) -> pa.DataType: + """The Arrow type a row gives a source-info column of type ``kind``. + + A row's ``Data`` types its tokens from their Python values + (``arrow_utils.source_info_arrow_type``): a string as ``large_string``, a list as + ``large_list`` of its element's type, with the item field named ``item`` and + nullable. A type of any other kind is left as it is. + """ + if ( + pa.types.is_list(kind) + or pa.types.is_large_list(kind) + or pa.types.is_fixed_size_list(kind) + ): + return pa.large_list(_source_info_value_type(kind.value_type)) # pyright: ignore[reportAttributeAccessIssue, reportUnknownArgumentType, reportUnknownMemberType] # a list type has a value type + if ( + pa.types.is_string(kind) + or pa.types.is_large_string(kind) + or pa.types.is_null(kind) + ): + return pa.large_string() + return kind + + +def row_built_provenance(table: pa.Table) -> pa.Table: + """Give ``table``'s system-tag and source-info fields the form a row builds. + + A row rebuilds its system tags and its source info from their values, so their + fields carry no field metadata, and a source-info column has the type its tokens + give (``_source_info_value_type``): a list's item field named ``item`` and + nullable at every depth. The values are unchanged: a type that differs only in + its item fields is cast. The fields' nullability is left as it is + (``StaticOutputOperatorPod._flag_by_values`` decides it). Other fields are not + touched. + + Args: + table: A table of user tags, system tags, data and source info. + + Returns: + The same values under the rebuilt fields. + """ + fields: list[pa.Field[pa.DataType]] = [] + columns: list[Any] = [] + changed = False + for field, column in zip(table.schema, table.columns, strict=True): + if field.name.startswith(constants.SOURCE_PREFIX): + kind = _source_info_value_type(field.type) + if kind != field.type: + column = column.cast(kind) + new_field = pa.field(field.name, kind, nullable=field.nullable) + elif field.name.startswith(constants.SYSTEM_TAG_PREFIX): + new_field = field.remove_metadata() + else: + new_field = field + changed = changed or not new_field.equals(field, check_metadata=True) + fields.append(new_field) + columns.append(column) + if not changed: + return table + return pa.Table.from_arrays( + columns, schema=pa.schema(fields, table.schema.metadata) ) @@ -232,7 +301,8 @@ def row_built_names( importing the operators (ITL-1347). The user tags in tag order, the system tags in the order of ``names``, the data - columns that are not data-tags, then the source info of every data column; data + columns that are not data-tags or meta columns, then the source info of every + such data column and data-tag; data and source info in the order of the data keys (a row's ``Data`` lists its source info so, data-tags first in tag order: ``Data._ensure_source_info_table``). @@ -248,6 +318,9 @@ def row_built_names( present = set(names) tags = set(tag_keys) system_tags = [n for n in names if n.startswith(constants.SYSTEM_TAG_PREFIX)] + # A meta (``__``) column is never data: a row's ``Data`` holds it apart, and no + # node passes it on (ITL-1080). + data_keys = [n for n in data_keys if not n.startswith(constants.META_PREFIX)] data = [n for n in data_keys if n not in tags] source_info = [ f"{constants.SOURCE_PREFIX}{n}" @@ -295,7 +368,7 @@ def stream_arrow_schema( converter = StaticOutputOperatorPod._upstream_context(typed).type_converter # pyright: ignore[reportPrivateUsage] # the one place that resolves an upstream's context table = arrow_utils.make_empty_table({**tag_schema, **data_schema}, converter) names = row_built_names(table.column_names, keys) - schema = table.select(names).schema + schema = row_built_provenance(table.select(names)).schema prefixes = (constants.SYSTEM_TAG_PREFIX, constants.SOURCE_PREFIX) for index, field in enumerate(schema): if field.name.startswith(prefixes): diff --git a/tests/test_core/operators/test_row_built_form.py b/tests/test_core/operators/test_row_built_form.py index b421bd843..2c6cc5e9a 100644 --- a/tests/test_core/operators/test_row_built_form.py +++ b/tests/test_core/operators/test_row_built_form.py @@ -25,8 +25,11 @@ import pyarrow.compute as pc import pytest +from orcapod.core.operators import DropNulls, SelectDataColumns from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod +from orcapod.core.streams import ArrowTableStream from orcapod.core.streams.base import ZERO_ROW_INPUT_COLUMNS, row_built_columns +from orcapod.system_constants import constants from tests.test_core.operators.test_async_sync_equivalence import ( AFTER_OPERATOR_CASES, CASES, @@ -128,3 +131,63 @@ def test_row_built_columns_is_the_same_on_every_slice() -> None: part = row_built_columns(table.slice(start, 1), keys) assert part.schema.equals(whole.schema, check_metadata=True) assert part.equals(whole.slice(start, 1)) + + +def _raw_stream() -> ArrowTableStream: + """A raw stream with provenance fields no source writes (Codex on PR #483). + + A system-tag field with field metadata, a list-valued source-info column whose item + field is named ``member`` and non-nullable, and a meta (``__``) data column with + its own source info. + """ + system_tag = f"{constants.SYSTEM_TAG_PREFIX}source_id::abc" + member = pa.field("member", pa.large_string(), nullable=False) + table = pa.table( + { + "k": pa.array([1, 2], pa.int64()), + "j": pa.array(["a", "b"], pa.large_string()), + system_tag: pa.array(["s1", "s2"], pa.large_string()), + "x": pa.array([1.0, float("nan")]), + "z": pa.array([3, None], pa.int8()), + "__note": pa.array(["a", "b"]), + "_source_x": pa.array([["a", "b"], ["c"]], pa.large_list(member)), + "_source_z": pa.array(["t1", "t2"], pa.large_string()), + "_source___note": pa.array(["n1", "n2"], pa.large_string()), + } + ) + position = table.schema.get_field_index(system_tag) + schema = table.schema.set( + position, table.schema.field(position).with_metadata({b"m": b"v"}) + ) + return ArrowTableStream( + pa.Table.from_arrays(table.columns, schema=schema), tag_columns=["k", "j"] + ) + + +@pytest.mark.parametrize( + "make", + [ + pytest.param(_raw_stream, id="raw"), + pytest.param( + lambda: SelectDataColumns(["z", "x"])(_raw_stream()), id="select-z-x" + ), + pytest.param(lambda: DropNulls(["j", "k"])(_raw_stream()), id="drop-nulls"), + ], +) +def test_row_built_form_of_a_raw_stream(make: Any) -> None: + """F equals R on a raw stream: provenance fields as rows build them, no meta. + + R takes a system tag and a source-info token from its values, so the system-tag + field has no metadata and a list token's item field is nullable ``item``; a meta + column is not data, so neither it nor its source info is passed on. + """ + stream = make() + built, _, _ = StaticOutputOperatorPod._rows_to_table(list(stream.iter_data())) # pyright: ignore[reportPrivateUsage] # R, the oracle + formed = StaticOutputOperatorPod._row_built_form( # pyright: ignore[reportPrivateUsage] # F, under test + stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS), stream.keys() + ) + assert "__note" not in formed.column_names + assert "_source___note" not in formed.column_names + assert formed.column_names == built.column_names + assert formed.schema.equals(built.schema, check_metadata=True) + assert_same_values(formed, built) diff --git a/tests/test_pipeline/test_tag_table_source_info.py b/tests/test_pipeline/test_tag_table_source_info.py index 094b66702..048b4d47d 100644 --- a/tests/test_pipeline/test_tag_table_source_info.py +++ b/tests/test_pipeline/test_tag_table_source_info.py @@ -32,12 +32,13 @@ from orcapod.core.function_pod import FunctionPod from orcapod.core.nodes.function_node import FunctionJobNode from orcapod.core.operators import SelectDataColumns -from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod +from tests.test_core.operators.test_materialize_source_info import ( + _broadcast_row_zero, # pyright: ignore[reportPrivateUsage] # the one re-creation of the pre-fix broadcast +) from orcapod.core.sources import ArrowTableSource from orcapod.databases import DeltaTableDatabase, InMemoryArrowDatabase from orcapod.pipeline import AsyncPipelineOrchestrator from orcapod.pipeline.job import PipelineJob -from orcapod.protocols.core_protocols import DataProtocol, TagProtocol from orcapod.protocols.database_protocols import ArrowDatabaseProtocol from orcapod.system_constants import PIPELINE_DB_SCHEMA_VERSION @@ -160,24 +161,6 @@ def _output_source_info_tokens(job: PipelineJob, label: str, column: str) -> lis return [data.source_info()[column] for _, data in rows] -def _broadcast_row_zero(monkeypatch: pytest.MonkeyPatch) -> None: - """Make every materialization stamp row 0's source info, as before ITL-845.""" - original = StaticOutputOperatorPod._rows_to_table # pyright: ignore[reportPrivateUsage] # re-creating the pre-fix behaviour - - def broadcasting( - rows: Sequence[tuple[TagProtocol, DataProtocol]], - ) -> tuple[pa.Table, tuple[str, ...], tuple[str, ...]]: - """Stamp row 0's source info on every row, then build the table.""" - row_zero = rows[0][1].source_info() - return original( - [(tag, data.with_source_info(**row_zero)) for tag, data in rows] - ) - - monkeypatch.setattr( - StaticOutputOperatorPod, "_rows_to_table", staticmethod(broadcasting) - ) - - @pytest.mark.parametrize("orchestrator", ["sync", "async"]) class TestFreshRunStoresPerRowSourceInfo: def test_source_into_function(self, orchestrator: str): From f06846308aa92a195fd403813a04ba3ec38997c9 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 03:06:16 -0800 Subject: [PATCH 09/36] fix(side_effects): cast the node to StreamProtocol through object (ITL-1360) Co-Authored-By: Claude Opus 5.5 --- src/orcapod/side_effects.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/orcapod/side_effects.py b/src/orcapod/side_effects.py index 95f4c922e..81a834fc2 100644 --- a/src/orcapod/side_effects.py +++ b/src/orcapod/side_effects.py @@ -1278,8 +1278,12 @@ def _output_stream( """ from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod + # A side-effect job node is a stream (``StreamBase``) that the checker cannot + # match against the protocol through its mixins. + # A side-effect job node is a ``StreamBase``; the checker cannot match its + # mixin members against ``StreamProtocol``, so the cast goes through object. return StaticOutputOperatorPod._materialize_upstream( - rows, cast("StreamProtocol", self) + rows, cast("StreamProtocol", cast(object, self)) ) def _deliver_rows( From 5b39d5bb50d26d1209033d04ccbb53a7870811c6 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 03:14:56 -0800 Subject: [PATCH 10/36] fix(function_node): a type disagreement fails the run with as_table's error (ITL-1360) A function node builds its output stream before its run commits. Rows that cannot make one table (rows of a store written before ITL-928 next to rows computed now) fail the run at the node with the InputValidationError its as_table() raises, naming the column and both types, never a bare ArrowInvalid. Named difference e9 in the spec (provisional, coordinator decision 2026-11-22, pending the developer). Stage 1's changelog text is folded into the ITL-1360 fragment: one fragment for the PR that carries both stages. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1347.md | 11 -------- changelog.d/ITL-1360.md | 14 +++++++--- .../dev/specs/itl-1347-job-table-transport.md | 7 +++-- src/orcapod/core/nodes/function_node.py | 18 ++++++++++-- .../test_function_node_arrow_types.py | 28 +++++++++++++++---- 5 files changed, 53 insertions(+), 25 deletions(-) delete mode 100644 changelog.d/ITL-1347.md diff --git a/changelog.d/ITL-1347.md b/changelog.d/ITL-1347.md deleted file mode 100644 index 1396fe682..000000000 --- a/changelog.d/ITL-1347.md +++ /dev/null @@ -1,11 +0,0 @@ -### Changed - -- **A job run hands an operator node's kept table to the nodes after it** — an operator node - in a job keeps its run's output as a table built from its rows, and the sync orchestrator - then built the same table again from the same rows for each node that reads it. The node - now returns its rows carrying the table it built (`RowsWithTable`), and the orchestrator - wraps that table for each successor (`_materialize_upstream`). The table is built once - instead of once per successor plus once to keep. Every successor's input is the same: - columns, types, row order, system tags, source info, pipeline and content hashes. No hash, - stored table or output changes. First stage of the table transport between job nodes - (`docs/dev/specs/itl-1347-job-table-transport.md`). (ITL-1347) diff --git a/changelog.d/ITL-1360.md b/changelog.d/ITL-1360.md index 5e6886038..0d7f58069 100644 --- a/changelog.d/ITL-1360.md +++ b/changelog.d/ITL-1360.md @@ -9,10 +9,16 @@ the rows has, without making the rows. `OrchestratorResult.node_outputs` holds each node's output stream, and a held node gives the stream of its held rows. Every successor's input is unchanged: columns, types, row order, system tags, source info, - pipeline and content hashes. No hash, stored table or output changes. This replaces the - rows that carried their table (`RowsWithTable`) of the first stage. Second stage of the - table transport between job nodes (`docs/dev/specs/itl-1347-job-table-transport.md`). - (ITL-1360) + pipeline and content hashes. No hash, stored table or output changes. An operator node's + table is built once, for what it keeps and for every successor, instead of once to keep + and once per successor. The first two stages of the table transport between job nodes + (`docs/dev/specs/itl-1347-job-table-transport.md`). (ITL-1347, ITL-1360) +- **A function node whose rows disagree on a column's type fails the run** — rows read from + a store written before ITL-928 (a `uint32` tag read back as `int32`) and rows computed now + cannot make one table. The run now fails at the node with the `InputValidationError` + naming the column and both types that the node's `as_table()` raised before; a node with a + successor used to fail with a bare `ArrowInvalid`, and one without completed the run. Such + a store must be rebuilt. (ITL-1360) ### Added diff --git a/docs/dev/specs/itl-1347-job-table-transport.md b/docs/dev/specs/itl-1347-job-table-transport.md index ce0097d17..c517ae50f 100644 --- a/docs/dev/specs/itl-1347-job-table-transport.md +++ b/docs/dev/specs/itl-1347-job-table-transport.md @@ -509,9 +509,9 @@ with the developer's approval, given row by row. Each row gets its own test: it row, by name. The developer has accepted some behaviours of `main` that are not listed as rows; they are kept as `main` has them, and documented below. -**No row changes a sync-path result.** On the sync path the branch equals `main` byte for -byte. Stages 1–4 hold this by construction and by L0–L5, and a lemma that fails stops its -stage. +**No row changes a sync-path result, except e9** (provisional, pending the developer). On +the sync path the branch equals `main` byte for byte. Stages 1–4 hold this by construction +and by L0–L5, and a lemma that fails stops its stage. | # | What differs | On `main` today | On the branch | Why `main` is wrong (bug, reproducer) | Approval needed | |---|---|---|---|---|---| @@ -521,6 +521,7 @@ stage. | e6 | Async values that depend on an earlier validation of the same operator object | `SemiJoin._validated_common_keys` and `Index._element_arrow_type_fallback` hold the last validation's values (ITL-858, section 1.2). One operator object applied to two streams can use the other stream's keys or fallback type | Read from each input's description, with no state | The ITL-858 finding; filed as ITL-1358. Reproducer: one `SemiJoin` instance validated on stream B, then run async over stream A with other keys. To be confirmed in stage 5 | ITL-1358 (filed); fixed with stage 5 once a reproducer confirms it | | e7 | What a consumer does after its producer failed (async, failure path) | The producer closes its output in `finally`, so a consumer sees a normal end and may finish, and a `LOG` operator node may store, a partial result before the task group cancels it | Readers raise `UpstreamFailedError` at the failure point instead of seeing a normal end, so no consumer finishes, or stores its result, as if its input were complete. Batches a consumer processed before the failure are still processed, and a streaming node may already have passed them on or a function node stored results for them, as on `main`; there is no rollback. A barrier operator never computes over a partial input. The run raises the producer's own error, as today | A candidate race, to be confirmed with a reproducer in stage 5: a `fail_fast` function node raising on row 3 of 6, feeding a `Select` node in `LOG` mode; check the operator cache after the failed run. If `main` never stores in practice, this row is no difference | filed by the developer only once a test reproduces it | | e8 | Meta columns of an async side-effect node's rows | An async side-effect node passes on and holds the rows it receives as they are, so a computed row keeps its `__computed` meta column (from the cached function pod), and the node's `as_table(all_info=True)` shows it. On sync, its input is rebuilt from rows (`_rows_to_table` drops meta), so the column is absent | Async drops input meta columns as sync does. With table transport this follows from the transport columns, which hold no meta column | A `main` bug: the async and sync paths give the node different columns. Found by the stage 0 harness on `job-speed` 0e15d0db, which does not change side-effect nodes; the stage 0 differential checks it on pinned `main`. Reproducer: a function node (with a result store) feeding a `tap_pod`, async against sync, comparing the side-effect node's `as_table(all_info=True)` columns | approved (developer, 2026-11-22) | +| e9 | A sync function node whose output rows disagree on a column's Arrow type | A node with no successor completes the run; its `as_table()` raises `InputValidationError` ("Function node 'double': Rows disagree on the Arrow type of column 'k': int32 and uint32"). A node with a successor fails the run with a bare pyarrow `ArrowInvalid`, raised where the successor's input is rebuilt | The node builds its output stream when it runs (stage 2), so the run fails at the node, before it commits, with the `InputValidationError` `as_table()` raises (same type and message), with or without a successor; the node then holds no run. What is stored equals `main`'s: the row computed before the disagreement could be seen stays written, as after any failure | Not a `main` bug to fix: a consequence of building the output stream in `execute`, and for a node with a successor an improvement (`main`'s `ArrowInvalid` names nothing). It arises only from a store written before ITL-928, whose cached rows give a `uint32` tag back as `int32`; such a store must be rebuilt. Reproducer: `tests/test_core/function_pod/test_function_node_arrow_types.py::test_new_rows_over_a_store_written_before_the_fix_raise_naming_the_column` (leaf and with successor) | provisional, coordinator decision 2026-11-22, pending developer | **Resolved: refusals after rows have flowed (was c, question 9).** The developer's `Rejoin` rule (ITL-1355) removes every data-dependent refusal from `Rejoin`: it checks only what its diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 3b2b2e1da..21075cb8f 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -2467,7 +2467,14 @@ def _output_stream( """ from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod - return StaticOutputOperatorPod._materialize_upstream(rows, self) + try: + return StaticOutputOperatorPod._materialize_upstream(rows, self) + except pa.ArrowInvalid: + # Rows that disagree on a column's Arrow type (cached rows of a store + # written before ITL-928): raise what ``as_table`` raises for them, naming + # the node, the column and both types (ITL-1360, e9). + self._table_from_pairs(rows) + raise def execute_data( self, @@ -2649,6 +2656,13 @@ def execute( self._row_processed, ctx_obs, node_label, node_hash ) + # The output stream, built before the run is committed: rows that cannot + # make one table fail the run (ITL-1360, e9). + try: + result_stream = self._output_stream(output) + except InputValidationError: + ctx_obs.on_node_end(node_label, node_hash) + raise self._commit_or_end_node( self._commit_at_node_end, ctx_obs, node_label, node_hash ) @@ -2668,7 +2682,7 @@ def execute( self.clear_cache() raise - return self._output_stream(output) + return result_stream def _empty_data_cache_hit( self, tag: TagProtocol, data: EmptyData, base_entry_id: bytes diff --git a/tests/test_core/function_pod/test_function_node_arrow_types.py b/tests/test_core/function_pod/test_function_node_arrow_types.py index 6886d8715..99e389c77 100644 --- a/tests/test_core/function_pod/test_function_node_arrow_types.py +++ b/tests/test_core/function_pod/test_function_node_arrow_types.py @@ -291,27 +291,45 @@ def _as_written_before_the_fix(root: pathlib.Path) -> None: ) +@pytest.mark.parametrize("chained", [False, True], ids=["leaf", "with_successor"]) def test_new_rows_over_a_store_written_before_the_fix_raise_naming_the_column( - tmp_path: pathlib.Path, + chained: bool, tmp_path: pathlib.Path ) -> None: """Rows of one node never make a column of a type none of them has. A Delta database written before ITL-928 gives a ``uint32`` tag back as ``int32``: rows served from it and rows computed now disagree, and the node says so instead of picking a type. Such a database must be rebuilt. + + The run fails at the node, with the error ``as_table`` raises for such rows (main + raised it only on a later read of a node with no successor, and a bare + ``ArrowInvalid`` in the run of one with a successor; ITL-1360, difference e9). The + node then holds no run. """ - _build(DeltaTableDatabase(tmp_path), _source_table("uint32").slice(0, 2)).run() + _build( + DeltaTableDatabase(tmp_path), + _source_table("uint32").slice(0, 2), + chained=chained, + ).run() _as_written_before_the_fix(tmp_path) - job = _build(DeltaTableDatabase(tmp_path), _source_table("uint32")) - job.run() + job = _build(DeltaTableDatabase(tmp_path), _source_table("uint32"), chained=chained) with pytest.raises(InputValidationError) as raised: - job.nodes["double"].as_table() + job.run() message = str(raised.value) + assert message.startswith("Function node 'double': ") assert "'k'" in message assert "int32" in message assert "uint32" in message + # A run that raised defines no rows. + assert job.nodes["double"].as_table().num_rows == 0 + # What is stored is what main stores: the row computed before the disagreement + # could be seen stays written, as after any failure, next to the two old rows. + stored = _build(DeltaTableDatabase(tmp_path), _source_table("uint32")) + records = stored.nodes["double"].get_all_records() + assert records is not None + assert records.num_rows == 3 def test_new_rows_over_a_store_written_after_the_fix_keep_the_tag_type( From 49a81d6a8c70d803c3f0d319f36b8c72c14611cd Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 03:23:17 -0800 Subject: [PATCH 11/36] fix(streams): type the schema metadata row_built_provenance keeps (ITL-1360) Co-Authored-By: Claude Opus 5.5 --- docs/dev/specs/itl-1347-job-table-transport.md | 2 +- src/orcapod/core/streams/base.py | 5 ++++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/docs/dev/specs/itl-1347-job-table-transport.md b/docs/dev/specs/itl-1347-job-table-transport.md index c517ae50f..af8b392bf 100644 --- a/docs/dev/specs/itl-1347-job-table-transport.md +++ b/docs/dev/specs/itl-1347-job-table-transport.md @@ -521,7 +521,7 @@ and by L0–L5, and a lemma that fails stops its stage. | e6 | Async values that depend on an earlier validation of the same operator object | `SemiJoin._validated_common_keys` and `Index._element_arrow_type_fallback` hold the last validation's values (ITL-858, section 1.2). One operator object applied to two streams can use the other stream's keys or fallback type | Read from each input's description, with no state | The ITL-858 finding; filed as ITL-1358. Reproducer: one `SemiJoin` instance validated on stream B, then run async over stream A with other keys. To be confirmed in stage 5 | ITL-1358 (filed); fixed with stage 5 once a reproducer confirms it | | e7 | What a consumer does after its producer failed (async, failure path) | The producer closes its output in `finally`, so a consumer sees a normal end and may finish, and a `LOG` operator node may store, a partial result before the task group cancels it | Readers raise `UpstreamFailedError` at the failure point instead of seeing a normal end, so no consumer finishes, or stores its result, as if its input were complete. Batches a consumer processed before the failure are still processed, and a streaming node may already have passed them on or a function node stored results for them, as on `main`; there is no rollback. A barrier operator never computes over a partial input. The run raises the producer's own error, as today | A candidate race, to be confirmed with a reproducer in stage 5: a `fail_fast` function node raising on row 3 of 6, feeding a `Select` node in `LOG` mode; check the operator cache after the failed run. If `main` never stores in practice, this row is no difference | filed by the developer only once a test reproduces it | | e8 | Meta columns of an async side-effect node's rows | An async side-effect node passes on and holds the rows it receives as they are, so a computed row keeps its `__computed` meta column (from the cached function pod), and the node's `as_table(all_info=True)` shows it. On sync, its input is rebuilt from rows (`_rows_to_table` drops meta), so the column is absent | Async drops input meta columns as sync does. With table transport this follows from the transport columns, which hold no meta column | A `main` bug: the async and sync paths give the node different columns. Found by the stage 0 harness on `job-speed` 0e15d0db, which does not change side-effect nodes; the stage 0 differential checks it on pinned `main`. Reproducer: a function node (with a result store) feeding a `tap_pod`, async against sync, comparing the side-effect node's `as_table(all_info=True)` columns | approved (developer, 2026-11-22) | -| e9 | A sync function node whose output rows disagree on a column's Arrow type | A node with no successor completes the run; its `as_table()` raises `InputValidationError` ("Function node 'double': Rows disagree on the Arrow type of column 'k': int32 and uint32"). A node with a successor fails the run with a bare pyarrow `ArrowInvalid`, raised where the successor's input is rebuilt | The node builds its output stream when it runs (stage 2), so the run fails at the node, before it commits, with the `InputValidationError` `as_table()` raises (same type and message), with or without a successor; the node then holds no run. What is stored equals `main`'s: the row computed before the disagreement could be seen stays written, as after any failure | Not a `main` bug to fix: a consequence of building the output stream in `execute`, and for a node with a successor an improvement (`main`'s `ArrowInvalid` names nothing). It arises only from a store written before ITL-928, whose cached rows give a `uint32` tag back as `int32`; such a store must be rebuilt. Reproducer: `tests/test_core/function_pod/test_function_node_arrow_types.py::test_new_rows_over_a_store_written_before_the_fix_raise_naming_the_column` (leaf and with successor) | provisional, coordinator decision 2026-11-22, pending developer | +| e9 | A sync function node whose output rows disagree on a column's Arrow type | A node with no successor completes the run; its `as_table()` raises `InputValidationError` ("Function node 'double': Rows disagree on the Arrow type of column 'k': int32 and uint32"). A node with a successor fails the run with a bare pyarrow `ArrowInvalid`, raised where the successor's input is rebuilt | The node builds its output stream when it runs (stage 2), so the run fails at the node, before it commits, with the `InputValidationError` `as_table()` raises (same type and message), with or without a successor; the node then holds no run. What is stored equals `main`'s: the row computed before the disagreement could be seen is stored, as on `main` (2 stored rows before the run, 3 after, on both) | Not a `main` bug to fix: a consequence of building the output stream in `execute`, and for a node with a successor an improvement (`main`'s `ArrowInvalid` names nothing). It arises only from a store written before ITL-928, whose cached rows give a `uint32` tag back as `int32`; such a store must be rebuilt. Reproducer: `tests/test_core/function_pod/test_function_node_arrow_types.py::test_new_rows_over_a_store_written_before_the_fix_raise_naming_the_column` (leaf and with successor) | provisional, coordinator decision 2026-11-22, pending developer | **Resolved: refusals after rows have flowed (was c, question 9).** The developer's `Rejoin` rule (ITL-1355) removes every data-dependent refusal from `Rejoin`: it checks only what its diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py index b7a68d0f4..38ade1cb1 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -287,7 +287,10 @@ def row_built_provenance(table: pa.Table) -> pa.Table: if not changed: return table return pa.Table.from_arrays( - columns, schema=pa.schema(fields, table.schema.metadata) + columns, + schema=pa.schema( + fields, cast("dict[bytes | str, bytes | str] | None", table.schema.metadata) + ), ) From fbf8aff26cf487532300d3957b5d4861ee41a97a Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 03:35:43 -0800 Subject: [PATCH 12/36] fix(function_node): a failed write is reported before e9 (ITL-1360) The output stream is built after the run's writes are committed, so a store write error keeps precedence as on main. Co-Authored-By: Claude Opus 5.5 --- docs/dev/specs/itl-1347-job-table-transport.md | 2 +- src/orcapod/core/nodes/function_node.py | 11 ++++++----- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/docs/dev/specs/itl-1347-job-table-transport.md b/docs/dev/specs/itl-1347-job-table-transport.md index af8b392bf..08d27f4ba 100644 --- a/docs/dev/specs/itl-1347-job-table-transport.md +++ b/docs/dev/specs/itl-1347-job-table-transport.md @@ -521,7 +521,7 @@ and by L0–L5, and a lemma that fails stops its stage. | e6 | Async values that depend on an earlier validation of the same operator object | `SemiJoin._validated_common_keys` and `Index._element_arrow_type_fallback` hold the last validation's values (ITL-858, section 1.2). One operator object applied to two streams can use the other stream's keys or fallback type | Read from each input's description, with no state | The ITL-858 finding; filed as ITL-1358. Reproducer: one `SemiJoin` instance validated on stream B, then run async over stream A with other keys. To be confirmed in stage 5 | ITL-1358 (filed); fixed with stage 5 once a reproducer confirms it | | e7 | What a consumer does after its producer failed (async, failure path) | The producer closes its output in `finally`, so a consumer sees a normal end and may finish, and a `LOG` operator node may store, a partial result before the task group cancels it | Readers raise `UpstreamFailedError` at the failure point instead of seeing a normal end, so no consumer finishes, or stores its result, as if its input were complete. Batches a consumer processed before the failure are still processed, and a streaming node may already have passed them on or a function node stored results for them, as on `main`; there is no rollback. A barrier operator never computes over a partial input. The run raises the producer's own error, as today | A candidate race, to be confirmed with a reproducer in stage 5: a `fail_fast` function node raising on row 3 of 6, feeding a `Select` node in `LOG` mode; check the operator cache after the failed run. If `main` never stores in practice, this row is no difference | filed by the developer only once a test reproduces it | | e8 | Meta columns of an async side-effect node's rows | An async side-effect node passes on and holds the rows it receives as they are, so a computed row keeps its `__computed` meta column (from the cached function pod), and the node's `as_table(all_info=True)` shows it. On sync, its input is rebuilt from rows (`_rows_to_table` drops meta), so the column is absent | Async drops input meta columns as sync does. With table transport this follows from the transport columns, which hold no meta column | A `main` bug: the async and sync paths give the node different columns. Found by the stage 0 harness on `job-speed` 0e15d0db, which does not change side-effect nodes; the stage 0 differential checks it on pinned `main`. Reproducer: a function node (with a result store) feeding a `tap_pod`, async against sync, comparing the side-effect node's `as_table(all_info=True)` columns | approved (developer, 2026-11-22) | -| e9 | A sync function node whose output rows disagree on a column's Arrow type | A node with no successor completes the run; its `as_table()` raises `InputValidationError` ("Function node 'double': Rows disagree on the Arrow type of column 'k': int32 and uint32"). A node with a successor fails the run with a bare pyarrow `ArrowInvalid`, raised where the successor's input is rebuilt | The node builds its output stream when it runs (stage 2), so the run fails at the node, before it commits, with the `InputValidationError` `as_table()` raises (same type and message), with or without a successor; the node then holds no run. What is stored equals `main`'s: the row computed before the disagreement could be seen is stored, as on `main` (2 stored rows before the run, 3 after, on both) | Not a `main` bug to fix: a consequence of building the output stream in `execute`, and for a node with a successor an improvement (`main`'s `ArrowInvalid` names nothing). It arises only from a store written before ITL-928, whose cached rows give a `uint32` tag back as `int32`; such a store must be rebuilt. Reproducer: `tests/test_core/function_pod/test_function_node_arrow_types.py::test_new_rows_over_a_store_written_before_the_fix_raise_naming_the_column` (leaf and with successor) | provisional, coordinator decision 2026-11-22, pending developer | +| e9 | A sync function node whose output rows disagree on a column's Arrow type | A node with no successor completes the run; its `as_table()` raises `InputValidationError` ("Function node 'double': Rows disagree on the Arrow type of column 'k': int32 and uint32"). A node with a successor fails the run with a bare pyarrow `ArrowInvalid`, raised where the successor's input is rebuilt | The node builds its output stream when it runs (stage 2), so the run fails at the node, once its writes are committed (a failed write is still reported first, as on `main`) and before the node takes the run, with the `InputValidationError` `as_table()` raises (same type and message), with or without a successor; the node then holds no run. What is stored equals `main`'s: the row computed before the disagreement could be seen is stored, as on `main` (2 stored rows before the run, 3 after, on both) | Not a `main` bug to fix: a consequence of building the output stream in `execute`, and for a node with a successor an improvement (`main`'s `ArrowInvalid` names nothing). It arises only from a store written before ITL-928, whose cached rows give a `uint32` tag back as `int32`; such a store must be rebuilt. Reproducer: `tests/test_core/function_pod/test_function_node_arrow_types.py::test_new_rows_over_a_store_written_before_the_fix_raise_naming_the_column` (leaf and with successor) | provisional, coordinator decision 2026-11-22, pending developer | **Resolved: refusals after rows have flowed (was c, question 9).** The developer's `Rejoin` rule (ITL-1355) removes every data-dependent refusal from `Rejoin`: it checks only what its diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 21075cb8f..60d6dc365 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -2656,16 +2656,17 @@ def execute( self._row_processed, ctx_obs, node_label, node_hash ) - # The output stream, built before the run is committed: rows that cannot - # make one table fail the run (ITL-1360, e9). + self._commit_or_end_node( + self._commit_at_node_end, ctx_obs, node_label, node_hash + ) + # The output stream, built once the run is committed (a failed write is + # reported first, as on main) and before the node takes the run: rows that + # cannot make one table fail the run (ITL-1360, e9). try: result_stream = self._output_stream(output) except InputValidationError: ctx_obs.on_node_end(node_label, node_hash) raise - self._commit_or_end_node( - self._commit_at_node_end, ctx_obs, node_label, node_hash - ) # The node's rows are those of this run's inputs, whatever else it caches. self._set_run_rows(emitted_entry_ids, failed=failed_rows) # Mark this node as freshly computed before the observer hears the end, so From 6947e719386557ca4521b5f966f422f0be8957a1 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 03:38:45 -0800 Subject: [PATCH 13/36] docs(operators): state F's domain; pin its one exception and the bind refusal (ITL-1360) Co-Authored-By: Claude Opus 5.5 --- .../core/operators/static_output_pod.py | 18 ++++- .../operators/test_row_built_form.py | 75 +++++++++++++++++++ 2 files changed, 89 insertions(+), 4 deletions(-) diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index c46ec8786..8f5e5afe8 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -482,10 +482,20 @@ def _row_built_form( """Return ``table`` as ``_rows_to_table`` builds it from the table's own rows. F in the ITL-1347 spec: the same table, without making the rows. The columns, - their order and their types are decided row by row (``streams.base.row_built_columns``), the - system-tag and source-info field flags by their values over the whole table - (``_flag_by_values``). The equality with ``_rows_to_table`` is tested over every - operator, source kind and column role (ITL-1347, L0-L2). + their order and their types are decided row by row + (``streams.base.row_built_columns``), the system-tag and source-info field flags + by their values over the whole table (``_flag_by_values``). The equality with + ``_rows_to_table`` is tested over every operator, source kind and column role + (ITL-1347, L0-L2). + + Its domain: F equals ``_rows_to_table`` for every stream whose source-info tokens + are strings or non-empty lists of tokens, which is every stream a source or an + operator makes (a token list has one element per member of a batch, group or + merge). The one exception is a hand-built raw ``ArrowTableStream`` whose + source-info column is a list type holding only empty lists: a row types its + tokens from their values, so ``_rows_to_table`` loses the list levels the + empty lists do not show, while F keeps the column's type. Such a stream reaches + a job only when bound to a slot with a copied source-id and record-id pair. Args: table: A table of user tags, system tags, data and source info, with rows. diff --git a/tests/test_core/operators/test_row_built_form.py b/tests/test_core/operators/test_row_built_form.py index 2c6cc5e9a..0fba4c92d 100644 --- a/tests/test_core/operators/test_row_built_form.py +++ b/tests/test_core/operators/test_row_built_form.py @@ -191,3 +191,78 @@ def test_row_built_form_of_a_raw_stream(make: Any) -> None: assert formed.column_names == built.column_names assert formed.schema.equals(built.schema, check_metadata=True) assert_same_values(formed, built) + + +def _source_table() -> pa.Table: + """A source's table with its system tags and source info (one tag, one data).""" + from orcapod.sources import DictSource + + source = DictSource( + [{"k": 1, "x": 1}, {"k": 2, "x": 2}], + tag_columns=["k"], + tag_only_columns=True, + source_id="s", + ) + return source.as_table(columns={"source": True, "system_tags": True}) + + +def test_empty_source_info_lists_are_outside_the_domain_of_the_row_built_form() -> None: + """F's one named exception: source-info tokens that are only empty lists. + + No source or operator makes an empty token list. A hand-built raw stream can: + ``_rows_to_table`` types the tokens from their values (one list level, the empty + lists show no more), while F keeps the column's two levels. Pinned so that a + change to either side is seen (the refusal of such a stream is the developer's + decision). + """ + table = _source_table() + position = table.schema.get_field_index("_source_x") + empty = pa.array([[], []], pa.large_list(pa.large_list(pa.large_string()))) + stream = ArrowTableStream( + table.set_column(position, "_source_x", empty), tag_columns=["k"] + ) + built, _, _ = StaticOutputOperatorPod._rows_to_table(list(stream.iter_data())) # pyright: ignore[reportPrivateUsage] # R, the oracle + formed = StaticOutputOperatorPod._row_built_form( # pyright: ignore[reportPrivateUsage] # F, under test + stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS), stream.keys() + ) + assert built.schema.field("_source_x").type == pa.large_list(pa.large_string()) + assert formed.schema.field("_source_x").type == pa.large_list( + pa.large_list(pa.large_string()) + ) + + +def test_a_source_with_a_nullable_system_tag_is_not_bound() -> None: + """A system-tag field with a null never reaches a job: a slot refuses the source. + + So F never meets one; ``_rows_to_table`` could not build its rows (two rows would + give the field two nullability flags). + """ + from orcapod import PipelineJob + from orcapod.databases import InMemoryArrowDatabase + from orcapod.errors import SourceSpecMismatchError + from orcapod.sources import DictSource + + source = DictSource( + [{"k": 1, "x": 1}, {"k": 2, "x": 2}], + tag_columns=["k"], + tag_only_columns=True, + source_id="s", + ) + job = PipelineJob(name="nullable_system_tag", database=InMemoryArrowDatabase()) + with job: + source.select_data_columns(["x"], label="selected") + table = _source_table() + record_id = next( + name + for name in table.column_names + if name.startswith(constants.SYSTEM_TAG_PREFIX) and "record_id" in name + ) + position = table.schema.get_field_index(record_id) + with_null = table.set_column( + position, + pa.field(record_id, pa.large_string(), nullable=True), + pa.array(["row_0", None], pa.large_string()), + ) + slot = next(label for label in job.nodes if label != "selected") + with pytest.raises(SourceSpecMismatchError, match="record_id"): + job.bind(sources={slot: ArrowTableStream(with_null, tag_columns=["k"])}) From 335c4bc8e5c6a1992d35a1350f2c2f43a296e5f1 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 05:01:09 -0800 Subject: [PATCH 14/36] fix(pipeline): F types source info from its tokens, over the whole table (ITL-1360) Codex on PR #485, finding 1. A row types each source-info token from its value (arrow_utils.source_info_arrow_type); F now does the same on the complete table (_type_source_info_by_values, beside _flag_by_values), so a list of None or of empty lists is kept and stored as the rows give it. Tokens of two types (a list on one row, None on another) cannot make one table: F raises SourceInfoTypesDisagree and the node builds its rows, which raise main's ArrowInvalid; a source node ends its node first, as on main. The domain exception of F is gone; its test is an equality test. Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/nodes/operator_node.py | 29 +++- src/orcapod/core/nodes/source_node.py | 15 +- .../core/operators/static_output_pod.py | 129 +++++++++++++-- .../operators/test_row_built_form.py | 155 ++++++++++++++++-- 4 files changed, 286 insertions(+), 42 deletions(-) diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index 34b600658..36904bf59 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -38,7 +38,10 @@ ) from orcapod.channels import Channel, ChannelClosed, ReadableChannel, WritableChannel from orcapod.config import OrcapodConfig -from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod +from orcapod.core.operators.static_output_pod import ( + SourceInfoTypesDisagree, + StaticOutputOperatorPod, +) from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.core.streams.base import ( ZERO_ROW_INPUT_COLUMNS, @@ -1688,11 +1691,16 @@ def execute( # Check REPLAY cache first cached_output = self.get_cached_output() if cached_output is not None: - output = StaticOutputOperatorPod._output_stream( - cached_output.as_table(columns=ZERO_ROW_INPUT_COLUMNS), - cached_output.keys(), - self, - ) + try: + output = StaticOutputOperatorPod._output_stream( + cached_output.as_table(columns=ZERO_ROW_INPUT_COLUMNS), + cached_output.keys(), + self, + ) + except SourceInfoTypesDisagree as error: + StaticOutputOperatorPod._raise_as_rows_do( + cached_output.iter_data(), error + ) ctx_obs.on_node_end(node_label, node_hash) return output @@ -1708,7 +1716,14 @@ def execute( # Cache, in row order with or without rows (ITL-1131, ITL-1133). if result_table.num_rows: - kept_table = StaticOutputOperatorPod._row_built_form(result_table, keys) + try: + kept_table = StaticOutputOperatorPod._row_built_form( + result_table, keys + ) + except SourceInfoTypesDisagree as error: + StaticOutputOperatorPod._raise_as_rows_do( + result_stream.iter_data(), error + ) self._cached_output_stream = ArrowTableStream( kept_table, tag_columns=tag_keys, data_tags=data_tags ) diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index 7644f1703..7da04da1c 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -1235,7 +1235,10 @@ def execute( Raises: UnboundSourceError: When no concrete data is available. """ - from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod + from orcapod.core.operators.static_output_pod import ( + SourceInfoTypesDisagree, + StaticOutputOperatorPod, + ) node_label = self.label node_hash = self.content_hash().to_string() @@ -1244,7 +1247,15 @@ def execute( # The table and keys of this node's rows: a slot's own key order can differ # from its source's. table, keys = self._rows_table() - result = StaticOutputOperatorPod._output_stream(table, keys, self) + try: + result = StaticOutputOperatorPod._output_stream(table, keys, self) + except SourceInfoTypesDisagree as error: + # Rows whose source-info tokens cannot make one table: the node has read + # its rows, and the run fails where its rows are handed on, raising what + # their concatenation raises. + if observer is not None: + observer.on_node_end(node_label, node_hash) + StaticOutputOperatorPod._raise_as_rows_do(self.iter_data(), error) if observer is not None: observer.on_node_end(node_label, node_hash) return result diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index ac7717972..077cf4817 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -3,9 +3,9 @@ import asyncio import logging from abc import abstractmethod -from collections.abc import Collection, Iterator, Sequence +from collections.abc import Collection, Iterable, Iterator, Sequence from datetime import datetime, timezone -from typing import TYPE_CHECKING, Any, ClassVar, cast +from typing import TYPE_CHECKING, Any, ClassVar, NoReturn, cast import pyarrow as pa @@ -66,6 +66,15 @@ from orcapod.protocols.hashing_protocols import SemanticHasherProtocol +class SourceInfoTypesDisagree(ValueError): + """Two rows give one source-info column different types (``_row_built_form``). + + A table built from such rows cannot be concatenated: the caller builds the rows + (``StaticOutputOperatorPod._rows_to_table``), which raises the error a table built + from rows raises, so the run fails as it does when rows are handed on. + """ + + class StaticOutputOperatorPod(TraceableBase): """Abstract base class for pods whose core logic yields a static output stream. @@ -493,27 +502,81 @@ def _flag_by_values(table: pa.Table) -> pa.Table: # Same arrays, new field flags: no cast, so no value or type can change. return pa.Table.from_arrays(table.columns, schema=pa.schema(fields)) + @staticmethod + def _type_source_info_by_values(table: pa.Table) -> pa.Table: + """Type each source-info column from its tokens, as the rows of a table built from rows do. + + A step of F (``_row_built_form``) on the complete table, beside + ``_flag_by_values``. A row's ``Data`` types each source-info token from its + value (``arrow_utils.source_info_arrow_type``, the one rule): a string or + ``None`` as ``large_string``, a list as ``large_list`` of its first informative + element's type, so a list of ``None`` or of empty lists shows fewer levels than + its column may declare. The rows' tables are then concatenated, which needs + every row to give a column one type. This step gives each column that type, + built from the same values. A ``large_string`` column is every row's type + already and is left as it is. + + Args: + table: A table of user tags, system tags, data and source info, after the + per-slice steps (``streams.base.row_built_columns``). + + Returns: + The table with each source-info column of the type its tokens give. + + Raises: + SourceInfoTypesDisagree: If two rows give one source-info column different + types, where the rows' tables cannot be concatenated. The caller builds + 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) + fields = list(table.schema) + changed = False + for index, field in enumerate(fields): + if not field.name.startswith(constants.SOURCE_PREFIX): + continue + if pa.types.is_large_string(field.type): + continue + values = table.column(index).to_pylist() + kinds = {arrow_utils.source_info_arrow_type(value) for value in values} + if len(kinds) != 1: + raise SourceInfoTypesDisagree(field.name) + (kind,) = kinds + if kind == field.type: + continue + columns[index] = pa.chunked_array([pa.array(values, type=kind)]) + fields[index] = pa.field(field.name, kind, nullable=field.nullable) + changed = True + if not changed: + return table + return pa.Table.from_arrays( + columns, + schema=pa.schema( + fields, + cast("dict[bytes | str, bytes | str] | None", table.schema.metadata), + ), + ) + @staticmethod def _row_built_form( table: pa.Table, keys: tuple[Sequence[str], Sequence[str]] ) -> pa.Table: """Return ``table`` as ``_rows_to_table`` builds it from the table's own rows. - F in the ITL-1347 spec: the same table, without making the rows. The columns, - their order and their types are decided row by row - (``streams.base.row_built_columns``), the system-tag and source-info field flags - by their values over the whole table (``_flag_by_values``). The equality with - ``_rows_to_table`` is tested over every operator, source kind and column role - (ITL-1347, L0-L2). - - Its domain: F equals ``_rows_to_table`` for every stream whose source-info tokens - are strings or non-empty lists of tokens, which is every stream a source or an - operator makes (a token list has one element per member of a batch, group or - merge). The one exception is a hand-built raw ``ArrowTableStream`` whose - source-info column is a list type holding only empty lists: a row types its - tokens from their values, so ``_rows_to_table`` loses the list levels the - empty lists do not show, while F keeps the column's type. Such a stream reaches - a job only when bound to a slot with a copied source-id and record-id pair. + F in the ITL-1347 spec: the same table, without making the rows. Two steps: + + - per slice (``streams.base.row_built_columns``), what each row decides on its + own: the columns, their order, their large types, and the provenance fields' + form (no system-tag field metadata, source-info lists of nullable items); + - on the complete table, what depends on the values of every row: each + source-info column's type, from its tokens (``_type_source_info_by_values``), + then the system-tag and source-info field flags (``_flag_by_values``). + + The equality with ``_rows_to_table`` is tested over every operator, source kind, + column role and raw-stream provenance shape (ITL-1347, L0-L2). Args: table: A table of user tags, system tags, data and source info, with rows. @@ -522,8 +585,38 @@ def _row_built_form( Returns: The table ``_rows_to_table`` would build from its rows. + + Raises: + SourceInfoTypesDisagree: If the rows' tokens give a source-info column two + types (``_type_source_info_by_values``). + """ + return StaticOutputOperatorPod._flag_by_values( + StaticOutputOperatorPod._type_source_info_by_values( + row_built_columns(table, keys) + ) + ) + + @staticmethod + def _raise_as_rows_do( + rows: Iterable[tuple[TagProtocol, DataProtocol]], + error: SourceInfoTypesDisagree, + ) -> NoReturn: + """Build ``rows`` into a table to raise the error a table built from them raises. + + Called when ``_row_built_form`` finds rows whose source-info tokens cannot make + one table (``SourceInfoTypesDisagree``): the rows' own concatenation + (``_rows_to_table``) raises exactly what a run that hands rows on raises. + + Args: + rows: The rows of the table F was given, in order. + error: The disagreement F found, raised if the rows do concatenate. + + Raises: + pyarrow.ArrowInvalid: As ``_rows_to_table`` raises it. + SourceInfoTypesDisagree: ``error``, if the rows concatenate after all. """ - return StaticOutputOperatorPod._flag_by_values(row_built_columns(table, keys)) + StaticOutputOperatorPod._rows_to_table(list(rows)) + raise error @staticmethod def _output_stream( diff --git a/tests/test_core/operators/test_row_built_form.py b/tests/test_core/operators/test_row_built_form.py index 0fba4c92d..23a54bedf 100644 --- a/tests/test_core/operators/test_row_built_form.py +++ b/tests/test_core/operators/test_row_built_form.py @@ -25,8 +25,15 @@ import pyarrow.compute as pc import pytest -from orcapod.core.operators import DropNulls, SelectDataColumns -from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod +from orcapod import PipelineJob +from orcapod.core.operators import Batch, DropNulls, SelectDataColumns +from orcapod.core.operators.static_output_pod import ( + SourceInfoTypesDisagree, + StaticOutputOperatorPod, +) +from orcapod.databases import InMemoryArrowDatabase +from orcapod.pipeline.observer import NoOpObserver +from orcapod.types import CacheMode from orcapod.core.streams import ArrowTableStream from orcapod.core.streams.base import ZERO_ROW_INPUT_COLUMNS, row_built_columns from orcapod.system_constants import constants @@ -206,29 +213,147 @@ def _source_table() -> pa.Table: return source.as_table(columns={"source": True, "system_tags": True}) -def test_empty_source_info_lists_are_outside_the_domain_of_the_row_built_form() -> None: - """F's one named exception: source-info tokens that are only empty lists. +def _with_source_x(values: list[Any], kind: pa.DataType) -> ArrowTableStream: + """A source's rows as a raw stream, ``_source_x`` replaced by ``values`` of ``kind``. - No source or operator makes an empty token list. A hand-built raw stream can: - ``_rows_to_table`` types the tokens from their values (one list level, the empty - lists show no more), while F keeps the column's two levels. Pinned so that a - change to either side is seen (the refusal of such a stream is the developer's - decision). + It keeps the source's system-tag pair, so a job slot accepts it (Codex on PR #485). """ table = _source_table() position = table.schema.get_field_index("_source_x") - empty = pa.array([[], []], pa.large_list(pa.large_list(pa.large_string()))) - stream = ArrowTableStream( - table.set_column(position, "_source_x", empty), tag_columns=["k"] + return ArrowTableStream( + table.set_column( + position, + pa.field("_source_x", kind, nullable=True), + pa.array(values, kind), + ), + tag_columns=["k"], ) + + +_STRINGS = pa.large_list(pa.large_string()) +_NESTED = pa.large_list(_STRINGS) + + +@pytest.mark.parametrize( + "make", + [ + pytest.param(lambda: _with_source_x([[], []], _NESTED), id="empty-lists"), + pytest.param(lambda: _with_source_x([None, None], _STRINGS), id="null-lists"), + pytest.param( + lambda: _with_source_x([[None], [None]], _NESTED), id="lists-of-null" + ), + pytest.param( + lambda: Batch(batch_size=1)( + _with_source_x([None, None], pa.large_string()) + ), + id="batch-1-of-null-tokens", + ), + pytest.param( + lambda: Batch(batch_size=2)(_with_source_x([None, None], _STRINGS)), + id="batch-2-of-null-lists", + ), + pytest.param(lambda: _with_source_x([None, None], pa.null()), id="null-type"), + ], +) +def test_source_info_types_follow_the_tokens(make: Any) -> None: + """F types each source-info column from its tokens, as the rows do. + + A list of ``None`` or of empty lists shows fewer levels than its column declares; + the rows type it from the tokens (``arrow_utils.source_info_arrow_type``), and so + does F, over the whole table. + """ + stream = make() built, _, _ = StaticOutputOperatorPod._rows_to_table(list(stream.iter_data())) # pyright: ignore[reportPrivateUsage] # R, the oracle formed = StaticOutputOperatorPod._row_built_form( # pyright: ignore[reportPrivateUsage] # F, under test stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS), stream.keys() ) - assert built.schema.field("_source_x").type == pa.large_list(pa.large_string()) - assert formed.schema.field("_source_x").type == pa.large_list( - pa.large_list(pa.large_string()) + assert formed.column_names == built.column_names + assert formed.schema.equals(built.schema, check_metadata=True) + assert_same_values(formed, built) + + +def test_tokens_of_two_types_raise_as_the_rows_do() -> None: + """A list token on one row and ``None`` on another: no table holds both rows. + + The rows' tables cannot be concatenated (``ArrowInvalid``); F says so + (``SourceInfoTypesDisagree``), and a node then builds the rows, which raise. + """ + stream = _with_source_x([["s"], None], _STRINGS) + with pytest.raises(pa.ArrowInvalid, match="Schema at index 1 was different"): + StaticOutputOperatorPod._rows_to_table(list(stream.iter_data())) # pyright: ignore[reportPrivateUsage] # R, the oracle + with pytest.raises(SourceInfoTypesDisagree, match="_source_x"): + StaticOutputOperatorPod._row_built_form( # pyright: ignore[reportPrivateUsage] # F, under test + stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS), stream.keys() + ) + + +class _NodeEvents(NoOpObserver): + """Records node starts and ends.""" + + def __init__(self) -> None: + self.events: list[tuple[str, str]] = [] + + def contextualize(self, *identity_path: str) -> _NodeEvents: + return self + + def on_node_start( + self, node_label: str, node_hash: str, tag_schema: Any = None + ) -> None: + self.events.append(("start", node_label)) + + def on_node_end(self, node_label: str, node_hash: str) -> None: + self.events.append(("end", node_label)) + + +def _batched_job(database: InMemoryArrowDatabase) -> PipelineJob: + """``source -> select x -> Batch(2)``, the batch node in ``LOG`` mode.""" + from orcapod.sources import DictSource + + source = DictSource( + [{"k": 1, "x": 1}, {"k": 2, "x": 2}], + tag_columns=["k"], + tag_only_columns=True, + source_id="s", + ) + job = PipelineJob(name="source_info_types", database=database) + with job: + Batch(batch_size=2)(source.select_data_columns(["x"]), label="batched") + job.nodes["batched"].attach_databases( + pipeline_database=database.at("log"), cache_mode=CacheMode.LOG ) + return job + + +def test_a_job_keeps_and_stores_the_token_type_the_rows_give() -> None: + """A bound raw source with null list tokens, through ``Batch(2)`` in ``LOG`` mode. + + The rows type ``[None, None]`` as ``large_list``: kept and stored so, + as on ``main``, not as the list of the input's declared list type. + """ + database = InMemoryArrowDatabase() + job = _batched_job(database) + job.bind(sources={"s": _with_source_x([None, None], _STRINGS)}) + job.run() + node = job.nodes["batched"] + kept = node.as_table(columns={"source": True}) + assert kept.schema.field("_source_x").type == _STRINGS + stored = node.get_all_records(columns={"source": True}) + assert stored is not None + assert stored.schema.field("_source_x").type == _STRINGS + + +def test_a_job_over_tokens_of_two_types_fails_as_main_does() -> None: + """The run raises the rows' ``ArrowInvalid`` after the source node has ended. + + On ``main`` the source node hands its rows on, and the run fails where they are + concatenated for its successor: the same error, after the same events. + """ + job = _batched_job(InMemoryArrowDatabase()) + job.bind(sources={"s": _with_source_x([["s"], None], _STRINGS)}) + observer = _NodeEvents() + with pytest.raises(pa.ArrowInvalid, match="Schema at index 1 was different"): + job.run(observer=observer) + assert observer.events == [("start", "s"), ("end", "s")] def test_a_source_with_a_nullable_system_tag_is_not_bound() -> None: From 942fe148d2c5718a2682a58998b525d3017aca66 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 05:03:40 -0800 Subject: [PATCH 15/36] fix(source_node): a source's rows keep their data order (ITL-1360) Codex on PR #485, finding 2. A PollingSource states its declared key order, but its rows (and a table built from them) list the data in the fetched table's order. The source node takes its rows' keys from the table by the rule its rows follow (_keys_of_rows), so an operator after it keeps and stores the columns as on main. L2 test with a poller fetching in another order. Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/nodes/source_node.py | 34 +++++++-- .../test_stream_transport_equivalence.py | 74 ++++++++++++++++++- 2 files changed, 102 insertions(+), 6 deletions(-) diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index 7da04da1c..2fdfccd1d 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -13,7 +13,7 @@ import json import logging from abc import ABC, abstractmethod -from collections.abc import AsyncIterator, Collection, Iterator, Mapping +from collections.abc import AsyncIterator, Collection, Iterator, Mapping, Sequence from datetime import datetime from typing import TYPE_CHECKING, Any, cast @@ -185,6 +185,32 @@ def _declared_positions(self, names: list[str]) -> list[int]: return order +def _keys_of_rows( + table: pa.Table, keys: tuple[Sequence[str], Sequence[str]] +) -> tuple[tuple[str, ...], tuple[str, ...]]: + """Return the tag and data keys a source's rows have, given its table and ``keys()``. + + A source's rows come from a stream over its table (``ArrowTableStream``), whose rows + list their tags in the stream's tag order and their data with the data-tags first, + in tag order, then the other data columns in the table's order. A source whose + ``keys()`` states its declared order (a ``PollingSource`` whose fetched table has + another column order) has rows in the table's order all the same, as a table built + from its rows does (Codex on PR #485). + + Args: + table: The source's table, as its rows are read from it. + keys: The source's ``keys()``. + + Returns: + The tag keys, and the data keys in the order of the rows. + """ + tag_keys, data_keys = (tuple(keys[0]), tuple(keys[1])) + data_tags = data_tag_names(tag_keys, data_keys) + data = set(data_keys) - set(tag_keys) + in_table = tuple(name for name in table.column_names if name in data) + return tag_keys, (*data_tags, *in_table) + + def _system_tag_columns( source: StreamProtocol, tag_names: Collection[str] ) -> tuple[list[str], list[str], list[str]]: @@ -1193,9 +1219,8 @@ def _rows_table(self) -> tuple[pa.Table, tuple[tuple[str, ...], tuple[str, ...]] Here this node's own table (``ZERO_ROW_INPUT_COLUMNS``) and keys. """ stream = cast("StreamProtocol", self) - tag_keys, data_keys = stream.keys() table = stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS) - return table, (tuple(tag_keys), tuple(data_keys)) + return table, _keys_of_rows(table, stream.keys()) def arrow_schema(self) -> pa.Schema: """The Arrow schema of the columns this stream passes between job nodes. @@ -1754,8 +1779,7 @@ def _rows_table(self) -> tuple[pa.Table, tuple[tuple[str, ...], tuple[str, ...]] ) table = self._bound_source.as_table(columns=ZERO_ROW_INPUT_COLUMNS) if self._declared_form is None: - tag_keys, data_keys = self._bound_source.keys() - return table, (tuple(tag_keys), tuple(data_keys)) + return table, _keys_of_rows(table, self._bound_source.keys()) return self._declared_form.apply(table), self._row_keys() def iter_data(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: diff --git a/tests/test_pipeline/test_stream_transport_equivalence.py b/tests/test_pipeline/test_stream_transport_equivalence.py index 68f608d1c..3874d5c87 100644 --- a/tests/test_pipeline/test_stream_transport_equivalence.py +++ b/tests/test_pipeline/test_stream_transport_equivalence.py @@ -40,7 +40,7 @@ from orcapod.core.streams.base import ZERO_ROW_INPUT_COLUMNS from orcapod.databases import InMemoryArrowDatabase from orcapod.errors import ProvisionalHashWarning -from orcapod.operators import MergeJoin, Rejoin +from orcapod.operators import MergeJoin, Rejoin, SelectDataColumns from orcapod.side_effects import SideEffectJobNode from orcapod.system_constants import constants from orcapod.types import CacheMode @@ -318,3 +318,75 @@ def test_a_loaded_job_describes_its_nodes( output.schema ), label assert node.arrow_types_declared, label + + +def _poller(fetched_order: tuple[str, ...]) -> Any: + """A ``PollingSource`` declaring tags ``k, j`` and data ``b, a``. + + It fetches a table with its columns in ``fetched_order``: a valid source whose + declared order is not its rows' (Codex on PR #485). + """ + from orcapod.core.sources import PollingSource + from tests.test_hashing.test_logical_type_forms import ( + _TableImpl, # pyright: ignore[reportPrivateUsage] # the one test polling implementation + ) + + columns = { + "k": pa.array(["1", "2"], pa.large_string()), + "j": pa.array(["x", "y"], pa.large_string()), + "a": pa.array([1, 2], pa.int64()), + "b": pa.array([3, 4], pa.int64()), + } + declared = pa.schema( + [pa.field(name, columns[name].type, False) for name in ("k", "j", "b", "a")] + ) + fetched = pa.table({name: columns[name] for name in fetched_order}) + fetched = fetched.cast(pa.schema([f.with_nullable(False) for f in fetched.schema])) + return PollingSource( + _TableImpl(fetched, declared), + tag_columns=["k", "j"], + record_id_columns=["k", "j"], + source_id="poller", + ) + + +@pytest.mark.filterwarnings("ignore::orcapod.errors.ProvisionalHashWarning") +@pytest.mark.parametrize( + "fetched_order", + [("j", "k", "a", "b"), ("k", "j", "b", "a"), ("k", "b", "j", "a")], + ids="-".join, +) +def test_a_poller_fetching_in_another_order_hands_on_its_rows( + fetched_order: tuple[str, ...], outputs: dict[str, Any] +) -> None: + """L2 for a poller whose fetched column order differs from its declared order. + + The source node's output equals its rows rebuilt (checked by ``outputs``), and the + operator after it keeps and stores its columns in the rows' order, as on ``main``. + """ + # Built before the job captures: importing the polling implementation's module + # inside ``with job`` would capture the sources that module builds. + poller = _poller(fetched_order) + database = InMemoryArrowDatabase() + job = PipelineJob(name="poller_order", database=database) + with job: + SelectDataColumns(["a", "b"])(poller, label="selected") + job.nodes["selected"].attach_databases( + pipeline_database=database.at("log"), cache_mode=CacheMode.LOG + ) + _run(job) + node = job.nodes["selected"] + rows_order = [ + *job.nodes["selected"].keys()[0], + *(name for name in fetched_order if name in ("a", "b")), + ] + source_order = [f"{constants.SOURCE_PREFIX}{n}" for n in rows_order[2:]] + kept = node.as_table(columns={"source": True}).column_names + assert kept == [*rows_order, *source_order] + stored = node.get_all_records(columns={"source": True}) + assert stored is not None + assert [name for name in stored.column_names if not name.startswith("__")] == [ + *rows_order, + *source_order, + ] + assert "poller" in outputs From a6582388b64d66f533c0a30b5cfc9189b71d7fb7 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 05:06:38 -0800 Subject: [PATCH 16/36] fix(pipeline): async held rows as planned; async outputs built on read (ITL-1360) Codex on PR #485, findings 3 and 4. The run plan keeps the rows of each held node as it took them (RunPlan.held_rows) beside their output streams. The async orchestrator takes those rows again (held_rows, as on main) and sends them, instead of reading the node again; the sync orchestrator takes the streams. The async orchestrator's node_outputs builds each node's stream when it is first read (StreamsOnRead), so an async run over rows that cannot make one table (e9's store written before ITL-928) finishes and holds its rows, as on main; e9 stays a sync-only difference. Co-Authored-By: Claude Opus 5.5 --- src/orcapod/pipeline/async_orchestrator.py | 34 ++++++------- src/orcapod/pipeline/job.py | 33 ++++++++---- src/orcapod/pipeline/node_run.py | 18 ++++--- src/orcapod/pipeline/result.py | 43 +++++++++++++++- .../test_function_node_arrow_types.py | 27 ++++++++++ .../test_current_run_review_fixes.py | 10 +--- .../test_stream_transport_equivalence.py | 51 +++++++++++++++++++ 7 files changed, 172 insertions(+), 44 deletions(-) diff --git a/src/orcapod/pipeline/async_orchestrator.py b/src/orcapod/pipeline/async_orchestrator.py index 061616cba..a9f87691c 100644 --- a/src/orcapod/pipeline/async_orchestrator.py +++ b/src/orcapod/pipeline/async_orchestrator.py @@ -24,7 +24,7 @@ OrcapodDatabaseWriteError, TypeIdentityError, ) -from orcapod.pipeline.result import OrchestratorResult +from orcapod.pipeline.result import OrchestratorResult, StreamsOnRead from orcapod.utils.database_errors import keep_database_error from orcapod.protocols.node_protocols import ( is_function_node, @@ -41,7 +41,6 @@ from orcapod.pipeline.dag import GraphProtocol from orcapod.protocols.core_protocols import ( DataProtocol, - StreamProtocol, TagProtocol, ) from orcapod.protocols.observability_protocols import ExecutionObserverProtocol @@ -87,7 +86,7 @@ def run( run_id: str | None = None, pipeline_uri: str = "", load_only: bool = False, - held: Mapping[Any, StreamProtocol] | None = None, + held_rows: Mapping[Any, list[tuple[TagProtocol, DataProtocol]]] | None = None, ) -> OrchestratorResult: """Synchronous entry point — runs the async pipeline to completion. @@ -132,7 +131,7 @@ def run( run_id=run_id, pipeline_uri=pipeline_uri, load_only=load_only, - held=held, + held_rows=held_rows, ) ) @@ -154,7 +153,7 @@ def make_run() -> Coroutine[Any, Any, OrchestratorResult]: run_id=run_id, pipeline_uri=pipeline_uri, load_only=load_only, - held=held, + held_rows=held_rows, ) return _run_on_own_thread(make_run, rows_in_flight) @@ -168,7 +167,7 @@ async def run_async( run_id: str | None = None, pipeline_uri: str = "", load_only: bool = False, - held: Mapping[Any, StreamProtocol] | None = None, + held_rows: Mapping[Any, list[tuple[TagProtocol, DataProtocol]]] | None = None, ) -> OrchestratorResult: """Async entry point for callers already inside an event loop. @@ -181,8 +180,9 @@ async def run_async( pipeline_uri: Opaque URI string identifying this pipeline run. Forwarded verbatim to ``observer.on_run_start``. load_only: As for ``SyncPipelineOrchestrator.run``. - held: As for ``SyncPipelineOrchestrator.run``: nodes not run, whose - rows feed their successors. + held_rows: Nodes not run, with the rows of their current run as the run's + plan took them (``RunPlan.held_rows``): those rows feed their + successors. The async path carries rows until ITL-1347 stage 5. Returns: OrchestratorResult with node outputs. @@ -194,7 +194,7 @@ async def run_async( run_id=run_id, pipeline_uri=pipeline_uri, load_only=load_only, - held=held, + held_rows=held_rows, ) async def _run_async( @@ -206,7 +206,7 @@ async def _run_async( run_id: str | None = None, pipeline_uri: str = "", load_only: bool = False, - held: Mapping[Any, StreamProtocol] | None = None, + held_rows: Mapping[Any, list[tuple[TagProtocol, DataProtocol]]] | None = None, ) -> OrchestratorResult: """Core async logic: wire channels, launch tasks, collect results.""" from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod @@ -269,7 +269,7 @@ async def _run_async( collector = collectors[node] writer = _CollectingWriter(writer, collector) - if held is not None and node in held: + if held_rows is not None and node in held_rows: # Not run: the rows of its current run feed its successors. Its # own inputs are read and discarded, so no producer blocks on # a channel nobody reads. @@ -279,9 +279,8 @@ async def _run_async( tg, failed_nodes, node, - # The held node's own rows, as before stage 2: the async - # path still carries rows (ITL-1347, stage 5 changes it). - _send_held(list(node.iter_data()), writer), + # The rows the plan took (ITL-1347, stage 5 changes it). + _send_held(held_rows[node], writer), ) elif is_source_node(node): _start_node( @@ -366,10 +365,9 @@ async def _run_async( return OrchestratorResult( node_outputs=( - { - node: StaticOutputOperatorPod._materialize_upstream(rows, node) - for node, rows in collectors.items() - } + StreamsOnRead( + collectors, StaticOutputOperatorPod._materialize_upstream + ) if materialize_results else {} ) diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index 1443d4f43..e2b84a81a 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -990,15 +990,28 @@ def run( counter = RunCountingObserver() effective_orchestrator = orchestrator or SyncPipelineOrchestrator() with self._executing(prepared, plan, commit_every_rows, load_only=load_only): - _ = effective_orchestrator.run( - plan.dag, - observer=_with_counter(observer, counter), - run_id=prepared.run_id, - pipeline_uri=prepared.pipeline_uri, - materialize_results=materialize_results, - load_only=load_only, - held=plan.held, - ) + if isinstance(effective_orchestrator, SyncPipelineOrchestrator): + # Held nodes give their output streams on the sync path (ITL-1347). + _ = effective_orchestrator.run( + plan.dag, + observer=_with_counter(observer, counter), + run_id=prepared.run_id, + pipeline_uri=prepared.pipeline_uri, + materialize_results=materialize_results, + load_only=load_only, + held=plan.held, + ) + else: + # The async path sends the rows the plan took (until stage 5). + _ = effective_orchestrator.run( + plan.dag, + observer=_with_counter(observer, counter), + run_id=prepared.run_id, + pipeline_uri=prepared.pipeline_uri, + materialize_results=materialize_results, + load_only=load_only, + held_rows=plan.held_rows, + ) summary = self._finish_run( prepared, counter, @@ -1068,7 +1081,7 @@ async def run_async( pipeline_uri=prepared.pipeline_uri, materialize_results=materialize_results, load_only=load_only, - held=plan.held, + held_rows=plan.held_rows, ) summary = self._finish_run( prepared, diff --git a/src/orcapod/pipeline/node_run.py b/src/orcapod/pipeline/node_run.py index 9e67317fb..ad0ab8561 100644 --- a/src/orcapod/pipeline/node_run.py +++ b/src/orcapod/pipeline/node_run.py @@ -251,7 +251,10 @@ class RunPlan: them (a source slot is read; any other one is held). held: The output stream of each held node of ``dag``: of its current run, or of a stream outside the job; it feeds the nodes after it as if the node had - just run. + just run (the sync orchestrator). + held_rows: The rows of each held node, as the plan took them; ``held`` is + built from them. The async orchestrator sends them (it carries rows until + ITL-1347 stage 5). to_run: The nodes the run runs, in dependency order. held_counts: Every node of the whole graph that holds a current run, with its row count, for the summary. @@ -261,6 +264,7 @@ class RunPlan: held: dict[Any, Any] to_run: list[Any] held_counts: dict[Any, int] + held_rows: dict[Any, list[Any]] def plan_run(graph: Any, *, load_only: bool, outside: Sequence[Any] = ()) -> RunPlan: @@ -336,17 +340,19 @@ def is_source(node: Any) -> bool: # A held node's output stream: what the sync orchestrator built from its rows for # the nodes after it, exactly (ITL-1347, stage 2). - held = { - node: StaticOutputOperatorPod._materialize_upstream( - list(node.iter_data()), node - ) + held_rows = { + node: list(node.iter_data()) for node in included if not any(node is r for r in to_run) and not is_source(node) } + held = { + node: StaticOutputOperatorPod._materialize_upstream(rows, node) + for node, rows in held_rows.items() + } # Counted from what each node holds: iterating an operator's rows would build a # (Tag, Data) pair per row only to count them (ITL-1351). held_counts = {node: node.held_row_count() for node in current} - return RunPlan(dag, held, to_run, held_counts) + return RunPlan(dag, held, to_run, held_counts, held_rows) def commit_run(databases: Sequence[ArrowDatabaseProtocol], ran: Sequence[Any]) -> None: diff --git a/src/orcapod/pipeline/result.py b/src/orcapod/pipeline/result.py index 12448df8c..bb117de2d 100644 --- a/src/orcapod/pipeline/result.py +++ b/src/orcapod/pipeline/result.py @@ -2,6 +2,7 @@ from __future__ import annotations +from collections.abc import Callable, Iterator, Mapping from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any @@ -9,6 +10,43 @@ from orcapod.protocols.core_protocols import StreamProtocol +class StreamsOnRead(Mapping[Any, "StreamProtocol"]): + """Each node's output stream, built when it is first read. + + The async orchestrator collects each node's rows as they are sent; a node's stream + is built from them (``build``) the first time it is read, and kept. A run whose + rows cannot make one table (rows of a store written before ITL-928) therefore + finishes, as it does on ``main``, and only reading that node's output raises, as + reading its rows as a table does (ITL-1360). + """ + + def __init__( + self, + rows: Mapping[Any, Any], + build: Callable[[Any, Any], "StreamProtocol"], + ) -> None: + """Hold each node's rows and how a stream is built from them. + + Args: + rows: Each node's collected rows. + build: Builds a node's stream from its rows, given ``(rows, node)``. + """ + self._rows = dict(rows) + self._build = build + self._built: dict[Any, StreamProtocol] = {} + + def __getitem__(self, node: Any) -> "StreamProtocol": + if node not in self._built: + self._built[node] = self._build(self._rows[node], node) + return self._built[node] + + def __iter__(self) -> Iterator[Any]: + return iter(self._rows) + + def __len__(self) -> int: + return len(self._rows) + + @dataclass class OrchestratorResult: """Result of an orchestrator run. @@ -16,7 +54,8 @@ class OrchestratorResult: Attributes: node_outputs: Mapping from graph node to its output stream (backed by an Arrow table; ``as_table()`` gives it, ``iter_data()`` its rows). Empty when - ``materialize_results=False``. + ``materialize_results=False``. The async orchestrator builds each stream + when it is first read (``StreamsOnRead``). """ - node_outputs: dict[Any, "StreamProtocol"] = field(default_factory=dict) + node_outputs: Mapping[Any, "StreamProtocol"] = field(default_factory=dict) diff --git a/tests/test_core/function_pod/test_function_node_arrow_types.py b/tests/test_core/function_pod/test_function_node_arrow_types.py index b7a431498..56cc00a5d 100644 --- a/tests/test_core/function_pod/test_function_node_arrow_types.py +++ b/tests/test_core/function_pod/test_function_node_arrow_types.py @@ -394,3 +394,30 @@ def test_a_null_typed_row_is_compared_as_null() -> None: with pytest.raises(InputValidationError, match="'k': null and int64"): _concat_row_tables(rows) + + +@pytest.mark.parametrize("materialize_results", [True, False]) +def test_an_async_run_over_a_store_written_before_the_fix_finishes( + materialize_results: bool, tmp_path: pathlib.Path +) -> None: + """e9 is sync only: an async run over such a store finishes and holds its rows. + + The async orchestrator builds a node's output stream when it is read + (``StreamsOnRead``), so the run finishes as on ``main`` with either value of + ``materialize_results``; reading the node's rows as one table raises, as it does + on ``main``. + """ + from orcapod.pipeline import AsyncPipelineOrchestrator + + _build(DeltaTableDatabase(tmp_path), _source_table("uint32").slice(0, 2)).run() + _as_written_before_the_fix(tmp_path) + job = _build(DeltaTableDatabase(tmp_path), _source_table("uint32")) + job.run( + orchestrator=AsyncPipelineOrchestrator(), + materialize_results=materialize_results, + ) + + node = job.nodes["double"] + assert len(list(node.iter_data())) == 3 + with pytest.raises(InputValidationError, match="'k'"): + node.as_table() diff --git a/tests/test_pipeline/test_current_run_review_fixes.py b/tests/test_pipeline/test_current_run_review_fixes.py index 7ad949768..25f266174 100644 --- a/tests/test_pipeline/test_current_run_review_fixes.py +++ b/tests/test_pipeline/test_current_run_review_fixes.py @@ -17,8 +17,6 @@ import pyarrow as pa import pytest -from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod - from orcapod import PipelineJob, function_pod from orcapod.core.nodes import OperatorJobNode from orcapod.core.nodes.source_node import SourceJobNode @@ -752,18 +750,14 @@ def test_a_direct_async_run_drains_the_inputs_of_a_held_node( (grouped, summed), ): dag.add_edge(upstream, downstream) - held = { - rowwise: StaticOutputOperatorPod._materialize_upstream( # pyright: ignore[reportPrivateUsage] # a held node's output stream, as the run plan builds it - list(rowwise.iter_data()), rowwise - ) - } + held = {rowwise: list(rowwise.iter_data())} summed.clear_cache() grouped.clear_cache() orchestrator = AsyncPipelineOrchestrator(buffer_size=2, error_policy=error_policy) async def run() -> None: """Run the whole graph with ``rowwise`` held, under a time limit.""" - await asyncio.wait_for(orchestrator.run_async(dag, held=held), timeout=30) + await asyncio.wait_for(orchestrator.run_async(dag, held_rows=held), timeout=30) asyncio.run(run()) assert summed.as_table().num_rows == 2 diff --git a/tests/test_pipeline/test_stream_transport_equivalence.py b/tests/test_pipeline/test_stream_transport_equivalence.py index 3874d5c87..0d10ecf07 100644 --- a/tests/test_pipeline/test_stream_transport_equivalence.py +++ b/tests/test_pipeline/test_stream_transport_equivalence.py @@ -40,6 +40,8 @@ from orcapod.core.streams.base import ZERO_ROW_INPUT_COLUMNS from orcapod.databases import InMemoryArrowDatabase from orcapod.errors import ProvisionalHashWarning +from orcapod.pipeline import AsyncPipelineOrchestrator +from orcapod.pipeline.observer import NoOpObserver from orcapod.operators import MergeJoin, Rejoin, SelectDataColumns from orcapod.side_effects import SideEffectJobNode from orcapod.system_constants import constants @@ -390,3 +392,52 @@ def test_a_poller_fetching_in_another_order_hands_on_its_rows( *source_order, ] assert "poller" in outputs + + +@function_pod(output_keys="z") +def plus_one(d1_doubled: int) -> int: + return d1_doubled + 1 + + +class _ClearsOnRunStart(NoOpObserver): + """Clears ``node`` when the run starts and counts ``label``'s data starts.""" + + def __init__(self, node: Any, label: str) -> None: + self._node = node + self._label = label + self.data_starts = 0 + + def contextualize(self, *identity_path: str) -> _ClearsOnRunStart: + return self + + def on_run_start(self, run_id: str, pipeline_uri: str = "") -> None: + self._node.clear_cache() + + def on_data_start(self, node_label: str, tag: Any, data: Any) -> None: + if node_label == self._label: + self.data_starts += 1 + + +def test_an_async_held_node_sends_the_rows_the_plan_took() -> None: + """The async run sends a held node's rows as planned, not as read again later. + + An observer clears the held node when the run starts; the rows the plan took still + feed the node after it, as on ``main`` (Codex on PR #485). + """ + from orcapod.sources import DictSource + + job = PipelineJob(name="held_snapshot", database=InMemoryArrowDatabase()) + with job: + source = DictSource( + [{"k": i, "d1": i} for i in range(3)], + tag_columns=["k"], + tag_only_columns=True, + source_id="s", + ) + plus_one.pod(doubled.pod(source, label="twice"), label="plus") + job.run() + job.nodes["plus"].clear_cache() + observer = _ClearsOnRunStart(job.nodes["twice"], "plus") + summary = job.run(orchestrator=AsyncPipelineOrchestrator(), observer=observer) + assert summary.nodes["twice"].held == 3 + assert observer.data_starts == 3 From 44d95c3bd8853dcfb6380135cbe543b89e1ae396 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 05:08:31 -0800 Subject: [PATCH 17/36] fix(streams): a description never polls; L7 compares column order (ITL-1360) Codex on PR #485, findings 5 and 6. stream_arrow_schema's fallback for a stream that cannot type itself without rows asks only for its tags and system tags and states a string source-info field for each data column: asking for its source-info columns made a PollingSource that had not polled fetch its first batch. L7 compares columns in order. The arrangements where a source's tag schema is in layout order while its keys and rows follow the declared order (ITL-1365, being fixed on main) are strict xfails naming it, as is the reviewer's plain operator stream. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1360.md | 4 +- src/orcapod/core/streams/base.py | 13 +- .../test_stream_transport_equivalence.py | 123 ++++++++++++++++-- 3 files changed, 126 insertions(+), 14 deletions(-) diff --git a/changelog.d/ITL-1360.md b/changelog.d/ITL-1360.md index 0d7f58069..ce18adf22 100644 --- a/changelog.d/ITL-1360.md +++ b/changelog.d/ITL-1360.md @@ -7,7 +7,9 @@ every successor as it is: a source node gives its source's Arrow table, and an operator node its result's table (REPLAY: its stored table), each in the form a table built from the rows has, without making the rows. `OrchestratorResult.node_outputs` holds each - node's output stream, and a held node gives the stream of its held rows. Every + node's output stream (the async orchestrator builds it when it is first read), and + on the sync path a held node gives the stream of its held rows; the async path still + sends a held node's rows as the run's plan took them (`held_rows`). Every successor's input is unchanged: columns, types, row order, system tags, source info, pipeline and content hashes. No hash, stored table or output changes. An operator node's table is built once, for what it keeps and for every successor, instead of once to keep diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py index 38ade1cb1..f396b9c4f 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -365,11 +365,18 @@ def stream_arrow_schema( keys = typed.keys() table = typed_zero_row_input(stream) if table is None: - tag_schema, data_schema = typed.output_schema( - columns={"system_tags": True, "source": True} - ) + # Only what the stream declares: asking for its source-info columns would make + # a source that has not polled poll (a description never computes, polls or + # reads). A source's tokens are strings, so each data column's source info is + # a string field. + tag_schema, data_schema = typed.output_schema(columns={"system_tags": True}) converter = StaticOutputOperatorPod._upstream_context(typed).type_converter # pyright: ignore[reportPrivateUsage] # the one place that resolves an upstream's context table = arrow_utils.make_empty_table({**tag_schema, **data_schema}, converter) + for name in data_schema: + table = table.append_column( + pa.field(f"{constants.SOURCE_PREFIX}{name}", pa.large_string()), + pa.array([], pa.large_string()), + ) names = row_built_names(table.column_names, keys) schema = row_built_provenance(table.select(names)).schema prefixes = (constants.SYSTEM_TAG_PREFIX, constants.SOURCE_PREFIX) diff --git a/tests/test_pipeline/test_stream_transport_equivalence.py b/tests/test_pipeline/test_stream_transport_equivalence.py index 0d10ecf07..04977f91d 100644 --- a/tests/test_pipeline/test_stream_transport_equivalence.py +++ b/tests/test_pipeline/test_stream_transport_equivalence.py @@ -237,27 +237,55 @@ def test_a_held_node_hands_on_the_stream_built_from_its_rows( assert set(outputs) == {"noted"} -def _without_exceptions(schema: pa.Schema) -> dict[str, tuple[Any, bool, Any]]: - """Fields by name as (type, nullable, metadata), the spec's exceptions applied. +def _without_exceptions(schema: pa.Schema) -> list[tuple[str, Any, bool, Any]]: + """Fields in order as (name, type, nullable, metadata), the spec's exceptions applied. A system-tag or source-info field's flag is decided by a table's values (stated - nullable), and a ``null`` column is ``large_string`` in rows (ITL-1319). Columns are - matched by name: an operator node's declared tag order can differ from its rows' - under another physical layout, as on ``main``, and column order is not a result - (developer, 2026-11-22). + nullable), and a ``null`` column is ``large_string`` in rows (ITL-1319). Column + order counts on the sync path (Codex on PR #485). """ prefixes = (constants.SYSTEM_TAG_PREFIX, constants.SOURCE_PREFIX) - return { - field.name: ( + return [ + ( + field.name, pa.large_string() if pa.types.is_null(field.type) else field.type, True if field.name.startswith(prefixes) else field.nullable, field.metadata, ) for field in schema - } + ] + + +def _tag_schema_out_of_key_order(arrangement: Arrangement) -> bool: + """Whether the source's tag schema lists its tags in another order than its keys. + + ITL-1365: ``ArrowTableStream`` builds its tag schema in the table's layout order, + while its keys and rows follow the declared tag order; an operator predicts its + keys from that schema, so its ``arrow_schema()`` lists the tags in the layout + order and its rows do not. + """ + source = make_source(MAIN, arrangement) + return tuple(source.output_schema()[0]) != tuple(source.keys()[0]) + + +def _l7_arrangements() -> list[Any]: + return [ + pytest.param( + arrangement, + id=arrangement.id, + marks=pytest.mark.xfail( + strict=True, + raises=AssertionError, + reason="ITL-1365: a tag schema in layout order, keys in declared order", + ), + ) + if _tag_schema_out_of_key_order(arrangement) + else pytest.param(arrangement, id=arrangement.id) + for arrangement in arrangements(MAIN)[::4] + ] -@pytest.mark.parametrize("arrangement", arrangements(MAIN)[::4], ids=lambda a: a.id) +@pytest.mark.parametrize("arrangement", _l7_arrangements()) def test_declared_arrow_schema_equals_the_output( arrangement: Arrangement, outputs: dict[str, Any] ) -> None: @@ -441,3 +469,78 @@ def test_an_async_held_node_sends_the_rows_the_plan_took() -> None: summary = job.run(orchestrator=AsyncPipelineOrchestrator(), observer=observer) assert summary.nodes["twice"].held == 3 assert observer.data_starts == 3 + + +@pytest.mark.filterwarnings("ignore::orcapod.errors.ProvisionalHashWarning") +def test_describing_a_poller_that_has_not_polled_reads_nothing() -> None: + """L7: ``arrow_schema()`` of a poller that has not polled never fetches. + + It answers from the declared schema, the same every time, with each data column's + source info, and ``arrow_types_declared`` stays false (Codex on PR #485). + """ + from orcapod.core.sources import PollingSource + from orcapod.types import Schema + from tests.test_hashing.test_logical_type_forms import ( + _TableImpl, # pyright: ignore[reportPrivateUsage] # the one test polling implementation + ) + + fetches: list[int] = [] + + class Counting(_TableImpl): + async def fetch(self, cursor: Any = None) -> Any: + fetches.append(1) + return await super().fetch(cursor) + + def schema(self) -> Any: + return Schema({"k": str, "a": int, "b": int}) + + table = pa.table( + { + "k": pa.array(["1"], pa.large_string()), + "a": pa.array([1]), + "b": pa.array([2]), + } + ) + poller = PollingSource( + Counting(table, table.schema), + tag_columns=["k"], + record_id_columns=["k"], + source_id="unpolled", + ) + first = poller.arrow_schema() + second = poller.arrow_schema() + assert fetches == [] + assert first.equals(second, check_metadata=True) + assert [n for n in first.names if n.startswith(constants.SOURCE_PREFIX)] == [ + "_source_a", + "_source_b", + ] + assert not poller.arrow_types_declared + + +@pytest.mark.xfail( + strict=True, + raises=AssertionError, + reason="ITL-1365: a tag schema in layout order, keys in declared order", +) +def test_an_operator_stream_declares_its_tags_in_its_rows_order() -> None: + """A plain operator stream's ``arrow_schema()`` lists its tags as its rows do. + + Tags declared ``b, a`` over a table laid out ``a, b`` (Codex on PR #485). + """ + from orcapod.core.sources import ArrowTableSource + + table = pa.table( + { + "a": pa.array([1, 2]), + "b": pa.array([3, 4]), + "w": pa.array([5, 6]), + "x": pa.array([7, 8]), + } + ) + source = ArrowTableSource( + table, tag_columns=["b", "a"], tag_only_columns=True, source_id="s" + ) + stream = SelectDataColumns(["x"])(source) + built, _, _ = StaticOutputOperatorPod._rows_to_table(list(stream.iter_data())) # pyright: ignore[reportPrivateUsage] # the rows' order + assert stream.arrow_schema().names[:2] == built.column_names[:2] From b9f987905c3c1da3fa59dda4acf81a5da059d732 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 05:36:45 -0800 Subject: [PATCH 18/36] fix(pipeline): channels check source-info types as tokens; no new import cycle (ITL-1360) A source-info column's type follows its tokens over the complete table, so a channel's batch check (record_batch_channels._schema_mismatch) takes any token type there, as it takes any nullability; the channels test that pinned F's old empty-list exception is an equality test. The side-effect node builds its output stream through function_node.rows_as_output_stream instead of importing the operator module, which closed a new import cycle with the record-batch protocol module. Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/nodes/function_node.py | 22 ++++++++++++++++ src/orcapod/core/record_batch_channels.py | 25 ++++++++++++++++++- src/orcapod/side_effects.py | 17 ++++++------- .../operators/test_record_batch_execution.py | 22 ++++++---------- 4 files changed, 62 insertions(+), 24 deletions(-) diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 60d6dc365..de4920088 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -282,6 +282,28 @@ def _with_datagram_id(data: Data, datagram_id: uuid.UUID) -> Data: ) +def rows_as_output_stream( + rows: Sequence[tuple[TagProtocol, DataProtocol]], node: StreamProtocol +) -> StreamProtocol: + """Return ``rows`` as ``node``'s output stream, as the sync orchestrator built it. + + ``StaticOutputOperatorPod._materialize_upstream``, for the job nodes whose output is + still their rows (function and side-effect nodes, until ITL-1347 stages 3 and 4): + the rows' table with the node's identity, or its zero-row input with no row. One + place imports the operator module for them. + + Args: + rows: The node's output rows, in order. + node: The node. + + Returns: + The node's output stream. + """ + from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod + + return StaticOutputOperatorPod._materialize_upstream(rows, node) # pyright: ignore[reportPrivateUsage] # the one definition of a rebuilt upstream + + def _executor_supports_concurrent( data_function: DataFunctionProtocol, ) -> bool: diff --git a/src/orcapod/core/record_batch_channels.py b/src/orcapod/core/record_batch_channels.py index a6f5e57ab..8b258b5b1 100644 --- a/src/orcapod/core/record_batch_channels.py +++ b/src/orcapod/core/record_batch_channels.py @@ -563,7 +563,10 @@ def _schema_mismatch(declared: pa.Schema, batch: pa.RecordBatch) -> str | None: ``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 - follows the values of the complete table (``_flag_by_values``). + follows the values of the complete table (``_flag_by_values``). Nor is a + source-info column's type, which follows its tokens over the complete table + (``_type_source_info_by_values``): it must only be a token type (``large_string``, + or ``large_list`` of a token type). """ sent = batch.schema if declared.names != sent.names: @@ -571,6 +574,14 @@ def _schema_mismatch(declared: pa.Schema, batch: pa.RecordBatch) -> str | None: provenance = (constants.SYSTEM_TAG_PREFIX, constants.SOURCE_PREFIX) for index, (expected, column) in enumerate(zip(declared, sent)): carried = arrow_utils.normalize_to_large_types(expected.type) + if column.name.startswith(constants.SOURCE_PREFIX): + if not _is_token_type(column.type): + return f"column {column.name!r} is {column.type}, not a token type" + if column.metadata or not column.type.equals( + _without_metadata(column.type), check_metadata=True + ): + return f"column {column.name!r} carries field metadata" + continue if column.type != carried: return f"column {column.name!r} is {column.type}, the stream's is {carried}" if carried != expected.type and not _holds_only_nulls( @@ -603,6 +614,18 @@ def _schema_mismatch(declared: pa.Schema, batch: pa.RecordBatch) -> str | None: return None +def _is_token_type(kind: pa.DataType) -> bool: + """Whether ``kind`` is a source-info token type: ``large_string``, or a list of one. + + The types ``arrow_utils.source_info_arrow_type`` gives a token. + """ + if pa.types.is_large_string(kind): + return True + if isinstance(kind, pa.LargeListType): + return _is_token_type(kind.value_type) # pyright: ignore[reportUnknownArgumentType, reportUnknownMemberType] + return False + + def _without_metadata(kind: pa.DataType) -> pa.DataType: """``kind`` with the field metadata of every nested field removed.""" if isinstance(kind, pa.LargeListType): diff --git a/src/orcapod/side_effects.py b/src/orcapod/side_effects.py index 81a834fc2..071aa82ac 100644 --- a/src/orcapod/side_effects.py +++ b/src/orcapod/side_effects.py @@ -20,7 +20,11 @@ from orcapod.core.base import TraceableBase from orcapod.core.nodes.staleness import RunHoldingNode -from orcapod.core.nodes.function_node import _build_record_id_preimage, run_job_node +from orcapod.core.nodes.function_node import ( + _build_record_id_preimage, + rows_as_output_stream, + run_job_node, +) from orcapod.core.streams.base import ( StreamBase, check_head_size, @@ -1274,17 +1278,12 @@ def _output_stream( """The output stream of a run that passed ``rows`` on. What the sync orchestrator built from a node's rows for its successors - (``StaticOutputOperatorPod._materialize_upstream``). + (``StaticOutputOperatorPod._materialize_upstream``, through + ``rows_as_output_stream``). """ - from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod - - # A side-effect job node is a stream (``StreamBase``) that the checker cannot - # match against the protocol through its mixins. # A side-effect job node is a ``StreamBase``; the checker cannot match its # mixin members against ``StreamProtocol``, so the cast goes through object. - return StaticOutputOperatorPod._materialize_upstream( - rows, cast("StreamProtocol", cast(object, self)) - ) + return rows_as_output_stream(rows, cast("StreamProtocol", cast(object, self))) def _deliver_rows( self, input_stream: StreamProtocol, *, run_id: str | None diff --git a/tests/test_core/operators/test_record_batch_execution.py b/tests/test_core/operators/test_record_batch_execution.py index c47c11a3c..beddb5ece 100644 --- a/tests/test_core/operators/test_record_batch_execution.py +++ b/tests/test_core/operators/test_record_batch_execution.py @@ -592,15 +592,11 @@ def _schema_outcome(make: Callable[[], StreamProtocol]) -> tuple[str, Any]: @pytest.mark.parametrize("layout", ["one_batch", "one_row_per_batch"]) -def test_empty_source_info_lists_are_outside_the_row_built_forms_domain( - layout: str, -) -> None: - """Pins a documented exception of F (``_row_built_form``): F equals the table built - from rows for every stream whose source-info tokens are strings or non-empty - lists, which is every stream a source or an operator makes. A hand-built raw - stream whose source-info column is a nested list type holding only empty lists is - outside that domain: the channel keeps the column's two list levels, while the - job's sync path rebuilds the tokens from their values and gives one.""" +def test_empty_source_info_lists_are_typed_from_their_tokens(layout: str) -> None: + """A raw stream whose source-info column is a nested list type holding only empty + lists: the channel's result equals the job's sync path, both typing the tokens from + their values over the complete table (``_type_source_info_by_values``), as the rows + do: one list level, not the column's two.""" raw = ArrowTableStream( pa.table( { @@ -618,11 +614,9 @@ def test_empty_source_info_lists_are_outside_the_row_built_forms_domain( job_sync = _job_sync(SelectDataColumns(["x"]), raw) got = channel.as_table(columns=ALL) rebuilt = job_sync.as_table(columns=ALL) - assert got.to_pylist() == rebuilt.to_pylist() # the same rows - assert got.schema.field("_source_x").type == pa.large_list( - pa.large_list(pa.large_string()) - ) - assert rebuilt.schema.field("_source_x").type == pa.large_list(pa.large_string()) + assert got.to_pylist() == rebuilt.to_pylist() + assert got.schema.equals(rebuilt.schema) + assert got.schema.field("_source_x").type == pa.large_list(pa.large_string()) def test_a_system_tag_with_a_null_is_refused_by_the_job_sync_path() -> None: From 25386a1a432106064be8f3ae652869c9571aa2c6 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 06:47:17 -0800 Subject: [PATCH 19/36] test(pipeline): name ITL-1366's input as difference e10 (ITL-1360) A declared source slot over a narrower source with one data-tag among two tags: main raises ValueError when the source's rows are rebuilt for its successor; the sync path completes with the rows the bind describes; the async path raises as main does until stage 5. Spec row e10, provisional (coordinator decision 2026-11-22, pending the developer). Co-Authored-By: Claude Opus 5.5 --- .../dev/specs/itl-1347-job-table-transport.md | 3 +- .../test_declared_slot_one_data_tag.py | 93 +++++++++++++++++++ 2 files changed, 95 insertions(+), 1 deletion(-) create mode 100644 tests/test_pipeline/test_declared_slot_one_data_tag.py diff --git a/docs/dev/specs/itl-1347-job-table-transport.md b/docs/dev/specs/itl-1347-job-table-transport.md index 08d27f4ba..430710056 100644 --- a/docs/dev/specs/itl-1347-job-table-transport.md +++ b/docs/dev/specs/itl-1347-job-table-transport.md @@ -509,7 +509,7 @@ with the developer's approval, given row by row. Each row gets its own test: it row, by name. The developer has accepted some behaviours of `main` that are not listed as rows; they are kept as `main` has them, and documented below. -**No row changes a sync-path result, except e9** (provisional, pending the developer). On +**No row changes a sync-path result, except e9 and e10** (provisional, pending the developer). On the sync path the branch equals `main` byte for byte. Stages 1–4 hold this by construction and by L0–L5, and a lemma that fails stops its stage. @@ -522,6 +522,7 @@ and by L0–L5, and a lemma that fails stops its stage. | e7 | What a consumer does after its producer failed (async, failure path) | The producer closes its output in `finally`, so a consumer sees a normal end and may finish, and a `LOG` operator node may store, a partial result before the task group cancels it | Readers raise `UpstreamFailedError` at the failure point instead of seeing a normal end, so no consumer finishes, or stores its result, as if its input were complete. Batches a consumer processed before the failure are still processed, and a streaming node may already have passed them on or a function node stored results for them, as on `main`; there is no rollback. A barrier operator never computes over a partial input. The run raises the producer's own error, as today | A candidate race, to be confirmed with a reproducer in stage 5: a `fail_fast` function node raising on row 3 of 6, feeding a `Select` node in `LOG` mode; check the operator cache after the failed run. If `main` never stores in practice, this row is no difference | filed by the developer only once a test reproduces it | | e8 | Meta columns of an async side-effect node's rows | An async side-effect node passes on and holds the rows it receives as they are, so a computed row keeps its `__computed` meta column (from the cached function pod), and the node's `as_table(all_info=True)` shows it. On sync, its input is rebuilt from rows (`_rows_to_table` drops meta), so the column is absent | Async drops input meta columns as sync does. With table transport this follows from the transport columns, which hold no meta column | A `main` bug: the async and sync paths give the node different columns. Found by the stage 0 harness on `job-speed` 0e15d0db, which does not change side-effect nodes; the stage 0 differential checks it on pinned `main`. Reproducer: a function node (with a result store) feeding a `tap_pod`, async against sync, comparing the side-effect node's `as_table(all_info=True)` columns | approved (developer, 2026-11-22) | | e9 | A sync function node whose output rows disagree on a column's Arrow type | A node with no successor completes the run; its `as_table()` raises `InputValidationError` ("Function node 'double': Rows disagree on the Arrow type of column 'k': int32 and uint32"). A node with a successor fails the run with a bare pyarrow `ArrowInvalid`, raised where the successor's input is rebuilt | The node builds its output stream when it runs (stage 2), so the run fails at the node, once its writes are committed (a failed write is still reported first, as on `main`) and before the node takes the run, with the `InputValidationError` `as_table()` raises (same type and message), with or without a successor; the node then holds no run. What is stored equals `main`'s: the row computed before the disagreement could be seen is stored, as on `main` (2 stored rows before the run, 3 after, on both) | Not a `main` bug to fix: a consequence of building the output stream in `execute`, and for a node with a successor an improvement (`main`'s `ArrowInvalid` names nothing). It arises only from a store written before ITL-928, whose cached rows give a `uint32` tag back as `int32`; such a store must be rebuilt. Reproducer: `tests/test_core/function_pod/test_function_node_arrow_types.py::test_new_rows_over_a_store_written_before_the_fix_raise_naming_the_column` (leaf and with successor) | provisional, coordinator decision 2026-11-22, pending developer | +| e10 | ITL-1366: a declared source slot over a narrower source with one data-tag among two tags | The run raises `ValueError` ("Duplicate column name 'k'") where the source's rows are rebuilt for its successor (`_rows_to_table`: the row's tag and data both hold the data-tag), when exactly one of the two tags is a data-tag and the tags are declared `j, k`; the source node has ended, the successor never starts. The same on the async path | Sync: the source node hands on F of the declared table (`_DeclaredForm.apply` of the bound table, the data-tag once, among the tags) and the run completes with the rows the bind describes. Async: as on `main` until stage 5 | A `main` bug (ITL-1366): the bind is accepted, then the rows cannot be built. Reproducer: `tests/test_pipeline/test_declared_slot_one_data_tag.py` (no, one or both data-tags, both tag orders, sync and async) | provisional, coordinator decision 2026-11-22, pending developer | **Resolved: refusals after rows have flowed (was c, question 9).** The developer's `Rejoin` rule (ITL-1355) removes every data-dependent refusal from `Rejoin`: it checks only what its diff --git a/tests/test_pipeline/test_declared_slot_one_data_tag.py b/tests/test_pipeline/test_declared_slot_one_data_tag.py new file mode 100644 index 000000000..490c5f006 --- /dev/null +++ b/tests/test_pipeline/test_declared_slot_one_data_tag.py @@ -0,0 +1,93 @@ +"""A declared slot over a narrower source with one data-tag among two tags (ITL-1366, e10). + +A source slot declared from a source whose ``x`` is ``int | None``, bound to the same +table with ``x: int`` (a narrower source, given as the declared schema), feeding an +operator. On ``main`` the run raises ``ValueError`` ("Duplicate column name") where the +source's rows are rebuilt for its successor, when exactly one of the two tags is a +data-tag and the tags are declared ``j, k``. On the sync path the branch hands on the +declared table itself (F over ``_DeclaredForm.apply`` of the bound table), and the run +completes with the rows the bind describes (spec row e10; provisional, coordinator +decision 2026-11-22, pending the developer). The async path still carries rows until +ITL-1347 stage 5 and raises as ``main`` does. +""" + +from __future__ import annotations + +from typing import Any + +import pyarrow as pa +import pytest + +from orcapod import PipelineJob +from orcapod.databases import InMemoryArrowDatabase +from orcapod.pipeline import AsyncPipelineOrchestrator +from orcapod.sources import ArrowTableSource + +ROWS = [ + {"j": 3, "k": 5, "x": 1, "y": 7.5}, + {"j": 4, "k": 6, "x": 2, "y": 8.5}, +] + +ROLES: dict[str, bool | tuple[str, ...]] = { + "no_data_tag": True, + "k_data_tag": ("j",), + "j_data_tag": ("k",), + "both_data_tags": (), +} + + +def _source(nullable_x: bool, order: tuple[str, str], roles: Any) -> ArrowTableSource: + table = pa.table( + { + "x": pa.array([1, 2], pa.int64()), + "k": pa.array([5, 6], pa.int64()), + "j": pa.array([3, 4], pa.int64()), + "y": pa.array([7.5, 8.5], pa.float64()), + } + ) + table = table.cast( + pa.schema([f.with_nullable(f.name == "x" and nullable_x) for f in table.schema]) + ) + return ArrowTableSource( + table, tag_columns=list(order), tag_only_columns=roles, source_id="s" + ) + + +def _bound_job(order: tuple[str, str], roles: Any) -> PipelineJob: + """The slot declared with ``x: int | None``, bound to the table with ``x: int``.""" + job = PipelineJob(name="declared_one_data_tag", database=InMemoryArrowDatabase()) + with job: + _source(True, order, roles).select_data_columns(["y", "x"], label="selected") + slot = next(label for label in job.nodes if label != "selected") + job.bind(sources={slot: _source(False, order, roles)}) + return job + + +def _rows(job: PipelineJob) -> list[dict[str, Any]]: + table = job.nodes["selected"].as_table() + return sorted(table.to_pylist(), key=lambda row: row["j"]) + + +@pytest.mark.parametrize("roles", list(ROLES), ids=list(ROLES)) +@pytest.mark.parametrize("order", [("j", "k"), ("k", "j")], ids=["j-k", "k-j"]) +def test_the_sync_run_completes_with_the_rows_the_bind_describes( + order: tuple[str, str], roles: str +) -> None: + """Every arrangement runs on the sync path and gives the bound table's rows.""" + job = _bound_job(order, ROLES[roles]) + job.run() + assert _rows(job) == ROWS + + +@pytest.mark.parametrize("roles", list(ROLES), ids=list(ROLES)) +@pytest.mark.parametrize("order", [("j", "k"), ("k", "j")], ids=["j-k", "k-j"]) +def test_the_async_run_is_as_on_main(order: tuple[str, str], roles: str) -> None: + """The async path carries rows until stage 5: it raises where ``main`` raises.""" + job = _bound_job(order, ROLES[roles]) + raises_on_main = order == ("j", "k") and roles in ("k_data_tag", "j_data_tag") + if raises_on_main: + with pytest.raises(ValueError, match="Duplicate column name"): + job.run(orchestrator=AsyncPipelineOrchestrator()) + else: + job.run(orchestrator=AsyncPipelineOrchestrator()) + assert _rows(job) == ROWS From 6757ed663d2361bb60174df37edb4d15d893ed37 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 07:02:20 -0800 Subject: [PATCH 20/36] fix(source_node): a narrower bind's rows keep main's key order; descriptions follow the rows (ITL-1360) Codex on PR #485, round 2, findings 1 and 5. A narrower source's rows are given as the declared schema one by one, the tag and the data table each through _DeclaredForm.apply, where a tag that is also data takes its place from the declared data order. _row_keys derives the keys by that same apply over zero-row tag and data tables (repeats dropped, missing names appended, for ITL-1366's one data-tag of two: e10), and the bound table is only retyped (_DeclaredForm.retype), since F selects by the keys. L2 sweep over declared layouts, tag orders and data-tag roles against the row path, kept and raw stored. A stream's description takes its data order from its table (keys_of_rows, now in streams.base), so a poller that fetched in another order is described as its rows are. A source-info field's type, like its flag, is decided by the values of a complete table: said in arrow_schema()'s docstring and the spec; L7 leaves both out by name, and pins a poller after a fetch and a value-decided list depth. Co-Authored-By: Claude Opus 5.5 --- .../dev/specs/itl-1347-job-table-transport.md | 10 +- src/orcapod/core/nodes/source_node.py | 116 +++++++++++------ src/orcapod/core/streams/base.py | 38 +++++- .../protocols/core_protocols/streams.py | 10 +- .../test_pipeline/test_narrower_bind_order.py | 120 ++++++++++++++++++ .../test_stream_transport_equivalence.py | 64 +++++++++- 6 files changed, 303 insertions(+), 55 deletions(-) create mode 100644 tests/test_pipeline/test_narrower_bind_order.py diff --git a/docs/dev/specs/itl-1347-job-table-transport.md b/docs/dev/specs/itl-1347-job-table-transport.md index 430710056..3b9203c6a 100644 --- a/docs/dev/specs/itl-1347-job-table-transport.md +++ b/docs/dev/specs/itl-1347-job-table-transport.md @@ -194,9 +194,13 @@ A run checks its sources first (ITL-1102), which polls them. **ITL-1307 later.** When `Schema` carries its Arrow schema, `arrow_schema()` reads the two schemas plus the system-tag and source-info fields, in one place (`StreamBase`). -Two exceptions keep today's bytes: -- **Source-info nullability** is decided by a complete Arrow table's values (F step 5). - `arrow_schema()` states those fields nullable (question 5). +Three exceptions keep today's bytes: +- **Source-info and system-tag nullability** is decided by a complete Arrow table's values + (F step 5). `arrow_schema()` states those fields nullable (question 5). +- **Source-info types** are decided by a complete Arrow table's tokens, as each row types + its tokens from their values (`_type_source_info_by_values`): a list of `None` or of + empty lists shows fewer list levels than its column declares. `arrow_schema()` states the + declared token type; consumers must not rely on it (Codex on PR #485). - **`null` columns.** Rows carry `large_string`, and a zero-row Arrow table carries `null`, as today (ITL-1319). diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index 2fdfccd1d..7c1f31ae1 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -23,14 +23,15 @@ from orcapod.config import OrcapodConfig from orcapod.core.base import TraceableBase from orcapod.core.datagrams import Data, Tag -from orcapod.core.data_tags import data_tag_names from orcapod.core.operators.drop_nulls import _without_none # pyright: ignore[reportPrivateUsage] # DropNulls' rule for removing None from a type, shared, never copied from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.core.streams.base import ( ZERO_ROW_INPUT_COLUMNS, + keys_of_rows, stream_arrow_schema, schema_requires_io, typed_arrow_schemas, + typed_zero_row_input, typed_zero_row_table, ) from orcapod.core.streams.view import ( @@ -154,6 +155,24 @@ def apply(self, table: pa.Table) -> pa.Table: source-info columns in declared order within the positions each group holds. """ + table = self.retype(table) + return table.select(self._declared_positions(table.column_names)) + + def retype(self, table: pa.Table) -> pa.Table: + """Return *table*'s arrays under the declared fields, in *table*'s column order. + + The fields ``apply`` gives (the columns in ``nullable`` flagged nullable, the + columns in ``renames`` renamed), without placing the columns: a table whose + columns are then selected by the rows' keys (the row-built form, ITL-1347) + needs no placement, and a table holding a data-tag once, among the tags, would + lose a column to a placement made for a row's separate tag and data tables. + + Args: + table: Rows read from the bound source. + + Returns: + The same arrays under the declared fields. + """ schema = table.schema for position, field in enumerate(table.schema): if field.name in self.nullable: @@ -162,8 +181,7 @@ def apply(self, table: pa.Table) -> pa.Table: field = field.with_name(self.renames[field.name]) schema = schema.set(position, field) # pyright: ignore[reportUnknownMemberType] # stubs leave Field unparametrized # Same arrays under the declared fields: no cast, so no value or type changes. - table = pa.Table.from_arrays(table.columns, schema=schema) - return table.select(self._declared_positions(table.column_names)) + return pa.Table.from_arrays(table.columns, schema=schema) def _declared_positions(self, names: list[str]) -> list[int]: """Return the column positions of *names* with each group in declared order. @@ -185,30 +203,16 @@ def _declared_positions(self, names: list[str]) -> list[int]: return order -def _keys_of_rows( - table: pa.Table, keys: tuple[Sequence[str], Sequence[str]] -) -> tuple[tuple[str, ...], tuple[str, ...]]: - """Return the tag and data keys a source's rows have, given its table and ``keys()``. - - A source's rows come from a stream over its table (``ArrowTableStream``), whose rows - list their tags in the stream's tag order and their data with the data-tags first, - in tag order, then the other data columns in the table's order. A source whose - ``keys()`` states its declared order (a ``PollingSource`` whose fetched table has - another column order) has rows in the table's order all the same, as a table built - from its rows does (Codex on PR #485). - - Args: - table: The source's table, as its rows are read from it. - keys: The source's ``keys()``. +def _each_once(order: Sequence[str], names: Sequence[str]) -> tuple[str, ...]: + """``order`` with each of ``names`` once: repeats dropped, missing names appended. - Returns: - The tag keys, and the data keys in the order of the rows. + ``_DeclaredForm.apply`` places a row's columns; with one data-tag among two tags it + can place a column twice and lose another (ITL-1366, where ``main`` then fails to + build the rows). The keys keep its order and hold each name once (spec row e10). """ - tag_keys, data_keys = (tuple(keys[0]), tuple(keys[1])) - data_tags = data_tag_names(tag_keys, data_keys) - data = set(data_keys) - set(tag_keys) - in_table = tuple(name for name in table.column_names if name in data) - return tag_keys, (*data_tags, *in_table) + wanted = set(names) + kept = tuple(dict.fromkeys(n for n in order if n in wanted)) + return (*kept, *(n for n in names if n not in kept)) def _system_tag_columns( @@ -1220,7 +1224,7 @@ def _rows_table(self) -> tuple[pa.Table, tuple[tuple[str, ...], tuple[str, ...]] """ stream = cast("StreamProtocol", self) table = stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS) - return table, _keys_of_rows(table, stream.keys()) + return table, keys_of_rows(table, stream.keys()) def arrow_schema(self) -> pa.Schema: """The Arrow schema of the columns this stream passes between job nodes. @@ -1742,23 +1746,54 @@ def identity_structure(self) -> Any: return self._bound_source.identity_structure() return super().identity_structure() - def _row_keys(self) -> tuple[tuple[str, ...], tuple[str, ...]]: - """The tag and data keys of this node's rows, known without reading a row. + def _row_keys( + self, table: pa.Table | None = None + ) -> tuple[tuple[str, ...], tuple[str, ...]]: + """The tag and data keys of this node's rows, as ``iter_data`` gives them. + + The bound source's rows have the keys of its table (``keys_of_rows``). A + narrower source's rows are given as the declared schema one by one + (``_declared_row``: its tag table and its data table each through + ``_DeclaredForm.apply``), so their keys are those of a zero-row tag table and a + zero-row data table of the bound source through the same ``apply``: a tag that + is also data takes its place from the declared data order, as on ``main``. + + Args: + table: The bound source's table (``ZERO_ROW_INPUT_COLUMNS``, with or + without rows). Default: its typed zero-row table, which reads no row; + the declared keys when it cannot say its types without rows. - The bound source's keys; for a narrower source given as the declared schema - (``_DeclaredForm``), the declared order with the data-tags first among the data - keys, as the stream over its table lists them (``_declared_stream``); the slot's - own when unbound. + Returns: + The tag keys and the data keys of the rows. """ if self._bound_source is None: return self.keys() + bound_keys = self._bound_source.keys() + if table is None: + table = typed_zero_row_input(self._bound_source) + if table is None: + return self.keys() + rows_keys = keys_of_rows(table, bound_keys) form = self._declared_form - if form is not None: - data_tags = data_tag_names(form.tag_order, form.data_order) - others = tuple(n for n in form.data_order if n not in data_tags) - return form.tag_order, (*data_tags, *others) - tag_keys, data_keys = self._bound_source.keys() - return tuple(tag_keys), tuple(data_keys) + if form is None: + return rows_keys + tag_keys, data_keys = rows_keys + names = table.column_names + system_tags = [n for n in names if n.startswith(constants.SYSTEM_TAG_PREFIX)] + source_info = [n for n in names if n.startswith(constants.SOURCE_PREFIX)] + empty = table.slice(0, 0) + tag_order = form.apply(empty.select([*tag_keys, *system_tags])).column_names + data_order = form.apply(empty.select([*data_keys, *source_info])).column_names + return ( + _each_once( + [n for n in tag_order if not n.startswith(constants.SYSTEM_TAG_PREFIX)], + tag_keys, + ), + _each_once( + [n for n in data_order if not n.startswith(constants.SOURCE_PREFIX)], + data_keys, + ), + ) def _rows_table(self) -> tuple[pa.Table, tuple[tuple[str, ...], tuple[str, ...]]]: """The table of this node's rows (``iter_data``) and the rows' keys. @@ -1778,9 +1813,10 @@ def _rows_table(self) -> tuple[pa.Table, tuple[tuple[str, ...], tuple[str, ...]] "Call job.bind(sources={'': source}) before running." ) table = self._bound_source.as_table(columns=ZERO_ROW_INPUT_COLUMNS) + keys = self._row_keys(table) if self._declared_form is None: - return table, _keys_of_rows(table, self._bound_source.keys()) - return self._declared_form.apply(table), self._row_keys() + return table, keys + return self._declared_form.retype(table), keys def iter_data(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: """Delegate to concrete source, or raise if unbound. diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py index f396b9c4f..d081777fe 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -21,6 +21,7 @@ import pyarrow as pa from orcapod.core.base import TraceableBase +from orcapod.core.data_tags import data_tag_names from orcapod.core.streams.view import ( SCHEMA_NEEDS_POLL_NOTE, ViewStatus, @@ -333,6 +334,32 @@ def row_built_names( return [*tag_keys, *system_tags, *data, *source_info] +def keys_of_rows( + table: pa.Table, keys: tuple[Sequence[str], Sequence[str]] +) -> tuple[tuple[str, ...], tuple[str, ...]]: + """Return the tag and data keys a source's rows have, given its table and ``keys()``. + + A source's rows come from a stream over its table (``ArrowTableStream``), whose rows + list their tags in the stream's tag order and their data with the data-tags first, + in tag order, then the other data columns in the table's order. A source whose + ``keys()`` states its declared order (a ``PollingSource`` whose fetched table has + another column order) has rows in the table's order all the same, as a table built + from its rows does (Codex on PR #485). + + Args: + table: The source's table, as its rows are read from it. + keys: The source's ``keys()``. + + Returns: + The tag keys, and the data keys in the order of the rows. + """ + tag_keys, data_keys = (tuple(keys[0]), tuple(keys[1])) + data_tags = data_tag_names(tag_keys, data_keys) + data = set(data_keys) - set(tag_keys) + in_table = tuple(name for name in table.column_names if name in data) + return tag_keys, (*data_tags, *in_table) + + def stream_arrow_schema( stream: object, keys: tuple[Sequence[str], Sequence[str]] | None = None ) -> pa.Schema: @@ -346,7 +373,10 @@ def stream_arrow_schema( stream that cannot type itself without rows answers with its Python schema converted by its data context (``arrow_types_declared`` is then false). Each system-tag and source-info field is stated nullable: a table decides its flag from - its values (F's last step). A ``null`` column keeps the zero-row ``null`` type; rows + its values (F's last step). A source-info field's type is stated as the declared + token type; a complete table decides it from its tokens + (``StaticOutputOperatorPod._type_source_info_by_values``), so consumers must not + rely on it. A ``null`` column keeps the zero-row ``null`` type; rows carry ``large_string`` (ITL-1319). ITL-1307 later reads it from ``Schema`` instead, here. @@ -361,8 +391,7 @@ def stream_arrow_schema( from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod typed = cast(StreamProtocol, stream) - if keys is None: - keys = typed.keys() + given_keys = keys table = typed_zero_row_input(stream) if table is None: # Only what the stream declares: asking for its source-info columns would make @@ -377,6 +406,9 @@ def stream_arrow_schema( pa.field(f"{constants.SOURCE_PREFIX}{name}", pa.large_string()), pa.array([], pa.large_string()), ) + # The rows' keys: the data in the order of the stream's table (a poller that + # fetched its columns in another order than it declares lists them so). + keys = given_keys if given_keys is not None else keys_of_rows(table, typed.keys()) names = row_built_names(table.column_names, keys) schema = row_built_provenance(table.select(names)).schema prefixes = (constants.SYSTEM_TAG_PREFIX, constants.SOURCE_PREFIX) diff --git a/src/orcapod/protocols/core_protocols/streams.py b/src/orcapod/protocols/core_protocols/streams.py index 5dff04d96..a5f544601 100644 --- a/src/orcapod/protocols/core_protocols/streams.py +++ b/src/orcapod/protocols/core_protocols/streams.py @@ -178,10 +178,12 @@ def arrow_schema(self) -> "pa.Schema": tags, system tags, data, source info; data and source info in data-key order), with the Arrow types, nullability and field metadata of the rows; no context and no meta column (ITL-1347). Known without reading, computing or polling a row. - Two exceptions keep today's bytes: system-tag and source-info fields are stated - nullable (a table decides their flags from its values), and a ``null`` column - keeps the ``null`` type a zero-row table has (rows carry ``large_string``; - ITL-1319). + Three properties are decided by the values of a complete table, not by the + description: whether a system-tag or source-info field is nullable (stated + nullable here), and a source-info field's type (stated as the declared token + type; a list of ``None`` or of empty lists shows fewer levels, so consumers must + not rely on it). And a ``null`` column keeps the ``null`` type a zero-row table + has (rows carry ``large_string``; ITL-1319). Returns: The declared Arrow schema. diff --git a/tests/test_pipeline/test_narrower_bind_order.py b/tests/test_pipeline/test_narrower_bind_order.py new file mode 100644 index 000000000..a754b8647 --- /dev/null +++ b/tests/test_pipeline/test_narrower_bind_order.py @@ -0,0 +1,120 @@ +"""A narrower bind hands on its rows in their order (ITL-1360, L2; Codex on PR #485). + +A source slot declared from a source whose ``x`` is ``int | None``, bound to the same +columns with ``x: int`` (a narrower source, given as the declared schema), feeding a +``Batch`` node in ``LOG`` mode. The source node's output is F of the bound table with +the keys its rows have (``SourceJobNode._row_keys``: ``_DeclaredForm.apply`` of a +row's tag and data tables, as each row is given). Every pairing of declared layout, tag +order and data-tag roles must keep and store what the row path keeps and stores: the +same run with the source's output built from its rows +(``StaticOutputOperatorPod._materialize_upstream``), as on ``main``. The arrangements +where the row path raises (one data-tag of two, ITL-1366) are spec row e10, tested in +``test_declared_slot_one_data_tag.py``. +""" + +from __future__ import annotations + +import itertools +from typing import Any + +import pyarrow as pa +import pytest + +from orcapod import PipelineJob +from orcapod.core.nodes.source_node import SourceNodeBase +from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod +from orcapod.databases import InMemoryArrowDatabase +from orcapod.operators import Batch +from orcapod.sources import ArrowTableSource +from orcapod.types import CacheMode + +ROLES: dict[str, bool | tuple[str, ...]] = { + "no_data_tag": True, + "a_data_tag": ("b",), + "b_data_tag": ("a",), + "both_data_tags": (), +} + + +def _source( + nullable_x: bool, layout: tuple[str, ...], tag_order: tuple[str, str], roles: Any +) -> ArrowTableSource: + columns = { + "x": pa.array([1, 2], pa.int64()), + "a": pa.array([5, 6], pa.int64()), + "b": pa.array([3, 4], pa.int64()), + } + table = pa.table({name: columns[name] for name in layout}) + table = table.cast( + pa.schema([f.with_nullable(f.name == "x" and nullable_x) for f in table.schema]) + ) + return ArrowTableSource( + table, tag_columns=list(tag_order), tag_only_columns=roles, source_id="s" + ) + + +def _run( + layout: tuple[str, ...], tag_order: tuple[str, str], roles: Any +) -> tuple[list[str], pa.Schema]: + """Run the job; return the batch node's kept columns and its raw stored schema.""" + database = InMemoryArrowDatabase() + job = PipelineJob(name="narrower_bind_order", database=database) + with job: + Batch(batch_size=2)(_source(True, layout, tag_order, roles), label="batched") + job.nodes["batched"].attach_databases( + pipeline_database=database.at("log"), cache_mode=CacheMode.LOG + ) + slot = next(label for label in job.nodes if label != "batched") + job.bind(sources={slot: _source(False, ("x", "a", "b"), tag_order, roles)}) + job.run() + node = job.nodes["batched"] + kept = node.as_table(columns={"source": True}).column_names + stored = node.get_all_records(columns={"source": True}) + assert stored is not None + return kept, stored.schema + + +def _row_path(monkeypatch: pytest.MonkeyPatch) -> None: + """Make every source node hand on its rows rebuilt, as on ``main``.""" + + def execute(self: Any, *, observer: Any = None) -> Any: + if observer is not None: + observer.on_node_start(self.label, self.content_hash().to_string()) + out = StaticOutputOperatorPod._materialize_upstream( + list(self.iter_data()), self + ) # pyright: ignore[reportPrivateUsage] # the row path + if observer is not None: + observer.on_node_end(self.label, self.content_hash().to_string()) + return out + + monkeypatch.setattr(SourceNodeBase, "execute", execute) + + +def _raises_on_the_row_path(roles: str) -> bool: + """The row path raises only with one data-tag of two (ITL-1366, e10).""" + return roles in ("a_data_tag", "b_data_tag") + + +@pytest.mark.parametrize("roles", list(ROLES), ids=list(ROLES)) +@pytest.mark.parametrize("tag_order", [("a", "b"), ("b", "a")], ids=["a-b", "b-a"]) +@pytest.mark.parametrize( + "layout", list(itertools.permutations(("a", "b", "x"))), ids="".join +) +def test_a_narrower_bind_keeps_and_stores_as_the_row_path( + layout: tuple[str, ...], + tag_order: tuple[str, str], + roles: str, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Kept columns and the raw stored schema equal the row path's, in order.""" + got = _run(layout, tag_order, ROLES[roles]) + with monkeypatch.context() as patch: + _row_path(patch) + try: + expected = _run(layout, tag_order, ROLES[roles]) + except ValueError as error: + assert "Duplicate column name" in str(error) + assert _raises_on_the_row_path(roles) + pytest.skip("the row path raises here: spec row e10") + assert got[0] == expected[0] + assert got[1].equals(expected[1], check_metadata=True) diff --git a/tests/test_pipeline/test_stream_transport_equivalence.py b/tests/test_pipeline/test_stream_transport_equivalence.py index 04977f91d..b9652d0aa 100644 --- a/tests/test_pipeline/test_stream_transport_equivalence.py +++ b/tests/test_pipeline/test_stream_transport_equivalence.py @@ -42,7 +42,7 @@ from orcapod.errors import ProvisionalHashWarning from orcapod.pipeline import AsyncPipelineOrchestrator from orcapod.pipeline.observer import NoOpObserver -from orcapod.operators import MergeJoin, Rejoin, SelectDataColumns +from orcapod.operators import Batch, MergeJoin, Rejoin, SelectDataColumns from orcapod.side_effects import SideEffectJobNode from orcapod.system_constants import constants from orcapod.types import CacheMode @@ -240,15 +240,20 @@ def test_a_held_node_hands_on_the_stream_built_from_its_rows( def _without_exceptions(schema: pa.Schema) -> list[tuple[str, Any, bool, Any]]: """Fields in order as (name, type, nullable, metadata), the spec's exceptions applied. - A system-tag or source-info field's flag is decided by a table's values (stated - nullable), and a ``null`` column is ``large_string`` in rows (ITL-1319). Column - order counts on the sync path (Codex on PR #485). + Decided by the values of a complete table, not by the description: a system-tag or + source-info field's flag (stated nullable) and a source-info field's type (left out). + A ``null`` column is ``large_string`` in rows (ITL-1319). Column order counts on the + sync path (Codex on PR #485). """ prefixes = (constants.SYSTEM_TAG_PREFIX, constants.SOURCE_PREFIX) return [ ( field.name, - pa.large_string() if pa.types.is_null(field.type) else field.type, + None + if field.name.startswith(constants.SOURCE_PREFIX) + else pa.large_string() + if pa.types.is_null(field.type) + else field.type, True if field.name.startswith(prefixes) else field.nullable, field.metadata, ) @@ -544,3 +549,52 @@ def test_an_operator_stream_declares_its_tags_in_its_rows_order() -> None: stream = SelectDataColumns(["x"])(source) built, _, _ = StaticOutputOperatorPod._rows_to_table(list(stream.iter_data())) # pyright: ignore[reportPrivateUsage] # the rows' order assert stream.arrow_schema().names[:2] == built.column_names[:2] + + +@pytest.mark.filterwarnings("ignore::orcapod.errors.ProvisionalHashWarning") +def test_a_poller_that_fetched_describes_its_rows_order() -> None: + """L7: after a fetch in another order than declared, the description follows the rows. + + A poller declaring ``k, j, b, a`` that fetched ``j, k, a, b`` lists its data as its + rows do (Codex on PR #485). + """ + poller = _poller(("j", "k", "a", "b")) + rows = list(poller.iter_data()) + built, _, _ = StaticOutputOperatorPod._rows_to_table(rows) # pyright: ignore[reportPrivateUsage] # the rows' order + assert poller.arrow_types_declared + assert _without_exceptions(poller.arrow_schema()) == _without_exceptions( + built.schema + ) + + +def test_a_value_decided_source_info_depth_is_a_named_exception() -> None: + """L7: ``Batch`` over null list tokens; the description and the rows agree but for it. + + The rows give ``[None, None]`` one list level (``large_list``); the + description states the declared token type. A source-info type is decided by the + values of a complete table and is one of the description's named exceptions. + """ + from orcapod.core.streams import ArrowTableStream + from orcapod.sources import DictSource + + table = DictSource( + [{"k": 1, "x": 1}, {"k": 2, "x": 2}], + tag_columns=["k"], + tag_only_columns=True, + source_id="s", + ).as_table(columns={"source": True, "system_tags": True}) + position = table.schema.get_field_index("_source_x") + strings = pa.large_list(pa.large_string()) + raw = ArrowTableStream( + table.set_column( + position, + pa.field("_source_x", strings, nullable=True), + pa.array([None, None], strings), + ), + tag_columns=["k"], + ) + batched = Batch(batch_size=2)(raw) + built, _, _ = StaticOutputOperatorPod._rows_to_table(list(batched.iter_data())) # pyright: ignore[reportPrivateUsage] # the rows + declared = batched.arrow_schema() + assert declared.field("_source_x").type != built.schema.field("_source_x").type + assert _without_exceptions(declared) == _without_exceptions(built.schema) From b5f5a185e1793539355a35a39a351fc855e9e89a Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 07:03:23 -0800 Subject: [PATCH 21/36] fix(pipeline): held streams built when read and not kept; membership builds nothing (ITL-1360) Codex on PR #485, round 2, findings 2, 6 and 7. A run plan's held streams are StreamsOnRead (keep=False): built when the sync orchestrator reaches the node, never while planning (an async run over a held node whose rows cannot make one table then runs as on main), and released once the node's successors ran. Membership, length and iteration of StreamsOnRead never build a stream. Co-Authored-By: Claude Opus 5.5 --- src/orcapod/pipeline/node_run.py | 16 +-- src/orcapod/pipeline/result.py | 31 +++-- .../test_function_node_arrow_types.py | 36 ++++++ .../test_held_streams_on_read.py | 112 ++++++++++++++++++ 4 files changed, 179 insertions(+), 16 deletions(-) create mode 100644 tests/test_pipeline/test_held_streams_on_read.py diff --git a/src/orcapod/pipeline/node_run.py b/src/orcapod/pipeline/node_run.py index ad0ab8561..f39f403c6 100644 --- a/src/orcapod/pipeline/node_run.py +++ b/src/orcapod/pipeline/node_run.py @@ -14,7 +14,7 @@ from __future__ import annotations -from collections.abc import Iterable, Iterator, Sequence +from collections.abc import Iterable, Iterator, Mapping, Sequence from dataclasses import dataclass from typing import TYPE_CHECKING, Any @@ -25,6 +25,7 @@ run_node_summaries, ) from orcapod.pipeline.restrictions import restrictions_in_force, source_name +from orcapod.pipeline.result import StreamsOnRead from orcapod.utils.database_errors import flush_best_effort if TYPE_CHECKING: @@ -251,7 +252,7 @@ class RunPlan: them (a source slot is read; any other one is held). held: The output stream of each held node of ``dag``: of its current run, or of a stream outside the job; it feeds the nodes after it as if the node had - just run (the sync orchestrator). + just run (the sync orchestrator). Built when read (``StreamsOnRead``). held_rows: The rows of each held node, as the plan took them; ``held`` is built from them. The async orchestrator sends them (it carries rows until ITL-1347 stage 5). @@ -261,7 +262,7 @@ class RunPlan: """ dag: Any - held: dict[Any, Any] + held: Mapping[Any, Any] to_run: list[Any] held_counts: dict[Any, int] held_rows: dict[Any, list[Any]] @@ -345,10 +346,11 @@ def is_source(node: Any) -> bool: for node in included if not any(node is r for r in to_run) and not is_source(node) } - held = { - node: StaticOutputOperatorPod._materialize_upstream(rows, node) - for node, rows in held_rows.items() - } + # Built when the sync orchestrator reaches the node, never while planning (an + # async run reads only the rows), and not kept by the plan (ITL-1360). + held = StreamsOnRead( + held_rows, StaticOutputOperatorPod._materialize_upstream, keep=False + ) # Counted from what each node holds: iterating an operator's rows would build a # (Tag, Data) pair per row only to count them (ITL-1351). held_counts = {node: node.held_row_count() for node in current} diff --git a/src/orcapod/pipeline/result.py b/src/orcapod/pipeline/result.py index bb117de2d..c0a95a4a7 100644 --- a/src/orcapod/pipeline/result.py +++ b/src/orcapod/pipeline/result.py @@ -11,34 +11,47 @@ class StreamsOnRead(Mapping[Any, "StreamProtocol"]): - """Each node's output stream, built when it is first read. + """Each node's output stream, built from its rows when it is read. The async orchestrator collects each node's rows as they are sent; a node's stream - is built from them (``build``) the first time it is read, and kept. A run whose - rows cannot make one table (rows of a store written before ITL-928) therefore - finishes, as it does on ``main``, and only reading that node's output raises, as - reading its rows as a table does (ITL-1360). + is built from them (``build``) when it is read. A run whose rows cannot make one + table (rows of a store written before ITL-928) therefore finishes, as it does on + ``main``, and only reading that node's output raises, as reading its rows as a + table does (ITL-1360). Membership, length and iteration never build a stream. A run + plan's held streams are built the same way, when the sync orchestrator reaches the + node, and are not kept (``keep=False``): the orchestrator drops each one once its + successors have run. """ def __init__( self, rows: Mapping[Any, Any], build: Callable[[Any, Any], "StreamProtocol"], + *, + keep: bool = True, ) -> None: """Hold each node's rows and how a stream is built from them. Args: - rows: Each node's collected rows. + rows: Each node's rows. build: Builds a node's stream from its rows, given ``(rows, node)``. + keep: Keep a stream once built, so a second read returns it again. """ self._rows = dict(rows) self._build = build + self._keep = keep self._built: dict[Any, StreamProtocol] = {} def __getitem__(self, node: Any) -> "StreamProtocol": - if node not in self._built: - self._built[node] = self._build(self._rows[node], node) - return self._built[node] + if node in self._built: + return self._built[node] + stream = self._build(self._rows[node], node) + if self._keep: + self._built[node] = stream + return stream + + def __contains__(self, node: object) -> bool: + return node in self._rows def __iter__(self) -> Iterator[Any]: return iter(self._rows) diff --git a/tests/test_core/function_pod/test_function_node_arrow_types.py b/tests/test_core/function_pod/test_function_node_arrow_types.py index 56cc00a5d..4d27611ef 100644 --- a/tests/test_core/function_pod/test_function_node_arrow_types.py +++ b/tests/test_core/function_pod/test_function_node_arrow_types.py @@ -421,3 +421,39 @@ def test_an_async_run_over_a_store_written_before_the_fix_finishes( assert len(list(node.iter_data())) == 3 with pytest.raises(InputValidationError, match="'k'"): node.as_table() + + +def test_a_second_async_run_holds_the_node_and_sends_its_rows( + tmp_path: pathlib.Path, +) -> None: + """The plan builds no held stream for an async run: it sends the held rows as on main. + + Over a store written before ITL-928, the held ``double`` holds rows that cannot + make one table; a second async run (``increment`` cleared) holds it and sends its + three rows on, as on ``main`` (Codex on PR #485, round 2). + """ + from orcapod.pipeline import AsyncPipelineOrchestrator + from orcapod.pipeline.observer import NoOpObserver + + class DataStarts(NoOpObserver): + def __init__(self) -> None: + self.count = 0 + + def contextualize(self, *identity_path: str) -> DataStarts: + return self + + def on_data_start(self, node_label: str, tag: Any, data: Any) -> None: + if node_label == "increment": + self.count += 1 + + _build( + DeltaTableDatabase(tmp_path), _source_table("uint32").slice(0, 2), chained=True + ).run() + _as_written_before_the_fix(tmp_path) + job = _build(DeltaTableDatabase(tmp_path), _source_table("uint32"), chained=True) + job.run(orchestrator=AsyncPipelineOrchestrator()) + job.nodes["increment"].clear_cache() + observer = DataStarts() + summary = job.run(orchestrator=AsyncPipelineOrchestrator(), observer=observer) + assert summary.nodes["double"].held == 3 + assert observer.count == 3 diff --git a/tests/test_pipeline/test_held_streams_on_read.py b/tests/test_pipeline/test_held_streams_on_read.py new file mode 100644 index 000000000..99c031830 --- /dev/null +++ b/tests/test_pipeline/test_held_streams_on_read.py @@ -0,0 +1,112 @@ +"""Held streams and async outputs are built when read (ITL-1360; Codex on PR #485). + +A run plan's held streams (``RunPlan.held``) and the async orchestrator's +``node_outputs`` are ``StreamsOnRead``: a node's stream is built from its rows when it +is read. Membership, length and iteration never build one; the plan keeps no held +stream it has built, so the sync orchestrator releases it once its successors ran. +""" + +from __future__ import annotations + +import gc +import weakref +from typing import Any + +import pytest + +from orcapod import PipelineJob, function_pod +from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod +from orcapod.databases import InMemoryArrowDatabase +from orcapod.pipeline.observer import NoOpObserver +from orcapod.pipeline.result import StreamsOnRead +from orcapod.sources import DictSource + + +def test_membership_length_and_iteration_build_nothing() -> None: + """``in``, ``len`` and iteration read the nodes only; reading a value builds it.""" + + def build(rows: Any, node: Any) -> Any: + raise AssertionError(f"built {node}") + + outputs = StreamsOnRead({"a": [], "b": []}, build) + assert "a" in outputs + assert "c" not in outputs + assert len(outputs) == 2 + assert list(outputs) == ["a", "b"] + with pytest.raises(AssertionError, match="built a"): + _ = outputs["a"] + + +def test_a_kept_stream_is_built_once_and_an_unkept_one_each_read() -> None: + built: list[Any] = [] + + def build(rows: Any, node: Any) -> Any: + built.append(node) + return object() + + kept = StreamsOnRead({"a": []}, build) + assert kept["a"] is kept["a"] + unkept = StreamsOnRead({"a": []}, build, keep=False) + _ = unkept["a"] + _ = unkept["a"] + assert built == ["a", "a", "a"] + + +@function_pod(output_keys="y") +def step(x: int) -> int: + return x + 1 + + +def test_a_held_stream_is_released_once_its_successors_ran( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """``source -> a -> b -> c -> d`` with ``a`` held: its stream is gone when ``c`` starts.""" + job = PipelineJob(name="held_lifetime", database=InMemoryArrowDatabase()) + with job: + source = DictSource( + [{"k": i, "x": i} for i in range(3)], + tag_columns=["k"], + tag_only_columns=True, + source_id="s", + ) + a = step.pod(source, label="a") + b = step.pod(a.map_data({"y": "x"}), label="b") + c = step.pod(b.map_data({"y": "x"}), label="c") + step.pod(c.map_data({"y": "x"}), label="d") + job.run() + for label in ("b", "c", "d"): + job.nodes[label].clear_cache() + for node in job.nodes.values(): + if node.label.startswith("MapData"): + node.clear_cache() + + held: list[weakref.ref[Any]] = [] + original = StaticOutputOperatorPod._materialize_upstream # pyright: ignore[reportPrivateUsage] # the held stream's build + + def materialize(rows: Any, upstream: Any, **kwargs: Any) -> Any: + stream = original(rows, upstream, **kwargs) + if getattr(upstream, "label", None) == "a": + held.append(weakref.ref(stream)) + return stream + + monkeypatch.setattr( + StaticOutputOperatorPod, "_materialize_upstream", staticmethod(materialize) + ) + + alive_at_c: list[bool] = [] + + class AtC(NoOpObserver): + def contextualize(self, *identity_path: str) -> AtC: + return self + + def on_node_start( + self, node_label: str, node_hash: str, tag_schema: Any = None + ) -> None: + if node_label == "c": + gc.collect() + alive_at_c.append(any(ref() is not None for ref in held)) + + summary = job.run(observer=AtC(), materialize_results=False) + assert summary.nodes["a"].held == 3 + assert held + assert alive_at_c == [False] From c6c47aab98ad9550429c1a191dd4ee712a20e63f Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 07:04:01 -0800 Subject: [PATCH 22/36] fix(streams): an undeclared poller that has not polled is described with no column (ITL-1360) Codex on PR #485, round 2, finding 3. A stream whose schema is known only by polling (schema_requires_io) is described with no column, as a head shows it: no fetch, no modified-time change, arrow_types_declared stays false. Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/streams/base.py | 9 ++++- .../test_stream_transport_equivalence.py | 39 +++++++++++++++++++ 2 files changed, 47 insertions(+), 1 deletion(-) diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py index d081777fe..dac45879a 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -371,7 +371,9 @@ def stream_arrow_schema( (``row_built_names``: user tags, system tags, data, source info, data and source info in data-key order), with no context and no meta column. A stream that cannot type itself without rows answers with its Python schema - converted by its data context (``arrow_types_declared`` is then false). Each + converted by its data context (``arrow_types_declared`` is then false), and one + whose schema is known only by polling (nothing declared, nothing polled: + ``schema_requires_io``) answers with no column. Each system-tag and source-info field is stated nullable: a table decides its flag from its values (F's last step). A source-info field's type is stated as the declared token type; a complete table decides it from its tokens @@ -393,6 +395,11 @@ def stream_arrow_schema( typed = cast(StreamProtocol, stream) given_keys = keys table = typed_zero_row_input(stream) + if table is None and schema_requires_io(stream, ColumnConfig(system_tags=True)): + # Nothing declared, nothing polled (a poller with no declared schema): the + # columns are known only from rows, and a description never polls. No column, + # as a head says (``SCHEMA_NEEDS_POLL_NOTE``); ``arrow_types_declared`` is false. + return pa.schema([]) if table is None: # Only what the stream declares: asking for its source-info columns would make # a source that has not polled poll (a description never computes, polls or diff --git a/tests/test_pipeline/test_stream_transport_equivalence.py b/tests/test_pipeline/test_stream_transport_equivalence.py index b9652d0aa..f13f9dc89 100644 --- a/tests/test_pipeline/test_stream_transport_equivalence.py +++ b/tests/test_pipeline/test_stream_transport_equivalence.py @@ -598,3 +598,42 @@ def test_a_value_decided_source_info_depth_is_a_named_exception() -> None: declared = batched.arrow_schema() assert declared.field("_source_x").type != built.schema.field("_source_x").type assert _without_exceptions(declared) == _without_exceptions(built.schema) + + +@pytest.mark.filterwarnings("ignore::orcapod.errors.ProvisionalHashWarning") +def test_describing_an_undeclared_poller_that_has_not_polled_reads_nothing() -> None: + """L7: a poller with no declared schema is described with no column, and not polled. + + Its columns are known only from rows; the description never fetches, its modified + time does not move and ``arrow_types_declared`` stays false (Codex on PR #485). + """ + from orcapod.core.sources import PollingSource + from tests.test_hashing.test_logical_type_forms import ( + _TableImpl, # pyright: ignore[reportPrivateUsage] # the one test polling implementation + ) + + fetches: list[int] = [] + + class Undeclared(_TableImpl): + async def fetch(self, cursor: Any = None) -> Any: + fetches.append(1) + return await super().fetch(cursor) + + def schema(self) -> Any: + return None + + table = pa.table( + {"k": pa.array(["1"], pa.large_string()), "a": pa.array([1], pa.int64())} + ) + poller = PollingSource( + Undeclared(table, table.schema), + tag_columns=["k"], + record_id_columns=["k"], + source_id="undeclared", + ) + modified = poller.last_modified + assert poller.arrow_schema() == pa.schema([]) + assert poller.arrow_schema() == pa.schema([]) + assert fetches == [] + assert poller.last_modified == modified + assert not poller.arrow_types_declared From 5a1725e4952a460a1d023f36d06c7474cc106eec Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 07:05:00 -0800 Subject: [PATCH 23/36] fix(pipeline): any failure of F's whole-table build falls back to the rows (ITL-1360) Codex on PR #485, round 2, finding 4. RowBuiltFormUnavailable is the one signal that a node's output must come from its rows: raised by _row_built_form for tokens of two types (SourceInfoTypesDisagree, now its subclass) and for any Arrow error of the whole-table build. Source and operator nodes catch it and build their rows, which raise main's error after main's observer events. Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/nodes/operator_node.py | 6 +-- src/orcapod/core/nodes/source_node.py | 4 +- .../core/operators/static_output_pod.py | 43 +++++++++++++------ .../operators/test_row_built_form.py | 16 +++++++ 4 files changed, 51 insertions(+), 18 deletions(-) diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index 36904bf59..be0bd1162 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -39,7 +39,7 @@ from orcapod.channels import Channel, ChannelClosed, ReadableChannel, WritableChannel from orcapod.config import OrcapodConfig from orcapod.core.operators.static_output_pod import ( - SourceInfoTypesDisagree, + RowBuiltFormUnavailable, StaticOutputOperatorPod, ) from orcapod.core.streams.arrow_table_stream import ArrowTableStream @@ -1697,7 +1697,7 @@ def execute( cached_output.keys(), self, ) - except SourceInfoTypesDisagree as error: + except RowBuiltFormUnavailable as error: StaticOutputOperatorPod._raise_as_rows_do( cached_output.iter_data(), error ) @@ -1720,7 +1720,7 @@ def execute( kept_table = StaticOutputOperatorPod._row_built_form( result_table, keys ) - except SourceInfoTypesDisagree as error: + except RowBuiltFormUnavailable as error: StaticOutputOperatorPod._raise_as_rows_do( result_stream.iter_data(), error ) diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index 7c1f31ae1..230543548 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -1265,7 +1265,7 @@ def execute( UnboundSourceError: When no concrete data is available. """ from orcapod.core.operators.static_output_pod import ( - SourceInfoTypesDisagree, + RowBuiltFormUnavailable, StaticOutputOperatorPod, ) @@ -1278,7 +1278,7 @@ def execute( table, keys = self._rows_table() try: result = StaticOutputOperatorPod._output_stream(table, keys, self) - except SourceInfoTypesDisagree as error: + except RowBuiltFormUnavailable as error: # Rows whose source-info tokens cannot make one table: the node has read # its rows, and the run fails where its rows are handed on, raising what # their concatenation raises. diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index 077cf4817..49c75276a 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -66,12 +66,20 @@ from orcapod.protocols.hashing_protocols import SemanticHasherProtocol -class SourceInfoTypesDisagree(ValueError): +class RowBuiltFormUnavailable(ValueError): + """F cannot be built from the whole table (``_row_built_form``). + + The one signal that a node's output must come from its rows instead: the caller + builds the rows (``StaticOutputOperatorPod._rows_to_table``, through + ``_raise_as_rows_do``), which raises the error a table built from rows raises, so + the run fails as it does when rows are handed on, with the same observer events. + """ + + +class SourceInfoTypesDisagree(RowBuiltFormUnavailable): """Two rows give one source-info column different types (``_row_built_form``). - A table built from such rows cannot be concatenated: the caller builds the rows - (``StaticOutputOperatorPod._rows_to_table``), which raises the error a table built - from rows raises, so the run fails as it does when rows are handed on. + A table built from such rows cannot be concatenated. """ @@ -587,24 +595,33 @@ def _row_built_form( The table ``_rows_to_table`` would build from its rows. Raises: - SourceInfoTypesDisagree: If the rows' tokens give a source-info column two - types (``_type_source_info_by_values``). + RowBuiltFormUnavailable: If the whole table cannot be built: the rows' + tokens give a source-info column two types + (``SourceInfoTypesDisagree``), or an Arrow conversion fails. The node + then builds its rows (``_raise_as_rows_do``). """ - return StaticOutputOperatorPod._flag_by_values( - StaticOutputOperatorPod._type_source_info_by_values( - row_built_columns(table, keys) + try: + return StaticOutputOperatorPod._flag_by_values( + StaticOutputOperatorPod._type_source_info_by_values( + row_built_columns(table, keys) + ) ) - ) + except RowBuiltFormUnavailable: + raise + except pa.ArrowException as error: + # Values the whole table cannot be built from (a token the rows' own + # conversion refuses too): the rows decide, as on ``main``. + raise RowBuiltFormUnavailable(str(error)) from error @staticmethod def _raise_as_rows_do( rows: Iterable[tuple[TagProtocol, DataProtocol]], - error: SourceInfoTypesDisagree, + error: RowBuiltFormUnavailable, ) -> NoReturn: """Build ``rows`` into a table to raise the error a table built from them raises. Called when ``_row_built_form`` finds rows whose source-info tokens cannot make - one table (``SourceInfoTypesDisagree``): the rows' own concatenation + one table (``RowBuiltFormUnavailable``): the rows' own concatenation (``_rows_to_table``) raises exactly what a run that hands rows on raises. Args: @@ -613,7 +630,7 @@ def _raise_as_rows_do( Raises: pyarrow.ArrowInvalid: As ``_rows_to_table`` raises it. - SourceInfoTypesDisagree: ``error``, if the rows concatenate after all. + RowBuiltFormUnavailable: ``error``, if the rows build after all. """ StaticOutputOperatorPod._rows_to_table(list(rows)) raise error diff --git a/tests/test_core/operators/test_row_built_form.py b/tests/test_core/operators/test_row_built_form.py index 23a54bedf..c511d1b5c 100644 --- a/tests/test_core/operators/test_row_built_form.py +++ b/tests/test_core/operators/test_row_built_form.py @@ -391,3 +391,19 @@ def test_a_source_with_a_nullable_system_tag_is_not_bound() -> None: slot = next(label for label in job.nodes if label != "selected") with pytest.raises(SourceSpecMismatchError, match="record_id"): job.bind(sources={slot: ArrowTableStream(with_null, tag_columns=["k"])}) + + +def test_a_token_the_rows_cannot_convert_fails_as_main_does() -> None: + """A conversion failure of F's whole-table build falls back to the rows, as on main. + + Each row's token ``[None, [[]]]`` gives one list level (``source_info_arrow_type``), + whose conversion fails (``ArrowTypeError``). The node builds its rows, which raise + the same error, after the source node has ended (Codex on PR #485, round 2). + """ + nested = pa.large_list(_NESTED) + job = _batched_job(InMemoryArrowDatabase()) + job.bind(sources={"s": _with_source_x([[None, [[]]], [None, [[]]]], nested)}) + observer = _NodeEvents() + with pytest.raises(pa.ArrowTypeError, match="Expected bytes"): + job.run(observer=observer) + assert observer.events == [("start", "s"), ("end", "s")] From 95c9d1723a7137c0b9ac9f057a692a60642a599b Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 07:16:54 -0800 Subject: [PATCH 24/36] test(pipeline): type the held-lifetime test's streams (ITL-1360) Co-Authored-By: Claude Opus 5.5 --- tests/test_pipeline/test_held_streams_on_read.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/test_pipeline/test_held_streams_on_read.py b/tests/test_pipeline/test_held_streams_on_read.py index 99c031830..daed771fc 100644 --- a/tests/test_pipeline/test_held_streams_on_read.py +++ b/tests/test_pipeline/test_held_streams_on_read.py @@ -69,9 +69,9 @@ def test_a_held_stream_is_released_once_its_successors_ran( tag_only_columns=True, source_id="s", ) - a = step.pod(source, label="a") - b = step.pod(a.map_data({"y": "x"}), label="b") - c = step.pod(b.map_data({"y": "x"}), label="c") + a: Any = step.pod(source, label="a") + b: Any = step.pod(a.map_data({"y": "x"}), label="b") + c: Any = step.pod(b.map_data({"y": "x"}), label="c") step.pod(c.map_data({"y": "x"}), label="d") job.run() for label in ("b", "c", "d"): From a3d90a5ff3e29c7b784115bda3c46652ecc4528b Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 08:32:42 -0800 Subject: [PATCH 25/36] fix(pipeline): rows built on read off the provably-equal routes (ITL-1360) Codex on PR #485, round 3. One rule closes the class of the last three rounds: the eager whole-table build is used only where it is provably main's result (a transparent bind, an operator's own result, REPLAY of a table F can build). On every other route a node hands on the rows main would hold, as RowsOnRead, whose table main's own row path (_materialize_upstream) builds where the sync orchestrator gives it to a successor (at_edge): a narrower bind (no key re-derivation; its description is its declared schema's, arrow_types_declared false), a whole-table build that is unavailable (the rows read once), REPLAY of a stored table F cannot build, a held node (built at the successor's edge, not kept by the plan), and a function or side-effect node's rows. main's order, error and moment follow by construction; a leaf nobody reads is never built. e9 and e10 are gone: a leaf function node over a store written before ITL-928 completes and its as_table() raises main's InputValidationError, with a successor main's ArrowInvalid surfaces at the edge; ITL-1366's input raises main's ValueError at the successor's edge, sync, async and channel alike. Their tests are equality-with-main tests. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1360.md | 11 +- .../dev/specs/itl-1347-job-table-transport.md | 12 +- src/orcapod/core/nodes/function_node.py | 40 +-- src/orcapod/core/nodes/operator_node.py | 10 +- src/orcapod/core/nodes/source_node.py | 161 +++++------ .../core/operators/static_output_pod.py | 68 +++++ src/orcapod/core/streams/base.py | 10 +- src/orcapod/pipeline/node_run.py | 21 +- src/orcapod/pipeline/sync_orchestrator.py | 8 +- .../test_function_node_arrow_types.py | 92 +++++-- .../test_declared_slot_one_data_tag.py | 34 +-- .../test_pipeline/test_narrower_bind_order.py | 38 +-- tests/test_pipeline/test_rows_on_read.py | 254 ++++++++++++++++++ .../test_stream_transport_equivalence.py | 10 +- 14 files changed, 554 insertions(+), 215 deletions(-) create mode 100644 tests/test_pipeline/test_rows_on_read.py diff --git a/changelog.d/ITL-1360.md b/changelog.d/ITL-1360.md index ce18adf22..6579ccde7 100644 --- a/changelog.d/ITL-1360.md +++ b/changelog.d/ITL-1360.md @@ -6,7 +6,10 @@ successor. It now returns the node's output stream, which the sync orchestrator hands to every successor as it is: a source node gives its source's Arrow table, and an operator node its result's table (REPLAY: its stored table), each in the form a table built from - the rows has, without making the rows. `OrchestratorResult.node_outputs` holds each + the rows has, without making the rows. Where that is not provably the table its rows give + (a narrower bind, a table the whole-table build cannot use, a held node, a function or + side-effect node), the node hands on its rows, built into a table where a successor reads + them, as before. `OrchestratorResult.node_outputs` holds each node's output stream (the async orchestrator builds it when it is first read), and on the sync path a held node gives the stream of its held rows; the async path still sends a held node's rows as the run's plan took them (`held_rows`). Every @@ -15,12 +18,6 @@ table is built once, for what it keeps and for every successor, instead of once to keep and once per successor. The first two stages of the table transport between job nodes (`docs/dev/specs/itl-1347-job-table-transport.md`). (ITL-1347, ITL-1360) -- **A function node whose rows disagree on a column's type fails the run** — rows read from - a store written before ITL-928 (a `uint32` tag read back as `int32`) and rows computed now - cannot make one table. The run now fails at the node with the `InputValidationError` - naming the column and both types that the node's `as_table()` raised before; a node with a - successor used to fail with a bare `ArrowInvalid`, and one without completed the run. Such - a store must be rebuilt. (ITL-1360) ### Added diff --git a/docs/dev/specs/itl-1347-job-table-transport.md b/docs/dev/specs/itl-1347-job-table-transport.md index 3b9203c6a..086097dc3 100644 --- a/docs/dev/specs/itl-1347-job-table-transport.md +++ b/docs/dev/specs/itl-1347-job-table-transport.md @@ -513,9 +513,13 @@ with the developer's approval, given row by row. Each row gets its own test: it row, by name. The developer has accepted some behaviours of `main` that are not listed as rows; they are kept as `main` has them, and documented below. -**No row changes a sync-path result, except e9 and e10** (provisional, pending the developer). On -the sync path the branch equals `main` byte for byte. Stages 1–4 hold this by construction -and by L0–L5, and a lemma that fails stops its stage. +**No row changes a sync-path result.** On the sync path the branch equals `main` byte for +byte. Stages 1–4 hold this by construction and by L0–L5, and a lemma that fails stops its +stage. Where building a node's output from its whole table is not provably `main`'s result +(a narrower bind, a whole-table build that is unavailable, an odd stored table, a held +node, a node whose output is still its rows), the node hands on its rows and the table is +built from them by `main`'s row path where a successor reads them (`RowsOnRead`, +`at_edge`): `main`'s order, error and moment by construction (Codex on PR #485, round 3). | # | What differs | On `main` today | On the branch | Why `main` is wrong (bug, reproducer) | Approval needed | |---|---|---|---|---|---| @@ -525,8 +529,6 @@ and by L0–L5, and a lemma that fails stops its stage. | e6 | Async values that depend on an earlier validation of the same operator object | `SemiJoin._validated_common_keys` and `Index._element_arrow_type_fallback` hold the last validation's values (ITL-858, section 1.2). One operator object applied to two streams can use the other stream's keys or fallback type | Read from each input's description, with no state | The ITL-858 finding; filed as ITL-1358. Reproducer: one `SemiJoin` instance validated on stream B, then run async over stream A with other keys. To be confirmed in stage 5 | ITL-1358 (filed); fixed with stage 5 once a reproducer confirms it | | e7 | What a consumer does after its producer failed (async, failure path) | The producer closes its output in `finally`, so a consumer sees a normal end and may finish, and a `LOG` operator node may store, a partial result before the task group cancels it | Readers raise `UpstreamFailedError` at the failure point instead of seeing a normal end, so no consumer finishes, or stores its result, as if its input were complete. Batches a consumer processed before the failure are still processed, and a streaming node may already have passed them on or a function node stored results for them, as on `main`; there is no rollback. A barrier operator never computes over a partial input. The run raises the producer's own error, as today | A candidate race, to be confirmed with a reproducer in stage 5: a `fail_fast` function node raising on row 3 of 6, feeding a `Select` node in `LOG` mode; check the operator cache after the failed run. If `main` never stores in practice, this row is no difference | filed by the developer only once a test reproduces it | | e8 | Meta columns of an async side-effect node's rows | An async side-effect node passes on and holds the rows it receives as they are, so a computed row keeps its `__computed` meta column (from the cached function pod), and the node's `as_table(all_info=True)` shows it. On sync, its input is rebuilt from rows (`_rows_to_table` drops meta), so the column is absent | Async drops input meta columns as sync does. With table transport this follows from the transport columns, which hold no meta column | A `main` bug: the async and sync paths give the node different columns. Found by the stage 0 harness on `job-speed` 0e15d0db, which does not change side-effect nodes; the stage 0 differential checks it on pinned `main`. Reproducer: a function node (with a result store) feeding a `tap_pod`, async against sync, comparing the side-effect node's `as_table(all_info=True)` columns | approved (developer, 2026-11-22) | -| e9 | A sync function node whose output rows disagree on a column's Arrow type | A node with no successor completes the run; its `as_table()` raises `InputValidationError` ("Function node 'double': Rows disagree on the Arrow type of column 'k': int32 and uint32"). A node with a successor fails the run with a bare pyarrow `ArrowInvalid`, raised where the successor's input is rebuilt | The node builds its output stream when it runs (stage 2), so the run fails at the node, once its writes are committed (a failed write is still reported first, as on `main`) and before the node takes the run, with the `InputValidationError` `as_table()` raises (same type and message), with or without a successor; the node then holds no run. What is stored equals `main`'s: the row computed before the disagreement could be seen is stored, as on `main` (2 stored rows before the run, 3 after, on both) | Not a `main` bug to fix: a consequence of building the output stream in `execute`, and for a node with a successor an improvement (`main`'s `ArrowInvalid` names nothing). It arises only from a store written before ITL-928, whose cached rows give a `uint32` tag back as `int32`; such a store must be rebuilt. Reproducer: `tests/test_core/function_pod/test_function_node_arrow_types.py::test_new_rows_over_a_store_written_before_the_fix_raise_naming_the_column` (leaf and with successor) | provisional, coordinator decision 2026-11-22, pending developer | -| e10 | ITL-1366: a declared source slot over a narrower source with one data-tag among two tags | The run raises `ValueError` ("Duplicate column name 'k'") where the source's rows are rebuilt for its successor (`_rows_to_table`: the row's tag and data both hold the data-tag), when exactly one of the two tags is a data-tag and the tags are declared `j, k`; the source node has ended, the successor never starts. The same on the async path | Sync: the source node hands on F of the declared table (`_DeclaredForm.apply` of the bound table, the data-tag once, among the tags) and the run completes with the rows the bind describes. Async: as on `main` until stage 5 | A `main` bug (ITL-1366): the bind is accepted, then the rows cannot be built. Reproducer: `tests/test_pipeline/test_declared_slot_one_data_tag.py` (no, one or both data-tags, both tag orders, sync and async) | provisional, coordinator decision 2026-11-22, pending developer | **Resolved: refusals after rows have flowed (was c, question 9).** The developer's `Rejoin` rule (ITL-1355) removes every data-dependent refusal from `Rejoin`: it checks only what its diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index de4920088..3f32b20d1 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -285,12 +285,11 @@ def _with_datagram_id(data: Data, datagram_id: uuid.UUID) -> Data: def rows_as_output_stream( rows: Sequence[tuple[TagProtocol, DataProtocol]], node: StreamProtocol ) -> StreamProtocol: - """Return ``rows`` as ``node``'s output stream, as the sync orchestrator built it. + """Return ``rows`` as ``node``'s output stream: the rows, built when read. - ``StaticOutputOperatorPod._materialize_upstream``, for the job nodes whose output is - still their rows (function and side-effect nodes, until ITL-1347 stages 3 and 4): - the rows' table with the node's identity, or its zero-row input with no row. One - place imports the operator module for them. + For the job nodes whose output is still their rows (function and side-effect + nodes, until ITL-1347 stages 3 and 4): ``RowsOnRead``, built by ``main``'s row path + where a successor reads it. One place imports the operator module for them. Args: rows: The node's output rows, in order. @@ -299,9 +298,9 @@ def rows_as_output_stream( Returns: The node's output stream. """ - from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod + from orcapod.core.operators.static_output_pod import RowsOnRead - return StaticOutputOperatorPod._materialize_upstream(rows, node) # pyright: ignore[reportPrivateUsage] # the one definition of a rebuilt upstream + return cast(StreamProtocol, cast(object, RowsOnRead(rows, node))) def _executor_supports_concurrent( @@ -2483,20 +2482,13 @@ def _output_stream( ) -> StreamProtocol: """The output stream of a run whose output rows are ``rows``. - What the sync orchestrator built from a node's rows for its successors - (``StaticOutputOperatorPod._materialize_upstream``): the rows' table with this - node's identity, or the node's zero-row input when there is no row. + The rows, their table built when read by ``main``'s row path + (``RowsOnRead``): the sync orchestrator builds it where a successor reads it, + as ``main`` rebuilt the rows there, and a leaf's is never built (ITL-1347). """ - from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod + from orcapod.core.operators.static_output_pod import RowsOnRead - try: - return StaticOutputOperatorPod._materialize_upstream(rows, self) - except pa.ArrowInvalid: - # Rows that disagree on a column's Arrow type (cached rows of a store - # written before ITL-928): raise what ``as_table`` raises for them, naming - # the node, the column and both types (ITL-1360, e9). - self._table_from_pairs(rows) - raise + return cast(StreamProtocol, cast(object, RowsOnRead(rows, self))) def execute_data( self, @@ -2681,14 +2673,6 @@ def execute( self._commit_or_end_node( self._commit_at_node_end, ctx_obs, node_label, node_hash ) - # The output stream, built once the run is committed (a failed write is - # reported first, as on main) and before the node takes the run: rows that - # cannot make one table fail the run (ITL-1360, e9). - try: - result_stream = self._output_stream(output) - except InputValidationError: - ctx_obs.on_node_end(node_label, node_hash) - raise # The node's rows are those of this run's inputs, whatever else it caches. self._set_run_rows(emitted_entry_ids, failed=failed_rows) # Mark this node as freshly computed before the observer hears the end, so @@ -2705,7 +2689,7 @@ def execute( self.clear_cache() raise - return result_stream + return self._output_stream(output) def _empty_data_cache_hit( self, tag: TagProtocol, data: EmptyData, base_entry_id: bytes diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index be0bd1162..ccdaa6f35 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -40,6 +40,7 @@ from orcapod.config import OrcapodConfig from orcapod.core.operators.static_output_pod import ( RowBuiltFormUnavailable, + RowsOnRead, StaticOutputOperatorPod, ) from orcapod.core.streams.arrow_table_stream import ArrowTableStream @@ -1697,9 +1698,12 @@ def execute( cached_output.keys(), self, ) - except RowBuiltFormUnavailable as error: - StaticOutputOperatorPod._raise_as_rows_do( - cached_output.iter_data(), error + except RowBuiltFormUnavailable: + # A stored table F cannot build from: its rows, built when read, + # as main handed them on (ITL-1347). + output = cast( + StreamProtocol, + cast(object, RowsOnRead(cached_output.iter_data(), self)), ) ctx_obs.on_node_end(node_label, node_hash) return output diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index 8862b6bca..b9467328d 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -15,7 +15,7 @@ import json import logging from abc import ABC, abstractmethod -from collections.abc import AsyncIterator, Collection, Iterator, Mapping, Sequence +from collections.abc import AsyncIterator, Collection, Iterator, Mapping from datetime import datetime from typing import TYPE_CHECKING, Any, cast @@ -162,24 +162,6 @@ def apply(self, table: pa.Table) -> pa.Table: source-info columns in declared order within the positions each group holds. """ - table = self.retype(table) - return table.select(self._declared_positions(table.column_names)) - - def retype(self, table: pa.Table) -> pa.Table: - """Return *table*'s arrays under the declared fields, in *table*'s column order. - - The fields ``apply`` gives (the columns in ``nullable`` flagged nullable, the - columns in ``renames`` renamed), without placing the columns: a table whose - columns are then selected by the rows' keys (the row-built form, ITL-1347) - needs no placement, and a table holding a data-tag once, among the tags, would - lose a column to a placement made for a row's separate tag and data tables. - - Args: - table: Rows read from the bound source. - - Returns: - The same arrays under the declared fields. - """ schema = table.schema for position, field in enumerate(table.schema): if field.name in self.nullable: @@ -188,7 +170,8 @@ def retype(self, table: pa.Table) -> pa.Table: field = field.with_name(self.renames[field.name]) schema = schema.set(position, field) # pyright: ignore[reportUnknownMemberType] # stubs leave Field unparametrized # Same arrays under the declared fields: no cast, so no value or type changes. - return pa.Table.from_arrays(table.columns, schema=schema) + table = pa.Table.from_arrays(table.columns, schema=schema) + return table.select(self._declared_positions(table.column_names)) def _declared_positions(self, names: list[str]) -> list[int]: """Return the column positions of *names* with each group in declared order. @@ -210,18 +193,6 @@ def _declared_positions(self, names: list[str]) -> list[int]: return order -def _each_once(order: Sequence[str], names: Sequence[str]) -> tuple[str, ...]: - """``order`` with each of ``names`` once: repeats dropped, missing names appended. - - ``_DeclaredForm.apply`` places a row's columns; with one data-tag among two tags it - can place a column twice and lose another (ITL-1366, where ``main`` then fails to - build the rows). The keys keep its order and hold each name once (spec row e10). - """ - wanted = set(names) - kept = tuple(dict.fromkeys(n for n in order if n in wanted)) - return (*kept, *(n for n in names if n not in kept)) - - def _system_tag_columns( source: StreamProtocol, tag_names: Collection[str] ) -> tuple[list[str], list[str], list[str]]: @@ -1279,10 +1250,14 @@ def iter_data(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: """Yield ``(tag, data)`` pairs, or raise if data is unavailable.""" ... - def _rows_table(self) -> tuple[pa.Table, tuple[tuple[str, ...], tuple[str, ...]]]: + def _rows_table( + self, + ) -> tuple[pa.Table, tuple[tuple[str, ...], tuple[str, ...]]] | None: """The table of this node's rows (``iter_data``) and the rows' keys. - Here this node's own table (``ZERO_ROW_INPUT_COLUMNS``) and keys. + Here this node's own table (``ZERO_ROW_INPUT_COLUMNS``) and keys. ``None`` where + F of a table is not provably the rows' own table: the node then hands on its + rows (``RowsOnRead``). """ stream = cast("StreamProtocol", self) table = stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS) @@ -1328,6 +1303,7 @@ def execute( """ from orcapod.core.operators.static_output_pod import ( RowBuiltFormUnavailable, + RowsOnRead, StaticOutputOperatorPod, ) @@ -1335,18 +1311,19 @@ def execute( node_hash = self.content_hash().to_string() if observer is not None: observer.on_node_start(node_label, node_hash) - # The table and keys of this node's rows: a slot's own key order can differ - # from its source's. - table, keys = self._rows_table() - try: - result = StaticOutputOperatorPod._output_stream(table, keys, self) - except RowBuiltFormUnavailable as error: - # Rows whose source-info tokens cannot make one table: the node has read - # its rows, and the run fails where its rows are handed on, raising what - # their concatenation raises. - if observer is not None: - observer.on_node_end(node_label, node_hash) - StaticOutputOperatorPod._raise_as_rows_do(self.iter_data(), error) + # The table and keys of this node's rows, when F of the table is provably the + # rows' own table; otherwise (a narrower bind) the rows, built when read. + rows_table = self._rows_table() + result: StreamProtocol + if rows_table is None: + result = cast("StreamProtocol", RowsOnRead(self.iter_data(), self)) + else: + table, keys = rows_table + try: + result = StaticOutputOperatorPod._output_stream(table, keys, self) + except RowBuiltFormUnavailable: + # The rows decide (read once, here), built when read, as on main. + result = cast("StreamProtocol", RowsOnRead(self.iter_data(), self)) if observer is not None: observer.on_node_end(node_label, node_hash) return result @@ -1808,63 +1785,46 @@ def identity_structure(self) -> Any: return self._bound_source.identity_structure() return super().identity_structure() - def _row_keys( - self, table: pa.Table | None = None - ) -> tuple[tuple[str, ...], tuple[str, ...]]: - """The tag and data keys of this node's rows, as ``iter_data`` gives them. - - The bound source's rows have the keys of its table (``keys_of_rows``). A - narrower source's rows are given as the declared schema one by one - (``_declared_row``: its tag table and its data table each through - ``_DeclaredForm.apply``), so their keys are those of a zero-row tag table and a - zero-row data table of the bound source through the same ``apply``: a tag that - is also data takes its place from the declared data order, as on ``main``. - - Args: - table: The bound source's table (``ZERO_ROW_INPUT_COLUMNS``, with or - without rows). Default: its typed zero-row table, which reads no row; - the declared keys when it cannot say its types without rows. + def _row_keys(self) -> tuple[tuple[str, ...], tuple[str, ...]]: + """The tag and data keys of this node's rows, known without reading a row. - Returns: - The tag keys and the data keys of the rows. + The bound source's rows have the keys of its table (``keys_of_rows``, over its + typed zero-row table, which reads no row). A narrower bind (``_DeclaredForm``) + and an unbound slot answer with the slot's own keys: their description reports + its types undeclared (``arrow_types_declared``). """ - if self._bound_source is None: + if self._bound_source is None or self._declared_form is not None: return self.keys() - bound_keys = self._bound_source.keys() + table = typed_zero_row_input(self._bound_source) if table is None: - table = typed_zero_row_input(self._bound_source) - if table is None: - return self.keys() - rows_keys = keys_of_rows(table, bound_keys) - form = self._declared_form - if form is None: - return rows_keys - tag_keys, data_keys = rows_keys - names = table.column_names - system_tags = [n for n in names if n.startswith(constants.SYSTEM_TAG_PREFIX)] - source_info = [n for n in names if n.startswith(constants.SOURCE_PREFIX)] - empty = table.slice(0, 0) - tag_order = form.apply(empty.select([*tag_keys, *system_tags])).column_names - data_order = form.apply(empty.select([*data_keys, *source_info])).column_names - return ( - _each_once( - [n for n in tag_order if not n.startswith(constants.SYSTEM_TAG_PREFIX)], - tag_keys, - ), - _each_once( - [n for n in data_order if not n.startswith(constants.SOURCE_PREFIX)], - data_keys, - ), - ) + return self.keys() + return keys_of_rows(table, self._bound_source.keys()) - def _rows_table(self) -> tuple[pa.Table, tuple[tuple[str, ...], tuple[str, ...]]]: - """The table of this node's rows (``iter_data``) and the rows' keys. + def arrow_schema(self) -> pa.Schema: + """The Arrow schema of the columns this stream passes between job nodes. + + See ``stream_arrow_schema``. A narrower bind hands on its rows as ``main`` gives + them (``RowsOnRead``), so its description is the declared Python schema's + (``arrow_types_declared`` is false): no second placement rule. + """ + if self._declared_form is not None: + return stream_arrow_schema(self, self.keys(), typed=False) + return stream_arrow_schema(self, self._row_keys()) - The bound source's table and keys; for a narrower source, the source's table - given as the declared schema (``_DeclaredForm.apply``, which serves a whole - table as it serves each row in ``_declared_rows``) with the declared keys - (``_row_keys``). Its data-tags keep their source info, as each declared row - does. + @property + def arrow_types_declared(self) -> bool: + """False for a narrower bind (see ``arrow_schema``), else as every source node.""" + if self._declared_form is not None: + return False + return super().arrow_types_declared + + def _rows_table( + self, + ) -> tuple[pa.Table, tuple[tuple[str, ...], tuple[str, ...]]] | None: + """The bound source's table and the keys of its rows (``keys_of_rows``). + + ``None`` for a narrower bind: its rows are given as the declared schema one by + one (``_declared_rows``), so the node hands on those rows (``RowsOnRead``). Raises: UnboundSourceError: When no concrete source is attached. @@ -1874,11 +1834,10 @@ def _rows_table(self) -> tuple[pa.Table, tuple[tuple[str, ...], tuple[str, ...]] f"SourceJobNode '{self._name}' has no concrete source bound. " "Call job.bind(sources={'': source}) before running." ) + if self._declared_form is not None: + return None table = self._bound_source.as_table(columns=ZERO_ROW_INPUT_COLUMNS) - keys = self._row_keys(table) - if self._declared_form is None: - return table, keys - return self._declared_form.retype(table), keys + return table, keys_of_rows(table, self._bound_source.keys()) def iter_data(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: """Delegate to concrete source, or raise if unbound. diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index a815101be..f9017efd0 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -1353,6 +1353,74 @@ def with_open_provenance_flags(batch: pa.RecordBatch) -> pa.RecordBatch: return pa.RecordBatch.from_arrays(batch.columns, schema=schema) +class RowsOnRead: + """A node's output held as its rows, its table built on first read (ITL-1347). + + The one rule for every route where building the output from the whole table is + not provably ``main``'s result (a narrower bind, a whole-table build that is + unavailable, an odd stored table, a held node, a node whose output is still its + rows): the node hands on the rows ``main`` would hold, and the table is built from + them by ``main``'s own row path (``StaticOutputOperatorPod._materialize_upstream``) + when the stream is first read. The sync orchestrator reads each input of a node + before running it (``at_edge``), where ``main`` rebuilt it; a stream nobody reads + is never built, as ``main`` never rebuilt a leaf's rows. Every attribute is the + built stream's. + """ + + # Not a stream the row-built form already made: a channel opened on it reads it. + _orcapod_row_built_output = False + + def __init__( + self, rows: Sequence[tuple[TagProtocol, DataProtocol]], node: StreamProtocol + ) -> None: + """Hold ``node``'s rows; nothing is built. + + Args: + rows: The rows ``main`` would hold, in order (read once, here). + node: The node (or stream) whose output they are. + """ + self._rows: list[tuple[TagProtocol, DataProtocol]] | None = list(rows) + self._node = node + self._stream: StreamProtocol | None = None + + def built(self) -> StreamProtocol: + """The stream, built from the rows on the first call (``main``'s row path).""" + if self._stream is None: + rows = self._rows if self._rows is not None else [] + self._stream = StaticOutputOperatorPod._materialize_upstream( + rows, self._node + ) + self._rows = None + return self._stream + + def __getattr__(self, name: str) -> Any: + return getattr(self.built(), name) + + def __iter__(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: + return iter(self.built().iter_data()) + + def __repr__(self) -> str: + return f"RowsOnRead({short_stream_repr(self._node)})" + + +def at_edge(stream: StreamProtocol) -> StreamProtocol: + """``stream`` as a node's input: a ``RowsOnRead`` output is built here. + + The sync orchestrator reads every input of a node before it runs the node, where + ``main`` rebuilt the rows of the node before it, so an error of that build surfaces + at the same point, after the same observer events. + + Args: + stream: An output a node handed on. + + Returns: + The stream to give the node. + """ + if isinstance(stream, RowsOnRead): + return stream.built() + return stream + + class _RowsOfStream(ArrowTableStream): """Rows standing in for the stream they came from, with its pipeline hash. diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py index bebc82ad2..46293426c 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -364,7 +364,10 @@ def keys_of_rows( def stream_arrow_schema( - stream: object, keys: tuple[Sequence[str], Sequence[str]] | None = None + stream: object, + keys: tuple[Sequence[str], Sequence[str]] | None = None, + *, + typed: bool = True, ) -> pa.Schema: """Return ``stream``'s declared Arrow schema: what ``arrow_schema()`` answers (ITL-1347). @@ -389,6 +392,9 @@ def stream_arrow_schema( stream: The stream, source or node. keys: The tag and data keys of the stream's rows, when they differ from ``keys()`` (a source slot gives its bound source's rows); default ``keys()``. + typed: Take the stream's typed zero-row table (``typed_zero_row_input``); + ``False`` describes it from its declared Python schema only (a narrower + bind, whose rows ``main``'s row path places). Returns: The declared Arrow schema. @@ -397,7 +403,7 @@ def stream_arrow_schema( typed = cast(StreamProtocol, stream) given_keys = keys - table = typed_zero_row_input(stream) + table = typed_zero_row_input(stream) if typed else None if table is None and schema_requires_io(stream, ColumnConfig(system_tags=True)): # Nothing declared, nothing polled (a poller with no declared schema): the # columns are known only from rows, and a description never polls. No column, diff --git a/src/orcapod/pipeline/node_run.py b/src/orcapod/pipeline/node_run.py index f39f403c6..49a035b4a 100644 --- a/src/orcapod/pipeline/node_run.py +++ b/src/orcapod/pipeline/node_run.py @@ -243,6 +243,13 @@ def check_sources(streams: Iterable[Any]) -> tuple[str, ...]: return tuple(unchecked) +def _rows_on_read(rows: Sequence[Any], node: Any) -> Any: + """A held node's output: its rows, built where a successor reads them (``RowsOnRead``).""" + from orcapod.core.operators.static_output_pod import RowsOnRead + + return RowsOnRead(rows, node) + + @dataclass(frozen=True) class RunPlan: """What a run does with each node of its graph (ITL-1095). @@ -252,7 +259,7 @@ class RunPlan: them (a source slot is read; any other one is held). held: The output stream of each held node of ``dag``: of its current run, or of a stream outside the job; it feeds the nodes after it as if the node had - just run (the sync orchestrator). Built when read (``StreamsOnRead``). + just run (the sync orchestrator). Built when read (``RowsOnRead``). held_rows: The rows of each held node, as the plan took them; ``held`` is built from them. The async orchestrator sends them (it carries rows until ITL-1347 stage 5). @@ -337,8 +344,6 @@ def is_source(node: Any) -> bool: for node in to_run: for upstream in graph.predecessors(node): dag.add_edge(upstream, node) - from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod - # A held node's output stream: what the sync orchestrator built from its rows for # the nodes after it, exactly (ITL-1347, stage 2). held_rows = { @@ -346,11 +351,11 @@ def is_source(node: Any) -> bool: for node in included if not any(node is r for r in to_run) and not is_source(node) } - # Built when the sync orchestrator reaches the node, never while planning (an - # async run reads only the rows), and not kept by the plan (ITL-1360). - held = StreamsOnRead( - held_rows, StaticOutputOperatorPod._materialize_upstream, keep=False - ) + # The rows main held, built where a successor reads them (``RowsOnRead``, + # ``at_edge``), never while planning; an async run reads only the rows. + # The plan keeps no output it handed out (``keep=False``): the orchestrator drops + # each once the node's successors ran. + held = StreamsOnRead(held_rows, _rows_on_read, keep=False) # Counted from what each node holds: iterating an operator's rows would build a # (Tag, Data) pair per row only to count them (ITL-1351). held_counts = {node: node.held_row_count() for node in current} diff --git a/src/orcapod/pipeline/sync_orchestrator.py b/src/orcapod/pipeline/sync_orchestrator.py index 553307bfa..523322fa4 100644 --- a/src/orcapod/pipeline/sync_orchestrator.py +++ b/src/orcapod/pipeline/sync_orchestrator.py @@ -170,7 +170,9 @@ def _single_input( raise ValueError( f"FunctionNode expects exactly 1 upstream, got {len(predecessors)}" ) - return outputs[predecessors[0]] + from orcapod.core.operators.static_output_pod import at_edge + + return at_edge(outputs[predecessors[0]]) @staticmethod def _ordered_inputs( @@ -185,7 +187,9 @@ def _ordered_inputs( predecessors, key=lambda p: upstream_order.get(id(p), 0), ) - return [outputs[p] for p in sorted_preds] + from orcapod.core.operators.static_output_pod import at_edge + + return [at_edge(outputs[p]) for p in sorted_preds] @staticmethod def _gc_outputs( diff --git a/tests/test_core/function_pod/test_function_node_arrow_types.py b/tests/test_core/function_pod/test_function_node_arrow_types.py index 4d27611ef..bd76bc8a5 100644 --- a/tests/test_core/function_pod/test_function_node_arrow_types.py +++ b/tests/test_core/function_pod/test_function_node_arrow_types.py @@ -296,41 +296,48 @@ def _as_written_before_the_fix(root: pathlib.Path) -> None: ) -@pytest.mark.parametrize("chained", [False, True], ids=["leaf", "with_successor"]) def test_new_rows_over_a_store_written_before_the_fix_raise_naming_the_column( - chained: bool, tmp_path: pathlib.Path + tmp_path: pathlib.Path, ) -> None: """Rows of one node never make a column of a type none of them has. A Delta database written before ITL-928 gives a ``uint32`` tag back as ``int32``: rows served from it and rows computed now disagree, and the node says so instead - of picking a type. Such a database must be rebuilt. - - The run fails at the node, with the error ``as_table`` raises for such rows (main - raised it only on a later read of a node with no successor, and a bare - ``ArrowInvalid`` in the run of one with a successor; ITL-1360, difference e9). The - node then holds no run. + of picking a type. Such a database must be rebuilt. A leaf's run completes (its + rows are never built into one table, ``RowsOnRead``), as on ``main``. """ - _build( - DeltaTableDatabase(tmp_path), - _source_table("uint32").slice(0, 2), - chained=chained, - ).run() + _build(DeltaTableDatabase(tmp_path), _source_table("uint32").slice(0, 2)).run() _as_written_before_the_fix(tmp_path) - job = _build(DeltaTableDatabase(tmp_path), _source_table("uint32"), chained=chained) + job = _build(DeltaTableDatabase(tmp_path), _source_table("uint32")) + job.run() with pytest.raises(InputValidationError) as raised: - job.run() + job.nodes["double"].as_table() message = str(raised.value) - assert message.startswith("Function node 'double': ") assert "'k'" in message assert "int32" in message assert "uint32" in message - # A run that raised defines no rows. - assert job.nodes["double"].as_table().num_rows == 0 - # What is stored is what main stores: the row computed before the disagreement - # could be seen stays written, as after any failure, next to the two old rows. + + +def test_rows_over_a_store_written_before_the_fix_fail_at_the_successor( + tmp_path: pathlib.Path, +) -> None: + """With a successor, the run fails where the rows are built for it, as on ``main``. + + The node's rows are built into one table where its successor reads them + (``at_edge``): the concatenation raises ``ArrowInvalid`` there, as ``main``'s row + rebuild does. The computed row is stored, as on ``main``. + """ + _build( + DeltaTableDatabase(tmp_path), _source_table("uint32").slice(0, 2), chained=True + ).run() + _as_written_before_the_fix(tmp_path) + job = _build(DeltaTableDatabase(tmp_path), _source_table("uint32"), chained=True) + + with pytest.raises(pa.ArrowInvalid): + job.run() + stored = _build(DeltaTableDatabase(tmp_path), _source_table("uint32")) records = stored.nodes["double"].get_all_records() assert records is not None @@ -457,3 +464,48 @@ def on_data_start(self, node_label: str, tag: Any, data: Any) -> None: summary = job.run(orchestrator=AsyncPipelineOrchestrator(), observer=observer) assert summary.nodes["double"].held == 3 assert observer.count == 3 + + +def test_a_held_nodes_rows_are_built_at_its_successors_edge( + tmp_path: pathlib.Path, +) -> None: + """A held node's rows are built where its successor reads them, as on ``main``. + + A direct sync run: ``double`` held (its rows cannot make one table), an independent + source, then ``increment`` after ``double``. The independent source runs before + ``increment``'s input is built and raises (Codex on PR #485, round 3). + """ + from orcapod.core.operators.static_output_pod import RowsOnRead + from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator + from orcapod.pipeline.dag import OrcaDAG + from orcapod.pipeline.observer import NoOpObserver + + _build( + DeltaTableDatabase(tmp_path), _source_table("uint32").slice(0, 2), chained=True + ).run() + _as_written_before_the_fix(tmp_path) + job = _build(DeltaTableDatabase(tmp_path), _source_table("uint32"), chained=True) + job.run(orchestrator=AsyncPipelineOrchestrator()) + double, increment = job.nodes["double"], job.nodes["increment"] + increment.clear_cache() + independent = _build(InMemoryArrowDatabase(), _source_table("uint32")).nodes["src"] + + starts: list[str] = [] + + class Starts(NoOpObserver): + def contextualize(self, *identity_path: str) -> Starts: + return self + + def on_node_start( + self, node_label: str, node_hash: str, tag_schema: Any = None + ) -> None: + starts.append(node_label) + + dag: OrcaDAG[Any] = OrcaDAG() + dag.add_node(double) + dag.add_node(independent) + dag.add_edge(double, increment) + held = {double: RowsOnRead(list(double.iter_data()), double)} + with pytest.raises(pa.ArrowInvalid): + SyncPipelineOrchestrator().run(dag, observer=Starts(), held=held) + assert starts == ["src"] diff --git a/tests/test_pipeline/test_declared_slot_one_data_tag.py b/tests/test_pipeline/test_declared_slot_one_data_tag.py index 490c5f006..88fcc4045 100644 --- a/tests/test_pipeline/test_declared_slot_one_data_tag.py +++ b/tests/test_pipeline/test_declared_slot_one_data_tag.py @@ -1,14 +1,13 @@ -"""A declared slot over a narrower source with one data-tag among two tags (ITL-1366, e10). +"""A declared slot over a narrower source with one data-tag among two tags (ITL-1366). A source slot declared from a source whose ``x`` is ``int | None``, bound to the same table with ``x: int`` (a narrower source, given as the declared schema), feeding an operator. On ``main`` the run raises ``ValueError`` ("Duplicate column name") where the source's rows are rebuilt for its successor, when exactly one of the two tags is a -data-tag and the tags are declared ``j, k``. On the sync path the branch hands on the -declared table itself (F over ``_DeclaredForm.apply`` of the bound table), and the run -completes with the rows the bind describes (spec row e10; provisional, coordinator -decision 2026-11-22, pending the developer). The async path still carries rows until -ITL-1347 stage 5 and raises as ``main`` does. +data-tag and the tags are declared ``j, k`` (ITL-1366, a ``main`` bug fixed there +separately). A narrower bind hands on its rows as ``main`` gives them (``RowsOnRead``), +built where the successor reads them: the branch raises the same error at the same +point, on the sync and the async path, and completes every other arrangement. """ from __future__ import annotations @@ -68,26 +67,21 @@ def _rows(job: PipelineJob) -> list[dict[str, Any]]: return sorted(table.to_pylist(), key=lambda row: row["j"]) +@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"]) @pytest.mark.parametrize("roles", list(ROLES), ids=list(ROLES)) @pytest.mark.parametrize("order", [("j", "k"), ("k", "j")], ids=["j-k", "k-j"]) -def test_the_sync_run_completes_with_the_rows_the_bind_describes( - order: tuple[str, str], roles: str +def test_the_run_is_as_on_main( + order: tuple[str, str], roles: str, asynchronous: bool ) -> None: - """Every arrangement runs on the sync path and gives the bound table's rows.""" - job = _bound_job(order, ROLES[roles]) - job.run() - assert _rows(job) == ROWS - - -@pytest.mark.parametrize("roles", list(ROLES), ids=list(ROLES)) -@pytest.mark.parametrize("order", [("j", "k"), ("k", "j")], ids=["j-k", "k-j"]) -def test_the_async_run_is_as_on_main(order: tuple[str, str], roles: str) -> None: - """The async path carries rows until stage 5: it raises where ``main`` raises.""" + """Raises where ``main`` raises (ITL-1366), else gives the bound table's rows.""" job = _bound_job(order, ROLES[roles]) + kwargs: dict[str, Any] = ( + {"orchestrator": AsyncPipelineOrchestrator()} if asynchronous else {} + ) raises_on_main = order == ("j", "k") and roles in ("k_data_tag", "j_data_tag") if raises_on_main: with pytest.raises(ValueError, match="Duplicate column name"): - job.run(orchestrator=AsyncPipelineOrchestrator()) + job.run(**kwargs) else: - job.run(orchestrator=AsyncPipelineOrchestrator()) + job.run(**kwargs) assert _rows(job) == ROWS diff --git a/tests/test_pipeline/test_narrower_bind_order.py b/tests/test_pipeline/test_narrower_bind_order.py index a754b8647..45bca4160 100644 --- a/tests/test_pipeline/test_narrower_bind_order.py +++ b/tests/test_pipeline/test_narrower_bind_order.py @@ -2,14 +2,13 @@ A source slot declared from a source whose ``x`` is ``int | None``, bound to the same columns with ``x: int`` (a narrower source, given as the declared schema), feeding a -``Batch`` node in ``LOG`` mode. The source node's output is F of the bound table with -the keys its rows have (``SourceJobNode._row_keys``: ``_DeclaredForm.apply`` of a -row's tag and data tables, as each row is given). Every pairing of declared layout, tag +``Batch`` node in ``LOG`` mode. The source node hands on its rows as ``main`` gives +them (``_declared_rows``), built where the successor reads them (``RowsOnRead``). +Every pairing of declared layout, tag order and data-tag roles must keep and store what the row path keeps and stores: the same run with the source's output built from its rows -(``StaticOutputOperatorPod._materialize_upstream``), as on ``main``. The arrangements -where the row path raises (one data-tag of two, ITL-1366) are spec row e10, tested in -``test_declared_slot_one_data_tag.py``. +(``StaticOutputOperatorPod._materialize_upstream``), as on ``main``, also where the +row path raises (one data-tag of two, ITL-1366). """ from __future__ import annotations @@ -90,9 +89,12 @@ def execute(self: Any, *, observer: Any = None) -> Any: monkeypatch.setattr(SourceNodeBase, "execute", execute) -def _raises_on_the_row_path(roles: str) -> bool: - """The row path raises only with one data-tag of two (ITL-1366, e10).""" - return roles in ("a_data_tag", "b_data_tag") +def _outcome(layout: tuple[str, ...], tag_order: tuple[str, str], roles: Any) -> Any: + """The run's kept columns and raw stored schema, or the error it raised.""" + try: + return _run(layout, tag_order, roles) + except ValueError as error: + return (type(error), str(error)) @pytest.mark.parametrize("roles", list(ROLES), ids=list(ROLES)) @@ -106,15 +108,17 @@ def test_a_narrower_bind_keeps_and_stores_as_the_row_path( roles: str, monkeypatch: pytest.MonkeyPatch, ) -> None: - """Kept columns and the raw stored schema equal the row path's, in order.""" - got = _run(layout, tag_order, ROLES[roles]) + """Kept columns and the raw stored schema equal the row path's, in order. + + Where the row path raises (one data-tag of two, ITL-1366, a ``main`` bug), the + branch raises the same error. + """ + got = _outcome(layout, tag_order, ROLES[roles]) with monkeypatch.context() as patch: _row_path(patch) - try: - expected = _run(layout, tag_order, ROLES[roles]) - except ValueError as error: - assert "Duplicate column name" in str(error) - assert _raises_on_the_row_path(roles) - pytest.skip("the row path raises here: spec row e10") + expected = _outcome(layout, tag_order, ROLES[roles]) + if isinstance(expected[1], str): + assert got == expected + return assert got[0] == expected[0] assert got[1].equals(expected[1], check_metadata=True) diff --git a/tests/test_pipeline/test_rows_on_read.py b/tests/test_pipeline/test_rows_on_read.py new file mode 100644 index 000000000..971969730 --- /dev/null +++ b/tests/test_pipeline/test_rows_on_read.py @@ -0,0 +1,254 @@ +"""Outputs held as rows, built where a successor reads them (ITL-1347; Codex on PR #485). + +On every route where building a node's output from its whole table is not provably +``main``'s result, the node hands on its rows (``RowsOnRead``), built by ``main``'s row +path where the sync orchestrator gives them to a successor (``at_edge``). So the +order, the error and the moment it surfaces are ``main``'s: a narrower bind, a source +whose whole-table build is unavailable (its rows read once), a held node. A leaf +nobody reads is never built. +""" + +from __future__ import annotations + +from typing import Any + +import pyarrow as pa +import pytest + +from orcapod import PipelineJob +from orcapod.core.streams import ArrowTableStream +from orcapod.databases import InMemoryArrowDatabase +from orcapod.operators import Batch +from orcapod.pipeline.dag import OrcaDAG +from orcapod.pipeline.observer import NoOpObserver +from orcapod.pipeline.sync_orchestrator import SyncPipelineOrchestrator +from orcapod.sources import ArrowTableSource, DictSource +from orcapod.types import CacheMode +from tests.test_core.operators.test_row_built_form import ( + _NESTED, # pyright: ignore[reportPrivateUsage] # the shared provenance fixtures + _NodeEvents, # pyright: ignore[reportPrivateUsage] + _source_table, # pyright: ignore[reportPrivateUsage] + _with_source_x, # pyright: ignore[reportPrivateUsage] +) + +_UNCONVERTIBLE = pa.large_list(_NESTED) + + +def _unconvertible() -> ArrowTableStream: + """Tokens ``[None, [[]]]``: the whole-table build is unavailable, the rows raise.""" + return _with_source_x([[None, [[]]], [None, [[]]]], _UNCONVERTIBLE) + + +def _plain() -> DictSource: + return DictSource( + [{"k": 1, "x": 1}, {"k": 2, "x": 2}], + tag_columns=["k"], + tag_only_columns=True, + source_id="s", + ) + + +def test_a_fallback_source_reads_its_rows_once() -> None: + """A rebind after the source node ended does not change what it handed on. + + Its rows were read once, when it ran: the successor's edge raises the original + rows' ``ArrowTypeError``, as on ``main``. + """ + job = PipelineJob(name="read_once", database=InMemoryArrowDatabase()) + with job: + Batch(batch_size=2)(_plain().select_data_columns(["x"]), label="batched") + job.bind(sources={"s": _unconvertible()}) + node = job.nodes["s"] + + class RebindsAtEnd(NoOpObserver): + def contextualize(self, *identity_path: str) -> RebindsAtEnd: + return self + + def on_node_end(self, node_label: str, node_hash: str) -> None: + if node_label == "s": + node.bound_source = _plain() + + with pytest.raises(pa.ArrowTypeError, match="Expected bytes"): + job.run(observer=RebindsAtEnd()) + + +def test_a_fallback_source_nobody_reads_completes() -> None: + """A source whose rows cannot be built, as a leaf of a direct sync run: it completes. + + ``main`` never rebuilt a leaf's rows; neither does the branch (``RowsOnRead``). + """ + job = PipelineJob(name="leaf", database=InMemoryArrowDatabase()) + with job: + _plain().select_data_columns(["x"], label="selected") + job.bind(sources={"s": _unconvertible()}) + dag: OrcaDAG[Any] = OrcaDAG() + dag.add_node(job.nodes["s"]) + observer = _NodeEvents() + SyncPipelineOrchestrator().run(dag, observer=observer, materialize_results=False) + assert observer.events == [("start", "s"), ("end", "s")] + + +def test_a_narrower_raw_bind_keeps_the_slots_system_tag_order() -> None: + """A raw stream whose system tags are record id then source id, bound narrower. + + ``main`` gives each row the slot's order (source id, then record id); so do the + kept and the raw stored tables (Codex on PR #485, round 3). + """ + from orcapod.system_constants import constants + + table = _source_table() + source_id = next(n for n in table.column_names if "source_id" in n) + record_id = next(n for n in table.column_names if "record_id" in n) + others = [n for n in table.column_names if n not in (source_id, record_id)] + reversed_pair = table.select([*others, record_id, source_id]) + raw = ArrowTableStream(reversed_pair, tag_columns=["k"]) + + database = InMemoryArrowDatabase() + job = PipelineJob(name="reversed_pair", database=database) + with job: + declared = DictSource( + [{"k": 1, "x": 1}, {"k": 2, "x": None}], + tag_columns=["k"], + tag_only_columns=True, + source_id="s", + ) + Batch(batch_size=2)(declared, label="batched") + job.nodes["batched"].attach_databases( + pipeline_database=database.at("log"), cache_mode=CacheMode.LOG + ) + job.bind(sources={"s": raw}) + job.run() + node = job.nodes["batched"] + kept = node.as_table(columns={"system_tags": True}).column_names + system_tags = [n for n in kept if n.startswith(constants.SYSTEM_TAG_PREFIX)] + assert ["source_id" in n for n in system_tags] == [True, False] + stored = node.get_all_records(columns={"system_tags": True}) + assert stored is not None + stored_tags = [ + n for n in stored.column_names if n.startswith(constants.SYSTEM_TAG_PREFIX) + ] + assert ["source_id" in n for n in stored_tags] == [True, False] + + +def test_a_narrower_bind_is_described_from_its_declared_schema() -> None: + """A narrower bind's description never places columns: its types are undeclared. + + With one data-tag among two tags (ITL-1366's input), the description does not + raise; ``arrow_types_declared`` is false (Codex on PR #485, round 3). + """ + table = pa.table( + { + "x": pa.array([1, 2], pa.int64()), + "k": pa.array([5, 6], pa.int64()), + "j": pa.array([3, 4], pa.int64()), + "y": pa.array([7.5, 8.5], pa.float64()), + } + ) + + def source(nullable_x: bool) -> ArrowTableSource: + fields = [f.with_nullable(f.name == "x" and nullable_x) for f in table.schema] + return ArrowTableSource( + table.cast(pa.schema(fields)), + tag_columns=["j", "k"], + tag_only_columns=("j",), + source_id="s", + ) + + job = PipelineJob(name="narrower_description", database=InMemoryArrowDatabase()) + with job: + source(True).select_data_columns(["y", "x"], label="selected") + slot = next(label for label in job.nodes if label != "selected") + job.bind(sources={slot: source(False)}) + node = job.nodes[slot] + schema = node.arrow_schema() + assert not node.arrow_types_declared + assert set(node.keys()[0]) <= set(schema.names) + + +def test_a_narrower_bind_channel_raises_as_its_rows_do() -> None: + """The source node's channel carries its rows: ITL-1366's input raises as on main. + + ``open_channel()`` reads the node's output, the rows built when read, which raise + the duplicate-column error ``main``'s row path raises. + """ + import asyncio + + table = pa.table( + { + "x": pa.array([1, 2], pa.int64()), + "k": pa.array([5, 6], pa.int64()), + "j": pa.array([3, 4], pa.int64()), + "y": pa.array([7.5, 8.5], pa.float64()), + } + ) + + def source(nullable_x: bool) -> ArrowTableSource: + fields = [f.with_nullable(f.name == "x" and nullable_x) for f in table.schema] + return ArrowTableSource( + table.cast(pa.schema(fields)), + tag_columns=["j", "k"], + tag_only_columns=("j",), + source_id="s", + ) + + job = PipelineJob(name="narrower_channel", database=InMemoryArrowDatabase()) + with job: + source(True).select_data_columns(["y", "x"], label="selected") + slot = next(label for label in job.nodes if label != "selected") + job.bind(sources={slot: source(False)}) + node: Any = job.nodes[slot] + with pytest.raises(ValueError, match="Duplicate column name"): + asyncio.run(node.open_channel().collect()) + + +def _replay_job(database: InMemoryArrowDatabase, *, with_successor: bool) -> Any: + """``source -> select x`` with the select node replaying from ``database``.""" + job = PipelineJob(name="replay_odd", database=InMemoryArrowDatabase()) + with job: + selected = _plain().select_data_columns(["x"], label="selected") + if with_successor: + Batch(batch_size=2)(selected, label="batched") + job.nodes["selected"].attach_databases( + pipeline_database=database, cache_mode=CacheMode.REPLAY + ) + return job + + +@pytest.mark.parametrize("with_successor", [False, True], ids=["leaf", "successor"]) +def test_replay_of_a_table_the_whole_table_build_cannot_use( + with_successor: bool, +) -> None: + """REPLAY of a stored table with unconvertible tokens hands on its rows. + + The node ends as usual; a leaf completes; a successor's edge raises the rows' + ``ArrowTypeError``, as ``main``'s row rebuild does (Codex on PR #485, round 3). + """ + logged = InMemoryArrowDatabase() + job = PipelineJob(name="replay_odd", database=InMemoryArrowDatabase()) + with job: + _plain().select_data_columns(["x"], label="selected") + node: Any = job.nodes["selected"] + node.attach_databases(pipeline_database=logged, cache_mode=CacheMode.LOG) + job.run() + path = node._stored_table_path # pyright: ignore[reportPrivateUsage] # the table to seed + stored = logged.get_all_records(path, record_id_column="__record_id") + assert stored is not None + position = stored.schema.get_field_index("_source_x") + odd = stored.set_column( + position, + pa.field("_source_x", _UNCONVERTIBLE, nullable=True), + pa.array([[None, [[]]]] * stored.num_rows, _UNCONVERTIBLE), + ) + seeded = InMemoryArrowDatabase() + seeded.add_records(path, odd, record_id_column="__record_id") + + replay = _replay_job(seeded, with_successor=with_successor) + observer = _NodeEvents() + if with_successor: + with pytest.raises(pa.ArrowTypeError, match="Expected bytes"): + replay.run(observer=observer) + assert ("end", "selected") in observer.events + assert ("start", "batched") not in observer.events + else: + replay.run(observer=observer) + assert ("end", "selected") in observer.events diff --git a/tests/test_pipeline/test_stream_transport_equivalence.py b/tests/test_pipeline/test_stream_transport_equivalence.py index f13f9dc89..7b9ff4193 100644 --- a/tests/test_pipeline/test_stream_transport_equivalence.py +++ b/tests/test_pipeline/test_stream_transport_equivalence.py @@ -36,7 +36,7 @@ from orcapod.core.nodes.function_node import FunctionJobNode from orcapod.core.nodes.operator_node import OperatorJobNode from orcapod.core.nodes.source_node import SourceNodeBase -from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod +from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod, at_edge from orcapod.core.streams.base import ZERO_ROW_INPUT_COLUMNS from orcapod.databases import InMemoryArrowDatabase from orcapod.errors import ProvisionalHashWarning @@ -125,7 +125,13 @@ def _identity(stream: Any) -> tuple[Any, ...]: def assert_same_stream(got: Any, expected: Any) -> None: - """Equal identity, and equal tables byte for byte (every column group).""" + """Equal identity, and equal tables byte for byte (every column group). + + ``got`` is taken as a successor receives it (``at_edge``: an output held as its rows + is built there). + """ + got = at_edge(got) + expected = at_edge(expected) assert _identity(got) == _identity(expected) got_table = got.as_table(columns=ALL_COLUMNS).combine_chunks() expected_table = expected.as_table(columns=ALL_COLUMNS).combine_chunks() From a31ed4b62386f9095fd942d612fbad3c7564ead0 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 08:45:53 -0800 Subject: [PATCH 26/36] fix(pipeline): RowsOnRead typed through rows_on_read (ITL-1360) Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/nodes/function_node.py | 8 ++++---- src/orcapod/core/nodes/operator_node.py | 7 ++----- src/orcapod/core/nodes/source_node.py | 8 ++++---- .../core/operators/static_output_pod.py | 19 ++++++++++++++++++- src/orcapod/core/streams/base.py | 6 +++--- src/orcapod/pipeline/node_run.py | 4 ++-- .../test_function_node_arrow_types.py | 4 ++-- 7 files changed, 35 insertions(+), 21 deletions(-) diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 3f32b20d1..ebd445e5c 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -298,9 +298,9 @@ def rows_as_output_stream( Returns: The node's output stream. """ - from orcapod.core.operators.static_output_pod import RowsOnRead + from orcapod.core.operators.static_output_pod import rows_on_read - return cast(StreamProtocol, cast(object, RowsOnRead(rows, node))) + return rows_on_read(rows, node) def _executor_supports_concurrent( @@ -2486,9 +2486,9 @@ def _output_stream( (``RowsOnRead``): the sync orchestrator builds it where a successor reads it, as ``main`` rebuilt the rows there, and a leaf's is never built (ITL-1347). """ - from orcapod.core.operators.static_output_pod import RowsOnRead + from orcapod.core.operators.static_output_pod import rows_on_read - return cast(StreamProtocol, cast(object, RowsOnRead(rows, self))) + return rows_on_read(rows, self) def execute_data( self, diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index ccdaa6f35..925eab47a 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -40,8 +40,8 @@ from orcapod.config import OrcapodConfig from orcapod.core.operators.static_output_pod import ( RowBuiltFormUnavailable, - RowsOnRead, StaticOutputOperatorPod, + rows_on_read, ) from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.core.streams.base import ( @@ -1701,10 +1701,7 @@ def execute( except RowBuiltFormUnavailable: # A stored table F cannot build from: its rows, built when read, # as main handed them on (ITL-1347). - output = cast( - StreamProtocol, - cast(object, RowsOnRead(cached_output.iter_data(), self)), - ) + output = rows_on_read(cached_output.iter_data(), self) ctx_obs.on_node_end(node_label, node_hash) return output diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index b9467328d..5c7b5afcf 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -1303,8 +1303,8 @@ def execute( """ from orcapod.core.operators.static_output_pod import ( RowBuiltFormUnavailable, - RowsOnRead, StaticOutputOperatorPod, + rows_on_read, ) node_label = self.label @@ -1316,14 +1316,14 @@ def execute( rows_table = self._rows_table() result: StreamProtocol if rows_table is None: - result = cast("StreamProtocol", RowsOnRead(self.iter_data(), self)) + result = rows_on_read(self.iter_data(), self) else: table, keys = rows_table try: result = StaticOutputOperatorPod._output_stream(table, keys, self) except RowBuiltFormUnavailable: # The rows decide (read once, here), built when read, as on main. - result = cast("StreamProtocol", RowsOnRead(self.iter_data(), self)) + result = rows_on_read(self.iter_data(), self) if observer is not None: observer.on_node_end(node_label, node_hash) return result @@ -1808,7 +1808,7 @@ def arrow_schema(self) -> pa.Schema: (``arrow_types_declared`` is false): no second placement rule. """ if self._declared_form is not None: - return stream_arrow_schema(self, self.keys(), typed=False) + return stream_arrow_schema(self, self.keys(), from_table=False) return stream_arrow_schema(self, self._row_keys()) @property diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index f9017efd0..6d5eec544 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -1371,7 +1371,7 @@ class RowsOnRead: _orcapod_row_built_output = False def __init__( - self, rows: Sequence[tuple[TagProtocol, DataProtocol]], node: StreamProtocol + self, rows: Iterable[tuple[TagProtocol, DataProtocol]], node: StreamProtocol ) -> None: """Hold ``node``'s rows; nothing is built. @@ -1403,6 +1403,23 @@ def __repr__(self) -> str: return f"RowsOnRead({short_stream_repr(self._node)})" +def rows_on_read( + rows: Iterable[tuple[TagProtocol, DataProtocol]], node: StreamProtocol +) -> StreamProtocol: + """``RowsOnRead`` of ``rows`` as a stream (it delegates every member to the built one). + + Args: + rows: The rows ``main`` would hold, in order (read once, here). + node: The node (or stream) whose output they are. + + Returns: + The output, built from the rows when first read. + """ + # ``RowsOnRead`` stands for the stream it builds; the checker cannot see that + # through its delegation, so the cast goes through object. + return cast(StreamProtocol, cast(object, RowsOnRead(rows, node))) + + def at_edge(stream: StreamProtocol) -> StreamProtocol: """``stream`` as a node's input: a ``RowsOnRead`` output is built here. diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py index 46293426c..c61c38c17 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -367,7 +367,7 @@ def stream_arrow_schema( stream: object, keys: tuple[Sequence[str], Sequence[str]] | None = None, *, - typed: bool = True, + from_table: bool = True, ) -> pa.Schema: """Return ``stream``'s declared Arrow schema: what ``arrow_schema()`` answers (ITL-1347). @@ -392,7 +392,7 @@ def stream_arrow_schema( stream: The stream, source or node. keys: The tag and data keys of the stream's rows, when they differ from ``keys()`` (a source slot gives its bound source's rows); default ``keys()``. - typed: Take the stream's typed zero-row table (``typed_zero_row_input``); + from_table: Take the stream's typed zero-row table (``typed_zero_row_input``); ``False`` describes it from its declared Python schema only (a narrower bind, whose rows ``main``'s row path places). @@ -403,7 +403,7 @@ def stream_arrow_schema( typed = cast(StreamProtocol, stream) given_keys = keys - table = typed_zero_row_input(stream) if typed else None + table = typed_zero_row_input(stream) if from_table else None if table is None and schema_requires_io(stream, ColumnConfig(system_tags=True)): # Nothing declared, nothing polled (a poller with no declared schema): the # columns are known only from rows, and a description never polls. No column, diff --git a/src/orcapod/pipeline/node_run.py b/src/orcapod/pipeline/node_run.py index 49a035b4a..88a0e5ffe 100644 --- a/src/orcapod/pipeline/node_run.py +++ b/src/orcapod/pipeline/node_run.py @@ -245,9 +245,9 @@ def check_sources(streams: Iterable[Any]) -> tuple[str, ...]: def _rows_on_read(rows: Sequence[Any], node: Any) -> Any: """A held node's output: its rows, built where a successor reads them (``RowsOnRead``).""" - from orcapod.core.operators.static_output_pod import RowsOnRead + from orcapod.core.operators.static_output_pod import rows_on_read - return RowsOnRead(rows, node) + return rows_on_read(rows, node) @dataclass(frozen=True) diff --git a/tests/test_core/function_pod/test_function_node_arrow_types.py b/tests/test_core/function_pod/test_function_node_arrow_types.py index bd76bc8a5..195d72133 100644 --- a/tests/test_core/function_pod/test_function_node_arrow_types.py +++ b/tests/test_core/function_pod/test_function_node_arrow_types.py @@ -475,7 +475,7 @@ def test_a_held_nodes_rows_are_built_at_its_successors_edge( source, then ``increment`` after ``double``. The independent source runs before ``increment``'s input is built and raises (Codex on PR #485, round 3). """ - from orcapod.core.operators.static_output_pod import RowsOnRead + from orcapod.core.operators.static_output_pod import rows_on_read from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator from orcapod.pipeline.dag import OrcaDAG from orcapod.pipeline.observer import NoOpObserver @@ -505,7 +505,7 @@ def on_node_start( dag.add_node(double) dag.add_node(independent) dag.add_edge(double, increment) - held = {double: RowsOnRead(list(double.iter_data()), double)} + held = {double: rows_on_read(double.iter_data(), double)} with pytest.raises(pa.ArrowInvalid): SyncPipelineOrchestrator().run(dag, observer=Starts(), held=held) assert starts == ["src"] From 3223e6444a0cede44a0acf0129bf9019e9b02978 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 09:23:00 -0800 Subject: [PATCH 27/36] fix(pipeline): the eager route only for library source kinds; RowsOnRead is a stream (ITL-1360) Codex on PR #485, round 4. - TABLE_IS_ROWS, declared once on RootSource (False) and True on the library source kinds whose as_table() and iter_data() read the same data with no effect: only a node bound to one hands on F of its table. Any other bound stream (a side-effect or function pod stream, an operator's result, a raw stream, a poller) hands on its rows, as main iterated them. - No table is prepared before main prepares it: a result with no row (source or operator) is RowsOnRead too, so its zero-row form is derived at the successor's edge and the operator is never called a second time. - RowsOnRead satisfies StreamProtocol structurally on 3.11-3.13 (every protocol member declared on the class; producer, upstreams, context, label and modified time read without building); iter_data() gives the rows it holds unchanged (meta included), sync and async node_outputs alike; arrow_schema() is the node's declared one (arrow_types_declared false) and open_channel() builds only at its first read. - A description whose types are undeclared gives names in no guaranteed order: transport_schema returns None for it and the channel's name check compares names as a set. Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/nodes/operator_node.py | 4 +- src/orcapod/core/nodes/source_node.py | 25 ++- .../core/operators/static_output_pod.py | 148 ++++++++++++-- src/orcapod/core/record_batch_channels.py | 5 +- .../core/sources/arrow_table_source.py | 1 + src/orcapod/core/sources/base.py | 10 + src/orcapod/core/sources/cached_source.py | 1 + src/orcapod/core/sources/csv_source.py | 1 + src/orcapod/core/sources/data_frame_source.py | 1 + src/orcapod/core/sources/db_table_source.py | 1 + .../core/sources/delta_table_source.py | 1 + src/orcapod/core/sources/derived_source.py | 1 + src/orcapod/core/sources/dict_source.py | 1 + src/orcapod/core/sources/list_source.py | 1 + .../core/sources/spiraldb_table_source.py | 1 + src/orcapod/pipeline/async_orchestrator.py | 8 +- .../protocols/core_protocols/streams.py | 8 +- tests/test_pipeline/test_rows_on_read.py | 181 ++++++++++++++++++ 18 files changed, 361 insertions(+), 38 deletions(-) diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index 925eab47a..c7b237fe3 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -1752,7 +1752,9 @@ def execute( kept_table, tag_keys, data_tags, self ) else: - output = StaticOutputOperatorPod._materialize_upstream([], self) + # Its zero-row form is derived where a successor reads it, as on main: + # the operator is not called again here (``RowsOnRead``). + output = rows_on_read([], self) ctx_obs.on_node_end(node_label, node_hash) return output except BaseException: diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index 5c7b5afcf..8795c9702 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -17,7 +17,7 @@ from abc import ABC, abstractmethod from collections.abc import AsyncIterator, Collection, Iterator, Mapping from datetime import datetime -from typing import TYPE_CHECKING, Any, cast +from typing import TYPE_CHECKING, Any import pyarrow as pa @@ -1253,15 +1253,13 @@ def iter_data(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: def _rows_table( self, ) -> tuple[pa.Table, tuple[tuple[str, ...], tuple[str, ...]]] | None: - """The table of this node's rows (``iter_data``) and the rows' keys. + """The table of this node's rows (``iter_data``) and the rows' keys, or ``None``. - Here this node's own table (``ZERO_ROW_INPUT_COLUMNS``) and keys. ``None`` where - F of a table is not provably the rows' own table: the node then hands on its - rows (``RowsOnRead``). + ``None`` here: a node that carries no data of its own hands on its rows + (``RowsOnRead``), which raise what reading it raises. A bound job node gives + its bound source's table when F of it is provably the rows' own table. """ - stream = cast("StreamProtocol", self) - table = stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS) - return table, keys_of_rows(table, stream.keys()) + return None def arrow_schema(self) -> pa.Schema: """The Arrow schema of the columns this stream passes between job nodes. @@ -1823,8 +1821,10 @@ def _rows_table( ) -> tuple[pa.Table, tuple[tuple[str, ...], tuple[str, ...]]] | None: """The bound source's table and the keys of its rows (``keys_of_rows``). - ``None`` for a narrower bind: its rows are given as the declared schema one by - one (``_declared_rows``), so the node hands on those rows (``RowsOnRead``). + ``None`` for a narrower bind (its rows are given as the declared schema one by + one, ``_declared_rows``) and for a bound stream that is not a library source + kind whose table is its rows (``TABLE_IS_ROWS``): the node then hands on those + rows (``RowsOnRead``). Raises: UnboundSourceError: When no concrete source is attached. @@ -1836,6 +1836,11 @@ def _rows_table( ) if self._declared_form is not None: return None + if not getattr(type(self._bound_source), "TABLE_IS_ROWS", False): + # Not a library source kind whose table is its rows (a side-effect or + # function pod stream, an operator's result, a raw stream, a poller): its + # rows, as main iterated them. + return None table = self._bound_source.as_table(columns=ZERO_ROW_INPUT_COLUMNS) return table, keys_of_rows(table, self._bound_source.keys()) diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index 13edc119a..5f51eb2a4 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -3,7 +3,14 @@ import asyncio import logging from abc import abstractmethod -from collections.abc import Collection, Coroutine, Iterable, Iterator, Sequence +from collections.abc import ( + AsyncIterator, + Collection, + Coroutine, + Iterable, + Iterator, + Sequence, +) from datetime import datetime, timezone from typing import TYPE_CHECKING, Any, ClassVar, NoReturn, cast @@ -657,7 +664,9 @@ def _output_stream( The output stream, with ``node``'s identity. """ if table.num_rows == 0: - return StaticOutputOperatorPod._materialize_upstream([], node) + # No row: the zero-row input is derived where a successor reads it, as on + # main (``RowsOnRead``): nothing is prepared before then. + return rows_on_read([], node) tag_keys, data_keys = keys return StaticOutputOperatorPod._as_upstream_stream( StaticOutputOperatorPod._row_built_form(table, keys), @@ -1181,12 +1190,18 @@ def transport_schema(stream: StreamProtocol) -> pa.Schema | None: Returns: The schema, or ``None`` for a stream that cannot say its Arrow types without - rows (an unbound input slot, a source that has not polled yet). + rows (an unbound input slot, a source that has not polled yet, a description + whose types are undeclared: ``arrow_types_declared`` false). """ # TODO(ITL-1360): ``stream.arrow_schema()``, once every stream has it. from orcapod.core.streams.base import row_built_names, row_built_provenance from orcapod.utils import arrow_utils + if not getattr(stream, "arrow_types_declared", True): + # The rows decide the types (and the column order) of a description whose + # types are undeclared (a narrower bind, ``RowsOnRead``): the first batch sets + # them. + return None typed = StaticOutputOperatorPod._zero_row_input(stream) # pyright: ignore[reportPrivateUsage] # the zero-row form of an input if typed is None: return None @@ -1360,14 +1375,21 @@ class RowsOnRead: """A node's output held as its rows, its table built on first read (ITL-1347). The one rule for every route where building the output from the whole table is - not provably ``main``'s result (a narrower bind, a whole-table build that is - unavailable, an odd stored table, a held node, a node whose output is still its - rows): the node hands on the rows ``main`` would hold, and the table is built from - them by ``main``'s own row path (``StaticOutputOperatorPod._materialize_upstream``) - when the stream is first read. The sync orchestrator reads each input of a node - before running it (``at_edge``), where ``main`` rebuilt it; a stream nobody reads - is never built, as ``main`` never rebuilt a leaf's rows. Every attribute is the - built stream's. + not provably ``main``'s result (a narrower bind, a bound stream that is not a + library source kind, a whole-table build that is unavailable, an odd stored table, + a held node, a result with no row, a node whose output is still its rows): the node + hands on the rows ``main`` would hold, and the table is built from them by + ``main``'s own row path (``StaticOutputOperatorPod._materialize_upstream``) when + the table is first read. The sync orchestrator reads each input of a node before + running it (``at_edge``), where ``main`` rebuilt it; a stream nobody reads is never + built, as ``main`` never rebuilt a leaf's rows. + + It is a stream (``StreamProtocol``), structurally: every member of the protocol is + the built stream's, except those that read nothing. Its rows (``iter_data``, + iteration) are the rows it holds, unchanged, as ``main`` returned them. Its + description (``arrow_schema``) is the node's declared one and builds nothing + (``arrow_types_declared`` is false). Opening a channel builds nothing; the + channel's first read does. """ # Not a stream the row-built form already made: a channel opened on it reads it. @@ -1382,30 +1404,120 @@ def __init__( rows: The rows ``main`` would hold, in order (read once, here). node: The node (or stream) whose output they are. """ - self._rows: list[tuple[TagProtocol, DataProtocol]] | None = list(rows) + self._rows: list[tuple[TagProtocol, DataProtocol]] = list(rows) self._node = node self._stream: StreamProtocol | None = None def built(self) -> StreamProtocol: """The stream, built from the rows on the first call (``main``'s row path).""" if self._stream is None: - rows = self._rows if self._rows is not None else [] self._stream = StaticOutputOperatorPod._materialize_upstream( - rows, self._node + self._rows, self._node ) - self._rows = None return self._stream - def __getattr__(self, name: str) -> Any: - return getattr(self.built(), name) + def iter_data(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: + """The rows it holds, unchanged (their meta columns included), as ``main``.""" + return iter(self._rows) def __iter__(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: - return iter(self.built().iter_data()) + return self.iter_data() + + async def async_iter_data( + self, + ) -> AsyncIterator[tuple[TagProtocol, DataProtocol]]: + """The rows it holds, unchanged.""" + for row in self._rows: + yield row + + def arrow_schema(self) -> pa.Schema: + """The node's declared description, from its Python schema; builds nothing. + + The rows decide the Arrow types (``arrow_types_declared`` is false): a + description with undeclared types gives the declared names, with no + guaranteed order. + """ + from orcapod.core.streams.base import stream_arrow_schema + + return stream_arrow_schema(self._node, from_table=False) + + @property + def arrow_types_declared(self) -> bool: + """False: the rows decide the types (see ``arrow_schema``).""" + return False + + def open_channel(self) -> Any: + """Open an input channel on this stream; its first read builds the table.""" + from orcapod.core.streams.base import CompleteStreamFeed + from orcapod.core.streams.record_batch_input import InputChannel + + return InputChannel( + cast(StreamProtocol, cast(object, self)), + CompleteStreamFeed(cast(StreamProtocol, cast(object, self))), + ) + + # The members that tell what the output is without reading it: the node's, which + # the built stream takes too (``_as_upstream_stream``), or the built stream's once + # it is built. A protocol check (``isinstance``) reads them and builds nothing. + @property + def producer(self) -> Any: + return self._node.producer + + @property + def upstreams(self) -> tuple[StreamProtocol, ...]: + return self._node.upstreams + + @property + def data_context_key(self) -> str: + return self._node.data_context_key + + @property + def label(self) -> Any: + source = self._stream if self._stream is not None else self._node + return getattr(source, "label", None) + + @property + def last_modified(self) -> Any: + source = self._stream if self._stream is not None else self._node + return getattr(source, "last_modified", None) + + def __getattr__(self, name: str) -> Any: + # Every other member (``join``, ``as_polars_df``, ...) is the built stream's. + return getattr(self.built(), name) def __repr__(self) -> str: return f"RowsOnRead({short_stream_repr(self._node)})" +def _stream_protocol_members() -> list[str]: + """The members ``StreamProtocol`` declares, its bases' included. + + What ``isinstance(x, StreamProtocol)`` looks for on the class: declaring each one + there lets ``RowsOnRead`` pass the check on every supported Python. + """ + names: set[str] = set() + for base in StreamProtocol.__mro__: + if base is object or base.__name__ in ("Protocol", "Generic"): + continue + names.update(name for name in vars(base) if not name.startswith("_")) + return sorted(names) + + +def _delegated(name: str) -> Any: + """A method of ``RowsOnRead`` that is the built stream's (``RowsOnRead.built``).""" + + def delegate(self: RowsOnRead, *args: Any, **kwargs: Any) -> Any: + return getattr(self.built(), name)(*args, **kwargs) + + delegate.__name__ = name + return delegate + + +for _name in _stream_protocol_members(): + if _name not in vars(RowsOnRead): + setattr(RowsOnRead, _name, _delegated(_name)) + + def rows_on_read( rows: Iterable[tuple[TagProtocol, DataProtocol]], node: StreamProtocol ) -> StreamProtocol: diff --git a/src/orcapod/core/record_batch_channels.py b/src/orcapod/core/record_batch_channels.py index b32a4e648..842e62a4a 100644 --- a/src/orcapod/core/record_batch_channels.py +++ b/src/orcapod/core/record_batch_channels.py @@ -191,9 +191,10 @@ def _check_schema(self, batch: pa.RecordBatch) -> None: if schema is None: # No Arrow types in the description: the first batch that passes sets them # (they must be in the large variants), but the names are still the - # stream's. A refused batch sets nothing. + # stream's, in no guaranteed order (an undeclared description gives names + # only). A refused batch sets nothing. names = batch.schema.names - if names != row_built_names(names, self._stream.keys()): + if set(names) != set(row_built_names(names, self._stream.keys())): raise ValueError( f"A record batch sent as {_named(self._stream)} does not have that " + f"stream's columns: it has {names}, the stream's keys are " diff --git a/src/orcapod/core/sources/arrow_table_source.py b/src/orcapod/core/sources/arrow_table_source.py index 460075915..5af85d506 100644 --- a/src/orcapod/core/sources/arrow_table_source.py +++ b/src/orcapod/core/sources/arrow_table_source.py @@ -89,6 +89,7 @@ class ArrowTableSource(RootSource): # The config type key; also the kind prefix of the default source id. SOURCE_KIND: ClassVar[str] = "arrow_table" + TABLE_IS_ROWS: ClassVar[bool] = True def __init__( self, diff --git a/src/orcapod/core/sources/base.py b/src/orcapod/core/sources/base.py index 1eed1f022..1f8eef123 100644 --- a/src/orcapod/core/sources/base.py +++ b/src/orcapod/core/sources/base.py @@ -93,6 +93,16 @@ class RootSource(StreamBase): identifier, config or stored path. """ + TABLE_IS_ROWS: ClassVar[bool] = False + """Whether ``as_table()`` and ``iter_data()`` read the same data, with no effect. + + Declared ``True`` only by the library source kinds that read one stream either way + (ITL-1347): a job node bound to one hands on F of its table, which equals the table + built from its rows. Any other bound stream (a side-effect or function pod stream, + an operator's result, a raw stream, a source kind that polls or delivers on a read) + hands on its rows (``RowsOnRead``), as ``main`` iterated them. + """ + def __init__( self, source_id: str | None = None, diff --git a/src/orcapod/core/sources/cached_source.py b/src/orcapod/core/sources/cached_source.py index 308a24fb6..98e531222 100644 --- a/src/orcapod/core/sources/cached_source.py +++ b/src/orcapod/core/sources/cached_source.py @@ -79,6 +79,7 @@ class CachedSource(RootSource): """ SOURCE_KIND: ClassVar[str] = "cached" + TABLE_IS_ROWS: ClassVar[bool] = True """Config type key and default source-id kind of this source (one vocabulary).""" HASH_COLUMN_NAME = "_record_hash" diff --git a/src/orcapod/core/sources/csv_source.py b/src/orcapod/core/sources/csv_source.py index cd780ab1e..bfd0b423d 100644 --- a/src/orcapod/core/sources/csv_source.py +++ b/src/orcapod/core/sources/csv_source.py @@ -276,6 +276,7 @@ class CSVSource(RootSource): """ SOURCE_KIND: ClassVar[str] = "csv" + TABLE_IS_ROWS: ClassVar[bool] = True """Config type key and default source-id kind of this source (one vocabulary).""" TAKES_TAG_ONLY_COLUMNS: ClassVar[bool] = True diff --git a/src/orcapod/core/sources/data_frame_source.py b/src/orcapod/core/sources/data_frame_source.py index 5db583ec2..f973c9647 100644 --- a/src/orcapod/core/sources/data_frame_source.py +++ b/src/orcapod/core/sources/data_frame_source.py @@ -44,6 +44,7 @@ class DataFrameSource(RootSource): # The config type key; also the kind prefix of the default source id. SOURCE_KIND: ClassVar[str] = "data_frame" + TABLE_IS_ROWS: ClassVar[bool] = True def __init__( self, diff --git a/src/orcapod/core/sources/db_table_source.py b/src/orcapod/core/sources/db_table_source.py index decdc09ea..721b2308d 100644 --- a/src/orcapod/core/sources/db_table_source.py +++ b/src/orcapod/core/sources/db_table_source.py @@ -80,6 +80,7 @@ class DBTableSource(RootSource): """ SOURCE_KIND: ClassVar[str] = "db_table" + TABLE_IS_ROWS: ClassVar[bool] = True """Config type key and default source-id kind of this source (one vocabulary).""" TAKES_TAG_ONLY_COLUMNS: ClassVar[bool] = True diff --git a/src/orcapod/core/sources/delta_table_source.py b/src/orcapod/core/sources/delta_table_source.py index ae623bdec..2a60e6304 100644 --- a/src/orcapod/core/sources/delta_table_source.py +++ b/src/orcapod/core/sources/delta_table_source.py @@ -49,6 +49,7 @@ class DeltaTableSource(RootSource): """ SOURCE_KIND: ClassVar[str] = "delta_table" + TABLE_IS_ROWS: ClassVar[bool] = True """Config type key and default source-id kind of this source (one vocabulary).""" TAKES_TAG_ONLY_COLUMNS: ClassVar[bool] = True diff --git a/src/orcapod/core/sources/derived_source.py b/src/orcapod/core/sources/derived_source.py index 1a7a58a93..1464e3f08 100644 --- a/src/orcapod/core/sources/derived_source.py +++ b/src/orcapod/core/sources/derived_source.py @@ -191,6 +191,7 @@ class DerivedSource(RootSource): # The config type key (names the class a saved config is rebuilt with) and # the kind prefix of the plain form's default source id. SOURCE_KIND: ClassVar[str] = "derived" + TABLE_IS_ROWS: ClassVar[bool] = True PROVISIONAL = True """Provisional in data context v1, both forms (ITL-1331, ``PROVISIONAL_SOURCES``).""" diff --git a/src/orcapod/core/sources/dict_source.py b/src/orcapod/core/sources/dict_source.py index bb99e1f9c..5a3935153 100644 --- a/src/orcapod/core/sources/dict_source.py +++ b/src/orcapod/core/sources/dict_source.py @@ -40,6 +40,7 @@ class DictSource(RootSource): # The config type key; also the kind prefix of the default source id. SOURCE_KIND: ClassVar[str] = "dict" + TABLE_IS_ROWS: ClassVar[bool] = True def __init__( self, diff --git a/src/orcapod/core/sources/list_source.py b/src/orcapod/core/sources/list_source.py index 48d8eae61..0b42e33ef 100644 --- a/src/orcapod/core/sources/list_source.py +++ b/src/orcapod/core/sources/list_source.py @@ -39,6 +39,7 @@ def _default_tag(element: Any, idx: int) -> dict[str, Any]: # The config type key; also the kind prefix of the default source id. SOURCE_KIND: ClassVar[str] = "list" + TABLE_IS_ROWS: ClassVar[bool] = True def __init__( self, diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index 8b022ff87..af04d5f34 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -374,6 +374,7 @@ class SpiralDBTableSource(RootSource): """ SOURCE_KIND: ClassVar[str] = "spiraldb_table" + TABLE_IS_ROWS: ClassVar[bool] = True """Config type key and default source-id kind of this source (one vocabulary).""" TAKES_TAG_ONLY_COLUMNS: ClassVar[bool] = True diff --git a/src/orcapod/pipeline/async_orchestrator.py b/src/orcapod/pipeline/async_orchestrator.py index a9f87691c..9edd1614e 100644 --- a/src/orcapod/pipeline/async_orchestrator.py +++ b/src/orcapod/pipeline/async_orchestrator.py @@ -209,7 +209,9 @@ async def _run_async( held_rows: Mapping[Any, list[tuple[TagProtocol, DataProtocol]]] | None = None, ) -> OrchestratorResult: """Core async logic: wire channels, launch tasks, collect results.""" - from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod + from orcapod.core.operators.static_output_pod import ( + rows_on_read, + ) from orcapod.pipeline.observer import NoOpObserver run_id = run_id or str(uuid.uuid4()) @@ -365,9 +367,7 @@ async def _run_async( return OrchestratorResult( node_outputs=( - StreamsOnRead( - collectors, StaticOutputOperatorPod._materialize_upstream - ) + StreamsOnRead(collectors, rows_on_read) if materialize_results else {} ) diff --git a/src/orcapod/protocols/core_protocols/streams.py b/src/orcapod/protocols/core_protocols/streams.py index 0ab5ecdf0..bf6272745 100644 --- a/src/orcapod/protocols/core_protocols/streams.py +++ b/src/orcapod/protocols/core_protocols/streams.py @@ -194,9 +194,11 @@ def arrow_schema(self) -> "pa.Schema": def arrow_types_declared(self) -> bool: """Whether ``arrow_schema()`` holds the rows' own Arrow types. - ``False`` only when the stream cannot type itself without rows (an unbound - slot, a ``PollingSource`` never polled; ITL-1089): its schema is then converted - from the Python schema. + ``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 converted from + the Python schema, and its names come in no guaranteed order; no consumer + relies on their order (ITL-1347). """ ... diff --git a/tests/test_pipeline/test_rows_on_read.py b/tests/test_pipeline/test_rows_on_read.py index 971969730..29c1f5f01 100644 --- a/tests/test_pipeline/test_rows_on_read.py +++ b/tests/test_pipeline/test_rows_on_read.py @@ -252,3 +252,184 @@ def test_replay_of_a_table_the_whole_table_build_cannot_use( else: replay.run(observer=observer) assert ("end", "selected") in observer.events + + +# ── round 4: the boundary of the eager route, and the lazy output itself ────── + + +DELIVERED: list[int] = [] + + +def _deliver(x: int, ctx: Any) -> None: + DELIVERED.append(x) + + +def _leaf_run(job: PipelineJob, label: str) -> _NodeEvents: + """Run only ``label`` (a source node), as a leaf of a direct sync DAG.""" + dag: OrcaDAG[Any] = OrcaDAG() + dag.add_node(job.nodes[label]) + observer = _NodeEvents() + SyncPipelineOrchestrator().run(dag, observer=observer, materialize_results=False) + return observer + + +def test_a_bound_tap_stream_delivers_every_row_as_main_does() -> None: + """A side-effect stream bound to a slot is not a library source kind: its rows. + + The node iterates it as ``main`` did, delivering every row, and a leaf completes + (Codex on PR #485, round 4: the eager route read ``as_table()`` instead). + """ + from orcapod.side_effects import tap_pod + + tap = tap_pod(_deliver) + DELIVERED.clear() + raw = _with_source_x([[None, [[]]], [None, [[]]]], _UNCONVERTIBLE) + tapped: Any = tap.process(raw) + job = PipelineJob(name="tap_bound", database=InMemoryArrowDatabase()) + with job: + _plain().select_data_columns(["x"], label="selected") + job.bind(sources={"s": tapped}) + observer = _leaf_run(job, "s") + assert DELIVERED == [1, 2] + assert observer.events == [("start", "s"), ("end", "s")] + + +@pytest.mark.parametrize( + "make", + [ + pytest.param(lambda: _plain().select_data_columns(["x"]), id="operator"), + pytest.param( + lambda: ArrowTableStream(_source_table(), tag_columns=["k"]), id="raw" + ), + ], +) +def test_a_bound_stream_that_is_not_a_source_kind_hands_on_its_rows(make: Any) -> None: + """Only a library source kind whose table is its rows (``TABLE_IS_ROWS``) is eager.""" + from orcapod.core.operators.static_output_pod import RowsOnRead + + job = PipelineJob(name="bound_kinds", database=InMemoryArrowDatabase()) + with job: + _plain().select_data_columns(["x"], label="selected") + job.bind(sources={"s": make()}) + assert isinstance(job.nodes["s"].execute(), RowsOnRead) + + +def test_a_library_source_kind_is_eager() -> None: + from orcapod.core.operators.static_output_pod import RowsOnRead + + job = PipelineJob(name="eager_kind", database=InMemoryArrowDatabase()) + with job: + _plain().select_data_columns(["x"], label="selected") + assert not isinstance(job.nodes["s"].execute(), RowsOnRead) + + +def test_an_empty_output_is_derived_at_the_edge() -> None: + """A source with no row: its zero-row output is derived where the successor reads. + + An observer that rebinds the source when it ends changes what the successor + receives, as on ``main`` (Codex on PR #485, round 4). + """ + + def empty(mark: str) -> ArrowTableSource: + field = pa.field("x", pa.int64(), nullable=False, metadata={"mark": mark}) + table = pa.table({"k": pa.array([], pa.int64()), "x": pa.array([], pa.int64())}) + table = pa.Table.from_arrays( + table.columns, + schema=pa.schema([pa.field("k", pa.int64(), nullable=False), field]), + ) + return ArrowTableSource(table, tag_columns=["k"], source_id="s") + + job = PipelineJob(name="empty_edge", database=InMemoryArrowDatabase()) + with job: + empty("before").select_data_columns(["x"], label="selected") + slot = next(label for label in job.nodes if label != "selected") + node = job.nodes[slot] + + class RebindsAtEnd(NoOpObserver): + def contextualize(self, *identity_path: str) -> RebindsAtEnd: + return self + + def on_node_end(self, node_label: str, node_hash: str) -> None: + if node_label == slot: + node.bound_source = empty("after") + + job.run(observer=RebindsAtEnd()) + kept = job.nodes["selected"].as_table() + assert kept.schema.field("x").metadata == {b"mark": b"after"} + + +def test_an_operator_with_an_empty_result_is_not_called_again() -> None: + """An empty result's zero-row form is derived at the edge, never by a second call. + + An operator that raises on empty input completes as a leaf, as on ``main`` + (Codex on PR #485, round 4). + """ + from orcapod.operators import SelectDataColumns + + calls: list[int] = [] + + class EmptyThenRaises(SelectDataColumns): + def unary_static_process(self, stream: Any) -> Any: + rows = stream.as_table().num_rows + calls.append(rows) + if rows == 0: + raise ValueError("cannot process empty input") + return super().unary_static_process(stream).polars_filter(x=-1) + + job = PipelineJob(name="empty_result", database=InMemoryArrowDatabase()) + with job: + EmptyThenRaises(["x"])(_plain(), label="emptied") + observer = _NodeEvents() + job.run(observer=observer) + assert ("end", "emptied") in observer.events + assert 0 not in calls + + +@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"]) +def test_returned_function_rows_keep_their_meta(asynchronous: bool) -> None: + """``node_outputs[node].iter_data()`` gives the node's own rows, meta included.""" + from orcapod import function_pod + from orcapod.pipeline import AsyncPipelineOrchestrator + + @function_pod(output_keys="y") + def plus(x: int) -> int: + return x + 1 + + job = PipelineJob(name="returned_rows", database=InMemoryArrowDatabase()) + with job: + plus.pod(_plain(), label="plus") + dag: OrcaDAG[Any] = OrcaDAG() + dag.add_edge(job.nodes["s"], job.nodes["plus"]) + orchestrator: Any = ( + AsyncPipelineOrchestrator() if asynchronous else SyncPipelineOrchestrator() + ) + result = orchestrator.run(dag) + rows = list(result.node_outputs[job.nodes["plus"]].iter_data()) + assert rows + assert all("__computed" in data.keys(columns={"meta": True}) for _, data in rows) + + +def test_a_lazy_output_is_described_and_opened_without_reading() -> None: + """Describing an unread output, or opening its channel, builds nothing. + + The first read of the channel raises what the rows' build raises (Codex on PR + #485, round 4). + """ + import asyncio + + from orcapod.core.operators.static_output_pod import RowsOnRead + from orcapod.protocols.core_protocols import StreamProtocol + + job = PipelineJob(name="lazy_out", database=InMemoryArrowDatabase()) + with job: + _plain().select_data_columns(["x"], label="selected") + job.bind(sources={"s": _unconvertible()}) + out: Any = job.nodes["s"].execute() + assert isinstance(out, RowsOnRead) + assert isinstance(out, StreamProtocol) + assert not out.arrow_types_declared + assert "x" in out.arrow_schema().names + channel = out.open_channel() + assert out._stream is None # pyright: ignore[reportPrivateUsage] # nothing built + with pytest.raises(pa.ArrowTypeError, match="Expected bytes"): + asyncio.run(channel.collect()) From 6844386531b682d5fc029c4034fea62d9aaa7161 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 09:40:38 -0800 Subject: [PATCH 28/36] fix(pipeline): type the protocol-member walk and round-4 tests (ITL-1360) Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/operators/static_output_pod.py | 3 ++- tests/test_pipeline/test_rows_on_read.py | 5 +++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index 5f51eb2a4..d6fc8e1bd 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -1496,7 +1496,8 @@ def _stream_protocol_members() -> list[str]: there lets ``RowsOnRead`` pass the check on every supported Python. """ names: set[str] = set() - for base in StreamProtocol.__mro__: + protocol = cast(type, cast(object, StreamProtocol)) + for base in protocol.__mro__: if base is object or base.__name__ in ("Protocol", "Generic"): continue names.update(name for name in vars(base) if not name.startswith("_")) diff --git a/tests/test_pipeline/test_rows_on_read.py b/tests/test_pipeline/test_rows_on_read.py index 29c1f5f01..97fa85171 100644 --- a/tests/test_pipeline/test_rows_on_read.py +++ b/tests/test_pipeline/test_rows_on_read.py @@ -281,7 +281,7 @@ def test_a_bound_tap_stream_delivers_every_row_as_main_does() -> None: """ from orcapod.side_effects import tap_pod - tap = tap_pod(_deliver) + tap: Any = tap_pod(_deliver) DELIVERED.clear() raw = _with_source_x([[None, [[]]], [None, [[]]]], _UNCONVERTIBLE) tapped: Any = tap.process(raw) @@ -374,7 +374,8 @@ def unary_static_process(self, stream: Any) -> Any: calls.append(rows) if rows == 0: raise ValueError("cannot process empty input") - return super().unary_static_process(stream).polars_filter(x=-1) + result: Any = super().unary_static_process(stream) + return result.polars_filter(x=-1) job = PipelineJob(name="empty_result", database=InMemoryArrowDatabase()) with job: From 0e357ee07e02b2de429f02b34ebffff0338f9463 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 09:59:53 -0800 Subject: [PATCH 29/36] fix(pipeline): eager only for a source kind's own reading; result order; channel checks (ITL-1360) Codex on PR #485, round 5. - table_is_rows(source): TABLE_IS_ROWS is honoured only when the declaring class reads the source, the source's own class or a subclass that overrides none of the row readers (iter_data, as_table, __iter__, async_iter_data, keys, output_schema); a filtering subclass hands on its rows, as main iterated them. - An operator node keeps, stores and hands on its result in the order the result's rows have (DynamicPodStream.result_keys), never re-placed by the prediction. - A channel without declared types compares names as a multiset (a duplicate column is refused), and each source-info column's token type must settle with the batches already accepted, refused at send with SourceInfoTypesDisagree otherwise. - A lazy output describes itself with its node's own description, and a description from declared types takes the Arrow schemas a slot states, never a conversion of Python types (time64[ns], decimal256). - Changelog corrected (no order promise where types are undeclared; when arrow_types_declared is false; what reading node_outputs builds). - Observer-only limit pinned: spec row e11 (open) and a strict xfail. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1360.md | 45 +++-- .../dev/specs/itl-1347-job-table-transport.md | 1 + src/orcapod/core/nodes/operator_node.py | 6 +- src/orcapod/core/nodes/source_node.py | 3 +- .../core/operators/static_output_pod.py | 25 ++- src/orcapod/core/record_batch_channels.py | 50 ++++- src/orcapod/core/sources/base.py | 34 ++++ src/orcapod/core/streams/base.py | 22 ++- .../test_record_batch_channels.py | 47 +++++ tests/test_pipeline/test_rows_on_read.py | 171 ++++++++++++++++++ 10 files changed, 374 insertions(+), 30 deletions(-) diff --git a/changelog.d/ITL-1360.md b/changelog.d/ITL-1360.md index 6579ccde7..dbe931f26 100644 --- a/changelog.d/ITL-1360.md +++ b/changelog.d/ITL-1360.md @@ -4,28 +4,33 @@ function and side-effect job node (and of the node protocols) returned the node's rows as a list of (tag, data) pairs, and the sync orchestrator rebuilt a table from them for each successor. It now returns the node's output stream, which the sync orchestrator hands to - every successor as it is: a source node gives its source's Arrow table, and an operator - node its result's table (REPLAY: its stored table), each in the form a table built from - the rows has, without making the rows. Where that is not provably the table its rows give - (a narrower bind, a table the whole-table build cannot use, a held node, a function or - side-effect node), the node hands on its rows, built into a table where a successor reads - them, as before. `OrchestratorResult.node_outputs` holds each - node's output stream (the async orchestrator builds it when it is first read), and - on the sync path a held node gives the stream of its held rows; the async path still - sends a held node's rows as the run's plan took them (`held_rows`). Every - successor's input is unchanged: columns, types, row order, system tags, source info, - pipeline and content hashes. No hash, stored table or output changes. An operator node's - table is built once, for what it keeps and for every successor, instead of once to keep - and once per successor. The first two stages of the table transport between job nodes - (`docs/dev/specs/itl-1347-job-table-transport.md`). (ITL-1347, ITL-1360) + every successor. A node bound to a library source kind whose table is its rows + (`TABLE_IS_ROWS`) gives its source's Arrow table, and an operator node its result's + table (REPLAY: its stored table), each in the form a table built from the rows has, + without making the rows. Every other output (a narrower bind, another kind of bound + stream, a table the whole-table build cannot use, a result with no row, a held node, a + function or side-effect node) is the node's rows, unchanged, whose table is built where + a successor reads it, as before. `OrchestratorResult.node_outputs` holds each node's + output stream: its rows (`iter_data()`) are the rows the node returned, and its table is + built when the table is first read (`as_table()`, a successor's edge); on the sync path + a held node gives the stream of its held rows, and the async path still sends a held + node's rows as the run's plan took them (`held_rows`). Every successor's input is + unchanged: columns, types, row order, system tags, source info, pipeline and content + hashes, and an error surfaces where and when it did. No hash, stored table or output + changes. An operator node's table is built once, for what it keeps and for every + successor, instead of once to keep and once per successor. The first two stages of the + table transport between job nodes (`docs/dev/specs/itl-1347-job-table-transport.md`). + (ITL-1347, ITL-1360) ### Added - **`arrow_schema()` and `arrow_types_declared` on every stream** — `StreamProtocol`, every stream and every source node state the Arrow schema of the columns a job node - passes on (user tags, system tags, data and source info, in row order), without reading, - computing or polling a row. System-tag and source-info fields are stated nullable, since - a table decides their flags from its values; a `null` column keeps the `null` type of a - table with no rows. `arrow_types_declared` is false only for a stream that cannot type - itself without rows (an unbound slot, a `PollingSource` not yet polled), whose schema is - converted from its Python schema. (ITL-1360) + passes on (user tags, system tags, data and source info), without reading, computing or + polling a row. System-tag and source-info fields are stated nullable and a source-info + field's type as the declared token type: a complete table decides both from its values, + so a consumer must not rely on them. A `null` column keeps the `null` type of a table + with no rows. `arrow_types_declared` is false where the rows decide the types: a stream + that cannot type itself without rows (an unbound slot, a `PollingSource` not yet + polled), a narrower bind, and an output held as its rows. Such a description gives the + declared names and types, in no guaranteed order. (ITL-1360) diff --git a/docs/dev/specs/itl-1347-job-table-transport.md b/docs/dev/specs/itl-1347-job-table-transport.md index 086097dc3..f81936af1 100644 --- a/docs/dev/specs/itl-1347-job-table-transport.md +++ b/docs/dev/specs/itl-1347-job-table-transport.md @@ -529,6 +529,7 @@ built from them by `main`'s row path where a successor reads them (`RowsOnRead`, | e6 | Async values that depend on an earlier validation of the same operator object | `SemiJoin._validated_common_keys` and `Index._element_arrow_type_fallback` hold the last validation's values (ITL-858, section 1.2). One operator object applied to two streams can use the other stream's keys or fallback type | Read from each input's description, with no state | The ITL-858 finding; filed as ITL-1358. Reproducer: one `SemiJoin` instance validated on stream B, then run async over stream A with other keys. To be confirmed in stage 5 | ITL-1358 (filed); fixed with stage 5 once a reproducer confirms it | | e7 | What a consumer does after its producer failed (async, failure path) | The producer closes its output in `finally`, so a consumer sees a normal end and may finish, and a `LOG` operator node may store, a partial result before the task group cancels it | Readers raise `UpstreamFailedError` at the failure point instead of seeing a normal end, so no consumer finishes, or stores its result, as if its input were complete. Batches a consumer processed before the failure are still processed, and a streaming node may already have passed them on or a function node stored results for them, as on `main`; there is no rollback. A barrier operator never computes over a partial input. The run raises the producer's own error, as today | A candidate race, to be confirmed with a reproducer in stage 5: a `fail_fast` function node raising on row 3 of 6, feeding a `Select` node in `LOG` mode; check the operator cache after the failed run. If `main` never stores in practice, this row is no difference | filed by the developer only once a test reproduces it | | e8 | Meta columns of an async side-effect node's rows | An async side-effect node passes on and holds the rows it receives as they are, so a computed row keeps its `__computed` meta column (from the cached function pod), and the node's `as_table(all_info=True)` shows it. On sync, its input is rebuilt from rows (`_rows_to_table` drops meta), so the column is absent | Async drops input meta columns as sync does. With table transport this follows from the transport columns, which hold no meta column | A `main` bug: the async and sync paths give the node different columns. Found by the stage 0 harness on `job-speed` 0e15d0db, which does not change side-effect nodes; the stage 0 differential checks it on pinned `main`. Reproducer: a function node (with a result store) feeding a `tap_pod`, async against sync, comparing the side-effect node's `as_table(all_info=True)` columns | approved (developer, 2026-11-22) | +| e11 | An empty source fanned out to two operators, with an observer that rebinds the source between the two edges | Each successor's input is rebuilt at its own edge, so the second sees the rebound source's zero-row form (its field metadata) | The output held as its rows (`RowsOnRead`) is built once, at the first edge, and the second edge reuses it, so the second successor sees the first edge's form | Not a `main` bug: an observer that mutates the graph mid-run (Codex on PR #485, round 5). Reproducer: `tests/test_pipeline/test_rows_on_read.py::test_a_fanned_out_empty_source_rebound_between_edges` (strict xfail) | open: not approved; the coordinator takes it to the developer as a documented limit (2026-11-22) | **Resolved: refusals after rows have flowed (was c, question 9).** The developer's `Rejoin` rule (ITL-1355) removes every data-dependent refusal from `Rejoin`: it checks only what its diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index c7b237fe3..b839bddf9 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -1711,9 +1711,11 @@ def execute( # The result's table, as the table built from its rows would be, without # making the rows (ITL-1347, stage 2). result_table = result_stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS) - keys = result_stream.keys() + # The order the result's rows have (``result_keys``), never the prediction. + result_keys = getattr(result_stream, "result_keys", None) + keys = result_keys() if callable(result_keys) else result_stream.keys() tag_keys = keys[0] - data_tags = stream_data_tags(result_stream) + data_tags = data_tag_names(*keys) # Cache, in row order with or without rows (ITL-1131, ITL-1133). if result_table.num_rows: diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index 8795c9702..5732b3142 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -26,6 +26,7 @@ from orcapod.core.base import TraceableBase from orcapod.core.datagrams import Data, Tag from orcapod.core.operators.drop_nulls import _without_none # pyright: ignore[reportPrivateUsage] # DropNulls' rule for removing None from a type, shared, never copied +from orcapod.core.sources.base import table_is_rows from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.core.streams.base import ( ZERO_ROW_INPUT_COLUMNS, @@ -1836,7 +1837,7 @@ def _rows_table( ) if self._declared_form is not None: return None - if not getattr(type(self._bound_source), "TABLE_IS_ROWS", False): + if not table_is_rows(self._bound_source): # Not a library source kind whose table is its rows (a side-effect or # function pod stream, an operator's result, a raw stream, a poller): its # rows, as main iterated them. diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index d6fc8e1bd..0816a1bb2 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -1431,12 +1431,15 @@ async def async_iter_data( yield row def arrow_schema(self) -> pa.Schema: - """The node's declared description, from its Python schema; builds nothing. + """The node's own description (``arrow_schema()``); builds nothing. - The rows decide the Arrow types (``arrow_types_declared`` is false): a - description with undeclared types gives the declared names, with no - guaranteed order. + The rows decide the Arrow types (``arrow_types_declared`` is false): the + description gives the node's names and declared types, with no guaranteed + order. """ + describe = getattr(self._node, "arrow_schema", None) + if callable(describe): + return cast(pa.Schema, describe()) from orcapod.core.streams.base import stream_arrow_schema return stream_arrow_schema(self._node, from_table=False) @@ -1837,6 +1840,20 @@ def iter_data( ) return self._cached_stream.iter_data() + def result_keys(self) -> tuple[tuple[str, ...], tuple[str, ...]]: + """The keys of the stream the operator returned: the order its rows have. + + The prediction (``keys``) never reorders a result: an operator node keeps, + stores and hands on its result in the order its rows have, as ``main`` built + it from them (ITL-1347). + """ + self._refresh() + assert self._cached_stream is not None, ( + "StreamProtocol has not been updated or is empty." + ) + tag_keys, data_keys = self._cached_stream.keys() + return tuple(tag_keys), tuple(data_keys) + def head( self, n: int = 10, diff --git a/src/orcapod/core/record_batch_channels.py b/src/orcapod/core/record_batch_channels.py index 842e62a4a..da5edeb08 100644 --- a/src/orcapod/core/record_batch_channels.py +++ b/src/orcapod/core/record_batch_channels.py @@ -22,6 +22,7 @@ from orcapod.channels import ChannelClosed from orcapod.core.operators.static_output_pod import ( + SourceInfoTypesDisagree, stream_from_batches, transport_schema, ) @@ -150,6 +151,9 @@ def __init__( # batch's when the stream cannot say its Arrow types without rows. self._schema: pa.Schema | None = None self._schema_known = False + # Each source-info column's token type as the batches accepted so far settle it + # (``_settled_token_types``): a later batch must settle with it. + self._token_types: dict[str, pa.DataType] = {} self._changed = asyncio.Event() @property @@ -194,7 +198,7 @@ def _check_schema(self, batch: pa.RecordBatch) -> None: # stream's, in no guaranteed order (an undeclared description gives names # only). A refused batch sets nothing. names = batch.schema.names - if set(names) != set(row_built_names(names, self._stream.keys())): + if sorted(names) != sorted(row_built_names(names, self._stream.keys())): raise ValueError( f"A record batch sent as {_named(self._stream)} does not have that " + f"stream's columns: it has {names}, the stream's keys are " @@ -207,7 +211,9 @@ def _check_schema(self, batch: pa.RecordBatch) -> None: f"A record batch sent as {_named(self._stream)} does not have that " + f"stream's columns: {mismatch}." ) + token_types = _settled_token_types(batch, self._token_types) self._schema = schema + self._token_types = token_types async def send(self, batch: pa.RecordBatch) -> None: """Send one Arrow record batch of the stream's transport columns. @@ -356,6 +362,48 @@ def _named(stream: Any) -> str: # pyright: ignore[reportExplicitAny] # any str return repr(label) if label else repr(stream) +def _settled_token_types( + batch: pa.RecordBatch, accepted: dict[str, pa.DataType] +) -> dict[str, pa.DataType]: + """Each source-info column's token type, settled with the batches already accepted. + + A source-info column's type follows its tokens over the complete table + (``StaticOutputOperatorPod._type_source_info_by_values``): the description leaves it + open, but the channel's batches must settle together, or their result could not be + built. A batch whose tokens give a column a type the accepted batches do not is + refused at send, with the error the complete table would raise. + + Args: + batch: The batch being sent. + accepted: Each column's token type from the batches accepted so far. + + Returns: + The token types with this batch accepted. + + Raises: + SourceInfoTypesDisagree: If the batch's tokens give a column two types, or a + type other than the accepted batches'. + """ + settled = dict(accepted) + for field, column in zip(batch.schema, batch.columns, strict=True): + if not field.name.startswith(constants.SOURCE_PREFIX): + continue + if pa.types.is_large_string(field.type): + kinds = {pa.large_string()} + else: + kinds = { + arrow_utils.source_info_arrow_type(value) + for value in column.to_pylist() + } + if field.name in settled: + kinds.add(settled[field.name]) + if len(kinds) > 1: + raise SourceInfoTypesDisagree(field.name) + if kinds: + (settled[field.name],) = kinds + return settled + + 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``. diff --git a/src/orcapod/core/sources/base.py b/src/orcapod/core/sources/base.py index 1f8eef123..4b62f45dd 100644 --- a/src/orcapod/core/sources/base.py +++ b/src/orcapod/core/sources/base.py @@ -47,6 +47,40 @@ def saved_tag_only_columns(config: dict[str, Any]) -> bool | list[str]: return config["tag_only_columns"] +_ROW_READERS = ( + "iter_data", + "as_table", + "__iter__", + "async_iter_data", + "keys", + "output_schema", +) +"""The members a source's rows and table are read through.""" + + +def table_is_rows(source: object) -> bool: + """Whether ``source``'s ``as_table()`` and ``iter_data()`` provably read the same data. + + True only when the class that declares ``TABLE_IS_ROWS = True`` (a library source + kind) reads ``source``: ``source``'s own class, or a subclass that overrides none of + the members the rows and the table are read through (``_ROW_READERS``). A subclass + that changes how it reads (a filtering ``iter_data``) is not that kind any more, and + a job node bound to it hands on its rows, as ``main`` iterated them (ITL-1347). + + Args: + source: The object bound to a source slot. + + Returns: + Whether F of its table is the table its rows give. + """ + for klass in type(source).__mro__: + if "TABLE_IS_ROWS" in vars(klass): + return bool(vars(klass)["TABLE_IS_ROWS"]) + if any(name in vars(klass) for name in _ROW_READERS): + return False + return False + + class RootSource(StreamBase): """Abstract base class for all root sources in Orcapod. diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py index c61c38c17..00fa55f40 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -415,8 +415,26 @@ def stream_arrow_schema( # reads). A source's tokens are strings, so each data column's source info is # a string field. tag_schema, data_schema = typed.output_schema(columns={"system_tags": True}) - converter = StaticOutputOperatorPod._upstream_context(typed).type_converter # pyright: ignore[reportPrivateUsage] # the one place that resolves an upstream's context - table = arrow_utils.make_empty_table({**tag_schema, **data_schema}, converter) + stated = getattr(stream, "arrow_schemas", None) + if isinstance(stated, tuple): + # The Arrow types the stream declares itself (a slot): never a conversion + # of its Python types, which may have no Arrow type of their own. + tag_arrow, data_arrow = cast("tuple[pa.Schema, pa.Schema]", stated) + fields = [ + *tag_arrow, + *( + pa.field(name, pa.large_string()) + for name in tag_schema + if name not in tag_arrow.names + ), + *(f for f in data_arrow if f.name not in tag_arrow.names), + ] + table = pa.schema(fields).empty_table() + else: + converter = StaticOutputOperatorPod._upstream_context(typed).type_converter # pyright: ignore[reportPrivateUsage] # the one place that resolves an upstream's context + table = arrow_utils.make_empty_table( + {**tag_schema, **data_schema}, converter + ) for name in data_schema: table = table.append_column( pa.field(f"{constants.SOURCE_PREFIX}{name}", pa.large_string()), diff --git a/tests/test_channels/test_record_batch_channels.py b/tests/test_channels/test_record_batch_channels.py index fe6767385..cf99ec808 100644 --- a/tests/test_channels/test_record_batch_channels.py +++ b/tests/test_channels/test_record_batch_channels.py @@ -1910,3 +1910,50 @@ def test_stream_from_batches_is_the_one_conversion() -> None: made = stream_from_batches(stream, batches_of(stream, rows)) assert same(made.as_table(columns=ALL), R(stream)) assert stream_from_batches(stream, []).as_table().num_rows == 0 + + +def test_a_batch_with_a_duplicate_column_is_refused() -> None: + """Without Arrow types the names are compared as a multiset: a duplicate is refused + (Codex on PR #485, round 5).""" + table = source().as_table(columns=ALL) + stream = _UntypedStream( + table, tag_columns=["subject", "trial"], data_tags=["trial"] + ) + (batch,) = batches_of(stream) + name = next(n for n in batch.schema.names if not n.startswith(("_", "subject"))) + doubled = batch.append_column(batch.schema.field(name), batch.column(name)) + + async def write() -> None: + output = OutputChannel(stream) + await output.send(doubled) + + with pytest.raises(ValueError, match="the stream's keys are"): + run(write) + + +def test_a_batch_whose_tokens_cannot_settle_with_accepted_ones_is_refused() -> None: + """A second batch with list tokens where the first had string tokens is refused at + send, with the error the complete table would raise (Codex on PR #485, round 5).""" + from orcapod.core.operators.static_output_pod import SourceInfoTypesDisagree + + stream = source() + (batch,) = batches_of(stream) + column = next(n for n in batch.schema.names if n.startswith("_source_")) + position = batch.schema.get_field_index(column) + tokens = pa.large_list(pa.large_string()) + listed = pa.RecordBatch.from_arrays( + [ + *batch.columns[:position], + pa.array([["t"]] * batch.num_rows, tokens), + *batch.columns[position + 1 :], + ], + schema=batch.schema.set(position, pa.field(column, tokens, nullable=True)), + ) + + async def write() -> None: + output = OutputChannel(stream) + await output.send(batch) + await output.send(listed) + + with pytest.raises(SourceInfoTypesDisagree, match=column): + run(write) diff --git a/tests/test_pipeline/test_rows_on_read.py b/tests/test_pipeline/test_rows_on_read.py index 97fa85171..b237f1987 100644 --- a/tests/test_pipeline/test_rows_on_read.py +++ b/tests/test_pipeline/test_rows_on_read.py @@ -434,3 +434,174 @@ def test_a_lazy_output_is_described_and_opened_without_reading() -> None: assert out._stream is None # pyright: ignore[reportPrivateUsage] # nothing built with pytest.raises(pa.ArrowTypeError, match="Expected bytes"): asyncio.run(channel.collect()) + + +# ── round 5 ────────────────────────────────────────────────────────────────── + + +def _subclass_overriding(member: str) -> type: + """An ``ArrowTableSource`` subclass that overrides ``member`` (reading as before).""" + from orcapod.core.sources import ArrowTableSource as Base + + def through(self: Any, *args: Any, **kwargs: Any) -> Any: + return getattr(super(cls, self), member)(*args, **kwargs) + + cls = type(f"Overrides_{member}", (Base,), {member: through}) + return cls + + +@pytest.mark.parametrize( + "member", + ["iter_data", "as_table", "__iter__", "async_iter_data", "keys", "output_schema"], +) +def test_a_subclass_that_overrides_a_reader_is_not_a_table_is_rows_kind( + member: str, +) -> None: + """``TABLE_IS_ROWS`` is not inherited past an override of how rows are read.""" + from orcapod.core.sources.base import table_is_rows + + table = _source_table().select(["k", "x"]) + cls = _subclass_overriding(member) + source = cls(table, tag_columns=["k"], tag_only_columns=True, source_id="s") + assert not table_is_rows(source) + plain = ArrowTableSource( + table, tag_columns=["k"], tag_only_columns=True, source_id="s" + ) + assert table_is_rows(plain) + subclass = type("Plain", (ArrowTableSource,), {}) + assert table_is_rows( + subclass(table, tag_columns=["k"], tag_only_columns=True, source_id="s") + ) + + +def test_a_filtering_subclass_delivers_only_its_rows() -> None: + """A subclass whose ``iter_data`` filters is read through it, as on ``main``.""" + + class AboveTen(ArrowTableSource): + def iter_data(self) -> Any: + return (row for row in super().iter_data() if row[1]["x"] > 10) + + table = pa.table({"k": pa.array([1, 2]), "x": pa.array([10, 20])}) + job = PipelineJob(name="filtering", database=InMemoryArrowDatabase()) + with job: + ArrowTableSource( + table, tag_columns=["k"], tag_only_columns=True, source_id="s" + ).select_data_columns(["x"], label="selected") + job.bind( + sources={ + "s": AboveTen( + table, tag_columns=["k"], tag_only_columns=True, source_id="s" + ) + } + ) + job.run() + assert job.nodes["selected"].as_table()["x"].to_pylist() == [20] + + +def test_an_operator_result_keeps_its_own_column_order() -> None: + """A result laid out ``y, x`` against a prediction ``x, y`` is kept, stored and + handed on as ``y, x``, as ``main`` built it from the result's rows.""" + from orcapod.operators import SelectDataColumns + + class Reordered(SelectDataColumns): + def unary_static_process(self, stream: Any) -> Any: + out: Any = super().unary_static_process(stream) + table = out.as_table(columns={"source": True, "system_tags": True}) + names = [n for n in table.column_names if n not in ("x", "y")] + plain = [n for n in names if not n.startswith("_source_")] + source = ["_source_y", "_source_x"] + rest = [n for n in names if n.startswith("_source_") and n not in source] + return ArrowTableStream( + table.select([*plain, "y", "x", *source, *rest]), tag_columns=["k"] + ) + + database = InMemoryArrowDatabase() + job = PipelineJob(name="reordered", database=database) + with job: + source = DictSource( + [{"k": 1, "x": 1, "y": 2}, {"k": 2, "x": 3, "y": 4}], + tag_columns=["k"], + tag_only_columns=True, + source_id="s", + ) + Batch(batch_size=2)(Reordered(["x", "y"])(source, label="reordered"), label="b") + job.nodes["reordered"].attach_databases( + pipeline_database=database.at("log"), cache_mode=CacheMode.LOG + ) + job.run() + expected = ["k", "y", "x", "_source_y", "_source_x"] + node = job.nodes["reordered"] + assert node.as_table(columns={"source": True}).column_names == expected + stored = node.get_all_records(columns={"source": True}) + assert stored is not None + assert [n for n in stored.column_names if not n.startswith("__")] == expected + assert job.nodes["b"].as_table(columns={"source": True}).column_names == expected + + +@pytest.mark.parametrize( + "kind", + [pa.time64("ns"), pa.decimal256(76, 40)], + ids=["time64ns", "decimal256"], +) +def test_a_lazy_output_describes_itself_without_converting_python_types( + kind: pa.DataType, +) -> None: + """Types with no Python type of their own are described from the node, never raised.""" + values = ( + pa.array([1, 2]).cast(kind) + if pa.types.is_decimal(kind) + else pa.array([1, 2], kind) + ) + base = pa.table({"k": pa.array([1, 2], pa.int64()), "x": values}) + base = base.cast(pa.schema([f.with_nullable(False) for f in base.schema])) + source = ArrowTableSource( + base, tag_columns=["k"], tag_only_columns=True, source_id="s" + ) + raw = ArrowTableStream( + source.as_table(columns={"source": True, "system_tags": True}), + tag_columns=["k"], + ) + job = PipelineJob(name="lazy_types", database=InMemoryArrowDatabase()) + with job: + source.select_data_columns(["x"], label="selected") + job.bind(sources={"s": raw}) + out: Any = job.nodes["s"].execute() + assert out.arrow_schema().field("x").type == kind + + +@pytest.mark.xfail( + strict=True, + raises=AssertionError, + reason="spec row e11: observer rebinds between two edges of one empty output (open)", +) +def test_a_fanned_out_empty_source_rebound_between_edges() -> None: + """Pinned limit (spec row e11): ``main`` rebuilds each edge, the branch builds once.""" + from orcapod.operators import SelectDataColumns + + def empty(mark: str) -> ArrowTableSource: + field = pa.field("x", pa.int64(), nullable=False, metadata={"mark": mark}) + table = pa.Table.from_arrays( + [pa.array([], pa.int64()), pa.array([], pa.int64())], + schema=pa.schema([pa.field("k", pa.int64(), nullable=False), field]), + ) + return ArrowTableSource(table, tag_columns=["k"], source_id="s") + + job = PipelineJob(name="fan_out_empty", database=InMemoryArrowDatabase()) + with job: + source = empty("initial") + SelectDataColumns(["x"])(source, label="first") + SelectDataColumns(["x"])(source, label="second") + slot = next(label for label in job.nodes if label not in ("first", "second")) + node = job.nodes[slot] + + class RebindsAfterFirst(NoOpObserver): + def contextualize(self, *identity_path: str) -> RebindsAfterFirst: + return self + + def on_node_end(self, node_label: str, node_hash: str) -> None: + if node_label == "first": + node.bound_source = empty("next") + + job.run(observer=RebindsAfterFirst()) + kept = job.nodes["second"].as_table() + assert kept.schema.field("x").metadata == {b"mark": b"next"} From 14b28b96d6391129be53665eddbbae089d83b0ba Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 10:13:57 -0800 Subject: [PATCH 30/36] fix(pipeline): type the result keys and token kinds for basedpyright (ITL-1360) Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/nodes/operator_node.py | 8 ++++++-- src/orcapod/core/record_batch_channels.py | 1 + 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index b839bddf9..dcfdfebdc 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -39,6 +39,7 @@ from orcapod.channels import Channel, ChannelClosed, ReadableChannel, WritableChannel from orcapod.config import OrcapodConfig from orcapod.core.operators.static_output_pod import ( + DynamicPodStream, RowBuiltFormUnavailable, StaticOutputOperatorPod, rows_on_read, @@ -1712,8 +1713,11 @@ def execute( # making the rows (ITL-1347, stage 2). result_table = result_stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS) # The order the result's rows have (``result_keys``), never the prediction. - result_keys = getattr(result_stream, "result_keys", None) - keys = result_keys() if callable(result_keys) else result_stream.keys() + keys: tuple[tuple[str, ...], tuple[str, ...]] = ( + result_stream.result_keys() + if isinstance(result_stream, DynamicPodStream) + else result_stream.keys() + ) tag_keys = keys[0] data_tags = data_tag_names(*keys) diff --git a/src/orcapod/core/record_batch_channels.py b/src/orcapod/core/record_batch_channels.py index da5edeb08..d744f3c22 100644 --- a/src/orcapod/core/record_batch_channels.py +++ b/src/orcapod/core/record_batch_channels.py @@ -388,6 +388,7 @@ def _settled_token_types( for field, column in zip(batch.schema, batch.columns, strict=True): if not field.name.startswith(constants.SOURCE_PREFIX): continue + kinds: set[pa.DataType] if pa.types.is_large_string(field.type): kinds = {pa.large_string()} else: From 352ce7b95bf698d14d594fa9ee7c89dd6bd27c6e Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 11:01:46 -0800 Subject: [PATCH 31/36] fix(pipeline): eager only for exactly a proven class; result order from the stream holding the rows (ITL-1360) Codex on PR #485, final check. - One precondition, positive and exact (reads_as_its_class): the stream that holds the rows is exactly a class whose whole-table read is its rows, and nothing on the instance shadows one of that class's methods or properties. No inspection of overrides. Applied in two places: - a bound source: its class itself declares TABLE_IS_ROWS (table_is_rows); a subclass, a mixin, an instance-replaced reader or a _stream property hands on its rows, as main iterated them. SQLiteTableSource and PostgreSQLTableSource now declare the flag on their own class. - an operator's result: followed through every DynamicPodStream (produced_stream) to the stream holding its rows; exactly an ArrowTableStream gives its own keys() (the keys iter_data reads its rows with), any other kind takes main's row path verbatim. - Spec and changelog state the rule. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1360.md | 16 +- .../dev/specs/itl-1347-job-table-transport.md | 12 ++ src/orcapod/core/nodes/operator_node.py | 89 +++++---- .../core/operators/static_output_pod.py | 31 ++- src/orcapod/core/sources/base.py | 43 ++-- src/orcapod/core/sources/cached_source.py | 2 +- src/orcapod/core/sources/csv_source.py | 2 +- src/orcapod/core/sources/db_table_source.py | 2 +- .../core/sources/delta_table_source.py | 2 +- .../core/sources/postgresql_table_source.py | 1 + .../core/sources/spiraldb_table_source.py | 2 +- .../core/sources/sqlite_table_source.py | 1 + src/orcapod/core/streams/base.py | 33 ++++ tests/test_pipeline/test_rows_on_read.py | 187 +++++++++++++++++- 14 files changed, 336 insertions(+), 87 deletions(-) diff --git a/changelog.d/ITL-1360.md b/changelog.d/ITL-1360.md index dbe931f26..51b12db1a 100644 --- a/changelog.d/ITL-1360.md +++ b/changelog.d/ITL-1360.md @@ -4,13 +4,15 @@ function and side-effect job node (and of the node protocols) returned the node's rows as a list of (tag, data) pairs, and the sync orchestrator rebuilt a table from them for each successor. It now returns the node's output stream, which the sync orchestrator hands to - every successor. A node bound to a library source kind whose table is its rows - (`TABLE_IS_ROWS`) gives its source's Arrow table, and an operator node its result's - table (REPLAY: its stored table), each in the form a table built from the rows has, - without making the rows. Every other output (a narrower bind, another kind of bound - stream, a table the whole-table build cannot use, a result with no row, a held node, a - function or side-effect node) is the node's rows, unchanged, whose table is built where - a successor reads it, as before. `OrchestratorResult.node_outputs` holds each node's + every successor. A node bound to an instance of exactly a library source kind whose + table is its rows (`TABLE_IS_ROWS`, never inherited by a subclass) gives its source's + Arrow table, and an operator node whose result yields its rows from exactly an + `ArrowTableStream` its result's table in that stream's row order (REPLAY: its stored + table), each in the form a table built from the rows has, without making the rows. + Every other output (a narrower bind, a subclass or another kind of bound stream, an + operator result of another stream kind, a table the whole-table build cannot use, a + result with no row, a held node, a function or side-effect node) is the node's rows, + unchanged, whose table is built where a successor reads it, as before. `OrchestratorResult.node_outputs` holds each node's output stream: its rows (`iter_data()`) are the rows the node returned, and its table is built when the table is first read (`as_table()`, a successor's edge); on the sync path a held node gives the stream of its held rows, and the async path still sends a held diff --git a/docs/dev/specs/itl-1347-job-table-transport.md b/docs/dev/specs/itl-1347-job-table-transport.md index f81936af1..dc60bc475 100644 --- a/docs/dev/specs/itl-1347-job-table-transport.md +++ b/docs/dev/specs/itl-1347-job-table-transport.md @@ -520,6 +520,18 @@ stage. Where building a node's output from its whole table is not provably `main node, a node whose output is still its rows), the node hands on its rows and the table is built from them by `main`'s row path where a successor reads them (`RowsOnRead`, `at_edge`): `main`'s order, error and moment by construction (Codex on PR #485, round 3). +"Provably" is one precondition, positive and exact, never an inspection of overrides +(Codex on PR #485, final check): **the stream that holds the rows is exactly a class whose +whole-table read is its rows, and nothing on the instance shadows one of that class's +methods or properties** (`reads_as_its_class`). It is applied in two places: + +- a bound source: its class is a library source kind that itself declares + `TABLE_IS_ROWS` (`table_is_rows`); +- an operator's result: the stream it yields its rows from, followed through every + `DynamicPodStream` (`produced_stream`), is `ArrowTableStream`, and its own `keys()` (the + keys `iter_data` reads its rows with, tags in its tag-column order) give the order. + +Any subclass, replaced reader or other stream kind takes `main`'s row path. | # | What differs | On `main` today | On the branch | Why `main` is wrong (bug, reproducer) | Approval needed | |---|---|---|---|---|---| diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index dcfdfebdc..4227c2cc8 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -39,9 +39,9 @@ from orcapod.channels import Channel, ChannelClosed, ReadableChannel, WritableChannel from orcapod.config import OrcapodConfig from orcapod.core.operators.static_output_pod import ( - DynamicPodStream, RowBuiltFormUnavailable, StaticOutputOperatorPod, + produced_stream, rows_on_read, ) from orcapod.core.streams.arrow_table_stream import ArrowTableStream @@ -49,6 +49,7 @@ ZERO_ROW_INPUT_COLUMNS, StreamBase, check_head_size, + reads_as_its_class, short_stream_repr, ) from orcapod.core.streams.view import ( @@ -1708,37 +1709,55 @@ def execute( # Compute result_stream = self._operator.process(*input_streams) - - # The result's table, as the table built from its rows would be, without - # making the rows (ITL-1347, stage 2). - result_table = result_stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS) - # The order the result's rows have (``result_keys``), never the prediction. - keys: tuple[tuple[str, ...], tuple[str, ...]] = ( - result_stream.result_keys() - if isinstance(result_stream, DynamicPodStream) - else result_stream.keys() - ) - tag_keys = keys[0] - data_tags = data_tag_names(*keys) - - # Cache, in row order with or without rows (ITL-1131, ITL-1133). - if result_table.num_rows: - try: - kept_table = StaticOutputOperatorPod._row_built_form( - result_table, keys - ) - except RowBuiltFormUnavailable as error: - StaticOutputOperatorPod._raise_as_rows_do( - result_stream.iter_data(), error - ) - self._cached_output_stream = ArrowTableStream( - kept_table, tag_columns=tag_keys, data_tags=data_tags + produced = produced_stream(result_stream) + + output: StreamProtocol + if not reads_as_its_class(produced, ArrowTableStream): + # A result that is not exactly a stream over its table (a custom + # stream kind, a replaced reader): main's own row path, its rows read + # once, its table built where a successor reads it (ITL-1347). + rows = list(result_stream.iter_data()) + self._cached_output_stream = StaticOutputOperatorPod._kept_output( + result_stream, rows ) + output = rows_on_read(rows, self) else: - kept_table = None - self._cached_output_stream = ( - StaticOutputOperatorPod._zero_rows_in_row_order(result_stream) - ) + # The result's table, as the table built from its rows would be, + # without making the rows (ITL-1347, stage 2). An exact + # ``ArrowTableStream``'s ``keys()`` are the keys its rows are read with + # (``iter_data``), so they are the order of the result's rows, to any + # depth of composition, never the prediction. + result_table = result_stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS) + keys = produced.keys() + tag_keys = keys[0] + data_tags = data_tag_names(*keys) + + # Cache, in row order with or without rows (ITL-1131, ITL-1133). + if result_table.num_rows: + try: + kept_table = StaticOutputOperatorPod._row_built_form( + result_table, keys + ) + except RowBuiltFormUnavailable as error: + StaticOutputOperatorPod._raise_as_rows_do( + result_stream.iter_data(), error + ) + self._cached_output_stream = ArrowTableStream( + kept_table, tag_columns=tag_keys, data_tags=data_tags + ) + # The output stream, built once the node holds its run (as the + # sync orchestrator built a successor's input after ``execute`` + # returned). + output = StaticOutputOperatorPod._as_upstream_stream( + kept_table, tag_keys, data_tags, self + ) + else: + self._cached_output_stream = ( + StaticOutputOperatorPod._zero_rows_in_row_order(result_stream) + ) + # Its zero-row form is derived where a successor reads it, as on + # main: the operator is not called again here (``RowsOnRead``). + output = rows_on_read([], self) self._update_modified_time() @@ -1751,16 +1770,6 @@ def execute( ): self._store_output_stream(self._cached_output_stream) - # The output stream, built once the node holds its run (as the sync - # orchestrator built a successor's input after ``execute`` returned). - if kept_table is not None: - output = StaticOutputOperatorPod._as_upstream_stream( - kept_table, tag_keys, data_tags, self - ) - else: - # Its zero-row form is derived where a successor reads it, as on main: - # the operator is not called again here (``RowsOnRead``). - output = rows_on_read([], self) ctx_obs.on_node_end(node_label, node_hash) return output except BaseException: diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index 0816a1bb2..90209a8a8 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -1612,6 +1612,25 @@ def pipeline_hash( return self._input_pipeline_hash +def produced_stream(stream: StreamProtocol) -> StreamProtocol: + """Return the stream whose rows ``stream`` yields, through any depth of composition. + + An operator's result is a ``DynamicPodStream`` whose rows are those of the stream + its ``static_process`` returned, which may itself be another operator's + ``DynamicPodStream``: this follows them all to the stream that holds the rows + (ITL-1347). + + Args: + stream: An operator's result, or any stream. + + Returns: + The stream that holds ``stream``'s rows. + """ + while isinstance(stream, DynamicPodStream): + stream = stream.produced_stream() + return stream + + class DynamicPodStream(StreamBase): """Recomputable stream wrapping a ``StaticOutputOperatorPod`` invocation.""" @@ -1840,19 +1859,17 @@ def iter_data( ) return self._cached_stream.iter_data() - def result_keys(self) -> tuple[tuple[str, ...], tuple[str, ...]]: - """The keys of the stream the operator returned: the order its rows have. + def produced_stream(self) -> StreamProtocol: + """The stream the operator returned for the current inputs (computed if stale). - The prediction (``keys``) never reorders a result: an operator node keeps, - stores and hands on its result in the order its rows have, as ``main`` built - it from them (ITL-1347). + Its rows are this stream's rows; ``produced_stream`` (the module function) + follows it through every ``DynamicPodStream`` to the stream that holds them. """ self._refresh() assert self._cached_stream is not None, ( "StreamProtocol has not been updated or is empty." ) - tag_keys, data_keys = self._cached_stream.keys() - return tuple(tag_keys), tuple(data_keys) + return self._cached_stream def head( self, diff --git a/src/orcapod/core/sources/base.py b/src/orcapod/core/sources/base.py index 4b62f45dd..fdaa3cdd1 100644 --- a/src/orcapod/core/sources/base.py +++ b/src/orcapod/core/sources/base.py @@ -6,6 +6,7 @@ from orcapod.config import OrcapodConfig from orcapod.core.streams.base import ( StreamBase, + reads_as_its_class, typed_arrow_schemas, typed_zero_row_table, ) @@ -47,25 +48,15 @@ def saved_tag_only_columns(config: dict[str, Any]) -> bool | list[str]: return config["tag_only_columns"] -_ROW_READERS = ( - "iter_data", - "as_table", - "__iter__", - "async_iter_data", - "keys", - "output_schema", -) -"""The members a source's rows and table are read through.""" - - def table_is_rows(source: object) -> bool: """Whether ``source``'s ``as_table()`` and ``iter_data()`` provably read the same data. - True only when the class that declares ``TABLE_IS_ROWS = True`` (a library source - kind) reads ``source``: ``source``'s own class, or a subclass that overrides none of - the members the rows and the table are read through (``_ROW_READERS``). A subclass - that changes how it reads (a filtering ``iter_data``) is not that kind any more, and - a job node bound to it hands on its rows, as ``main`` iterated them (ITL-1347). + Positive and exact (ITL-1347): true only when ``source``'s class itself declares + ``TABLE_IS_ROWS = True`` (a library source kind) and ``source`` reads as that class + (``reads_as_its_class``: its exact type, no member replaced on the instance). Any + subclass, a mixin, a replaced reader or a property that changes what the source + reads through is not proven, and a job node bound to it hands on its rows, as + ``main`` iterated them. Args: source: The object bound to a source slot. @@ -73,12 +64,8 @@ def table_is_rows(source: object) -> bool: Returns: Whether F of its table is the table its rows give. """ - for klass in type(source).__mro__: - if "TABLE_IS_ROWS" in vars(klass): - return bool(vars(klass)["TABLE_IS_ROWS"]) - if any(name in vars(klass) for name in _ROW_READERS): - return False - return False + kind = type(source) + return vars(kind).get("TABLE_IS_ROWS") is True and reads_as_its_class(source, kind) class RootSource(StreamBase): @@ -130,11 +117,13 @@ class RootSource(StreamBase): TABLE_IS_ROWS: ClassVar[bool] = False """Whether ``as_table()`` and ``iter_data()`` read the same data, with no effect. - Declared ``True`` only by the library source kinds that read one stream either way - (ITL-1347): a job node bound to one hands on F of its table, which equals the table - built from its rows. Any other bound stream (a side-effect or function pod stream, - an operator's result, a raw stream, a source kind that polls or delivers on a read) - hands on its rows (``RowsOnRead``), as ``main`` iterated them. + Declared ``True`` only by the library source kinds that read one stream either way, + each on its own class: it is read for the exact class only, never inherited + (``table_is_rows``; ITL-1347). A job node bound to an instance of exactly such a + class hands on F of its table, which equals the table built from its rows. Any + other bound stream (a subclass, a side-effect or function pod stream, an operator's + result, a raw stream, a source kind that polls or delivers on a read) hands on its + rows (``RowsOnRead``), as ``main`` iterated them. """ def __init__( diff --git a/src/orcapod/core/sources/cached_source.py b/src/orcapod/core/sources/cached_source.py index 98e531222..a9bfd8f08 100644 --- a/src/orcapod/core/sources/cached_source.py +++ b/src/orcapod/core/sources/cached_source.py @@ -79,8 +79,8 @@ class CachedSource(RootSource): """ SOURCE_KIND: ClassVar[str] = "cached" - TABLE_IS_ROWS: ClassVar[bool] = True """Config type key and default source-id kind of this source (one vocabulary).""" + TABLE_IS_ROWS: ClassVar[bool] = True HASH_COLUMN_NAME = "_record_hash" diff --git a/src/orcapod/core/sources/csv_source.py b/src/orcapod/core/sources/csv_source.py index bfd0b423d..9a0d99dcf 100644 --- a/src/orcapod/core/sources/csv_source.py +++ b/src/orcapod/core/sources/csv_source.py @@ -276,8 +276,8 @@ class CSVSource(RootSource): """ SOURCE_KIND: ClassVar[str] = "csv" - TABLE_IS_ROWS: ClassVar[bool] = True """Config type key and default source-id kind of this source (one vocabulary).""" + TABLE_IS_ROWS: ClassVar[bool] = True TAKES_TAG_ONLY_COLUMNS: ClassVar[bool] = True def __init__( diff --git a/src/orcapod/core/sources/db_table_source.py b/src/orcapod/core/sources/db_table_source.py index 721b2308d..a95c316f2 100644 --- a/src/orcapod/core/sources/db_table_source.py +++ b/src/orcapod/core/sources/db_table_source.py @@ -80,8 +80,8 @@ class DBTableSource(RootSource): """ SOURCE_KIND: ClassVar[str] = "db_table" - TABLE_IS_ROWS: ClassVar[bool] = True """Config type key and default source-id kind of this source (one vocabulary).""" + TABLE_IS_ROWS: ClassVar[bool] = True TAKES_TAG_ONLY_COLUMNS: ClassVar[bool] = True def __init__( diff --git a/src/orcapod/core/sources/delta_table_source.py b/src/orcapod/core/sources/delta_table_source.py index 2a60e6304..c744b3913 100644 --- a/src/orcapod/core/sources/delta_table_source.py +++ b/src/orcapod/core/sources/delta_table_source.py @@ -49,8 +49,8 @@ class DeltaTableSource(RootSource): """ SOURCE_KIND: ClassVar[str] = "delta_table" - TABLE_IS_ROWS: ClassVar[bool] = True """Config type key and default source-id kind of this source (one vocabulary).""" + TABLE_IS_ROWS: ClassVar[bool] = True TAKES_TAG_ONLY_COLUMNS: ClassVar[bool] = True def __init__( diff --git a/src/orcapod/core/sources/postgresql_table_source.py b/src/orcapod/core/sources/postgresql_table_source.py index 0f12aa372..bc2b437b2 100644 --- a/src/orcapod/core/sources/postgresql_table_source.py +++ b/src/orcapod/core/sources/postgresql_table_source.py @@ -172,6 +172,7 @@ class PostgreSQLTableSource(DBTableSource): SOURCE_KIND: ClassVar[str] = "postgresql_table" """Config type key and default source-id kind of this source (one vocabulary).""" + TABLE_IS_ROWS: ClassVar[bool] = True def __init__( self, diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index af04d5f34..c6c271657 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -374,8 +374,8 @@ class SpiralDBTableSource(RootSource): """ SOURCE_KIND: ClassVar[str] = "spiraldb_table" - TABLE_IS_ROWS: ClassVar[bool] = True """Config type key and default source-id kind of this source (one vocabulary).""" + TABLE_IS_ROWS: ClassVar[bool] = True TAKES_TAG_ONLY_COLUMNS: ClassVar[bool] = True # Whether a notebook display reads the first rows. False shows the schema and the diff --git a/src/orcapod/core/sources/sqlite_table_source.py b/src/orcapod/core/sources/sqlite_table_source.py index f4e753553..9353ea07c 100644 --- a/src/orcapod/core/sources/sqlite_table_source.py +++ b/src/orcapod/core/sources/sqlite_table_source.py @@ -101,6 +101,7 @@ class SQLiteTableSource(DBTableSource): SOURCE_KIND: ClassVar[str] = "sqlite_table" """Config type key and default source-id kind of this source (one vocabulary).""" + TABLE_IS_ROWS: ClassVar[bool] = True def __init__( self, diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py index 00fa55f40..26e05c0ce 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -1,5 +1,7 @@ from __future__ import annotations +import functools +import inspect import logging from abc import abstractmethod from collections import deque @@ -48,6 +50,37 @@ logger = logging.getLogger(__name__) +def reads_as_its_class(obj: object, cls: type) -> bool: + """Whether ``obj`` is exactly ``cls`` and reads only through ``cls``'s own members. + + Exact, never by inspection of what a subclass overrides: ``type(obj) is cls``, and + ``obj`` holds no attribute of its own that shadows a method or a property of + ``cls`` (an ``iter_data`` replaced on the instance). A ``functools.cached_property`` + keeps its value in the instance by design and is not a shadow. A subclass, however + small, is never ``cls`` here (ITL-1347). + + Args: + obj: The object to check. + cls: The class whose reading is proven. + + Returns: + Whether ``obj`` reads as ``cls`` does. + """ + if type(obj) is not cls: + return False + own = getattr(obj, "__dict__", None) + if not own: + return True + missing = object() + for name in own: + member = inspect.getattr_static(cls, name, missing) + if member is missing or isinstance(member, functools.cached_property): + continue + if callable(member) or hasattr(type(member), "__get__"): + return False + return True + + def schema_requires_io(stream: object, config: ColumnConfig) -> bool: """Whether reading ``stream``'s schema with ``config`` would read or poll a source. diff --git a/tests/test_pipeline/test_rows_on_read.py b/tests/test_pipeline/test_rows_on_read.py index b237f1987..68c9d3770 100644 --- a/tests/test_pipeline/test_rows_on_read.py +++ b/tests/test_pipeline/test_rows_on_read.py @@ -468,8 +468,9 @@ def test_a_subclass_that_overrides_a_reader_is_not_a_table_is_rows_kind( table, tag_columns=["k"], tag_only_columns=True, source_id="s" ) assert table_is_rows(plain) + # Exact, never by inspection: a subclass that overrides nothing is not proven. subclass = type("Plain", (ArrowTableSource,), {}) - assert table_is_rows( + assert not table_is_rows( subclass(table, tag_columns=["k"], tag_only_columns=True, source_id="s") ) @@ -538,6 +539,190 @@ def unary_static_process(self, stream: Any) -> Any: assert job.nodes["b"].as_table(columns={"source": True}).column_names == expected +# ── final check: the eager route is positive and exact ──────────────────────── + + +def _only_above_ten(rows: Any) -> Any: + return (row for row in rows if row[1]["x"] > 10) + + +class _FilteringStream(ArrowTableStream): + def iter_data(self) -> Any: + return _only_above_ten(super().iter_data()) + + +class _ReadsThroughAProperty(ArrowTableSource): + """Reads through a ``_stream`` property that hands on a filtering stream.""" + + @property + def _stream(self) -> Any: + return getattr(self, "saved_stream") + + @_stream.setter + def _stream(self, base: Any) -> None: + self.saved_stream = _FilteringStream( + base.as_table(columns={"source": True, "system_tags": True}), + tag_columns=["k"], + ) + + +def _bound_selection(source: Any) -> list[int]: + """Bind ``source`` to a slot feeding a selection; return what the sync run keeps.""" + table = pa.table({"k": pa.array([1, 2]), "x": pa.array([10, 20])}) + job = PipelineJob(name="exact", database=InMemoryArrowDatabase()) + with job: + ArrowTableSource( + table, tag_columns=["k"], tag_only_columns=True, source_id="s" + ).select_data_columns(["x"], label="selected") + job.bind(sources={"s": source}) + job.run() + return job.nodes["selected"].as_table()["x"].to_pylist() + + +@pytest.mark.parametrize("how", ["instance_reader", "property", "plain_subclass"]) +def test_only_an_exact_unshadowed_library_source_is_eager(how: str) -> None: + """An ``iter_data`` replaced on the instance and a ``_stream`` property both read + the rows the reader gives (``[20]``, as ``main``); a plain subclass is not proven + either, and gives ``main``'s rows (Codex on PR #485, final check).""" + from orcapod.core.sources.base import table_is_rows + + table = pa.table({"k": pa.array([1, 2]), "x": pa.array([10, 20])}) + kwargs: dict[str, Any] = { + "tag_columns": ["k"], + "tag_only_columns": True, + "source_id": "s", + } + if how == "instance_reader": + source: Any = ArrowTableSource(table, **kwargs) + read = source.iter_data + source.iter_data = lambda: _only_above_ten(read()) + expected = [20] + elif how == "property": + source = _ReadsThroughAProperty(table, **kwargs) + expected = [20] + else: + source = type("Plain", (ArrowTableSource,), {})(table, **kwargs) + expected = [10, 20] + assert not table_is_rows(source) + assert _bound_selection(source) == expected + + +def test_an_exact_library_source_is_eager() -> None: + """The exact class, with nothing replaced on the instance, takes the eager route.""" + from orcapod.core.sources.base import table_is_rows + + table = pa.table({"k": pa.array([1, 2]), "x": pa.array([10, 20])}) + source = ArrowTableSource( + table, tag_columns=["k"], tag_only_columns=True, source_id="s" + ) + source.as_table() + list(source.iter_data()) + assert table_is_rows(source) + assert _bound_selection(source) == [10, 20] + + +def _swapped(stream: Any, first: str, second: str, tags: list[str]) -> Any: + """``stream``'s table with ``first`` and ``second`` swapped, over ``tags``.""" + from orcapod.core.streams.base import ZERO_ROW_INPUT_COLUMNS + + table = stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS) + names = list(table.column_names) + a, b = names.index(first), names.index(second) + names[a], names[b] = names[b], names[a] + return ArrowTableStream(table.select(names), tag_columns=tags) + + +@pytest.mark.parametrize("replay", [False, True], ids=["log", "replay"]) +@pytest.mark.parametrize("layout", ["data", "tags"]) +def test_a_composed_operator_result_keeps_its_own_order( + layout: str, replay: bool +) -> None: + """An operator whose ``static_process`` returns ANOTHER operator's result keeps, + stores and hands on the order of the rows that result yields, to any depth: data + ``y, x`` (laid out so) and tags ``b, a`` (declared so), as ``main`` built them from + the rows; REPLAY of the stored table too (Codex on PR #485, final check).""" + from orcapod.operators import SelectDataColumns + + class Reordered(SelectDataColumns): + def unary_static_process(self, stream: Any) -> Any: + if layout == "data": + return _swapped(stream, "x", "y", ["a", "b"]) + return _swapped(stream, "x", "x", ["b", "a"]) + + class Composed(SelectDataColumns): + def unary_static_process(self, stream: Any) -> Any: + return Reordered(["x", "y"]).process(stream) + + database = InMemoryArrowDatabase() + job = PipelineJob(name="composed", database=database) + with job: + source = DictSource( + [{"a": 1, "b": 5, "x": 1, "y": 2}, {"a": 2, "b": 6, "x": 3, "y": 4}], + tag_columns=["a", "b"], + tag_only_columns=True, + source_id="s", + ) + Batch(batch_size=2)(Composed(["x", "y"])(source, label="composed"), label="b") + node: Any = job.nodes["composed"] + node.attach_databases( + pipeline_database=database.at("log"), cache_mode=CacheMode.LOG + ) + job.run() + if replay: + node.attach_databases( + pipeline_database=database.at("log"), cache_mode=CacheMode.REPLAY + ) + node.clear_cache() + job.run() + # ``main`` 321284ae, measured: the stored table keeps its tags in the slot's order, + # and REPLAY hands on the stored table's order. + data = ["a", "b", "y", "x", "_source_y", "_source_x"] + stored_tags = ["a", "b", "x", "y", "_source_x", "_source_y"] + result_tags = ["b", "a", "x", "y", "_source_x", "_source_y"] + if layout == "data": + kept, in_store = data, data + else: + kept, in_store = (stored_tags if replay else result_tags), stored_tags + assert node.as_table(columns={"source": True}).column_names == kept + stored = node.get_all_records(columns={"source": True}) + assert stored is not None + assert [n for n in stored.column_names if not n.startswith("__")] == in_store + assert job.nodes["b"].as_table(columns={"source": True}).column_names == kept + + +def test_a_result_of_another_stream_kind_takes_mains_row_path() -> None: + """A result that is not exactly an ``ArrowTableStream`` is read as ``main`` read + it: its rows (here, the ones its iterator yields), never its table.""" + from orcapod.core.streams.base import ZERO_ROW_INPUT_COLUMNS + from orcapod.operators import SelectDataColumns + + class Filtering(SelectDataColumns): + def unary_static_process(self, stream: Any) -> Any: + table = stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS) + return _FilteringStream(table, tag_columns=["k"]) + + database = InMemoryArrowDatabase() + job = PipelineJob(name="other_kind", database=database) + with job: + source = ArrowTableSource( + pa.table({"k": pa.array([1, 2]), "x": pa.array([10, 20])}), + tag_columns=["k"], + tag_only_columns=True, + source_id="s", + ) + Batch(batch_size=2)(Filtering(["x"])(source, label="filtered"), label="b") + node: Any = job.nodes["filtered"] + node.attach_databases( + pipeline_database=database.at("log"), cache_mode=CacheMode.LOG + ) + job.run() + assert node.as_table()["x"].to_pylist() == [20] + stored = node.get_all_records() + assert stored is not None + assert stored["x"].to_pylist() == [20] + assert job.nodes["b"].as_table()["x"].to_pylist() == [[20]] + + @pytest.mark.parametrize( "kind", [pa.time64("ns"), pa.decimal256(76, 40)], From 36fd78aacd08b8624f429d838021c5bc0050e89d Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 11:40:24 -0800 Subject: [PATCH 32/36] fix(pipeline): every wrapper in a result's chain proven; eager only in the node's data context (ITL-1360) CodeRabbit on PR #485 (352ce7b9). - produced_stream follows a DynamicPodStream only when it reads as DynamicPodStream itself (reads_as_its_class); a subclass, or a wrapper with iter_data replaced on the instance, stops the chain and the operator node takes main's row path (main read [20] through such a wrapper; 352ce7b9 gave [10, 20]). - An operator result whose rows report another data context than the node's takes main's row path: the rows execute hands on are main's rows, in their own context (the kept table is the node's context, as on main). Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1360.md | 2 +- .../dev/specs/itl-1347-job-table-transport.md | 4 +- src/orcapod/core/nodes/operator_node.py | 11 ++- .../core/operators/static_output_pod.py | 13 ++- tests/test_pipeline/test_rows_on_read.py | 96 +++++++++++++++++++ 5 files changed, 118 insertions(+), 8 deletions(-) diff --git a/changelog.d/ITL-1360.md b/changelog.d/ITL-1360.md index 51b12db1a..1f3892262 100644 --- a/changelog.d/ITL-1360.md +++ b/changelog.d/ITL-1360.md @@ -7,7 +7,7 @@ every successor. A node bound to an instance of exactly a library source kind whose table is its rows (`TABLE_IS_ROWS`, never inherited by a subclass) gives its source's Arrow table, and an operator node whose result yields its rows from exactly an - `ArrowTableStream` its result's table in that stream's row order (REPLAY: its stored + `ArrowTableStream` in the node's data context its result's table in that stream's row order (REPLAY: its stored table), each in the form a table built from the rows has, without making the rows. Every other output (a narrower bind, a subclass or another kind of bound stream, an operator result of another stream kind, a table the whole-table build cannot use, a diff --git a/docs/dev/specs/itl-1347-job-table-transport.md b/docs/dev/specs/itl-1347-job-table-transport.md index dc60bc475..27c9764ed 100644 --- a/docs/dev/specs/itl-1347-job-table-transport.md +++ b/docs/dev/specs/itl-1347-job-table-transport.md @@ -528,7 +528,9 @@ methods or properties** (`reads_as_its_class`). It is applied in two places: - a bound source: its class is a library source kind that itself declares `TABLE_IS_ROWS` (`table_is_rows`); - an operator's result: the stream it yields its rows from, followed through every - `DynamicPodStream` (`produced_stream`), is `ArrowTableStream`, and its own `keys()` (the + `DynamicPodStream` that is itself proven (`produced_stream`; a subclass or a wrapper + with a replaced member stops the chain), is `ArrowTableStream` in the node's data + context (its rows report that context, as `main`'s rows did), and its own `keys()` (the keys `iter_data` reads its rows with, tags in its tag-column order) give the order. Any subclass, replaced reader or other stream kind takes `main`'s row path. diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index 4227c2cc8..c5b94a773 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -1712,10 +1712,15 @@ def execute( produced = produced_stream(result_stream) output: StreamProtocol - if not reads_as_its_class(produced, ArrowTableStream): + if ( + not reads_as_its_class(produced, ArrowTableStream) + or produced.data_context_key != self.data_context_key + ): # A result that is not exactly a stream over its table (a custom - # stream kind, a replaced reader): main's own row path, its rows read - # once, its table built where a successor reads it (ITL-1347). + # stream kind, a replaced reader), or whose rows report another data + # context than the node's: main's own row path, its rows read once and + # handed on unchanged, its table built where a successor reads it + # (ITL-1347). rows = list(result_stream.iter_data()) self._cached_output_stream = StaticOutputOperatorPod._kept_output( result_stream, rows diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index 90209a8a8..2d7fd0347 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -44,6 +44,7 @@ ZERO_ROW_INPUT_COLUMNS, StreamBase, check_head_size, + reads_as_its_class, short_stream_repr, typed_zero_row_input, typed_zero_row_table, @@ -1618,15 +1619,21 @@ def produced_stream(stream: StreamProtocol) -> StreamProtocol: An operator's result is a ``DynamicPodStream`` whose rows are those of the stream its ``static_process`` returned, which may itself be another operator's ``DynamicPodStream``: this follows them all to the stream that holds the rows - (ITL-1347). + (ITL-1347). A wrapper is followed only when it reads as ``DynamicPodStream`` itself + (``reads_as_its_class``: its rows are then exactly those of the stream it holds); a + subclass or a wrapper with a member replaced on the instance is where the chain + stops, so the caller, which proves the stream it is given, takes the row path. Args: stream: An operator's result, or any stream. Returns: - The stream that holds ``stream``'s rows. + The stream that holds ``stream``'s rows, or the first wrapper not proven to + read through the stream it holds. """ - while isinstance(stream, DynamicPodStream): + while isinstance(stream, DynamicPodStream) and reads_as_its_class( + stream, DynamicPodStream + ): stream = stream.produced_stream() return stream diff --git a/tests/test_pipeline/test_rows_on_read.py b/tests/test_pipeline/test_rows_on_read.py index 68c9d3770..2113fb27d 100644 --- a/tests/test_pipeline/test_rows_on_read.py +++ b/tests/test_pipeline/test_rows_on_read.py @@ -723,6 +723,102 @@ def unary_static_process(self, stream: Any) -> Any: assert job.nodes["b"].as_table()["x"].to_pylist() == [[20]] +# ── CodeRabbit on 352ce7b9: every wrapper proven, and the rows' data context ───── + + +@pytest.mark.parametrize("how", ["subclass", "instance_reader"]) +def test_a_dynamic_stream_that_is_not_proven_stops_the_chain(how: str) -> None: + """A ``DynamicPodStream`` subclass, or one whose ``iter_data`` is replaced on the + instance, inside an operator's result is read through its own rows (``[20]``), + as ``main`` read them: the chain is followed only through proven wrappers.""" + from orcapod.core.operators.static_output_pod import DynamicPodStream + from orcapod.operators import SelectDataColumns + + class FilteringDynamic(DynamicPodStream): + def iter_data(self) -> Any: + return _only_above_ten(super().iter_data()) + + class Inner(SelectDataColumns): + pass + + class Outer(SelectDataColumns): + def unary_static_process(self, stream: Any) -> Any: + if how == "subclass": + return FilteringDynamic(Inner(["x", "y"]), (stream,)) + inner: Any = Inner(["x", "y"]).process(stream) + read = inner.iter_data + inner.iter_data = lambda: _only_above_ten(read()) + return inner + + database = InMemoryArrowDatabase() + job = PipelineJob(name="unproven", database=database) + with job: + source = ArrowTableSource( + pa.table({"k": [1, 2], "x": [10, 20], "y": [1, 2], "z": [5, 6]}), + tag_columns=["k"], + tag_only_columns=True, + source_id="s", + ) + Batch(batch_size=2)(Outer(["x", "y"])(source, label="outer"), label="b") + node: Any = job.nodes["outer"] + node.attach_databases( + pipeline_database=database.at("log"), cache_mode=CacheMode.LOG + ) + job.run() + assert node.as_table()["x"].to_pylist() == [20] + stored = node.get_all_records() + assert stored is not None + assert stored["x"].to_pylist() == [20] + assert job.nodes["b"].as_table()["x"].to_pylist() == [[20]] + + +OTHER_CONTEXT = "std:v1:test-rows-on-read-other" + + +def test_a_result_in_another_data_context_hands_on_its_own_rows( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """An operator node over a stream of another data context hands on the result's + rows as ``main`` returned them (in their own data context); what it keeps is in its + own data context, as on ``main``.""" + import dataclasses + + import orcapod.contexts as contexts + from orcapod.core.nodes.operator_node import OperatorJobNode + from orcapod.operators import SelectDataColumns + from orcapod.system_constants import constants + + other = dataclasses.replace( + contexts.get_default_context(), context_key=OTHER_CONTEXT + ) + registry = contexts._get_registry() # pyright: ignore[reportPrivateUsage] # the test registers a second context + original = registry.get_context + + def get_context(key: Any = None) -> contexts.DataContext: # pyright: ignore[reportExplicitAny] # the registry's own argument + return other if key == OTHER_CONTEXT else original(key) + + monkeypatch.setattr(registry, "get_context", get_context) + + def stream() -> ArrowTableStream: + table = pa.table( + { + "k": ["a", "b"], + "x": [1, 2], + "y": [3, 4], + constants.CONTEXT_KEY: pa.array([OTHER_CONTEXT] * 2, pa.large_string()), + } + ) + return ArrowTableStream(table, tag_columns=["k"], data_context=other) + + node = OperatorJobNode(SelectDataColumns(["x"]), [stream()]) + output: Any = node.execute(stream()) + assert [data.data_context_key for _, data in output.iter_data()] == [ + OTHER_CONTEXT + ] * 2 + kept = node.as_table(columns={"context": True})[constants.CONTEXT_KEY] + assert kept.to_pylist() == [node.data_context_key] * 2 + + @pytest.mark.parametrize( "kind", [pa.time64("ns"), pa.decimal256(76, 40)], From dd6b7cd40e8234cc3c599019201f4b8252749042 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 12:34:21 -0800 Subject: [PATCH 33/36] fix(pipeline): eager only in the node's data context with row-typed system tags; a retained output keeps its rows (ITL-1360) Codex on PR #485, round 7. - The one precondition gains two conditions, applied on both routes: the rows report the node's data context, and every system-tag field of the table is non-null large_string, what the rows give (system_tags_as_rows_give). An exact CachedSource with its own data context hands on its rows in that context (the edge table is built in the slot's context, as on main); a result with an int16 system tag takes main's row path (int64 non-null and main's record hashes; with a null, main's ArrowInvalid before the end event). - With results retained, the sync orchestrator drops a RowsOnRead's built stream once every successor has read it (release_built), so it holds only its rows, as main did; neighbours are taken before the run, since an observer may rebind a source. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1360.md | 39 ++-- .../dev/specs/itl-1347-job-table-transport.md | 13 +- src/orcapod/core/nodes/operator_node.py | 32 +-- src/orcapod/core/nodes/source_node.py | 15 +- .../core/operators/static_output_pod.py | 9 + src/orcapod/core/streams/base.py | 22 ++ src/orcapod/pipeline/sync_orchestrator.py | 41 ++++ tests/test_pipeline/test_rows_on_read.py | 204 ++++++++++++++++++ 8 files changed, 337 insertions(+), 38 deletions(-) diff --git a/changelog.d/ITL-1360.md b/changelog.d/ITL-1360.md index 1f3892262..8121d7e70 100644 --- a/changelog.d/ITL-1360.md +++ b/changelog.d/ITL-1360.md @@ -4,24 +4,27 @@ function and side-effect job node (and of the node protocols) returned the node's rows as a list of (tag, data) pairs, and the sync orchestrator rebuilt a table from them for each successor. It now returns the node's output stream, which the sync orchestrator hands to - every successor. A node bound to an instance of exactly a library source kind whose - table is its rows (`TABLE_IS_ROWS`, never inherited by a subclass) gives its source's - Arrow table, and an operator node whose result yields its rows from exactly an - `ArrowTableStream` in the node's data context its result's table in that stream's row order (REPLAY: its stored - table), each in the form a table built from the rows has, without making the rows. - Every other output (a narrower bind, a subclass or another kind of bound stream, an - operator result of another stream kind, a table the whole-table build cannot use, a - result with no row, a held node, a function or side-effect node) is the node's rows, - unchanged, whose table is built where a successor reads it, as before. `OrchestratorResult.node_outputs` holds each node's - output stream: its rows (`iter_data()`) are the rows the node returned, and its table is - built when the table is first read (`as_table()`, a successor's edge); on the sync path - a held node gives the stream of its held rows, and the async path still sends a held - node's rows as the run's plan took them (`held_rows`). Every successor's input is - unchanged: columns, types, row order, system tags, source info, pipeline and content - hashes, and an error surfaces where and when it did. No hash, stored table or output - changes. An operator node's table is built once, for what it keeps and for every - successor, instead of once to keep and once per successor. The first two stages of the - table transport between job nodes (`docs/dev/specs/itl-1347-job-table-transport.md`). + every successor. Where that table is provably the rows' own, the node gives it + without making the rows: a node bound to an instance of exactly a library source kind + whose table is its rows (`TABLE_IS_ROWS`, never inherited by a subclass), and an + operator node whose result yields its rows from exactly an `ArrowTableStream`, in that + stream's row order (REPLAY: its stored table), each only when the rows report the + node's data context and every system tag is non-null text, as rows give it. Every other + output (a narrower bind, a subclass or another kind of bound stream or result, rows of + another data context, system tags of another type, a table the whole-table build + cannot use, a result with no row, a held node, a function or side-effect node) is the + node's rows, unchanged, whose table is built where a successor reads it, as before; a + retained one keeps only its rows once every successor has read it. + `OrchestratorResult.node_outputs` holds each node's output stream: its rows + (`iter_data()`) are the rows the node returned, and its table is built when the table + is first read (`as_table()`, a successor's edge); on the sync path a held node gives + the stream of its held rows, and the async path still sends a held node's rows as the + run's plan took them (`held_rows`). Every successor's input is unchanged: columns, + types, row order, system tags, source info, pipeline and content hashes, and an error + surfaces where and when it did. No hash, stored table or output changes. An operator + node's table is built once, for what it keeps and for every successor, instead of once + to keep and once per successor. The first two stages of the table transport between + job nodes (`docs/dev/specs/itl-1347-job-table-transport.md`). (ITL-1347, ITL-1360) ### Added diff --git a/docs/dev/specs/itl-1347-job-table-transport.md b/docs/dev/specs/itl-1347-job-table-transport.md index 27c9764ed..082e7a042 100644 --- a/docs/dev/specs/itl-1347-job-table-transport.md +++ b/docs/dev/specs/itl-1347-job-table-transport.md @@ -521,9 +521,11 @@ node, a node whose output is still its rows), the node hands on its rows and the built from them by `main`'s row path where a successor reads them (`RowsOnRead`, `at_edge`): `main`'s order, error and moment by construction (Codex on PR #485, round 3). "Provably" is one precondition, positive and exact, never an inspection of overrides -(Codex on PR #485, final check): **the stream that holds the rows is exactly a class whose -whole-table read is its rows, and nothing on the instance shadows one of that class's -methods or properties** (`reads_as_its_class`). It is applied in two places: +(Codex on PR #485, final check and round 7): **the stream that holds the rows is exactly a +class whose whole-table read is its rows, nothing on the instance shadows one of that +class's methods or properties** (`reads_as_its_class`), **its rows report the node's data +context, and every system-tag field of its table is what the rows give, non-null +`large_string`** (`system_tags_as_rows_give`). It is applied in two places: - a bound source: its class is a library source kind that itself declares `TABLE_IS_ROWS` (`table_is_rows`); @@ -533,7 +535,10 @@ methods or properties** (`reads_as_its_class`). It is applied in two places: context (its rows report that context, as `main`'s rows did), and its own `keys()` (the keys `iter_data` reads its rows with, tags in its tag-column order) give the order. -Any subclass, replaced reader or other stream kind takes `main`'s row path. +Any subclass, replaced reader, other stream kind, other data context or other system-tag +type takes `main`'s row path. A retained output held as its rows (`RowsOnRead`) keeps +only its rows once every successor has read it (`release_built`), as `main` retained +only the rows. | # | What differs | On `main` today | On the branch | Why `main` is wrong (bug, reproducer) | Approval needed | |---|---|---|---|---|---| diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index c5b94a773..1e60993e9 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -51,6 +51,7 @@ check_head_size, reads_as_its_class, short_stream_repr, + system_tags_as_rows_give, ) from orcapod.core.streams.view import ( JOB_NODE_NOT_RUN_NOTE, @@ -1712,27 +1713,32 @@ def execute( produced = produced_stream(result_stream) output: StreamProtocol + # The result's table, as the table built from its rows would be, without + # making the rows (ITL-1347, stage 2), when it provably is its rows: the + # stream holding them is exactly an ``ArrowTableStream`` in the node's + # data context, whose system tags are what the rows give. + result_table: pa.Table | None = None if ( - not reads_as_its_class(produced, ArrowTableStream) - or produced.data_context_key != self.data_context_key + reads_as_its_class(produced, ArrowTableStream) + and produced.data_context_key == self.data_context_key ): - # A result that is not exactly a stream over its table (a custom - # stream kind, a replaced reader), or whose rows report another data - # context than the node's: main's own row path, its rows read once and - # handed on unchanged, its table built where a successor reads it - # (ITL-1347). + result_table = result_stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS) + if not system_tags_as_rows_give(result_table.schema): + result_table = None + if result_table is None: + # Otherwise (a custom stream kind, a replaced reader, rows of another + # data context, system tags the rows type otherwise): main's own row + # path, its rows read once and handed on unchanged, its table built + # where a successor reads it (ITL-1347). rows = list(result_stream.iter_data()) self._cached_output_stream = StaticOutputOperatorPod._kept_output( result_stream, rows ) output = rows_on_read(rows, self) else: - # The result's table, as the table built from its rows would be, - # without making the rows (ITL-1347, stage 2). An exact - # ``ArrowTableStream``'s ``keys()`` are the keys its rows are read with - # (``iter_data``), so they are the order of the result's rows, to any - # depth of composition, never the prediction. - result_table = result_stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS) + # An exact ``ArrowTableStream``'s ``keys()`` are the keys its rows are + # read with (``iter_data``), so they are the order of the result's + # rows, to any depth of composition, never the prediction. keys = produced.keys() tag_keys = keys[0] data_tags = data_tag_names(*keys) diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index 5732b3142..76736f987 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -31,6 +31,7 @@ from orcapod.core.streams.base import ( ZERO_ROW_INPUT_COLUMNS, keys_of_rows, + system_tags_as_rows_give, row_built_columns, stream_arrow_schema, schema_requires_io, @@ -1837,12 +1838,20 @@ def _rows_table( ) if self._declared_form is not None: return None - if not table_is_rows(self._bound_source): + if ( + not table_is_rows(self._bound_source) + or self._bound_source.data_context_key != self.data_context_key + ): # Not a library source kind whose table is its rows (a side-effect or - # function pod stream, an operator's result, a raw stream, a poller): its - # rows, as main iterated them. + # function pod stream, an operator's result, a raw stream, a poller), or + # one whose rows report another data context than the node's: its rows, + # as main iterated them (the edge table is built in the node's context). return None table = self._bound_source.as_table(columns=ZERO_ROW_INPUT_COLUMNS) + if not system_tags_as_rows_give(table.schema): + # System tags the rows would type otherwise (a narrow integer, a + # nullable field): the rows decide, as on main. + return None return table, keys_of_rows(table, self._bound_source.keys()) def iter_data(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index 2d7fd0347..1a214dffe 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -1417,6 +1417,15 @@ def built(self) -> StreamProtocol: ) return self._stream + def release_built(self) -> None: + """Drop the built stream and keep only the rows. + + The sync orchestrator calls this on an output it retains once every successor + has read it: ``main`` held only the rows, so the retained output holds one + representation, and a later read builds the same table again from them. + """ + self._stream = None + def iter_data(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: """The rows it holds, unchanged (their meta columns included), as ``main``.""" return iter(self._rows) diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py index 26e05c0ce..d2ec40632 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -81,6 +81,28 @@ def reads_as_its_class(obj: object, cls: type) -> bool: return True +def system_tags_as_rows_give(schema: pa.Schema) -> bool: + """Whether every system-tag field is what the row rebuild gives: non-null text. + + ``main`` rebuilt a node's table from its rows, whose system tags are typed from + their values: a ``large_string`` field, non-nullable (the only kind library code + makes). A whole table is its rows only when its system tags are already so; a + narrow integer, a nullable field or any other type is decided by the rows + (ITL-1347). + + Args: + schema: The table's schema. + + Returns: + Whether every system-tag field is non-nullable ``large_string``. + """ + return all( + field.type == pa.large_string() and not field.nullable + for field in schema + if field.name.startswith(constants.SYSTEM_TAG_PREFIX) + ) + + def schema_requires_io(stream: object, config: ColumnConfig) -> bool: """Whether reading ``stream``'s schema with ``config`` would read or poll a source. diff --git a/src/orcapod/pipeline/sync_orchestrator.py b/src/orcapod/pipeline/sync_orchestrator.py index 523322fa4..3286caab7 100644 --- a/src/orcapod/pipeline/sync_orchestrator.py +++ b/src/orcapod/pipeline/sync_orchestrator.py @@ -95,6 +95,16 @@ def run( current: Any = None try: topo_order = list(graph.topological_sort()) + # Taken before any node runs: an observer may rebind a source, which + # changes how the graph finds that node afterwards. + neighbours = ( + { + id(n): (list(graph.predecessors(n)), list(graph.successors(n))) + for n in topo_order + } + if materialize_results + else {} + ) outputs: dict[Any, StreamProtocol] = {} processed: set[Any] = set() @@ -137,6 +147,8 @@ def run( if not materialize_results: self._gc_outputs(node, graph, outputs, processed) + else: + self._release_built_inputs(node, neighbours, outputs, processed) if not materialize_results: outputs.clear() @@ -191,6 +203,35 @@ def _ordered_inputs( return [at_edge(outputs[p]) for p in sorted_preds] + @staticmethod + def _release_built_inputs( + current_node: Any, + neighbours: dict[int, tuple[list[Any], list[Any]]], + outputs: dict[Any, StreamProtocol], + processed: set[Any], + ) -> None: + """Keep a retained output read by all its successors as its rows only. + + A ``RowsOnRead`` output builds its table at each successor's edge; once every + successor has run, the retained output drops the built stream and keeps the + rows, which is all ``main`` retained (ITL-1347). A later read builds it again. + + Args: + current_node: The node that just ran. + neighbours: Each node's predecessors and successors, by ``id``, taken + before the run. + outputs: The retained outputs. + processed: The nodes that ran. + """ + from orcapod.core.operators.static_output_pod import RowsOnRead + + for pred in neighbours[id(current_node)][0]: + output = outputs.get(pred) + if isinstance(output, RowsOnRead) and all( + succ in processed for succ in neighbours[id(pred)][1] + ): + output.release_built() + @staticmethod def _gc_outputs( current_node: Any, diff --git a/tests/test_pipeline/test_rows_on_read.py b/tests/test_pipeline/test_rows_on_read.py index 2113fb27d..c99226060 100644 --- a/tests/test_pipeline/test_rows_on_read.py +++ b/tests/test_pipeline/test_rows_on_read.py @@ -819,6 +819,210 @@ def stream() -> ArrowTableStream: assert kept.to_pylist() == [node.data_context_key] * 2 +# ── Codex round 7: the source's data context, system tags, retained lifetime ─── + + +def test_a_source_in_another_data_context_hands_on_its_own_rows() -> None: + """An exact ``CachedSource`` with its own data context: the rows a sync run returns + report the source's context, as ``main`` returned them, and the edge table is built + in the slot's context, as ``main`` rebuilt it.""" + import dataclasses + + from orcapod.contexts import get_default_context + from orcapod.core.nodes.source_node import SourceJobNode + from orcapod.core.operators.static_output_pod import at_edge + from orcapod.sources import CachedSource + from orcapod.system_constants import constants + + custom = dataclasses.replace(get_default_context(), context_key="review:custom") + inner = DictSource( + [{"k": 1, "x": 10}, {"k": 2, "x": 20}], + tag_columns=["k"], + tag_only_columns=True, + source_id="s", + data_context=custom, + ) + source = CachedSource( + inner, + cache_database=InMemoryArrowDatabase(), + source_id="cached", + data_context=custom, + ) + slot = SourceJobNode.from_stream(source) + dag: OrcaDAG[Any] = OrcaDAG() + dag.add_node(slot) + output: Any = SyncPipelineOrchestrator().run(dag).node_outputs[slot] + assert [ + (tag.data_context_key, data.data_context_key) + for tag, data in output.iter_data() + ] == [("review:custom", "review:custom")] * 2 + edge = at_edge(output).as_table(columns={"context": True}) + assert edge[constants.CONTEXT_KEY].to_pylist() == [slot.data_context_key] * 2 + + +class _AddSystemTag: + """``SelectDataColumns`` whose result carries one more system tag, ``int16``.""" + + @staticmethod + def operator(values: list[int | None], exact: bool) -> Any: + from orcapod.operators import SelectDataColumns + from orcapod.system_constants import constants + + class Unproven(ArrowTableStream): + """Reads as ``ArrowTableStream``; not proven: ``main``'s row path.""" + + kind = ArrowTableStream if exact else Unproven + + class AddSystemTag(SelectDataColumns): + def unary_static_process(self, stream: Any) -> Any: + out: Any = super().unary_static_process(stream) + table = out.as_table(columns={"source": True, "system_tags": True}) + table = table.append_column( + f"{constants.SYSTEM_TAG_PREFIX}region", + pa.array(values[: table.num_rows], pa.int16()), + ) + return kind(table, tag_columns=["k"]) + + return AddSystemTag(["x"]) + + +def _system_tag_job(values: list[int | None], exact: bool) -> tuple[Any, Any]: + database = InMemoryArrowDatabase() + job = PipelineJob(name="system_tag", database=database) + with job: + source = DictSource( + [{"k": 1, "x": 1}, {"k": 2, "x": 2}], + tag_columns=["k"], + tag_only_columns=True, + source_id="s", + ) + _AddSystemTag.operator(values, exact)(source, label="marked") + job.nodes["marked"].attach_databases( + pipeline_database=database.at("log"), cache_mode=CacheMode.LOG + ) + return job, database + + +def test_a_narrow_system_tag_is_stored_as_the_rows_give() -> None: + """A result over an exact ``ArrowTableStream`` with an ``int16`` system tag: kept, + stored and record-hashed as ``main``'s rows give it (``int64``, non-null), the + same as ``main``'s own row path (an unproven stream) gives.""" + from orcapod.system_constants import constants + + name = f"{constants.SYSTEM_TAG_PREFIX}region" + stored: dict[bool, Any] = {} + for exact in (True, False): + job, database = _system_tag_job([1, 2], exact) + job.run() + node: Any = job.nodes["marked"] + kept = node.as_table(columns={"system_tags": True}).schema.field(name) + assert (kept.type, kept.nullable) == (pa.int64(), False) + stored[exact] = database.at("log").get_all_records( + node._stored_table_path, # pyright: ignore[reportPrivateUsage] # the raw LOG table + record_id_column="_record_hash", + ) + for table in stored.values(): + field = table.schema.field(name) + assert (field.type, field.nullable) == (pa.int64(), False) + assert ( + stored[True]["_record_hash"].to_pylist() + == stored[False]["_record_hash"].to_pylist() + ) + + +def test_a_null_system_tag_raises_at_the_operator_as_main_does() -> None: + """With a null among its values, ``main``'s rows cannot make one table: the + operator raises ``ArrowInvalid`` before its end event, as on ``main``.""" + job, _ = _system_tag_job([None, 2], exact=True) + observer = _NodeEvents() + with pytest.raises(pa.ArrowInvalid): + job.run(observer=observer) + assert ("start", "marked") in observer.events + assert ("end", "marked") not in observer.events + + +def test_a_source_table_with_other_system_tags_is_not_its_rows() -> None: + """The source route's guard: an exact ``ArrowTableSource`` whose system tag is a + narrow integer has a table that is not its rows (they give ``int64``); a stock + source's system tags are what the rows give.""" + from orcapod.core.streams.base import system_tags_as_rows_give + + schema = pa.schema( + [ + pa.field("k", pa.int64(), nullable=False), + pa.field("x", pa.int64(), nullable=False), + pa.field("region", pa.int16(), nullable=False), + ] + ) + narrow = ArrowTableSource( + pa.Table.from_pylist( + [{"k": 1, "x": 10, "region": 1}, {"k": 2, "x": 20, "region": 2}], + schema=schema, + ), + tag_columns=["k"], + tag_only_columns=True, + system_tag_columns=["region"], + source_id="s", + ) + assert not system_tags_as_rows_give( + narrow.as_table(columns={"system_tags": True}).schema + ) + stock = _plain() + assert system_tags_as_rows_give( + stock.as_table(columns={"system_tags": True}).schema + ) + + +def test_a_retained_output_keeps_only_its_rows_once_read( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """With results retained, an output held as its rows drops its built stream once + every successor has read it (``main`` retained only the rows): no built stream + outlives the run, its rows are its own, and a later read builds the table again.""" + import gc + import weakref + + from orcapod import function_pod + from orcapod.core.operators.static_output_pod import ( + RowsOnRead, + StaticOutputOperatorPod, + ) + + @function_pod(output_keys="y") + def plus_one(x: int) -> int: + return x + 1 + + job = PipelineJob(name="retained", database=InMemoryArrowDatabase()) + with job: + computed: Any = plus_one.pod( + _plain().select_data_columns(["x"]), label="computed" + ) + computed.select_data_columns(["y"], label="second") + computed.select_data_columns(["y"], label="third") + + built: list[weakref.ref[Any]] = [] + original = StaticOutputOperatorPod._materialize_upstream # pyright: ignore[reportPrivateUsage] # the row path, watched + + def watched(*args: Any, **kwargs: Any) -> Any: + stream = original(*args, **kwargs) + built.append(weakref.ref(stream)) + return stream + + monkeypatch.setattr( + StaticOutputOperatorPod, "_materialize_upstream", staticmethod(watched) + ) + graph = job._node_graph # pyright: ignore[reportPrivateUsage] # the job's graph + assert graph is not None + result = SyncPipelineOrchestrator().run(graph) + output: Any = result.node_outputs[job.nodes["computed"]] + assert isinstance(output, RowsOnRead) + gc.collect() + assert built + assert all(ref() is None for ref in built) + assert len(list(output.iter_data())) == 2 + assert output.as_table().num_rows == 2 + + @pytest.mark.parametrize( "kind", [pa.time64("ns"), pa.decimal256(76, 40)], From 1c5c0458abfec9eb3dbd4505d3c4aec4aab26bd5 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 12:51:10 -0800 Subject: [PATCH 34/36] docs(pipeline): an observer that changes the pipeline mid-run is unsupported (ITL-1360, ITL-1369) Developer decision, November 22, 2026: an observer only watches; one that changes the job, its nodes or its bound sources during a run is unsupported, and what the run then does is undefined and not part of the equality with main (ITL-1369 will prevent it). The open spec row e11 and its strict xfail are removed; the governing rule states it, and so do the pipeline-job concept page, CLAUDE.md and .zed/rules. No code changes. Co-Authored-By: Claude Opus 5.5 --- .zed/rules | 4 ++ CLAUDE.md | 4 ++ docs/concepts/pipeline-job.md | 4 +- .../dev/specs/itl-1347-job-table-transport.md | 4 +- tests/test_pipeline/test_rows_on_read.py | 38 ------------------- 5 files changed, 14 insertions(+), 40 deletions(-) diff --git a/.zed/rules b/.zed/rules index bbd720618..2e6101650 100644 --- a/.zed/rules +++ b/.zed/rules @@ -1499,6 +1499,10 @@ data. The rules: are not concerned. The refusal is for now: how an operator node logs and replays is to be redesigned to load its cache and then apply the restriction (TODO(ITL-1219)). - Empty data → ArrowTableSource raises ValueError("Table is empty"). +- An observer only watches (developer, November 22, 2026, ITL-1369): an observer or callback + that changes the job, its nodes or its bound sources during a run is unsupported; what the + run then does is undefined and is not part of the equality with main. Preventing it (a + guard, then a read-only view) is ITL-1369; never chase a case that needs such a change. - A side-effect job node delivers only when it runs (developer, November 13, 2026, ITL-1091): job.run(), node.run() (state-driven, ITL-1095: a node holding a current run delivers nothing, so clear_cache() it first to deliver again; otherwise the job run's work for that diff --git a/CLAUDE.md b/CLAUDE.md index 0c6d59591..6b760dd45 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1546,6 +1546,10 @@ data. The rules: are not concerned. The refusal is for now: how an operator node logs and replays is to be redesigned to load its cache and then apply the restriction (`TODO(ITL-1219)`). - Empty data → `ArrowTableSource` raises `ValueError("Table is empty")`. +- An observer only watches (developer, November 22, 2026, ITL-1369): an observer or callback + that changes the job, its nodes or its bound sources during a run is unsupported; what the + run then does is undefined and is not part of the equality with `main`. Preventing it (a + guard, then a read-only view) is ITL-1369; never chase a case that needs such a change. - A side-effect job node delivers only when it runs (developer, November 13, 2026, ITL-1091): `job.run()`, `node.run()` (state-driven, ITL-1095: a node holding a current run delivers nothing, so `clear_cache()` it first to deliver again; otherwise the job run's work for that diff --git a/docs/concepts/pipeline-job.md b/docs/concepts/pipeline-job.md index 625400b73..e234ac81b 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -62,7 +62,9 @@ Among `job.run()`'s optional arguments, the tutorial's [Part 9](../tutorial/09-when-things-go-wrong.md) demonstrates `orchestrator=` (for example `SyncPipelineOrchestrator(error_policy="fail_fast")` to stop at the first failing row; the default policy skips failed rows and continues) and `observer=` (`StatusObserver`, -`LoggingObserver`) to record what happened during the run. `load_only=True` fills the nodes +`LoggingObserver`) to record what happened during the run. An observer only watches: one +that changes the job, its nodes or its bound sources during a run is unsupported, and what +the run then does is undefined (ITL-1369). `load_only=True` fills the nodes from what is already stored and computes nothing; see [Loading without computing](function-pods.md#loading-without-computing-runload_onlytrue). diff --git a/docs/dev/specs/itl-1347-job-table-transport.md b/docs/dev/specs/itl-1347-job-table-transport.md index 082e7a042..21769a847 100644 --- a/docs/dev/specs/itl-1347-job-table-transport.md +++ b/docs/dev/specs/itl-1347-job-table-transport.md @@ -539,6 +539,9 @@ Any subclass, replaced reader, other stream kind, other data context or other sy type takes `main`'s row path. A retained output held as its rows (`RowsOnRead`) keeps only its rows once every successor has read it (`release_built`), as `main` retained only the rows. +An observer or callback that changes the job, its nodes or its bound sources during a run +is unsupported; what the run then does is undefined and is not part of the equality with +`main` (ITL-1369; developer, November 22, 2026). | # | What differs | On `main` today | On the branch | Why `main` is wrong (bug, reproducer) | Approval needed | |---|---|---|---|---|---| @@ -548,7 +551,6 @@ only the rows. | e6 | Async values that depend on an earlier validation of the same operator object | `SemiJoin._validated_common_keys` and `Index._element_arrow_type_fallback` hold the last validation's values (ITL-858, section 1.2). One operator object applied to two streams can use the other stream's keys or fallback type | Read from each input's description, with no state | The ITL-858 finding; filed as ITL-1358. Reproducer: one `SemiJoin` instance validated on stream B, then run async over stream A with other keys. To be confirmed in stage 5 | ITL-1358 (filed); fixed with stage 5 once a reproducer confirms it | | e7 | What a consumer does after its producer failed (async, failure path) | The producer closes its output in `finally`, so a consumer sees a normal end and may finish, and a `LOG` operator node may store, a partial result before the task group cancels it | Readers raise `UpstreamFailedError` at the failure point instead of seeing a normal end, so no consumer finishes, or stores its result, as if its input were complete. Batches a consumer processed before the failure are still processed, and a streaming node may already have passed them on or a function node stored results for them, as on `main`; there is no rollback. A barrier operator never computes over a partial input. The run raises the producer's own error, as today | A candidate race, to be confirmed with a reproducer in stage 5: a `fail_fast` function node raising on row 3 of 6, feeding a `Select` node in `LOG` mode; check the operator cache after the failed run. If `main` never stores in practice, this row is no difference | filed by the developer only once a test reproduces it | | e8 | Meta columns of an async side-effect node's rows | An async side-effect node passes on and holds the rows it receives as they are, so a computed row keeps its `__computed` meta column (from the cached function pod), and the node's `as_table(all_info=True)` shows it. On sync, its input is rebuilt from rows (`_rows_to_table` drops meta), so the column is absent | Async drops input meta columns as sync does. With table transport this follows from the transport columns, which hold no meta column | A `main` bug: the async and sync paths give the node different columns. Found by the stage 0 harness on `job-speed` 0e15d0db, which does not change side-effect nodes; the stage 0 differential checks it on pinned `main`. Reproducer: a function node (with a result store) feeding a `tap_pod`, async against sync, comparing the side-effect node's `as_table(all_info=True)` columns | approved (developer, 2026-11-22) | -| e11 | An empty source fanned out to two operators, with an observer that rebinds the source between the two edges | Each successor's input is rebuilt at its own edge, so the second sees the rebound source's zero-row form (its field metadata) | The output held as its rows (`RowsOnRead`) is built once, at the first edge, and the second edge reuses it, so the second successor sees the first edge's form | Not a `main` bug: an observer that mutates the graph mid-run (Codex on PR #485, round 5). Reproducer: `tests/test_pipeline/test_rows_on_read.py::test_a_fanned_out_empty_source_rebound_between_edges` (strict xfail) | open: not approved; the coordinator takes it to the developer as a documented limit (2026-11-22) | **Resolved: refusals after rows have flowed (was c, question 9).** The developer's `Rejoin` rule (ITL-1355) removes every data-dependent refusal from `Rejoin`: it checks only what its diff --git a/tests/test_pipeline/test_rows_on_read.py b/tests/test_pipeline/test_rows_on_read.py index c99226060..800fced83 100644 --- a/tests/test_pipeline/test_rows_on_read.py +++ b/tests/test_pipeline/test_rows_on_read.py @@ -1052,41 +1052,3 @@ def test_a_lazy_output_describes_itself_without_converting_python_types( job.bind(sources={"s": raw}) out: Any = job.nodes["s"].execute() assert out.arrow_schema().field("x").type == kind - - -@pytest.mark.xfail( - strict=True, - raises=AssertionError, - reason="spec row e11: observer rebinds between two edges of one empty output (open)", -) -def test_a_fanned_out_empty_source_rebound_between_edges() -> None: - """Pinned limit (spec row e11): ``main`` rebuilds each edge, the branch builds once.""" - from orcapod.operators import SelectDataColumns - - def empty(mark: str) -> ArrowTableSource: - field = pa.field("x", pa.int64(), nullable=False, metadata={"mark": mark}) - table = pa.Table.from_arrays( - [pa.array([], pa.int64()), pa.array([], pa.int64())], - schema=pa.schema([pa.field("k", pa.int64(), nullable=False), field]), - ) - return ArrowTableSource(table, tag_columns=["k"], source_id="s") - - job = PipelineJob(name="fan_out_empty", database=InMemoryArrowDatabase()) - with job: - source = empty("initial") - SelectDataColumns(["x"])(source, label="first") - SelectDataColumns(["x"])(source, label="second") - slot = next(label for label in job.nodes if label not in ("first", "second")) - node = job.nodes[slot] - - class RebindsAfterFirst(NoOpObserver): - def contextualize(self, *identity_path: str) -> RebindsAfterFirst: - return self - - def on_node_end(self, node_label: str, node_hash: str) -> None: - if node_label == "first": - node.bound_source = empty("next") - - job.run(observer=RebindsAfterFirst()) - kept = job.nodes["second"].as_table() - assert kept.schema.field("x").metadata == {b"mark": b"next"} From 392655e001583ace2863b573500f69514e6016d6 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 13:51:52 -0800 Subject: [PATCH 35/36] fix(pipeline): an operator node reads its result from the one computation it captured (ITL-1360) CodeRabbit on PR #485 (dd6b7cd4): after produced_stream had refreshed the result wrapper, the node read the table (eager route) and the rows (row path, the error rows) through the wrapper again; over an upstream with no modified time each such read runs the operator again, so the operator ran twice where main runs it once, and the table could come from a second computation. The node now reads the table, the rows and the error rows from the captured stream. With no row, main's own kept-output path reads the wrapper once more, and so does the branch (main's count, unchanged). Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/nodes/operator_node.py | 10 ++++-- tests/test_pipeline/test_rows_on_read.py | 46 ++++++++++++++++++++++++ 2 files changed, 53 insertions(+), 3 deletions(-) diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index 1e60993e9..9e28abc91 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -1722,7 +1722,10 @@ def execute( reads_as_its_class(produced, ArrowTableStream) and produced.data_context_key == self.data_context_key ): - result_table = result_stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS) + # From the captured stream: reading the wrapper again could run the + # operator again (an upstream with no modified time), so the table, + # the keys and the gate describe one computation. + result_table = produced.as_table(columns=ZERO_ROW_INPUT_COLUMNS) if not system_tags_as_rows_give(result_table.schema): result_table = None if result_table is None: @@ -1730,7 +1733,8 @@ def execute( # data context, system tags the rows type otherwise): main's own row # path, its rows read once and handed on unchanged, its table built # where a successor reads it (ITL-1347). - rows = list(result_stream.iter_data()) + # The rows of the computation already made (``produced``), read once. + rows = list(produced.iter_data()) self._cached_output_stream = StaticOutputOperatorPod._kept_output( result_stream, rows ) @@ -1751,7 +1755,7 @@ def execute( ) except RowBuiltFormUnavailable as error: StaticOutputOperatorPod._raise_as_rows_do( - result_stream.iter_data(), error + produced.iter_data(), error ) self._cached_output_stream = ArrowTableStream( kept_table, tag_columns=tag_keys, data_tags=data_tags diff --git a/tests/test_pipeline/test_rows_on_read.py b/tests/test_pipeline/test_rows_on_read.py index 800fced83..988d83f5a 100644 --- a/tests/test_pipeline/test_rows_on_read.py +++ b/tests/test_pipeline/test_rows_on_read.py @@ -1023,6 +1023,52 @@ def watched(*args: Any, **kwargs: Any) -> Any: assert output.as_table().num_rows == 2 +# ── CodeRabbit on dd6b7cd4: one computation per run ─────────────────────────── + + +@pytest.mark.parametrize("mode", [CacheMode.OFF, CacheMode.LOG], ids=["off", "log"]) +@pytest.mark.parametrize("route", ["eager", "rows"]) +def test_an_operator_runs_once_over_an_undated_upstream( + route: str, mode: CacheMode +) -> None: + """Over an upstream with no modified time, every read of the operator's result + wrapper runs the operator again; the node reads its table, keys and rows from the + one computation it captured, so the operator runs once, as on ``main``.""" + from orcapod.core.nodes.operator_node import OperatorJobNode + from orcapod.operators import SelectDataColumns + + calls: list[int] = [] + + class Undated(ArrowTableStream): + @property + def last_modified(self) -> Any: + return None + + class Unproven(ArrowTableStream): + """Not proven: ``main``'s row path.""" + + class Counting(SelectDataColumns): + def unary_static_process(self, stream: Any) -> Any: + calls.append(1) + out: Any = super().unary_static_process(stream) + if route == "eager": + return out + table = out.as_table(columns={"source": True, "system_tags": True}) + return Unproven(table, tag_columns=["k"]) + + table = pa.table({"k": [1, 2], "x": [10, 20], "y": [1, 2]}) + upstream = Undated(table, tag_columns=["k"]) + node = OperatorJobNode( + Counting(["x"]), + [upstream], + pipeline_database=InMemoryArrowDatabase(), + cache_mode=mode, + ) + output: Any = node.execute(upstream) + assert len(list(output.iter_data())) == 2 + assert len(calls) == 1 + + @pytest.mark.parametrize( "kind", [pa.time64("ns"), pa.decimal256(76, 40)], From 3ceed8a64200819e6d6632a10504ad45beeb82eb Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 14:27:39 -0800 Subject: [PATCH 36/36] test(pipeline): no deferred-read test rebinds a source mid-run; document an undeclared schema (ITL-1360) CodeRabbit on PR #485 (1ae78fbb): - test_a_fallback_source_reads_its_rows_once and test_an_empty_output_is_derived_at_the_edge no longer rebind a source from an observer (unsupported, ITL-1369): the first counts the source's row reads (once) and checks the edge's error comes after the source's end and before the successor starts; the second records the zero-row build between the source's end and the successor's start. - arrow_types_declared states what a False description can hold: an explicit Arrow declaration, a converted Python schema, or an empty schema for an unpolled poller; not guaranteed to hold the column names. Docstring and tests only. Co-Authored-By: Claude Opus 5.5 --- .../protocols/core_protocols/streams.py | 10 +- tests/test_pipeline/test_rows_on_read.py | 93 ++++++++++--------- 2 files changed, 55 insertions(+), 48 deletions(-) diff --git a/src/orcapod/protocols/core_protocols/streams.py b/src/orcapod/protocols/core_protocols/streams.py index ba68aa0da..c5d4e9d34 100644 --- a/src/orcapod/protocols/core_protocols/streams.py +++ b/src/orcapod/protocols/core_protocols/streams.py @@ -197,9 +197,13 @@ def arrow_types_declared(self) -> bool: ``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 converted from - the Python schema, and its names come in no guaranteed order; no consumer - relies on their order (ITL-1347). + narrower bind, an output held as its rows). 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 + an empty schema. So a ``False`` description is not guaranteed to hold the + stream's column names, and the names it holds come in no guaranteed order; no + consumer relies on either (ITL-1347). """ ... diff --git a/tests/test_pipeline/test_rows_on_read.py b/tests/test_pipeline/test_rows_on_read.py index 988d83f5a..2ffc76211 100644 --- a/tests/test_pipeline/test_rows_on_read.py +++ b/tests/test_pipeline/test_rows_on_read.py @@ -20,7 +20,6 @@ from orcapod.databases import InMemoryArrowDatabase from orcapod.operators import Batch from orcapod.pipeline.dag import OrcaDAG -from orcapod.pipeline.observer import NoOpObserver from orcapod.pipeline.sync_orchestrator import SyncPipelineOrchestrator from orcapod.sources import ArrowTableSource, DictSource from orcapod.types import CacheMode @@ -49,27 +48,30 @@ def _plain() -> DictSource: def test_a_fallback_source_reads_its_rows_once() -> None: - """A rebind after the source node ended does not change what it handed on. - - Its rows were read once, when it ran: the successor's edge raises the original - rows' ``ArrowTypeError``, as on ``main``. - """ + """A source whose whole-table build is unavailable: its rows are read once, when it + runs, and the successor's edge raises the rows' ``ArrowTypeError`` after the + source's end and before the successor starts, as on ``main``.""" job = PipelineJob(name="read_once", database=InMemoryArrowDatabase()) with job: - Batch(batch_size=2)(_plain().select_data_columns(["x"]), label="batched") - job.bind(sources={"s": _unconvertible()}) - node = job.nodes["s"] - - class RebindsAtEnd(NoOpObserver): - def contextualize(self, *identity_path: str) -> RebindsAtEnd: - return self + Batch(batch_size=2)( + _plain().select_data_columns(["x"], label="selected"), label="batched" + ) + source: Any = _unconvertible() + reads: list[int] = [] + read = source.iter_data - def on_node_end(self, node_label: str, node_hash: str) -> None: - if node_label == "s": - node.bound_source = _plain() + def counted() -> Any: + reads.append(1) + return read() + source.iter_data = counted + job.bind(sources={"s": source}) + observer = _NodeEvents() with pytest.raises(pa.ArrowTypeError, match="Expected bytes"): - job.run(observer=RebindsAtEnd()) + job.run(observer=observer) + assert len(reads) == 1 + assert ("end", "s") in observer.events + assert ("start", "selected") not in observer.events def test_a_fallback_source_nobody_reads_completes() -> None: @@ -323,39 +325,40 @@ def test_a_library_source_kind_is_eager() -> None: assert not isinstance(job.nodes["s"].execute(), RowsOnRead) -def test_an_empty_output_is_derived_at_the_edge() -> None: - """A source with no row: its zero-row output is derived where the successor reads. - - An observer that rebinds the source when it ends changes what the successor - receives, as on ``main`` (Codex on PR #485, round 4). - """ - - def empty(mark: str) -> ArrowTableSource: - field = pa.field("x", pa.int64(), nullable=False, metadata={"mark": mark}) - table = pa.table({"k": pa.array([], pa.int64()), "x": pa.array([], pa.int64())}) - table = pa.Table.from_arrays( - table.columns, - schema=pa.schema([pa.field("k", pa.int64(), nullable=False), field]), - ) - return ArrowTableSource(table, tag_columns=["k"], source_id="s") - +def test_an_empty_output_is_derived_at_the_edge( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A source with no row: its zero-row input is built where the successor reads it, + after the source has ended and before the successor starts, as ``main`` rebuilt + it (Codex on PR #485, round 4).""" + from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod + + field = pa.field("x", pa.int64(), nullable=False) + table = pa.Table.from_arrays( + [pa.array([], pa.int64()), pa.array([], pa.int64())], + schema=pa.schema([pa.field("k", pa.int64(), nullable=False), field]), + ) job = PipelineJob(name="empty_edge", database=InMemoryArrowDatabase()) with job: - empty("before").select_data_columns(["x"], label="selected") + ArrowTableSource(table, tag_columns=["k"], source_id="s").select_data_columns( + ["x"], label="selected" + ) slot = next(label for label in job.nodes if label != "selected") - node = job.nodes[slot] - - class RebindsAtEnd(NoOpObserver): - def contextualize(self, *identity_path: str) -> RebindsAtEnd: - return self + observer = _NodeEvents() + original = StaticOutputOperatorPod._materialize_upstream # pyright: ignore[reportPrivateUsage] # the row path, watched - def on_node_end(self, node_label: str, node_hash: str) -> None: - if node_label == slot: - node.bound_source = empty("after") + def watched(rows: Any, upstream: Any) -> Any: + observer.events.append(("build", str(upstream.label))) + return original(rows, upstream) - job.run(observer=RebindsAtEnd()) - kept = job.nodes["selected"].as_table() - assert kept.schema.field("x").metadata == {b"mark": b"after"} + monkeypatch.setattr( + StaticOutputOperatorPod, "_materialize_upstream", staticmethod(watched) + ) + job.run(observer=observer) + events = observer.events + built = events.index(("build", slot)) + assert events.index(("end", slot)) < built < events.index(("start", "selected")) + assert job.nodes["selected"].as_table().num_rows == 0 def test_an_operator_with_an_empty_result_is_not_called_again() -> None: