Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions changelog.d/ITL-1351.md
Original file line number Diff line number Diff line change
@@ -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.
33 changes: 32 additions & 1 deletion src/orcapod/core/nodes/function_node.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
"""
Expand All @@ -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.
Expand Down
12 changes: 12 additions & 0 deletions src/orcapod/core/nodes/operator_node.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
13 changes: 13 additions & 0 deletions src/orcapod/core/nodes/staleness.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""
Expand Down
4 changes: 3 additions & 1 deletion src/orcapod/pipeline/node_run.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)


Expand Down
8 changes: 8 additions & 0 deletions src/orcapod/side_effects.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
154 changes: 154 additions & 0 deletions tests/test_pipeline/test_held_row_count.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
"""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()
# The held rows come from runs on the orchestrator under test (CodeRabbit, #476).
_job(db).run(orchestrator=ORCHESTRATORS[orchestrator]())
job = _job(db)
job.run(orchestrator=ORCHESTRATORS[orchestrator](), 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())
Loading