diff --git a/changelog.d/ITL-1474.md b/changelog.d/ITL-1474.md new file mode 100644 index 000000000..d627fefdc --- /dev/null +++ b/changelog.d/ITL-1474.md @@ -0,0 +1,10 @@ +### Changed + +- Async function pods now default to the usable CPU count clamped to 1–16 in-flight + calls. A pod inherits the pipeline setting unless it supplies a positive integer or + explicit `None`. + +### Breaking changes and migration + +- To keep unlimited async dispatch, use `PodConfig(max_concurrency=None)`. To inherit + the pipeline limit, omit `max_concurrency` or set it to `"inherit"`. diff --git a/docs/concepts/function-pods.md b/docs/concepts/function-pods.md index 8aebfb95f..6e31d16f6 100644 --- a/docs/concepts/function-pods.md +++ b/docs/concepts/function-pods.md @@ -596,6 +596,52 @@ print(job.nodes["bmi"].as_table().num_rows) # 3 ``` +### Limiting in-flight calls + +An async function pod's default limit is the usable CPU count, up to 16 in-flight +calls and with a minimum of one. Different pods can run concurrently. Choose a smaller +limit when each call holds substantial memory or talks to a service with a concurrency +limit. + +Orcapod counts CPUs the same way as CPython's default thread pool. It uses +`os.process_cpu_count()` when available (Python 3.13 and later) and `os.cpu_count()` +otherwise. If that function returns no count, the limit is one. `PipelineConfig()` +computes the default when constructed. Async jobs create that default config when the +pod runs. + +```python +from orcapod.core.function_pod import FunctionPod +from orcapod.types import PodConfig + +limited_bmi = FunctionPod.from_fn( + compute_bmi, output_keys="bmi", pod_config=PodConfig(max_concurrency=4) +) +``` + +Apply `limited_bmi(source, label="bmi")` when recording a job. Set +`PodConfig(max_concurrency=None)` to allow unlimited dispatch or use `1` to process +one row at a time. If calls to a pod wait for each other, choose a limit that lets +all calls in the group start. + +When calling `FunctionPod.async_execute` directly, you can also supply a `PipelineConfig`. +The two settings resolve as follows. + +| `PodConfig.max_concurrency` | `PipelineConfig.default_max_concurrency` | Effective limit | +| --- | --- | --- | +| Omitted or `"inherit"` | Omitted | Usable CPU count, clamped to 1–16 | +| Omitted or `"inherit"` | Positive integer | Pipeline limit | +| Omitted or `"inherit"` | `None` | Unlimited | +| Positive integer | Any | Pod limit | +| `None` | Any | Unlimited | + +Local coroutine functions run on the event loop. Local synchronous functions in an +async job use the event loop's thread pool. CPython's default pool has up to +`min(32, (cpu_count or 1) + 4)` workers. For Python 3.11 and 3.12 this uses +`os.cpu_count()`, and for Python 3.13 and later it uses `os.process_cpu_count()`. +For example, a reported count of 18 yields 22 default workers and a per-pod limit of 16. +If fewer workers are available than the pod's limit, the pool runs fewer calls and queues +the rest. The pool is shared across pods on the loop. + ### Reading the run summary `job.run()` (and `await job.run_async()`) returns a `RunSummary`: for each function node, how @@ -825,7 +871,9 @@ Inside `job.run()`, each function node commits its results and pipeline records store in batches: every `commit_every_rows` rows (default 100), when the node finishes, before a failed run raises, and when the job ends. Committing in batches keeps a run's time linear in its rows; on a `DeltaTableDatabase` each commit is one Delta version per table, so -a 1,000-row node writes 10 versions per table instead of 1,000. +a 1,000-row node writes 10 pipeline table versions instead of 1,000. +In an async run, the result store can group writes differently depending on which calls +have finished when a pipeline batch is ready to commit. ```python job.run(commit_every_rows=500) # fewer, larger commits diff --git a/docs/concepts/pipeline-job.md b/docs/concepts/pipeline-job.md index 41a19df1b..260f6cabf 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -68,6 +68,12 @@ the run then does is undefined (ITL-1369). `load_only=True` fills the nodes from what is already stored and computes nothing; see [Loading without computing](function-pods.md#loading-without-computing-runload_onlytrue). +Use `await job.run_async()` or pass an `AsyncPipelineOrchestrator` to `job.run()` to +execute nodes concurrently. Each function pod defaults to a limit based on the usable +CPU count, clamped to 1–16 in-flight calls during an async run. The +[function pod concurrency settings](function-pods.md#limiting-in-flight-calls) show how +to choose a limit for a particular pod. + ## Nodes Each recorded step, and each source, is a **node**. `job.nodes` maps a node's name to the diff --git a/docs/dev/plans/2026-11-26-itl-1474-async-function-pod-concurrency.md b/docs/dev/plans/2026-11-26-itl-1474-async-function-pod-concurrency.md new file mode 100644 index 000000000..fbfcd3856 --- /dev/null +++ b/docs/dev/plans/2026-11-26-itl-1474-async-function-pod-concurrency.md @@ -0,0 +1,95 @@ +# ITL-1474 — Bound async function pod concurrency by default + +## Default + +The developer chose a default of the usable CPU count clamped to 1–16 on November 26, +2026. The limit applies to each pod execution, including the compute phase of an async +job, and controls how far the pod reads ahead. The pod acquires its semaphore before +creating a row task and holds the permit through invocation and output delivery. The +async job orchestrator starts nodes concurrently and bounds each edge's queue separately. +A bounded channel alone cannot bound calls because an unrestricted pod can drain it into +tasks. + +The local executor awaits coroutine functions on the job's event loop. It submits +synchronous functions to that loop's default thread pool, which already caps active +threads but can queue submitted work. The no-executor Python function path uses the same +event-loop and thread-pool split. A synchronous call into a coroutine has a separate, +single-thread bridge when a loop is already running. The optional Ray executor submits +remote tasks and waits on their futures. Ray schedules those tasks using its own capacity +and task resource options. There is no local process pool for function invocations. + +CPython's default thread pool uses up to `min(32, (cpu_count or 1) + 4)` workers. In +Python 3.11 and 3.12, it uses `os.cpu_count()`. Since 3.13, it uses +`os.process_cpu_count()`. A machine count of 18 thus yields a pool of 22 under the +corresponding default. With the chosen cap, one pod on that loop can submit at most +16 calls at once. Where the pool has fewer available workers, fewer calls run and the +rest wait in the pool. The pool is shared by the loop, while the semaphore is per pod. + +- **Constant.** Sixteen bounds waiting row tasks and executor submissions + on every host while allowing overlap for I/O. Different workloads can override it. +- **Host logical CPUs (`os.cpu_count()`).** Easy to obtain, but can count CPUs the process + cannot use. It says little about coroutine I/O or capacity on a remote Ray cluster. +- **Process-visible logical CPUs.** Process affinity on supported platforms, or + `os.process_cpu_count()` on Python 3.13 and later, better reflects usable CPUs for local + CPU-bound work. It still does not reliably describe a container's CPU-time quota, or + the capacity and queueing behavior of the selected executor. +- **Container quota.** Reading platform-specific quotas would estimate local CPU-time + capacity. It adds platform logic and still cannot predict I/O capacity or remote worker + resources. Local CPU-heavy work can choose an explicit limit based on its executor. +- **Usable CPU count with a ceiling of 16 (chosen).** Use the same CPU-count API as + CPython's default thread pool on the running Python version. Use one when the count + is unavailable and clamp the result to 1–16. This reduces default fan-out on small + hosts and caps it on larger hosts. + +## Configuration and storage + +Compute the default for `PipelineConfig.default_max_concurrency` at config construction +with a dedicated default factory. Use the distinct +`"inherit"` default for `PodConfig.max_concurrency`. An +explicit positive integer or `None` on the pod wins over the pipeline config. `None` means +unlimited pod dispatch at either level. If the pod setting is omitted, the resolver uses +the supplied pipeline config, or the default pipeline config when none is supplied. Keep +existing validation of the effective positive limit. + +| Pod setting | Pipeline setting | Effective limit | +| --- | --- | --- | +| Omitted or `"inherit"` | Omitted | Usable CPU count, clamped to 1–16 | +| Omitted or `"inherit"` | Positive integer | Pipeline integer | +| Omitted or `"inherit"` | Explicit `None` | Unlimited | +| Positive integer | Any | Pod integer | +| Explicit `None` | Any | Unlimited | + +`PipelineConfig` currently reaches the pod through the `pipeline_config` argument of +`FunctionPod.async_execute`. `PipelineJob.run_async` and `AsyncPipelineOrchestrator` do +not expose this argument today. Job nodes delegate their compute work to the pod and +therefore pick up the default. Preserve those entry points and describe the pipeline-level +precedence at the pod API that supports it. + +Keep `"pod_config": null` in the existing position for an inherited setting. Write an +explicit integer as before and write `{"max_concurrency": null}` for explicit unlimited +dispatch. Existing saved configs with a null or missing `pod_config` load as inherited. +Earlier versions collapsed explicit `None` into omission, so those saves cannot carry the +original intent. Keep the default and settings out of identity and stored-path logic. Leave +the sync execution path and the async semaphore's lifecycle alone. The effective limit +only changes the number of in-flight rows. Async completion order remains unspecified. + +## Verification and delivery + +1. Write regressions first, using several rows, two tag columns and two data columns in + multiple layouts. Count concurrent calls in the real async job path with an async + function that yields while active. Test the default, an explicit positive limit and an + explicit unlimited setting, then verify the results and the equivalent synchronous + run. Exercise pipeline precedence via `FunctionPod.async_execute` with bounded + channels, including integer overrides, explicit unlimited overrides and inheritance. +2. Round-trip the public function pod config through JSON for omitted, numeric and null + values. Compare the untouched pod's serialized bytes before and after. Check pod and + pipeline hashes with `tests/test_hashing/golden/generate_golden_hashes.py --check` and stop if there is + drift. Run the new regressions on unmodified library code and record the failures. + Cases that demonstrate existing behavior serve as controls in the regressions. +3. Update the function pod and pipeline job docs and link to the async concurrency + guidance where appropriate. Cover the migration to explicit unlimited dispatch in + `changelog.d/ITL-1474.md`. Run the affected documentation samples. +4. Run targeted tests serially, Ruff lint and format checks, basedpyright, the design + issues check and the changelog check. Check clean three-way merge compatibility against + PRs #559–#571 by head without changing any stack branch. Open a draft PR against + `main` and use CI for the full suite. diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 22282a2f7..0c5c535b7 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -179,6 +179,12 @@ for a text listing, or `job.diagram().save("pipeline.html")` for a page; the sam ## Errors when running a job +### An async function pod uses too much memory + +Lower the pod's `max_concurrency` if several simultaneous calls hold more memory than the +run can spare. For example, use `PodConfig(max_concurrency=1)` to allow one call at a time +for that pod. See [Limiting in-flight calls](concepts/function-pods.md#limiting-in-flight-calls). + ### `ValueError: PipelineJob.run() requires a database.` **Cause.** The job was created without `database=`. diff --git a/src/orcapod/core/function_pod.py b/src/orcapod/core/function_pod.py index 8a24c3b49..371ba7a36 100644 --- a/src/orcapod/core/function_pod.py +++ b/src/orcapod/core/function_pod.py @@ -666,7 +666,7 @@ async def async_execute( """Streaming async execution with per-data concurrency control. Each input (tag, data) is dispatched as an independent async task. - A semaphore limits how many tasks are in-flight concurrently. + A semaphore limits in-flight tasks unless the effective limit is ``None``. Observer hooks fire per item: ``on_data_start`` before processing, ``on_data_end(cached=False)`` on success, ``on_data_crash`` on error. @@ -1018,7 +1018,7 @@ def to_config(self) -> dict[str, Any]: "pod_config": None, "ctx_arg_name": self.ctx_arg_name, } - if self._pod_config.max_concurrency is not None: + if self._pod_config.max_concurrency != "inherit": config["pod_config"] = { "max_concurrency": self._pod_config.max_concurrency, } diff --git a/src/orcapod/types/__init__.py b/src/orcapod/types/__init__.py index c3061039e..523cee629 100644 --- a/src/orcapod/types/__init__.py +++ b/src/orcapod/types/__init__.py @@ -21,12 +21,12 @@ import logging import os import uuid -from collections.abc import Collection, Iterator, Mapping -from dataclasses import dataclass +from collections.abc import Callable, Collection, Iterator, Mapping +from dataclasses import dataclass, field from datetime import date, datetime from enum import Enum from types import UnionType -from typing import TYPE_CHECKING, Any, Generic, Self, TypeAlias, TypeVar +from typing import TYPE_CHECKING, Any, Generic, Literal, Self, TypeAlias, TypeVar, cast import pyarrow as pa from typing_extensions import override @@ -341,6 +341,18 @@ class OrchestratorType(Enum): ASYNC_CHANNELS = "async_channels" +# Upper bound on the default number of in-flight calls per async function pod. +DEFAULT_FUNCTION_POD_CONCURRENCY_CAP = 16 + + +def _default_function_pod_concurrency() -> int: + """Return the default number of in-flight calls per async function pod.""" + cpu_count = cast( + Callable[[], int | None], getattr(os, "process_cpu_count", os.cpu_count) + ) + return min(DEFAULT_FUNCTION_POD_CONCURRENCY_CAP, max(1, cpu_count() or 1)) + + @dataclass(frozen=True, slots=True) class PipelineConfig: """Pipeline-level execution configuration. @@ -348,8 +360,10 @@ class PipelineConfig: Attributes: orchestrator: Which orchestrator strategy to use. channel_buffer_size: Max items buffered per channel edge. - default_max_concurrency: Pipeline-wide default for per-node - concurrency. ``None`` means unlimited. + default_max_concurrency: Limit for async function pods that inherit + from this config. When omitted, computed at construction as the + usable CPU count clamped between 1 and + ``DEFAULT_FUNCTION_POD_CONCURRENCY_CAP`` (16). ``None`` means unlimited. execution_engine: Optional data-function executor applied to all function nodes (e.g. ``RayExecutor``). ``None`` means in-process execution. @@ -359,7 +373,9 @@ class PipelineConfig: orchestrator: OrchestratorType = OrchestratorType.SYNCHRONOUS channel_buffer_size: int = 64 - default_max_concurrency: int | None = None + default_max_concurrency: int | None = field( + default_factory=_default_function_pod_concurrency + ) execution_engine: DataFunctionExecutorProtocol | None = None execution_engine_opts: dict[str, Any] | None = None @@ -369,12 +385,13 @@ class PodConfig: """Per-pod executor configuration. Attributes: - max_concurrency: Maximum concurrent function invocations for this pod. - ``None`` inherits from ``PipelineConfig.default_max_concurrency``. - ``1`` means sequential (rate-limited APIs, preserves ordering). + max_concurrency: Maximum in-flight calls when this pod runs asynchronously. + The default, ``"inherit"``, uses ``PipelineConfig.default_max_concurrency``. + An integer or ``None`` overrides the pipeline setting. ``None`` allows + unlimited dispatch, and ``1`` processes one row at a time. """ - max_concurrency: int | None = None + max_concurrency: int | None | Literal["inherit"] = "inherit" @dataclass(frozen=True, slots=True) @@ -431,9 +448,8 @@ def resolve_concurrency( Raises: ValueError: If the resolved value is ``<= 0``. """ - if pod_config.max_concurrency is not None: - result = pod_config.max_concurrency - else: + result = pod_config.max_concurrency + if result == "inherit": result = pipeline_config.default_max_concurrency if result is not None and result <= 0: raise ValueError(f"max_concurrency must be >= 1, got {result}") diff --git a/tests/test_channels/test_async_execute.py b/tests/test_channels/test_async_execute.py index b00408c06..0e64d70ad 100644 --- a/tests/test_channels/test_async_execute.py +++ b/tests/test_channels/test_async_execute.py @@ -669,7 +669,7 @@ def double(x: int) -> int: return x * 2 pf = PythonDataFunction(double, output_keys="result") - pod = FunctionPod(pf) # PodConfig default (None) + pod = FunctionPod(pf) pipeline_cfg = PipelineConfig(default_max_concurrency=2) stream = make_stream(4) diff --git a/tests/test_channels/test_channels.py b/tests/test_channels/test_channels.py index d3a21f496..3542909c9 100644 --- a/tests/test_channels/test_channels.py +++ b/tests/test_channels/test_channels.py @@ -20,6 +20,7 @@ from __future__ import annotations import asyncio +import os import pytest @@ -549,13 +550,14 @@ def test_orchestrator_type_enum(self): assert OrchestratorType.SYNCHRONOUS.value == "synchronous" assert OrchestratorType.ASYNC_CHANNELS.value == "async_channels" - def test_pipeline_config_defaults(self): + def test_pipeline_config_defaults(self, monkeypatch: pytest.MonkeyPatch): from orcapod.types import OrchestratorType, PipelineConfig + monkeypatch.setattr(os, "process_cpu_count", lambda: 4, raising=False) cfg = PipelineConfig() assert cfg.orchestrator == OrchestratorType.SYNCHRONOUS assert cfg.channel_buffer_size == 64 - assert cfg.default_max_concurrency is None + assert cfg.default_max_concurrency == 4 def test_pipeline_config_custom(self): from orcapod.types import OrchestratorType, PipelineConfig @@ -575,7 +577,7 @@ def test_node_config_defaults(self): cfg = NodeConfig() assert cfg.is_result_ephemeral is None pod_cfg = PodConfig() - assert pod_cfg.max_concurrency is None + assert pod_cfg.max_concurrency == "inherit" def test_resolve_concurrency_node_overrides_pipeline(self): from orcapod.types import PipelineConfig, PodConfig, resolve_concurrency @@ -591,9 +593,10 @@ def test_resolve_concurrency_falls_back_to_pipeline(self): pipeline = PipelineConfig(default_max_concurrency=8) assert resolve_concurrency(node, pipeline) == 8 - def test_resolve_concurrency_both_none(self): + def test_resolve_concurrency_both_default(self, monkeypatch: pytest.MonkeyPatch): from orcapod.types import PipelineConfig, PodConfig, resolve_concurrency + monkeypatch.setattr(os, "process_cpu_count", lambda: 4, raising=False) node = PodConfig() pipeline = PipelineConfig() - assert resolve_concurrency(node, pipeline) is None + assert resolve_concurrency(node, pipeline) == 4 diff --git a/tests/test_channels/test_copilot_review_issues.py b/tests/test_channels/test_copilot_review_issues.py index 78b32a76e..0f763a584 100644 --- a/tests/test_channels/test_copilot_review_issues.py +++ b/tests/test_channels/test_copilot_review_issues.py @@ -268,7 +268,7 @@ def test_resolve_concurrency_accepts_one(self): def test_resolve_concurrency_accepts_none(self): """max_concurrency=None means unlimited (no semaphore).""" - pod_config = PodConfig() + pod_config = PodConfig(max_concurrency=None) pipeline_config = PipelineConfig() assert resolve_concurrency(pod_config, pipeline_config) is None diff --git a/tests/test_core/alignment/gate.py b/tests/test_core/alignment/gate.py index c8ce143d0..c18fb8fd6 100644 --- a/tests/test_core/alignment/gate.py +++ b/tests/test_core/alignment/gate.py @@ -177,7 +177,6 @@ def fails(x: int) -> bool: return x % 3 == FAILING_REMAINDER -@function_pod(output_keys="y") async def gated_scale(x: int) -> int: """Return ``10 * x`` once ``GATE`` lets the row keyed ``x`` complete.""" await GATE.wait_turn(x) @@ -187,7 +186,6 @@ async def gated_scale(x: int) -> int: GATE.finish(x) -@function_pod(output_keys="y") async def gated_fragile(x: int) -> int: """As ``gated_scale``, but raise for every ``x`` where ``fails(x)``.""" await GATE.wait_turn(x) diff --git a/tests/test_core/alignment/jobs.py b/tests/test_core/alignment/jobs.py index ac8c81cd2..953ef2843 100644 --- a/tests/test_core/alignment/jobs.py +++ b/tests/test_core/alignment/jobs.py @@ -19,12 +19,13 @@ from orcapod.core.operators.group_by import GROUP_BY_FOLD_LABEL from orcapod import PipelineJob +from orcapod.core.function_pod import FunctionPod from orcapod.core.operators import GroupBy, Join from orcapod.databases import DeltaTableDatabase, InMemoryArrowDatabase from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator from orcapod.pipeline.run_summary import RunSummary from orcapod.system_constants import constants -from orcapod.types import CacheMode +from orcapod.types import CacheMode, PodConfig from .checker import Layout from .fixtures import Sources, content_hash_column, keys_a, make_sources @@ -86,9 +87,14 @@ def build_job( sources = make_sources(scenario, input_order) derive_y(sources) job = PipelineJob(name=JOB_NAME, database=store) - pod = gated_fragile if fragile else gated_scale + # A prescribed completion order may require the last input row to start first. + pod = FunctionPod.from_fn( + gated_fragile if fragile else gated_scale, + output_keys="y", + pod_config=PodConfig(max_concurrency=None), + ) with job: - scaled = pod.pod(sources.a, label="scaled") + scaled = pod(sources.a, label="scaled") Join()(scaled, sources.b, label="joined") GroupBy(by=["g"])(scaled, label="grouped") # OperatorNode.attach_databases is the public way to store an operator's rows. diff --git a/tests/test_core/test_node_config.py b/tests/test_core/test_node_config.py index f737c070f..5237e3b2f 100644 --- a/tests/test_core/test_node_config.py +++ b/tests/test_core/test_node_config.py @@ -1,12 +1,20 @@ +import os + import pytest -from orcapod.types import NodeConfig, PipelineConfig, PodConfig, resolve_concurrency +from orcapod.types import ( + DEFAULT_FUNCTION_POD_CONCURRENCY_CAP, + NodeConfig, + PipelineConfig, + PodConfig, + resolve_concurrency, +) class TestPodConfig: def test_defaults(self): config = PodConfig() - assert config.max_concurrency is None + assert config.max_concurrency == "inherit" def test_max_concurrency(self): config = PodConfig(max_concurrency=4) @@ -65,18 +73,49 @@ def test_merge_returns_new_instance(self): class TestResolveConcurrency: + @pytest.mark.parametrize("has_process_count", [True, False]) + @pytest.mark.parametrize( + ("cpu_count", "expected"), + [ + (1, 1), + (4, 4), + (DEFAULT_FUNCTION_POD_CONCURRENCY_CAP, 16), + (64, DEFAULT_FUNCTION_POD_CONCURRENCY_CAP), + (None, 1), + ], + ) + def test_default_concurrency_uses_usable_cpus( + self, + monkeypatch: pytest.MonkeyPatch, + has_process_count: bool, + cpu_count: int | None, + expected: int, + ) -> None: + if has_process_count: + monkeypatch.setattr(os, "cpu_count", lambda: 8) + monkeypatch.setattr( + os, "process_cpu_count", lambda: cpu_count, raising=False + ) + else: + monkeypatch.delattr(os, "process_cpu_count", raising=False) + monkeypatch.setattr(os, "cpu_count", lambda: cpu_count) + + pipeline = PipelineConfig() + assert pipeline.default_max_concurrency == expected + assert resolve_concurrency(PodConfig(), pipeline) == expected + def test_pod_config_wins_over_pipeline(self): pod = PodConfig(max_concurrency=4) pipeline = PipelineConfig(default_max_concurrency=2) assert resolve_concurrency(pod, pipeline) == 4 - def test_falls_back_to_pipeline_when_pod_is_none(self): - pod = PodConfig(max_concurrency=None) + def test_falls_back_to_pipeline_when_pod_inherits(self): + pod = PodConfig() pipeline = PipelineConfig(default_max_concurrency=2) assert resolve_concurrency(pod, pipeline) == 2 - def test_both_none_returns_none(self): - pod = PodConfig(max_concurrency=None) + def test_inherits_unlimited_pipeline_config(self): + pod = PodConfig() pipeline = PipelineConfig(default_max_concurrency=None) assert resolve_concurrency(pod, pipeline) is None diff --git a/tests/test_pipeline/test_function_pod_concurrency.py b/tests/test_pipeline/test_function_pod_concurrency.py new file mode 100644 index 000000000..ebcfa136f --- /dev/null +++ b/tests/test_pipeline/test_function_pod_concurrency.py @@ -0,0 +1,238 @@ +"""Function pod dispatch limits through async jobs and the channel API.""" + +from __future__ import annotations + +import asyncio +import json +import os +from itertools import product +from typing import TYPE_CHECKING, cast + +import pytest + +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.sources import DictSource +from orcapod.system_constants import constants +from orcapod.types import ( + DEFAULT_FUNCTION_POD_CONCURRENCY_CAP, + PipelineConfig, + PodConfig, +) + +if TYPE_CHECKING: + from collections.abc import Iterator + + import pyarrow as pa + + from orcapod.protocols.core_protocols import DataProtocol, TagProtocol + +ROW_COUNT = 24 + + +def _source(reverse: bool, *, tag_only: bool | list[str] = True) -> DictSource: + """Build rows with the requested tag roles in either layout.""" + rows = [ + {"group": f"g{i % 3}", "row": i, "x": i * 2, "y": i + 1} + for i in range(ROW_COUNT) + ] + tag_columns = ["group", "row"] + if reverse: + rows = [dict(reversed(list(row.items()))) for row in rows] + tag_columns.reverse() + return DictSource( + data=rows, tag_columns=tag_columns, tag_only_columns=tag_only, source_id="rows" + ) + + +class _Calls: + def __init__(self, *, reverse_outputs: bool = False) -> None: + self.active: int = 0 + self.peak: int = 0 + self.reverse_outputs: bool = reverse_outputs + + async def add(self, x: int, y: int) -> int: + """Yield while active so work from the job's next channel batch overlaps.""" + self.active += 1 + self.peak = max(self.peak, self.active) + try: + await asyncio.sleep(0) + await asyncio.sleep(0) + await asyncio.sleep(0) + return x + y + finally: + self.active -= 1 + + async def add_and_subtract(self, x: int, y: int) -> tuple[int, int]: + """Return the same named outputs in either declaration order.""" + total = await self.add(x, y) + difference = x - y + return (difference, total) if self.reverse_outputs else (total, difference) + + +def _node_identity( + node: FunctionJobNode, table: pa.Table +) -> tuple[str, str, tuple[str, ...]]: + """Capture the two hashes and the source's system-tag column names.""" + system_tags = tuple( + name + for name in table.column_names + if name.startswith(constants.SYSTEM_TAG_PREFIX) + ) + assert len(system_tags) == 2 + return ( + node.content_hash().to_string(), + node.pipeline_hash().to_string(), + system_tags, + ) + + +@pytest.mark.parametrize( + ("cpu_count", "default_peak"), [(4, 4), (64, DEFAULT_FUNCTION_POD_CONCURRENCY_CAP)] +) +@pytest.mark.parametrize( + ("tag_only", "multiple_outputs"), + [ + pytest.param(True, False, id="single-output"), + pytest.param(True, True, id="plain-tags"), + pytest.param(["row"], True, id="mixed-tags"), + pytest.param([], True, id="data-tags"), + ], +) +def test_async_job_bounds_calls_and_preserves_sync_results( + monkeypatch: pytest.MonkeyPatch, + cpu_count: int, + default_peak: int, + tag_only: bool | list[str], + multiple_outputs: bool, +) -> None: + """Exercise default, numeric and unlimited dispatch through a real job.""" + monkeypatch.setattr(os, "process_cpu_count", lambda: cpu_count, raising=False) + expected_rows = [ + {"group": f"g{i % 3}", "row": i, "total": 3 * i + 1} for i in range(ROW_COUNT) + ] + if multiple_outputs: + for i, row in enumerate(expected_rows): + row["difference"] = i - 1 + + dispatch_settings = [ + (PodConfig(max_concurrency=3), 3), + (PodConfig(max_concurrency=None), ROW_COUNT), + (None, default_peak), + ] + baseline_identity: tuple[str, str, tuple[str, ...]] | None = None + for reverse, (config, expected_peak) in product((False, True), dispatch_settings): + output_keys = ["total", "difference"] if multiple_outputs else ["total"] + if reverse: + output_keys.reverse() + tag_order = ["row", "group"] if reverse else ["group", "row"] + data_tags = ( + [tag for tag in tag_order if tag not in tag_only] + if isinstance(tag_only, list) + else [] + ) + expected_data_keys = [*data_tags, *output_keys] + columns = [*tag_order, *output_keys] + + calls = _Calls(reverse_outputs=reverse) + function = calls.add_and_subtract if multiple_outputs else calls.add + pod = FunctionPod.from_fn(function, output_keys=output_keys, pod_config=config) + job = PipelineJob(name="concurrency", database=InMemoryArrowDatabase()) + with job: + _ = pod(_source(reverse, tag_only=tag_only), label="add") + + async def run() -> None: + async with asyncio.timeout(60): + _ = await job.run_async() + + asyncio.run(run()) + async_node = cast(FunctionJobNode, job.nodes["add"]) + assert list(async_node.keys()[1]) == expected_data_keys + async_table = async_node.as_table(columns={"system_tags": True}) + assert async_table.select(columns).sort_by("row").to_pylist() == expected_rows + async_identity = _node_identity(async_node, async_table) + if baseline_identity is None: + baseline_identity = async_identity + # Only presentation order changes when the layout and equally typed outputs reverse. + assert async_identity == baseline_identity, (reverse, config) + assert calls.peak == expected_peak, config + + # A fresh store ensures that the sync run calls the function again. + calls.peak = 0 + sync_job = PipelineJob(name="concurrency", database=InMemoryArrowDatabase()) + with sync_job: + _ = pod(_source(reverse, tag_only=tag_only), label="add") + _ = sync_job.run() + sync_node = cast(FunctionJobNode, sync_job.nodes["add"]) + assert list(sync_node.keys()[1]) == expected_data_keys + sync_table = sync_node.as_table(columns={"system_tags": True}) + assert sync_table.select(columns).sort_by("row").to_pylist() == expected_rows + assert _node_identity(sync_node, sync_table) == baseline_identity, ( + reverse, + config, + ) + assert calls.peak == 1 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("reverse", [False, True]) +async def test_pod_concurrency_takes_precedence_over_pipeline(reverse: bool) -> None: + """Count actual calls through the async API that accepts PipelineConfig.""" + for config, pipeline_limit, expected_peak in [ + (PodConfig(), 4, 4), + (PodConfig(max_concurrency=3), 4, 3), + (PodConfig(), None, ROW_COUNT), + (PodConfig(max_concurrency=None), 4, ROW_COUNT), + ]: + calls = _Calls() + pod = FunctionPod.from_fn(calls.add, output_keys="total", pod_config=config) + input_channel: Channel[tuple[TagProtocol, DataProtocol]] = Channel( + buffer_size=ROW_COUNT + ) + output_channel: Channel[tuple[TagProtocol, DataProtocol]] = Channel( + buffer_size=ROW_COUNT + ) + for row in cast( + "Iterator[tuple[TagProtocol, DataProtocol]]", _source(reverse).iter_data() + ): + await input_channel.writer.send(row) + await input_channel.writer.close() + + async with asyncio.timeout(60): + await pod.async_execute( + [input_channel.reader], + output_channel.writer, + pipeline_config=PipelineConfig(default_max_concurrency=pipeline_limit), + ) + rows = await output_channel.reader.collect() + actual = [ + (tag.as_dict()["row"], tag.as_dict()["group"], data.as_dict()["total"]) + for tag, data in rows + ] + assert sorted(actual) == [(i, f"g{i % 3}", 3 * i + 1) for i in range(ROW_COUNT)] + assert calls.peak == expected_peak, (config, pipeline_limit) + + +def add(x: int, y: int) -> int: + """Importable function for the public config round trip.""" + return x + y + + +def test_function_pod_concurrency_config_round_trip() -> None: + """Preserve omission and numbers while round-tripping explicit unlimited.""" + cases: list[tuple[PodConfig | None, dict[str, int | None] | None]] = [ + (None, None), + (PodConfig(max_concurrency=3), {"max_concurrency": 3}), + (PodConfig(max_concurrency=None), {"max_concurrency": None}), + ] + for config, expected in cases: + pod = FunctionPod.from_fn(add, output_keys="total", pod_config=config) + saved = json.dumps(pod.to_config()) + payload = cast(dict[str, object], json.loads(saved)) + assert payload["pod_config"] == expected + restored = FunctionPod.from_config(payload) + assert json.dumps(restored.to_config()) == saved + assert restored.pod_config == pod.pod_config diff --git a/tests/test_pipeline/test_job_node_row_hashes.py b/tests/test_pipeline/test_job_node_row_hashes.py index 4cdf9d033..c43e3f941 100644 --- a/tests/test_pipeline/test_job_node_row_hashes.py +++ b/tests/test_pipeline/test_job_node_row_hashes.py @@ -14,9 +14,11 @@ import pytest from orcapod import PipelineJob, function_pod +from orcapod.core.function_pod import FunctionPod from orcapod.databases import InMemoryArrowDatabase from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator from orcapod.sources import DictSource +from orcapod.types import PodConfig N_ROWS = 5 @@ -31,7 +33,6 @@ def double(x: int) -> int: return 2 * x -@function_pod(output_keys="y") async def first_row_last(x: int) -> int: """Return twice ``x``; row 0 finishes only after the last row is computed. @@ -50,7 +51,7 @@ def run_job(pod: Any, rows: list[dict[str, Any]], orchestrator: Any) -> Any: """Run ``pod`` over ``rows`` in a fresh job; return its node.""" job = PipelineJob(name="row_hashes", database=InMemoryArrowDatabase()) with job: - pod.pod( + pod( DictSource( data=rows, tag_columns=["k"], source_id="rows", tag_only_columns=True ), @@ -63,7 +64,7 @@ def run_job(pod: Any, rows: list[dict[str, Any]], orchestrator: Any) -> Any: def sync_with_input_out_of_tag_order() -> Any: """A sync run whose input rows come in reverse tag order.""" rows = [{"k": f"r{i}", "x": i} for i in reversed(range(N_ROWS))] - return run_job(double, rows, SyncPipelineOrchestrator()) + return run_job(double.pod, rows, SyncPipelineOrchestrator()) def async_with_first_row_finishing_last() -> Any: @@ -71,7 +72,10 @@ def async_with_first_row_finishing_last() -> Any: global last_row_computed last_row_computed = asyncio.Event() rows = [{"k": f"r{i}", "x": i} for i in range(N_ROWS)] - return run_job(first_row_last, rows, AsyncPipelineOrchestrator()) + pod = FunctionPod.from_fn( + first_row_last, output_keys="y", pod_config=PodConfig(max_concurrency=N_ROWS) + ) + return run_job(pod, rows, AsyncPipelineOrchestrator()) RUNS = { diff --git a/tests/test_pipeline/test_job_run_in_event_loop.py b/tests/test_pipeline/test_job_run_in_event_loop.py index 5ebc8ac49..563b4e8cc 100644 --- a/tests/test_pipeline/test_job_run_in_event_loop.py +++ b/tests/test_pipeline/test_job_run_in_event_loop.py @@ -24,6 +24,7 @@ import pytest from orcapod import PipelineJob, function_pod +from orcapod.core.function_pod import FunctionPod from orcapod.core.nodes.function_node import ( PIPELINE_RECORDED_AT_COL, PIPELINE_RUN_ID_COL, @@ -32,6 +33,7 @@ from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator from orcapod.pipeline.observer import NoOpObserver from orcapod.sources import DictSource +from orcapod.types import PodConfig # Columns that differ between any two runs by design, also between two script runs: the # result's datagram uuid, the output's source-info token (which carries that uuid) and the @@ -488,7 +490,6 @@ def press_interrupt_once_next_row_returned() -> None: _thread.interrupt_main() -@function_pod(output_keys="y") def stuck_until_next_row_runs(x: int) -> int: """Row 0 presses the interrupt button once the next node's row is in its function.""" if x == 0: @@ -546,11 +547,17 @@ def test_second_interrupt_does_not_name_a_node_whose_function_returned() -> None second_press_helpers.clear() rows = [{"k": f"r{i}", "x": i} for i in range(2)] job = PipelineJob(name="returned_demo", database=InMemoryArrowDatabase()) + # The first row waits for the second, so this test requires both to start. + stuck_pod = FunctionPod.from_fn( + stuck_until_next_row_runs, + output_keys="y", + pod_config=PodConfig(max_concurrency=2), + ) with job: source = DictSource( data=rows, tag_columns=["k"], tag_only_columns=True, source_id="rows" ) - stuck = stuck_until_next_row_runs.pod(source, label="stuck") + stuck = stuck_pod(source, label="stuck") _ = returns_after_the_run_ended.pod(stuck, label="after") async def notebook_cell() -> None: diff --git a/tests/test_pipeline/test_mixed_function_commits.py b/tests/test_pipeline/test_mixed_function_commits.py index ba34f81a8..d5c6b9b64 100644 --- a/tests/test_pipeline/test_mixed_function_commits.py +++ b/tests/test_pipeline/test_mixed_function_commits.py @@ -15,7 +15,8 @@ import pyarrow as pa import pytest -from orcapod import PipelineJob, function_pod +from orcapod import PipelineJob +from orcapod.core.function_pod import FunctionPod from orcapod.databases import ( ConnectorArrowDatabase, DeltaTableDatabase, @@ -29,7 +30,9 @@ from orcapod.system_constants import ( PIPELINE_DB_SCHEMA_VERSION, RESULT_DB_SCHEMA_VERSION, + constants, ) +from orcapod.types import PodConfig from tests.test_databases.test_connector_arrow_database import MockDBConnector Layout = Literal["memory", "delta", "noop", "connector"] @@ -37,7 +40,6 @@ RESULT = RESULT_DB_SCHEMA_VERSION -@function_pod(output_keys="y") async def double(x: int, offset: int) -> int: """Return a stable result with two bound input fields.""" return 2 * x + offset @@ -68,16 +70,21 @@ def make_job( results: ArrowDatabaseProtocol | None = None, *, reverse_order: bool = False, + max_concurrency: int = 5, ) -> PipelineJob: """Build a batch over five rows, with optionally separate result storage.""" job = PipelineJob(name="mixed", database=pipeline) rows = [{"tag": i, "group": "all", "x": i, "offset": i + 10} for i in range(5)] tags = ["tag", "group"] + # The historical batching assertions assume every call can start at once. + pod = FunctionPod.from_fn( + double, output_keys="y", pod_config=PodConfig(max_concurrency=max_concurrency) + ) if reverse_order: rows = [dict(reversed(tuple(row.items()))) for row in rows] tags.reverse() with job: - _ = double.pod( + _ = pod( DictSource( data=rows, tag_columns=tags, tag_only_columns=True, source_id="src" ), @@ -232,6 +239,63 @@ def observe_promotion(db: InMemoryArrowDatabase, path: tuple[str, ...]) -> None: assert job.nodes["out"].as_source().as_table().num_rows == 5 +@pytest.mark.parametrize(("every", "batches"), [(1, [1] * 5), (3, [3, 2])]) +@pytest.mark.parametrize("limit", [1, 2]) +def test_low_async_concurrency_preserves_durable_rows_and_pipeline_commits( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + every: int, + batches: list[int], + limit: int, +) -> None: + """Pipeline commits contain only references to results already on disk.""" + flush_batch = DeltaTableDatabase.flush_batch + durable_rows: dict[int, set[tuple[int, str, int]]] = {} + for concurrency in (5, limit): + pipeline = tmp_path / str(concurrency) / "pipeline" + results = tmp_path / str(concurrency) / "results" + + def check_pipeline_references( + db: DeltaTableDatabase, path: tuple[str, ...] + ) -> None: + flush_batch(db, path) + if path[-1] == PIPELINE: + (pipeline_log,) = pipeline.rglob("_delta_log") + (result_log,) = results.rglob("_delta_log") + pipeline_table = deltalake.DeltaTable(str(pipeline_log.parent)) + result_table = deltalake.DeltaTable(str(result_log.parent)) + references = pipeline_table.to_pyarrow_table( + columns=[constants.DATA_RECORD_ID] + ).column(0) + result_ids = result_table.to_pyarrow_table( + columns=[DeltaTableDatabase.RECORD_ID_COLUMN] + ).column(0) + assert set(references.to_pylist()) <= set(result_ids.to_pylist()) + + with monkeypatch.context() as patch: + patch.setattr(DeltaTableDatabase, "flush_batch", check_pipeline_references) + job = make_job( + DeltaTableDatabase(pipeline), + DeltaTableDatabase(results), + reverse_order=concurrency != 5, + max_concurrency=concurrency, + ) + run(job, True, every) + + assert delta_history(pipeline, PIPELINE) == commits_of(batches) + reopened = make_job(DeltaTableDatabase(pipeline), DeltaTableDatabase(results)) + table = reopened.nodes["out"].as_source().as_table() + durable_rows[concurrency] = { + (row["tag"], row["group"], row["y"]) for row in table.to_pylist() + } + + assert ( + durable_rows[limit] + == durable_rows[5] + == {(i, "all", 3 * i + 10) for i in range(5)} + ) + + @pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"]) def test_shared_in_memory_store_keeps_whole_flush_count( asynchronous: bool, monkeypatch: pytest.MonkeyPatch diff --git a/tests/test_pipeline/test_node_head_sorting.py b/tests/test_pipeline/test_node_head_sorting.py index 00ee0cabf..e705c70e7 100644 --- a/tests/test_pipeline/test_node_head_sorting.py +++ b/tests/test_pipeline/test_node_head_sorting.py @@ -17,6 +17,7 @@ import pytest from orcapod import PipelineJob, function_pod +from orcapod.core.function_pod import FunctionPod from orcapod.core.nodes import OperatorJobNode from orcapod.core.operators import SelectDataColumns from orcapod.core.sources import ArrowTableSource @@ -24,7 +25,7 @@ from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator from orcapod.protocols.database_protocols import ArrowDatabaseProtocol from orcapod.streams import ViewStatus -from orcapod.types import CacheMode +from orcapod.types import CacheMode, PodConfig N_ROWS = 6 @@ -54,7 +55,6 @@ def triple(x: int) -> int: return 3 * x -@function_pod(output_keys="y") async def triple_last_row_first(x: int) -> int: """Triple ``x``; row ``i`` finishes only after row ``i + 1``, so rows complete in reverse tag order. The wait is bounded so a failure is a missing row, not a hang.""" @@ -65,6 +65,13 @@ async def triple_last_row_first(x: int) -> int: return 3 * x +REVERSE_TRIPLE = FunctionPod.from_fn( + triple_last_row_first, + output_keys="y", + pod_config=PodConfig(max_concurrency=N_ROWS), +) + + def _source(order: list[int]) -> ArrowTableSource: """A source of rows ``id`` and ``x`` in the given order (non-nullable ``int64``).""" table = pa.table( @@ -90,7 +97,7 @@ def _store(kind: str, tmp_path: Path) -> ArrowDatabaseProtocol: def _build(pod: Any, store: ArrowDatabaseProtocol, order: list[int]) -> PipelineJob: job = PipelineJob(name="itl1053", database=store) with job: - pod.pod(_source(order), label="node") + pod(_source(order), label="node") return job @@ -102,11 +109,11 @@ def _run(kind: str, store: ArrowDatabaseProtocol) -> PipelineJob: """ gates.clear() if kind == "sync": - job = _build(triple, store, list(reversed(range(N_ROWS)))) + job = _build(triple.pod, store, list(reversed(range(N_ROWS)))) job.run(orchestrator=SyncPipelineOrchestrator()) return job gates.extend(asyncio.Event() for _ in range(N_ROWS)) - job = _build(triple_last_row_first, store, list(range(N_ROWS))) + job = _build(REVERSE_TRIPLE, store, list(range(N_ROWS))) job.run(orchestrator=AsyncPipelineOrchestrator()) return job @@ -130,7 +137,7 @@ def test_a_function_nodes_head_is_the_prefix_of_as_table_in_any_completion_order assert _held_order(job.nodes["node"]) != sorted(_held_order(job.nodes["node"])) CALLS.clear() fresh = _build( - triple if run_kind == "sync" else triple_last_row_first, + triple.pod if run_kind == "sync" else REVERSE_TRIPLE, store, list(range(N_ROWS)), ) @@ -225,13 +232,17 @@ def _tie_run(kind: str) -> Any: job.run(orchestrator=SyncPipelineOrchestrator()) else: gates.extend(asyncio.Event() for _ in range(len(TIE_KEYS))) + pod = FunctionPod.from_fn( + tie_last_row_first, + output_keys="y", + pod_config=PodConfig(max_concurrency=len(TIE_KEYS)), + ) with job: - tie_last_row_first.pod(_tie_source(), label="node") + _ = pod(_tie_source(), label="node") job.run(orchestrator=AsyncPipelineOrchestrator()) return job.nodes["node"] -@function_pod(output_keys="y") async def tie_last_row_first(x: int) -> int: """Triple ``x``; row ``i`` finishes after row ``i + 1`` (reverse completion).""" if x + 1 < len(TIE_KEYS): @@ -283,7 +294,9 @@ def test_a_nodes_preview_is_the_same_after_any_completion_order( ) -> None: """The preview of a node shows tag order: reversed completion looks like a sync run.""" # A sync run over input in tag order holds its rows in tag order. - ascending = _build(triple, _store(store_kind, tmp_path / "a"), list(range(N_ROWS))) + ascending = _build( + triple.pod, _store(store_kind, tmp_path / "a"), list(range(N_ROWS)) + ) ascending.run(orchestrator=SyncPipelineOrchestrator()) sync_node = ascending.nodes["node"] async_node = _run("async", _store(store_kind, tmp_path / "b")).nodes["node"] diff --git a/tests/test_pipeline/test_node_staleness_after_run.py b/tests/test_pipeline/test_node_staleness_after_run.py index d22a69f67..461a53602 100644 --- a/tests/test_pipeline/test_node_staleness_after_run.py +++ b/tests/test_pipeline/test_node_staleness_after_run.py @@ -23,7 +23,6 @@ import pyarrow as pa import pytest -from orcapod import function_pod from orcapod.channels import Channel from orcapod.core.function_pod import FunctionPod from orcapod.core.nodes import FunctionJobNode @@ -35,7 +34,7 @@ from orcapod.pipeline.sync_orchestrator import SyncPipelineOrchestrator from orcapod.protocols.database_protocols import ArrowDatabaseProtocol from orcapod.streams import ViewStatus -from orcapod.types import CacheMode +from orcapod.types import CacheMode, PodConfig # The input order of A's rows (not in tag order), and the order the async rows complete # in when the gate is armed: the reverse. @@ -109,7 +108,6 @@ def finish(self, key: int) -> None: GATE = _ReverseGate() -@function_pod(output_keys="y") async def scale(id_: int, x: int) -> int: """Return ``10 * x``, completing in the gate's order; counts every call.""" await GATE.wait_turn(id_) @@ -118,6 +116,11 @@ async def scale(id_: int, x: int) -> int: return 10 * x +SCALE_POD = FunctionPod.from_fn( + scale, output_keys="y", pod_config=PodConfig(max_concurrency=len(COMPLETION_ORDER)) +) + + @pytest.fixture(autouse=True) def _reset() -> Iterator[None]: """Clear the call record and leave the gate disarmed around each test.""" @@ -170,7 +173,7 @@ def _job(store: ArrowDatabaseProtocol) -> PipelineJob: ) job = PipelineJob(name="itl1042", database=store) with job: - scaled = scale.pod(a, label="scaled") + scaled = SCALE_POD(a, label="scaled") Join()(scaled, b, label="joined") GroupBy(by=["g"])(scaled, label="grouped") # OperatorNode.attach_databases is the public way to store an operator's rows. @@ -320,10 +323,8 @@ def test_a_function_node_is_stamped_before_its_output_closes(with_store: bool) - tag_only_columns=True, ) store = InMemoryArrowDatabase() if with_store else None - pod = scale.pod - assert isinstance(pod, FunctionPod) node = FunctionJobNode( - pod, + SCALE_POD, source, pipeline_database=store, result_database=store,