Data flow

A task receives another task’s output by being called with it. >> only decides the order. In this DAG, load reads fetch’s data and show prints load’s output. left and right run after fetch and before finish, without reading fetch’s output.

examples/docs/data_flow.py
"""Passing parts of an output, and ordering tasks that share no data."""

from dataclasses import dataclass

from schedr import CommandOperator, Dag, chain, task


@dataclass(frozen=True)
class Batch:
    """Rows fetched from one source."""

    rows: int
    source: str


with Dag(
    "data_flow",
    description="Passes parts of one task's output to others, and orders tasks that share no data.",
    trigger=None,
):

    @task
    def fetch() -> Batch:
        return Batch(2, "primary")

    @task
    def load(rows: int, source: str) -> str:
        text = f"{source}:{rows}"
        print(text)
        return text

    @task
    def left() -> None:
        print("left")

    @task
    def right() -> None:
        print("right")

    @task
    def finish(note: str) -> None:
        print(note)

    batch = fetch()
    note = load(batch.rows, batch.source)
    CommandOperator("show", command=["echo", note])
    finished = finish(note)
    chain(batch, [left(), right()], finished)

fetch() returns an Output. batch.rows and batch["source"] reference fields of this example’s Batch. For a list output, items[0] references its first element. The master extracts that part when it builds the downstream task’s inputs. A key is a str or an int; a negative index is a ValueError.

Where a reference is written

What it does

An argument of a @task call

A data edge. The downstream task waits for that output. Lists, tuples and dict values are searched, at any depth.

A command argument in a list, or an env value

A data edge, the same way. A shell command string cannot contain placeholders.

x.on(Kind)

A data or order edge taken only on that outcome. Routing by outcome.

a >> b, b << a, or chain(a, b)

An order-only edge. b waits for a and receives nothing from it.

a >> [b, c], [a, b] >> c

An edge from every task on the left to every task on the right.

chain(a, [b, c], d)

a >> [b, c] >> d.

chain and >> take tasks, outputs and groups. A bare function is a TypeError. Both kinds of edge may exist between the same pair. A task depending on itself, or on a task that is not in this DAG, is a ValueError. When the block ends, a cycle is a ValueError: DAG `data_flow` has a dependency cycle: a -> b -> a.

The downstream call has to come after the upstream call, so the Output exists to pass. Build a dataclass inside the task that returns it. A reference placed inside a dataclass or a set in the DAG body is a TypeError at import. The message names the task and the argument, then Output is not supported or set is not supported. Lists, tuples and dict values are the containers a reference may sit in. The task receives the parameter’s type: consume((count, 3)) for tuple[int, int] gets a tuple, and consume({"x": count, "y": 3}) for a dataclass or a Pydantic model gets an instance built from those fields.

In the DAG body an Output is a reference. Using it as a value is a TypeError: if batch, for x in batch, str(batch) and an f-string. Pass it to a task, or write it in a t-string.

What the path must match

The part is checked against the upstream return type at import.

The upstream type

A valid next step

A dataclass or a TypedDict

A field that exists. batch.rows is int because Batch.rows is.

A Pydantic model

A field of its schema, by attribute name: config.retries has the field’s schema (int, minimum 0). See Pydantic models.

dict[str, T]

Any string key, of type T.

list[T]

Any index, of type T.

tuple[A, B]

An index that exists.

Any

Anything; the part stays Any.

ProcessResult

stdout, stderr, exit_code, stdout_truncated, stderr_truncated.

An outcome union (Rows | Unavailable)

A field of a member, after .on(Rows): batch.on(Rows).rows.

A mismatch is a TypeError naming the argument and both types. There is no coercion except int for float. When the upstream return type is an outcome union, name the member first: batch.on(Rows).rows.

When a task returns, its value is checked against the return type and stored as JSON. These fail the attempt, with a message naming where in the value: a type schedr doesn’t store (Decimal, set), a dict key that isn’t a str, NaN or infinity, an integer outside the stored range (-2**63 through 2**64 - 1; store larger integers as a str), a timedelta whose total microseconds fall outside that range, a string, key or outcome name containing NUL (\0), lists and dicts nested more than 100 deep, and any other error while writing it (a model’s serializer failing, a list containing itself). Every other value reads back as it was written, a dict such as {"$date": "x"} included.

t-strings

A t-string becomes a template. References in it are filled in when the task runs. A plain value is formatted while the file is imported: a string as itself, a number or a bool with str, a datetime or date in ISO 8601, a timedelta as seconds (3600, 1.5).

For a reference, these formats are allowed. A plain value uses Python’s format when a spec is supplied.

Format

Where

none

The text above.

a spec containing %, such as :%Y-%m-%d

A datetime, a date, or Any.

!r, !s and !a apply to a plain value. On a reference they are a TypeError. A t-string nested in another, or used as a dict key, is a TypeError.

When a task does not run

A task runs when its incoming edges and run_if allow it (Routing by outcome). With the default run_if=RunIf.NONE_FAILED, an upstream failure makes this task end upstream_failed without running. An edge that wasn’t taken (.on(...) whose outcome didn’t happen, or a @branch that didn’t choose this task) counts as skipped. Tasks with no dependency on the failure keep running. Defaults and retries explains what happens to the task that failed. Task groups organise tasks while the DAG is written. Mapping runs a task once per element.

Pydantic models

A task can return and take Pydantic models, with pip install schedr[pydantic] (Pydantic 2.11 or newer, before 3). schedr never imports Pydantic itself; it uses the model’s own methods. A model is stored as model_dump(mode="json") writes it, keyed by field names, and read back as JSON with model_validate_json, so Pydantic’s rules and validators apply when the downstream task receives it, a strict model’s included: dates arrive as the ISO text JSON holds.

examples/docs/pydantic_models.py
"""Pydantic models as outputs: an outcome union of models, a model whole, a field, a date."""

from datetime import UTC, datetime
from typing import Annotated

from pydantic import BaseModel, Field, HttpUrl

from schedr import Dag, RunIf, task
from schedr.pydantic import Model


class Settings(BaseModel):
    """Ordinary data: a plain `BaseModel`."""

    retries: Annotated[int, Field(ge=0)]
    region: str = "eu"


class Found(Model):
    """An outcome: derives from `schedr.pydantic.Model`."""

    url: HttpUrl
    fetched_at: datetime


class Missing(Model):
    """The other outcome."""

    reason: str


with Dag(
    "pydantic_models",
    description="Passes Pydantic models between tasks: a whole model, a field, a date.",
    trigger=None,
):

    @task
    def settings() -> Settings:
        return Settings(retries=3)

    @task
    def locate(config: Settings) -> Found | Missing:
        url = HttpUrl(f"https://data.example.com/{config.region}/latest.csv")
        return Found(url=url, fetched_at=datetime(2026, 10, 29, 3, tzinfo=UTC))

    @task(run_if=RunIf.ALL_SUCCEEDED)  # skipped with `Missing`, so never given None
    def download(found: Found, retries: int) -> str:
        print(f"downloading {found.url} with {retries} retries")
        return str(found.url)

    @task
    def report(missing: Missing) -> None:
        print(missing.reason)

    @task
    def stamp(fetched_at: datetime) -> str:  # a model's date, as a plain datetime
        return f"{fetched_at:%Y-%m-%d %H:%M %Z}"

    config = settings()
    located = locate(config)
    download(located.on(Found), config.retries)
    report(located.on(Missing))
    stamp(located.on(Found).fetched_at)

An outcome model derives from schedr.pydantic.Model (a BaseModel), as a dataclass outcome derives from schedr.Data (Type checkers). Ordinary data stays a plain BaseModel.

A model’s type is Pydantic’s own JSON Schema of it, and loading the file checks it strictly: an output fits a parameter only when every value it can be is provably accepted.

Passing

Result

A model to a parameter of the same model, or one with the same or fewer constraints

Fits

config.retries (int, minimum 0) to retries: int

Fits: tighter than the parameter

A plain int to a field with Field(ge=0)

Refused: the value might be negative. Give the output the same constraint

A str to an HttpUrl field

Refused: the parameter needs format uri

A field with pattern to one with another pattern

Refused: patterns must be identical

A model that may be None to one that may not

Refused

A model’s datetime, date or timedelta field (found.fetched_at) to a parameter of that type, or the other way

Fits: the task receives the value, read by Pydantic’s rules. A date the model holds without a time zone arrives without one

Parts that can’t be compared (allOf, not, if, custom schemas) fit only when the two sides are identical. The error names the field and both sides’ constraints.

A model’s text, number and boolean fields render into commands and t-strings like any value (command=["curl", found.url]). A model’s date renders as the text Pydantic wrote: a format spec such as :%Y doesn’t apply to it. A date a model holds without a time zone reaches a datetime parameter without one, and schedr refuses to store such a value again: declare the field AwareDatetime, or add a zone in the task. NaN, infinity and integers outside the 64-bit range in a model are refused, as in any output.