Mapping¶
A mapped task runs once per element of a list: one instance per file, per region, per customer. The list can be written in the DAG file or come from an upstream task’s output, so the number of instances is known only when the run gets there.
"""Mapping: one task instance per element, lanes, and gathering the results."""
from collections.abc import Sequence
from schedr import Dag, Data, RunIf, task
class Rows(Data):
"""A file's rows."""
count: int
class Missing(Data):
"""A file that isn't there."""
reason: str
@task
def list_files() -> list[str]:
return ["a.csv", "missing.csv", "orders.csv"]
@task
def fetch(bucket: str, path: str) -> Rows | Missing:
# An expected problem is an outcome, not an exception: the instance succeeds with
# `Missing`, and every gather downstream still runs. An uncaught exception would fail
# the step and cancel the other instances.
if path.startswith("missing"):
return Missing(reason=f"{bucket}/{path} not found")
return Rows(count=len(path))
@task
def count(rows: Rows) -> int:
return rows.count
@task
def total(counts: Sequence[int | None]) -> int:
# `count` was skipped where `fetch` ended `Missing`: `None` in its place. (A `Sequence`:
# type checkers read `count.expand(...)` as a `list[int]`, not knowing which are skipped.)
return sum(c for c in counts if c is not None)
@task
def count_any(result: Rows | Missing) -> int | None:
# Deciding in the task, on the whole union: no instance is skipped.
return result.count if isinstance(result, Rows) else None
@task
def report(results: list[Rows | Missing]) -> list[str]:
# The whole union of every instance, in the order of the files.
return [r.reason for r in results if isinstance(r, Missing)]
with Dag(
"mapped", description="Runs one task per element of a list, in lanes, and gathers the results."
):
# One `fetch` per file, the bucket fixed for all of them.
results = fetch.partial(bucket="raw").expand(path=list_files())
# Lanes: `count[i]` starts as soon as `fetch[i]` ends `Rows`; for `Missing` it is
# skipped. `total` (the gather) waits for all of them.
total(count.expand(rows=results.on(Rows)))
# All or nothing: with ALL_SUCCEEDED one skipped instance skips the whole task (and the
# gather after it), so `strict_total` runs only if every file had rows.
strict = count.override(task_id="strict_count", run_if=RunIf.ALL_SUCCEEDED)
total.override(task_id="strict_total")(strict.expand(rows=results.on(Rows)))
# Gather everything: map without narrowing, and decide in the task.
total.override(task_id="total_any")(count_any.expand(result=results))
report(results)
Mapping a task¶
.partial(...) fixes the arguments every instance shares; .expand(...) names the ones
that vary, each a list. fetch.partial(bucket="raw").expand(path=list_files()) runs one
fetch per file, each with bucket="raw".
Several mapped lists give every combination:
.expand(region=["eu", "us"], day=[1, 2])makes four instances, the first argument written varying slowest (eu/1,eu/2,us/1,us/2)..expand_kwargs(...)maps over a list of dicts, each one instance’s arguments. A list written in the file is checked when the file loads: every element is a dict (a reference element is left to its type), each key is a parameter, a key also passed to.partial()is refused, the fixed arguments and the dict together supply every required parameter, and each value matches that parameter’s type. The list itself must be alist[dict[str, Any]], written out or taken from an upstream task. A reference is not checked element by element at load. When the task waits for that output as a whole, an element that is not a dict fails the whole task when it expands, before any instance runs. When the list is another mapped task’s instances one by one (a lane), it fails that one instance when the instance is assigned, asinput_mismatch, and that failure is not retried.What
.expand()maps over is checked when the file loads: each list against the parameter’s type (path: strneeds alist[str]), names that exist, nothing both fixed and mapped.An element can be a t-string or a run context value, like an argument:
region.expand(name=[t"eu-{year}", "us"])giveseu-2026andus, and.expand(of=[dag_ctx.run.kind, "other"])the run’s kind andother. So can a value in an.expand_kwargs()dict. Each is built when its instance starts, from the outputs it references, exactly as the same t-string passed as an argument. One element may be a run parameter (.expand(name=[dag_ctx.params.region, "us"])). The list itself cannot (fetch.expand(path=dag_ctx.params.paths)): the number of instances can’t depend on the run’s parameters (Run parameters).The instances are numbered from 0 in that order (their
map_index). They run in parallel as worker slots allow, and each retries on its own.An empty list runs no instance: the task succeeds, and its output is
[].At most
[mapping] max_instancesinstances (1024 by default, a server setting); past it, the task fails without running any and says why.
A mapped task’s output is the list of its instances’ outputs, in their order. For type
checkers .expand(...) returns schedr.Mapped[R], a list[R] that also has .on(...) for
mapping over it element by element: index it (results[0]) or pass it whole to a task
taking a list.
Lanes: mapping over a mapped output¶
Mapping over another mapped task’s whole output pairs the instances element by element:
count.expand(rows=results.on(Rows)) gives count[i] the output of fetch[i]. Each pair is a
lane, and lanes move on their own: count[0] starts as soon as fetch[0] is done,
without waiting for the slowest file.
.on(...)works per element inside.expand(): an instance whose upstream instance ended with another outcome is skipped, and its place in the list isNone.To wait for all of them first, add an order edge from the whole task:
chain(results, counts)(the two mapped outputs) next to the expansion. Then nothing ofcountstarts before everyfetchhas finished, and nothing of it runs if one failed.Using the upstream task anywhere else in the same task (
.partial(all=results),results[0]) also makes it wait for the whole task..on(...)still goes per element then:count.partial(all=results).expand(rows=results.on(Rows))starts once everyfetchhas finished and skips the instances whosefetchended with another outcome..on(...)before>>waits for the whole task and asks its instances:results.on(Rows) >> report()counts one edge per instance, taken when that instance endedRows, andreport’srun_ifdecides as over any edges. With the defaultRunIf.NONE_FAILED,reportruns when any instance endedRows; withrun_if=RunIf.ALL_SUCCEEDED, only when every one did. An empty list takes the edge.
Gathering¶
A task that takes the whole list (total(counts)) is a gather: it waits for every
instance, then receives their outputs in order.
The instances |
The mapped task |
The gather |
|---|---|---|
all succeeded |
success |
runs, with every output |
some skipped |
success |
runs, with |
all skipped |
skipped |
skipped, as after any skipped task |
none (an empty list) |
success |
runs, with |
one failed after its retries |
failed at once: the other instances are cancelled, running ones stopped |
|
A gather that may receive None takes a Sequence[int | None] rather than a
list[int | None]: type checkers read the mapped output as a list[int] (they can’t know
which instances will be skipped), and a list parameter accepts only its exact element
type, a Sequence any narrower one.
All or nothing: with run_if=RunIf.ALL_SUCCEEDED on the mapped task, one skipped instance
skips the whole task, and so its gather: the gather gets every result or doesn’t run. A
mapped task applies its run_if to its instances the way any task applies it to its
upstream edges.
Gathering everything¶
A gather sees every instance only if none of them is skipped, and none of them fails:
Don’t narrow, decide in the task.
.on(Rows)skips the instances that ended otherwise. Mapping over the whole union (count_any.expand(result=results), takingRows | Missing) runs every instance, and the task decides what each one means.report(results)takes the whole union of every instance the same way.Return expected problems as outcomes, don’t raise them.
fetchreturnsMissingfor a file that isn’t there: the instance succeeds, and the gather receives theMissing. An uncaught exception is a real failure: it fails the step, cancels the other instances, and the gather doesn’t run. That is on purpose: a failure means the step failed.
How many at once¶
Instances become ready when their inputs and upstream edges allow it. A lane can become
ready before the other lanes. Ready instances take free slots on workers serving the queue,
subject to the DAG’s and task’s concurrency limits. @task(max_active_per_run=10) runs at
most 10 of them at once in a run, and max_active at most so many across runs (Concurrency
limits).
Following the instances¶
Inside a task,
task_ctx.map_indexis the instance’s index (Nonefor a task that isn’t mapped), andtask_ctx.try_numberits attempt (The DAG context). A command getsSCHEDR_MAP_INDEX. The run’s parameters and run information are read withschedr dag-ctx(Reading the run from a command).In the UI, a mapped task is one node, labelled with its instance count (
fetch ×3) and how many are done and how many failed. Its panel opens on the Instances tab; each instance’s own panel has that instance’s attempts, log and output. The whole task’s output is the gathered list. The web UI explains those panels.In the API, a run’s tasks list each mapped task as a whole (
map_index: -1,instances: 3) and then its instances.?map_index=-1means the same as leaving the index off: the task as a whole. A task’soutputwithout?map_index(or with-1) is the gathered list, with?map_index=1that instance’s;attempts,logandretryneed?map_indexfor a mapped task;cancelwithout it, or with-1, cancels the whole task. An index outside0toN-1is a 400, on every one of those endpoints, cancel included.In the CLI,
schedr tasks logs / attempts / output / cancel / retrytake--map-index N:logs,attemptsandretryneed it for a mapped task;outputwithout it prints the gathered list, andcancelwithout it cancels the whole task. A resource cleanup can also be cancelled as a task; see Resources.schedr runs showandschedr dags testlist the instances asfetch[0],fetch[1], … after the task.In tests,
run_dag(...).tasks["fetch"]is the whole task (itsoutputthe list) andtasks["fetch"][1]an instance (Testing a DAG).
.partial() and .expand() work on @task functions and
TriggerDagOperator. CommandOperator,
ScriptOperator and EmptyOperator cannot be mapped. Wait steps aren’t mapped either.
Mapping a command or a script¶
There are two ways to run a command or script per element. For many small calls, map a Python task that starts the process:
"""Run a small command per element in mapped Python tasks."""
import subprocess
from schedr import Dag, task
@task
def run_command(name: str) -> str:
completed = subprocess.run(
["printf", "hello %s", name], check=True, capture_output=True, text=True
)
return completed.stdout
with Dag("mapped_process", description="Runs a small command for each element of a list."):
run_command.expand(name=["eu", "us"])
A non-zero exit fails the task with check=True; catch the exception and return an outcome
if the DAG should route it. The task’s output is what the function returns, not a
ProcessResult; without capture, stdout and stderr go to the task’s log. The function
builds its environment from the connections and secrets it declares, rather than using
env= templates and connection variables. Run a script file by its path: a Python task’s
subprocess cannot use ScriptOperator’s schedr.toml jobs or schedr.script’s dag_ctx;
pass the process what it needs as arguments.
Alternatively, map a TriggerDagOperator to a target DAG with trigger=Chained(by=[...])
and a dataclass for params. Unpause the target DAG before starting the source run. The
target runs a CommandOperator or ScriptOperator on dag_ctx.params:
"""Start a chained command run per region and gather the run IDs."""
from dataclasses import dataclass
from schedr import (
Chained,
CommandOperator,
Dag,
Failed,
TimedOut,
TriggerDagOperator,
dag_ctx,
task,
)
@dataclass
class RegionParams:
"""The target's params: the region to greet."""
region: str = "eu"
@task
def regions() -> list[dict[str, str]]:
return [{"region": "eu"}, {"region": "us"}]
@task
def successful_ids(results: list[str | Failed | TimedOut]) -> list[str]:
return [result for result in results if isinstance(result, str)]
with Dag(
"region_command",
description="Runs a command for the region a mapped_regions run asks for.",
trigger=Chained(by=["mapped_regions"]),
params=RegionParams,
):
region: str = dag_ctx.params.region # pyright: ignore[reportAny]
CommandOperator("greet", command=["printf", "hello %s", region])
with Dag(
"mapped_regions",
description="Starts a region_command run per region and gathers their run IDs.",
):
runs = TriggerDagOperator.partial("start_regions", dag="region_command").expand(
params=regions()
)
successful_ids(runs.output)
This keeps the operator’s ProcessResult, exit-code outcomes, schedr.toml jobs and
env= templates. It costs a run per element and a second DAG with its params; use it when
each call deserves its own run, retries and history. For a list known when the DAG file
loads, a for loop can instead create one operator per element, each with a distinct ID.