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
3 changes: 3 additions & 0 deletions changelog.d/ITL-1437.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
### Changed

- Async run summaries explain that counts of computed and reused rows reflect the work each node did in that run. Scheduling can change which equal inputs compute a result and which reuse it.
5 changes: 5 additions & 0 deletions docs/concepts/function-pods.md
Original file line number Diff line number Diff line change
Expand Up @@ -603,6 +603,11 @@ many rows were computed, how many were read from the database, and how many fail
of a notebook cell it is shown as a table; `print` shows the same as text. The job keeps it as
`job.last_run`. The results themselves are read from `job.nodes`, as above.

The computed and from-store counts describe the work each node actually did in that run.
In an async run, equal inputs can arrive from different sources before a result is
available. Several rows may compute it concurrently, while later arrivals can reuse it.
Scheduling can change which nodes get credit for computing or reusing a result.

Running the same job again computes nothing new, and the summary says so:

```python
Expand Down
5 changes: 4 additions & 1 deletion docs/concepts/provenance.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,10 @@ three records the job keeps.
of the input with the same system tags.
- **A function node's stored records.** For each input row a function node received, its
pipeline record names that row (by its tags and system tags), the result it was served,
and whether this row computed the result or reused one. The stored result says which
and whether this row computed the result or reused one. The entry's `__computed`
field records what happened when that entry was written. When equal inputs arrive
concurrently in an async run, their arrival and cache lookup timing can change
which entries record a computation. The stored result says which
function ran: its name, version and body hash, the executor, the Python version and the
time. The trace shows these as a `FunctionRun`, and checks that the input row's content
hash is the one the record stored.
Expand Down
8 changes: 7 additions & 1 deletion src/orcapod/pipeline/job.py
Original file line number Diff line number Diff line change
Expand Up @@ -1079,8 +1079,9 @@ def run(
plan = prepared.plan
counter = RunCountingObserver()
effective_orchestrator = orchestrator or SyncPipelineOrchestrator()
is_sync = isinstance(effective_orchestrator, SyncPipelineOrchestrator)
with self._executing(prepared, plan, commit_every_rows, load_only=load_only):
if isinstance(effective_orchestrator, SyncPipelineOrchestrator):
if is_sync:
# Held nodes give their output streams on the sync path (ITL-1347).
_ = effective_orchestrator.run(
plan.dag,
Expand Down Expand Up @@ -1108,6 +1109,7 @@ def run(
plan,
load_only=load_only,
unchecked_sources=prepared.unchecked_sources,
asynchronous=not is_sync,
)
if not summary.ok:
warn_row_failures(summary, sys._getframe(1)) # pyright: ignore[reportPrivateUsage] # the caller's line is where the warning is shown
Expand Down Expand Up @@ -1179,6 +1181,7 @@ async def run_async(
plan,
load_only=load_only,
unchecked_sources=prepared.unchecked_sources,
asynchronous=True,
)
if not summary.ok:
warn_row_failures(summary, sys._getframe(1)) # pyright: ignore[reportPrivateUsage] # the caller's line is where the warning is shown
Expand Down Expand Up @@ -1481,6 +1484,7 @@ def _finish_run(
*,
load_only: bool = False,
unchecked_sources: tuple[str, ...] = (),
asynchronous: bool,
) -> RunSummary:
"""Commit the run's last writes, mark the job as run and keep its summary.

Expand All @@ -1493,6 +1497,7 @@ def _finish_run(
plan: The nodes the run ran and held (``plan_run``).
load_only: Whether the run loaded stored results only.
unchecked_sources: The sources the start-of-run check could not check.
asynchronous: Whether the async orchestrator executed the run.

Returns:
The run's summary, also kept as ``last_run``.
Expand Down Expand Up @@ -1556,6 +1561,7 @@ def _finish_run(
unchecked_sources=unchecked_sources,
ran_nothing=not plan.to_run,
restricted_sources=restrictions_in_force(prepared.exec_dag.nodes()),
asynchronous=asynchronous,
)
return self._last_run

Expand Down
23 changes: 23 additions & 0 deletions src/orcapod/pipeline/run_summary.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,10 @@
from orcapod.types import Condition, SchemaLike

_NOOP_LOGGER = NoOpLogger()
_ASYNC_ATTRIBUTION_NOTE = (
"Computed and from-store counts reflect this run. Equal inputs may arrive in a "
"different order or be computed concurrently."
)


@dataclass(frozen=True)
Expand Down Expand Up @@ -71,6 +75,10 @@ class RunSummary:
for a node with failed rows, the first error and how to see its full traceback. The job
also keeps it as ``job.last_run``.

Counts attribute work to the nodes that actually did it. In an async run, whichever
equal inputs arrive before a result is available may compute it. Later inputs can
reuse it, so the attribution and counts can vary with scheduling.

Attributes:
job_name: The job's name.
nodes: Per function node, in run order, keyed by label.
Expand Down Expand Up @@ -108,6 +116,7 @@ def __init__(
unchecked_sources: Sequence[str] = (),
ran_nothing: bool = False,
restricted_sources: Mapping[str, RestrictedSource] | None = None,
asynchronous: bool = False,
) -> None:
"""Build the summary.

Expand All @@ -122,13 +131,19 @@ def __init__(
for none) and the limit of each restricted source of the run
(``restrictions.restrictions_in_force``). Displayed by slot name
or direct source label.
asynchronous: Whether the async orchestrator executed the run.
"""
self.job_name: str = job_name
self.nodes: Mapping[str, NodeRunSummary] = {node.label: node for node in nodes}
self.load_only: bool = load_only
self.target: str | None = target
self.unchecked_sources: tuple[str, ...] = tuple(unchecked_sources)
self.ran_nothing: bool = ran_nothing
self._attribution_note: str = (
_ASYNC_ATTRIBUTION_NOTE
if asynchronous and not load_only and not ran_nothing and nodes
else ""
)
# One mapping split three ways, so the keys cannot disagree.
restricted = dict(sorted((restricted_sources or {}).items()))
self.conditions: Mapping[str, Condition] = {
Expand Down Expand Up @@ -256,6 +271,8 @@ def __repr__(self) -> str:
restricted = self._restrictions_line()
if restricted is not None:
lines.append(f" {restricted}")
if self._attribution_note:
lines.append(f" {self._attribution_note}")
for node in self.nodes.values():
lines.append(
f" {node.label}: {_rows(node.rows)}: {_counts(node, self.load_only)}"
Expand Down Expand Up @@ -300,8 +317,14 @@ def _repr_html_(self) -> str:
f"<td{failed_style}>{node.failed}</td><td>{error}</td>"
"</tr>"
)
attribution = (
f"<p>{html.escape(self._attribution_note)}</p>"
if self._attribution_note
else ""
)
return (
f"<p>{html.escape(self._headline())}</p>{self._source_lines_html()}"
f"{attribution}"
f"<table><thead><tr>{header}</tr></thead>"
f"<tbody>{''.join(body)}</tbody></table>"
)
Expand Down
88 changes: 85 additions & 3 deletions tests/test_pipeline/test_job_run_summary.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,21 +9,26 @@
from __future__ import annotations

import ast
import asyncio
import warnings
from collections.abc import Callable
from collections.abc import AsyncIterator, Callable
from pathlib import Path
from typing import Any

import pytest
from typing_extensions import override

from orcapod import PipelineJob, function_pod
from orcapod.core.nodes.function_node import FunctionJobNode
from orcapod.databases import DeltaTableDatabase, InMemoryArrowDatabase
from orcapod.errors import RowFailuresWarning
from orcapod.pipeline import (
AsyncPipelineOrchestrator,
RunSummary,
SyncPipelineOrchestrator,
)
from orcapod.pipeline.observer import NoOpObserver
from orcapod.protocols.core_protocols import DataProtocol, TagProtocol
from orcapod.sources import DictSource

# --- The public names this feature adds, in one place ---------------------------------
Expand Down Expand Up @@ -204,8 +209,6 @@ def test_notebook_representation_names_the_failing_node() -> None:

def test_run_async_returns_the_same_summary(store: Any) -> None:
"""``run_async`` returns the summary, warns, and keeps it as ``last_run``."""
import asyncio

job = make_job(store, even_only, "evens")
with pytest.warns(RowFailuresWarning, match="2 of 4 rows failed in node 'evens'"):
summary = asyncio.run(job.run_async())
Expand All @@ -214,6 +217,85 @@ def test_run_async_returns_the_same_summary(store: Any) -> None:
assert last_run(job) is summary


@pytest.mark.parametrize("first_async_source", [None, "a", "b"], ids=["sync", "a", "b"])
def test_equal_inputs_report_the_work_each_source_did(
first_async_source: str | None,
) -> None:
"""Three sources share results, while async arrival determines who computes."""
source_ids = ("a", "b", "c")
first_finished = asyncio.Event()
first_rows = 0

class GatedSource(DictSource):
@override
async def async_iter_data(
self,
) -> AsyncIterator[tuple[TagProtocol, DataProtocol]]:
if self.source_id != f"dict_v1:{first_async_source}":
_ = await first_finished.wait()
async for row in super().async_iter_data():
yield row

class ReleaseLaterSources(NoOpObserver):
@override
def on_data_end(
self,
node_label: str,
tag: TagProtocol,
input_data: DataProtocol,
output_data: DataProtocol | None,
cached: bool,
) -> None:
nonlocal first_rows
if node_label == f"double_{first_async_source}":
first_rows += 1
if first_rows == 2:
first_finished.set()

job = PipelineJob(name="equal_inputs", database=InMemoryArrowDatabase())
with job:
for source_id in source_ids:
source = GatedSource(
[{"k": "first", "x": 4}, {"k": "second", "x": 6}],
tag_columns=["k"],
tag_only_columns=True,
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
source_id=source_id,
)
_ = double.pod(source, label=f"double_{source_id}")

async def run_gated() -> RunSummary:
return await asyncio.wait_for(
job.run_async(observer=ReleaseLaterSources()), timeout=10
)

summary = job.run() if first_async_source is None else asyncio.run(run_gated())
computed_source = first_async_source or "a"
for source_id in source_ids:
label = f"double_{source_id}"
node = job.nodes[label]
assert isinstance(node, FunctionJobNode)
computed = source_id == computed_source
assert node_counts(summary, label) == ((2, 0, 0) if computed else (0, 2, 0))
rows = [
(tag.as_dict()["k"], data.as_dict()["y"]) for tag, data in node.iter_data()
]
expected = [("first", 8), ("second", 12)]
if first_async_source is None:
assert rows == expected
else:
assert len(rows) == len(expected)
assert set(rows) == set(expected)
for key, _ in expected:
((trace_label, invocation),) = node.trace({"k": key}, "y").function_runs()
assert trace_label == label
assert invocation.computed_here is computed

note = "Computed and from-store counts reflect this run"
assert (note in repr(summary)) == (first_async_source is not None)
html = summary._repr_html_() # pyright: ignore[reportPrivateUsage] # notebook display hook under test
assert (note in html) == (first_async_source is not None)


@function_pod(output_keys="z")
def plus_one(y: int) -> int:
"""Return ``y + 1``."""
Expand Down
Loading