From 3d7fd051ab2379eea3c5892866cb0955190214d2 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" <> Date: Sat, 21 Nov 2026 21:19:58 -0800 Subject: [PATCH 1/2] perf(pipeline): count a held node's rows from what it holds, not by building them (ITL-1351) plan_run counted every held node's rows for the run summary with sum(1 for _ in node.iter_data()). For an operator node that builds a (Tag, Data) pair per row of its output only to count it: in a run where every node is held, nearly all the time (5.6 of 5.7 s on a workshop-scale job). RunHoldingNode gains held_row_count(), the count iter_data would give, from what each kind holds: an operator node its current output's table row count, a function node its run's inputs that have an output (from the entry counts it keeps), a side-effect node its held rows. plan_run uses it. Counts and summaries are unchanged; no hash, stored layout or output changes. The tests compare the new counts with iterating the rows for every held node kind (operator, function, side effect), after a full and a load-only run, on both orchestrators, and check that a fully held run builds no Data (which fails on the old count). Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1351.md | 9 ++ src/orcapod/core/nodes/function_node.py | 33 ++++- src/orcapod/core/nodes/operator_node.py | 12 ++ src/orcapod/core/nodes/staleness.py | 13 ++ src/orcapod/pipeline/node_run.py | 4 +- src/orcapod/side_effects.py | 8 ++ tests/test_pipeline/test_held_row_count.py | 153 +++++++++++++++++++++ 7 files changed, 230 insertions(+), 2 deletions(-) create mode 100644 changelog.d/ITL-1351.md create mode 100644 tests/test_pipeline/test_held_row_count.py diff --git a/changelog.d/ITL-1351.md b/changelog.d/ITL-1351.md new file mode 100644 index 000000000..a003ecc38 --- /dev/null +++ b/changelog.d/ITL-1351.md @@ -0,0 +1,9 @@ +### Changed + +- A run counts the rows of the nodes it holds without building them (ITL-1351). The run + summary's count of a held node's rows (`plan_run`) iterated the node's rows, which built + a `(Tag, Data)` pair per row of an operator's output only to count it; a run in which + every node holds a current run spent most of its time there. Each kind of job node that + holds a run now counts what it holds (`held_row_count`: an operator node its output + table's row count, a function node its run's inputs with an output, a side-effect node + its held rows), with the same counts and summaries as before. diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 117eb50b9..adccd23b4 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -3955,6 +3955,38 @@ def iter_data(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: changed since its run) yields nothing (ITL-1095); ``as_source()`` reads every row stored for it. + Raises: + RuntimeError: If ``load_status`` is UNAVAILABLE. + """ + self._prepare_held_read() + yield from self._held_pairs() + + def held_row_count(self) -> int: + """The number of rows ``iter_data`` yields now, counted from the run's inputs. + + The same count as ``iter_data`` (one row per input of the run that has an + output), without going through the rows (ITL-1351). + + Returns: + The row count. + + Raises: + RuntimeError: If ``load_status`` is UNAVAILABLE. + """ + self._prepare_held_read() + counts = self._run_entry_counts + if counts is None: + return 0 + return sum( + counts.get(entry_id, 0) + for entry_id, (_, data) in self._cached_output_datas.items() + if data is not None + ) + + def _prepare_held_read(self) -> None: + """What every read of the held rows does first: refuse a node with no database + to read, and drop rows that went stale. + Raises: RuntimeError: If ``load_status`` is UNAVAILABLE. """ @@ -3966,7 +3998,6 @@ def iter_data(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: # A CACHE_ONLY node has no live input to be stale against. if status != LoadStatus.CACHE_ONLY and self.is_stale: self.clear_cache() - yield from self._held_pairs() def run(self, *, load_only: bool = False) -> StreamView: """Run the node as a job run would, and return a ``StreamView`` of its rows. diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index 12a19d954..2f725683a 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -1927,6 +1927,18 @@ def _current_output(self) -> StreamProtocol | None: return None return self._cached_output_stream + def held_row_count(self) -> int: + """The number of rows of the node's current run, from its output table. + + The same count as ``iter_data`` (0 when the node holds no run), without building + a ``(Tag, Data)`` pair per row (ITL-1351). + + Returns: + The row count. + """ + current = self._current_output() + return 0 if current is None else current.as_table().num_rows + def iter_data(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: """Return an iterator over the (tag, data) rows of the node's current run. diff --git a/src/orcapod/core/nodes/staleness.py b/src/orcapod/core/nodes/staleness.py index 8ae8162a8..b7a140a61 100644 --- a/src/orcapod/core/nodes/staleness.py +++ b/src/orcapod/core/nodes/staleness.py @@ -73,6 +73,19 @@ def _holds_run(self, *, load_only: bool) -> bool: """Whether the node holds the rows of a completed run good for such a run.""" raise NotImplementedError + def held_row_count(self) -> int: + """The number of rows ``iter_data`` yields now, counted without building them. + + A run's summary counts the rows of every node it holds (``plan_run``). + Iterating them would build a ``(Tag, Data)`` pair per row of an operator's + output (ITL-1351); each kind counts what it holds instead, with the same + result as ``sum(1 for _ in node.iter_data())``. + + Returns: + The row count. + """ + raise NotImplementedError + def _job_upstreams(node: Any) -> list[RunHoldingNode]: """The direct upstreams of ``node`` that are job nodes holding run rows.""" diff --git a/src/orcapod/pipeline/node_run.py b/src/orcapod/pipeline/node_run.py index 4252ce854..c1a031c90 100644 --- a/src/orcapod/pipeline/node_run.py +++ b/src/orcapod/pipeline/node_run.py @@ -343,7 +343,9 @@ 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_counts = {node: sum(1 for _ in node.iter_data()) for node in current} + # 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) diff --git a/src/orcapod/side_effects.py b/src/orcapod/side_effects.py index 20087e938..9cb769522 100644 --- a/src/orcapod/side_effects.py +++ b/src/orcapod/side_effects.py @@ -1335,6 +1335,14 @@ def iter_data(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: """ yield from self._current_rows() or () + def held_row_count(self) -> int: + """The number of rows the last run of this node passed on (``iter_data``'s count). + + Returns: + The row count; 0 with no rows from a completed run, as ``iter_data``. + """ + return len(self._current_rows() or ()) + @override def head( self, diff --git a/tests/test_pipeline/test_held_row_count.py b/tests/test_pipeline/test_held_row_count.py new file mode 100644 index 000000000..73e8ce8e8 --- /dev/null +++ b/tests/test_pipeline/test_held_row_count.py @@ -0,0 +1,153 @@ +"""A run counts the rows of the nodes it holds without building them (ITL-1351). + +``plan_run`` gives the run summary every held node's row count. It used to iterate the +node's rows, which builds a ``(Tag, Data)`` pair per row of an operator's output only to +count it. Each kind of held node now counts what it holds (``held_row_count``); the +counts, and so the summaries, must be those of iterating the rows, for every kind of node +that holds a run (operator, function, side effect), after a full and a load-only run, on +the sync and the async orchestrator. +""" + +from __future__ import annotations + +from typing import Any + +import pyarrow as pa +import pytest + +import orcapod.pipeline.job as job_module +from orcapod import PipelineJob, function_pod +from orcapod.core.datagrams import tag_data +from orcapod.core.nodes import FunctionJobNode, OperatorJobNode +from orcapod.databases import InMemoryArrowDatabase +from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator +from orcapod.side_effects import SideEffectJobNode, SideEffectPod, side_effect_pod +from orcapod.sources import ArrowTableSource + +ORCHESTRATORS = {"sync": SyncPipelineOrchestrator, "async": AsyncPipelineOrchestrator} +# The kinds of job node that hold a run (``RunHoldingNode``). +HOLDING = (OperatorJobNode, FunctionJobNode, SideEffectJobNode) + + +@function_pod(output_keys="y") +def scaled(x: int, w: float) -> float: + """Return ``x * w``.""" + return x * w + + +@function_pod(output_keys="total") +def summed(x: list[int]) -> int: + """Return the sum of a group's values.""" + return sum(x) + + +def _note(x: int, ctx: Any) -> None: # pyright: ignore[reportExplicitAny] # the invocation context + """A side effect that does nothing.""" + + +def _source() -> ArrowTableSource: + """Two tags (``g``, ``k``) and two data columns (``x``, ``w``, one null ``w``).""" + table = pa.table( + { + "k": pa.array([f"r{i}" for i in range(8)], pa.large_string()), + "x": pa.array(range(8), pa.int64()), + "g": pa.array([i % 3 for i in range(8)], pa.int64()), + "w": pa.array([0.5, 1.5, None, 2.5, 3.5, 4.5, 5.5, 6.5], pa.float64()), + }, + schema=pa.schema( + [ + pa.field("k", pa.large_string(), nullable=False), + pa.field("x", pa.int64(), nullable=False), + pa.field("g", pa.int64(), nullable=False), + pa.field("w", pa.float64()), + ] + ), + ) + return ArrowTableSource( + table, tag_columns=["g", "k"], tag_only_columns=True, source_id="held" + ) + + +def _job(db: Any) -> PipelineJob: # pyright: ignore[reportExplicitAny] # a database + """Operators (drop_nulls, select, group_by), function pods and a side effect.""" + tap = side_effect_pod(_note) + assert isinstance(tap, SideEffectPod) + job = PipelineJob(name="held", database=db) + with job: + kept: Any = _source().drop_nulls(["w"], label="kept") # pyright: ignore[reportExplicitAny] + scaled.pod(kept, label="scaled") + tap.process(kept.select_data_columns(["x"], label="xs"), label="tapped") + summed.pod( + kept.select_data_columns(["x"]).group_by("g", label="grouped"), label="sums" + ) + return job + + +def _iterated(job: PipelineJob) -> dict[str, int]: + """Every held node's row count by iterating its rows (the old count).""" + return { + label: sum(1 for _ in node.iter_data()) + for label, node in job.nodes.items() + if isinstance(node, HOLDING) + } + + +@pytest.mark.parametrize("orchestrator", sorted(ORCHESTRATORS)) +@pytest.mark.parametrize("load_only", [False, True], ids=["full", "load_only"]) +def test_a_held_run_counts_every_held_node_as_its_rows_and_builds_none( + orchestrator: str, load_only: bool, monkeypatch: pytest.MonkeyPatch +) -> None: + db = InMemoryArrowDatabase() + _job(db).run() + job = _job(db) + job.run(load_only=load_only) + + plans: list[Any] = [] # pyright: ignore[reportExplicitAny] # RunPlan + plan_run = job_module.plan_run + + def spying(*args: Any, **kwargs: Any) -> Any: # pyright: ignore[reportExplicitAny] + plans.append(plan_run(*args, **kwargs)) + return plans[-1] + + built: list[int] = [] + data_init = tag_data.Data.__init__ + + def counting(self: Any, *args: Any, **kwargs: Any) -> None: # pyright: ignore[reportExplicitAny] + built.append(1) + data_init(self, *args, **kwargs) + + monkeypatch.setattr(job_module, "plan_run", spying) + monkeypatch.setattr(tag_data.Data, "__init__", counting) + summary = job.run(orchestrator=ORCHESTRATORS[orchestrator](), load_only=load_only) + monkeypatch.undo() + + # Every node held: nothing ran, and counting the held rows built no datagram. + assert repr(summary).splitlines()[0].endswith("every node holds a current run.") + assert built == [] + (plan,) = plans + counts = {node.label: count for node, count in plan.held_counts.items()} + expected = _iterated(job) + assert counts == expected + # Two equal selects over one input are one node, so its label is the default one. + assert {"kept", "scaled", "tapped", "grouped", "sums"} <= set(counts) + assert len(counts) == len(expected) == 6 + assert expected["kept"] == 7 and expected["grouped"] == 3 + for label in ("scaled", "sums"): + assert summary.nodes[label].held == expected[label] + + +def test_a_node_counts_its_rows_as_iterating_them_does_before_and_after_a_run() -> None: + job = _job(InMemoryArrowDatabase()) + held = [n for n in job.nodes.values() if isinstance(n, HOLDING)] + assert {type(n).__name__ for n in held} == { + "OperatorJobNode", + "FunctionJobNode", + "SideEffectJobNode", + } + assert all(n.held_row_count() == 0 == sum(1 for _ in n.iter_data()) for n in held) + job.run() + for node in held: + assert node.held_row_count() == sum(1 for _ in node.iter_data()), node.label + for node in held: + node.clear_cache() + assert node.held_row_count() == 0 == sum(1 for _ in node.iter_data()) From 8094f093bc44d41ef1f1ebc5c828ba0df32f82d8 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" <> Date: Sat, 21 Nov 2026 21:58:07 -0800 Subject: [PATCH 2/2] test(pipeline): fill the held rows on the orchestrator under test (ITL-1351) CodeRabbit on #476: the preparation runs used the default (sync) orchestrator, so the async case never counted rows the async orchestrator had produced. Both preparation runs now use the orchestrator the case is about. Co-Authored-By: Claude Opus 5.5 --- tests/test_pipeline/test_held_row_count.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/tests/test_pipeline/test_held_row_count.py b/tests/test_pipeline/test_held_row_count.py index 73e8ce8e8..5c43bd3e1 100644 --- a/tests/test_pipeline/test_held_row_count.py +++ b/tests/test_pipeline/test_held_row_count.py @@ -98,9 +98,10 @@ def test_a_held_run_counts_every_held_node_as_its_rows_and_builds_none( orchestrator: str, load_only: bool, monkeypatch: pytest.MonkeyPatch ) -> None: db = InMemoryArrowDatabase() - _job(db).run() + # The held rows come from runs on the orchestrator under test (CodeRabbit, #476). + _job(db).run(orchestrator=ORCHESTRATORS[orchestrator]()) job = _job(db) - job.run(load_only=load_only) + job.run(orchestrator=ORCHESTRATORS[orchestrator](), load_only=load_only) plans: list[Any] = [] # pyright: ignore[reportExplicitAny] # RunPlan plan_run = job_module.plan_run