Routing by outcome¶
Every task reports which kind of success it had: its outcome. Downstream tasks route
on it with .on(...). An expected problem is a success path (a caught connection error
returned as Unavailable; a command’s declared exit code). An uncaught exception, or an
exit code the task did not declare, is a failure. schedr retries it if configured, then
fails the run if it still fails. Notifications depend on the DAG’s and server’s notification
settings.
This DAG fetches from two sources, loads whichever returned Rows, reports a mirror
outage, routes a command’s exit code, and a @branch chooses a subset of its downstream
tasks.
"""Routing by outcome: a union of dataclasses, a command's exit codes, and a branch."""
from schedr import (
CommandOperator,
Dag,
Data,
EmptyOperator,
Outcome,
RunIf,
Task,
branch,
task,
)
class Rows(Data, frozen=True):
"""Rows fetched from one source."""
rows: list[dict[str, str]]
class Unavailable(Data, frozen=True):
"""The source could not be reached."""
reason: str
class Check(Outcome):
"""What the probe found: each member is the exit code that means it."""
CHANGED = 0
UNCHANGED = 1
with Dag(
"route_by_outcome",
description="Routes work by a task's outcome and a command's exit code.",
trigger=None,
):
@task
def fetch() -> Rows | Unavailable:
return Rows([{"id": "1", "name": "Ada"}])
@task
def fetch_mirror() -> Rows | Unavailable:
return Unavailable("mirror down")
@task
def load(primary: Rows | None, mirror: Rows | None) -> int:
batch = primary or mirror
assert batch is not None
print(f"loading {len(batch.rows)}")
return len(batch.rows)
@task
def report_outage(outage: Unavailable) -> None:
print(outage.reason)
@task
def react(outcome: Check) -> str:
print(outcome.name)
return outcome.name
@task
def to_s3() -> None:
print("s3")
@task
def to_gcs() -> None:
print("gcs")
primary = fetch()
mirror = fetch_mirror()
count = load(primary.on(Rows), mirror.on(Rows))
report_outage(mirror.on(Unavailable))
probe = CommandOperator("probe", command="exit 0", outcomes=Check)
probe.on(Check.CHANGED) >> EmptyOperator("changed")
probe.on(Check.UNCHANGED) >> EmptyOperator("unchanged")
react(probe.outcome)
s3 = to_s3()
gcs = to_gcs()
@branch
def dest() -> list[Task]:
return [s3]
chosen = dest()
count >> chosen
chosen >> [s3, gcs]
done = EmptyOperator("done")
[s3, gcs] >> done
all_ok = EmptyOperator("all_ok", run_if=RunIf.ALL_SUCCEEDED)
[s3, gcs] >> all_ok
load runs because fetch returned Rows (fetch_mirror returned Unavailable, so
that argument is None). report_outage runs on the mirror. probe exits 0, which
Check declares as CHANGED, so changed runs and unchanged is skipped. dest
returns s3, so to_s3 runs and to_gcs is skipped; done still runs
(RunIf.NONE_FAILED), all_ok is skipped (RunIf.ALL_SUCCEEDED).
Declaring outcomes¶
Every task declares outcome names, either implicitly from its return type or explicitly
with an Outcome enum. The backend stores the name; the classes and enums exist only
in Python.
How it is declared |
Outcome names |
Stored |
|---|---|---|
Ordinary return ( |
|
The value, and |
Wait step returning |
|
The value and |
A union of two or more dataclasses, Pydantic models and |
|
The value, and the class name ( |
|
The members’ names |
|
|
The members’ names |
The |
|
|
The |
|
|
|
|
|
The chosen task IDs, and |
SUCCESS is DefaultOutcome.SUCCESS. Users never write the pair: they write return
types, outcomes= and .on(...); the runner (Python) or the agent (commands) builds it.
Wait steps describes timeout routing and its special plain >> rule.
Outcome classes derive from schedr.Data (class Rows(Data, frozen=True), a dataclass),
so type checkers accept .on(Rows); a plain @dataclass works too, with a TypingHint
warning and on(output, Rows) for type checkers (see Type checkers).
Pydantic outcome models derive from schedr.pydantic.Model the same way (see
Data flow).
A union is an outcome union only at the top level, and only of dataclasses, Pydantic
models and None. int | None, int | str, Rows | int and list[Rows | Unavailable]
are ordinary data with outcome SUCCESS. Members that are subclasses of one another, the
same class with different type parameters, or two classes of one name, are a TypeError
at import. An Outcome enum mixed into a union is too: outcomes are either a union of
classes or one enum. For data or nothing, return an empty dataclass or None.
class Check(Outcome):
CHANGED = 0
UNCHANGED = 1
For a command, each member’s value is the exit code meaning it. A declared code is a
success with that outcome; any other code, or a signal, fails the attempt. A custom enum
is the whole set of success codes: include 0 as a member if that code is a success.
Without outcomes=, exit code 0 is SUCCESS. The same enum works for a Python task
(-> Check): the member values are ignored, the output is None, and the member is the
outcome.
.on(...)¶
.on(...) is an edge and data. It makes the downstream task depend on those outcomes
and passes the output narrowed to them. An edge whose outcome did not happen is not
taken. A plain reference or plain >> is taken on any outcome, except that a plain >>
from a wait step is taken only when it has its value.
load(primary.on(Rows), mirror.on(Rows))
probe.on(Check.CHANGED) >> changed
Expression |
Edge |
Downstream receives when taken |
|---|---|---|
|
any outcome |
the value, decoded into the member the outcome names |
|
any outcome |
nothing (order only) |
|
|
the |
|
|
nothing (order only) |
|
|
the value |
|
|
the field of the |
|
|
|
|
|
|
.on() takes only members of the task’s own outcomes: a class of its union, or a member
of its enum (DefaultOutcome.SUCCESS on a task whose enum is DefaultOutcome). A kind
the task does not have is a TypeError at import, because that edge could never be
taken. Narrow the whole output first (f.on(Rows).rows); f.rows on a union is a
TypeError, and f.on(Rows).on(Rows) is too.
.outcome¶
.outcome passes the outcome itself as data: the member of the task’s Outcome enum,
for an enum task or a command. The stored value is the member’s name; a parameter
annotated with that enum is decoded into the member (react prints CHANGED). A
parameter annotated str receives the name.
.outcome is a TypeError on a union of classes (the value’s class already says which)
and on a part of the output. On a task whose output may have a field or key outcome
(one declaring it, a dict, Any), .outcome is refused: write result["outcome"] for
the field.
run_if¶
Trigger rules count edges. An edge not taken (an .on(...) whose outcome did not
happen, a @branch that did not choose that target, or a skipped upstream task) counts
as skipped.
Incoming edges |
|
|
|---|---|---|
Every edge succeeded |
runs |
runs |
Some skipped, the rest succeeded |
runs |
skipped |
Every edge skipped |
skipped |
skipped |
Any failed |
|
|
Data from an edge that wasn’t taken |
|
never happens |
Both decide as soon as the result is certain: the first failure makes the task
upstream_failed without waiting for the others. For ALL_SUCCEEDED, a skip decides
once no other edge can still fail (a failure wins).
Set it on @task, .override(...), CommandOperator, EmptyOperator and
StepDefaults. load in the example uses the default, so it runs from one Rows
source. all_ok sets RunIf.ALL_SUCCEEDED and is skipped because to_gcs was.
When a parameter must allow None¶
Under NONE_FAILED, a task whose every edge isn’t taken is skipped, not run with
None. A parameter must allow None only when its reference may stand for None
and the task has another edge that can run it anyway.
A reference may stand for None when .on(...) leaves an outcome of the upstream task
out, or when that task may itself be skipped. An .on(...) that names every outcome of
the task is an edge always taken, the same as naming none: it gives no None.
both(fetch().on(Rows, Unavailable)) takes Rows | Unavailable when those are all of
fetch’s outcomes. load(primary.on(Rows), mirror.on(Rows)) takes Rows | None twice,
because each .on(Rows) leaves Unavailable out and the other edge can still run load.
report_outage(mirror.on(Unavailable)) takes plain Unavailable.
The check runs when the with Dag block ends, so an order edge added after the call
counts. It reaches references at any depth (a list or dict that holds one) and outcome
references (check.outcome when check may be skipped). ALL_SUCCEEDED never receives
None from upstream. Order-only edges need nothing.
A None that reaches a t-string or a command line cannot be rendered: that attempt
fails.
@branch¶
Outcomes cover “route on what happened” (exactly one outcome per result). @branch
chooses any subset of its direct downstream tasks in the function’s code. Prefer
outcomes when they fit.
The function returns task handles (one, or a list). [] chooses none. Returning None,
a string, or a task that is not right after the branch, fails that attempt. The stored
output is the chosen task IDs; the outcome is SUCCESS. Each outgoing edge is a
selection edge, taken when the branch chose that target. A target not chosen counts
that edge as skipped, like any edge not taken: under NONE_FAILED it still runs if
another of its edges succeeded (done); under ALL_SUCCEEDED it is skipped (all_ok).
.on(...) on a @branch task is a TypeError: those edges are taken by choice.
@branch
def dest() -> list[Task]:
return [s3]
chosen = dest()
chosen >> [s3, gcs]
What schedr dags test shows¶
The report’s OUTCOME column is the outcome name on success (Rows, CHANGED,
SUCCESS) and - when the task did not succeed (skipped, failed, upstream_failed).
--json stores the same name on a successful task and null otherwise.
Testing a DAG explains the rest of the command.