Parallelize one Task over many inputs#
Use Task.map when the same Task should process many independent values. Instead of calling .remote() in a loop, map supplies inputs to separate remote executions and streams their results through one lazy iterator.
@app.task()
def square(value: int) -> int:
return value * value
@app.entrypoint()
def main() -> None:
for result in square.map([1, 2, 3, 4]):
print(result)
This prints 1, 4, 9, and 16 in input order. The iterator submits work as it is consumed, while keeping the amount of accepted work that has not yet been delivered bounded.
map is not a separate distributed batch object or a new execution authority. Each consumed input becomes an ordinary Yak Task invocation with the same normal remote lifecycle, result, and failure behavior. The map operation is an SDK-side coordinator that consumes inputs lazily, accepts independent invocations into a bounded window, waits for results, controls delivery order, and cleans up accepted unfinished work when the operation closes or aborts.
Sync and async iteration#
The synchronous form returns a lazy MapIterator and works with a normal for loop:
for result in square.map(range(1, 6)):
print(result)
The asynchronous form is available as Task.map.aio. It returns an AsyncMapIterator for async for:
async def main() -> None:
results = square.map.aio(range(1, 6))
try:
async for result in results:
print(result)
finally:
await results.aclose()
Use the async form naturally inside an async @app.entrypoint(): it lets the entrypoint yield control while it waits for remote results. The synchronous form is useful in synchronous code, but it must be consumed from the thread and event loop that own the Yak client. The generated Task.map reference contains the exact arguments, defaults, and return types.
The canonical executable example rendered below is the site-owned parallel_task_map.py. Run it with:
yak run parallel_task_map.py
Multiple callable arguments#
Map accepts multiple input iterables and passes one value from each iterable to each Task invocation. The inputs are consumed in lockstep:
@app.task()
def multiply(left: int, right: int) -> int:
return left * right
lefts = [2, 3, 4]
rights = [10, 10, 10]
for result in multiply.map(lefts, rights):
print(result)
The rows are paired as lefts[0] with rights[0], then lefts[1] with rights[1], and so on. Input iterables are expected to have equal lengths. When all input lengths are known and differ, the iterator raises ValueError before submitting rows. If a generator reveals a mismatch only while it is being consumed, ValueError is raised when that mismatch is detected.
Use kwargs for keyword arguments shared by every invocation:
@app.task()
def label(value: int, prefix: str) -> str:
return f"{prefix}-{value}"
for result in label.map([1, 2, 3], kwargs={"prefix": "item"}):
print(result)
For the complete parameter types and defaults, use the generated Task.map reference .
Ordered vs completion-order results#
Map yields results in input order by default, even when a later invocation finishes first. Set order_outputs=False when the consumer should receive each result as soon as its invocation completes.
inputs: A B C
finish order: B C A
ordered: A B C
unordered: B C A
Unordered delivery changes only when results are yielded. It does not change which input was sent to which invocation or the value associated with that input.
for result in work.map(inputs, order_outputs=False):
handle_ready_result(result)
order_outputs and its default are defined on the generated Task.map reference .
Laziness and bounded work#
Map does not greedily consume an arbitrarily large producer and submit every value at once. The max_in_flight option controls the map operation's accepted-but-not-yet-delivered window; its default is 32.
This makes generators practical for large or open-ended input streams:
def records():
for index in range(1_000_000):
yield index
results = process.map.aio(records(), max_in_flight=16)
try:
async for result in results:
await store(result)
finally:
await results.aclose()
The window keeps client-side memory bounded, avoids flooding Yak with all work immediately, and stops input consumption from continuing indefinitely when the consumer pauses. A result that has finished but is still waiting to be delivered still occupies the window, so a fast producer cannot outrun a slow consumer without bound.
max_in_flight must be a positive integer. It is a limit for this map operation's accepted-undelivered window, not a global concurrency limit for Yak or a promise that every accepted invocation is executing at the same time.
Failures#
By default, an invocation failure is raised while the corresponding map result is delivered and the map operation aborts. Accepted unfinished invocations owned by that map are cleaned up according to the map operation's ownership rules.
@app.task()
def maybe_fail(value: int) -> int:
if value == 0:
raise ValueError("zero is not valid")
return 10 // value
try:
for result in maybe_fail.map([2, 0, 4]):
print(result)
except Exception as error:
print("map stopped:", error)
Set return_exceptions=True when the caller needs to process each input outcome independently. Successful rows yield their value; failed rows yield an exception object instead of raising it immediately.
results = maybe_fail.map.aio([2, 0, 4], return_exceptions=True)
try:
async for outcome in results:
if isinstance(outcome, Exception):
print("failed:", outcome)
else:
print("value:", outcome)
finally:
await results.aclose()
The returned exception is the public Invocation error for that row, not a new map-specific result type. See the generated InvocationExecutionError , InvocationCancelledError , and InvocationTimedOutError references for the failure types exposed by the SDK.
Stopping early and cancellation#
If the consumer does not intend to consume the entire map, close the iterator explicitly. Closing stops input consumption and requests cancellation of accepted unfinished invocations owned by that map.
For synchronous iteration:
results = process.map(inputs)
try:
for result in results:
print(result)
if result >= 100:
break
finally:
results.close()
For asynchronous iteration:
results = process.map.aio(inputs)
try:
async for result in results:
print(result)
if result >= 100:
break
finally:
await results.aclose()
Explicit close gives the caller deterministic cleanup. Merely abandoning a Python iterator is not the recommended cancellation mechanism. The synchronous close() and asynchronous aclose() methods are part of the map iterator returned from Task.map .
Backpressure and slow consumers#
Remote invocations may finish faster than the caller can process their results. Map keeps the accepted-but-not-yet-delivered window bounded in that case. Once the window is full, it does not keep pulling from the input iterables or submitting more rows just because the producer has more values available.
Map refills the window when the consumer asks for another result. This is the backpressure boundary: a paused consumer pauses further input consumption and submission, while already accepted invocations continue through their ordinary Task lifecycles.
map vs calling .remote() yourself#
Use map when:
- the same Task should process many independent inputs;
- the caller wants bounded fan-out instead of managing a submission loop;
- results should be streamed incrementally; or
- ordered or completion-order delivery is useful.
Call .remote() or .remote_async() yourself when each invocation needs different control flow, per-invocation handles, different argument construction, or independent cancellation and result handling. Both approaches submit ordinary Yak Task invocations; map adds the lazy input, bounded-window, ordering, failure, and cleanup behavior around that repeated work.
Exact API surface#
This guide focuses on how to choose and consume a map operation. The generated Task.map reference is authoritative for signatures, parameter types, defaults, and the public map/map.aio call surfaces.