From 8b925be6093e93c93c399edd81e405055d0533bd Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 13:13:05 -0800 Subject: [PATCH 1/3] fix(function-pod): share in-flight async results for equal inputs --- changelog.d/ITL-1101.md | 3 + docs/concepts/function-pods.md | 7 +- docs/concepts/pipeline-job.md | 9 +- docs/concepts/provenance.md | 4 +- docs/dev/design_issues/NOISSUE-FN1.md | 4 + docs/reference/hashing.md | 9 +- src/orcapod/core/cached_function_pod.py | 70 +++++- src/orcapod/core/function_pod.py | 29 ++- src/orcapod/pipeline/run_summary.py | 10 +- .../test_function_pod_concurrency.py | 216 +++++++++++++++++- .../test_job_node_rows_after_run.py | 11 +- tests/test_pipeline/test_provenance_review.py | 11 +- .../test_result_reuse_itl_1503.py | 79 +++++-- 13 files changed, 401 insertions(+), 61 deletions(-) create mode 100644 changelog.d/ITL-1101.md diff --git a/changelog.d/ITL-1101.md b/changelog.d/ITL-1101.md new file mode 100644 index 000000000..9870603c7 --- /dev/null +++ b/changelog.d/ITL-1101.md @@ -0,0 +1,3 @@ +### Fixed + +- Async function nodes now compute each distinct input only once when equal rows arrive concurrently. This also prevents repeated calls to functions that take the invocation context. diff --git a/docs/concepts/function-pods.md b/docs/concepts/function-pods.md index 03d09578f..ef3e8396c 100644 --- a/docs/concepts/function-pods.md +++ b/docs/concepts/function-pods.md @@ -656,9 +656,10 @@ of a notebook cell it is shown as a table; `print` shows the same as text. The j `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. +Within a function node, each distinct input data hash needs at most one successful +computation. In an async run, rows that arrive during that computation wait for its +result. Different nodes can share a result table, so scheduling can change which nodes +compute a result or reuse it. Running the same job again computes nothing new, and the summary says so: diff --git a/docs/concepts/pipeline-job.md b/docs/concepts/pipeline-job.md index 5111c077a..1ffbf5e83 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -223,10 +223,11 @@ recreated at the same path that happens to have the same version number: a handl had loaded the old table keeps reading it (ITL-1413). Open a new database object after replacing a table. -A function that takes the invocation context (`ctx_arg`) performs an external action, and -its result table records which inputs it was performed for. Jobs that share a result -database share that record too: a job performs the action only for inputs no job sharing -the database has performed it for. +A function that takes the invocation context (`ctx_arg`) performs an external action once +per distinct input data hash in a function node, on both the sync and async paths. Rows +with equal input data reuse the same stored result even when their tags differ. Jobs that +share a result database share that record too. To perform an action for each row, use a +[`SideEffectPod`](function-pods.md#side-effects-in-a-job-delivered-by-a-run-never-by-a-read). ### Result commit ordering diff --git a/docs/concepts/provenance.md b/docs/concepts/provenance.md index 8bc650427..9983994b9 100644 --- a/docs/concepts/provenance.md +++ b/docs/concepts/provenance.md @@ -92,8 +92,8 @@ three records the job keeps. 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 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 + concurrently at one function node, the first call computes the result and the other + rows wait to reuse it. 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/docs/dev/design_issues/NOISSUE-FN1.md b/docs/dev/design_issues/NOISSUE-FN1.md index c8222cedc..e353d3d87 100644 --- a/docs/dev/design_issues/NOISSUE-FN1.md +++ b/docs/dev/design_issues/NOISSUE-FN1.md @@ -15,3 +15,7 @@ The parent `FunctionNode.async_execute` already had the correct concurrent patte **Fix:** Rewrote Phase 2 to use the same `Semaphore + TaskGroup` pattern as the parent class. Phase 1 (replay cached results from DB) remains unchanged. Concurrency is controlled via `NodeConfig.max_concurrency` and `PipelineConfig`, resolved through `resolve_concurrency()`. + +**Follow-up (ITL-1101):** Phase 2 shares a pending call by input data hash within one +cached function node execution. Equal rows keep their own tags and pipeline records. +Distinct inputs still compute concurrently. The existing result store serves later rows. diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index 8a4fdcc1a..017f66320 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -400,6 +400,7 @@ A record id is the row identifier (rule 8), built from row positions or key valu | hooks (`pod_hash`) | `core/function_pod.py:_FunctionPodBase._build_post_run_payload` | | in-memory graph keys and sort keys | `pipeline/base.py:AbstractPipelineBase.compile`, `pipeline/base.py:AbstractPipelineBase.compile..`, `pipeline/base.py:AbstractPipelineBase._validate_invocation`, `pipeline/base.py:AbstractPipelineBase._validate_invocation..`, `pipeline/base.py:AbstractPipelineBase.to_invocations`, `pipeline/base.py:AbstractPipelineBase.from_invocations`, `pipeline/base.py:AbstractPipelineBase.from_invocations..`, `pipeline/job.py:PipelineJob.compile`, `pipeline/restrictions.py:sources_read` (the source identity a restriction is kept under, ITL-1218) | | in-memory source registration keys | `pipeline/source_consistency.py:require_consistent_sources` | +| in-memory key for an in-flight function result (ITL-1101) | `core/cached_function_pod.py:CachedFunctionPod._async_process_once` | | in-memory lookup keys for a validated operator input or input pair (ITL-1358) | `core/operators/index.py:Index.validate_unary_input`, `core/operators/index.py:Index.async_execute`, `core/operators/pick.py:Pick.validate_unary_input`, `core/operators/pick.py:Pick.async_execute`, `core/operators/semijoin.py:SemiJoin.validate_binary_inputs`, `core/operators/semijoin.py:SemiJoin.async_execute` | | in-memory topological sort of compiled and restored nodes, using the pipeline hash to order ready invocations | `pipeline/base.py:AbstractPipelineBase._ordered_node_map..order_key` | | canonical input order (sort by digest). Inputs with equal pipeline hashes (developer decision, November 16, 2026, ITL-1154: kept as it is): system-tag column names follow the stable pipeline-hash sort; each row's values are sorted by (source id, record id) by `sort_system_tag_values`, so the result does not depend on argument order; the operator's identity holds its inputs as a frozenset | `core/operators/join.py:Join.order_input_streams..` | @@ -1210,7 +1211,7 @@ next preimage with its label (`to_prefixed_digest()`). | Id | Hash of | Used by | Stored | |---|---|---|---| -| **entry id** | the row's user tags, its system tags and its labelled input data hash | side effects and functions that take the invocation context: hit or miss, `invocation_hash` | the side-effect log (its row key and its `entry_id` column); the operator cache's `__pipeline_entry_id` column | +| **entry id** | the row's user tags, its system tags and its labelled input data hash | side-effect pods: hit or miss; functions that take the invocation context: `invocation_hash` | the side-effect log (its row key and its `entry_id` column); the operator cache's `__pipeline_entry_id` column | | **instance id** | the entry id and the source-info tokens of the row's data, in name order | a function node's lookup: is this instance stored? | the pipeline table's plain column `__pipeline_instance_id` | | **record id** | the recording node's content hash (`__node_content_hash`), the instance id and the result id (`__data_id`) | names a pipeline table row | the pipeline table's key and its column `__pipeline_record_id` | @@ -1235,9 +1236,9 @@ instance and the result it points at. "Recorded last" is read from `__recorded_at`, the recording process's UTC clock at the write: a clock set back between two writes of one instance leaves the earlier record current until a later write. -- Side effects and functions that take the invocation context are keyed by the **entry id** - only: a token never reaches their key, so a row that arrives again with new tokens is not - delivered again. +- A side-effect pod checks for completion by **entry id**, so a row that arrives again with + new tokens is already recorded. A function pod that takes the invocation context uses its + **input data hash** for result reuse and the entry id for the context's `invocation_hash`. The column names inside a preimage are part of its recipe: `__input_data_hash` enters the entry id, `__pipeline_entry_id` the instance id, `__pipeline_instance_id` and `__data_id` the record diff --git a/src/orcapod/core/cached_function_pod.py b/src/orcapod/core/cached_function_pod.py index f2f116113..b742b26f1 100644 --- a/src/orcapod/core/cached_function_pod.py +++ b/src/orcapod/core/cached_function_pod.py @@ -2,22 +2,26 @@ from __future__ import annotations +import asyncio import dataclasses import logging from datetime import datetime, timezone from collections.abc import Iterator -from typing import TYPE_CHECKING, Any +from functools import partial +from typing import TYPE_CHECKING, Any, TypeAlias +from typing_extensions import override from orcapod.core.data_function import CachedDataFunction from orcapod.core.datagrams import Datagram from orcapod.core.function_pod import ( + AsyncRowInvoker, FunctionPodStream, WrappedFunctionPod, function_zero_row_table, ) from orcapod.core.streams.view import StreamView from orcapod.system_constants import constants -from orcapod.types import ColumnConfig, Schema +from orcapod.types import ColumnConfig, ContentHash, Schema from orcapod.contexts.stored import ( StaleTables, data_context_field, @@ -39,6 +43,8 @@ module_logger = logging.getLogger(__name__) +_InFlight: TypeAlias = dict[tuple[str, ContentHash], asyncio.Future[None]] + class CachedFunctionPod(WrappedFunctionPod): """Pod-level caching wrapper that intercepts ``process_data()``. @@ -395,6 +401,54 @@ def _invoke_with_hooks( ) return out_tag, output_data + @override + def _async_row_invoker(self) -> AsyncRowInvoker: + """Share in-flight calls within one execution of this cached pod.""" + in_flight: _InFlight = {} + return partial( + self._async_invoke_with_hooks, + process=partial(self._async_process_once, in_flight), + ) + + async def _async_process_once( + self, + in_flight: _InFlight, + tag: TagProtocol, + data: DataProtocol, + *, + logger: DataExecutionLoggerProtocol | None = None, + run_id: str | None = None, + ) -> tuple[TagProtocol, DataProtocol | None]: + """Wait for an equal input's lookup, computation and store if in flight.""" + key = (data.data_context_key, data.content_hash()) + pending = in_flight.get(key) + if pending is not None: + # Cancelling a waiter must leave the shared call available to others. + await asyncio.shield(pending) + # Read back through the normal cache-hit path. Stores that discard + # results still compute each row, as in a sync run. + return await self.async_process_data( + tag, data, logger=logger, run_id=run_id + ) + + pending = asyncio.get_running_loop().create_future() + in_flight[key] = pending + try: + out_tag, result = await self.async_process_data( + tag, data, logger=logger, run_id=run_id + ) + pending.set_result(None) + return out_tag, result + except Exception as exc: + pending.set_exception(exc) + # The row re-raises either way, including when there were no waiters. + _ = pending.exception() + raise + finally: + if not pending.done(): + _ = pending.cancel() + del in_flight[key] + async def _async_invoke_with_hooks( self, tag: TagProtocol, @@ -402,33 +456,31 @@ async def _async_invoke_with_hooks( *, logger: DataExecutionLoggerProtocol | None = None, run_id: str | None = None, + process: AsyncRowInvoker | None = None, ) -> tuple[TagProtocol, DataProtocol | None]: """Async counterpart of ``_invoke_with_hooks`` for ``CachedFunctionPod``. - When ``_post_run_hooks`` is empty, delegates directly to - ``async_process_data`` with zero overhead. - Args: tag: The tag associated with the data. data: The input data to process. logger: Optional data execution logger. run_id: Pipeline run identifier forwarded to ``PostRunPayload.invocation_context``. + process: The row processor supplied by the streaming execution. Returns: A ``(tag, output_data)`` tuple. """ + process = self.async_process_data if process is None else process if not self._post_run_hooks: - return await self.async_process_data( - tag, data, logger=logger, run_id=run_id - ) + return await process(tag, data, logger=logger, run_id=run_id) started_at = datetime.now(timezone.utc) out_tag = tag output_data: DataProtocol | None = None try: - out_tag, output_data = await self.async_process_data( + out_tag, output_data = await process( tag, data, logger=logger, run_id=run_id ) if output_data is not None: diff --git a/src/orcapod/core/function_pod.py b/src/orcapod/core/function_pod.py index db62a212b..a72b895d0 100644 --- a/src/orcapod/core/function_pod.py +++ b/src/orcapod/core/function_pod.py @@ -5,7 +5,14 @@ import dataclasses import logging from abc import abstractmethod -from collections.abc import Callable, Collection, Iterable, Iterator, Sequence +from collections.abc import ( + Awaitable, + Callable, + Collection, + Iterable, + Iterator, + Sequence, +) from functools import update_wrapper, wraps from typing import TYPE_CHECKING, Any, Literal, Protocol, cast @@ -84,6 +91,19 @@ from orcapod.protocols.observability_protocols import ExecutionObserverProtocol +class AsyncRowInvoker(Protocol): + """Call a pod for one row of a streaming async execution.""" + + def __call__( + self, + tag: TagProtocol, + data: DataProtocol, + *, + logger: DataExecutionLoggerProtocol | None, + run_id: str | None, + ) -> Awaitable[tuple[TagProtocol, DataProtocol | None]]: ... + + def _executor_supports_concurrent( data_function: DataFunctionProtocol, ) -> bool: @@ -653,6 +673,10 @@ def handle_input_streams(self, *streams: StreamProtocol) -> StreamProtocol: return joined_stream return streams[0] + def _async_row_invoker(self) -> AsyncRowInvoker: + """Create the per-row invoker for one streaming async execution.""" + return self._async_invoke_with_hooks + async def async_execute( self, inputs: Sequence[ReadableChannel[tuple[TagProtocol, DataProtocol]]], @@ -694,6 +718,7 @@ async def async_execute( max_concurrency = resolve_concurrency(self.pod_config, pipeline_config) obs = observer if observer is not None else NoOpObserver() pod_label = self.label + invoke = self._async_row_invoker() sem = ( asyncio.Semaphore(max_concurrency) @@ -705,7 +730,7 @@ async def process_one(tag: TagProtocol, data: DataProtocol) -> None: obs.on_data_start(pod_label, tag, data) pkt_logger = obs.create_data_logger(tag, data) try: - out_tag, result_data = await self._async_invoke_with_hooks( + out_tag, result_data = await invoke( tag, data, logger=pkt_logger, run_id=run_id ) except OrcapodDatabaseError as exc: diff --git a/src/orcapod/pipeline/run_summary.py b/src/orcapod/pipeline/run_summary.py index 638334871..56e37cb2f 100644 --- a/src/orcapod/pipeline/run_summary.py +++ b/src/orcapod/pipeline/run_summary.py @@ -28,8 +28,8 @@ _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." + "Computed and from-store counts reflect this run. Scheduling can affect which " + "node computes a shared result." ) @@ -75,9 +75,9 @@ 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. + Counts attribute work to the nodes that actually did it. Rows within one node + share a computation for equal inputs. In an async run, scheduling can affect + which nodes compute or reuse a result from a shared result table. Attributes: job_name: The job's name. diff --git a/tests/test_pipeline/test_function_pod_concurrency.py b/tests/test_pipeline/test_function_pod_concurrency.py index ebcfa136f..53d58a289 100644 --- a/tests/test_pipeline/test_function_pod_concurrency.py +++ b/tests/test_pipeline/test_function_pod_concurrency.py @@ -6,15 +6,20 @@ import json import os from itertools import product -from typing import TYPE_CHECKING, cast +from typing import TYPE_CHECKING, cast, final import pytest +from typing_extensions import override from orcapod import PipelineJob from orcapod.channels import Channel from orcapod.core.function_pod import FunctionPod from orcapod.core.nodes.function_node import FunctionJobNode from orcapod.databases import InMemoryArrowDatabase +from orcapod.errors import RowFailuresWarning +from orcapod.pipeline import AsyncPipelineOrchestrator +from orcapod.pipeline.observer import NoOpObserver +from orcapod.side_effects import InvocationContext from orcapod.sources import DictSource from orcapod.system_constants import constants from orcapod.types import ( @@ -28,11 +33,220 @@ import pyarrow as pa + from orcapod.pipeline.run_summary import RunSummary from orcapod.protocols.core_protocols import DataProtocol, TagProtocol ROW_COUNT = 24 +@final +class _RowStarts(NoOpObserver): + """Release a function only after every row has entered the node.""" + + def __init__(self, expected: int) -> None: + self.expected = expected + self.started: list[int] = [] + self.crashed: list[int] = [] + self.ready = asyncio.Event() + + @override + def on_data_start( + self, node_label: str, tag: TagProtocol, data: DataProtocol + ) -> None: + if node_label == "add": + self.started.append(cast(int, tag.as_dict()["row"])) + if len(self.started) == self.expected: + self.ready.set() + + @override + def on_data_crash( + self, node_label: str, tag: TagProtocol, data: DataProtocol, error: Exception + ) -> None: + if node_label == "add": + self.crashed.append(cast(int, tag.as_dict()["row"])) + + +def _repeated_job( + pod: FunctionPod, database: InMemoryArrowDatabase, *, reverse: bool, shift: int = 0 +) -> PipelineJob: + """Build four rows with distinct tags and two distinct pairs of input values.""" + rows = [ + {"group": f"g{i % 2}", "row": i + shift, "x": x, "y": 10 * x} + for i, x in enumerate((1, 1, 1, 2)) + ] + tag_columns = ["group", "row"] + if reverse: + rows = [dict(reversed(list(row.items()))) for row in rows] + tag_columns.reverse() + job = PipelineJob(name="repeated", database=database) + with job: + source = DictSource( + data=rows, tag_columns=tag_columns, tag_only_columns=True, source_id="rows" + ) + _ = pod(source, label="add") + return job + + +@pytest.mark.parametrize("reverse", [False, True]) +@pytest.mark.parametrize("with_ctx", [False, True], ids=["plain", "context"]) +@pytest.mark.parametrize("limit", [1, None], ids=["serial", "unbounded"]) +def test_equal_inputs_call_once_and_keep_every_row( + limit: int | None, with_ctx: bool, reverse: bool +) -> None: + """Count actual invocations and reuse across different tags and across runs.""" + observer = _RowStarts(expected=4) + calls: list[int] = [] + gate = False + + async def add(x: int, y: int) -> int: + calls.append(x) + if gate: + _ = await observer.ready.wait() + return x + y + + async def with_context(x: int, y: int, ctx: InvocationContext) -> int: + assert ctx.pipeline_run_id is not None + return await add(x, y) + + pod = FunctionPod.from_fn( + with_context if with_ctx else add, + output_keys="total", + ctx_arg_name="ctx" if with_ctx else None, + pod_config=PodConfig(max_concurrency=limit), + ) + + def check(job: PipelineJob, shift: int) -> None: + node = cast(FunctionJobNode, job.nodes["add"]) + assert node.as_table().sort_by("row").to_pylist() == [ + {"group": f"g{i % 2}", "row": i + shift, "total": 11 * x} + for i, x in enumerate((1, 1, 1, 2)) + ] + + async def run(job: PipelineJob) -> RunSummary: + async with asyncio.timeout(10): + return await job.run_async(observer=observer) + + sync_job = _repeated_job(pod, InMemoryArrowDatabase(), reverse=reverse) + sync_summary = sync_job.run() + assert (sync_summary.nodes["add"].computed, sync_summary.nodes["add"].reused) == ( + 2, + 2, + ) + assert calls == [1, 2] + check(sync_job, 0) + + calls.clear() + gate = limit is None + database = InMemoryArrowDatabase() + async_job = _repeated_job(pod, database, reverse=reverse) + summary = asyncio.run(run(async_job)) + assert calls == [1, 2] + assert (summary.nodes["add"].computed, summary.nodes["add"].reused) == (2, 2) + check(async_job, 0) + + calls.clear() + # New tags have no pipeline records, so this run has to use the result table. + replay = _repeated_job(pod, database, reverse=reverse, shift=10) + summary = asyncio.run(run(replay)) + assert calls == [] + assert (summary.nodes["add"].computed, summary.nodes["add"].reused) == (0, 4) + check(replay, 10) + replay = _repeated_job(pod, database, reverse=reverse, shift=20) + assert replay.run().nodes["add"].reused == 4 + assert calls == [] + check(replay, 20) + + +@pytest.mark.parametrize("limit", [1, None], ids=["serial", "unbounded"]) +def test_first_call_failure_is_reported_once_for_each_waiting_row( + limit: int | None, +) -> None: + """All waiters fail under the row policy, and a later run retries the input.""" + observer = _RowStarts(expected=4) + calls: list[int] = [] + fail = True + + async def add(x: int, y: int, ctx: InvocationContext) -> int: + assert ctx.pipeline_run_id is not None + calls.append(x) + if fail and x == 1: + if limit is None: + _ = await observer.ready.wait() + raise ValueError("cannot add these values") + return x + y + + pod = FunctionPod.from_fn( + add, + output_keys="total", + ctx_arg_name="ctx", + pod_config=PodConfig(max_concurrency=limit), + ) + job = _repeated_job(pod, InMemoryArrowDatabase(), reverse=False) + node = cast(FunctionJobNode, job.nodes["add"]) + + async def run() -> None: + async with asyncio.timeout(10): + with pytest.warns(RowFailuresWarning, match="3 of 4 rows failed"): + summary = await job.run_async(observer=observer) + assert summary.nodes["add"].failed == 3 + assert sorted(observer.crashed) == [0, 1, 2] + assert calls == ([1, 2] if limit is None else [1, 1, 1, 2]) + assert node.as_table().to_pylist() == [ + {"group": "g1", "row": 3, "total": 22} + ] + + asyncio.run(run()) + fail = False + calls.clear() + summary = asyncio.run(job.run_async()) + assert calls == [1] + assert summary.nodes["add"].failed == 0 + assert node.as_table().num_rows == 4 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("fail_fast", [False, True], ids=["cancel", "fail-fast"]) +async def test_stopping_an_async_run_with_waiters_allows_retry(fail_fast: bool) -> None: + """Task group cancellation releases waiting rows and the next run starts fresh.""" + observer = _RowStarts(expected=4) + blocker = asyncio.Event() + calls: list[int] = [] + retry = False + + async def add(x: int, y: int) -> int: + calls.append(x) + if not retry: + _ = await observer.ready.wait() + if x == 2 and fail_fast: + raise ValueError("stop this run") + _ = await blocker.wait() + return x + y + + pod = FunctionPod.from_fn( + add, output_keys="total", pod_config=PodConfig(max_concurrency=None) + ) + job = _repeated_job(pod, InMemoryArrowDatabase(), reverse=False) + async with asyncio.timeout(10): + if fail_fast: + with pytest.raises(ValueError, match="stop this run"): + _ = await job.run_async( + orchestrator=AsyncPipelineOrchestrator(error_policy="fail_fast"), + observer=observer, + ) + else: + task = asyncio.create_task(job.run_async(observer=observer)) + _ = await observer.ready.wait() + _ = task.cancel() + with pytest.raises(asyncio.CancelledError): + _ = await task + assert calls == [1, 2] + retry = True + calls.clear() + summary = await job.run_async() + assert calls == [1, 2] + assert summary.nodes["add"].rows == 4 + + def _source(reverse: bool, *, tag_only: bool | list[str] = True) -> DictSource: """Build rows with the requested tag roles in either layout.""" rows = [ 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 7084498a0..6274e7810 100644 --- a/tests/test_pipeline/test_job_node_rows_after_run.py +++ b/tests/test_pipeline/test_job_node_rows_after_run.py @@ -18,11 +18,13 @@ from orcapod import PipelineJob, function_pod from orcapod.core.data_function import PythonDataFunction +from orcapod.core.function_pod import FunctionPod from orcapod.databases import InMemoryArrowDatabase from orcapod.errors import OrcapodDatabaseWriteError from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator from orcapod.core.streams import ViewStatus from orcapod.sources import DictSource +from orcapod.types import PodConfig @function_pod(output_keys="y") @@ -363,7 +365,6 @@ def _flaky_pod() -> Any: """Return a pod computing ``x + 1`` whose first call for ``x == 5`` raises.""" calls: list[int] = [] - @function_pod(output_keys="y") def flaky_inc(x: int) -> int: """Return ``x + 1``; raise on the first call for ``x == 5``.""" calls.append(x) @@ -371,7 +372,9 @@ def flaky_inc(x: int) -> int: raise ValueError("transient failure") return x + 1 - return flaky_inc.pod + return FunctionPod.from_fn( + flaky_inc, output_keys="y", pod_config=PodConfig(max_concurrency=1) + ) @staticmethod def _run_async(node: Any) -> list[tuple[int, int]]: @@ -428,8 +431,8 @@ def test_sync_one_of_two_equal_inputs_fails(self) -> None: assert received == [(0, 6), (2, 8)] assert self._held(node) == received - def test_async_one_of_two_equal_inputs_fails(self) -> None: - """Async: an equal input that failed is not held; the one that succeeded is.""" + def test_async_retries_a_failed_input_when_no_call_is_in_flight(self) -> None: + """With serial dispatch, the second occurrence retries the failed input.""" node = self._node(self._flaky_pod()) received = self._run_async(node) assert received == [(0, 6), (2, 8)] diff --git a/tests/test_pipeline/test_provenance_review.py b/tests/test_pipeline/test_provenance_review.py index 72ae41561..c22a08ef7 100644 --- a/tests/test_pipeline/test_provenance_review.py +++ b/tests/test_pipeline/test_provenance_review.py @@ -2185,8 +2185,8 @@ def _marks(job: PipelineJob) -> dict[str, dict[str, str]]: def _run_after_a1(database: Any, mode: str) -> PipelineJob: """A first run stores a1's scores; the job over every trial then runs in ``mode``, - so a2 trial 1 (a1 trial 1's input) reuses a stored result on either orchestrator - (the async one runs equal inputs of one run concurrently: both compute).""" + so a2 trial 1 (a1 trial 1's input) reuses an earlier run's result on either + orchestrator.""" _ = _trials_job(database, TRIALS[:2]).run() job = _trials_job(database) run(job, mode) @@ -2202,9 +2202,8 @@ def test_marks_of_equal_inputs_in_one_async_run_follow_their_records() -> None: """In one async run, a1 trial 1 and a2 trial 1 have equal inputs. Which of them computes and which reuses follows arrival order (ITL-1437), so it is not asserted. What is guaranteed: each row's mark is what its own stored record says - (FunctionRun.computed_here), at least one of them computed (both may: async - execution can record the two copies separately, ITL-1433), and a trace of several - rows merges their marks per node.""" + (FunctionRun.computed_here), one computed and the other reused, and a trace of + several rows merges their marks per node.""" job = _trials_job(InMemoryArrowDatabase()) run(job, "async") scores = job.nodes["scores"] @@ -2230,7 +2229,7 @@ def mark(computed: set[bool]) -> str: assert run_.computed_here is stored[(animal, 1)] assert dict(trace.highlight().marks) == {"scores": mark({stored[(animal, 1)]})} runs[animal] = run_ - assert True in {runs["a1"].computed_here, runs["a2"].computed_here} + assert {runs["a1"].computed_here, runs["a2"].computed_here} == {True, False} # The union over both rows merges their marks. both = scores.trace({"trial": 1}, "score") assert both.matched == 2 diff --git a/tests/test_pipeline/test_result_reuse_itl_1503.py b/tests/test_pipeline/test_result_reuse_itl_1503.py index 6dd80292e..4714891e2 100644 --- a/tests/test_pipeline/test_result_reuse_itl_1503.py +++ b/tests/test_pipeline/test_result_reuse_itl_1503.py @@ -26,10 +26,11 @@ import asyncio from pathlib import Path -from typing import Any +from typing import Any, final import pyarrow as pa import pytest +from typing_extensions import override from orcapod.channels import Channel from orcapod.core.cached_function_pod import CachedFunctionPod @@ -38,6 +39,8 @@ from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.databases import DeltaTableDatabase, InMemoryArrowDatabase from orcapod.errors import OrcapodDatabaseReadError, TypeIdentityError +from orcapod.pipeline.observer import NoOpObserver +from orcapod.protocols.core_protocols import DataProtocol, TagProtocol from orcapod.system_constants import constants from orcapod.types import NodeConfig, PodConfig @@ -117,7 +120,11 @@ def scale(value: int, weight: float) -> tuple[int, float]: self.pod = FunctionPod.from_fn(scale, output_keys=["doubled", "heavier"]) -async def _run_async(node: FunctionJobNode, source: ArrowTableStream) -> list[Any]: +async def _run_async( + node: FunctionJobNode, + source: ArrowTableStream, + observer: NoOpObserver | None = None, +) -> list[Any]: input_ch: Channel[Any] = Channel(buffer_size=32) output_ch: Channel[Any] = Channel(buffer_size=32) @@ -126,7 +133,9 @@ async def feed() -> None: await input_ch.writer.send(pair) await input_ch.writer.close() - await asyncio.gather(feed(), node.async_execute(input_ch.reader, output_ch.writer)) + await asyncio.gather( + feed(), node.async_execute(input_ch.reader, output_ch.writer, observer=observer) + ) return await output_ch.reader.collect() @@ -538,36 +547,61 @@ async def scale(value: int, weight: float) -> tuple[int, float]: ) -@pytest.mark.parametrize("release_order", [[1, 2, 3], [3, 1, 2], [2, 3, 1]]) +@final +class _RowStarts(NoOpObserver): + """Signal when a node starts handling the expected number of rows.""" + + def __init__(self, expected: int) -> None: + self.remaining = expected + self.ready = asyncio.Event() + + @override + def on_data_start( + self, node_label: str, tag: TagProtocol, data: DataProtocol + ) -> None: + self.remaining -= 1 + if self.remaining == 0: + self.ready.set() + + @pytest.mark.parametrize("ephemeral_mode", [False, True], ids=["persistent", "eph"]) -def test_equal_inputs_computed_together_store_one_result( - release_order: list[int], ephemeral_mode: bool -) -> None: +def test_equal_inputs_started_together_store_one_result(ephemeral_mode: bool) -> None: """Three rows of one input (two of one instance, one of another) in flight - together: every call runs, ONE result is stored, every row delivers it, the + together: one call runs, one result is stored, every row delivers it, the pipeline records name it, and a read gives what was delivered.""" - gated = _Gated(3, release_order) + observer = _RowStarts(3) + calls: list[int] = [] + + async def scale(value: int, weight: float) -> tuple[int, float]: + calls.append(value) + _ = await asyncio.wait_for(observer.ready.wait(), timeout=5) + return value + 1, weight + + pod = FunctionPod.from_fn( + scale, + output_keys=["doubled", "heavier"], + pod_config=PodConfig(max_concurrency=3), + ) source = _repeated_input(["a", "a", "b"], 10) pipeline, persistent, ephemeral = (InMemoryArrowDatabase() for _ in range(3)) node = FunctionJobNode( - gated.pod, source, pipeline_database=pipeline, result_database=persistent + pod, source, pipeline_database=pipeline, result_database=persistent ) if ephemeral_mode: node.node_config = NodeConfig(is_result_ephemeral=True) node.set_ephemeral_database(ephemeral) assert len({node.compute_instance_id(*pair) for pair in source.iter_data()}) == 2 - rows = asyncio.run(_run_async(node, source)) + rows = asyncio.run(_run_async(node, source, observer)) - assert gated.calls == 3 + assert calls == [10] written, untouched = ( (ephemeral, persistent) if ephemeral_mode else (persistent, ephemeral) ) stored_ids = _result_ids(written) assert len(stored_ids) == 1 assert _result_ids(untouched) == [] - # The first call to return made the stored result. - expected = (stored_ids[0], 10 + release_order[0], 1.5) + expected = (stored_ids[0], 11, 1.5) def as_delivered(pairs: list[Any]) -> list[tuple[Any, ...]]: return [ @@ -710,15 +744,16 @@ def test_async_readback_is_what_each_occurrence_delivered( result id, and a read gives that id for both. ``after``: the first occurrence was delivered before the result is published. - ``during``: it is still computing, so both compute and one result is kept. + ``during``: it is still computing, so the second occurrence waits for its result. """ release = asyncio.Event() - started = [asyncio.Event(), asyncio.Event()] + started = asyncio.Event() + observer = _RowStarts(2) calls: list[int] = [] async def scale(value: int, weight: float) -> tuple[int, float]: calls.append(value) - started[len(calls) - 1].set() + started.set() if first_in_flight: _ = await asyncio.wait_for(release.wait(), timeout=5) return value * 2, weight * 2 @@ -746,18 +781,20 @@ async def go() -> list[Any]: input_ch: Channel[Any] = Channel(buffer_size=3) output_ch: Channel[Any] = Channel(buffer_size=3) outputs = output_ch.reader.__aiter__() - run = asyncio.create_task(node.async_execute(input_ch.reader, output_ch.writer)) + run = asyncio.create_task( + node.async_execute(input_ch.reader, output_ch.writer, observer=observer) + ) await input_ch.writer.send(row) delivered = [] if first_in_flight: - _ = await asyncio.wait_for(started[0].wait(), timeout=5) + _ = await asyncio.wait_for(started.wait(), timeout=5) else: delivered.append(await anext(outputs)) published.append(_seed(persistent, seeding, source, {"a"})["a"]) await input_ch.writer.send(row) await input_ch.writer.close() if first_in_flight: - _ = await asyncio.wait_for(started[1].wait(), timeout=5) + _ = await asyncio.wait_for(observer.ready.wait(), timeout=5) release.set() delivered.append(await anext(outputs)) delivered.append(await anext(outputs)) @@ -765,7 +802,7 @@ async def go() -> list[Any]: return delivered delivered = asyncio.run(go()) - assert calls == ([2, 2] if first_in_flight else [2]) + assert calls == [2] (result_id,) = set(_ids(delivered)) assert result_id != published[0] assert _result_ids(ephemeral) == [result_id] From 791d3fa28ad7806ee6e6c632c236ac7cc45c4109 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 13:48:49 -0800 Subject: [PATCH 2/3] fix(function-pod): preserve outcomes when sharing async calls --- docs/concepts/function-pods.md | 7 +- docs/concepts/pipeline-job.md | 9 +- docs/dev/design_issues/NOISSUE-FN1.md | 3 +- src/orcapod/core/cached_function_pod.py | 78 ++++-- src/orcapod/core/result_cache.py | 19 +- .../test_function_pod_concurrency.py | 238 +++++++++++++++++- 6 files changed, 308 insertions(+), 46 deletions(-) diff --git a/docs/concepts/function-pods.md b/docs/concepts/function-pods.md index ef3e8396c..35dde578a 100644 --- a/docs/concepts/function-pods.md +++ b/docs/concepts/function-pods.md @@ -656,9 +656,10 @@ of a notebook cell it is shown as a table; `print` shows the same as text. The j `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. -Within a function node, each distinct input data hash needs at most one successful -computation. In an async run, rows that arrive during that computation wait for its -result. Different nodes can share a result table, so scheduling can change which nodes +In an async run, equal inputs arriving during a call wait to reuse its result. If the +call fails or is cancelled, each waiting row can make its own attempt. With a discard +result store, the async node keeps successful results in memory for the run. +Different nodes can share a result table, so scheduling can change which nodes compute a result or reuse it. Running the same job again computes nothing new, and the summary says so: diff --git a/docs/concepts/pipeline-job.md b/docs/concepts/pipeline-job.md index 1ffbf5e83..9a511fdda 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -223,10 +223,11 @@ recreated at the same path that happens to have the same version number: a handl had loaded the old table keeps reading it (ITL-1413). Open a new database object after replacing a table. -A function that takes the invocation context (`ctx_arg`) performs an external action once -per distinct input data hash in a function node, on both the sync and async paths. Rows -with equal input data reuse the same stored result even when their tags differ. Jobs that -share a result database share that record too. To perform an action for each row, use a +A function that takes the invocation context (`ctx_arg`) can perform an external action. +Rows with equal input data reuse a successful result even when their tags differ. In an +async run, overlapping rows share a successful call within one node. Jobs that share a +result database share stored results. A later run can call the function again if its +result was discarded or deleted. To perform an action for each row, use a [`SideEffectPod`](function-pods.md#side-effects-in-a-job-delivered-by-a-run-never-by-a-read). ### Result commit ordering diff --git a/docs/dev/design_issues/NOISSUE-FN1.md b/docs/dev/design_issues/NOISSUE-FN1.md index e353d3d87..b7cc3f9fe 100644 --- a/docs/dev/design_issues/NOISSUE-FN1.md +++ b/docs/dev/design_issues/NOISSUE-FN1.md @@ -18,4 +18,5 @@ Phase 1 (replay cached results from DB) remains unchanged. Concurrency is contro **Follow-up (ITL-1101):** Phase 2 shares a pending call by input data hash within one cached function node execution. Equal rows keep their own tags and pipeline records. -Distinct inputs still compute concurrently. The existing result store serves later rows. +Distinct inputs still compute concurrently. Failed or cancelled calls leave waiting rows +free to run their own attempts. A discard result store uses an in-run memo for later rows. diff --git a/src/orcapod/core/cached_function_pod.py b/src/orcapod/core/cached_function_pod.py index b742b26f1..84716ba70 100644 --- a/src/orcapod/core/cached_function_pod.py +++ b/src/orcapod/core/cached_function_pod.py @@ -43,7 +43,9 @@ module_logger = logging.getLogger(__name__) -_InFlight: TypeAlias = dict[tuple[str, ContentHash], asyncio.Future[None]] +_InFlight: TypeAlias = dict[ + tuple[str, ContentHash], asyncio.Future[DataProtocol | None] +] class CachedFunctionPod(WrappedFunctionPod): @@ -288,12 +290,19 @@ async def async_process_data( A ``(tag, output_data)`` tuple; output_data is ``None`` if the inner function filters the data out. """ - cached = self._cache.lookup(data, data_context_key=self.data_context_key) - if cached is not None: - module_logger.info("Pod-level cache hit") - cached = cached.with_meta_columns(**{self.RESULT_COMPUTED_FLAG: False}) - return tag, cached + return await self._async_process_once( + None, tag, data, logger=logger, run_id=run_id + ) + async def _async_compute_and_store( + self, + tag: TagProtocol, + data: DataProtocol, + *, + logger: DataExecutionLoggerProtocol | None, + run_id: str | None, + ) -> tuple[TagProtocol, DataProtocol | None]: + """Run one invocation after a cache miss and conditionally store its result.""" tag, output = await self._function_pod.async_process_data( tag, data, logger=logger, run_id=run_id ) @@ -412,42 +421,57 @@ def _async_row_invoker(self) -> AsyncRowInvoker: async def _async_process_once( self, - in_flight: _InFlight, + in_flight: _InFlight | None, tag: TagProtocol, data: DataProtocol, *, logger: DataExecutionLoggerProtocol | None = None, run_id: str | None = None, ) -> tuple[TagProtocol, DataProtocol | None]: - """Wait for an equal input's lookup, computation and store if in flight.""" + """Reuse successful work and leave failed invocations local to their rows.""" + cached = self.lookup_cached_data(data) + if cached is not None: + module_logger.info("Pod-level cache hit") + return tag, cached + if in_flight is None: + return await self._async_compute_and_store( + tag, data, logger=logger, run_id=run_id + ) + key = (data.data_context_key, data.content_hash()) + retains_results = self.result_database.stores_records pending = in_flight.get(key) if pending is not None: - # Cancelling a waiter must leave the shared call available to others. - await asyncio.shield(pending) - # Read back through the normal cache-hit path. Stores that discard - # results still compute each row, as in a sync run. - return await self.async_process_data( - tag, data, logger=logger, run_id=run_id - ) + result = await asyncio.shield(pending) + if result is not None: + if retains_results: + cached = self._cache.lookup( + data, + data_context_key=self.data_context_key, + result_id=result.datagram_uuid.bytes, + ) + if cached is not None: + return tag, cached + return tag, result.with_meta_columns( + **{self.RESULT_COMPUTED_FLAG: False} + ) - pending = asyncio.get_running_loop().create_future() - in_flight[key] = pending + # An unsuccessful leader leaves each waiting row at its original cache miss. + completion = asyncio.get_running_loop().create_future() + if pending is None: + in_flight[key] = completion + result = None try: - out_tag, result = await self.async_process_data( + out_tag, result = await self._async_compute_and_store( tag, data, logger=logger, run_id=run_id ) - pending.set_result(None) return out_tag, result - except Exception as exc: - pending.set_exception(exc) - # The row re-raises either way, including when there were no waiters. - _ = pending.exception() - raise finally: - if not pending.done(): - _ = pending.cancel() - del in_flight[key] + completion.set_result(result) + if pending is None and (retains_results or result is None): + del in_flight[key] + elif result is not None and not retains_results: + in_flight.setdefault(key, completion) async def _async_invoke_with_hooks( self, diff --git a/src/orcapod/core/result_cache.py b/src/orcapod/core/result_cache.py index e341983bf..0429351c8 100644 --- a/src/orcapod/core/result_cache.py +++ b/src/orcapod/core/result_cache.py @@ -13,6 +13,7 @@ from typing import TYPE_CHECKING, Any import pyarrow as pa +import pyarrow.compute as pc from orcapod.core.data_function_types import StoredColumn from orcapod.errors import ( @@ -315,6 +316,7 @@ def lookup( additional_constraints: dict[str, Any] | None = None, *, data_context_key: str, + result_id: bytes | None = None, ) -> DataProtocol | None: """Look up a cached output data for *input_data*. @@ -336,6 +338,7 @@ def lookup( for ``function_name``). data_context_key: Key of the caller's data context. Only rows written under it are matched, and the returned data carries it. + result_id: If given, read only this previously selected result. Returns: The cached output data with ``RESULT_COMPUTED_FLAG: False`` @@ -361,11 +364,17 @@ def lookup( constraints.update(additional_constraints) constraints[constants.DATA_CONTEXT_COL] = data_context_key - result_table = self._result_database.get_records_with_column_value( - self._versioned_record_path, - constraints, - record_id_column=RECORD_ID_COL, - ) + if result_id is None: + result_table = self._result_database.get_records_with_column_value( + self._versioned_record_path, constraints, record_id_column=RECORD_ID_COL + ) + else: + result_table = self._result_database.get_record_by_id( + self._versioned_record_path, result_id, record_id_column=RECORD_ID_COL + ) + if result_table is not None: + for column, value in constraints.items(): + result_table = result_table.filter(pc.field(column) == value) if result_table is None or result_table.num_rows == 0: return None diff --git a/tests/test_pipeline/test_function_pod_concurrency.py b/tests/test_pipeline/test_function_pod_concurrency.py index 53d58a289..8f07ea8b2 100644 --- a/tests/test_pipeline/test_function_pod_concurrency.py +++ b/tests/test_pipeline/test_function_pod_concurrency.py @@ -13,9 +13,10 @@ from orcapod import PipelineJob from orcapod.channels import Channel +from orcapod.core.data_function import CachedDataFunction from orcapod.core.function_pod import FunctionPod from orcapod.core.nodes.function_node import FunctionJobNode -from orcapod.databases import InMemoryArrowDatabase +from orcapod.databases import InMemoryArrowDatabase, NoOpArrowDatabase from orcapod.errors import RowFailuresWarning from orcapod.pipeline import AsyncPipelineOrchestrator from orcapod.pipeline.observer import NoOpObserver @@ -35,6 +36,7 @@ from orcapod.pipeline.run_summary import RunSummary from orcapod.protocols.core_protocols import DataProtocol, TagProtocol + from orcapod.protocols.database_protocols import ArrowDatabaseProtocol ROW_COUNT = 24 @@ -67,7 +69,12 @@ def on_data_crash( def _repeated_job( - pod: FunctionPod, database: InMemoryArrowDatabase, *, reverse: bool, shift: int = 0 + pod: FunctionPod, + database: InMemoryArrowDatabase, + *, + reverse: bool, + shift: int = 0, + result_database: ArrowDatabaseProtocol | None = None, ) -> PipelineJob: """Build four rows with distinct tags and two distinct pairs of input values.""" rows = [ @@ -78,7 +85,9 @@ def _repeated_job( if reverse: rows = [dict(reversed(list(row.items()))) for row in rows] tag_columns.reverse() - job = PipelineJob(name="repeated", database=database) + job = PipelineJob( + name="repeated", database=database, result_database=result_database + ) with job: source = DictSource( data=rows, tag_columns=tag_columns, tag_only_columns=True, source_id="rows" @@ -158,10 +167,10 @@ async def run(job: PipelineJob) -> RunSummary: @pytest.mark.parametrize("limit", [1, None], ids=["serial", "unbounded"]) -def test_first_call_failure_is_reported_once_for_each_waiting_row( +def test_permanent_failure_is_reported_for_each_waiting_row( limit: int | None, ) -> None: - """All waiters fail under the row policy, and a later run retries the input.""" + """Every equal row gets its own failed attempt, and a later run can retry.""" observer = _RowStarts(expected=4) calls: list[int] = [] fail = True @@ -190,7 +199,7 @@ async def run() -> None: summary = await job.run_async(observer=observer) assert summary.nodes["add"].failed == 3 assert sorted(observer.crashed) == [0, 1, 2] - assert calls == ([1, 2] if limit is None else [1, 1, 1, 2]) + assert sorted(calls) == [1, 1, 1, 2] assert node.as_table().to_pylist() == [ {"group": "g1", "row": 3, "total": 22} ] @@ -204,6 +213,223 @@ async def run() -> None: assert node.as_table().num_rows == 4 +@pytest.mark.parametrize("failure", [ValueError, TimeoutError, asyncio.CancelledError]) +def test_only_the_invocation_that_fails_loses_its_row( + failure: type[Exception] | type[asyncio.CancelledError], +) -> None: + """Equal rows retain their own attempts after an error, timeout or cancellation.""" + calls: list[int] = [] + observer = _RowStarts(expected=4) + block = False + + async def add(x: int, y: int) -> int: + calls.append(x) + if x == 1 and calls.count(1) == 1: + if block: + _ = await observer.ready.wait() + if failure is TimeoutError: + async with asyncio.timeout(0): + _ = await asyncio.Event().wait() + raise failure() + return x + y + + pod = FunctionPod.from_fn( + add, output_keys="total", pod_config=PodConfig(max_concurrency=None) + ) + + def check(job: PipelineJob, summary: RunSummary, failures: int) -> None: + node = cast(FunctionJobNode, job.nodes["add"]) + assert node.as_table().sort_by("row").to_pylist() == [ + {"group": "g1", "row": 1, "total": 11}, + {"group": "g0", "row": 2, "total": 11}, + {"group": "g1", "row": 3, "total": 22}, + ] + stored = node.get_all_records(all_info=True) + assert stored is not None + assert stored.sort_by("row")["row"].to_pylist() == [1, 2, 3] + stats = summary.nodes["add"] + assert (stats.failed, stats.computed, stats.reused) == (failures, 2, 1) + + sync_job = _repeated_job(pod, InMemoryArrowDatabase(), reverse=False) + cancelled = failure is asyncio.CancelledError + if cancelled: + with pytest.raises(asyncio.CancelledError): + _ = sync_job.run() + assert calls == [1] + else: + with pytest.warns(RowFailuresWarning, match="1 of 4 rows failed"): + summary = sync_job.run() + assert calls == [1, 1, 2] + check(sync_job, summary, 1) + + calls.clear() + block = True + job = _repeated_job(pod, InMemoryArrowDatabase(), reverse=False) + + async def run() -> RunSummary: + async with asyncio.timeout(10): + if cancelled: + return await job.run_async(observer=observer) + with pytest.warns(RowFailuresWarning, match="1 of 4 rows failed"): + return await job.run_async(observer=observer) + + summary = asyncio.run(run()) + assert sorted(calls) == [1, 1, 1, 2] + assert observer.crashed == ([] if cancelled else [0]) + check(job, summary, int(not cancelled)) + + +@pytest.mark.parametrize("limit", [1, None], ids=["serial", "unbounded"]) +def test_discard_result_store_reuses_successes_within_each_async_run( + limit: int | None, +) -> None: + """Equal inputs share a successful call even when the result store discards it.""" + calls: list[int] = [] + observer = _RowStarts(expected=4) + block = False + + async def add(x: int, y: int) -> int: + calls.append(x) + if block: + _ = await observer.ready.wait() + return x + y + + pod = FunctionPod.from_fn( + add, output_keys="total", pod_config=PodConfig(max_concurrency=limit) + ) + discarded = NoOpArrowDatabase() + sync_job = _repeated_job( + pod, InMemoryArrowDatabase(), reverse=False, result_database=discarded + ) + assert sync_job.run().nodes["add"].computed == 4 + assert calls == [1, 1, 1, 2] + expected = sync_job.nodes["add"].as_table().sort_by("row") + assert expected.num_rows == 4 + + async def run(job: PipelineJob) -> RunSummary: + async with asyncio.timeout(10): + return await job.run_async(observer=observer) + + block = limit is None + pipeline_db = InMemoryArrowDatabase() + for shift in (0, 10): + calls.clear() + observer = _RowStarts(expected=4) + job = _repeated_job( + pod, pipeline_db, reverse=False, result_database=discarded, shift=shift + ) + summary = asyncio.run(run(job)) + assert calls == [1, 2] + rows = job.nodes["add"].as_table().sort_by("row") + assert rows.select(["group", "total"]).equals( + expected.select(["group", "total"]) + ) + assert rows["row"].to_pylist() == list(range(shift, shift + 4)) + assert (summary.nodes["add"].computed, summary.nodes["add"].reused) == (2, 2) + (path,) = pipeline_db.list_table_paths() + records = pipeline_db.get_all_records(path) + assert records is not None + assert records.sort_by("row")["row"].to_pylist() == ( + list(range(4)) + (list(range(10, 14)) if shift else []) + ) + assert discarded.list_table_paths() == [] + + +def test_waiters_keep_the_selected_result_in_a_shared_result_store() -> None: + """A later standalone write cannot change an already waiting row's result.""" + observer = _RowStarts(expected=4) + calls: list[int] = [] + standalone_started = asyncio.Event() + release = asyncio.Event() + concurrent = False + + async def add(x: int, y: int) -> int: + calls.append(x) + if concurrent: + task = asyncio.current_task() + assert task is not None + if task.get_name() == "standalone": + standalone_started.set() + _ = await release.wait() + return x + y + + pod = FunctionPod.from_fn( + add, output_keys="total", pod_config=PodConfig(max_concurrency=None) + ) + + def make_job() -> tuple[ + PipelineJob, InMemoryArrowDatabase, InMemoryArrowDatabase, CachedDataFunction + ]: + result_db = InMemoryArrowDatabase() + pipeline_db = InMemoryArrowDatabase() + job = _repeated_job(pod, pipeline_db, reverse=False, result_database=result_db) + return ( + job, + pipeline_db, + result_db, + CachedDataFunction(pod.data_function, result_database=result_db), + ) + + def check( + job: PipelineJob, + pipeline_db: InMemoryArrowDatabase, + result_db: InMemoryArrowDatabase, + standalone_id: bytes, + ) -> None: + node = cast(FunctionJobNode, job.nodes["add"]) + (pipeline_path,) = pipeline_db.list_table_paths() + stored = pipeline_db.get_all_records( + pipeline_path, record_id_column="storage_key" + ) + assert stored is not None + records = stored.sort_by("row").to_pylist() + delivered = {tag.as_dict()["row"]: out for tag, out in node.iter_data()} + assert [row["row"] for row in records] == [0, 1, 2, 3] + assert [row["__computed"] for row in records] == [True, False, False, True] + result_ids = [row[constants.DATA_RECORD_ID] for row in records] + assert result_ids[0] == result_ids[1] == result_ids[2] != standalone_id + assert len({row["storage_key"] for row in records}) == 4 + for i, result_id in enumerate(result_ids): + out = delivered[i] + assert out.as_dict() == {"total": 11 if i < 3 else 22} + assert out.datagram_uuid.bytes == result_id + assert out.datagram_uuid.hex in str(out.source_info_table().to_pylist()) + first_tokens = delivered[0].source_info_table() + assert first_tokens.equals(delivered[1].source_info_table()) + assert first_tokens.equals(delivered[2].source_info_table()) + (path,) = result_db.list_table_paths() + results = result_db.get_all_records(path) + assert results is not None and results.num_rows == 3 + + job, pipeline_db, result_db, standalone = make_job() + node = cast(FunctionJobNode, job.nodes["add"]) + _, data = next(node.upstreams[0].iter_data()) + _ = job.run() + out = standalone.call(data, skip_cache_lookup=True) + assert out is not None and calls == [1, 2, 1] + check(job, pipeline_db, result_db, out.datagram_uuid.bytes) + + async def run() -> bytes: + async with asyncio.timeout(10): + running = asyncio.create_task(job.run_async(observer=observer)) + _ = await observer.ready.wait() + writing = asyncio.create_task( + standalone.async_call(data), name="standalone" + ) + _ = await standalone_started.wait() + release.set() + written = await writing + assert written is not None + _ = await running + return written.datagram_uuid.bytes + + calls.clear() + concurrent = True + job, pipeline_db, result_db, standalone = make_job() + check(job, pipeline_db, result_db, asyncio.run(run())) + assert calls == [1, 2, 1] + + @pytest.mark.asyncio @pytest.mark.parametrize("fail_fast", [False, True], ids=["cancel", "fail-fast"]) async def test_stopping_an_async_run_with_waiters_allows_retry(fail_fast: bool) -> None: From bd42c2c6fbd191df4507bc6f5420afe25173679b Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 15:02:42 -0800 Subject: [PATCH 3/3] fix(function-pod): require a stored result for async reuse --- changelog.d/ITL-1101.md | 2 +- docs/concepts/function-pods.md | 10 +- docs/concepts/pipeline-job.md | 9 +- docs/concepts/provenance.md | 5 +- docs/dev/design_issues/NOISSUE-FN1.md | 5 +- src/orcapod/core/cached_function_pod.py | 45 ++-- src/orcapod/core/result_cache.py | 19 +- src/orcapod/pipeline/run_summary.py | 2 +- .../test_function_pod_concurrency.py | 229 ++++++++++-------- 9 files changed, 171 insertions(+), 155 deletions(-) diff --git a/changelog.d/ITL-1101.md b/changelog.d/ITL-1101.md index 9870603c7..b168b8206 100644 --- a/changelog.d/ITL-1101.md +++ b/changelog.d/ITL-1101.md @@ -1,3 +1,3 @@ ### Fixed -- Async function nodes now compute each distinct input only once when equal rows arrive concurrently. This also prevents repeated calls to functions that take the invocation context. +- Async function nodes let concurrent rows with equal inputs reuse a stored result, including for functions that take the invocation context. Each row computes its own result on a cache miss. diff --git a/docs/concepts/function-pods.md b/docs/concepts/function-pods.md index a26043922..3a3531e23 100644 --- a/docs/concepts/function-pods.md +++ b/docs/concepts/function-pods.md @@ -656,11 +656,11 @@ of a notebook cell it is shown as a table; `print` shows the same as text. The j `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 arriving during a call wait to reuse its result. If the -call fails or is cancelled, each waiting row can make its own attempt. With a discard -result store, the async node keeps successful results in memory for the run. -Different nodes can share a result table, so scheduling can change which nodes -compute a result or reuse it. +In an async run, equal inputs arriving during a call wait for it to finish. After a +successful call, each waiting row looks up the input in the result store, as it would +in a sync run. If the lookup misses or the call fails or is cancelled, the row makes +its own attempt. Scheduling can change which result a lookup finds when several +callers write to a shared result table. Running the same job again computes nothing new, and the summary says so: diff --git a/docs/concepts/pipeline-job.md b/docs/concepts/pipeline-job.md index 9a511fdda..25871086b 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -224,10 +224,11 @@ had loaded the old table keeps reading it (ITL-1413). Open a new database object replacing a table. A function that takes the invocation context (`ctx_arg`) can perform an external action. -Rows with equal input data reuse a successful result even when their tags differ. In an -async run, overlapping rows share a successful call within one node. Jobs that share a -result database share stored results. A later run can call the function again if its -result was discarded or deleted. To perform an action for each row, use a +Rows with equal input data reuse a stored result even when their tags differ. In an async +run, overlapping rows at one node give the first call time to store its result before +checking for it again. Jobs that share a result database share stored results. A row can +call the function again if the result was discarded or deleted. To perform an action for +each row, use a [`SideEffectPod`](function-pods.md#side-effects-in-a-job-delivered-by-a-run-never-by-a-read). ### Result commit ordering diff --git a/docs/concepts/provenance.md b/docs/concepts/provenance.md index e6288ab38..3db253ff3 100644 --- a/docs/concepts/provenance.md +++ b/docs/concepts/provenance.md @@ -92,8 +92,9 @@ three records the job keeps. 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 entry's `__computed` field records what happened when that entry was written. When equal inputs arrive - concurrently at one function node, the first call computes the result and the other - rows wait to reuse it. The stored result says which + concurrently at one function node, the other rows wait for the first call to finish. + After a successful call, each waiting row checks the result store and computes its own + result if the lookup misses. 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/docs/dev/design_issues/NOISSUE-FN1.md b/docs/dev/design_issues/NOISSUE-FN1.md index b7cc3f9fe..3c5a80730 100644 --- a/docs/dev/design_issues/NOISSUE-FN1.md +++ b/docs/dev/design_issues/NOISSUE-FN1.md @@ -18,5 +18,6 @@ Phase 1 (replay cached results from DB) remains unchanged. Concurrency is contro **Follow-up (ITL-1101):** Phase 2 shares a pending call by input data hash within one cached function node execution. Equal rows keep their own tags and pipeline records. -Distinct inputs still compute concurrently. Failed or cancelled calls leave waiting rows -free to run their own attempts. A discard result store uses an in-run memo for later rows. +Distinct inputs still compute concurrently. After a successful call, waiting rows check +the result store as in sync execution. A cache miss, failed call or cancelled call leaves +the waiting row free to make its own attempt. diff --git a/src/orcapod/core/cached_function_pod.py b/src/orcapod/core/cached_function_pod.py index 84716ba70..a3c138688 100644 --- a/src/orcapod/core/cached_function_pod.py +++ b/src/orcapod/core/cached_function_pod.py @@ -43,9 +43,7 @@ module_logger = logging.getLogger(__name__) -_InFlight: TypeAlias = dict[ - tuple[str, ContentHash], asyncio.Future[DataProtocol | None] -] +_InFlight: TypeAlias = dict[tuple[str, ContentHash], asyncio.Future[bool]] class CachedFunctionPod(WrappedFunctionPod): @@ -428,7 +426,7 @@ async def _async_process_once( logger: DataExecutionLoggerProtocol | None = None, run_id: str | None = None, ) -> tuple[TagProtocol, DataProtocol | None]: - """Reuse successful work and leave failed invocations local to their rows.""" + """Let equal inputs wait for a pending call before checking for a result.""" cached = self.lookup_cached_data(data) if cached is not None: module_logger.info("Pod-level cache hit") @@ -439,27 +437,23 @@ async def _async_process_once( ) key = (data.data_context_key, data.content_hash()) - retains_results = self.result_database.stores_records pending = in_flight.get(key) if pending is not None: - result = await asyncio.shield(pending) - if result is not None: - if retains_results: - cached = self._cache.lookup( - data, - data_context_key=self.data_context_key, - result_id=result.datagram_uuid.bytes, - ) - if cached is not None: - return tag, cached - return tag, result.with_meta_columns( - **{self.RESULT_COMPUTED_FLAG: False} - ) + if await asyncio.shield(pending): + # Use the same lookup as a later sync row, including when the + # store discarded the result or another writer stored a newer one. + cached = self.lookup_cached_data(data) + if cached is not None: + module_logger.info("Pod-level cache hit") + return tag, cached + # A failed call or a result the store cannot return leaves this + # row to make its own attempt. + return await self._async_compute_and_store( + tag, data, logger=logger, run_id=run_id + ) - # An unsuccessful leader leaves each waiting row at its original cache miss. - completion = asyncio.get_running_loop().create_future() - if pending is None: - in_flight[key] = completion + completion: asyncio.Future[bool] = asyncio.get_running_loop().create_future() + in_flight[key] = completion result = None try: out_tag, result = await self._async_compute_and_store( @@ -467,11 +461,8 @@ async def _async_process_once( ) return out_tag, result finally: - completion.set_result(result) - if pending is None and (retains_results or result is None): - del in_flight[key] - elif result is not None and not retains_results: - in_flight.setdefault(key, completion) + completion.set_result(result is not None) + del in_flight[key] async def _async_invoke_with_hooks( self, diff --git a/src/orcapod/core/result_cache.py b/src/orcapod/core/result_cache.py index 062d27005..6186c0765 100644 --- a/src/orcapod/core/result_cache.py +++ b/src/orcapod/core/result_cache.py @@ -13,7 +13,6 @@ from typing import TYPE_CHECKING, Any import pyarrow as pa -import pyarrow.compute as pc from orcapod.core.data_function_types import StoredColumn from orcapod.errors import ( @@ -316,7 +315,6 @@ def lookup( additional_constraints: dict[str, Any] | None = None, *, data_context_key: str, - result_id: bytes | None = None, ) -> DataProtocol | None: """Look up a cached output data for *input_data*. @@ -338,7 +336,6 @@ def lookup( for ``function_name``). data_context_key: Key of the caller's data context. Only rows written under it are matched, and the returned data carries it. - result_id: If given, read only this previously selected result. Returns: The cached output data with ``RESULT_COMPUTED_FLAG: False`` @@ -364,17 +361,11 @@ def lookup( constraints.update(additional_constraints) constraints[constants.DATA_CONTEXT_COL] = data_context_key - if result_id is None: - result_table = self._result_database.get_records_with_column_value( - self._versioned_record_path, constraints, record_id_column=RECORD_ID_COL - ) - else: - result_table = self._result_database.get_record_by_id( - self._versioned_record_path, result_id, record_id_column=RECORD_ID_COL - ) - if result_table is not None: - for column, value in constraints.items(): - result_table = result_table.filter(pc.field(column) == value) + result_table = self._result_database.get_records_with_column_value( + self._versioned_record_path, + constraints, + record_id_column=RECORD_ID_COL, + ) if result_table is None or result_table.num_rows == 0: return None diff --git a/src/orcapod/pipeline/run_summary.py b/src/orcapod/pipeline/run_summary.py index 56e37cb2f..3d2a52fbc 100644 --- a/src/orcapod/pipeline/run_summary.py +++ b/src/orcapod/pipeline/run_summary.py @@ -76,7 +76,7 @@ class RunSummary: also keeps it as ``job.last_run``. Counts attribute work to the nodes that actually did it. Rows within one node - share a computation for equal inputs. In an async run, scheduling can affect + can reuse stored results for equal inputs. In an async run, scheduling can affect which nodes compute or reuse a result from a shared result table. Attributes: diff --git a/tests/test_pipeline/test_function_pod_concurrency.py b/tests/test_pipeline/test_function_pod_concurrency.py index 8f07ea8b2..5390ae66b 100644 --- a/tests/test_pipeline/test_function_pod_concurrency.py +++ b/tests/test_pipeline/test_function_pod_concurrency.py @@ -16,7 +16,11 @@ from orcapod.core.data_function import CachedDataFunction from orcapod.core.function_pod import FunctionPod from orcapod.core.nodes.function_node import FunctionJobNode -from orcapod.databases import InMemoryArrowDatabase, NoOpArrowDatabase +from orcapod.databases import ( + DeltaTableDatabase, + InMemoryArrowDatabase, + NoOpArrowDatabase, +) from orcapod.errors import RowFailuresWarning from orcapod.pipeline import AsyncPipelineOrchestrator from orcapod.pipeline.observer import NoOpObserver @@ -31,6 +35,7 @@ if TYPE_CHECKING: from collections.abc import Iterator + from pathlib import Path import pyarrow as pa @@ -279,69 +284,103 @@ async def run() -> RunSummary: check(job, summary, int(not cancelled)) -@pytest.mark.parametrize("limit", [1, None], ids=["serial", "unbounded"]) -def test_discard_result_store_reuses_successes_within_each_async_run( - limit: int | None, +@pytest.mark.parametrize("store", ["delta", "memory", "discard"]) +@pytest.mark.parametrize("limit", [1, 2, None], ids=["serial", "two", "unbounded"]) +def test_async_reuse_requires_a_result_store_hit( + tmp_path: Path, store: str, limit: int | None ) -> None: - """Equal inputs share a successful call even when the result store discards it.""" - calls: list[int] = [] - observer = _RowStarts(expected=4) - block = False + """Match the sync path's calls, result identity and source tokens for each row.""" + calls: list[tuple[int, int]] = [] + observer = _RowStarts(expected=4 if limit is None else limit) + async_run = False async def add(x: int, y: int) -> int: - calls.append(x) - if block: + calls.append((x, y)) + if async_run: _ = await observer.ready.wait() return x + y pod = FunctionPod.from_fn( add, output_keys="total", pod_config=PodConfig(max_concurrency=limit) ) - discarded = NoOpArrowDatabase() - sync_job = _repeated_job( - pod, InMemoryArrowDatabase(), reverse=False, result_database=discarded - ) - assert sync_job.run().nodes["add"].computed == 4 - assert calls == [1, 1, 1, 2] - expected = sync_job.nodes["add"].as_table().sort_by("row") - assert expected.num_rows == 4 + + def make_job(name: str) -> tuple[PipelineJob, InMemoryArrowDatabase]: + result_db: ArrowDatabaseProtocol + if store == "delta": + result_db = DeltaTableDatabase(tmp_path / name) + elif store == "memory": + result_db = InMemoryArrowDatabase() + else: + result_db = NoOpArrowDatabase() + pipeline_db = InMemoryArrowDatabase() + job = _repeated_job(pod, pipeline_db, reverse=False, result_database=result_db) + return job, pipeline_db + + def row_provenance( + job: PipelineJob, pipeline_db: InMemoryArrowDatabase + ) -> list[tuple[int, int, str]]: + (path,) = pipeline_db.list_table_paths() + stored = pipeline_db.get_all_records(path, record_id_column="storage_key") + assert stored is not None + records = stored.sort_by("row").to_pylist() + assert [row["row"] for row in records] == [0, 1, 2, 3] + assert len({row["storage_key"] for row in records}) == 4 + seen: dict[bytes, int] = {} + delivered = { + tag.as_dict()["row"]: out for tag, out in job.nodes["add"].iter_data() + } + assert set(delivered) == {0, 1, 2, 3} + provenance: list[tuple[int, int, str]] = [] + for row in records: + i = cast(int, row["row"]) + out = delivered[i] + assert out.as_dict() == {"total": 11 if i < 3 else 22} + result_id = out.datagram_uuid + assert result_id.bytes == row[constants.DATA_RECORD_ID] + token = cast( + str, out.source_info_table().column("_source_total")[0].as_py() + ) + assert result_id.hex in token + # Fresh stores generate fresh IDs. Compare which rows share an ID and + # the complete token with its generated ID replaced by that row index. + first = seen.setdefault(result_id.bytes, i) + provenance.append((i, first, token.replace(result_id.hex, str(first)))) + return provenance + + sync_job, sync_db = make_job("sync") + sync_stats = sync_job.run().nodes["add"] + sync_calls = calls.copy() + sync_provenance = row_provenance(sync_job, sync_db) + if store == "discard": + assert sync_calls == [(1, 10)] * 3 + [(2, 20)] + assert [first for _, first, _ in sync_provenance] == [0, 1, 2, 3] + else: + assert sync_calls == [(1, 10), (2, 20)] + assert [first for _, first, _ in sync_provenance] == [0, 0, 0, 3] async def run(job: PipelineJob) -> RunSummary: async with asyncio.timeout(10): return await job.run_async(observer=observer) - block = limit is None - pipeline_db = InMemoryArrowDatabase() - for shift in (0, 10): - calls.clear() - observer = _RowStarts(expected=4) - job = _repeated_job( - pod, pipeline_db, reverse=False, result_database=discarded, shift=shift - ) - summary = asyncio.run(run(job)) - assert calls == [1, 2] - rows = job.nodes["add"].as_table().sort_by("row") - assert rows.select(["group", "total"]).equals( - expected.select(["group", "total"]) - ) - assert rows["row"].to_pylist() == list(range(shift, shift + 4)) - assert (summary.nodes["add"].computed, summary.nodes["add"].reused) == (2, 2) - (path,) = pipeline_db.list_table_paths() - records = pipeline_db.get_all_records(path) - assert records is not None - assert records.sort_by("row")["row"].to_pylist() == ( - list(range(4)) + (list(range(10, 14)) if shift else []) - ) - assert discarded.list_table_paths() == [] + calls.clear() + async_run = True + async_job, async_db = make_job("async") + async_stats = asyncio.run(run(async_job)).nodes["add"] + assert row_provenance(async_job, async_db) == sync_provenance + assert sorted(calls) == sync_calls + assert (async_stats.computed, async_stats.reused) == ( + sync_stats.computed, + sync_stats.reused, + ) -def test_waiters_keep_the_selected_result_in_a_shared_result_store() -> None: - """A later standalone write cannot change an already waiting row's result.""" +@pytest.mark.parametrize("concurrent", [False, True], ids=["sync", "async"]) +def test_rows_use_the_latest_stored_result_at_lookup(concurrent: bool) -> None: + """A standalone write between the first row and later lookups can win.""" observer = _RowStarts(expected=4) calls: list[int] = [] standalone_started = asyncio.Event() release = asyncio.Event() - concurrent = False async def add(x: int, y: int) -> int: calls.append(x) @@ -357,64 +396,30 @@ async def add(x: int, y: int) -> int: add, output_keys="total", pod_config=PodConfig(max_concurrency=None) ) - def make_job() -> tuple[ - PipelineJob, InMemoryArrowDatabase, InMemoryArrowDatabase, CachedDataFunction - ]: - result_db = InMemoryArrowDatabase() - pipeline_db = InMemoryArrowDatabase() - job = _repeated_job(pod, pipeline_db, reverse=False, result_database=result_db) - return ( - job, - pipeline_db, - result_db, - CachedDataFunction(pod.data_function, result_database=result_db), - ) - - def check( - job: PipelineJob, - pipeline_db: InMemoryArrowDatabase, - result_db: InMemoryArrowDatabase, - standalone_id: bytes, - ) -> None: - node = cast(FunctionJobNode, job.nodes["add"]) - (pipeline_path,) = pipeline_db.list_table_paths() - stored = pipeline_db.get_all_records( - pipeline_path, record_id_column="storage_key" - ) - assert stored is not None - records = stored.sort_by("row").to_pylist() - delivered = {tag.as_dict()["row"]: out for tag, out in node.iter_data()} - assert [row["row"] for row in records] == [0, 1, 2, 3] - assert [row["__computed"] for row in records] == [True, False, False, True] - result_ids = [row[constants.DATA_RECORD_ID] for row in records] - assert result_ids[0] == result_ids[1] == result_ids[2] != standalone_id - assert len({row["storage_key"] for row in records}) == 4 - for i, result_id in enumerate(result_ids): - out = delivered[i] - assert out.as_dict() == {"total": 11 if i < 3 else 22} - assert out.datagram_uuid.bytes == result_id - assert out.datagram_uuid.hex in str(out.source_info_table().to_pylist()) - first_tokens = delivered[0].source_info_table() - assert first_tokens.equals(delivered[1].source_info_table()) - assert first_tokens.equals(delivered[2].source_info_table()) - (path,) = result_db.list_table_paths() - results = result_db.get_all_records(path) - assert results is not None and results.num_rows == 3 - - job, pipeline_db, result_db, standalone = make_job() + result_db = InMemoryArrowDatabase() + pipeline_db = InMemoryArrowDatabase() + job = _repeated_job(pod, pipeline_db, reverse=False, result_database=result_db) + standalone = CachedDataFunction(pod.data_function, result_database=result_db) node = cast(FunctionJobNode, job.nodes["add"]) _, data = next(node.upstreams[0].iter_data()) - _ = job.run() - out = standalone.call(data, skip_cache_lookup=True) - assert out is not None and calls == [1, 2, 1] - check(job, pipeline_db, result_db, out.datagram_uuid.bytes) + + @final + class WriteBetweenRows(NoOpObserver): + written: DataProtocol | None = None + + @override + def on_data_start( + self, node_label: str, tag: TagProtocol, data: DataProtocol + ) -> None: + if node_label == "add" and tag.as_dict()["row"] == 1: + self.written = standalone.call(data, skip_cache_lookup=True) async def run() -> bytes: async with asyncio.timeout(10): running = asyncio.create_task(job.run_async(observer=observer)) _ = await observer.ready.wait() writing = asyncio.create_task( - standalone.async_call(data), name="standalone" + standalone.async_call(data, skip_cache_lookup=True), name="standalone" ) _ = await standalone_started.wait() release.set() @@ -423,11 +428,37 @@ async def run() -> bytes: _ = await running return written.datagram_uuid.bytes - calls.clear() - concurrent = True - job, pipeline_db, result_db, standalone = make_job() - check(job, pipeline_db, result_db, asyncio.run(run())) - assert calls == [1, 2, 1] + if concurrent: + standalone_id = asyncio.run(run()) + assert calls == [1, 2, 1] + else: + writer = WriteBetweenRows() + _ = job.run(observer=writer) + assert writer.written is not None + standalone_id = writer.written.datagram_uuid.bytes + assert calls == [1, 1, 2] + + (pipeline_path,) = pipeline_db.list_table_paths() + stored = pipeline_db.get_all_records(pipeline_path, record_id_column="storage_key") + assert stored is not None + records = stored.sort_by("row").to_pylist() + delivered = {tag.as_dict()["row"]: out for tag, out in node.iter_data()} + assert [row["row"] for row in records] == [0, 1, 2, 3] + assert [row["__computed"] for row in records] == [True, False, False, True] + result_ids = [row[constants.DATA_RECORD_ID] for row in records] + assert result_ids[0] != standalone_id + assert result_ids[1:3] == [standalone_id, standalone_id] + assert len(set(result_ids)) == 3 + assert len({row["storage_key"] for row in records}) == 4 + for i, result_id in enumerate(result_ids): + out = delivered[i] + assert out.as_dict() == {"total": 11 if i < 3 else 22} + assert out.datagram_uuid.bytes == result_id + assert out.datagram_uuid.hex in str(out.source_info_table().to_pylist()) + assert delivered[1].source_info_table().equals(delivered[2].source_info_table()) + (path,) = result_db.list_table_paths() + results = result_db.get_all_records(path) + assert results is not None and results.num_rows == 3 @pytest.mark.asyncio