Tasks and operators¶
A task is one step of a DAG. @task makes a Python function a task. CommandOperator runs
a command. EmptyOperator is a step with no work, used to join other tasks. This example uses
each of them and calls load twice:
"""A Python task, used twice, plus a shell command, an argument list and an empty task."""
from datetime import timedelta
from schedr import CommandOperator, Dag, EmptyOperator, task
with Dag(
"tasks_demo",
description="Runs a Python task twice, a shell command, an argument list and an empty task.",
trigger=None,
):
@task
def extract() -> list[str]:
return ["ada", "grace"]
@task(timeout=timedelta(minutes=10))
def load(names: list[str]) -> int:
print(f"loading {len(names)}")
return len(names)
names = extract()
count = load(names)
again = load.override(task_id="load_again")(names)
CommandOperator(
"announce",
command='echo loaded "$COUNT" in "$REGION"',
env={"COUNT": count, "REGION": "eu"},
)
CommandOperator("list_one", command=["echo", names[0]])
done = EmptyOperator("done")
[count, again] >> done
Define a @task function anywhere. Call it inside with Dag(...) to record a task, or
call it anywhere else to run the function directly, which is how a unit test calls it
(Testing a DAG). The call inside the block returns an
Output. The task’s ID is the function’s name, unless task_id= or
.override(task_id=...) sets another. load and load_again are two tasks with one
function.
An operator is constructed inside the block. Outside it, CommandOperator and
EmptyOperator raise RuntimeError.
@task¶
Part |
Rule |
|---|---|
Return annotation |
Required. |
Parameters |
Each one is declared. |
Arguments |
Checked against the signature when the DAG is imported. A missing or extra argument is a |
Calling it twice |
The second call needs another ID: |
|
Supported; see Async tasks. Async generators are refused. |
@task(timeout=..., retries=..., run_if=...) sets that task’s options. .override(...)
returns a new task function and leaves the original unchanged. See
Defaults and retries and Routing by outcome for the options.
Each Python task runs in its own process. Use the default start settings when the task can
share the worker’s preloaded libraries. Set
preload=False when the task misbehaves next to those libraries: it still forks, but only
from the bare fork server. Set fresh_process=True when the task misbehaves after a fork:
it is always a new process, and never forked. The same two arguments are on .override(...)
and StepDefaults(...), and the task’s own argument wins. What the worker does with them is
The fork server.
Memory¶
Set memory= on @task, CommandOperator, ScriptOperator or @resource to give
the task its own memory budget instead of the worker’s share. Give bytes, such as
2 * GiB, or a size string such as "2GiB", "512MiB", "1024KiB" or
"20000000B". The budget must be at least 16 MiB.
from schedr import task
@task(memory="2GiB", hard_memory_limit=True)
def transform() -> None:
...
The worker’s watchdog kills the task above its budget: the attempt ends oom_killed
with MemoryBudgetExceeded. A worker takes the task only if its memory limit less its
reserve can hold the budget. Otherwise the task waits for a suitable worker, with a
reason saying that no worker has enough memory.
hard_memory_limit=True also sets RLIMIT_DATA at the budget; it requires memory=.
An allocation past the cap fails inside the task instead of causing a kill: Python raises
MemoryError, while malloc fails in other programs. The cap counts reserved memory, so
a program that reserves a lot up front, such as the JVM or Go, may fail. A capped Python
task starts in a fresh process and is never forked, so it takes a little longer to start.
A resource’s cleanup gets its setup’s budget and cap. A @sensor has no budget of its
own: it shares its host’s [watchers] memory_budget. The master completes wait_for
without a watcher host or process. Memory options on either are refused when the DAG loads. See
Workers: Memory for how the worker enforces budgets.
Async tasks¶
Use async def for concurrent waits inside one attempt, for example several HTTP calls
with asyncio.gather. A slow synchronous call blocks the event loop and the other waits.
For waiting for an external event, see Wait steps.
"""Async task functions: concurrent waits inside one attempt."""
import asyncio
from collections.abc import AsyncIterator
from dataclasses import dataclass
from datetime import timedelta
from schedr import Dag, acleanup_handle, connection, task, task_ctx
@dataclass
class Export:
"""What the attempt started on the warehouse."""
job_id: str
@connection(base_url="https://api.example.com")
async def async_orders_api(base_url: str) -> AsyncIterator[str]:
"""Stands in for an async client, opened with `async with`."""
await asyncio.sleep(0)
yield base_url
async def fetch_page(base_url: str, page: int) -> int:
"""Stands in for one HTTP call."""
await asyncio.sleep(0.01)
return len(base_url) + page
async def cancel_export(handles: list[Export]) -> None:
"""A cleanup can be async too."""
for handle in handles:
print(f"cancelling {handle.job_id}")
with Dag("async_orders", description="Fetches orders with concurrent async waits inside one task."):
@task(
connections=[async_orders_api],
cleanup=cancel_export,
cleanup_timeout=timedelta(seconds=20),
)
async def fetch_all() -> int:
await acleanup_handle(Export("export-1"))
async with async_orders_api() as base_url:
pages = await asyncio.gather(*(fetch_page(base_url, p) for p in range(10)))
return sum(pages)
@task(secrets=["etl/api#token"])
async def report(total: int) -> None:
token = await task_ctx.asecret("etl/api", "token")
print(f"{total} rows, with a token of {len(token)} characters")
report(fetch_all())
@task, @branch, @resource setups and cleanups can be async functions. Async
generators are refused as tasks. A generator @trigger requires an async generator instead
(Event triggers). Each async attempt runs in its
own event loop. When its main coroutine ends, leftover tasks are cancelled; errors from
them are logged as warnings and do not change the attempt’s result. A timeout or cancel
cancels the coroutine, allowing finally and async with exits to run within the grace
period. A blocked loop may instead be killed when the grace expires
(Workers).
The event loop¶
schedr uses uvloop whenever the attempt’s interpreter can import it, however it was
installed; it looks for the module, not the extra. pip install schedr[uvloop] is one way
to install it. Otherwise schedr uses asyncio’s own loop. There is no configuration key:
installing the module selects it. Each async attempt’s log says event loop: uvloop or
event loop: asyncio.
Commands¶
CommandOperator(task_id, command, *, env=..., outcomes=...) runs one process.
|
How it runs |
|---|---|
A |
A shell. It takes no placeholders: a t-string with one is refused when the file loads, because the shell would read the value as code. |
A list |
The program and its arguments, with no shell. Each element is one argument, so nothing is quoted. An empty list is a |
An element, and a value in env, may be a string, a t-string or a reference such as
names[0]. A name in env matches [A-Za-z_][A-Za-z0-9_]*. To pass a value, use a list,
["./notify.sh", out.report_url], or env read by the shell:
command='./notify.sh "$URL"', env={"URL": out.report_url}. While the command runs, it
reads the run’s parameters and run information with schedr dag-ctx. A Python script it
starts reads them with from schedr.script import dag_ctx
(Reading the run from a command).
Without outcomes=, exit code 0 is success (DefaultOutcome.SUCCESS). With
outcomes=, a declared exit code is success with that outcome; any other code, or a
signal, fails the attempt. Routing by outcome explains the enum and
.on(...). The output is a ProcessResult: stdout, stderr, exit_code,
stdout_truncated, stderr_truncated. announce.stdout and announce.stderr are
references to those strings. The size limit applies to each stream. They are text: invalid
UTF-8 and NUL bytes appear as � (U+FFFD), so find -print0’s names are separated by �;
the task’s log keeps the bytes as written.
EmptyOperator(task_id, *, run_if=...) has no output. The master completes it when its
upstream edges allow it to run, and no worker runs it.
What a task may return¶
The return annotation is checked while the file is imported. A type outside this set is an import error naming the part. The same types are what one task may pass to another (Data flow).
Annotation |
What is stored |
|---|---|
|
The value. An |
|
An aware datetime, as |
|
|
|
A list of |
|
No element or value type: treated as |
|
A fixed tuple, as |
|
String keys only. |
|
|
A dataclass or a |
Its fields. A dataclass matches by its class name and fields; the stored JSON is the fields. |
A Pydantic model |
Its JSON representation. Install |
|
|
|
Either type. Two or more dataclasses (or |
A subclass of |
No output ( |
|
No parse-time check. The returned value still has to be one of the rows above. |
set and frozenset are refused (use list). bytes is refused (encode it, for example
base64 in a str). Outcome unions, Outcome enums and .on(...) are
Routing by outcome.
Where a task writes files¶
A task runs from a read-only copy of its DAG root, and its files go elsewhere: a temporary
directory, or an output folder outside every DAG root. Not into the DAG root by its path
either: every file there counts for the root’s code hash, so a write is new code, and the run’s
next tasks wait about 35 s for the workers to have it, again after each write (see
Which code runs). A folder that must
stay under the root is excluded with .schedrignore.
IDs¶
A task ID is nonempty and up to 250 bytes: ASCII letters, digits and _ . -. A . is allowed
(extract.load); an empty part (extract. or .load) is an IdError. A task written
inside a group gets the group’s name as that prefix (load.extract).
No custom operators¶
Subclassing CommandOperator, EmptyOperator or Trigger outside schedr is a
TypeError. Share a function that creates tasks, or share a @task function.
Use ScriptOperator for plain scripts, or
TriggerDagOperator for starting another DAG.