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
10 changes: 10 additions & 0 deletions changelog.d/ITL-1474.md
Original file line number Diff line number Diff line change
@@ -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"`.
50 changes: 49 additions & 1 deletion docs/concepts/function-pods.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
6 changes: 6 additions & 0 deletions docs/concepts/pipeline-job.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
@@ -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.
6 changes: 6 additions & 0 deletions docs/troubleshooting.md
Original file line number Diff line number Diff line change
Expand Up @@ -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=`.
Expand Down
4 changes: 2 additions & 2 deletions src/orcapod/core/function_pod.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down Expand Up @@ -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,
}
Expand Down
42 changes: 29 additions & 13 deletions src/orcapod/types/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -341,15 +341,29 @@ 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.

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.
Expand All @@ -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

Expand All @@ -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)
Expand Down Expand Up @@ -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}")
Expand Down
2 changes: 1 addition & 1 deletion tests/test_channels/test_async_execute.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
13 changes: 8 additions & 5 deletions tests/test_channels/test_channels.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
from __future__ import annotations

import asyncio
import os

import pytest

Expand Down Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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
2 changes: 1 addition & 1 deletion tests/test_channels/test_copilot_review_issues.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
2 changes: 0 additions & 2 deletions tests/test_core/alignment/gate.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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)
Expand Down
Loading
Loading