schedr.tasks¶
@task: Python tasks, and Output, the reference a task call returns.
Inside with Dag(...), calling a @task function records a task and returns an
Output: passing it to another task (as an argument, at any depth in lists and dicts)
creates the dependency. >> adds order-only dependencies. Outside a DAG, a @task
function is the plain function, so it can be unit-tested directly (see archive/PROJECT.md, Native
API and Testing DAGs).
- class schedr.tasks.Mapped(iterable=(), /)¶
Bases:
list[T],GenericA mapped task’s output, as type checkers read it: the list of its instances’ outputs.
At run time it is a reference (an
Output), as any task’s output in the DAG body. Index it (results[0]), pass it whole to a task taking a list (a gather), or map over it element by element (check.expand(n=results)), narrowing each element with.on(...):count.expand(rows=results.on(Rows)).
- class schedr.tasks.Output(task_id, path=(), on=(), *, dag=None)¶
Bases:
GenericThe output of a task, or a part of it, as a reference in the DAG body.
out.rows(a field),out["key"](a key) andout[0](an index) reference parts; the master extracts them when it builds the downstream task’s inputs.- Parameters:
task_id (str)
path (tuple[str | int, ...])
on (tuple[str, ...])
dag (DagBuilder | None)
- on(kind: type[U], /) Output[U]¶
- on(kind: type[U], other: type[V], /) Output[U | V]
- on(kind: None, /) Output[None]
- on(*members: Outcome) Output[T]
Depends on the task only when it ends with one of these outcomes.
The output is narrowed to them:
load(fetch().on(Rows)),check.on(Check.CHANGED) >> notify.An edge whose outcome didn’t happen isn’t taken: under
RunIf.NONE_FAILEDthe downstream task getsNonefor it (its parameter must allowNone), underRunIf.ALL_SUCCEEDEDit is skipped.- Parameters:
*kinds (object) – Classes (or
None) of the task’s outcome union, or members of itsOutcomeenum.- Returns:
The narrowed reference.
- Raises:
TypeError – For an outcome the task doesn’t have, or
.on()on a part of the output (narrow first:f.on(Rows).rows).- Return type:
Output[object]
- property outcome: _OutcomeOutput¶
pass it to a task taking its
Outcomeenum.- Raises:
TypeError – On a task whose outcomes are a union of classes (the value’s class already says which), on a wait step, or on a part of the output.
- Type:
The task’s outcome itself as data
- class schedr.tasks.TaskFunction(fn, task_id, options, branch=False, cleanup=None)¶
Bases:
Generic[P,R]A function decorated with
@task.Calling it inside
with Dag(...)records a task and returns itsOutput; outside, it calls the function.- Parameters:
fn (Callable[[P], R])
task_id (str)
options (TaskOptions)
branch (bool)
cleanup (Callable[[...], object] | None)
- property task_id: str¶
The ID of the task a call creates.
- partial(**fixed)¶
Fixes some arguments of a mapped task:
load.partial(bucket="raw").expand(...).- Parameters:
**fixed (object) – Arguments every instance gets.
- Returns:
The task with them fixed, to
.expand(...).- Raises:
TypeError – For a name that isn’t a parameter.
- Return type:
PartialTask[P, R]
- expand(**mapped)¶
A mapped task: one instance per element of the lists given (their cartesian product).
load.expand(path=files)runsloadonce per element offiles(a literal list or an upstream output that is a list, a mapped task’s included, element by element). Type checkers read it as the list of the instances’ outputs, in the order of the elements.- Parameters:
**mapped (object) – Each mapped parameter’s list.
- Returns:
The list of the instances’ outputs (a reference in a DAG body).
- Return type:
- expand_kwargs(values)¶
A mapped task: one instance per dict of
values, its arguments.- Parameters:
values (object) – A list of dicts (a literal, or an upstream output that is one).
- Returns:
The list of the instances’ outputs (a reference in a DAG body).
- Return type:
- override(*, task_id=None, retries=None, retry_delay=None, timeout=None, queue=None, max_output_size=None, preload=None, fresh_process=None, run_if=None, max_active=None, max_active_per_run=None, memory=None, hard_memory_limit=None, secrets=None, connections=None, cleanup=None, cleanup_timeout=None, cleanup_retries=None, cleanup_retry_delay=None, cleanup_anywhere=None, uses=None, max_wait=None)¶
The same function as another task, e.g.
load.override(task_id="load_eu")(...).- Parameters:
task_id (str | None) – A different task ID (needed to use the function twice in one DAG).
retries (int | None) – Overrides the retries.
retry_delay (timedelta | None) – Overrides the retry delay.
timeout (timedelta | None) – Overrides the timeout.
queue (str | None) – Overrides the queue.
max_output_size (int | None) – Overrides the output size limit.
preload (bool | None) – Overrides whether it forks from the preloaded fork server.
fresh_process (bool | None) – Overrides whether it is always a new process.
run_if (RunIf | None) – Overrides its trigger rule.
max_active (int | None) – Overrides its limit across runs.
max_active_per_run (int | None) – Overrides its limit within a run.
memory (int | str | None) – Overrides its own memory budget.
hard_memory_limit (bool | None) – Overrides whether that budget is a hard cap.
secrets (SecretsArg) – Overrides the secrets it declares.
connections (ConnectionsArg) – Overrides the connections it declares.
cleanup (Callable[[...], object] | None) – Overrides its cleanup.
cleanup_timeout (timedelta | None) – Overrides how long one try of its cleanup may run.
cleanup_retries (int | None) – Overrides how many times a failed cleanup is retried.
cleanup_retry_delay (timedelta | None) – Overrides the delay before each cleanup retry.
cleanup_anywhere (bool | None) – Overrides whether the cleanup may run on another worker.
uses (Sequence[object] | None) – Overrides the resources it needs.
max_wait (timedelta | None) – Overrides how long a wait step waits; a wait step’s only.
- Returns:
A new task function; this one is unchanged.
- Return type:
Self
- class schedr.tasks.AsyncTaskFunction(fn, task_id, options, branch=False, cleanup=None)¶
Bases:
TaskFunction[P,R],Generic[P,R,A]A function decorated with
@taskthat isasync def.A call reads, to a type checker, as
R, soload(extract())checks in a DAG; in a test,await task.fn(...)is typed as the coroutine it is, ofA, what the function returns (decision 319). They differ for-> None, whose call in a DAG reads asDone.- Parameters:
fn (Callable[[P], R])
task_id (str)
options (TaskOptions)
branch (bool)
cleanup (Callable[[...], object] | None)
- fn(*args, **kwargs)¶
Calls the function, to
awaitin a test.- Parameters:
*args (P) – Its arguments.
**kwargs (P) – Its arguments.
- Returns:
Its coroutine; what the task declares is in force while it runs.
- Return type:
Coroutine[object, object, A]
- schedr.tasks.is_async(fn)¶
Whether calling
fngives a coroutine, seeing through afunctools.wrapsdecorator.- Parameters:
fn (Callable[[...], object])
- Return type:
bool
- class schedr.tasks.PartialTask(function, fixed)¶
Bases:
Generic[P,R]A
@taskfunction with some arguments fixed:load.partial(bucket="raw").- Parameters:
function (TaskFunction[P, R])
fixed (dict[str, object])
- expand(**mapped)¶
-
- Parameters:
**mapped (object) – Each mapped parameter’s list.
- Returns:
The list of the instances’ outputs (a reference in a DAG body).
- Raises:
RuntimeError – Outside
with Dag(...).TypeError – For no mapped argument, an unknown or fixed one, or a required parameter left without a value.
- Return type:
- expand_kwargs(values)¶
See
TaskFunction.expand_kwargs().- Parameters:
values (object) – A list of dicts (a literal, or an upstream output that is one).
- Returns:
The list of the instances’ outputs (a reference in a DAG body).
- Raises:
RuntimeError – Outside
with Dag(...).TypeError – For a list written in the DAG with an element that isn’t a dict, or a dict naming an unknown or fixed parameter or leaving a required one without a value.
- Return type:
- schedr.tasks.refuse_param_mapping(converted, where)¶
Refuses mapping over the run’s parameters: the number of instances would depend on them.
- Raises:
TypeError – When the whole list is a
dag_ctx.paramsreference.- Parameters:
converted (Value)
where (str)
- Return type:
None
- class schedr.tasks.TaskDecorator(task_id, options, cleanup=None)¶
Bases:
objectWhat
@task(...)with arguments gives: makes a function a task, as@taskdoes.- Parameters:
task_id (str | None)
options (TaskOptions)
cleanup (Callable[[...], object] | None)
- schedr.tasks.task(fn: Callable[P, Coroutine[object, object, None]], /) AsyncTaskFunction[P, Done, None]¶
- schedr.tasks.task(fn: Callable[P, Coroutine[object, object, R]], /) AsyncTaskFunction[P, R]
- schedr.tasks.task(fn: Callable[P, None], /) TaskFunction[P, Done]
- schedr.tasks.task(fn: Callable[P, R], /) TaskFunction[P, R]
- schedr.tasks.task(*, task_id: str | None = None, retries: int | None = None, retry_delay: timedelta | None = None, timeout: timedelta | None = None, queue: str | None = None, max_output_size: int | None = None, preload: bool | None = None, fresh_process: bool | None = None, run_if: RunIf | None = None, max_active: int | None = None, max_active_per_run: int | None = None, memory: int | str | None = None, hard_memory_limit: bool | None = None, secrets: SecretsArg = None, connections: ConnectionsArg = None, cleanup: Callable[[...], object] | None = None, cleanup_timeout: timedelta | None = None, cleanup_retries: int | None = None, cleanup_retry_delay: timedelta | None = None, cleanup_anywhere: bool | None = None, uses: Sequence[object] | None = None) TaskDecorator
Makes a function a Python task:
@taskor@task(retries=2, ...).The function must annotate its return type and declare each parameter (no
*args/**kwargs). The task ID defaults to the function’s name. Type checkers read a call of it in a DAG body as the function’s value; a function returningNonegivesDone.- Parameters:
fn (Callable[[...], object] | None) – The function (when used as
@taskwithout parentheses).task_id (str | None) – The task’s ID; default: the function’s name.
retries (int | None) – How many times a failed attempt is retried.
retry_delay (timedelta | None) – The delay before each retry.
timeout (timedelta | None) – The attempt’s timeout.
queue (str | None) – The queue the task goes to.
max_output_size (int | None) – The output size limit in bytes.
preload (bool | None) – Fork it from the preloaded fork server, on a worker that has one (default);
False: only from the bare one, for code that misbehaves next to the preloaded libraries.fresh_process (bool | None) – Always a new process, never forked, for code that misbehaves after a fork.
run_if (RunIf | None) – When it runs, from its upstream edges:
RunIf.NONE_FAILED(the default) orRunIf.ALL_SUCCEEDED.max_active (int | None) – At most this many of its instances running at once, across all runs (
None: no limit); e.g. 1 for a task holding an exclusive external lock.max_active_per_run (int | None) – At most this many of its instances running at once within one run (
None: no limit), for a mapped task:.expand()over 1,000 files, 10 at a time.memory (int | str | None) – Its own memory budget, instead of the worker’s share: bytes (
2 * GiB) or a size ("2GiB","512MiB"), at least 16 MiB. The worker kills it above (its attempt endsoom_killed); only a worker whose memory limit holds it takes it.hard_memory_limit (bool | None) – Also cap it hard at
memory: an allocation past it fails inside the task (MemoryError) instead of the task being killed. It counts reserved memory, so a program reserving a lot up front may fail; off by default.secrets (SecretsArg) – The secrets it reads on demand, with
task_ctx.secret(...):secrets['path']['key'],'path#key','path'(every key) orSecretPrefix(...)(every secret under it, fetched when read). Secrets in its arguments need no declaring.connections (ConnectionsArg) – The connections it opens (
with mongodb_default() as db:), each the@connectionfunction or its name: only these open, each rendered before the task starts (a missing one or an unreadable secret fails it before it runs).cleanup (Callable[[...], object] | None) – A function run after each attempt, whatever its end, like
finally, in the attempt’s slot and before its retry or downstream tasks. It takes any of the task’s parameters, andhandles: list[A | B]: the attempt’scleanup_handlevalues. It must be idempotent; a cleanup that keeps failing fails the run.cleanup_timeout (timedelta | None) – How long one try of the cleanup may run (default: the worker’s
cleanup_timeout: 5 minutes, or less to fit in its grace period).cleanup_retries (int | None) – How many times a failed cleanup is retried (default 3).
cleanup_retry_delay (timedelta | None) – The delay before each cleanup retry (default 30 seconds).
cleanup_anywhere (bool | None) – Whether the cleanup may run on another worker when this one is lost (default no: only you know whether it depends on where the task ran).
uses (Sequence[object] | None) – The resources it needs without taking their data (decision 259).
- Returns:
The task function, or a decorator making one.
- Raises:
TypeError – If the function can’t be a task.
- Return type:
object
- schedr.tasks.chain(*items)¶
Order-only dependencies along a sequence:
chain(a, [b, c], d)isa >> [b, c] >> d.- Parameters:
*items (object) – Tasks, outputs, or lists of them.
- Return type:
None
- type schedr.tasks.Task = object¶
A task handle, as a
@branchfunction returns: a task call or an operator.Type checkers read a task call as its value (
Done,Rows, …), so any object is accepted here; a handle that isn’t a direct downstream task fails the branch when it runs.
- class schedr.tasks.Chosen(*args, **kwargs)¶
Bases:
ProtocolWhat a call of a
@branchtask gives, for type checkers: what it chose, to order.targets(cfg) >> [to_s3, to_gcs]:>>orders it, nothing can be passed.
- schedr.tasks.on(output, kind, /)¶
output.on(kind)for type checkers, when the class doesn’t declare.on.plain_load(on(fetch(), Plain))wherePlainis a plain@dataclassoutcome: it runs exactly asfetch().on(Plain), and type checkers read it as aPlain(seeschedr.Datato make.onitself typed).- Parameters:
output (object) – A task call (an
Outputin a DAG body).kind (type[U]) – One class of its outcome union.
- Returns:
The narrowed reference.
- Raises:
TypeError – If
outputisn’t a task’s output, orkindisn’t one of its outcomes.- Return type:
U
- schedr.tasks.branch(fn: Callable[P, Coroutine[object, object, list[Task] | Task]], /) AsyncTaskFunction[P, Chosen, list[Task] | Task]¶
- schedr.tasks.branch(fn: Callable[P, list[Task] | Task], /) TaskFunction[P, Chosen]
Makes a function a branch: it chooses which of its direct downstream tasks run.
The function returns the chosen tasks’ handles (one, or a list;
[]for none, neverNone), e.g.return [to_s3, to_local]withtargets(cfg) >> [to_s3, to_gcs, to_local]. Its output is their task IDs; each edge out of it is taken only when it chose that task.- Parameters:
fn (Callable[[...], object]) – The function; annotate its return as
list[Task](orTask).- Returns:
The task function.
- Raises:
TypeError – If the function can’t be a task.
- Return type:
object