From 66a780a49b5e1a1f1b543f00f17374c0130242fa Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Mon, 23 Nov 2026 23:59:00 -0800 Subject: [PATCH] docs(pipeline): clarify async computation attribution --- changelog.d/ITL-1437.md | 3 + docs/concepts/function-pods.md | 5 ++ docs/concepts/provenance.md | 5 +- src/orcapod/pipeline/job.py | 8 +- src/orcapod/pipeline/run_summary.py | 23 ++++++ tests/test_pipeline/test_job_run_summary.py | 88 ++++++++++++++++++++- 6 files changed, 127 insertions(+), 5 deletions(-) create mode 100644 changelog.d/ITL-1437.md diff --git a/changelog.d/ITL-1437.md b/changelog.d/ITL-1437.md new file mode 100644 index 000000000..f4a936da1 --- /dev/null +++ b/changelog.d/ITL-1437.md @@ -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. diff --git a/docs/concepts/function-pods.md b/docs/concepts/function-pods.md index 59d9c53d8..8aebfb95f 100644 --- a/docs/concepts/function-pods.md +++ b/docs/concepts/function-pods.md @@ -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 diff --git a/docs/concepts/provenance.md b/docs/concepts/provenance.md index 12b8e538d..6b0081968 100644 --- a/docs/concepts/provenance.md +++ b/docs/concepts/provenance.md @@ -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. diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index 434f198f3..2f80d1fa0 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -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, @@ -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 @@ -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 @@ -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. @@ -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``. @@ -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 diff --git a/src/orcapod/pipeline/run_summary.py b/src/orcapod/pipeline/run_summary.py index a10442636..778ac8140 100644 --- a/src/orcapod/pipeline/run_summary.py +++ b/src/orcapod/pipeline/run_summary.py @@ -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) @@ -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. @@ -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. @@ -122,6 +131,7 @@ 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} @@ -129,6 +139,11 @@ def __init__( 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] = { @@ -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)}" @@ -300,8 +317,14 @@ def _repr_html_(self) -> str: f"{node.failed}{error}" "" ) + attribution = ( + f"

{html.escape(self._attribution_note)}

" + if self._attribution_note + else "" + ) return ( f"

{html.escape(self._headline())}

{self._source_lines_html()}" + f"{attribution}" f"{header}" f"{''.join(body)}
" ) diff --git a/tests/test_pipeline/test_job_run_summary.py b/tests/test_pipeline/test_job_run_summary.py index a219f15c6..645273cf7 100644 --- a/tests/test_pipeline/test_job_run_summary.py +++ b/tests/test_pipeline/test_job_run_summary.py @@ -9,14 +9,17 @@ 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 ( @@ -24,6 +27,8 @@ 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 --------------------------------- @@ -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()) @@ -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, + 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``."""