diff --git a/changelog.d/ITL-1101.md b/changelog.d/ITL-1101.md new file mode 100644 index 000000000..b168b8206 --- /dev/null +++ b/changelog.d/ITL-1101.md @@ -0,0 +1,3 @@ +### Fixed + +- 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 e6b0490a5..3a3531e23 100644 --- a/docs/concepts/function-pods.md +++ b/docs/concepts/function-pods.md @@ -656,9 +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 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. +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 5111c077a..25871086b 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -223,10 +223,13 @@ 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`) can perform an external action. +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 e3f0adcf3..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 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 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 c8222cedc..3c5a80730 100644 --- a/docs/dev/design_issues/NOISSUE-FN1.md +++ b/docs/dev/design_issues/NOISSUE-FN1.md @@ -15,3 +15,9 @@ 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. 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/docs/reference/hashing.md b/docs/reference/hashing.md index b99d06705..157986c24 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..` | @@ -1224,7 +1225,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` | @@ -1249,9 +1250,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 edee43f22..3594ecad2 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, @@ -43,6 +47,8 @@ module_logger = logging.getLogger(__name__) +_InFlight: TypeAlias = dict[tuple[str, ContentHash], asyncio.Future[bool]] + class CachedFunctionPod(WrappedFunctionPod): """Pod-level caching wrapper that intercepts ``process_data()``. @@ -286,12 +292,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 ) @@ -399,6 +412,62 @@ 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 | None, + tag: TagProtocol, + data: DataProtocol, + *, + logger: DataExecutionLoggerProtocol | None = None, + run_id: str | None = None, + ) -> tuple[TagProtocol, DataProtocol | None]: + """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") + 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()) + pending = in_flight.get(key) + if pending is not None: + 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 + ) + + 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( + tag, data, logger=logger, run_id=run_id + ) + return out_tag, result + finally: + completion.set_result(result is not None) + del in_flight[key] + async def _async_invoke_with_hooks( self, tag: TagProtocol, @@ -406,33 +475,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 229f2ecd4..671514bbb 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 @@ -85,6 +92,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: @@ -657,6 +677,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]]], @@ -698,6 +722,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) @@ -709,7 +734,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..3d2a52fbc 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 + 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: 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..5390ae66b 100644 --- a/tests/test_pipeline/test_function_pod_concurrency.py +++ b/tests/test_pipeline/test_function_pod_concurrency.py @@ -6,15 +6,25 @@ 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.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 ( + DeltaTableDatabase, + InMemoryArrowDatabase, + NoOpArrowDatabase, +) +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 ( @@ -25,14 +35,475 @@ if TYPE_CHECKING: from collections.abc import Iterator + from pathlib import Path import pyarrow as pa + 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 +@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, + result_database: ArrowDatabaseProtocol | None = None, +) -> 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, result_database=result_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_permanent_failure_is_reported_for_each_waiting_row( + limit: int | None, +) -> None: + """Every equal row gets its own failed attempt, and a later run can retry.""" + 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 sorted(calls) == [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.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("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: + """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, 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) + ) + + 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) + + 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, + ) + + +@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() + + 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) + ) + + 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()) + + @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, skip_cache_lookup=True), name="standalone" + ) + _ = await standalone_started.wait() + release.set() + written = await writing + assert written is not None + _ = await running + return written.datagram_uuid.bytes + + 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 +@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]