Starting another DAG¶
TriggerDagOperator starts a run of another DAG from a task. The target opts in with
trigger=Chained() or names the DAGs allowed to start it with Chained(by=[...]).
by=[] is an error. Here chained_report starts chained_load and waits for it:
"""Start a load from a report, passing its region to a chained DAG."""
from dataclasses import dataclass
from datetime import timedelta
from schedr import Chained, Dag, Failed, TimedOut, TriggerDagOperator, dag_ctx, task
@dataclass
class LoadParams:
"""What a load run is given; the default lets it run alone too."""
region: str = "eu"
@task
def load(region: str) -> str:
return f"loaded {region}"
@task
def report(run_id: str) -> str:
return f"load run {run_id} succeeded"
@task
def failed(result: Failed) -> str:
return f"load run {result.run_id} ended {result.state}"
@task
def late(result: TimedOut) -> str:
del result
return "load is still going or finished late"
with Dag(
"chained_load",
description="Loads the region a chained_report run asks for.",
trigger=Chained(by=["chained_report"]),
params=LoadParams,
):
region: str = dag_ctx.params.region # pyright: ignore[reportAny]
load(region)
with Dag("chained_report", description="Builds a report, then starts chained_load for its region."):
started = TriggerDagOperator(
"start_load", dag="chained_load", params={"region": "eu"}, max_wait=timedelta(minutes=5)
)
report(started.on(str))
failed(started.on(Failed))
late(started.on(TimedOut))
Unpause chained_load before running chained_report on a server:
schedr dags unpause chained_load
schedr runs trigger chained_report
The master runs the operator without a worker or slot. It creates a chained run linked to
its parent run. The new run’s planned_for is the parent’s unless the operator gives an
aware datetime or a reference as planned_for=. Its params= can contain literals,
upstream outputs and dag_ctx references. They overlay the target’s defaults and are checked
against its schema before the run is created. A Chained DAG’s parameters need no defaults;
the operator or a manual run must supply required fields.
How the task ends¶
With wait=True (the default), the task waits for the target run. Time spent queued
counts toward max_wait:
Target run |
Operator task |
|---|---|
succeeds |
Its value is the run’s ID ( |
fails, is cancelled or skipped |
|
does not end within |
|
With wait=False, the task ends with the run’s ID as soon as the run is created; it does
not wait for its result and cannot take max_wait. Read the target’s output with a
RunOf sensor or the API.
A retry starts a new target run only after the previous attempt failed. The master records
its intended run ID before creating the run, so a restart between those writes does not
create two. Cancelling the operator or its parent run cancels a target run it is still
waiting for; a run started with wait=False continues.
Refusals¶
A missing, conflicting, held or paused target fails the task and its retries apply. A target may be missing while its root has not been parsed yet. These failures are not retried:
The target is not
Chained, or itsbydoes not name the parent DAG.The target refuses the parameters or
planned_for.
DAGs may start each other in a cycle (a starts b, which starts a): it is allowed, as
between RunOf triggers. Only a DAG starting its own runs is refused, when its file loads.
One way to start a DAG¶
A DAG gets automatic runs from its own trigger, or from other DAGs’ operators with
trigger=Chained(). trigger=None is for manual runs only. Any DAG can also be run
manually, including a scheduled or Chained DAG. Pausing a Chained DAG makes operators
fail until it is unpaused; manual runs remain available.
Mapping chained runs¶
Map a TriggerDagOperator to start one chained run per element. Fix the task ID,
dag, wait and other shared options in .partial(), then map params or
planned_for with .expand():
"""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)
The list may be literal or an upstream output. .expand(params=..., planned_for=...)
takes the cartesian product of the lists, the first argument written varying slowest.
To pair values instead, use .expand_kwargs([{"params": {...}, "planned_for": ...}, ...]),
with either a literal list or an upstream output. Only params and planned_for can be
mapped; each argument is fixed in .partial() or mapped, never both.
Each instance ends as a single operator does. The mapped task’s .output is its values in
element order: each run’s ID, Failed or TimedOut. Unlike a single operator’s .output,
it is not narrowed to .on(str): each element has its own outcome, as with a mapped
@task. A following task takes list[str | Failed | TimedOut] and filters it, as above,
or narrows the elements one by one. With wait=False, every element is an ID.
An instance that fails without routing, after its retries, fails the run; the other instances
and the runs they are waiting for are cancelled. [mapping] max_instances limits the number
of instances, as for any mapped task (Mapping).
Testing¶
schedr dags test and run_dag run the target for real when its DAG file is in the path
tested. Include the target in that path; otherwise the operator fails. The test unpauses
Chained DAGs in the path. schedr dags check fails the operator’s file if a target in
the root refuses it; a target in no file of the root gives a warning.
From Airflow¶
TriggerDagRunOperator maps to TriggerDagOperator, and logical_date to planned_for.
For a target with Airflow’s schedule=None, use trigger=Chained() when another DAG’s
operator starts it; use trigger=None for manual runs only.