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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions changelog.d/ITL-1101.md
Original file line number Diff line number Diff line change
@@ -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.
8 changes: 5 additions & 3 deletions docs/concepts/function-pods.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Expand Down
11 changes: 7 additions & 4 deletions docs/concepts/pipeline-job.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
5 changes: 3 additions & 2 deletions docs/concepts/provenance.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
6 changes: 6 additions & 0 deletions docs/dev/design_issues/NOISSUE-FN1.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
9 changes: 5 additions & 4 deletions docs/reference/hashing.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.<locals>.<lambda>`, `pipeline/base.py:AbstractPipelineBase._validate_invocation`, `pipeline/base.py:AbstractPipelineBase._validate_invocation.<locals>.<genexpr>`, `pipeline/base.py:AbstractPipelineBase.to_invocations`, `pipeline/base.py:AbstractPipelineBase.from_invocations`, `pipeline/base.py:AbstractPipelineBase.from_invocations.<locals>.<genexpr>`, `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.<locals>.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.<locals>.<lambda>` |
Expand Down Expand Up @@ -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` |

Expand All @@ -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
Expand Down
95 changes: 81 additions & 14 deletions src/orcapod/core/cached_function_pod.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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()``.
Expand Down Expand Up @@ -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
)
Expand Down Expand Up @@ -399,40 +412,94 @@ 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,
data: DataProtocol,
*,
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:
Expand Down
29 changes: 27 additions & 2 deletions src/orcapod/core/function_pod.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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]]],
Expand Down Expand Up @@ -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)
Expand All @@ -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:
Expand Down
10 changes: 5 additions & 5 deletions src/orcapod/pipeline/run_summary.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."
)


Expand Down Expand Up @@ -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.
Expand Down
Loading
Loading