Python API structure

schedr’s Python package has two kinds of API:

  • Native API: schedr’s own DAG authoring API, at the top level of the schedr package (see Native API).

  • Compatibility APIs: look-alikes of other orchestrators’ APIs, each in its own subpackage named after the orchestrator. schedr.airflow is the first. Others may be added later (e.g. schedr.<other>).

schedr/                 # native API
schedr/airflow/         # Airflow 3 look-alike API
schedr/<other>/         # future compatibility APIs

All APIs describe DAGs in terms of the same underlying model, so the Rust scheduler handles them identically. A compatibility API is a translation layer onto that model, not a separate engine.

How the Python API works with the engine

The Python API is a description layer, not an execution engine. Python code of the API runs at two moments only; all scheduling behaviour lives in Rust, on the master.

Parse time: Python describes the DAG. The runner (parse mode) imports the DAG file. API calls (creating a DAG, tasks, dependencies, groups, mapping) only record what was declared; the runner turns the record into DAG JSON in the shared model:

Feature

What Python records

Who implements the behaviour

Dependencies (>>, chain())

Edges between task IDs

Master: dependency resolution

Trigger rules

A per-task field

Master: when a task is ready, skipped or upstream_failed

Branching

A python task flagged as a branch

Master: skips the branches not chosen and propagates the skip

Task groups

Flattened to group_id.task_id names and edges, plus group metadata for the UI

Master schedules ordinary tasks (checks the groups)

Dynamic task mapping

The task, its fixed arguments, and what it maps over (a literal or an output reference)

Master: once the upstream output exists, creates N task instances (map_index 0…N−1)

t-strings

Literal text plus typed references

Agent / runner: filled in at run time

EmptyOperator

An empty task

Master completes it, no worker

TriggerDagOperator

A trigger_dag task

Master creates the target run and waits for it, no worker

Run time: Python runs one callable. For a python task the runner (task mode) imports the DAG file again, finds the task by ID, fills in its arguments (inputs from upstream outputs, t-strings, secrets via the agent), calls the function and returns the result over the socket. A branch task is no different: its return value (the task IDs to follow) is just its output, and the master acts on it. command and script tasks need no Python: the agent renders and runs them.

Difference from Airflow: in Airflow, operator classes carry behaviour in Python (e.g. BranchPythonOperator.execute() marks other tasks skipped itself). In schedr, operator classes are thin: their type and arguments go into the model, and Rust implements what each type means. That is why the native API and every compatibility API can share one engine. User code can never change scheduling behaviour (skips, branching, retries) from inside a task.

Native API

  • DAGs are defined only with with Dag(...). There is no @dag decorator: a decorated function must be called to create the DAG, and a forgotten call would make the DAG vanish silently (files without DAGs are ignored). The context manager also makes generating DAGs in a loop straightforward.

  • A @task must annotate its return type (-> None for a task without output). A missing annotation is a parse error. -> Any is the explicit opt-out from the parse-time type check (the run-time check still applies).

  • Task kinds: Python tasks are decorated functions (@task); other kinds are operator classes: CommandOperator, ScriptOperator, EmptyOperator, TriggerDagOperator.

  • No custom operators. Users can’t subclass an operator class to define their own task kind with its own execute(); subclassing a schedr operator class is a parse error. Reuse is by composition: a plain Python function that creates tasks with parameters (a task factory), or a shared @task function in a helper module. Every task is therefore one of the known kinds, which the master and the agent understand without user code. Consequence for the Airflow layer: see Airflow compatibility (Scope).

  • Data flow defines dependencies. Calling a task inside a DAG returns an output reference; passing it to another task (as an argument, or inside a t-string) creates the dependency. >> remains for order-only dependencies (no data passed).

  • Typing of calls: type checkers read a call as its value (decision 57, the user’s, 2026-10-29; A + bases). At run time a call in a DAG body gives an Output (a reference); for type checkers a @task returning T gives T, so it passes to a task taking T and its fields are typed, in mypy --strict and pyright / basedpyright alike, without a plugin. Python’s typing can’t say “an Output[T] is also a T” (no intersection types, no mapping over a ParamSpec’s parameters), so the DAG methods come from the value’s side:

    • Outcome classes derive from schedr.Data (a dataclass_transform base: the subclass is a dataclass, options as class keywords, class Rows(Data, frozen=True)) or schedr.pydantic.Model (a BaseModel, imported only with Pydantic; one base, as basedpyright refuses BaseModel and another base with an __init__ together). Both declare .on(...) (typed as the narrowed class), >> and << for type checkers only. Ordinary data stays a plain @dataclass / BaseModel.

    • A plain outcome class stays allowed (57.1 B): it runs as written; type checkers then need schedr.on(output, Cls) (typed Cls), and loading the file raises a schedr.TypingHint warning naming the class, which schedr dags check prints (57.4: the runner returns the warnings an import raised with the file’s result, as warnings on file_parsed; not sent to the master) and pytest lists. Not chosen: an error (A: one kind of outcome class, but no way to keep plain classes).

    • Calls without data are handles: a task returning None gives Done (chosen by @task’s overloads, so a wrong argument is still a plain argument error), a @branch call Chosen, .on(None) and an enum outcome’s .on(member) Done; each has >>. Outcome enums declare .on, .outcome (typed as the enum) and >>; CommandOperator is generic in its outcomes= enum (.on takes its members, .outcome is one; .on(...), .output a ProcessResult, .stdout a str); ProcessResult declares >>. Task (a branch’s return annotation) is object.

    • dag_ctx fields are typed as their values (datetime, str).

    • What only loading the file checks: an output used as a value in the DAG body (if rows:, len(rows): type checkers read rows as the value and accept them), None from an edge that may be skipped, outcomes and graph rules. Writing DAGs (Type checkers) says so.

    • Gaps: >> between two values of builtin types (rows >> counts) needs chain(); a branch’s returned handles aren’t checked (Task is object; the branch fails when it runs); .partial(), .expand() and .expand_kwargs() take object (Python typing can’t say “a list of this parameter’s type” for each argument), so a wrong mapped list is caught when the file loads, not in the editor.

    • Checked: make lint runs mypy --strict and basedpyright (its default, strictest mode, with reportUnusedExpression and reportUnusedCallResult off: a >> b and an operator alone on a line are statements on purpose) over the example DAGs and python/tests/typing/dag_types.py, whose expected mistakes carry ignore comments that must stay needed (57.3). basedpyright is pointed at pyproject.toml (--project): a pyrightconfig.json in a parent directory would win otherwise. An editor runs basedpyright on every file it opens: an execution environment for python/ turns off there the rules basedpyright alone enforces (the library and its tests are mypy’s and ruff’s), python/tests/typing keeping the strict ones, so the editor shows what make lint checks (the user, 2026-11-03: Zed flagged the library’s wrapped messages).

    • Not chosen: B Output typed as a subclass of Any (accepted everywhere: no argument checked); D′ calls kept as Output[T] with .value for each data pass and .on(Cls) typed Cls (every plain pass grows); C a mypy plugin (mypy only: editors on pyright get nothing); a types-schedr stubs package (the same typing language, so no more expressive, plus drift); a per-task @task(typed=False) typed Any (57.2: the user, for the same reason as B).

  • IDs. The DAG ID is an explicit, required string. A task ID defaults to the function name for @task and is required for operators. Duplicate IDs are a parse error. Using a @task function more than once in a DAG (e.g. in a loop): fn.override(task_id= "load_eu") (Airflow’s name), which can also override retries, retry_delay, timeout, queue, max_output_size; the duplicate-ID error points to it.

  • @task functions declare each parameter: *args / **kwargs and positional-only parameters (B114) are a parse error (arguments are stored and passed by name). Async functions are a parse error until M4 (see Async task functions); sensors and triggers are always async (see Sensors and triggers).

  • start, end (on the trigger) and initial_since (on Dag) without a time zone (start="2026-01-01", a date, a naive datetime) are read in the trigger’s time zone, like the cron expression (UTC for Every and no trigger). An explicit offset wins. (Unlike CLI input, where no offset means UTC: this is DAG code, written next to the trigger.)

  • trigger=: what starts runs. One Dag parameter, a typed object, for everything that starts runs besides people and other DAGs: a time trigger, Cron("0 3 * * *"), Every(timedelta(hours=1)) or Once("2026-12-24T23:00") (a single fire time), plus preset constants (DAILY, …); an event trigger, a @trigger function called with its arguments (trigger=new_files(prefix="s3://in/"), M4, see Sensors and triggers); or None (manual runs only). The time zone is set per time trigger, default UTC.

    • One base class, schedr.Trigger, which can’t be subclassed outside schedr (like the operators): custom triggers are @trigger functions.

    • catchup belongs to the time triggers that have fire times to miss: Cron(..., catchup=True), Every(..., catchup=True). Once, event triggers and None have none, so a catchup that would mean nothing can’t be written.

    • start and end belong to the trigger too: Cron(..., start=..., end=...), Every(..., start=..., end=...), and for event triggers .override(start=..., end=...) (M4). They only limit the runs the trigger creates (manual runs and backfills ignore them), naive values are read in the trigger’s time zone, and Every counts its fire times from start, so they are part of the trigger. None and Once have no window, so a start / end that would mean nothing can’t be written. Presets take them with .override(...), which every trigger has: trigger=DAILY.override(start="2026-01-01"). The master checks start not after end as before; the Python API checks it at parse time too.

    • initial_since stays on Dag: it sets the window of the DAG’s first run, which matters for manual-only DAGs and Once too, so it is about runs, not the trigger.

    • Not chosen for start / end: keeping them on Dag as “the DAG’s active period” (familiar from Airflow, but allows combinations that mean nothing, and ties Dag’s arguments to the trigger’s time zone).

    • Custom triggers are event triggers only. The master never runs Python, and fire times, catchup, backfill and since come from fire times it computes, so a calendar written in Python (“business days except holidays”) can’t be a time trigger. It can be an event trigger yielding events at those times (no catchup, no backfill); a calendar the master understands would be a built-in, data-only time trigger (e.g. Cron(..., exclude=[...])), possibly later.

    • Options of an event trigger (queue=, restart_if_idle=, start=, end=) are set with .override(...), as for tasks: new_files(prefix="s3://in/").override(queue="io").

    • Unchanged: run kinds (scheduled, event: where a run came from); the schedr.toml keys schedule / every / once / catchup / start / end (flat keys read naturally in TOML, and jobs have no event triggers); the Airflow layer’s schedule= (Airflow’s name, translated).

    • Not chosen: schedule= (the earlier name: it named half of what it took, and event triggers needed a When(...) wrapper to fit into it); when= (no clash with the other uses of “trigger”, schedr runs trigger, TriggerDagOperator, triggered_by, but vaguer). The noun (the DAG’s trigger) and the verb (trigger a run) read differently, and trigger= pairs with @trigger.

    • Once is the way to run a DAG once at a future time (e.g. a migration tonight at 23:00): an ordinary time trigger with one fire time, so pausing and the UI’s “next run” work as for any other (it has no previous fire time, so a DAG using since must set initial_since). It is set in the DAG file (reviewed, in git); there is no deferred manual trigger (see Runs: manual runs, backfill and pausing).

    • Daylight-saving changes (cron schedules in a time zone with DST; e.g. 30 2 * * * in Europe/Warsaw):

      • Gap (spring forward, 02:30 doesn’t exist): the fire time moves to the first valid moment after the gap (03:00), with planned_for = that moment; several fire times falling into the gap collapse into that one run. Not chosen: skipping (a hole in a daily DAG); shifting by the gap (03:30).

      • Overlap (fall back, 02:30 happens twice): a fire time whose hour field is fixed (30 2 * * *) fires once, at the first occurrence, so a daily schedule gives exactly one run per day; one with a wildcard or step in the hour field (*/15 * * * *, 0 * * * *) fires on each real occurrence (otherwise an hour without runs).

      • Windows stay consecutive: the runs around a change cover 23.5 or 25 hours of real time, correct for “one run per day”.

      • Every(...) is measured in real time (UTC), unaffected by DST. Its fire times are whole intervals from start, or from the Unix epoch without one (so Every(timedelta(hours=1)) fires on the hour, UTC); fire times before start exist too.

    • Cron details: 5 fields, or 6 with seconds first (no year field); presets @yearly, @monthly, @weekly, @daily, @hourly; when both day of month and day of week are restricted either one matches (classic cron). The hour field is fixed when it is a single number (all presets but @hourly are); anything else (*, a step, a range, a list) is not, for the overlap rule. The expression is matched against wall-clock times by croner; schedr turns each match into real moments by the rules above.

    • Time zones: the master uses the system’s time zone database, with one bundled into the binary as a fallback (containers often have none); the Python API checks zone names with zoneinfo.

  • Run time semantics. No Airflow-style “logical date” shifted one interval back. A run is created when its schedule fires and knows dag_ctx.run.planned_for (the fire time) and dag_ctx.run.since (the previous fire time), so the run covers (since, planned_for] (see Run parameters and the DAG context; manual runs: see Runs: manual runs, backfill and pausing). The first run is the first fire time at or after start. catchup defaults to False. (Airflow 3 moved the same way: cron schedules run at the fire time.)

  • Without start the schedule starts when the master first stored the DAG: a new daily DAG unpaused at 10:00 gets the run for today’s fire time at once; with catchup=True every fire time since it was first stored gets a run.

  • max_active_runs counts running runs; queued runs wait outside it. A scheduler pass creates at most 100 runs per DAG (a catchup backlog with no limit continues in the next pass).

  • end (optional, mirror of start): the last scheduled run is the last fire time at or before end (in the trigger’s time zone). After it the DAG stays listed with its history, but no new scheduled runs are created; the UI shows it as “ended”. Manual runs are still allowed: start and end apply only to runs of kind scheduled; manual and backfill runs may be for any time, before start or after end (see Runs: manual runs, backfill and pausing). Native use: temporary DAGs (a campaign, a migration window) that stop on their own.

  • max_active_runs (default 1; None = no limit): at most this many runs of the DAG at a time. A fire time that comes while the DAG is at its limit is treated as missed (like fire times missed while the master is down) and the catchup rules decide: with catchup=False, when a run finishes only the most recent missed fire time gets a run (a slow DAG never builds a backlog); with catchup=True the missed ones get runs in order, still at most max_active_runs at a time. Scheduled fire times never queue (they are missed); only manual and backfill runs wait, as queued. Default 1 because overlapping runs are rarely wanted in a sync-style workload. Manual and backfill runs count too, and wait instead of being dropped (see Runs: manual runs, backfill and pausing).

  • tags and description: metadata (shown in the UI, filter by tag).

  • Run parameters: Dag(..., params=SomeDataclass); see Run parameters and the DAG context.

  • Concurrency limits (besides worker slots and queues, which are capacity, not intent):

    • max_active_tasks on the Dag (default None, no limit): at most this many tasks of the DAG running at once, across all its runs (limit the load a DAG puts on other systems; keep one big DAG from filling every worker).

    • max_active_per_run on a task (default None): at most this many instances of the task running at once within one run; mainly to limit a mapped task’s fan-out (@task(max_active_per_run=10), 1,000 instances, 10 at a time).

    • max_active on a task (default None): the same across all runs (e.g. a task holding an exclusive external lock).

    • Task limits also on operators and in StepDefaults; an unmapped task has one instance per run. schedr.toml jobs need no key (one-task DAGs: max_active_runs covers them).

    • Across DAGs (a named limit shared by several DAGs, Airflow’s pools): not now; queues (a dedicated worker group with a fixed number of slots) cover it. Possibly later: named limits in the server configuration, referenced by tasks.

    • How the master applies them: see Task assignment.

    • Decided for M4.4 (decisions 87-92 and 95-96, the user’s, 2026-10-30: all as recommended):

      • 87, which version’s limits (A): max_active_per_run from each run’s own DAG version; the limits across runs (max_active_tasks, max_active) from the DAG’s current version, since a limit across runs has one value at a time. Not chosen: B each run’s own version for all (no single limit would hold); C the current version for all (a run’s own limit changing while it runs).

      • 88, counting (A): in the master’s memory, the running, cleaning-up and assigned-not-started instances per DAG and per task, rebuilt from the database when the master starts (the lease keeps one master, its writes fenced) and checked as each task is assigned; tested to match the database after a restart. Not chosen: B a count query in each assignment’s transaction (a query per assignment, B18’s cost at thousands a round). This replaces “in the same transaction” in Task assignment.

      • 89, mapped tasks: each instance counts toward all three limits; the -1 row never does.

      • 90, max_active_per_run on an unmapped task (A): a parse-time warning shown by dags check (it limits nothing: one instance a run), not for a value from StepDefaults. Not chosen: B silent; C an error (breaks defaults shared with mapped tasks).

      • 91, the reason and the metric: “waiting: max_active_per_run (10) reached” (the limit and its value); master_tasks_waiting{reason="max_active_tasks" | "max_active" | "max_active_per_run"} beside the existing reasons.

      • 92, proof (B): an integration test with many tasks and tight limits sampling the active counts, and a stress scenario written in M4.4 too, run when the user next runs the stress suite (never without their go). Not chosen: A running the scenario as part of M4.4.

      • 95, changing a limit without a code change (the user, 2026-10-30: not now): no override through the API or CLI (like Airflow’s editable pools); with limits shared across DAGs, a proposal for M6 (PLAN.md).

      • 96, limits on the DAG page (the user, 2026-10-30: yes): each limit set with its current count (”max_active_per_run 10, 7 running”), from the master’s counts (88A), beside 91’s waiting reasons.

      • Settled by precedent: a limit below 1 is a parse-time error (None: no limit); lowering a limit lets the running finish and holds new ones until under it; tasks waiting to retry and tasks the master completes never count; the counts follow the master’s rollback rules (a rolled-back message restores them).

  • Defaults are typed, not a dict: Dag(defaults=StepDefaults(retries=2, ...)) instead of default_args={...}. Groups can set their own defaults; a task’s own arguments win.

  • Routing: outcomes first, @branch for subsets (see Task results and outcomes). To route on what a task found, the task returns an outcome and downstream tasks use .on(...):

    @task
    def size_of(rows: list[Row]) -> Big | Small: ...
    
    size = size_of(rows)
    full_load(size.on(Big))
    incremental(size.on(Small))
    

    @branch chooses any subset of its direct downstream tasks. The function returns task handles (one or a list), not task ID strings, so typos are caught at parse time. In the model the branch’s output is the list of task IDs, and each of its outgoing edges is a selection edge, taken when the branch chose its target. A target not chosen counts that edge as skipped, like any edge not taken (decision 55B, the user’s, 2026-10-28: one rule for every edge): under NoneFailed it still runs if another of its edges succeeded, under AllSucceeded it is skipped. The empty subset is allowed: returning [] skips the direct downstream tasks that have no other edge (None is not allowed; write []). Not chosen: a target not chosen skipped outright, whatever its other edges (A: Airflow’s behaviour, but an exception to counting edges). For M5: Airflow skips an unchosen target outright; schedr isn’t Airflow one to one (the user’s), so a translated @task.branch follows this rule, and the translation’s notes say so for a target with other upstream tasks (give it AllSucceeded to be skipped whenever not chosen).

    @branch
    def targets(cfg: Config) -> list[Task]:
        return [t for t, on in ((to_s3, cfg.s3), (to_gcs, cfg.gcs), (to_local, True)) if on]
    
    targets(cfg) >> [to_s3, to_gcs, to_local]
    
  • Task groups: with group("name"):. A group organises tasks while the DAG is written; it isn’t something that runs. At parse time it is flattened: its tasks become ordinary tasks with prefixed IDs (name.task_id; nested groups outer.inner.task_id) and ordinary edges, plus group metadata for the UI (members, name, parent). The master schedules ordinary tasks and edges; it reads groups only to check them (decision 64) and to accept decision 94’s edges.

    • What it is for: reusing a piece of DAG (a function building extract → transform → load, called once per source, each call in its own group so the IDs don’t collide); shared settings (its own StepDefaults, run_if, uses=; an inner group’s override an outer one’s, a task’s own arguments win over both); depending on a block of work (start >> load >> publish without listing what load holds); reading the graph (the UI draws a box around its tasks).

    • What it isn’t: it has no state (no “group succeeded” stored; the UI may derive one from its tasks), no trigger rule of its own (run_if on a group is only its tasks’ default; the group never waits nor is skipped, its tasks are), not a sub-DAG (no runs, not triggered), and not mappable (mapped groups not supported, in both APIs; see Airflow compatibility: Branching, task groups and mapping).

    • A dependency on a group goes through its roots and leaves (decision 56A, the user’s, 2026-10-29): x >> group links x to the group’s roots (its tasks with no upstream inside the group), group >> y links the group’s leaves (no downstream inside it) to y, as Airflow’s TaskGroup does. Roots and leaves are computed once the whole DAG is written, from all its edges (Grok’s review, 2026-10-30: computing them when the group’s block closed missed edges written after it), so where a statement is written doesn’t matter; a dependency inside a group counts for that group’s ends. A dependency on an empty group, or on one whose tasks form a cycle, is a parse error, reported when the with Dag(...) block ends and naming where the dependency was written (decision 97, the user’s, 2026-10-30: A, sync.py:42: ...; not chosen: B the message alone, whose traceback points at the block’s end). Example: with a >> b and c in load, start >> load gives start >> a, start >> c, and load >> publish gives b >> publish, c >> publish. Edges count in trigger rules (55B), so this lets skips flow along the group’s own chain: a skipped a skips b, which doesn’t also hang on start. Not chosen: B every task in the group (the earlier wording: n×m edges, a task whose in-group upstream was skipped still runs on the outer edge, and Airflow’s translation would need a rule of its own); C every task for x >> group and the leaves for group >> y (neither rule’s simplicity).

    • Built in M4.2b (2026-10-29): with group("load", defaults=StepDefaults(...), run_if=...) as load: (schedr.group, a Group handle); a group’s name is one ID part; it may not repeat in its parent nor be a task’s ID; the same @task function in two groups needs no .override(); a group whose block raised (the error caught in the DAG file) is closed all the same.

    • A dependency on a group that ends with a @branch (decision 94, the user’s, 2026-10-30: B): route >> then joins the set of the group’s last tasks to the tasks after it with plain order edges, a @branch among them included: it counts as having run, whatever it chose, and each task after it applies its own run_if over that set (NONE_FAILED: runs unless one failed or all were skipped; ALL_SUCCEEDED: only when all succeeded). The branch’s own edges stay choices. The master accepts an order edge from a @branch to a task outside the branch’s group (every other edge from a branch is a choice). Before, the edge became a choice the branch never made, so then was always skipped although the group succeeded (ten cases laid out for the user, 2026-10-30). Not chosen: A refusing such a dependency at parse time; D a branch in a group choosing only tasks inside it (refuses DAGs that work, and Airflow translations).

    • In DAG JSON (decision 64, the user’s, 2026-10-29: A): a top-level groups list ({id, parent}, outer before inner) and an optional group on each task (its innermost group), both left out when empty; the master checks them (unique, parents declared, no cycle, each task’s group declared) and otherwise ignores them. Membership is explicit, so M5’s prefix_group_id=False can be represented. Not chosen: B membership from the ID’s prefix (nothing to store, but prefix_group_id=False can’t be said, and a group holding only nested groups has no record).

    • On the run graph (decision 65, the user’s, 2026-10-29: A): clustered boxes. Each layer is ordered group by group (sibling groups in one fixed order in every layer, so boxes never swap sides; tasks outside groups fall between them by barycenter), a long edge’s points belong to the innermost group both its ends share, and after the x fit everything moves right only: an item that must be left of a group’s box (before its members, or up to the last item of an earlier group in a layer without them) moves the whole group right, any other item inside a box moves right of it. A box is its members and nested boxes, with padding and a label band; the gap between layers grows with the deepest nesting. Property tests check that a box holds its tasks and no other, nested boxes sit inside their parent’s, and nothing overlaps. Not chosen: B bounding boxes over the unchanged layout (a box may enclose other tasks); C labels without boxes.

  • Mapping keeps Airflow’s names, .partial(...) / .expand(...), so both APIs share one mental model (e.g. load_file.partial(bucket="raw").expand(path=files)). Which mapping features beyond that: see Airflow compatibility (Dynamic task mapping), decided for both APIs.

    • Built in M4.3 (2026-10-29), in three sub-steps: M4.3a the API, DAG JSON and checks; M4.3b the master (expansion, instances, fan-in); M4.3c the runner, API, CLI, UI and run_dag per instance. @task functions only for now (operators’ .partial() / .expand(), which M5’s BashOperator needs, later). For type checkers .expand(...) returns list[R].

    • DAG JSON (decision 69, the user’s, 2026-10-29: A): the fixed arguments stay in arguments (.partial), and an expand field says what varies: {"product": [{"name": name, "value": value}, ...]} (.expand; each value a literal list or a reference to a list, in the order written) or {"kwargs": value} (.expand_kwargs, a list of dicts). Not chosen: B marking mapped arguments inside arguments (every reader of arguments would have to know the wrapper).

    • Checked when the file loads: each mapped list against list[<the parameter's type>] (literal elements encoded, references typed); names (known, not both fixed and mapped, the rest of the required parameters fixed); a @branch can’t be mapped. A reference to a mapped task’s output is a list of its output type: indexing is allowed (results[0]), a field of every element (results.rows) refused; .on(...) and .outcome on the whole output refused outside .expand() (element by element inside it). A list from a mapped task some of whose instances may be skipped (it maps over a narrowed mapped output, or over such a task) has None for them: the receiving type must allow it. Not under run_if=RunIf.ALL_SUCCEEDED: there a skipped instance skips the whole task (B116).

    • Mapping over a mapped output (decision 70, the user’s, 2026-10-29: A): the downstream task’s instances are created once every upstream instance has finished, then check[i] gets process[i]’s output. Not chosen: B starting check[i] as soon as process[i] ends (a pipeline: faster, but instance pairs to track and the count known only at the end).

    • In the REST API (decision 71, the user’s, 2026-10-29: A): one row per instance in a run’s tasks (map_index, -1 for an unmapped task), per-instance URLs with ?map_index=N. Not chosen: B nesting instances under their task (a new URL family).

    • [mapping] max_instances (1024, at least 1) in the server’s configuration.

    • The order of the instances (decision 79, the user’s, 2026-10-30: A): over several lists, the first argument written varies slowest (.expand(region=[...], day=[...]): all of the first region’s days, then the next region’s), as in Airflow; it is the gather’s order. So product is an ordered list in DAG JSON. Not chosen: B the parameters’ names in alphabetical order (no format change, but renaming a parameter would reorder map_index).

    • Lanes: mapping over a mapped output (decision 70 revised, the user’s, 2026-10-30: B): check.expand(n=sizes) over the mapped size creates check’s instances as soon as size has expanded (its count is known then), and check[i] waits only for size[i]: each lane moves on its own, and the barrier is the first task taking the whole list (a gather) or any task that isn’t mapped element by element. Only that element-wise data edge is a lane (70.1): every other edge into a mapped task, an order edge from the same task included, counts the upstream as a whole, so size >> check next to the expansion restores the barrier (A’s behaviour: nothing of check starts before all of size has finished, nothing of it runs if size failed); M5’s Airflow layer adds that edge itself. A reference to size anywhere else in check (.partial(all=sizes), sizes[0]) also makes the edge whole. Not chosen: A the barrier always (slower: each step waits for its slowest instance); C a per-task setting (the edge does it). .on(...) stays per element when the edge is whole (decision 119, the user’s, 2026-10-31: A; B80): check.partial(all=sizes).expand(n=sizes.on(Rows)) waits for the whole of size, then skips each instance whose size[i] ended with another outcome (or was skipped), as a lane does. The whole mapped task’s own outcome only says its instances ended, so it never decides an .on(...). Not chosen: B refusing .on(...) at load when the output is used again (a form the API accepts, and the guide promised).

    • .on(...) on an order edge from a mapped task (decision 120, the user’s, 2026-10-31; B132): results.on(Rows) >> report() counts as one edge per instance, each taken when that instance ended with one of the outcomes, and report’s own run_if decides over them with its other edges: NONE_FAILED (the default) runs it when any instance ended Rows, ALL_SUCCEEDED only when every one did, as a mapped task applies its rule to its instances (75b D). With no instances the edge is taken, as the mapped task with an empty list succeeds. Before, Rows was compared with the whole task’s own outcome and report was always skipped. Not chosen: always every instance; always any; refusing it at load as for arguments.

    • How a mapped task is stored (decision 74, the user’s: A): every task keeps its map_index = -1 row. For an unmapped task it is the one runnable instance; for a mapped task it is the task as a whole (what edges, trigger rules and the run’s result look at), never sent to a worker, with no attempts or output: scheduled until its upstream is ready, running once expanded, then its state from its instances. Expansion adds the instances 0..N-1, which run, retry and are cancelled each on its own. Not chosen: B no row for the whole task (every rule would aggregate instances).

    • Its state from its instances (decision 75, the user’s): a failure fails the step at once (75a: B): when an instance fails after its last retry (or its lane’s upstream did), the task’s other instances are cancelled, running ones stopped (their results ignored); the task is failed (upstream_failed when only lanes failed), its downstream upstream_failed. Otherwise, once every instance has finished, the task applies its own run_if to its instances as if they were its edges (75b: D): NONE_FAILED (default) skipped when every instance was skipped, else success with None for the skipped ones; ALL_SUCCEEDED skipped when any was (“all or nothing”); no instances (N = 0): success with []. A gather that must see everything maps without narrowing (.on(...) skips instances; the task deciding on the whole Rows | Missing doesn’t), and expected failures are outcomes, not exceptions (see the mapping guide’s example). Not chosen: 75a A letting the other instances finish (Airflow’s); 75b C always success with [None, ...].

    • An instance’s element (decision 76, the user’s: A): the master resolves each instance’s mapped values and sends them with its inputs under $expand (with the element’s outcome under $expand_outcomes for one from a mapped upstream, so a union decodes to the right member); the runner passes them as the mapped parameters. The task JSON is the same for every instance. The list mapped over isn’t sent whole as well (each instance would carry all of it: inputs growing with the square of its length, B83): only what the task’s other arguments reference is. Not chosen: B a task JSON per instance (inline in AssignTask, so a large element could exceed the message limit).

    • A mapped task’s whole output (decision 77, the user’s: A): stored per instance only; a downstream task’s list is built when read, in map_index order, None for a skipped instance. Not chosen: B storing the list on the -1 row too (twice the storage, and the list could exceed limits its instances met).

    • Around it, per instance (M4.3c) (decisions 80-86, the user’s, 2026-10-30: all A):

      • 80, the run’s tasks in the API: the -1 row is listed too, as the task as a whole (map_index: -1, instances: N, null for an unmapped task, and reason when it failed without an attempt), then its instances 0..N-1. Not chosen: B instances only.

      • 81, a mapped task’s output: without ?map_index, the gathered list as a downstream task receives it (None for a skipped instance); with ?map_index=N, that instance’s output and outcome. Not chosen: B an error without ?map_index.

      • 82, attempts, logs, retry, cancel: attempts, logs and retry need ?map_index=N on a mapped task (a 400 gives the range without it); cancel without it cancels the whole task, with it that instance. Not chosen: B merging every instance’s attempts and logs.

      • 83, the run graph: one node per mapped task, its instance count in the label and a count of its instances by state; the task panel lists the instances, each with its attempts, log and output. Not chosen: B a node per instance (a wide fan-out swamps it).

      • 84, schedr.task_ctx: task_ctx.task_id, task_ctx.try_number and task_ctx.map_index (None for an unmapped task) while a task runs: the object secrets and connections join later. Not chosen: B dag_ctx.run.map_index (not the run’s); C the SCHEDR_MAP_INDEX variable only.

      • 85, run_dag: result.tasks["fetch"] is the task as a whole (its .output the gathered list); result.tasks["fetch"][1] (and .instances) each instance’s result. Not chosen: B "fetch[1]" keys.

      • 86, the CLI: --map-index N on tasks logs / attempts / output / cancel / retry; runs show and dags test list instances as fetch[0], fetch[1], … after the task’s own row. Not chosen: B fetch[1] as the task argument.

    • Why a task failed with no attempt (decision 78, the user’s: A): a nullable reason on task_instances (more instances than max_instances; a mapped list that is null or not a list when it expands). Not chosen: B reusing queued_reason.

    • Settled by Grok’s M4.3 review (2026-10-30), within decisions 75a, 76 and 82: ?map_index=-1 (the whole task, as listed) means the same as no index, and an index outside 0..N-1 is a 400, on every endpoint (cancel included); a result that arrives after the step already failed is ignored (the instance ends cancelled, its output not stored); an element of .expand_kwargs() over a mapped task that isn’t a dict fails its instance at assignment, unretried (input_mismatch), as a mapped list’s does at expansion; dicts written in the DAG for .expand_kwargs() are checked like .expand()’s names and types when the file loads (an argument also in .partial() refused, by the master too, which also refuses a mapped @branch); an expansion is stored in one transaction; .on(...) naming every outcome of a task is an unconditioned edge (no None to allow).

    • An element written with a t-string or dag_ctx is built per instance (decision 118, the user’s, 2026-10-31: A; B81): region.expand(name=[t"eu-{year}", "us"]), .expand(of=[dag_ctx.run.kind, "other"]), and an entry of an .expand_kwargs() dict alike. The master doesn’t render such an element (it renders nothing user-written): it counts it when the task expands and sends it to that instance in its stored form, under $expand_values, with the outputs its template references; the instance’s runner builds it as it builds an argument. Airflow renders Jinja per mapped instance too. Not chosen: B refusing it at load (workaround: build the list in a task, or pass the value through .partial()), surprising for a form the language accepts.

  • Strict arguments. An unknown argument is a plain Python TypeError when the DAG file is imported (so an import error). The native API never “accepts and warns”; that applies only to the Airflow layer (see Airflow compatibility: Thin translating classes).

Example (it runs as written with M1: schedr dags test sync_customers --path sync.py; queues other than default and secrets in env come with M2 and M4):

from datetime import timedelta

from schedr import CommandOperator, Cron, Dag, StepDefaults, dag_ctx, task

with Dag(
    "sync_customers",
    trigger=Cron("0 3 * * *", tz="Europe/Warsaw", start="2026-01-01"),
    defaults=StepDefaults(retries=2, retry_delay=timedelta(minutes=5)),
):

    @task
    def extract() -> list[dict[str, str]]:
        return [{"id": "1", "name": "Ada"}, {"id": "2", "name": "Grace"}]

    @task(timeout=timedelta(minutes=10))
    def load(rows: list[dict[str, str]]) -> int:
        print(f"loading {len(rows)} customers")
        return len(rows)

    rows = extract()  # Output[list[dict[str, str]]]
    count = load(rows)  # load depends on extract (data flow)

    CommandOperator(  # depends on load: its command uses `count`
        "notify",
        command=["echo", t"synced {count} customers for {dag_ctx.run.planned_for}"],
    )

Outcomes, failures and joins

  • Only success branches. A user cannot create a failure branch in the native API (no on_failure edges, no failure trigger rules, no callbacks). A failed task fails; its downstream tasks become upstream_failed.

    • Rationale: a failure means an unexpected failure. A failure branch is the same as catching an exception and reporting success: failure becomes control flow. Instead, the user handles the problems they expect inside the task and turns them into success paths: outcomes, routed with .on(...) (a caught exception returned as an outcome of a Python task; a declared exit code of a command / script task; see Task results and outcomes). So whenever a task fails, the failure was not expected, and schedr handles it: retries, notifications, failing the run.

    • Rejected: master-side failure rules (trigger rules such as one_failed or all_done evaluated by the master). They would be sound (the master sees timeouts, memory kills and lost workers, and retries stay intact), but they are still failure branches and defeat the rationale above, even if limited to the Airflow layer.

    • Work that must happen whatever the result (releasing a lock, deleting temporary resources) is not error handling; see Cleanup and resources.

  • Python tasks: an exception caught inside the task is a normal return (route on it by returning an outcome); an uncaught exception is a failure. No exception-to-outcome mapping, so no ambiguous cases with try/except.

  • Failures are still recognized and recorded by schedr itself (UI, logs, run history, notifications): the attempt status (failed, timed_out, oom_killed, …), the structured error summary of a failed Python task, and the ProcessResult of a failed command/script (stderr, exit code) are stored and shown. They are not available to other tasks as inputs.

  • Process outcomes for command / script tasks: an enum (Python tasks have outcomes too: see Task results and outcomes). The user declares an IntEnum subclass of schedr.Outcome; values are exit codes, names are outcome names (shown in the UI). A declared exit code means success (no retry); any exit code not in the enum is a failure. Possibly later: retry control per exit code (e.g. retry on 75 / EX_TEMPFAIL, never on 2).

    class Check(Outcome):
        CHANGED = 0
        UNCHANGED = 1
    
    check = CommandOperator("check", command="./has_changes.sh", outcomes=Check)
    check.on(Check.CHANGED) >> load
    check.on(Check.UNCHANGED) >> report_nothing
    check >> cleanup                      # plain >>: after any success outcome
    
    • Typed: a typo is caught by the type checker and at parse time. One exit code per member; several codes → several members, check.on(Check.A, Check.B).

    • Default: schedr.DefaultOutcome (single member SUCCESS = 0) when outcomes isn’t given: 0 is success, everything else is a failure.

    • A custom enum replaces the default entirely; 0 is not added implicitly (a user who declares their own enum is expected to know what they’re doing).

    • A plain >> from a task with outcomes means any success outcome. Edges not taken are skipped like branch skips.

  • Two trigger rules, no others. The model (neutral names, no Airflow terms) has exactly two rules, and the native API offers both:

    • NoneFailed (the default): a task runs when every upstream task that wasn’t skipped succeeded, and at least one upstream succeeded; it is skipped when all its upstream tasks were skipped; it becomes upstream_failed if any upstream task failed. Without skipped upstream tasks this is exactly Airflow’s all_success; after a branch, joins work with nothing to configure.

    • AllSucceeded (opt-in: @task(run_if=RunIf.ALL_SUCCEEDED), also on operators, groups and in StepDefaults; enum RunIf { NONE_FAILED, ALL_SUCCEEDED }, default NONE_FAILED): runs only when every upstream task succeeded; any failure → upstream_failed; otherwise any skip → skipped. For “run only if every upstream task really ran”:

      check.on(Check.CHANGED) >> load      # load is skipped when nothing changed
      [load, refresh_meta] >> publish      # with ALL_SUCCEEDED: skipped too
      
    • Both decide as soon as the result is certain: the first failure makes the task upstream_failed without waiting for the others; for AllSucceeded, a skip decides once no other edge can still fail (a failure wins).

      Upstream tasks…

      NoneFailed

      AllSucceeded

      all succeeded

      runs

      runs

      some skipped, the rest succeeded

      runs

      skipped

      all skipped

      skipped

      skipped

      any failed

      upstream_failed

      upstream_failed

      Data from a skipped upstream task

      None (parameter must allow None)

      never happens

    • A NoneFailed task taking data from a task that can be skipped (downstream of a branch or outcome) must have a parameter type that allows None, or it’s a parse error. An AllSucceeded task never receives None from upstream, so it needs no Optional. Order-only dependencies (>>) need nothing.

    • In the native API skips come only from @branch and .on(...).

    • Airflow’s trigger rules are translated onto these two or are an error (see Airflow compatibility: Trigger rules).

    • Rejected: AtLeastOneSuccess (run as soon as one upstream task succeeded, tolerating failures of the others; Airflow’s one_success). Its main use, redundant sources (“if A is down, use B”), is an expected problem: the source task returns it as an outcome and NoneFailed joins the sources (see Task results and outcomes), with no failure tolerated. What remains is racing (not waiting for the slower upstream), which doesn’t justify the costs: inputs that depend on timing (a retry could see different data), upstream tasks that can’t be cancelled, and a downstream task that succeeded in a run that still fails.

  • Run result: a run is failed if anything unexpected went wrong in it, otherwise success. Follows from the rationale above: failing the run (and notifying) is part of how schedr handles an unexpected failure. In both APIs.

    Event

    Fails the run?

    Why

    A task failed after its last retry (failed, timed_out, oom_killed, lost, …)

    yes

    an unexpected failure that wasn’t recovered

    A cleanup failed after its last retry (see Cleanup and resources)

    yes

    the same; a resource may be leaking

    An attempt failed but a retry then succeeded

    no

    schedr recovered from it

    A task became upstream_failed

    no

    a consequence; the original failure already counts

    A task was skipped (branch, outcome, edge not taken)

    no

    an expected path

    A task returned an outcome such as Unavailable

    no

    an expected problem handled by the user: a success

    • The result is set when every task and every cleanup has finished; independent parts of the graph keep running after a failure (no fail-fast; the UI may show “will fail” earlier).

    • Not Airflow’s leaf rule (the run fails only if a leaf task failed), which turns runs green that hid a failure: a task failing behind a join Airflow already skipped (its all_success decides on the first skip); a failed cleanup (not in the graph); a cleanup leaf that succeeded after the work failed. Migrated DAGs differ only in such cases.

    • Runs cancelled by a user: running attempts are cancelled (SIGTERM, then SIGKILL) and their per-task cleanups run; tasks not started become cancelled; resource cleanups run if their setup succeeded (cancelled is a final state, so all users are done). The run ends as cancelled, unless an unexpected failure happened in it (including a cleanup failing during the cancel): then failed, so a cancel never hides a failure. A pure cancel sends no “run failed” notification.

    • No “clear” (re-running tasks of an existing run). A run is never re-run partially; to run again, trigger the DAG again (a new run). So a run’s results, outcomes and resources never change once it has finished.

  • Notifications are configured, not programmed, and live outside the task graph. A DAG names notification channels (Dag(..., notify=["team-a-slack"])); channels are defined in the server configuration by operators, with credentials from environment variables (server secrets, like the database password), not from the user-facing secret storage, since the master never fetches from it. The master sends them (formatting a message runs no user code).

    • Events (an Event enum):

      Event

      When

      Default

      RUN_FAILED

      a run ended failed (see Run result); includes cleanup failures, named in the message

      yes

      TASK_FAILED

      a task failed after its last retry (earlier than RUN_FAILED; Airflow’s email_on_failure)

      opt-in

      TASK_RETRY

      an attempt failed and will be retried (Airflow’s email_on_retry; noisy)

      opt-in

      RUN_CANCELLED

      a run was cancelled by a user

      opt-in

      RUN_SUCCEEDED

      a run ended success (“the report is ready”)

      opt-in

      RUN_RECOVERED

      a run succeeded after the DAG’s previous run failed (“it’s fixed”)

      opt-in

      TRIGGER_FAILING

      the DAG’s trigger raised [triggers] failing_after times in a row (default 5), or stopped because its generator returned (see Sensors and triggers): otherwise a broken trigger fails silently, with no runs and nothing red

      opt-in

      Not now: a task running too long / SLAs (a separate, large feature; errors in the Airflow layer). The default event set is a server setting (default: RUN_FAILED).

    • Choosing events per channel: a plain list means the default events; a dict chooses them per channel. Events are chosen where the DAG names the channel (not on EmailChannel), so the same form works for server and DAG-defined channels; Event is an enum, so a typo is an attribute error at import.

      Dag(..., notify=[team_a, "ops-slack"])                 # default events: RUN_FAILED
      
      Dag(
          ...,
          notify={
              team_a: [Event.RUN_FAILED, Event.TASK_RETRY],
              "ops-slack": [Event.RUN_FAILED, Event.RUN_RECOVERED],
          },
      )
      
    • Channel types: email (server transport; channels in the server configuration or DAG-defined, see below) and a generic webhook (an HTTP POST with a JSON body), defined only in the server configuration with credentials from environment variables; it covers Slack, Microsoft Teams, PagerDuty and Opsgenie through their incoming webhooks. Dedicated Slack / Teams channels with nicer formatting: possibly later.

    • Message content is fixed by schedr (no user templates: formatting runs on the master and must never run user code): the DAG, the run, the event, the failed tasks with their error summaries (exception type and message, or exit code and the tail of stderr), cleanup failures, links to the run and the logs in the UI. Webhooks get the same information as structured JSON, so receiving systems can format it. Secret values never appear (error summaries are already masked by the agent).

    • DAG-defined email channels. Besides channels defined in the server configuration (named by strings), a DAG can define an EmailChannel holding only recipients:

      team_a = EmailChannel("team-a", ["a@example.com", "b@example.com"])
      
      with Dag("etl", trigger=DAILY, notify=[team_a, "ops-slack"]): ...
      
      • Objects are DAG channels, strings name server channels. Passing the object (not its name) means a typo is a NameError at import, and a DAG channel can’t shadow a server channel of the same name. It can be reused through a helper module in the DAG root; each DAG’s JSON carries the recipients it uses.

      • The server keeps everything with credentials: the email transport (SMTP server and its credentials) is in the server configuration; the DAG never handles a credential.

      • Checks: address syntax at parse time; server channel names, and recipients against an optional allow-list of email domains in the server configuration, when the master validates the DAG (a violation is a DAG error in the UI). The server can switch off DAG-defined channels entirely.

      • Email only, for now: other channel types (e.g. a Slack webhook) need a credential, and the master never reads the user-facing secret storage; they stay server-defined.

      • Which events each channel gets: chosen in notify= (see above).

      • Not chosen: naming DAG channels by strings in notify= (mixes them with server channels in one namespace); an inline Email("a@x.com") in notify= (can’t be reused).

Run parameters and the DAG context

The DAG context, dag_ctx, describes the current run: the run information and the run’s parameters. It is the same for every task of the run, known before any task starts, and never comes from another task, so reading it anywhere is safe and deterministic (it isn’t task data: “data flow is the only way to pass task data” still holds).

  • One name everywhere. In the DAG body (parse time) dag_ctx.params.region is a reference, filled in at run time; in a running task the same expression gives the value. Using it as a value in the DAG body (e.g. if dag_ctx.params.full:, or comparing it with ==, B108) is a parse error (“a reference can’t be used as a value in the DAG file; branch with a task”), as for outputs. from schedr import dag_ctx. (Replaces the earlier schedr.templates.run placeholder.)

  • Run information: dag_ctx.run.id, dag_ctx.run.kind, dag_ctx.run.planned_for, dag_ctx.run.since, dag_ctx.dag_id, … (scripts also get it as SCHEDR_* environment variables, see Plain script delivery).

  • Values at run time: while the runner calls a task’s function, dag_ctx gives the values (planned_for / since as aware datetimes in UTC), set with a context variable for the call only; everywhere else (DAG body, tests outside a run) it gives references. Type checkers read them as the values in both places (datetime, str; decision 57), as they read a task call.

Declaring parameters.

@dataclass
class ReportParams:
    region: Literal["eu", "us"] = "eu"
    full: bool = False
    day: date | None = None
    limits: list[int] = field(default_factory=list)

with Dag("report", trigger=DAILY, params=ReportParams):
    ...
  • A dataclass or a Pydantic model, with the same supported types as outputs.

  • On a DAG with a schedule every field needs a default (scheduled runs use the defaults); a DAG without a schedule may have required fields, given at trigger time.

  • schedr.toml jobs: [jobs.<name>.params] with default values (each type taken from its default):

    [jobs.report_daily.params]
    region = "eu"
    full = false
    limit = 100
    
  • The runner turns the declaration into a JSON Schema stored in the DAG JSON.

Setting values (per run).

Run

Values

scheduled

the defaults

manual, UI

a form generated from the schema, pre-filled with the defaults (text, number, checkbox, date picker, a select for Literal, JSON for lists / nested objects)

manual, CLI

schedr runs trigger report -p region=us -p full:=true -p 'limits:=[1,2]', or --params '{"region": "us"}' (the field syntax of In-task CLI)

The master validates the values against the schema before creating the run (no user code runs; Pydantic validators run only when a task decodes the values); unknown keys or wrong types are a rejected command with the reason. The values are stored with the run and shown in its summary.

Reading.

Where

How

Example

a task argument (typed)

a reference in the DAG body

extract(region=dag_ctx.params.region, day=dag_ctx.params.day)

t-strings (commands, script args, env, task arguments)

a reference, rendered by the agent

command=["./publish.sh", t"{dag_ctx.params.region}"]

Python task code (also cleanups, resource setups)

read at run time, decoded strictly into the dataclass passed

p = dag_ctx.params(ReportParams); dag_ctx.run.planned_for

scripts and commands (incl. schedr.toml jobs)

schedr dag-ctx (see In-task CLI)

schedr dag-ctx params get --field region

plain Python scripts

schedr.script (see In-task CLI): the same dag_ctx as Python task code

from schedr.script import dag_ctx; dag_ctx.params.region

  • Paths are checked at parse time against the declared dataclass (an unknown field, or a type that doesn’t fit the task’s parameter, is an import error). Statically dag_ctx.params.x is untyped (Any), as with output paths; dag_ctx.params(ReportParams) is typed by the class passed (one not matching the declaration is an error).

  • A task argument gets the value with its type (a date stays a date).

  • The context travels in each task’s specification (AssignTask, run information): reading it never calls the master.

  • Parameters are not environment variables (no clashes with other variables).

  • What can’t use parameters: the master (it only validates them; scheduling never depends on them); edge conditions (no routing on a parameter: a task returns an outcome, or a @branch decides); notification messages show the values but have no templating. Mapping over a parameter (.expand(x=dag_ctx.params.items)) is refused at parse time: the number of instances would depend on it.

How M4.5 builds it (decisions 132-138, the user’s, 2026-11-01: 1A 2A+E 3A 4A 5A 6A):

  • 132. Order: M4.5a params (declaration, the master’s check, stored with the run, runs trigger -p / --params, dags test -p, references, dag_ctx.params(Cls), the run’s summary); M4.5b the agent channel (schedr dag-ctx, schedr.script); M4.5c the UI’s trigger form. Not chosen: the channel first.

  • 133. The master checks values with the jsonschema crate (default features off: it never fetches a remote $ref; formats validated), plus a check of every schema when the master validates the DAG: only the keywords and formats that crate checks (and annotations such as title, description, default, examples, discriminator), only local $refs; anything else is a DAG error naming the keyword, so a schema never asks for a check the master silently skips. Pydantic’s own validators still run only when a task decodes the values. Not chosen: a checker of our own (Pydantic constraints refused); boon (no release since 2025-01); a worker validating with the real class (user code before the run exists, a trigger waiting for a worker).

  • 134. Shown masked: a run’s params are shown (API, UI, runs show) masked like a task’s output (decision 131: texts, and fields named by secret words); tasks get the real values. Not chosen: shown as given.

  • 135. At most 64 KiB of a run’s params as JSON, defaults included, refused at trigger time with the reason (and a DAG whose defaults are over it, at parse time): they travel in every task’s assignment. Not chosen: 1 MiB; no limit.

  • 136. Airflow Param comes with the Airflow-compatibility work; M4.5 takes a dataclass or a Pydantic model only.

  • 137. A queued run keeps its values, validated against the version it was created on, and is never checked again (a field dropped in a later version still reaches that run’s tasks). Not chosen: re-validated when the run starts.

  • 138. How values are kept (Claude’s, from 133): the DAG JSON’s params holds the class’s type descriptor, a standard JSON Schema of it (a dataclass’s written by schedr: dates as format: date / date-time, a timedelta as ISO 8601 duration text (the master checks it as it stores it), a tuple as prefixItems; a model’s by Pydantic) and the defaults, as JSON. A trigger’s values are JSON (-p day=2026-10-01); the master fills in the defaults, refuses unknown keys (a Pydantic model’s schema allows extra keys), validates, then stores them as outputs are stored (tagged: {"$date": ...}), converted by the type descriptor, so the agent renders a date with a format spec and the runner decodes it as it decodes an output. Scheduled runs store the defaults. A DAG without params takes none (-p refused).

After the reviews (decisions 139-142, 2026-11-01; 139-141 Claude’s, accepted by the user):

  • 139. A duration may be given in weeks (P1W = 7 days, a fixed length); years and months are still refused. Not chosen: weeks refused.

  • 140. A whole number written with a fraction (-p count:=1.0) fits an int field, stored as 1: JSON Schema’s integer takes it, so refusing it after that check was inconsistent. Not chosen: refused.

  • 141. The master checks format: duration itself, as ISO 8601 (fractions of a second included: PT1H0.5S, as Pydantic writes a timedelta); the jsonschema crate’s own is RFC 3339’s, without fractions, and refused such a model’s defaults. Not chosen: dropping format: duration from models’ schemas (the master would check no model duration).

  • 142. Masking covers values given at trigger time, not text written in DAG code (the user’s, 2026-11-01, after Codex’s third review): a value given when a run is triggered is never shown in clear (refusals, run views, the run’s DAG, errors, logs), and a run’s stored params and its defaults are shown masked; text written in the DAG’s code (a default, a Literal’s values, a field name, a schema) is code, shown as written where code is shown (task output types, import and parse errors, dags check). The docs say not to put secrets in DAG code; secrets have their own mechanism (M4). Not chosen: masking code-authored text everywhere (open-ended, those paths predate M4.5a), now or as a later step.

How decision 134 holds (after Grok’s review and three of Codex’s, 2026-11-01), fail-closed: a refusal’s reason never quotes a value nor a value the schema holds; it is built by the master from what failed (the keyword, a missing or unknown field, the expected type, the format), with names masked as texts, and under a field named by a secret word (JSON pointer steps decoded) not even the keyword; a reason from the type (a duration in months) never quotes the value; text containing NUL is refused, by the webserver before the command is stored (its storage would replace it, decision 114); the run’s DAG (GET /runs/{run}/dag) keeps only its params’ defaults, masked (the schema and type can hold copies of values); a bad request body and a bad -p never quote the value and mask names; a dataclass default that doesn’t fit is refused without its value or type, and a model’s defaults are dumped without Pydantic’s warnings (which quote the value). Not chosen: masking the jsonschema crate’s messages (each fix left another way around).

The UI’s trigger form (decisions 149-152, the user’s, 2026-11-02, M4.5c):

  • 149. The webserver describes the form; the UI doesn’t read JSON Schema. A single DAG’s view (GET /api/v1/dags/{dag_id}) gets params: the form’s fields, built by the webserver from the DAG’s schema and defaults, each with its name, kind, whether it is required, its default (withheld under a secret name, decision 150) and a Literal’s choices. Not chosen: the raw JSON Schema for the UI to interpret (a second schema reader, and defaults under secret names reaching the browser unless masked separately); the UI reading the DAG JSON (couples the UI to its format).

  • 150. A field named by a secret word is an empty password input (“leave empty for the default”): its default never reaches the browser; left empty, the master fills the default in. Not chosen: pre-filled with **** meaning “keep the default” (a real **** can’t be given); the default in clear as DAG code (decision 142 would allow it, but the form is not where code is shown).

  • 151. An optional field (date | None) has a “none” checkbox beside its input. Not chosen: an empty input meaning None (ambiguous for str | None, where an empty string is a value).

  • 152. A field that isn’t a simple value (a nested dataclass or model, a list, a dict) is a JSON text box pre-filled with its default as JSON (the form --params takes); the master checks it. Not chosen: nested sub-forms (much more UI for little gain); leaving such fields out of the form (the CLI or API only).

The form sends only the fields changed; the master fills in the defaults and checks the values as for any trigger, and a refusal shows the master’s reason in the dialog (Claude’s).

  • 159. A page whose fields or defaults changed since it loaded is refused (“reload it and trigger again”, not sent; the user, 2026-11-02). The page carries a fingerprint of the fields it showed (names, kinds, null, secrecy, whether required, choices and the defaults); the trigger compares it with the DAG’s current fields. A box left showing a replaced default would otherwise send it as if chosen (rows 10 shown, the DAG now 20: a run with 10). A secret’s default is not in it: it never reaches the page (decision 150), and its empty box sends nothing, so the master fills in the current one. Not chosen: sending what the page showed (a run with a value no one chose); a hash of a secret default in the fingerprint (on the page, open to guessing).

Airflow (see Airflow compatibility):

Airflow

Becomes

params={"region": Param("eu", enum=["eu", "us"]), "full": False}

the JSON Schema (Param is JSON Schema; supported: type, enum, default, minimum / maximum, minLength / maxLength, format: date; others a parse error)

{{ params.region }}

dag_ctx.params.region (a t-string)

context["params"], a params argument of a callable

dag_ctx, behind the scenes (callables taking **context / params)

dag_run.conf

the parameter values; unknown keys are an error

Runs: manual runs, backfill and pausing

Runs created by the scheduler are of kind scheduled; a person can also trigger a run (manual) or a series of runs for past fire times (backfill). What the run’s time and window are, how runs share max_active_runs, how they are identified, and what pausing does:

  1. Time: every run has dag_ctx.run.planned_for, the moment the run is for (renamed from scheduled_at, which promised a schedule a manual run doesn’t have; not planned_at: *_at names say when something happened, like triggered_at, so it would read as the time the run was planned), and dag_ctx.run.since; the run covers (since, planned_for]. Both are always set (never None), computed once when the run is created and stored with it (a later schedule change or another run’s result never changes them).

    extract(since=dag_ctx.run.since, until=dag_ctx.run.planned_for)
    # WHERE updated_at > since AND updated_at <= until
    

    Run

    planned_for

    since

    planned_for is a fire time: scheduled, backfill, trigger --for <fire time>

    the fire time

    the previous fire time of the schedule

    plain trigger

    the trigger time

    the planned_for of the nearest earlier run of any kind

    trigger --for <other time>

    that time

    the planned_for of the nearest earlier run of any kind

    DAG without a schedule (only manual runs)

    the trigger time or --for

    the planned_for of the nearest earlier run

    • One rule for every run on a fire time: its window is one schedule period, whatever runs exist. So a scheduled run, a backfill run and a --for re-run of the same fire time get the same window (the way to re-run a past day, since there’s no “clear”); a backfill cuts its range into clean, consecutive periods; a manual click never cuts a scheduled period (a daily aggregation still covers the whole day), and the scheduler stays independent of manual runs.

    • Manual runs not on a fire time load everything since the last run of any kind (“previous” = the nearest earlier planned_for, not the run created last), so they may overlap with the next scheduled run (harmless for idempotent loads). A DAG without a schedule has only such runs: a plain chain of its own runs.

    • Missed fire times leave a hole, by design. With catchup=False, fire times without a run (master down, max_active_runs reached) are skipped with their data: with the master down for the 10-14 and 10-15 fire times, it creates only the 10-15 run when it returns (the most recent missed one), covering (10-14 03:00, 10-15 03:00]; the period of 10-14 is never loaded. A user who needs the hole filled says so explicitly: catchup=True on the DAG’s trigger (every period gets its own run) or a manual backfill (whose default picks exactly the fire times without a successful run). The UI marks skipped fire times on the DAG’s run list. Not chosen: folding missed fire times into the next scheduled run’s window (a hidden third behaviour besides catchup=True/False; windows would depend on which runs exist, so a backfill or --for run couldn’t get one clean period).

    • Failed runs still count: since doesn’t depend on how other runs ended (a failed day stays failed until re-run with --for or a backfill). Not chosen: “since the last successful run” (windows would depend on other runs’ results and timing).

    • First run: on a Cron / Every schedule the rule above already gives one ordinary period (the cron has a previous fire time even before start). A DAG can set initial_since= (a datetime) for the run on its first fire time at or after start, e.g. to load history on the first run. A DAG without a schedule (its first run) or with a Once schedule (no previous fire time) whose references use since must set initial_since (a parse error otherwise). Not chosen: -inf (no such datetime in Python; datetime.min breaks many systems, e.g. MySQL’s DATETIME starts at year 1000; None would bring Optional into every task); an empty window (the first run silently does nothing).

    • Not chosen: separate chains for manual and scheduled runs (a manual run’s window would depend on when somebody last clicked, possibly months ago); manual runs moving the scheduled chain (a click would split a scheduled period; a failed click would lose data).

    • When there is nothing to go back to: a run on a fire time with no previous fire time (Once) and no initial_since gets an empty window (since = planned_for); the Python API makes that a parse error when a task uses since (“set initial_since=”). A manual run not on a fire time with no earlier run uses initial_since, else the previous fire time, else an empty window.

    • A manual run is stored queued and starts at once if the DAG has a free place, so one path serves both; it never waits for the scheduler’s next pass.

    • dag_ctx.run.kind: scheduled / manual / backfill / chained (created by another DAG’s run, see Dependencies between DAGs) / event (created by an event from the DAG’s trigger, see Sensors and triggers). Not chosen: triggered for runs of another DAG and sensed for event runs (“trigger” already names the CLI verb and @trigger, so a “triggered” run wouldn’t come from a trigger).

    • triggered_at (when the run was created) is run metadata only (UI, CLI, audit trail), not in dag_ctx: a task using it would behave differently on a re-run of the same day. It differs from planned_for for missed runs, catchup, re-runs and backfills.

    • Parameters from -p / --params / the UI form.

    • Airflow’s ds / logical_date / data_interval_end translate onto planned_for, data_interval_start onto since. Scripts get SCHEDR_PLANNED_FOR and SCHEDR_SINCE.

    • --for (option of schedr runs trigger, and a field in the UI’s trigger form) sets planned_for; without it the run is for now.

    • --for in the future is rejected (”--for must not be in the future”; measured by the master’s clock with a small tolerance, about a minute, for clock skew). Running it now would build a report for a day that hasn’t happened or record a window covering data that doesn’t exist yet; almost always a typo. A run once at a future time comes from the schedule instead (Once(...), or start / end; see Native API). Not chosen: a deferred manual trigger (a run stored now and started later: waiting runs to show, cancel, and reconcile with pausing and DAG removal; the schedule already does all of that).

    • start / end don’t limit manual runs. They are data of the scheduled runs: the check is made by the run’s kind, only for kind = scheduled. A manual trigger or a backfill may be for any time, before start or after end, by design: a person chose that date (e.g. backfilling December for a DAG deployed in January, without moving start, which with catchup=True would make the scheduler create those runs itself). Fire times before start are still fire times of the schedule, so such runs get the usual window.

    • Time zone of --for: a time without an offset is UTC, with a warning (“no offset given: interpreted as 2026-10-15T03:00Z (UTC)”); an explicit offset (+02:00, -04:00) is accepted. The UTC time shown in the UI can be copied as is (see Web UI and CLI: Times and time zones), and --for is never ambiguous (UTC has no DST gaps or overlaps; the DST rules apply only to schedules). Not chosen: the schedule’s time zone (not shown in the UI, and ambiguous around DST changes).

    • The scheduler is independent of manual runs: it keeps its own bookkeeping (the last fire time it created a run for), which manual and backfill runs never change; a manual run for a fire time never stops the scheduled run for it (e.g. a --for run for a fire time missed while the master was down: the scheduler still creates its own run). Uniqueness: (DAG, planned_for) is unique for kind = scheduled (a database constraint), so a master that crashes after creating a run and restarts can’t create the same scheduled run twice; manual and backfill runs are exempt (several runs for the same day are allowed).

  2. Backfill: schedr runs backfill report --from … --to … [-p …]: one run (kind backfill) per fire time in the range, each like trigger --for <fire time>.

    • Window: one schedule period per run (see point 1), whether or not a scheduled run ever happened at that fire time; the runs of a backfill cover consecutive periods with no overlap.

    • Details:

      • Fire times that already have a run: by default only fire times with no successful run for that planned_for (of any kind), evaluated when the backfill is created (“31 fire times, 27 already succeeded, creating 4 runs”); --all for every fire time.

      • Creation: all runs at once, as waiting runs sharing a backfill ID (progress in the UI; schedr runs cancel --backfill <id> cancels what’s left); [backfill] max_runs (default 1000: a year of a daily DAG, a month of an hourly one; close to [mapping] max_instances) rejects bigger backfills, suggesting to split the range.

      • Range: --from / --to inclusive, time zone as for --for (UTC without an offset, with a warning); --to optional, a range ending in the future ends at now; no fire time in the range is an error; a DAG without a schedule is an error; start / end don’t limit it (point 1).

      • Order: oldest first, at most max_active_runs at a time (competition with scheduled runs: point 3).

      • Parameters: the -p / --params values apply to every run, validated once before anything is created.

      • API, progress and UI (decision 363, the user’s, 2026-11-08): POST /api/v1/dags/{id}/backfills answers the backfill’s ID and how many runs it created and skipped; GET /api/v1/backfills/{id} gives its runs’ counts by state; schedr runs backfill --dry-run counts without creating; the UI has a “Backfill” form on the DAG page and shows “backfill 3/31”. Not chosen: the UI later.

      • Order (decision 364): oldest first only. Not chosen: --newest-first (Airflow’s --run-backwards).

  3. Overlap: manual and backfill runs count towards max_active_runs. They are never dropped: at the limit a run is created and waits, unlike a scheduled fire time, which is treated as missed (a missed fire time recurs with the schedule and catchup decides; a person’s request doesn’t recur). Several runs with the same planned_for are allowed.

    • Run state queued, next to running, success, failed, cancelled, with the reason in the UI (“waiting: max_active_runs (1) reached”). Cancelling a queued run ends it as cancelled without starting any task.

    • Who gets a freed place: by kind, then oldest first within each kind: scheduled (a missed fire time, per the catchup rules) → manual, chained and event → backfill. Production runs are never delayed by people or bulk work; a person who clicked doesn’t wait behind a long backfill; a backfill uses whatever capacity is left. Not chosen: creation order (a click could wait days behind a backfill, and production behind both); manual first (delays production for little gain).

    • No per-backfill override of max_active_runs (e.g. --max-active 4): the limit usually protects something (a source system, a table being written). To go faster, change max_active_runs in the DAG.

    • With max_active_runs=None nothing waits: every manual and backfill run starts at once (a 365-day backfill starts 365 runs, limited only by max_active_tasks, worker slots and queues; documented).

  4. Identity: an opaque, globally unique, time-ordered run ID, a UUIDv7 (RFC 9562; Postgres stores it natively as uuid), as dag_ctx.run.id, never built from the date, so re-running a day can’t collide. Not chosen: ULID (a community spec; its only advantage, a shorter text form, matters little since runs are shown by DAG and date).

    • Each run records: id, kind (scheduled / manual / backfill / chained / event), planned_for, since, triggered_at, triggered_by (scheduler, the parent run for chained, trigger for event runs, or the user name from the command row, the same one recorded for audit and never used to allow or deny anything), backfill_id (backfill runs), and the parameter values.

    • UI label: sync_orders · 2026-10-15 03:00 · manual by anna (or · scheduled, · backfill 3/31 by anna); runs with the same planned_for are told apart by kind and triggered_at; the ID is in the run’s details, with a copy button.

    • CLI: runs are referred to by their full ID (schedr runs cancel 0192c4e1-…); no short prefixes (a UUIDv7 starts with its timestamp, so runs created around the same time share long prefixes). schedr runs list sync_orders --for 2026-10-15T03:00 lists the runs for a day with their IDs.

    • Airflow: run_id → dag_ctx.run.id; a DAG parsing Airflow’s run ID format (manual__2026-10-15T…) breaks (in the migration notes; the migration tool reports it where it can see it). dag_run.run_type → dag_ctx.run.kind (scheduled, manual, backfill; asset_triggered doesn’t exist, Assets being out of scope).

  5. Pausing (schedr dags pause / unpause, in the UI too; new DAGs start paused) stops the scheduler from creating runs, and nothing else.

    • Runs in progress finish, including retries, cleanups and resources. To stop work now, cancel the runs; the pause dialog offers “pause” and “pause and cancel runs in progress”. Not chosen: freezing runs in progress until unpause (a frozen run holds its resources, e.g. a cluster left running for the whole pause, and continues later with stale data); cancelling them (one click away, not the default).

    • Fire times while paused are treated as missed, as during a master outage: on unpause catchup=False gives the most recent one a run, catchup=True gives every one a run, in order. Before confirming an unpause the UI says how many runs it will create (e.g. the first unpause of a new DAG with catchup=True: “unpausing will create 290 runs”). Not chosen: skipping them for good (would break catchup=True’s “every period runs”).

    • Manual runs and backfills of a paused DAG run normally, with a confirmation in the UI (”sync_orders is paused; run anyway?”): pausing limits the scheduler, as start / end do. Testing a fix by hand before unpausing is a common need, and new DAGs start paused. Not chosen: queueing them until unpause; rejecting them.

    • Queued runs (manual or backfill, waiting for max_active_runs) keep their place.

Dependencies between DAGs

“After extract_crm finishes, run load_dwh”, across teams or schedules: a trigger_dag task kind, carried out by the master (like empty: no worker, no slot, no user code).

TriggerDagOperator(
    "load_dwh",
    dag="dwh_load",                    # the target DAG's ID
    params={"region": dag_ctx.params.region},
    wait=True,                         # default: succeed or fail with the target run
)
  • The new run: kind chained, linked to the parent run (triggered_by; the UI links both ways); planned_for = the parent run’s planned_for (same day), since by the usual rules for the target’s schedule (see Runs: manual runs, backfill and pausing). It counts towards the target’s max_active_runs and waits as queued with the priority of manual runs; it runs even if the target is paused (like a manual run).

  • params may use references (outputs, dag_ctx), resolved by the master, and are validated against the target’s schema when the task runs; invalid values fail the task, not retried (certain to repeat).

  • wait=True (default): the task stays running until the target run ends, and succeeds if it succeeded, fails if it failed or was cancelled (the failure propagates). It holds no worker slot but counts as a running task for max_active_tasks / max_active*. wait=False: succeeds as soon as the run is created.

  • Cancelling the parent run cancels a triggered run it is still waiting for; with wait=False the triggered run is independent.

  • Output: the triggered run’s ID (Output[str]).

  • Checks: an unknown target DAG ID is a DAG warning at validation (the target may be in a root not parsed yet); a missing or conflicting target fails the task at run time; a trigger whose target is already in the chain of parent runs fails the task (“cycle: a → b → a”), so runs can’t spawn forever.

  • Not chosen: leaving it out (merging DAGs, or triggering from task code: no link, no waiting, failures don’t propagate); waiting on another DAG’s run (not covered yet: see Sensors and triggers).

  • Updated for M4.12 (decisions 357-366, the user’s, 2026-11-08, all as recommended), after RunOf (decision 353) gave waiting nodes outcomes:

    • Built in two parts (357): M4.12a the operator, M4.12b backfill.

    • Its value (358, option A’): the target run’s ID, as the RunOf node gives, with wait=True or not; the target’s output is read with @sensor(wait_for=RunOf(...)) or the API. Not chosen: a RunResult[T] (richer than the node, so the two would differ; I first misdescribed it as the node’s).

    • A failed target (359): as the RunOf node, Failed is an outcome where the DAG routes it (.on(Failed)), otherwise the task fails and the run goes red; a cancelled (or skipped) target counts as Failed, its state in it. Replaces “fails if it failed or was cancelled”. Not chosen: always a task failure.

    • max_wait= (360): past it, a TimedOut outcome, as for any wait step; the target run goes on (it is a run of its own). Not chosen: cancelling it at the limit; no limit (no worker runs it, so timeout doesn’t apply).

    • Retries (361): a retry starts a new target run only after the previous one failed; the run is created and recorded on the task in one transaction, so a master’s restart never starts two. Not chosen: a new run every try.

    • planned_for= (362): optional, a datetime or a reference (dag_ctx.run.planned_for), the parent’s by default; Airflow’s logical_date maps to it. Not chosen: always the parent’s.

    • Not from schedr.api (365): tasks start runs with this operator; the API’s routes for tasks stay events only.

    • A cycle through trigger=RunOf(...) across DAGs (left to M4.12 by decision 353) stays uncaught: the check is the chain of parent runs, which RunOf runs don’t have (Claude’s, noted for later).

  • Airflow: TriggerDagRunOperator: trigger_dag_id → dag, conf → params, logical_date → planned_for of the new run, wait_for_completion → wait (Airflow’s default False is set explicitly); reset_dag_run=True is an error (no “clear”); non-default allowed_states / failed_states are an error; poke_interval is filtered out with a parse warning. ExternalTaskSensor: not covered yet (see Sensors and triggers).

Task results and outcomes

Every task, whatever its kind, can report which kind of success it had (its outcome), and downstream tasks route on it with .on(...). Before this, only command / script tasks had outcomes, and a Python task needed an extra @branch task to route on its result. Outcomes are how a user turns the problems they expect into success paths (see Outcomes, failures and joins).

@dataclass
class Rows:
    rows: list[dict[str, str]]

@dataclass
class Unavailable:
    reason: str

@task
def fetch_primary() -> Rows | Unavailable:
    try:
        return Rows(download(PRIMARY))
    except ConnectionError as e:      # expected problem → a success path
        return Unavailable(str(e))

primary = fetch_primary()
mirror = fetch_mirror()               # same signature

load(primary.on(Rows), mirror.on(Rows))        # load(primary: Rows | None, mirror: Rows | None)
report_outage(primary.on(Unavailable))

With NoneFailed, load runs if at least one source returned Rows and is skipped if both returned Unavailable; a real failure (timeout, crash) still blocks it and fails the run.

Result structure.

  • Every finished attempt has a status (success, failed, timed_out, …) and, when it succeeded, the pair (output, outcome): in the DAG JSON, the Finished message and storage, whatever the task kind. The output may be None. The output size limit applies to the output only. Mapped tasks: one pair per instance.

  • Failures are never outcomes. An outcome is always a kind of success, so “a failure is unexpected” still holds.

  • Every task has an outcome enum: DefaultOutcome (single member SUCCESS) for ordinary return types, empty tasks and commands without outcomes=; a declared Outcome enum (-> Check, outcomes=Check); or an implicit one derived from an outcome union (one member per class, each carrying its own data). In the backend an outcome is always a name (a member’s name or a class name) and each task declares the list of its names; the enums and classes exist only in the Python API.

  • Users never write the pair. They write return types, outcomes= and .on(X); the runner (Python tasks) or the agent (command / script) builds the pair. Returning tuples would be worse to write and to type-check, and would allow nonsense like (Rows(...), "Unavailable").

  • The stored outcome name is shown in the UI (see Web UI and CLI: What the UI shows) and decides which member a stored output is decoded into (a plain JSON object could fit several dataclasses). The name comes from the DAG’s declaration; decoding follows the downstream annotation (a parameter annotated Any gets a plain dict), so no code is ever loaded by a stored name.

  • Exceptions are never mapped to outcomes: outcomes are only returned values (Python) or declared exit codes (command / script). An uncaught exception is a failure.

Python outcomes.

  • With data: a union of classes. A return type defines outcomes when it is a union of two or more outcome members: dataclasses, Pydantic models and None (outcome name "None"). They are the only types the runner tells apart reliably at run time (isinstance): a TypedDict is a plain dict, bool is a subclass of int, list[int] and list[str] are the same class. Any other return type (int, Rows, int | None, int | str, Rows | int) is ordinary data with the single outcome SUCCESS; to route on such a value, return an outcome instead, or use @branch.

  • Without data: an Outcome enum, the same kind as for command / script tasks: def check() -> Check, then .on(Check.CHANGED). The member values (exit codes) are ignored for Python tasks; the output is None and the member is the outcome. The same enum works for a Python task and a command task, so a check can be reimplemented (Bash ↔ Python) without changing any edge.

  • A Python task’s outcomes are either a union of classes or one Outcome enum, never both; for “data or nothing”, use an empty dataclass (-> Rows | NoData) or None.

  • No marker is needed: routing is opt-in, so an outcome union behaves like any other type until .on(...) is used.

  • Parse errors: members that are subclasses of one another; the same class with different type parameters (Page[int] | Page[str]); two members with the same name from different modules. Only the top level of the return type counts (list[Rows | Unavailable] is data); type aliases are resolved.

  • Not chosen: classes only (boilerplate, a different style from commands); mixing classes and enum members in one union with Literal[Enum.MEMBER] (obscure, needs two typed variants of .on(), adds nothing over an empty dataclass).

What each task produces:

Task / return type

Outcome names

Stored (output, outcome), examples

-> None

SUCCESS

(null, "SUCCESS")

-> int

SUCCESS

(42, "SUCCESS")

-> int | None

SUCCESS

(42, "SUCCESS"), (null, "SUCCESS")

-> int | str, -> Rows | int

SUCCESS

(42, "SUCCESS"), ("abc", "SUCCESS")

-> Rows

SUCCESS

({"rows": [...]}, "SUCCESS")

-> Rows | None

Rows, None

({...}, "Rows"), (null, "None")

-> Rows | Unavailable

Rows, Unavailable

({"rows": [...]}, "Rows"), ({"reason": "..."}, "Unavailable")

-> Rows | Unavailable | None

Rows, Unavailable, None

also (null, "None")

-> Check (Outcome enum)

CHANGED, UNCHANGED

(null, "CHANGED")

command / script, no outcomes

SUCCESS (exit code 0)

(<ProcessResult>, "SUCCESS")

command / script, outcomes=Check

CHANGED, UNCHANGED (from exit codes)

(<ProcessResult>, "CHANGED")

empty

SUCCESS

(null, "SUCCESS")

@branch

SUCCESS

(["full_load"], "SUCCESS") (the chosen task IDs)

SUCCESS is DefaultOutcome.SUCCESS.

Routing.

  • One edge model: every edge is “on these outcomes”; a plain reference or plain >> means “on any outcome”. The only other edge kinds are the selection edge of a @branch task and the requirement edge added by uses= (see Cleanup and resources):

    Edge kind

    Comes from

    Counts in the trigger rule

    on-outcome (incl. plain >> and data)

    >>, data, .on(...)

    taken when the upstream’s outcome matches

    selection

    @branch

    taken when the target was chosen (not chosen: counts as skipped, 55B)

    requirement

    uses=

    never as a success; a failed setup → upstream_failed, a skipped setup → skipped

  • .on(X) is both an edge and data: it makes the downstream task depend on that outcome and passes the output narrowed to X (typed def on[T](self, kind: type[T]) -> Output[T], so the narrowing is checked statically). Edges whose outcome didn’t happen are not taken.

  • .outcome passes the outcome itself as data (Output[Check]), for enum tasks and command / script tasks.

Examples, with f = fetch() (-> Rows | Unavailable), c = check() (-> Check), cmd = CommandOperator(..., outcomes=Check), g returning Rows | None. Taken means the edge’s outcome condition was met (a plain reference or plain >> is always taken). Data rule when not taken: a NoneFailed task passes None (the parameter must allow None); an AllSucceeded task is skipped instead. If the upstream task itself was skipped, every edge from it counts as not taken.

Expression

Edge condition

Static type

Downstream receives when taken

When not taken

x(f)

any outcome

Output[Rows | Unavailable]

the value, decoded into the member the outcome names

n/a

f >> x

any outcome

—

nothing (order only)

n/a

x(f.on(Rows))

Rows

Output[Rows]

the Rows value

data rule

f.on(Rows) >> x

Rows

—

nothing (order only)

data rule (no data involved)

x(f.on(Rows, Unavailable))

Rows or Unavailable

Output[Rows | Unavailable]

the value

data rule

x(f.on(Rows).rows)

Rows

Output[list[...]]

the field of the Rows value

data rule

x(f.rows)

—

parse error

rows isn’t on every member; narrow with .on(Rows) first

—

t"... {f.on(Rows).rows} ..."

Rows

in a t-string

the rendered value

data rule (None in a template is an error)

x(c)

any outcome

Output[None]

None (an enum task has no output)

n/a

c.on(Check.CHANGED) >> x

CHANGED

—

nothing

data rule (no data involved)

x(c.outcome)

any outcome

Output[Check]

the member, e.g. Check.CHANGED

n/a

x(cmd.on(Check.CHANGED))

CHANGED

Output[ProcessResult]

the ProcessResult

data rule

x(cmd.on(Check.CHANGED).stdout)

CHANGED

Output[str]

stdout (an error if truncated)

data rule

x(cmd.outcome)

any outcome

Output[Check]

the member

n/a

x(g.on(None))

None

Output[None]

None

data rule (useful only for order)

When None can reach a parameter (Claude’s, 2026-10-28, refining the data rule above with a side agent’s note): under NoneFailed, a task whose every edge isn’t taken is skipped, not run with None. So a parameter must allow None only when its reference may stand for None (narrowed with .on(...), or to a task that may be skipped) and the task has another edge (another upstream task or condition) that can run it anyway: load(primary.on(Rows), mirror.on(Rows)) takes Rows | None twice, load(fetch().on(Rows)) takes plain Rows. It is checked when the with Dag(...) block ends, so an order edge added after the call counts. An Outcome enum parameter (react(check.outcome)) is stored by its member’s name. .on and .outcome take precedence over output fields of those names (result["outcome"] reaches the field); so that result.outcome never silently means the other, .outcome is refused on a task whose output may have a field or key outcome (one declaring it, a dict, Any), and is typed str (only a str or Outcome enum parameter takes it; a side agent’s note).

How M4.1a stores it (Claude’s, 2026-10-28, within the design above): each task carries its outcomes in the DAG JSON (outcomes: [{name, exit_code}], left out when it is only SUCCESS on exit code 0), an edge its condition (on: [names], left out for any outcome), a reference the same ({"kind": "output", ..., "on": [...]}), .outcome a reference of its own ({"kind": "outcome", "task": ...}), and a task its rule in its settings (run_if, left out for none_failed): all additive, so a DAG JSON of before reads as before. The master sends the outcomes of the upstream tasks a task uses with its assignment (upstream_outcomes, "" for a skipped one); the agent (commands) and the runner (Python) resolve a reference whose edge wasn’t taken, or to a skipped task, as null, and one to a task in neither as a missing input, as before. A command’s exit code is a success when one of its outcomes declares it, and that outcome is its own; any other code fails.

Rules:

  • Trigger rules count edges, not tasks: an edge not taken counts as skipped, so x(f.on(Rows), f.on(Unavailable)) runs under NoneFailed and is skipped under AllSucceeded.

  • A path on an outcome union needs narrowing first: f.rows is a parse error, f.on(Rows).rows is fine (the parse-time path check: a field must exist on the referenced type).

  • .outcome on a union task is a parse error: its type would be an invented Literal["Rows", "Unavailable"], and the value’s class already says it. On a plain task it is always DefaultOutcome.SUCCESS.

  • .on() accepts only members of the task’s own outcome enum, otherwise a parse error (.on(Other.CHANGED), f.on(Check.CHANGED), f.on(Unrelated)). Such an edge could never be taken: the downstream task would be skipped in every run, silently. Python itself catches only misspelt members, not a wrong enum or an unrelated class.

  • .on(DefaultOutcome.SUCCESS) follows from the previous rule: allowed on a task whose enum is DefaultOutcome (same as a plain reference; useful for generated edges, e.g. the Airflow translation), a parse error on a task with another enum, even one with a member named SUCCESS (membership is checked, not names).

@branch and outcomes.

  • Outcomes cover “route on what happened” (exactly one outcome per result, routing in the DAG structure); @branch covers what outcomes can’t: choosing any subset of the direct downstream tasks in the function’s code. The documentation recommends outcomes first.

  • A branch task’s result is (list of chosen task IDs, "SUCCESS"); its outgoing edges are selection edges, taken when their target is in the list. .on(...) on a branch task is a parse error.

  • Airflow’s @task.branch / BranchPythonOperator translate onto @branch (they can select several targets, so they can’t translate onto outcomes).

  • Not chosen: several outcomes per result (would break “one outcome per result”: .outcome, decoding by outcome name, the tables above); removing @branch (Airflow’s @task.branch would become an error by the principle in Thin translating classes).

Mapped tasks. Each mapped instance has its own (output, outcome) pair.

  • Element by element inside .expand(): allowed. check.expand(r=results.on(Rows)) gives check[i] the output of process[i] when its outcome was Rows; otherwise the edge to check[i] isn’t taken and check[i] is skipped. Map-index alignment is kept (the number of instances doesn’t change).

  • On the whole mapped output: a parse error for now. x(results.on(Rows)) (with x not mapped) has no single clear meaning (filter the list and lose the alignment with map indexes; replace non-matches with None; take the edge only if all instances matched). To collect them, write a task that takes the whole list and filters it. The same applies to .outcome.

  • A downstream task taking the whole list of a mapped task whose instances can be skipped gets None for skipped instances, in map-index order, so the element type must allow None (list[Rows | None]), as for any skippable data.

Async task functions

@task accepts async def functions (milestone M4; until then they are a parse error).

  • asyncio.run(...) per attempt. Each attempt is its own process, so the runner runs the coroutine in its own event loop: nothing shared between tasks. Timeouts and the memory watchdog stay outside, in the agent, unchanged; it works the same with the fork server (a fresh child per attempt). The master doesn’t know or care that a function is async: nothing changes in DAG JSON or the protocol.

  • The division between async and the model: waiting within one attempt (concurrent HTTP calls, an async database driver, an async-only SDK) is local concurrency, asyncio.run inside the attempt. Waiting for something to happen (a file, an event) is a sensor or a trigger (see Sensors and triggers), which run in the worker’s watcher host, not in a task process holding a task slot.

  • Help from the agent and runner: SIGTERM cancels the main coroutine (a handler in the runner) so finally / async with blocks run within the grace time, then SIGKILL as today; the process then ends by that signal, as a sync task’s does, whatever the coroutine did with the cancellation; async variants of the in-task calls (decision 315) over the same agent socket, so async code never blocks its own event loop.

  • Async in-task calls (decision 315, the user’s, 2026-11-06): an a prefix, await task_ctx.asecret(...), await task_ctx.asecret_value(...) and await acleanup_handle(...). The sync calls still work in async code, blocking its loop while they wait. Not chosen: the same name returning something both a str and awaitable (type checkers can’t describe it without Any); sync calls only, wrapped by the author in asyncio.to_thread.

  • uvloop whenever it is installed (decision 316, the user’s, 2026-11-06): an optional speed-up. Async tasks and the watcher host run on uvloop whenever the interpreter can import it, however it got there: schedr looks for the module, not for the extra. schedr[uvloop] is only a convenient way to install it. Without it they use asyncio’s own loop, so schedr keeps no required dependencies. So installing uvloop for any reason switches that interpreter’s async tasks to it, and each async attempt’s log says which loop it ran on (event loop: uvloop), so a difference between machines shows. No configuration key: being installed is the switch. Not chosen: a key per interpreter (what the design first said; a key for what installing already says); uvloop as a required dependency, the only loop (one loop to test, but the first compiled package every install must take); asyncio for tasks and uvloop for watchers only (they share the interpreter, and would behave differently).

  • Async connections: @connection on an async def generator gives an AsyncConnection, opened with async with; its @name.check may be async def, and connections test runs it in a loop. Typed connections give both clients from one definition (decisions 53, 317 and 318), their check running with the sync one. A sync connection works in an async task, blocking its loop.

  • Calling an async task in a test (decision 319, the user’s, 2026-11-06): await task.fn(...), typed as the coroutine it is, with what the task declares in force. A plain call also gives the coroutine (decision 49), but reads to a type checker as what the task returns, as a DAG’s load(extract()) must check, so await task() is flagged. .fn gives what the function returns (None for -> None, which is Done in a DAG). A functools.wraps decorator keeps it: the kind is read through the wrapper. .fn is the name connections already use. Not chosen: a cast or an ignore in authors’ tests; a separate @atask (it would need the same .fn).

  • Not chosen for tasks: Rust driving the coroutines inside the agent (no Python in the agent: user code could crash it); one shared async process for many tasks (no per-task memory budget or signal-based cancel, one crash or blocking call hurts all of them; watchers accept this trade-off because they mostly wait, tasks don’t); coroutines that suspend and resume in another process (a coroutine’s state can’t be saved).

  • Settled for M4 (decision 49, the user’s, 2026-10-28): a plain call of an async def task outside a DAG returns the coroutine, to await in tests (task_context and run_dag run it); async cleanups and resource setups / cleanups are supported like sync ones; background tasks still running when the main coroutine returns are cancelled, as asyncio.run does, their errors logged as warnings and the attempt’s result unchanged (“finally, not except”: what the task returned is its result). Not chosen: a plain call running the coroutine itself (B: no way to await it in an async test); sync-only cleanups for now; a leftover task’s error failing the attempt.

Sensors and triggers

Two ways of waiting for the outside world, both async def user code running in the worker’s watcher host (milestone M4, part of the first version). Together they are watchers: what applies to both (the host, its slots, the 30-second rule) is named after that.

  • A wait step (@sensor) is a step inside a run: it waits for one thing that belongs to that run (the partner’s file for this day) and ends, with a value or with the TimedOut outcome. Downstream tasks run after it, with its value as data.

  • A trigger (@trigger) starts runs: it watches for events (new files in a bucket) and never ends; each event creates a run. It belongs to the DAG, not to a run: a DAG with an event trigger has trigger=new_files(...) instead of a time trigger.

Wait step (inside a run)

Trigger (starts runs)

Full control

@sensor: async def, returns a value

@trigger: async generator, yields events

Poke

@sensor.poke(every=…): returns a value or NOT_YET

@trigger.poke(every=…): returns a list of events; empty means nothing happened

Used as

a task in the graph

Dag(trigger=new_files(…))

A plain def is a parse error for all four; using a wait step as trigger=, or a trigger in the graph, is a parse error too.

Wait steps.

@sensor(max_wait=timedelta(hours=6))
async def partner_file(day: datetime) -> str:       # full control: the user writes the loop
    async with listen("orders_ready") as channel:    # e.g. Postgres LISTEN
        ...
        return path

@sensor.poke(every=timedelta(minutes=1), max_wait=timedelta(hours=6))
async def partner_file(day: datetime) -> str | NotYet:   # schedr calls it every minute
    path = f"s3://in/orders_{day}.csv"
    return path if await exists(path) else NOT_YET

with Dag("sync_orders", trigger=DAILY):
    load(partner_file(dag_ctx.run.planned_for).on(str))
  • A wait step is a task kind (sensor in DAG JSON, next to python, command, empty, with mode: loop | poke): arguments and references, data flow, >>, retries, queues and run results work as for any task. It only runs differently: in the watcher host, on a watcher slot, not a task slot.

  • Poke: the function always returns something, the value or the NOT_YET marker (so a legitimate None is never “not yet”); the output type is the return annotation without NotYet. schedr calls it every every, each call limited to every (calls never overlap); a call that raises is a failure with the usual retries (a flaky source is the user’s to catch and turn into NOT_YET). A call blocking the loop past a limit can’t be cancelled, so its own time decides: what it then returns came too late. A call that runs out its every is cancelled and is a failure too, with a clear message (decision 322, the user’s, 2026-11-06): a poke that is always too slow shows at once. Not chosen: counting it as NOT_YET (it looks like a normal wait until TimedOut); a separate call_timeout= (one more option to explain).

  • max_wait: a wait step that hasn’t finished within its max_wait (or [sensors] default_timeout, 24 h) ends with the TimedOut outcome, not a failure: waiting in vain is an expected problem (see Outcomes, failures and joins). The clock starts at the instance’s first start and is kept across retries and moves (decision 321, the user’s, 2026-11-06): max_wait=6h means the run waits at most about 6 h, whatever happens to workers. Not chosen: per attempt, as a task’s (max_wait=6h with 3 retries could wait 24 h).

  • What downstream tasks see (decision 324, the user’s, 2026-11-06): a call reads as Waited[T], its value or TimedOut (schedr’s, never written in the function’s return type), so the timeout shows where the value is used. load(file) with path: str is refused at parse and by type checkers; load(file.on(str)) runs on the value and is skipped on a timeout; file.on(TimedOut) >> alert() runs on a timeout; a parameter str | TimedOut gets either (.on(str, TimedOut) for type checkers, which can’t read Waited[str] as that union). One rule of its own: a plain >> from a wait step means “when it has its value”, since wait >> process is the commonest use and must not run without the file; .on(str, TimedOut) runs after either. A value or TimedOut, not a failure: a failed wait step’s downstream tasks are upstream_failed as usual. With another upstream task, an edge not taken is as for any .on(...): run_if decides. Not chosen: a plain >> on any outcome, as for other tasks (no rule of its own, but wait >> process silently runs after a timeout); a call reading as T with plain edges only on a value (shorter, but the timeout is invisible in the code). Named TimedOut (the user’s): not SensorTimeout (reads wrong on approvals), nor NoEvent (an event is what a trigger yields).

  • Options: @task’s, except cleanup= and its settings (a parse error saying to use finally; decision 323, the user’s, 2026-11-06: waiting rarely leaves anything behind, and it can come later without breaking anyone; not chosen: a cleanup process on a task slot, tying the two kinds of slot together), and preload/fresh_process, which don’t apply.

  • Not mapped for now (Claude’s call, 2026-11-06, for the user to look at): .expand() on a wait step is an error, as each instance could end its own way and TimedOut has no element-wise routing yet. The list a mapped task gets can come from one, or be mapped over one’s value.

  • max_wait, and StepDefaults (decision 325, the user’s, 2026-11-06): a wait step’s limit has its own name, as timeout means “fail if the work runs too long” on a task and “stop waiting, not a failure” here; timeout= on a wait step, and max_wait= on a task, are errors. TaskDefaults is renamed StepDefaults, for a DAG’s or group’s steps, tasks and wait steps: retries, queue and the like apply to both, timeout to tasks, max_wait to wait steps. No alias: it is a preview. Order: the wait step’s own, its group’s, the DAG’s, [sensors] default_max_wait. Not chosen: timeout for both (StepDefaults(timeout=5m) would silently cut waits short; not inheriting it was unclear too); TaskDefaults and SensorDefaults on a shared base (shared settings written twice, and a parameter more on Dag, groups); a plain Defaults (“defaults for what?”); a narrower TaskDefaults beside StepDefaults (two ways to set retries).

  • Until the host is built (M4.11a1): a wait step runs as a task’s process does, on a task slot, with a clock per attempt; M4.11a2 to a4 move it to the host, its watcher slots and the kept deadline. The waiting itself (runner/waiting.py) stays the same. A function ignoring its cancel at the timeout is stopped by the agent past its grace, like a task over its time: timed_out, a failure.

Triggers.

@trigger
async def new_files(after: str | None, prefix: str) -> AsyncIterator[Event[Path]]:
    async for obj in watch_bucket(prefix, start_after=after):
        yield Event(key=obj.name, data=Path(obj.name), at=obj.modified)

@trigger.poke(every=timedelta(minutes=1))
async def new_files(after: str | None, prefix: str) -> list[Event[Path]]:
    return [Event(key=o.name, data=Path(o.name)) for o in await list_after(prefix, after)]

with Dag("ingest", trigger=new_files(prefix="s3://in/")):
    load(dag_ctx.event.data)
  • Events: Event(key, data, at=None); data has a type (Event[T], checked like outputs). The master stores every event in an events table, unique per (DAG, key): a key seen before creates no run. Events are acted on in order (yield order; list order for a poke, oldest first); the last key acted on is the bookmark, passed back as after whenever the trigger starts again (restart, new worker, new code). Delivery is at least once; repeated keys are dropped, so no event is lost or run twice.

  • A poke that finds nothing leaves no trace: an empty list creates no run, no event and no history, and the bookmark stays; only “last poked at” on the trigger’s status and a debug line in its log. Nothing is kept between calls except after. A poke that raises creates nothing, keeps the bookmark, and shows the error on the trigger’s status with a count of consecutive failures; the next call comes at the next interval.

  • Arguments of a trigger are literals given in the call (new_files(prefix=...); no run exists, so no references); after is filled in by schedr.

  • Runs it creates: kind event; dag_ctx.event.key, .data, .at (references in the DAG body, values at run time, like dag_ctx.run); planned_for = the event’s at, or when the master received it; since = the previous event’s planned_for.

  • A time trigger and an event trigger together are not possible: a DAG has one trigger=. (A periodic catch-up is a second DAG with a time trigger; if that needs syncing what each processed, the job needs another kind of orchestration.)

  • max_active_runs: events are requests from the outside world, so they queue like manual runs and are never dropped. Who gets a freed place: scheduled → manual, chained and event → backfill. Back-pressure: when a DAG has [triggers] max_queued_events (default 1000) queued event runs, the master stops its trigger and starts it again from the bookmark when the queue drains: the events wait in the source, not in our database.

  • Lifecycle: one instance per event-triggered DAG in the cluster. It starts when the DAG is unpaused and stops when it is paused, removed or in conflict; it starts again from the bookmark on unpause and on a new DAG version (new code); start / end (set with .override(...)) limit when it runs. A trigger that raises starts again with backoff (often temporary), the error shown on its status. A generator that returns is an error (triggers must keep yielding): it is stopped and not started again until a new DAG version or an explicit restart (UI / CLI).

  • No timeout for a trigger: holding its watcher slot while the DAG is live is its job (one slot per unpaused event-triggered DAG, like the little a time trigger costs the master); a timeout would only stop the DAG’s runs silently. Stopping at a time is end; stopping for now is pausing. A trigger that holds the event loop is handled by the 30-second rule like any watcher.

  • A generator that stalls (waiting forever on a connection that died without an error: no blocking, no error, no events) can’t be told from a quiet source, so it gets an optional restart: new_files(...).override(restart_if_idle=timedelta(hours=6)) starts it again from the bookmark when no event came for that long. Not an error (nothing is lost or repeated): counted in the metrics, the last restart shown on the trigger’s status. Off by default (only the author knows how quiet the source can be); @trigger.poke doesn’t need it (each call is limited to every).

  • Manual runs of an event-triggered DAG must bring an event (its tasks read dag_ctx.event): re-run a stored event (schedr runs trigger ingest --event <key>, or “Run again” next to the event in the UI), or supply one (--event-key test-1 --event-data '{…}' or --event-data @file.json; a JSON field in the UI form). A plain trigger with neither is rejected. Either way it is a manual run, and it never writes to events (a supplied key there would make the real event a duplicate later). The data is checked as JSON when the command is applied, and against Event[T] when the task decodes it (input_mismatch).

  • Not available for event-triggered DAGs: catchup (not an argument of an event trigger) and backfill (there are no fire times).

The watcher host.

[watchers]                  # the worker's watcher host: runs wait steps and triggers
slots = 500                 # watcher slots per worker (both kinds); 0 runs none
memory_budget = "1GiB"      # for the host as a whole
block_limit = "30s"         # a wait step or trigger must reach an `await` within this

[sensors]                   # wait steps (@sensor, @sensor.poke)
default_max_wait = "24h"    # for wait steps without their own `max_wait`

[triggers]                  # triggers (@trigger, @trigger.poke)
max_queued_events = 1000    # queued event runs per DAG before its trigger is stopped
failing_after = 5           # consecutive errors before TRIGGER_FAILING
  • One per code set (decision 320, the user’s, 2026-11-06; the design first said one per worker, importing a DAG file under a name with its hash, which left helper modules cached once in sys.modules and one sys.path for all, so new DAG code could silently run with old helpers, and two roots with one package name would collide): one host per interpreter and set of root copies. A new code version starts a new host; the old one exits when its last watcher ends, so usually 1 or 2 processes, and imports behave as in a task. [watchers] memory_budget is a total across a worker’s hosts. Not chosen: restarting the host on new code (a deploy of any DAG loses every full-control wait step’s progress, and doesn’t solve two roots); one host with an import finder giving each version its own helpers (brittle: pickling, dataclass lookups, C extensions); one host, documented (wrong code silently).

  • Each host: the agent starts python -m schedr.runner watchers, one long-lived asyncio process, and supervises it like any runner (same socket protocol, multiplexed by watcher ID: start_watcher, cancel_watcher, to_watcher, later event_ack from the agent; watcher_message from the host, around what a task’s runner would send, watcher_log and watcher_cancelled besides, later event, loop_blocked). Every wait step and trigger assigned to the worker runs in it as a coroutine. Not chosen: a host per queue (more processes and configuration for a half isolation, since tasks on the worker still share it); a thread in the agent (Python inside the agent through PyO3: user code could crash the supervisor); Rust driving the coroutines (they are Python’s asyncio and its async libraries; Rust can’t make waiting cheaper); a process per watcher (Airflow’s poke mode problem: a slot and a process held for hours).

  • The 30-second rule: a watcher must reach an await within 30 s ([watchers] block_limit); one watcher calling time.sleep() or a blocking client would freeze every watcher on the worker. A watchdog thread in the host checks every second that the loop turns; after 30 s it finds the watcher running from the loop thread’s stack and reports loop_blocked. Python can’t cancel a coroutine that doesn’t yield, so the agent kills the host: a wait step to blame fails with error kind blocked_event_loop (never retried: it would block again); a trigger to blame is stopped with that error on its status, like a generator that returned; the other watchers start again without using a retry, and the agent starts a new host. A host that stops answering altogether (its watchdog stuck too) is handled the same way by the agent’s own 30 s timeout.

  • A host crash or memory kill can’t be pinned on one watcher: every wait step on it ends lost and uses a retry, as a lost worker’s tasks do (retries keep a crash loop bounded), and every trigger starts again from its bookmark, with backoff. Memory is watched for the host as a whole ([watchers] memory_budget).

  • Cancelling a watcher cancels its coroutine (CancelledError at its next await), with the usual grace time; one that doesn’t end in time is handled as blocking.

  • Logs: each watcher is its own asyncio task with its own context, so print and logging are routed per watcher; lines go over the socket to the agent, which masks secrets and writes the watcher’s log file as for any attempt. Output from threads or C code goes to the host’s own log.

  • Built in M4.11a2 (decision 334, Claude’s calls, for the user to look at): a host is stopped as soon as its last watcher ends, so a lone wait step pays for a process start, and no timing or key is needed for an idle host. A host is always spawned, never forked: it lives for hours beside the fork server’s other children. A DAG file is imported once per host, so its top level isn’t run again for each attempt; a failed import is tried again by the next one. Its folder is the worker’s log folder and its environment the allow-list plus pass_env, as they can’t be a run’s: a wait step reads run values from dag_ctx and task_ctx, never SCHEDR_* variables, and uses absolute paths. Until M4.11a4: a wait step holds a task slot.

  • Built in M4.11a3 (decision 341, Claude’s calls): whoever gets a host killed is blamed: a loop held past block_limit (loop_blocked), a thread stuck past its grace (watcher_stuck), a cancel not taken in its grace. The others on it start again on a new host in the same attempt, their max_wait and timeout running on and no retry used; a poke that moved starts on what it moved to. While a DAG file is first imported on the loop, the limit is parse_file_timeout, so a slow import is no strike. Only one holding the loop on its own is blamed: many taking their turns can hold up a turn of the loop, and blame no one. A log not being written for that long kills its host too, with nobody to blame. A host silent for twice the longer limit (C holding the interpreter’s lock, so its watchdog can’t run either) is killed with nobody to blame, as for a crash or a memory kill: all on it end lost, error kind watcher_host_lost, each using a retry. [watchers] memory_budget kills the largest host when all together are over.

  • A poke moves to new code, and a move can’t fail it (decision 335, the user’s, 2026-11-06): a @sensor.poke finishes its current call and makes its next one on the new code, using no retry and keeping its deadline, if it can start there: the new host imports the file, finds the task under its ID and builds the call from the run’s stored arguments. If not (the task renamed or removed, an import error, a signature that no longer fits), it stays on its old code until it ends, and its log says why. The new host prepares first, the old one stops between calls, then the new one calls: two never poke at once. A full-control @sensor stays until it ends: its progress is in its coroutine, so it can hold an old host and code copy. A retry starts on the newest code, as any Python task’s (task_not_found if the task is gone). Not chosen: nothing moves (a poke’s bug fix waits up to its max_wait, and with hourly deploys and 24 h sensors a worker holds about 24 hosts); moving without the check (a rename would fail a healthy run); restarting @sensor too (see decision 320).

  • What a host’s own log masks: every value of every watcher it has had, for its whole life (what C code prints, or a thread outliving its step, can’t be told apart, and may come later).

  • asyncio.to_thread belongs to its wait step and has its time (decision 337, the user’s, 2026-11-06): the loop’s default executor (_WatcherThreads) runs each call in the context of who made it, so its log, secrets and refusals are its step’s, and tracks it. A call cancelled, or still running when its step ends, has StepEndedError (a BaseException) raised in its thread with PyThreadState_SetAsyncExc, the one way Python has to reach one; a call waiting for an agent’s answer is woken instead, and the next one waits for that answer before asking, as answers can come in any order. A thread that hasn’t ended after that step’s cancel grace (blocked in C) ends with its host, after the step’s result is told: only a process can be killed. Until M4.11a3 the other watchers on it just fail. A thread pool of the author’s own is refused at parsing. Not chosen: refusing to_thread (the usual way to call a blocking client); leaving a stuck thread running, logged (it holds a pool thread and overlaps a retry, again each time). The known risk: the error lands on any Python line, also inside a library’s own update, and the other watchers share that library; the docs say so, and a host isn’t restarted after such a stop.

  • A wait step or trigger that keeps blocking is switched off (decision 338, the user’s, 2026-11-06; built in M4.11a3): the master counts strikes per DAG and task (a blocked loop, a stuck thread, an ignored cancel). After [watchers] switch_off_after in a row (default 3), new attempts fail at once with error kind switched_off and never reach a host. A success resets the count. New code or a command switches it back on: with new code it has one chance, a single strike switching it off again until a success (a hash covers the whole root, so any deploy counts, and hourly deploys mustn’t hit its neighbours three times each). Sensors have their own names, not tasks: schedr sensors switch-on <dag> <sensor>, schedr sensors switched-off, POST /api/v1/dags/{dag}/sensors/{sensor}/switch-on; triggers get theirs in M4.11b. A host crash isn’t counted: it can’t be pinned on one step. A to_thread stop that lands doesn’t replace the host; a metric counts them. Not chosen: running an offender in a host of its own (a process per offender and more placement code; the others are hit a few times instead of once); a host of its own and never off (it keeps using up its time and retries).

  • Sensors and resources have endpoints of their own (decision 340, the user’s, 2026-11-06), not tasks: resources are only inside a run’s detail so far. Built with the switch-off in M4.11a3.

  • Repeated crashes and memory kills are made visible, not stopped (decision 342, the user’s, 2026-11-06): no wait step can be blamed, so none is switched off; each lost uses a retry, which bounds a run. A lost attempt’s error names the wait steps that were on its host, and a metric (M4.11a4) counts these ends per code set. Not chosen: separating them into a process each after a loss, to find the culprit (the most memory right after a memory kill, and the most code; it can be added later); a strike for all on the host (healthy long waits would be switched off with the culprit).

  • A kept deadline’s edges (M4.11a4, Claude’s calls): a wait step out of time while waiting to run again is ended TimedOut by the master, with no worker needed and its function not called. What a retry gets is what is left when it is assigned, and its clock starts when its call does, so its delivery and import come on top: “about” max_wait, as decision 321 says. Attempts without a recorded start don’t count: there are no old ones, as this is a preview.

  • What M4.11a4 shows (decision 343, the user’s, 2026-11-06): the Workers page has each worker’s hosts (code hash, wait steps, threads tied and untied, memory, hosts lost), sent with its heartbeat, and the same as metrics; tied is running to_thread calls and Python threads a step started, untied the rest of the process. The DAG page lists its switched-off sensors with a switch-on button, and a banner on the DAGs list says how many are off. Not chosen: worker totals only (which code set has them can’t be seen); a page of their own for either.

  • How a wait step looks in a run (decision 344, the user’s, 2026-11-07): at work it pulses (not for people who ask their browser for less motion); failed, it is red as any task is. One whose time ran out looks like a skipped task, grey, and says TimedOut, as it did run. Its run stays success, green, whether or not a task takes the timeout: .on(File) alone may be just what the author wants, and one who wants something done about a timeout writes .on(TimedOut). Not chosen: red (a declared outcome, and .on(TimedOut) routes on it); green (what it waited for didn’t come); yellow when no task takes it, on the wait step or on the run (it would call an author’s plan suspicious); failing such a run.

  • A cleanup that doesn’t fit in a drain (decision 346, the user’s, 2026-11-07): the agent doesn’t stop a running cleanup at the drain’s deadline; only what ends the worker then (a pod’s kill, a service manager) can lose it. So [worker] cleanup_timeout not fitting termination_grace_period is said once, at the worker’s start, and a task’s own cleanup_timeout once per task. Not chosen: a warning for each task on the default (each cleanup task outside the chart, whose grace is 600 s, warned); a default of 25 s (slow cleanups would time out, on Kubernetes too); a default grace of 600 s (a plain stop could wait 10 minutes).

  • A trigger is a hidden sensor without an attempt (decision 348, Claude’s for the user’s “same as sensors”, 2026-11-07; built in M4.11b): the DAG JSON carries the trigger’s function as a task of kind sensor, in the trigger and not among the DAG’s tasks, so it isn’t in the graph, gets no attempt and no row in a run. A worker runs it on a watcher slot in the watcher host of its code, with the secrets, connections, logs, masking, blame and restarts a sensor has; secrets= and connections= are declared as on @sensor (the user’s). Its events go up one at a time, acknowledged only once stored, so order and back-pressure hold; the agent sends what wasn’t acknowledged again on a new stream, and a repeat is only a bookmark move. The master starts a trigger from its bookmark while the DAG is unpaused, not held and within its start/end, and stops it when that ends, on a new version, when the worker’s code for the root changes (any change in the root, even if this DAG’s definition stays the same, so a deploy restarts every trigger in its folder; the user kept this, 2026-11-07, as a poke moving to new code does) and when the worker drains or is drained; a worker whose lease ran out gives it up, and when it returns with it, it’s told to stop. A running instance that the master doesn’t count is told to stop, from heartbeats and registrations. What an old instance sends is acknowledged and not stored: the one that took over resumes from the bookmark. A failed trigger starts again after SCHEDR_HIDDEN__MASTER__TRIGGER_RESTART_BACKOFF (5 s), doubling up to ..._MAX (5 min). A manual run of such a DAG brings an event, or is refused (decision 350). The master takes an event only from the worker holding that instance and only of the DAG’s current version; a key has 1 to 1024 bytes and no control characters, its data at most the trigger’s max_output_size (1 MiB by default), secrets masked by the agent as in an output: what breaks that fails the trigger with event_refused. Blocking triggers are stopped as sensors are ([watchers] switch_off_after, the user’s). Not chosen: a table of attempts for triggers (nothing about a trigger’s life is a try of anything), and a process of their own (a trigger is a wait step: decision 334).

  • How a trigger goes on, and when it doesn’t (decision 349, Claude’s within what this section says, 2026-11-07; built in M4.11b): a poke’s raise, or a call past every, tells the worker, which keeps the failures in a row and the last error and tells the master when that changes, otherwise with a heartbeat (so a poke every 100 ms is no write every 100 ms); its bookmark stays and the next call comes. A generator’s return is trigger_returned, stopped until its version or code changes. At [triggers] max_queued_events queued event runs (0: no limit) it is stopped and starts again once none is queued. restart_if_idle stops a generator with no event for that long, and it starts again at once. Its host killed for another watcher: it starts again from the bookmark, with the wait, rather than from what it was given. A strike is as a sensor’s (decision 338), in the same table by the function’s name; an event, or a poke’s call that went well, clears it. A trigger told to stop keeps its watcher slot on the master’s count until its worker says it ended, as the worker counts it, and what it ended with still counts; one that ended while the master was away is told on the next stream, on which it is still listed as running. A new instance goes on from the errors in a row the last one left. [triggers] failing_after makes it failing in master_triggers, and for TRIGGER_FAILING once notifications exist (none are built yet; their Event enum will need another name, Event is what a trigger yields).

  • Triggers have endpoints of their own (decision 350, the user’s for the endpoints, Claude’s for their shape, 2026-11-07; built in M4.11b): GET /api/v1/triggers, GET /api/v1/dags/{dag}/trigger, GET .../trigger/events, POST .../trigger/restart, POST .../trigger/switch-on; schedr triggers list|show|events|restart|switch-on. A restart forgets what it waited for and marks a running one as of no version, so the next pass stops it and starts another from the bookmark. sensors switch-on takes a trigger’s function too, as sensors switched-off lists it. A manual run brings event (a stored key) or event_key and event_data (--event, --event-key, --event-data, dags test likewise), a manual run that never writes to events. For tests, run_trigger(new_files(...), after=None, take=3, timeout=) in the process, and task_context(event=). [retention] events comes with M4.14. A DAG’s page shows the trigger, pulsing while it runs, its last 20 events with “Run again”, and takes an event in its Trigger dialog. What these reads show is masked as an output is.

  • first_of: acting on the first of several, in the graph (decision 347, the user’s, 2026-11-07; built in M4.11c): first_of(a.on(str), b.on(str)) >> fast_report is a node the master ends, as it does empty: no Python, no slot, no polling. It ends as soon as one edge is taken, with that value and the winner’s name; skipped when every edge ends up not taken; upstream_failed when an edge failed and none can still succeed. Nothing is cancelled: the losers run on as any task, and one failing fails the run when the run ends, which isn’t a late success (the run hadn’t ended), while the node and what follows it stay as they ended. Not chosen: .sensed_on(...) on each task (the user’s first idea: on one task it is .on(...), and the lines would have to merge into one hidden node); RunIf.ANY_SUCCEEDED (decision 345); asking the REST API from a wait step (a slot, polling, a token and an address for what the master knows); absorbing a loser’s failure (a run never hides a failed task). In the DAG body report(first_of(a.on(str), b.on(str))) passes the value on, and value, winner = first_of(..., with_winner=True) gives the winner’s ID too, both typed exactly (the user’s, 2026-11-07, option D; not chosen: .value and .winner on a node object, which a task’s parameter wouldn’t take as the value; winner_of(node), which type checkers can’t hold to a node; always a pair, which makes the common case write _; a parameter typed Winner filled in by itself, hidden wiring). at_least(n, a, b, c) (the user’s, built on the same count) waits for n and gives the list of values, with with_winner=True also the list of IDs, in the order the tasks ended. A skipped task doesn’t win, so this also joins the paths of a @branch. The master keeps {"$value": ..., "winner": ...} as the node’s output ($value, a name no field has, tells the runner it is the winner’s whole output), with one value also its winner’s outcome, so references, the runner and the UI read it as any output and there is no new kind of reference; what it keeps is at most the sum of its options’ max_output_size, or it fails output_too_large (the user’s, 2026-11-07, option B: values each allowed always fit, still bounded; not chosen: the node’s own 1 MiB, which failed two 600 KB values each within their limit; storing only the winners’ IDs and reading the values when needed, a new way to resolve a reference; a max_output_size= on the node). Refused: fewer than two different tasks, a part of an output, a mapped task, and x >> node, since every edge into it is something it chooses from.

  • Waiting for another DAG’s run: RunOf (decision 353, the user’s, 2026-11-07; to be built in M4.11d): RunOf("orders", task="load", lag=timedelta(hours=6)) says which run, and of it which task (none: the whole run). With lag, the run whose planned_for is this one’s minus lag, and of several such only the newest (by triggered_at): its result decides, a failed newer run gives Failed though an older one succeeded (the user’s, 2026-11-07, option C: schedr has no clear, so redoing orders for a day is a new run for that moment, and a report rerun afterwards must read it; not chosen: A, any success at once, which let a rerun of report build on the run being redone; B, waiting while any of them runs, then the newest success, which hid a failed redo; re-running report by itself when orders is redone is M4.12’s chained runs, or trigger=RunOf(...)); without it, a wait step waits for the next run to end and a trigger plans its run for now. It goes where something waits: the node wait_for(RunOf(...), max_wait=...), which the master ends with no slot and no polling, passing the other run’s ID, or Failed when it (or its task) didn’t succeed (skipped and cancelled too), or TimedOut. Failed is an outcome only where the DAG routes it (an edge from the node on Failed); otherwise the node fails and the run goes red (the user’s, 2026-11-07, option B; not chosen: always an outcome, which left a run green with what followed skipped; always a failure, with no .on(Failed)). TimedOut stays an outcome, as for any wait step; trigger=RunOf(...), a run per run of the other DAG that ends; and, for code that reads the result, @sensor(wait_for=RunOf(...)) and @trigger(wait_for=RunOf(...)), given a RunResult[T] (its run’s ID, DAG, planned_for, state, end, and with task= its state, outcome and output as T). A sensor returning NOT_YET waits for the next matching run, until max_wait. Any DAG may wait for and read any other’s runs, as anyone signed in sees them (schedr has no permissions of its own). trigger=RunOf(...) starts a run only for a run (or its task) that succeeded, and only for those ending while its DAG is live: nothing is caught up after a pause. Each such run is an event keyed by the other run’s ID, so it starts one run however often the master looks; its data is {"run_id", "dag_id", "planned_for"}, and queued ones count against [triggers] max_queued_events. A DAG can’t be started by its own runs, nor with a negative lag (Claude’s; a cycle across DAGs isn’t caught, see M4.12’s chained runs). Live means unpaused, present and not in conflict, with this trigger: the database sets dags.live_since in the same statement that pauses, removes, brings back or changes the DAG’s trigger, so the two can’t come apart. Each pass reads strictly after its cursor (end, run ID) on the triggers row, kept with the RunOf it was made for, so a deleted event row or an earlier trigger’s state never starts a run again; a pass queues no more than max_queued_events leaves room for. A manual run brings an event as an event trigger’s does: the UI’s dialog asks for its key, --event <key> runs a stored one again. lag is at most 10 years either way, for wait_for too, so a planned moment plus it stays a time (Claude’s, after the reviews). A RunOf naming a DAG or task not loaded says so in the waiting step’s reason (parse warnings aren’t stored); the step waits until max_wait, as that DAG may come from a folder that loads later. Built in two parts: d1 without code, d2 the functions. For d2 (the user’s, 2026-11-07, l-o all A): the function runs on a watcher slot, the master waiting without code and handing it each matching run’s RunResult once that run ends; a trigger function sees every run that ends (succeeded, failed, cancelled), the no-code form covering successes; it returns Event[T] | None, the key the other run’s ID unless it gives one; a raise fails a sensor’s attempt (its retries) and is a trigger failure (backoff, failing_after) that tries the same run again, the cursor not moving past it (not chosen: a task slot per match; successes only; a bool; skipping a run whose function raised). The sensor form (the user’s, 2026-11-07): the run is the function’s first parameter, run: RunResult[T] (not chosen: any parameter so annotated); it is called for every run that ends, failed ones too (not chosen: successes only, a failure ending the step as the node does); a @sensor.poke can’t take wait_for= (option A; not chosen: both, a timer and a run calling one function); NOT_YET means “not this run”, waiting for a later match until max_wait: with lag a newer run for the moment, a redo (option A, kept when the user asked what it adds over the master’s match: a failed run’s redo, and picking runs by content; not chosen: no NOT_YET there). The master holds such a sensor queued, recording on its instance since when it waits (its max_wait runs from there over its calls), the run handed and the last said NOT_YET to (a retry gets the same run), and hands the run as the literal value of its first parameter; the codec decodes generic dataclasses (RunResult[int]). After the reviews (Claude’s): the output is masked as the API masks it (decision 131); a mapped task’s is its elements’ list; T is narrowed by the task’s outcome; a retry gets the same run; a run that ended within max_wait is handed, its call given at least SCHEDR_HIDDEN__MASTER__HANDED_CALL_MIN (1 min); the wait starts at the instance’s ready_at. Not chosen: the latest run, or the latest that succeeded (hard to follow over backfills and reruns); failing at once when no run exists yet; The trigger form (Claude’s design, the user’s choice for a run it keeps failing on, 2026-11-07: C with an opt-in run_retries): each run of the other DAG (or its task) that ends while the DAG is live, oldest first, is one short call of the trigger on a watcher slot (AssignTrigger), the run’s RunResult (masked) the literal value of its first parameter; one call at a time. It returns Event[T] | None: the event’s key is the run’s ID unless it gives one, its at the run’s planned_for plus lag unless it gives one (lag can’t be negative). A clean end moves the cursor past the run, the run started or not; a raise is a trigger failure (backoff, failing_after) and the next call gets the same run (recorded on the triggers row as handed, run_of_handed_run/at), dropped if the DAG has been paused or its trigger changed since (never caught up). A run gone from the database is passed, logged. run_retries=N passes a run it raised on after N more tries, the reason kept as its last error; without it, schedr triggers skip <dag> (the API’s POST .../trigger/skip, the UI’s “Skip run” on the trigger panel, which shows the run it is called for) passes it, refused while a call runs. A call is limited to timeout= (10 minutes by default; the user’s, 2026-11-07, after a side agent saw that a hung await held the trigger, every later run and the skip): the runner cancels it, a failure (trigger_timed_out) as a raise is; one blocking the loop is the 30-second rule’s (not chosen: no limit, restart then skip by hand; a limit only when the author sets one). Its run is passed only for a call that returned (TriggerStopped.done; interrupted or cancelled it keeps it), in the statement that ends the call; a run handed after another was dropped starts with no failures; a return clears its strikes (Codex’s review). It can’t be a poke, restart_if_idle, or read its own DAG’s runs; run_retries and timeout are for it alone. @sensor(wait_for=..., timeout=...) limits each of its calls too, opt-in (the user’s, 2026-11-07, option A: a handed run’s call gets what is left of max_wait, hours, so a hung await read as “no run came”; not chosen: on every @sensor, whose one call is its wait; nothing). Over it, the attempt fails (retries, the same run); max_wait first still gives TimedOut. Both forms keep it in wait_for.timeout_ms (the user’s, option A: settings.timeout_ms stays the agent’s hard stop of a wait step; not chosen: inside RunOf, which the no-code forms share and where a call limit means nothing). The handed run travels inside the assignment: one too big for [grpc] max_message_size fails the call (a sensor inputs_too_large, a trigger a failed call that run_retries and a skip pass), and the worker takes messages up to that size (Grok’s review; the user’s, option A; not chosen: the master’s check alone; fetching the run apart, a protocol change). The setting moved from [master] grpc_max_message_size to [grpc] max_message_size, read by both ends (the user’s, 2026-11-07), with no alias for the old name: schedr is a preview (the user’s, 2026-11-08). Not chosen: A, retrying a run for ever with no way past it; B, passing a run after failing_after failures, which would mix “the trigger is broken” with “this run is bad”; a long-lived function fed runs (the generator form’s state for nothing). Not chosen either: offset= (too broad; its sign would flip between the forms) and planned_for_with_offset= (long), for what is lag inside RunOf; wait_for_run(...) for the node; a skip counting as done (the function form sees the real state); a trigger for every run that ends, whatever its state; catching up runs that ended while paused; refusing an unknown DAG at load.

  • Options are drawn as one group (decision 351, the user’s, 2026-11-07; built in M4.11c): the options of first_of sit in one box in the graph, with one dashed line from the box to the node, since they are treated as a group and aren’t each a dependency with the usual guarantees. The winner is highlighted in the box and named on the node. Where one box can’t be drawn (a task is an option of two nodes, options at different depths, or in different task groups) each option gets its own dashed line (Claude’s, a layout detail).

  • Named events through the API: EventNamed (decision 354, the user’s, 2026-11-08; built in M4.11e, part 1 the trigger and the node): an outside system posts POST /api/v1/events {name, key, data, at} (or schedr events post), and the four forms of RunOf take it: trigger=EventNamed("order-created") (a run per event), the node wait_for(EventNamed("approved", key=...)), and @sensor(wait_for=EventNamed(...)) / @trigger(wait_for=EventNamed(...)) with the Event as the first parameter (option A; not chosen: an event="name" keyword beside wait_for=RunOf, with no node form; only the no-code forms). A waiting step wakes on an event of its name whose key equals its key= (no key=: any); every run so waiting wakes; one posted after the run started but before the step began waiting is kept and matched (option A; not chosen: only events after it waits, which lose a fast caller’s; any stored event, which matches last week’s). One name per trigger, a repeat (the same name and key) starting nothing (option A; not chosen: several names, dag_ctx.event.name). Posting needs what triggering a run needs, schedr having no permissions of its own; an event at most [events] max_size (1 MiB), its key 1024 bytes, its name written as a DAG ID; kept until M4.14’s [retention] events; a security review (option A; not chosen: a token that can only post). Claude’s: at defaults to the moment it is posted, and a trigger’s run is planned for it; every post is an event of its own, a repeat of a name and key too (a waiting step in a rerun matches one posted again; a trigger still starts no second run for a key), a client’s retry deduplicated by its Idempotency-Key (after a side agent saw that “stored once” left a rerun waiting for ever). The change stream the UI follows moved from GET /api/v1/events to GET /api/v1/changes, freeing the name (the user’s, 2026-11-08; not chosen: /api/v1/named-events, two “events” meaning different things). Claude’s, when part 1 was built: “since the run started” is since it was created (triggered_at), so a run queued behind max_active_runs keeps what comes meanwhile; the trigger’s cursor (the last event seen, by when it was posted and its ID) is kept as RunOf’s, of its name, from when the DAG was live, at most what [triggers] max_queued_events leaves room for per pass; the node’s key is resolved by the master each round (a literal, dag_ctx.params..., dag_ctx.run.id, dag_ctx.dag_id, dag_ctx.event.key, an upstream output), and one resolving to no string fails the step with why (it has no Failed outcome: nothing happened elsewhere); its value is the Event[Json], its data’s tag-shaped dicts escaped. Json reads as Any in output and parameter types (it held Mapping[str, object], which the describer refused and recursed on), and generic dataclasses are described and encoded with their parameters, as they were decoded: Event[Json] is a task’s parameter type. After the reviews (Claude’s): a trigger reads back SCHEDR_HIDDEN__MASTER__EVENT_LOOKBACK (a minute) behind the newest event it acted on, by the keys its DAG has, for a post committed after a later one; a repeat leaves the next run’s window as it was, and a run is never given a since after its planned_for (an event for an earlier moment has an empty window); an event’s at at most a minute ahead, as --for; a key has no line separators or bidirectional marks (the CLI’s tables broke on them); data shaped like a schedr tag is escaped on every path (a post, a manual run, the node’s value); nothing posted after a wait’s max_wait counts. Part 2 (the user’s, 2026-11-08, option A): a key read from the run in @sensor(wait_for=EventNamed(..., key=...)) is written by defining the sensor inside the DAG’s block, where dag_ctx and outputs are references (not chosen: a per-call form; a reserved key= argument). Built in part 2 (Claude’s): @sensor(wait_for=EventNamed(...)) is called with the first matching event posted since its run was created and before its max_wait, NOT_YET waiting for a later one, a retry getting the same; @trigger(wait_for=EventNamed("name")) is called once per event of its name posted while live (no key=), the event it returns keyed and timed as that event unless it says; what it passed is kept in trigger_passed, read back a minute behind the last, so one stored late is still called for, once; SensorWaitFor holds run_of or event, exactly one. Codex’s review: a call’s item was passed when the call ended, even when the master had dropped the event it returned (its DAG changed meanwhile, a queue past its limit, a stop on its way), so the item was lost for good (both forms; RunOf since M4.11d2). Now a call that returned an event says so (TriggerStopped.returned_event) and its item is passed when that event is stored; one dropped is handed again (a repeat key starts no second run). The schemas, out of date, regenerated. Grok’s security review: a key read from a field named as a secret (params.token) showed in the step’s queued reason, though the run’s page hides that field: now ****. Not fixed: a worker built before returned_event (only a development build: a released 0.1.0 worker can’t run wait_for triggers); logged: B185 (a sensor’s NOT_YET cursor has no lookback), B186 (trigger_passed never pruned; fixed in M4.11f, the user’s: only named events are kept, the rows behind the lookback are forgotten once an event is handed, and a removed DAG’s with it; Codex’s review: a named event’s cursor never moves back now, as one handed late reopened a stretch whose rows were forgotten, and the pruning looks up the DAG’s own rows, not the name’s history; Grok’s security review: what was forgotten is now a floor the window never goes below, as a lookback raised meanwhile handed passed or skipped events again (triggers.passed_floor); an event whose key, or a batch item’s, holds a secret the trigger read was refused by the agent, as keys masked alike were stored as one; B189, the user’s: no refusal, the trigger’s log says it once, as refusing failed triggers whose keys only resembled a secret, and a hash of the real key would let a database reader recover a short secret). An event dated before the previous one (the user’s, 2026-11-08, option A): its run’s window is empty (since = planned_for), so no data is handled twice; a loader by window reads dag_ctx.event for it. Not chosen: no run, the status saying why (its data never handled); its window from the event dated just before it (overlapping windows, data handled twice).

  • delay and until: plain wait steps in Python (decision 355, the user’s, 2026-11-08; built in M4.11g): two @sensors schedr ships in schedr.sensors, no new step kind: delay(timedelta(minutes=10)) waits that long from its first try’s start, until(timedelta(hours=2)) until the run’s planned_for plus that (a datetime with a time zone: that moment); one past ends at once. A step tried again (its worker lost) waits only what is left: the master sends a wait step’s first try’s start with each later assignment (AssignTask.first_started, the same moment its max_wait counts from), the host gives it the step (TaskValues.first_started, not on task_ctx). They sleep at most a minute at a time, so a clock set meanwhile is seen. Claude’s, confirmed by the user (2026-11-08, all option A): their value is the moment they ended (a datetime); IDs delay and until, numbered from the second on; a delay given a timedelta waits up to that and a minute (max_wait) unless told, as a long delay would otherwise end TimedOut at the default; until keeps the usual default; a run parameter can give either; they aren’t in schedr’s top level (until is a common name); the first try’s start isn’t on task_ctx. Not chosen: a None value (a downstream task couldn’t say when it was released); the usual max_wait for delay (a two-day delay would end TimedOut at 24 h); top-level names (until clashes); task_ctx.first_started (one more public field to keep). Codex’s review: they gave their moment, not when they ended (now the end); a first try’s delay restarted its count when its host was restarted in the same attempt (the agent now sets a wait step’s first start itself on its first try, kept with the request); a negative wait from a run parameter wasn’t refused (now when it runs). Grok’s security review: a wait past what a datetime holds (a parameter of millions of days) raised and failed the attempt; now it ends at its max_wait, one before year 1 at once. Not fixed: a new worker under a master without first_started (the upgrade order is master first). Kept for later: by_deadline(a, b, at=...) and first_of(..., cancel_rest=True); approval(...) goes to M6 (human in the loop); none_of dropped (a plain branch does it). (Restored 2026-11-08: M4.11f’s commit had removed it with the code, B190.)

  • Tasks call schedr’s REST API through their agent: schedr.api (decision 356, the user’s, 2026-11-08: 1A 2A 3A 4A 5A and B2; built in M4.11h): one Client, two transports. Inside a running task or trigger (and a command task’s script, and schedr task-ctx api / schedr task-ctx events post|list) it needs no settings: the request goes to the agent, which sends it to the master on the Control stream (ApiCall, answered ApiAnswer), and the master runs it through the API’s own router in process, as task:<dag>/<run>/<task>[i] or trigger:<dag> (the posted-by name), only for an attempt open on that worker (or the trigger instance it holds), and only on an allow-list: POST and GET /api/v1/events for now (any event name). The agent resends unanswered calls on a new stream (an Idempotency-Key makes a resend one event) and gives up after a minute (503: send it again with the same key); an answer over [grpc] max_message_size is refused (502). What a task posts is masked with the secrets it read, as its output is, and its log says so (as a trigger’s does, B189). Outside a task the client goes over HTTP (httpx, the http extra) to SCHEDR_SERVER, as the CLI; a SchedrApi connection type (kind = "schedr": server, token or user/password) gives a client for another deployment. Sync and async (apost_event, aevents: in a thread, so a trigger’s loop goes on). schedr.testing.task_context posts to a fake (posted_events); schedr dags test and run_dag need nothing: they run a local standalone, master included, so a task posts to the test’s own database, gone with it (the folder’s other DAGs start paused there, so none starts). Decision 366 (the user’s, 2026-11-08: a fake for local runs) was taken on Claude’s wrong statement that local runs had no master and refused calls; checked with a run, it was dropped as needing nothing. A refusal is left only for a process that is no task’s or trigger’s (a connection’s test). Not chosen: a URL and token given to each task (secrets to hand out, and a route to the webserver from every worker); serving only events through dedicated messages (each new route a protocol change).

  • Batching is only for @trigger.poke, in Python (decision 352, the user’s, 2026-11-07; built in M4.11f): @trigger.poke(every=..., batch=timedelta(...)). A full @trigger or @sensor is the author’s own code and can batch as it sees fit, by yielding one event holding the group, so they take no batch=. It is the special case of @trigger where the host gathers what the pokes return and sends one ordinary event when the window ends; the master, the database, the CLI and “Run again” don’t change. Claude’s, to check when it is built: the key is the last item’s, so after keeps its meaning; the window starts at the first item and an empty one starts no run; a batch goes early near max_output_size; a restart finds the items again from the bookmark, which a poke that consumes what it reads can’t. A run reads dag_ctx.event.data as list[Event[T]], what the pokes returned (the user’s): the same objects, each stored once. Not chosen: list[T] (the items’ keys and times would be gone); batch="50s" (every other duration is a timedelta); tuple[list[T], list[Event]] (each item stored twice). Built (Claude’s, as noted above, and): batch_ms on the trigger’s sensor task, the host gathering; a batch’s event has no at of its own (planned for when it is sent); a window is sent when it ends even between two pokes; one item over the limit alone fails as a single event does; restart_if_idle isn’t checked against batch (Codex’s docs round: a poke is never restarted as idle; first built as a check, then removed); schedr.testing.run_trigger gives one event per poke that found items (the window isn’t waited for in a test). Codex’s review: a window ending during a poke waited for it, and took its items (now sent at its end, the poke going on, its items opening the next); each item made the whole batch encoded again (now each sized once, the list’s size kept: compact JSON, exact); the schemas, out of date; a test counting pokes in a 45 ms window (now 300 ms). Grok’s security review: a window ending with a repeat stored as one (the batch keyed by its last item), the new items before it lost (B188; the user’s, 2026-11-08, option A): each item is stored as an event of its own, the run gets the new ones (none new: no run), keyed by its last new item, the bookmark the window’s last key; an item run again by its key is a batch of it alone. Not chosen: B (only ordered sources may batch, nothing enforcing it), C (a hash of the keys as the key, the bookmark apart: repeats handled twice). Also fixed: room for masking in each item’s size (a masked number grows a byte), an empty key failing the trigger at once, the trigger’s max_output_size checked against [grpc] max_message_size. Logged: B187 (no protocol minor bump).

  • A task starts after its upstream tasks end (decision 345, the user’s, 2026-11-07): no run_if starts one on the first of several. To act on the first, first_of (decision 347) is a node of its own, after which a task starts as usual. Not chosen: RunIf.ANY_SUCCEEDED (too many caveats for a simple API: inputs that depend on timing, None for “not finished” as well as “not taken”, order edges that no longer order, no mapping, and an arrow in the graph that no longer means “after”).

  • Blame is what a host says (Grok’s review): a wait step with the will to can reach the shared socket and name a neighbour, which then gets its strikes or an ended attempt. That is within “a worker is one trust domain”: they share a process and can read each other’s memory anyway. Blame for an ID not on the host blames no one (all lost), and a stack passes the host’s mask, which has every value read on it.

  • Libraries’ own threads are watched, not refused (decision 339, the user’s, 2026-11-06; built in M4.11a3 and its UI in M4.11a4): polars 2.1 in to_thread left the loop free (8 ms at worst) and its pool is one per process, about 30 native threads idle after a query, so no list of libraries is refused and a thread alone is no strike: only a step that doesn’t end is. A Python thread started during a step (wrapping Thread.start) and alive when it ends is a warning in that step’s log. The UI shows each watcher host’s thread count, split into tied (the host’s calls for a step) and untied (the rest, from /proc/self/task: native threads can’t be tied to a step), also as a metric. Heavy queries belong in a task, as the docs say. Not chosen: a strike for a thread outliving its step (a client library’s harmless background thread would switch off a healthy sensor); refusing named libraries (never complete, and refuses small queries).

  • A watcher’s messages are bounded (Grok’s finding): 16 wait for its attempt, past them its host’s socket waits too, so a step printing faster than its log is written slows down the host, not the agent’s memory.

  • A moved poke’s recorded code: its attempt reports the hash it moved to, the code its value came from; its log says it moved.

  • A wait step can’t start a process or a thread (decision 336, the user’s, 2026-11-06): it shares a process and group with others, so nothing could stop what it left running when it ends, and a retry could overlap it. When its DAG is defined (schedr._wait_rules), so dags check says so: its compiled code is read for subprocess, os.system, os.fork, os.spawn*, os.exec*, pty, multiprocessing, ProcessPoolExecutor, asyncio.create_subprocess_*, threading.Thread, threading.Timer, ThreadPoolExecutor and _thread, also through the author’s own functions and classes, and using one is a TypeError: the file’s import error. Libraries aren’t read: they may start threads, and so does asyncio.to_thread, so threads have no refusal at run time. When it runs, for what can’t be read (a library’s insides, getattr, a function passed in): starting a process raises ProcessInWaitStepError, a normal failure: subprocess, os.system, os.fork, os.spawn*, os.posix_spawn and multiprocessing through an audit hook, and the loop’s own subprocess_exec as uvloop isn’t audited; asyncio.to_thread included, as it inherits the context. Allowed (Claude’s call, for the user to look at): the standard library’s platform, ctypes.util and uuid helpers, which client libraries call and which wait for their command; a blanket refusal would fail a normal database client. A host runs with -X thread_inherit_context=1, so a thread a step starts is refused too and prints to the step’s log, to the host’s once the step has ended. Not a sandbox: C code gets past it, and what it leaves runs until the host stops. A running thread can’t be stopped by anyone (Python has no way to, and an injected exception can’t interrupt a blocking C call): it lives until its own code ends it or the host stops. Not chosen: documenting it only (nothing enforces it); tracking subprocesses per step (patches the standard library, misses uvloop and grandchildren, a partial guarantee looking like a whole one). Asyncio tasks a step left running are cancelled and awaited before its end is told, as asyncio.run does. A host that loses the agent’s socket kills its group, as a journal can’t find what an ended host’s group left.

  • Secrets in a wait step: await task_ctx.asecret(...) and asecret_value(...) (M4.10) read without holding the loop, whatever the storage: the agent reads them all asynchronously, and the wait is the runner’s. async with a connection asks for its values the same way. Plain task_ctx.secret still works in a coroutine: one declared by name was fetched already, and only one under a SecretPrefix holds the loop.

  • Code: AssignTask carries the expected code hash, and a host holds one code set (decision 320), so old and new code run side by side in different hosts.

  • Isolation: watchers on one worker share a process and can read each other’s memory and secrets: within “a worker is one trust domain” (see Rust/Python integration), documented; teams that must be separated use separate queues and workers.

  • Secrets and connections are asked from the agent over the socket, as in task mode.

Where watchers run. Each wait step and each trigger runs on exactly one worker, assigned by the master (never on all workers: that would multiply the load on the watched system and create duplicate events).

  • Wait steps are attempts: the usual assignment rules (queue, spread by free watcher slots, rejections, “code not there yet”), and a wait step with no free watcher slot waits queued with the reason shown.

  • Triggers: queue from .override(queue=…), else the DAG’s default queue, else default; the same spread rule; at most one instance at a time. A trigger with no free watcher slot waits, with the reason on its status.

  • Triggers first: when a watcher slot frees up, a waiting trigger gets it before queued wait steps. Triggers are few (one per event-triggered DAG) and keep whole DAGs going; wait steps are many and belong to single runs. Triggers stopped by back-pressure free their slots, so wait steps can’t be locked out for good.

  • Capacity: [watchers] slots per worker (e.g. 500), separate from task slots; 0 runs none. The event-triggered DAGs plus the wait steps running at once must fit in the cluster’s watcher slots (the metrics show how close it is).

  • Workers coming and going: a new worker doesn’t take running watchers (no rebalancing in the first version; moving triggers would be cheap, from their bookmark, so it may come later). A draining worker hands its triggers and poke wait steps to other workers at once (they start fresh, no retry used); full-control wait steps get the drain grace time, then are interrupted and run again elsewhere without using a retry. A disconnected worker keeps them running (the 60 s lease, as for tasks); a lost worker’s wait steps end lost (a retry used), its triggers start elsewhere from the bookmark, and if it comes back it is told to kill them. Two instances of a trigger overlapping briefly after a network split is harmless: repeated event keys are dropped.

What it adds elsewhere.

  • DAG JSON: task kind sensor (mode, every_ms, timeout), trigger kind event (the trigger’s name, literal arguments, queue, restart_if_idle), dag_ctx fields event_key / event_data / event_at, the Event type in the type model, the TimedOut outcome.

  • States and storage: run kind event; tables events and triggers (instance, worker, state, bookmark, last error, consecutive failures); error kind blocked_event_loop.

  • Protocol: AssignTask for wait steps; AssignTrigger, CancelTrigger, TriggerEvent / TriggerEventAck, TriggerStopped; watcher slots in Register and Heartbeat.

  • Runner: a fourth mode, watchers, long-lived and multiplexed.

  • Master: a trigger supervisor next to the scheduler; event-triggered DAGs get no scheduled runs.

  • CLI / API / UI: runs trigger --event … / --event-key / --event-data; a DAG’s trigger status (running, worker, bookmark, last poke, last error, restart) and its events with “Run again”.

  • Testing DAGs: wait steps run in the test’s event loop (a poke until it returns a value); run_dag(dag, event=Event(...)) for event-triggered DAGs; run_trigger(new_files, after=None, take=3) collects a trigger’s first events; schedr dags test takes --event-key / --event-data for event-triggered DAGs.

  • Airflow layer: BaseSensorOperator, PythonSensor, @task.sensor, FileSensor map onto @sensor.poke (poke_interval → every, timeout → timeout, soft_fail=True → the TimedOut outcome; mode is irrelevant: no slot is held either way); a synchronous poke() runs in a bounded thread pool (asyncio.to_thread; a thread that hangs can’t be killed, documented); deferrable operators and Airflow’s triggerer are the same idea as the watcher host and translate onto it where their triggers are plain async code.

  • Not covered (possibly later): waiting for a time with no user code (a master-side wait, like empty); events pushed in through the API (POST /api/events/...); runs of other DAGs as events (ExternalTaskSensor without polling).

Human in the loop (M6)

A wait step a person ends: an approval or an answer given in the UI, the API or the CLI. Proposed by the user on 2026-11-05 and designed the same day; built after 1.0.0, in M6 (PLAN.md).

@dataclass
class Rollout:
    region: Literal["eu", "us"]
    percent: int

with Dag("release"):
    build = build_artifacts()
    ok = approve(t"Ship {build.version}?", approvers=["release-managers"],
                 four_eyes=True, timeout=timedelta(days=2))
    plan = ask("How should it roll out?", answer=Rollout)
    build >> ok >> plan >> deploy(build, plan)
    ok.on(Rejected) >> notify_team(build)
  • 283. The master holds it (the user: A, 2026-11-05): approve(...) and ask(...) are declared in Python and become a task of kind ask in DAG JSON (the question, the answer’s schema, approvers, timeout); no Python runs for the step. A wait step like a sensor (a task in the graph, its answer its output as data, timeout and TimedOut), but the master holds it: the task, once ready, waits for an answer instead of being assigned, with no user code and no worker or watcher slot. The docs show a @sensor.poke for an answer kept in another system (a ticket approved in an issue tracker): sensors cover that already. Not chosen: a @sensor for it (it would poll schedr’s own API, holding a watcher slot for days, each author writing the loop); both mechanisms.

  • 284. What can be asked (A): the answer’s type is the step’s output: approve a yes or no; ask(answer=...) a Literal or Enum (a choice) or a dataclass or pydantic model (a form, drawn as the params form is). The master checks an answer against the schema. Not chosen: approvals only.

  • 285. A “no” (A): a rejected approval ends with the Rejected outcome, not a failure: .on(Rejected) branches on it, plain >> downstream tasks are skipped, as with TimedOut. Not chosen: a failure.

  • 286. Who answers (A): whoever may trigger the DAG, by default; approvers=[...] (users or groups, checked against the signed-in user; LDAP groups in M6) narrows it; four_eyes=True keeps whoever triggered the run from answering. Not chosen: no narrowing.

  • 287. Timeout (A): timeout=, else [ask] default_timeout (7 days), ending with the TimedOut outcome. Not chosen: the sensors’ 24 h default.

  • 288. Notice (A, the user: an email with a link to the UI): a “Waiting for you” list in the UI with a badge, the answer form in the task panel, schedr runs answer <run> <task>, and a WAITING_FOR_ANSWER notification (M4.13’s channels) whose email links to the task in the UI. Not chosen: the UI and the CLI only.

  • 289. Record (A): each answer in the command log (who, when, what, an optional comment), shown in the task panel; an answer is final.

Cleanup and resources

Work that must run whatever the result of the tasks before it (releasing a lock, deleting temporary files, stopping something that was started): finally, not except. Outcomes cover the problems a user expects (see Task results and outcomes); cleanup is for what is left behind, including after unexpected failures, and sees neither outcomes nor failures.

Principles (consistent with “no failure branches”, see Outcomes, failures and joins):

  1. A cleanup runs when what it cleans up after has finished, however it ended (including timeouts, memory kills and lost workers, which only the master sees).

  2. It never changes the result: a failure stays a failure, the run still fails and notifications are still sent.

  3. It can’t see the failure: no failure status, no routing on it (otherwise it becomes error handling).

  4. Its own failure is an unexpected failure: it fails the run (see Run result).

Two layers, solving different problems:

Per-task cleanup

Resource

Cleans up

what one attempt started

what several tasks share

Runs

after every attempt, however it ended

once, after its last user is done, if its setup succeeded

Where

the same worker (local disk)

any worker

In the graph

no (shown inside the task, e.g. a dropdown or submenu)

no (shown in the run’s Resources panel; selecting it highlights its users)

Receives

the task’s inputs, run information, the attempt’s handles

the setup’s output, run information

Typical use

cancel a remote query after a timeout; delete temporary files

delete a cluster; release a lock held by several tasks

In Airflow

on_kill()

setup / teardown, all_done_setup_success

Neither is a node of the graph, so neither is ever a leaf. Airflow translation: see Airflow compatibility (Cleanup and resources).

Per-task cleanup

How it runs (decision 16A, 2026-10-27): always in a fresh process after the task’s, however the task ended (returned, raised or killed), through the fork server like the task (runner cleanup mode; the preloaded or bare server by the task’s own preload, spawn as the fallback): about 8 ms to start instead of about a second spawned, which matters as downstream tasks wait for the cleanup. The cleanup’s environment is the same on every path, and a task that broke its process (memory near the limit, threads left running) can’t take its cleanup with it. Not chosen: running it in the task’s own process when the task ended by itself (two paths to keep alike, the task’s state, one watchdog and timeout for both); downstream not waiting for the cleanup (the “cleaned before the next step” guarantee).

@task(cleanup=...), CommandOperator(..., cleanup=[...]): finally for one task. It covers what schedr itself interrupts: when the agent kills a task (timeout, memory watchdog, cancel, drain), work it started outside its process (a remote query, a Spark job) keeps going, and the task’s own try/finally can’t run. Each attempt cleans up after itself, so a retry starts clean.

What it receives: a real finally. The cleanup function gets the task’s inputs, the run information, and every handle the attempt registered, in registration order. It never gets the output or the status.

  • Handles carry what only existed during the attempt (e.g. a remote job ID; a killed task has no output). cleanup_handle(x) only registers (“clean this up when the attempt ends”), like Go’s defer; it is sent to the agent at once and journaled. Handles are never released: the task doesn’t clean up after itself, all cleanup logic is in the cleanup function.

  • So the cleanup receives the same list on success and on failure and does the same thing; a shorter list only means the attempt stopped earlier, not why. Cleanup actions must be idempotent (e.g. cancel_if_running); after a success they usually have nothing to do. Anything that must outlive the attempt isn’t registered.

  • Typing: the cleanup declares handles: list[ExportJob | TempDir]; checked at parse time (the cleanup’s parameters are the task’s inputs plus handles; the element type follows the outcome-union rules) and at registration (a handle of another type fails the attempt at once). cleanup_handle accepts any dataclass, so mypy can’t check the match. Handles are stored with their class name, like (output, outcome).

  • Not chosen: releasing a handle when the task finished normally (the cleanup would then get handles only after a failure and behave like an except block, against principle 3); an injected, typed Cleanup[H] parameter (too awkward for @task’s typing).

def undo_export(day: date, handles: list[ExportJob | TempDir]) -> None:
    for h in handles:
        match h:
            case ExportJob(job_id=j):
                warehouse.cancel_if_running(j)      # no-op if the job finished
            case TempDir(path=p):
                shutil.rmtree(p, ignore_errors=True)

@task(cleanup=undo_export)
def export(day: date) -> Exported:
    tmp = tempfile.mkdtemp()
    cleanup_handle(TempDir(tmp))
    job = warehouse.start_export("orders", day)
    cleanup_handle(ExportJob(job.id))
    job.wait()
    rows = compress_and_upload(tmp, f"s3://bucket/orders/{day}")
    return Exported(f"s3://bucket/orders/{day}", rows)

Where and when it runs.

  • Same worker, same slot: the agent starts the cleanup as soon as the attempt’s process has ended, for whatever reason (<python> -m schedr.runner cleanup for a Python task, the cleanup command for a command / script task), with the same memory budget and watchdog. The slot is freed only after the cleanup. Same worker, so the same local disk.

  • The attempt finishes after its cleanup, as a function call returns only after its finally block: downstream tasks and retries start only then (task instance state cleaning_up meanwhile). The worker reports the task’s result when its process ends and the cleanup’s in Finished (decision 229). Not chosen: reporting the task’s result at once and cleaning up in parallel (a retry or downstream task could meet the previous attempt’s resources, e.g. a lock not yet released).

  • cleanup_timeout per task (and in StepDefaults), server default 5 minutes. On timeout the agent kills the cleanup (SIGTERM, then SIGKILL): that cleanup attempt failed. Cleanup retries run on the same worker.

  • Cancel: the agent kills the task, then runs the cleanup (a cancelled export should cancel its remote job too). Drain: the agent stops the remaining tasks early enough to leave room for their cleanups (at the end of the grace period minus the longest cleanup_timeout among them); if the pod is killed anyway, it is a lost worker.

    • Kubernetes’ default terminationGracePeriodSeconds (30 s) is far too short for that: the Helm chart sets 600 s for workers (5 min for tasks, then 5 min for cleanups). The worker is told its grace period ([worker] termination_grace_period, matching the pod spec) and logs a warning at startup when a task’s cleanup_timeout doesn’t fit in it.

  • Agent restart on the same pod (journal kept): the agent runs the cleanups of the interrupted attempts from its journal.

  • Lost worker (pod gone, node failure): handles are also sent to the master when registered, so they survive the pod. The cleanup runs on another worker only if the task opts in with cleanup_anywhere=True (idempotent isn’t the same as safe on another pod: rmtree("/data/orders") there could delete another task’s files; only the author knows whether the cleanup depends on where it runs). Without the opt-in the cleanup is recorded as “didn’t run: worker lost”, which counts as a failed cleanup: the run fails even if the task’s retry succeeds.

Situation

Where the cleanup runs

The task ends (success, failure, timeout, OOM, cancel)

the same worker, at once, in the same slot

Drain

the same worker; tasks stopped early enough to leave time for it

The agent restarts on the same pod

the same worker, from the journal

The pod is lost, cleanup_anywhere=True

another worker, with the handles from the master

The pod is lost, no opt-in

not run → “didn’t run: worker lost” → the run fails

A failed cleanup is a separate failure; the task keeps its own result.

  • The task’s result stands: on success its outcome and output are kept and downstream tasks run. The UI shows e.g. “success · cleanup failed” (the cleanup result is an attribute of the task instance).

  • The cleanup has its own retries (count and delay configurable, separate from the task’s); being idempotent, it is always safe to run again.

  • After its last retry it fails the run (principle 4) and triggers the failure notifications (“cleanup of export failed”, with its error summary).

  • If the attempt failed too, both failures are recorded; the task’s retry goes ahead after the cleanup has ended.

  • Not chosen: failing the task (throws away a result that was delivered, retries the work instead of the cleanup); success with only a warning (a leak nobody acts on; contradicts the rationale of Outcomes, failures and joins).

command / script tasks (commands: see In-task CLI).

  • The cleanup is of the same kind as the task: a command for CommandOperator (cleanup=["./undo_export.sh"], same rules as command), a script for a script job ([jobs.<name>.cleanup] with script, interpreter, args). It gets the same environment as the task (SCHEDR_* run variables, the task’s env, its declared secrets, working directory); its arguments may use t-strings. ScriptOperator can override its args / env. (A Python cleanup for a command task: possibly later.)

  • Registering a handle: schedr task-ctx cleanup add ExportJob job_id="$job_id" (or --json '{...}'), over the agent socket, like the Python runner; synchronous: when it returns the handle is journaled (and forwarded to the master); on failure it exits non-zero.

  • Reading the handles in the cleanup command, with the same tool: schedr task-ctx cleanup list ExportJob --field job_id (one value per line), or JSON Lines (the default, in registration order). No jq needed, no size limit, nothing in the environment or on disk; works unchanged with cleanup_anywhere.

    # export.sh
    job_id=$(warehouse start-export orders "$1")
    schedr task-ctx cleanup add ExportJob job_id="$job_id"
    warehouse wait "$job_id"
    
    # undo_export.sh
    schedr task-ctx cleanup list ExportJob --field job_id |
      while read -r id; do warehouse cancel-if-running "$id"; done
    
  • Typing: optional cleanup_handles=["ExportJob", "TempDir"] (TOML: cleanup_handles = [...]); registering another type name then fails at once.

  • Not chosen: appending JSON lines to a file named by an environment variable (not synchronous, a handle can be lost if the pod dies before the agent reads it, quoting JSON in shell); passing the handles to the cleanup in an environment variable (128 KiB limit per string, readable through /proc/<pid>/environ, needs jq) or in a JSON Lines file (needs jq, a second mechanism next to the CLI).

Resources

A resource is created by a setup task, used by users, and cleaned up once by its cleanup when every user is done: freed as soon as its last user finishes, not at the end of the run, and no scope is computed from the graph (like reference counting).

with Dag("etl", trigger=DAILY):

    @resource                              # the setup: creates the resource
    def cluster(size: int) -> ClusterInfo:
        return cloud.create_cluster(size)

    @cluster.cleanup                      # how to clean it up
    def delete_cluster(c: ClusterInfo) -> None:
        cloud.delete_cluster_if_exists(c.cluster_id)

    @task(uses=[cluster])                  # a user that doesn't need its data
    def warm_cache() -> None: ...

    @task
    def transform(c: ClusterInfo) -> Parts: ...

    @task
    def load(c: ClusterInfo, parts: Parts) -> int: ...

    c = cluster(size=8)                    # Output[ClusterInfo]; the setup runs once
    warm_cache()
    load(c, transform(c))                  # taking a resource's output makes a user
  • @resource marks the setup: an ordinary task (options as for @task) whose return value is the resource. Its output follows the usual output rules; an outcome union as a setup’s return type is a parse error for now.

  • @<resource>.cleanup marks the cleanup; it receives the setup’s output and the run information, nothing else (no other outputs, no statuses). Options: timeout, retries, retry delay, queue, secrets, connections (decision 226). At most one per resource: without one the cleanup is empty (decision 260).

  • Users: a task taking a resource’s output as data is a user (only a resource’s output counts; not general inference from data flow); a task needing the resource but not its data declares uses=[cluster] (also on operators and groups, not in StepDefaults: too easy to make every task a user). The setup is implicitly a user. Users depend on the setup, so they never start before the resource exists.

  • uses= adds a requirement edge (see Task results and outcomes: edge kinds), which can only stop a user, never make it run: setup failed → the user is upstream_failed; setup skipped → the user is skipped; setup succeeded → no effect on the user’s rule (evaluated on its other edges; a user with no other edges runs). It still orders the tasks. Without this, a user skipped by a branch or an untaken .on() edge would run under NoneFailed because the setup succeeded. A data edge from the setup (transform(c)) stays an ordinary edge. Under AllSucceeded nothing changes.

  • Typing: @cluster.cleanup takes its type from the resource, so mypy checks that the cleanup accepts the setup’s return type; parse time checks it too.

    class Resource[**P, T]:                # called like a task
        def __call__(self, *args: P.args, **kwargs: P.kwargs) -> Output[T]: ...
    
    def resource[**P, T: Json](fn: Callable[P, T]) -> Resource[P, T]: ...
    
    def cleanup[T](r: Resource[..., T]) -> Callable[[Callable[[T], None]], Cleanup[T]]: ...
    
  • No handles for resources: the setup’s return value is what the cleanup gets. A setup that fails halfway (cluster created, then a crash before return) is handled by the setup’s own per-task cleanup (cleanup= and cleanup_handle(...) on the setup task). Handles are for attempts, setup outputs for resources.

  • Done means every user is in a final state: success, failed after its last retry, upstream_failed, skipped, cancelled (a task that will never run counts as done; a failed attempt with retries left doesn’t; a mapped user is done when all its instances are).

  • The cleanup runs once all users are done, if the setup succeeded (try: create → use → finally: delete: the try starts only once creation succeeded). It then receives the setup’s output, never None, and must be idempotent. A deterministic name (e.g. an S3 prefix from the run ID) is simply returned by the setup. Not chosen: running every time with T | None (puts None in every cleanup’s type for a check that almost never matters).

  • It runs on any worker, so it must not depend on location; local leftovers belong to the per-task cleanup. Its own retries, then it fails the run (see Run result). Resource instances have their own states (see Task assignment: task instance states).

  • Resources without a value (a static resource: a fixed lock, a well-known bucket prefix): the setup returns None (@resource def lock() -> None). The cleanup then takes no parameter (@lock.cleanup def release() -> None; an overload of cleanup for Resource[..., None] keeps it typed); users declare uses=[lock]. No ambiguity with a failed setup: the cleanup runs only if the setup succeeded.

  • A resource without setup code: tmp = Resource("tmp-prefix"); its setup is completed by the master (like an empty task, no process), its value is None, the cleanup takes no parameter, users declare uses=[tmp]. Use: “once these tasks are done, delete s3://tmp/<run_id>/”.

    tmp = Resource("tmp-prefix")
    
    @tmp.cleanup
    def drop_tmp() -> None:
        s3.delete_prefix(f"tmp/{dag_ctx.run.id}/")
    
    @task(uses=[tmp])
    def stage() -> None: ...
    
  • Setups and cleanups as commands or scripts. Any setup kind works with any cleanup kind (exactly one cleanup per resource).

    cluster = CommandResource(
        "cluster",
        command=["./create_cluster.sh", "--size", "8"],
        value=ClusterInfo,                    # the type of the reported value
    )
    CommandCleanup(cluster, command=["./delete_cluster.sh", t"{cluster.cluster_id}"])
    load(cluster, transform(cluster))         # users receive a ClusterInfo
    
    # create_cluster.sh
    id=$(cloud create-cluster --size "$2")
    schedr task-ctx resource set cluster_id="$id" region=eu   # synchronous, validated at once
    
    • Setup: CommandResource / ScriptResource (job= a declared script), operator forms of @resource, with a declared value= type. The command reports the value with schedr task-ctx resource set (see In-task CLI) over the agent socket; validated against value at once.

    • The setup succeeds only if it exits with 0 and reported a value; a missing value is a setup failure (“resource value not reported”), so the cleanup never gets None. Without value=, the resource has no value (type None) and nothing is reported.

    • Users receive the value (Output[ClusterInfo]), not the ProcessResult (which stays in the log): they can’t tell which kind of setup made the resource.

    • Cleanup: @cluster.cleanup (Python, value as a parameter, decoded from the reported value), CommandCleanup(cluster, command=[...]), ScriptCleanup(cluster, job=..., args=[...]). Command and script cleanups receive the value through t-strings: the resource object stands for its value (t"{cluster.cluster_id}", rendered by the agent, paths checked at parse time against the value type); a script can also read it with schedr task-ctx resource get --field cluster_id.

    • A setup that fails halfway: the setup’s own per-task cleanup (cleanup=, schedr task-ctx cleanup add), as for Python.

    • Not chosen: the setup prints JSON on stdout for schedr to parse (stdout mixes with whatever the tools print, brings stdout parsing into the native API, a malformed value is noticed only when the cleanup needs it); giving the cleanup the whole ProcessResult (every cleanup would dig the ID out of text).

  • A per-run cleanup is a resource used by every task (shorthand such as Dag(cleanup=...) possible later).

  • Not chosen: a setup–cleanup pair with a scope computed from the graph between two tasks; a cleanup for a group, the whole run or an explicit task list (none of them knows whether anything was created); a Resource(...) object with a handle list.

  • Built (M4.8a; decisions 216-219, 221-226, 228-230): cleanups on the same worker. @task(cleanup=fn) and CommandOperator(cleanup=...), with cleanup_timeout, cleanup_retries, cleanup_retry_delay (also in StepDefaults), cleanup_handles= for a command; cleanup_handle(x) and schedr task-ctx cleanup add|list; TaskEnded when the process ends, moving the instance to cleaning_up, and Finished with the task’s result and the cleanup’s. Small decisions: a cleanup is a task request with cleanup set, as a connection test is, not a separate runner mode, so it runs through the fork server unchanged; the attempt stays open during its cleanup, so slots, limits and a lost worker’s handling need nothing new; handles live only in the agent’s memory until M4.8b; the cleanup’s parameters are built with the task’s annotations, so one of another type is refused at parse time; a parameter the DAG left at its default gets the task’s default. task_context yields .handles, what cleanup_handle registered.

Decided for M4.8

Decisions 214-230 (the user’s, 2026-11-04; the options were Claude’s). 215 and 227 were dropped when laid out: each sub-step commits on the user’s word anyway, and ctx.handles above only records (a test calls the cleanup itself).

  • 214. Five sub-steps: M4.8a cleanups on the same worker; M4.8b surviving failures (agent restart, lost worker, cleanup_anywhere, drain); M4.8c Python resources; M4.8d command and script resources; M4.8e the UI and test doubles. Not chosen: two steps (diffs too large to review well).

  • 216. An attempt whose process never started has no cleanup (rejected, a missing secret, a timeout during the reads): cleanup result not needed. Not chosen: running it anyway (nothing to clean, and it would fail on the same missing secret).

  • 217. Cleanups retry 3 times, 30 s apart, by default: cleanup_retries, cleanup_retry_delay, on the task and in StepDefaults. A stuck cleanup can hold its slot about 21 minutes. Not chosen: 0 (one network blip fails a run).

  • 218. A cleanup gets the connections its task declared, as it gets its secrets: a command’s variables and files stay until the cleanup ends. Not chosen: none (cancelling remote work, the main use, needs them); cleanup_connections= (usually a copy of the task’s list).

  • 219. A cancel doesn’t stop a running cleanup: it ends by itself or at cleanup_timeout. Not chosen: killing it (leaves behind what it was cleaning).

  • 220. A lost worker without cleanup_anywhere fails the run even with no handle registered: the master can’t know what the attempt did, and a cleanup may work from its inputs alone. The failure’s message points to cleanup_anywhere. Not chosen: not needed without handles (a real leak would give a green run).

  • 221. A cleanup_anywhere cleanup with no worker to take it waits, shown unschedulable; the task’s retry waits too. Not chosen: giving up after cleanup_timeout (a short outage would fail a cleanup that could have run).

  • 222. Handles are masked as outputs are (decision 167), before the journal and the master: no secret on the worker’s disk or in the database, the same list on any worker, a warning in the log. A cleanup needing a secret declares it. A resource’s value is an output, so the same holds. Not chosen: real in the journal, masked for the master (a secret on disk, and cleanup_anywhere gets different data); refusing at registration (a common value like admin would kill a healthy task).

  • 223. A setup called twice in a DAG is a parse error. Not chosen: an instance per call (every reference would need an instance name).

  • 224. .expand on a setup is a parse error. Not chosen: a resource per instance (users, “done” and the UI all per index).

  • 225. A resource’s cleanup goes ahead of waiting tasks and isn’t held by DAG limits; it needs a worker slot. Not chosen: oldest-ready order (a paid cluster runs on behind queued work).

  • 226. A resource’s cleanup inherits its setup’s secrets and connections and may add its own (@cluster.cleanup( secrets=[...]); a static Resource("tmp") has only its own); queue defaults to the setup’s. A forgotten declaration would surface only when the cleanup runs and leak what it should delete. Not chosen: only its own (that risk); only inherited (nothing for a resource without setup code).

  • 228. Handles take at most 1 MiB in total per attempt; going over fails the attempt, naming the limit. They travel in an assignment with cleanup_anywhere, within the worker’s 4 MiB message (as decision 181). Not chosen: 64 KiB each and 1000 per attempt, sent in chunks (more code and larger rows for a rare case).

  • 229. The task’s result is reported when its process ends, the cleanup’s in Finished: the master learns cleaning_up from it, and a worker lost during the cleanup leaves the task success with didn't run: worker lost, not run again. Replaces “one Finished carries both”. Not chosen: a bare CleanupStarted with the result in Finished (a finished task would run twice).

  • 230. No flag to skip waiting for a per-task cleanup; a slow cleanup that needn’t hold anything up is a resource’s. It can be added later without breaking anything. Not chosen: cleanup_wait=False for downstream tasks (cleaning_up would stop meaning “downstream waits”, and a failed cleanup would be reported after downstream acted).

Followed as designed (laid out with them): a resource cleanup missing from newer code is a failed cleanup; the slot stays held during cleanup retry delays; a drain leaves room for one cleanup try, not its retries; after an agent restart cleanups run from the journal with the attempt’s kept code, the attempt stays lost and its instance cleaning_up until they end, a missing copy being a failed cleanup; each mapped instance has its own cleanup.

Decisions 242-251 (the user’s, 2026-11-04; the options were Claude’s), for M4.8b:

  • 242. cleanup add doesn’t wait for the master: it returns once the handle is journaled and sent, and it is sent again on reconnect. A pod lost in that gap loses the handle for cleanup_anywhere. Not chosen: waiting for an acknowledgement (a master outage would stall tasks).

  • 243. A cleanup on another worker is the same attempt, moved: its row goes to the new worker, so limits and slots stay right; the old worker’s name stays in the log and the error summary. Not chosen: a separate row or table (new slot, limit and ownership handling).

  • 244. A cleanup with no worker keeps its instance cleaning_up, with the reason “no worker for the cleanup”, shown as unschedulable (how decision 221 is shown). Not chosen: a real unschedulable state (it would be requeued as a new try).

  • 245. On another worker a cleanup runs that worker’s current code, like any assignment; a cleanup function gone from it is a failed cleanup. Not chosen: only the original hash (it could wait forever after a deploy).

  • 246. A moved cleanup uses the task’s queue, ahead of waiting tasks, not held by limits (as decision 225). Not chosen: normal order (a leak waits behind queued work).

  • 247. Each move of a cleanup counts as a try: after retries + 1 it ends worker_lost. Not chosen: no limit (a cleanup running out of memory would take down pod after pod).

  • 248. A cleanup from the journal starts only on the master’s Continue, the answer to Register, so it never runs alongside a moved one; a master outage delays it. Not chosen: at once, reporting later (it could run twice).

  • 249. A cleanup outlasting the grace period runs until the pod is killed: a lost worker; outside Kubernetes the agent waits for it. Not chosen: killing it at the end of the grace period (leaves behind what it was cleaning, as decision 219).

  • 250. “cleanup_timeout doesn’t fit” is logged at assignment, once per task, not at startup as first written: the agent doesn’t know its tasks then. Not chosen: at startup for the server default (with the 30 s default grace it would fire on nearly every start).

  • 251. M4.8b is two commits: M4.8b the journal, restarts, the result kept, worker_lost and the drain; M4.8b2 handles to the master and cleanup_anywhere. Not chosen: one commit.

  • 252. A worker cut off from the master stops its tasks with cleanup_anywhere, and only those: at the worker lease with no word from the master. Their cleanup could otherwise run elsewhere during the task. Not chosen: every task (a long master or database outage would kill all running work); docs only (the risk stays, on every author).

  • 253. The cleanup of a task stopped so waits for the master’s answer: Continue runs it, Kill drops it, as after a restart (decision 248): it runs once, here or on the other worker. Not chosen: at once (it could run on both).

  • 254. A task with cleanup_anywhere ending by itself with no master waits the same way. Not chosen: its cleanup at once, as other tasks’.

  • 255. A cleanup under way when the master goes is left running, and may overlap a moved one: the docs say so. Not chosen: stopped at the same deadline (half a cleanup is often worse).

  • 256. The worker stops the task at the lease; the master moves the cleanup 40 s later: the cancel grace (30 s by default) and SCHEDR_HIDDEN__MASTER__CLEANUP_MOVE_WAIT (10 s), so raising the grace can’t outrun it. Stored with the attempt, so a failover keeps it. Not chosen: a public key.

  • 257. A task stopped so is lost, using a retry, as after a restart. Not chosen: a status of its own.

  • 258. The master answers each Heartbeat with HeartbeatAck, as it arrives, not behind its lock, and not while paused. Heartbeats went one way: a silent network cut showed nowhere. Not chosen: HTTP/2 keepalive (under Istio the sidecar answers the ping, so a real cut goes unseen).

  • 259. A resource is not a task with a cleanup: it is one thing of two parts, setup and cleanup, and both always exist. A task is a set of instructions and may have no cleanup at all, which then runs out of sight; a resource is by definition a setup and its undoing. So the model has resources of their own, each with its two parts, not a task with a flag. Not chosen: a task kind with an optional cleanup.

  • 260. A resource without @<resource>.cleanup has an empty cleanup, there in the graph and the run like any other, finished by the master with a line in its log, no process and no worker. Two cleanups stay a parse error. Replaces “exactly one cleanup per resource”. Not chosen: refusing it at parse (the author would write an empty function to say the same).

  • 261. The cleanup is a visible task instance of kind resource_cleanup, ID <resource>.cleanup: it reuses attempts, retries, logs, dispatch and the lost-worker path, and shows in the API, the CLI and the graph. A resource_instances table holds the resource’s state. Not chosen: hidden from task lists; an attempt and dispatch path of its own (most of the dispatcher again).

  • 262. In the graph a resource is two caps joined by a rail: the setup above its users with a rounded top, the cleanup below with a rounded bottom, one colour, the name on both; the rail a line in the side gutter, on hover or selection at first. Requirement edges reach the cleanup only from the last users. In lists, one row in two parts. The word stays “cleanup”. Not chosen: one box (the edges would leave it and come back; no place for it in the layers); bands around the users.

  • 263. A cleanup failed after its last retry fails the run and stays cleanup_failed, shown clearly; a command to retry it comes later. Not chosen: schedr resources retry now (reopens a finished run).

  • 264. A paused DAG’s resource cleanups still run: pausing stops new work, not the freeing of what exists (as decision 225). Not chosen: waiting for unpause.

  • 265. M4.8c is two commits: M4.8c1 the Python API, model and parse rules; M4.8c2 the master’s state, the cleanup and the run result. A resource with no users gets a parse warning, its cleanup running right after its setup.

  • 266. What follows a group waits for the cleanups in it: g >> after waits for the cleanup of each resource set up in g, by an order edge from the cleanup, unless after or anything after it uses that resource: then it keeps the resource alive, and waiting would be a circle. A failed cleanup stops after like any failed upstream task (upstream_failed). @res.cleanup( blocking=False) (default True) lets what follows go on, and a failed cleanup then only fails the run. A resource outside any group holds nothing back: a group is how to ask for the wait. The cleanup is shown in its setup’s group, but isn’t one of the group’s ends. Not chosen: nothing ever waits for a cleanup (quiet races with a quota or a check for leftovers; the graph would show the cleanup in a group that doesn’t wait for it); an explicit cluster.cleaned >> after with no wait by default (more API, and the default surprises). The master’s cycle check counts user -> cleanup, so a hand-made DAG can’t hang a run. in_background=, detached=, wait= were the other names.

  • 267. A resource has one cleanup, wherever it is imported: like a connection, a resource is shared by the DAGs that import it, and its cleanup is attached to it, not to a DAG. A different cleanup is a different resource.

  • 268. The cleanup is a method of its resource: @cluster.cleanup, bare or with options (@cluster.cleanup(blocking=False)), on a setup, an override of it and Resource(name). It says what decision 267 says, matches the task ID cluster.cleanup and needs no import. Not chosen: @cleanup(cluster), a function of its own, kept nowhere as an alias.

  • 269. Generators for one process, two functions across tasks: a connection stays a generator (open and close in one with, sharing their locals, try/finally for free); a resource stays a setup and a cleanup, because they are separate tasks, in separate processes, maybe hours apart. Not chosen: a generator @resource (it would hold a process for the whole run and lose the cleanup with the worker, or run the code after yield with its locals gone); @conn.close to match resources (state forced through a return value, for nothing).

  • 270. A run keeps its max_active_runs slot until its cleanups end, with blocking=False too: a run isn’t finished before its resources are gone, so a new run can’t collide with a teardown. Not chosen: freeing the slot when the last task ends (runs overlapping on one resource).

  • 271. Command and script cleanups are methods too: cluster.cleanup_command([...]) and cluster.cleanup_script(job=...), with blocking=, as decision 268. Not chosen: CommandCleanup(cluster, ...) and ScriptCleanup(...) as first designed (two styles for one thing).

  • 272. The graph shows what a cleanup holds back: with blocking=True the tasks after a group are drawn from the cleanup’s cap, the wait they really have; the edges from the users to them say nothing more and aren’t drawn. With blocking=False they are drawn from the tasks and groups they were attached to, and the cleanup’s own link is dashed.

  • 273. A cleanup waits for an unschedulable user, up to unschedulable_timeout: such a user isn’t done, and comes back by itself when a worker registers or resumes, so deleting the resource under it would lose the run. @cluster.cleanup(unschedulable_timeout=timedelta(hours=1)) bounds the wait: then the user is failed, with the reason “no worker within 1 h”, what follows it is upstream_failed, the run fails and the cleanup runs. timedelta(0) fails it at once; the default is no limit. With several resources the shortest applies. Cancelling the user also releases the cleanup. It is a DAG setting, no config key. Not chosen: unschedulable counting as done (a later tasks retry meets a deleted resource); the user skipped (a green run where the work never happened); a flag beside a timeout (they could contradict each other); no_worker_timeout, unschedulable_wait, give_up_after, wait_for_users.

  • 274. A cleanup keeps its own kind (python, empty, later command or script); its role comes from Dag.resources and is shown as “cleanup of cluster”. Amends 261. Not chosen: a kind resource_cleanup (it would hide what runs).

  • 275. A resource’s state is derived from its two tasks, not stored: waiting for users (setup succeeded, cleanup not started), cleaning_up (queued, running or up for retry), cleaned, cleanup_failed, not needed (setup failed, skipped or cancelled). Amends 261. Not chosen: a resource_instances table (a copy that can drift, a second write each time).

  • 276. An empty cleanup’s line goes in the task’s reason, shown where a log would be: logs live on workers, and it has no attempt. Amends 260. Not chosen: a master-side log store.

  • 277. Cancelling keeps cleanups: a cancelled run still runs the cleanup of every resource set up (retries included), and ends cancelled, or failed if a cleanup fails; schedr tasks cancel refuses a resource’s cleanup (amended by 279: it stops one). As 264. Not chosen: cancel as for any task (a resource left behind). Claude’s small calls with it: a cleanup ignores max_active_tasks, max_active and max_active_per_run (StepDefaults would hand it limits otherwise); blocking and unschedulable_timeout are in the DAG JSON’s resource entry.

  • 278. A resource’s cleanup without a timeout gets [worker] resource_cleanup_timeout, 30 minutes by default (public; the user picked 30 minutes over Claude’s hour): its run doesn’t cancel it (277) and ends only after it, keeping its max_active_runs slot, so one hung on a system that never answers held the DAG’s next runs for ever. The master marks the assignment (AssignTask.resource_cleanup), the agent fills the timeout (as 235: the worker’s value, not the DAG’s); an older master never marks it. A timeout is a failed try: the retries still apply, so a hang holds the run up to the limit times the tries (cancel it, or set a shorter timeout=). Not chosen: [worker] cleanup_timeout (5 minutes kills real teardowns, a cluster’s deletion, halfway); no default (the hang); a hidden value (operators tune it for their teardowns).

  • 279. schedr tasks cancel stops a resource’s cleanup (the panel’s Cancel too), as any task: one waiting (for its users, a worker or a retry) is cancelled at once, a running one is stopped; a run’s cancel still keeps them (277). The resource is cleanup_cancelled (what its setup made may be left) and the run ends cancelled (failed if something failed). A blocking cleanup’s cancel cancels what follows its group (its edges); a non-blocking one has none, so nothing else. The Cancel dialog says so. Not chosen: only with --force (the run’s cancel already keeps it, so stopping one is a deliberate act); the run ending failed (a deliberate act read as an error); success (a possible leftover hidden).

  • 280. A task without cleanup_anywhere may run twice while its worker is cut off: at least once, made visible. A cut worker can’t tell a master outage from its own cut, so it stops only cleanup_anywhere tasks (252); a master that is up marks the cut worker’s attempts lost at the lease and retries them elsewhere, and its other tasks run on in both places until the worker reconnects and is told to kill them. A frozen worker (its process paused: a stalled VM or node) can stop nothing, so after a freeze any task may run twice, a cleanup_anywhere one too if it outlives the lease and the cleanup’s move wait (its retry waits for its cleanup, 219 and 256); only fencing the node could prevent it (the user, 2026-11-05, accepted). The chaos scenarios (M4.8z) count these overlaps (tries_run_twice, listed in the scenario’s bundle) instead of failing on them; any other overlap fails, a cleanup_anywhere task’s on a cut (not frozen) worker included. The docs say such a task should be idempotent. Not chosen (the user, 2026-11-05; a side note found it): fencing every task (a worker cut past the lease stops all, the master retries after lease and grace: a master or database outage would kill all running work, what 252 avoids); an opt-in exclusive=True (B’s stop-and-wait per task, a public option: a later step if wanted); never retrying a cut worker’s tasks (work stalls for the whole cut).

  • 281. Nothing a worker starts was given away (B163): the agent ends a stream silent for the worker lease whatever it runs (not only with a cleanup_anywhere task) and acts on nothing arriving past it, and the master takes back an unstarted assignment only after the lease (it was 10 s), so an assignment held in a one-way cut is never started after the master ran the task elsewhere. Cost: an assignment lost on its way is run again after the lease (60 s by default) instead of 10 s. The same holds while it fetches an assignment’s inputs (a chunk past the lease isn’t word either: nothing is started, and no rejection sent), and on a worker’s first stream, before it knows its lease: a Registered older than the lease it states is dropped and asked again, whatever waits (the user, 2026-11-05, on Codex’s review; the cost: a master taking more than the lease to answer a Register sees the worker connect again, as a worker that knew its lease already did). Not chosen (the user, 2026-11-05): the agent side alone (an assignment held between 10 s and the lease still started); the worker asking before each start (a round trip on every task).

  • 282. A moving cleanup’s result from its own worker counts: a worker cut off while its cleanup ran (255) reports the result when it comes back; arriving before the move took place, it is stored and the move dropped, so the cleanup doesn’t run again. Its Finished in the journal of its Register is answered Continue, not Kill, so it is sent again. Only the worker it first moved from ran the task: from one it moved from later (a cleanup alone), the task’s kept result stands. Not chosen (the user, 2026-11-05): ignoring it as before (the cleanup ran twice in stress scenario 21).

  • 290. Resources beside the tasks on the graph (the user’s, 2026-11-05): a run’s graph draws its resources’ setups and cleanups in a “Resources” box on the left, a lane per resource (resources at once in lanes of their own), each at the height of the row it would have had, so the tasks’ rows stay as they were; their lines run in a channel between the box and the tasks (a track per resource and direction) and cross over only between rows, never through a box. Not chosen: the right side; the resources listed from the top, away from their rows.

  • 291. A resource’s lines cut down (the user: “two lines + hover”, 2026-11-05): when its users share a group, one line from the setup into the group’s box (at its users’ first row) and one from the box (at their last row) to the cleanup; otherwise the lines to its first users and from its last ones. The other lines show on hover or selection of the resource (its setup, cleanup, a user’s dot or a summary line), with its rail; each user has a dot in the resources’ colour. The lines from a cleanup to what follows it are always drawn. Not chosen: no lines but on hover (the order not visible at a glance); one trunk per resource with a branch to each user (many users, many branches).

  • 297. A master that doesn’t lead is neither ready nor holding streams (B165): paused (its database lease not renewed) or taken over, it answers /readyz with 503 (“starting: master”, as a standby) until it leads again, so its Service sends workers to the master that leads; a stream that reaches it anyway is refused at once with UNAVAILABLE, “not leading”, and the worker connects again; so is one whose Register waited for the lock while it paused. It used to stay ready and hold a stream until it led again, so a worker’s reconnect could wait there past its lease (stress scenario 05). Not chosen (the user, 2026-11-05): only the refusal (a Service still sending every new stream to it); only the readiness (a worker that got there anyway waits).

  • 307. A worker waits at most half the master’s lease between tries (B168, 2026-11-05): once a master has told it its lease, a worker’s reconnect backoff is capped at half of it, so a worker still alive reaches a master back from a restart before that master’s lease on it runs out (a restarted master gives every worker a fresh lease from its start). It used to wait up to reconnect_max (30 s by default, past a short lease): the master took it for lost and moved its cleanup with only the handles it had got, so a handle registered while the master was down was left behind.

  • 308. Handles the master never got are cleaned by the worker that has them (B169, the user’s: “Worker cleans the rest” and “Take it back”, 2026-11-05): a worker’s Register says how many handles each attempt in its journal has (JournalEntry.handles). When its cleanup moved from that worker (cleanup_anywhere) and the master has fewer:

    • the move still waiting for a worker: undone, the cleanup is the returning worker’s again (adopted; its first move’s kept lost result dropped, so the worker’s own result counts), nothing else cleans those handles;

    • the move given to another worker, or ended: the master answers CLEAN_REST with cleanup_from (the master’s count), the worker stops the task if it still runs and cleans the handles from there on; its result is added to the attempt’s once (rest_cleaned): a failure of either (failed, worker_lost) fails it, else either’s ok, tries and time add up; the instance’s cleanup result takes a failed or ok rest (a failure fails the run if it is still open; an ended run becomes a yellow SUCCESS, decision 309). An attempt still open combines its end with the rest added. The rest’s CleanupResult says it is one (rest), so it never counts as the whole cleanup, even from a worker the cleanup was given back to meanwhile. The worker asked is the one the cleanup first moved from (cleanup_origin: the one that ran the task), whatever moves came after. The master’s count is its handles from the first on without a gap: one past a gap is cleaned again rather than one in it left behind. The worker counts its handles from its journal. A worker that never comes back takes its unknown handles with it: nothing knows they exist. Not chosen (the user, 2026-11-05): the worker left to clean everything again while the move waits (the known handles cleaned twice).

  • 309. A yellow SUCCESS: a run’s state changed after its end (the user’s, 2026-11-05): a run that ended SUCCESS and learns of a failure afterwards keeps its state (whatever its success set off has happened) but is shown yellow, not green, with the reason; for now one reason, LATE_CLEANUP_FAILED: a rest cleanup (308) failed after the run’s end, its handles maybe left behind. The task instance shows its failed cleanup; an error is logged and a metric counts it, for alerts; with notifications (M4.13) it is one of their events. Failures and successes are expected; a yellow success isn’t, and asks for attention: a late cleanup failing often points at the DAG (a cleanup that fails on what is already gone, where it should succeed: cleanups are meant to be idempotent), and may not be rare then. It is the only way a run’s state changes after its end: every other cleanup, resources’ too, ends before its run does (decision 270). Not chosen (the user, 2026-11-05): the run turned failed (something may have acted on its success already); a run waiting for its lost worker (every such run held, the late case left anyway).

  • Built (B168, B169; decisions 307-309, 2026-11-05): the agent’s reconnect wait capped at half the lease; JournalEntry.handles (from the journal), CLEAN_REST with cleanup_from, CleanupResult.rest, a waiting move given back (take_back_cleanup), cleanup_origin, rest_cleaned and the merge of a rest into the attempt’s cleanup (failed and worker_lost win); the run’s late_failure (API, UI in yellow, CLI) and schedr_master_runs_late_failed. Codex’s review found the multi-move, the rest taken as the whole, the count read before the loop heard of a handle, the gap in the master’s handles and worker_lost overwritten: all fixed with tests. Roles tests stop a worker’s agent (SIGSTOP) while the master is down, so the handle it registered never reaches the master.

  • Built (M4.8z; decisions 280-282, 290, 291, 297; fixes B162-B165): chaos scenarios in the stress suite: the TCP proxy between workers and master cuts a link one way or both, slows it or freezes a worker (SIGSTOP), and a seeded random schedule under load (scenario 21), its seed in the report; the checks count tries run twice (280) and fail on any other overlap, on a cleanup started before its try ended or run to its end more than once; each scenario leaves an investigation bundle. The nightly stress.yml runs scenario 21 alone with a fresh seed when main didn’t change. The harness proxy dials upstream per connection with a 2 s limit (its accept loop waited 135 s on a master gone, failing scenario 05). B162: a cleanup gate past the master’s deadline waits for its answer. B163 (281), B164 (282), B165 (297). The run graph puts resources on the left (290) with two lines each and the rest on hover (291); examples/workspace.py is a resource example with its test. Codex’s review found 7, all fixed with a test each (the checker’s by reading): a second move’s report took the place of the task’s success; a fetch of inputs and a first stream escaped the silence limit (281); a cleanup gate past the deadline missed a deadline moved on; the journal’s Finished of a cleanup waiting to move was answered Kill (282); a master paused while a Register waited for the lock took it (297); the stress checker merged two runs of one try.

  • Built (M4.9a; decisions 292, 293, 296, 298-300): script roots (SCHEDR_SCRIPT_PATH, [scripts.roots]) scanned, hashed and settled as DAG roots and reported as RootKind::Script; a name shared with a DAG root a startup error (299). Their parse jobs read every schedr.toml in Rust on the agent (schedr_agent::jobs; nothing imported): every key checked, unknown keys and those not available yet (params, outcomes, cleanup, cleanup_handles, notify, 298) an InvalidScriptConfig import error naming the job. A scheduled job is a one-task DAG <root>:<path>#<name> with the task <name> (300), paused when first found; DAG IDs take :/# (250 bytes), percent-encoded in the client’s and the UI’s URLs. The script task kind is in the model; workers reject it until M4.9b. schedr dags check reads a schedr.toml or a script root (a configured script root never imported; a configured DAG root always a DAG check; a job’s interpreter missing here a warning, the worker that runs it checks it). Codex’s review found 6: a configured script root without schedr.toml imported by the check, a DAG root with a stray schedr.toml not checked, a linked schedr.toml or an ignored one named on the command line misread, a job name too long for a task ID dropped in silence: fixed with a test each; a stored DAG parse counting for a script root of the same name and content is B167 (fixed in M4.9b, with 301). Also: two agent tests’ leases widened to 300 ms (flaky since 281); B166 logged.

  • Built (M4.9b; decisions 293-295, 301-304, 306; B167): the script task kind runs: the job’s interpreter ([interpreters]) on the script, made absolute, from its script root’s copy, args rendered one argument each, PYTHONPATH the root’s copy; rejections 3-5, a script gone from the expected code a failure. ScriptOperator(task_id, job, args=, env=, secrets=, ...) asks the agent for its declaration over the parse channel (script_declaration), with 302’s overrides; outside a parse it only records the reference (306), schedr dags check looking it up in SCHEDR_SCRIPT_PATH. Each parsed file records the script roots it asked about (parse_files.script_roots); the master sends each DAG root’s set (Registered.script_uses, ScriptUses); a DAG root’s reported hash folds them in (fold_hash, a script root’s hash marked script: B167), a worker lacking one withdraws the DAG root (an empty CodeVersionChanged, its tasks rejected). Parses and tasks see the other DAG roots and script roots at their copies, held while they run (a recovered cleanup too, from the journal). Codex’s review found 7 (3 critical, 1 high, 2 medium, 1 low): a reference escaping its script root with .., a DAG root withdrawn for a script root no worker has never reparsed (303 refined: a grace of 5 minutes, SCHEDR_HIDDEN__MASTER__SCRIPT_ROOT_GRACE), a recovered cleanup losing its other roots’ copies, a withdrawn root still accepting a task sent before, the parse timeout restarted by each question: fixed with a test each; job= (renamed before it) and the guide (the docs round).

  • Built (M4.9c; decisions 310-314): params, outcomes, cleanup_handles and [jobs.<name>.cleanup] in schedr.toml; CleanupRun::Script; TaskKind::Script.resource; ScriptResource; .cleanup_script(job, args=, env=, ...) on all four resource kinds, one of the three kinds of cleanup as before; the cleanup settings on ScriptOperator. Journal: KeptAttempt.script_dir, so a recovered cleanup runs its task’s copy of the script root and holds it. A moved or recovered cleanup plans only what the cleanup runs (use_cleanup_script), so a worker lacking just the task’s interpreter can take it. Only notify is still not available.

  • Built (M4.9d; decision 305): the real executor parses only the .py files holding the bytes schedr (scan::mentions_schedr, in the copy being parsed), and starts no runner for a root with none; schedr dags check the same, naming what it skips.

  • Built (M4.8c1; decisions 259-269): @resource, Resource(name), @res.cleanup, uses= on tasks, operators and groups, the requirement edge kind and Dag.resources (setup, cleanup, users). The cleanup is the task <setup>.cleanup, added when the DAG is complete. In skip and None analysis a requirement never lets a task run, it can only stop it. The master checks that a resource’s users agree with the edges from its setup, that neither part is mapped, and counts user -> cleanup in its cycle check. A second @<resource>.cleanup from the same place is the file imported again and replaces the first; one from elsewhere is refused (decision 267). Only parsing: the master runs a resource from M4.8c2.

  • Built (M4.8c2; decisions 263, 264, 266, 270, 273-277): the master runs a resource. A requirement edge is left out of a task’s rule and only stops it (RunProgress::gate); a cleanup that could run waits until every user is in a final state (unschedulable isn’t). An empty cleanup is finished by the master with the reason “no cleanup declared: nothing to clean”. A run’s cancel leaves its resources’ cleanups alone: they are dispatched, retried and not stopped (RunTasks::cancels), and schedr tasks cancel refuses one. Ready cleanups come first and no concurrency limit holds them. Each dispatch round fails a user unschedulable past its resources’ shortest unschedulable_timeout (an index on unschedulable instances). ResourceState::of derives a resource’s state for M4.8e. No new configuration value: the timeout is a DAG setting (decision 273). Pausing needed nothing: it holds no task back. Codex’s review (4, all fixed): a mapped user counted done while instances it failed were still being stopped; a timeout’s stops of a failed step dropped; the timeout’s task and run ends written apart (now one transaction); a run cancelled with only a cleanup left ended success (a run being cancelled can’t now).

  • Built (M4.8d; decision 271, the command half): CommandResource(name, command, value=T, ...) and <resource>.cleanup_command(command, env=..., **CleanupOptions) on all three resource objects; schedr task-ctx resource set|get. In DAG JSON a command carries its part, "resource": {"role": "setup"} or {"role": "cleanup", "setup": ...}, which the master checks against Dag.resources (a command setup must be a CommandResource, its value no ProcessResult). The master always sends a command cleanup its setup’s output. The agent keeps the reported value in memory (the setup’s attempt is stopped on an agent restart; once it ends, the value is its output and journaled with it): set checks it against the declared type with params::to_stored (no coercion; a Pydantic model’s value isn’t checked in Rust), masks it, and takes it once; get works only in a resource’s command cleanup and prints the value as --params takes it. A setup exiting 0 without a value fails, resource_not_reported. Small decisions (Claude’s, to be overruled): .value on an @resource setup and a CommandResource is the value as a reference typed as the value, resolved when the DAG sets the resource up (a module-level @resource has no task ID before), so a command cleanup writes t"{cluster.value.cluster_id}"; a CommandResource also takes t"{cluster.cluster_id}" as planned. run_dag gives a CommandResource setup’s output as JSON (its class isn’t recorded). With this every CLI command works: the “milestone” test of the last one went. ScriptResource and cleanup_script moved to M4.9 with script tasks. No new configuration value. Codex’s review (10; 9 fixed, with tests): the value masked when the attempt ends, so a secret read after the report is masked too; a setup’s own cleanup= no longer took the setup’s role (it failed as “not reported”); in a union a model or Any is tried last (it took a tuple untagged); resource set --json takes any JSON (--json 7); a reported dataclass gives every field (params::to_reported: nothing fills its defaults before a command reads it); a value is at most what resource get can answer (about 1 MiB stored); resource get reads null (an optional value, or none); dates and times only in Python’s years 0001-9999 (also for run parameters); CommandResource overloads, so mypy takes CommandResource[int | None](..., value=int | None). Not taken: a value reported by a child after the setup’s main process exited but while its output drains (the setup’s own process group, bounded by the drain).

  • Built (M4.8e; decisions 25B, 262, 272, 275): a run’s cleanups and resources are shown and can be asserted in a test. The API gives each attempt its cleanup (result, tries, duration of the last try, error, moves to another worker, and its handles, masked), each task its cleanup result, and a run its resources (setup, cleanup, users, blocking and the state ResourceState::of derives from its two tasks). schedr dags test --json carries them, and run_dag gives Attempt.cleanup (schedr.testing.Cleanup, its handles as stored), TaskResult.cleanup and RunResult.resources (ResourceResult); task_context’s ctx.handles was there since M4.8a. The UI fills its shells: a task’s status is state · outcome · cleanup (cleanup failed, cleanup lost); the panel’s Cleanup tab lists each attempt’s cleanup with its handles and names a resource’s other part; the run has a Resources table, one row in two parts; on the graph a setup and a cleanup are caps (rounded on top, at the bottom) with a band in the resources’ colour, joined by a rail in the gutter on hover or selection, requirement edges dotted in that colour. The graph draws the cleanup reached from the last users (the DAG has no such edge: the master reads users) instead of the setup’s own link; with blocking=True the edges from the users to what follows the group are left out (the cleanup’s edge says it), with blocking=False the users’ link to the cleanup is dashed. Small decisions (Claude’s, to be overruled): handles stay as stored JSON in run_dag (decoding them needs the cleanup’s types); a cleanup’s worker_lost reads cleanup lost in the status; a mapped task’s row shows the worst of its instances’ cleanups (failed, then worker_lost, ok, not_needed). No new configuration value. Codex’s review (8, all fixed, with tests): handles are masked as task data in the API (by field names and texts, as outputs; the agent masks only the secrets the attempt read), so run_dag and the UI get them masked; a handle row that doesn’t parse is shown as {"unreadable": ...}, not left out; a mapped task’s cleanup failures showed nowhere on its row; the last users are found with one search per user (it was a search per pair: 0.8 s for 800 users); a data edge from a user to what follows its group stays; a resource without users and with blocking=False gets its dashed link; the Cleanup tab no longer claims a task without rows has no cleanup=; two docstrings (blocking, the cleanup’s duration over all its tries).

  • Built (M4.8f; decisions 278, 279): a resource’s cleanup can be cancelled and has a default timeout, found from a side note on M4.8c2: a cleanup hung on a system that never answers couldn’t be cancelled (277) and had no timeout, so its run, and the DAG’s max_active_runs slot, waited for ever. Execution::cancel_task no longer refuses one (TaskCancel:: ResourceCleanup gone; RunTasks::cancels already honoured an instance’s own cancel); ResourceState::CleanupCancelled when its setup didn’t fail, else not_needed; the panel’s Cancel dialog on a resource’s cleanup warns of the leftover, of what follows a blocking group, and of the run’s end (cancel_note); the run’s Cancel dialog says its cleanups still run. [worker] resource_cleanup_timeout (30 minutes, per try): the master sets AssignTask.resource_cleanup, the agent fills timeout_ms in plan (AttemptSpec:: default_timeout). Codex’s review (1, fixed): the dialog promised cancelled when a task had failed (the run ends failed).

  • Built (M4.8b; decisions 242-251): an attempt of a task with a cleanup keeps <attempt_id>.attempt (its assignment, inputs inside, its code’s copy and hash, before Started) and <attempt_id>.handles (a line each, on disk before the task hears of it) in the journal, and a cleaning record from the task’s end, with the result and the cleanup’s process. After a restart the agent stops what is left, holds a slot and waits for Continue: a task that was running is lost, its end reported with TaskEnded, one in its cleanup keeps its result, and the cleanup starts over with all its tries and its secrets read again. Kill drops it. An entry stays running in Register: the master’s answer is the same, so no new journal state was needed. A record with no process yet still gets its cleanup: the agent can’t tell whether one started. The master keeps TaskEnded’s result in attempts.task_result; an attempt whose worker is lost, or isn’t reported after a restart, ends with it (else lost), with worker_lost as its cleanup result. A drain stops each task at the deadline less one try of its cleanup, and never touches one in its cleanup. No new configuration value.

  • Built (M4.8b2; decisions 243-247): handles go to the master as they are journaled (HandlesAdded, all of them again on Continue) into cleanup_handles: the first at each place stands, up to 1 MiB of bytes per attempt, only from the attempt’s own worker. With cleanup_anywhere (task, DAG default, operator), a lost worker’s attempt gives its cleanup to another worker (AssignTask.cleanup_only), ahead of waiting tasks and not held by limits; the task’s result stays the one the master kept. A worker refusing it is asked last, not left out: with none other it is asked again. An assignment with no Started comes back without counting as a move. The moved cleanup’s handles are read from its kept assignment after a restart; a handle that doesn’t read is refused, never dropped. No new configuration value. Known limit: a worker cut off from the master keeps running; after the lease the master can’t tell it from a dead pod. So a cleanup with cleanup_anywhere can start on another worker while the task still runs, and the old worker runs it too when the task ends there or Kill cancels it: such a cleanup must be safe during the task, not only safe to repeat. M4.8b3 narrows this.

  • Built (M4.8b3; decisions 252-258): HeartbeatAck; the agent notes when it last heard from the master and, with tasks with cleanup_anywhere running, at the lease stops them (CutOff, lost) and ends the session, so that the answer to its Register settles each one. A per-attempt gate between the task’s end and its cleanup holds from the session’s loss till that answer. The master keeps cleanup_not_before on the attempt. A Registered older than the lease is dropped and asked again: the cleanup may have moved since. A fetch of inputs keeps the heartbeats and the stop going (the session’s loop waits for it; its heartbeats used to stop). A held cleanup doesn’t hold up a drain. A hidden value, 62 in all. What stays: a frozen VM can’t stop anything, so the cleanup must still be safe during the task.

Timings: public keys and hidden ones

  • Built (M4.8t; decisions 231-238): what a deployment may need to tune is a key, the rest fixed, and SCHEDR_HIDDEN__* changes the fixed ones.

Decisions 231-238 (the user’s, 2026-11-04; the options were Claude’s).

  • 231. A timing is a key only if its right value depends on the deployment. New keys: [master] parse_job_timeout, [webserver] worker_request_timeout, connection_test_timeout, [worker] runner_start_timeout, fork_server_preload_timeout, cleanup_timeout, Vault storages’ request_timeout and connect_timeout. Each has a doc comment saying what it does and when to change it. Not chosen: every timing a key (a wrong value can run tasks twice or lose a healthy worker).

  • 232. Eighteen timings left the config: tick_interval, heartbeat_interval, lease_timeout, lease_period, read_back_window, read_back_interval, query_timeout (with the lease fixed at 30 s it could only go down), loop_stall_timeout, set_aside, listen_retry, quiet_dag_after, quiet_dag_wake_ahead, quiet_dag_full_pass_interval, refresh_interval, worker_connect_timeout, drain_report_period, memory_check_interval, handshake_timeout. A file or SCHEDR_CONFIG__* setting one fails as an unknown key; no migration, it is a prerelease.

  • 233. SCHEDR_HIDDEN__<SECTION>__<NAME> changes a fixed timing: environment only, read once at startup with the configuration, each one set warned about, documented as unsupported and at one’s own risk. The tests use it to run in seconds. The odd name keeps anyone from setting one by accident. An unknown name or a bad duration stops the start. Not chosen: keeping them as keys with a warning; a build for tests only (the tests would run another binary).

  • 234. A hidden timing of zero is refused, for all of them: a zero interval panics in tokio::time::interval.

  • 235. A cleanup without its own timeout takes [worker] cleanup_timeout: the DAG JSON leaves timeout_ms out, and the worker fills it in. Not chosen: the 5 minutes fixed in the Python API (the key would change nothing).

  • 236. The constants follow in M4.8u, about 40 more on the hidden route, as values passed down in each crate’s own struct with defaults, in the server, worker and webserver only: the client, task-ctx and the CLI don’t load this configuration. The two auth timings stay constants until it is checked what they do to a revoked token. Not chosen: one global set at startup (tests in a process would share it, and it hides a dependency).

  • 237. A new configuration value is public or hidden, and a constant in the binary only for a really good reason: a key when its right value depends on the deployment, SCHEDR_HIDDEN__* otherwise. Not chosen: a constant by default (changing it takes a rebuild).

  • 238. A public timing that can’t work at zero is refused at load: [dags] poll_interval, parse_file_timeout, [master] parse_job_timeout, [webserver] worker_request_timeout, [worker] log_retention, runner_start_timeout, fork_server_preload_timeout, cleanup_timeout, Vault storages’ request_timeout and connect_timeout. Where zero means something (settle_time, cancel_grace, code_wait, drain_terminate_period, fork_server_import_retry, cache_ttl) it stays allowed.

  • Built (M4.8u; decisions 239-241): every server-side timing on the hidden route, 61 in all.

  • 239. The auth timings go hidden too. Checked for decision 236: a change of the users file forgets every remembered check, so auth_remembered has no effect on revocation and only saves bcrypt runs; auth_recheck is how long a change takes to count, and the docs say so. Neither has a reason to stay a constant (decision 237).

  • 240. The inline timings count as well: Vault’s two renewal waits, a stopped group’s poll, a connection test’s cancel grace, the listeners’ retry after a failed accept.

  • 241. What stays a constant, and why: the gauge refresh limit (derived in production, half of loop_stall_timeout), the connection for migrating (no query_timeout, so no limit to tie to), and what the client, task-ctx and the CLI use (they don’t load this configuration).

Output serialization

Task outputs are JSON (with tagged extra types, below); there is no pickle. Three checks make sure an output can be serialized, from earliest to last:

  1. Type checker (editing time). @task only accepts functions whose return type is JSON-compatible, via a recursive type alias bound on its type variable:

    type Json = (
        bool | int | float | str | datetime | date | timedelta
        | Sequence[Json] | Mapping[str, object] | DataclassInstance | None
    )
    
    def task[**P, R: Json](fn: Callable[P, R]) -> Callable[P, R]: ...
    

    Sequence/Mapping (not list/dict, which are invariant) so that e.g. list[int] is accepted; Mapping[str, object] (not Mapping[str, Json]) because a TypedDict is only a Mapping[str, object] to type checkers, so dict values aren’t checked statically (the parse-time check does). Verified with mypy --strict: TypedDicts and dataclasses are accepted; set[int], dict[int, str] and object are rejected. Only as good as the user’s tooling, and Sequence lets a few wrong types through (e.g. bytes), so it is a help, not the guarantee.

  2. Parse time (the guarantee). The runner reads the return annotation (typing.get_type_hints()) and walks it recursively against the supported types: None, bool, int, float, str, datetime, date, timedelta, list, tuple, dict[str, …], Literal, unions/Optional, TypedDict, dataclasses and Pydantic models (see Dataclasses and Pydantic models below). An unsupported type is an import error for the file, naming the task and the offending part (e.g. “task extract: return type dict[int, str]: output keys must be str”); the DAG is not registered. The same type model checks inputs: passing an Output[T] to a parameter whose annotation doesn’t accept T is a parse error.

    • Annotations are resolved when the task is first called in the DAG body, so they may refer to names defined later in the file.

    • Not supported (parse errors naming the part): tuple[T, ...] (use list[T]), a bare tuple, recursive types (a dataclass referring to itself), generic type aliases with parameters, set, bytes, Decimal, object and other classes. Pydantic models have their own descriptor (M4.1e, decision 59; below).

    • Compatibility of an output with a parameter: int fits float; bool doesn’t fit int (no coercion, as at run time); containers are checked element by element; a union fits if each member fits; a Literal fits if each value fits; dataclasses and TypedDicts match by name and fields. Paths (out.rows[0]) are checked against the producer’s type, for every reference at any depth.

    • Literal arguments are encoded against the parameter’s type at parse time, so a wrong literal is a parse error too.

    • An argument written as a structure with references inside is built as the parameter’s type (decision 112, the user’s, 2026-10-31: A; B65): consume((produce(), 3)) for tuple[int, int] gets a tuple, consume({"x": produce()}) for a dataclass or a Pydantic model gets an instance (the model validated by Pydantic’s rules for Python values, each field already its type), each part decoded against its own type at any depth. For a union (tuple[int, int] | None, Point | None) it is built as the first member of its shape that it fits (B121), and its literals are checked against that member at parse time when only one member has its shape. A field missing or refused fails the attempt (input_mismatch). Not chosen: B refusing such arguments at parse time (DAGs using them today would stop loading).

    • References in command lines and templates must have a type that can be rendered as text: strings, numbers, booleans, dates, times, durations, Any, or unions of them. None, lists, dicts and classes are parse errors (pass a field, or convert in a task).

  3. Run time (the actual value). The runner encodes the returned value guided by the annotation and fails the attempt (failed) on: unsupported types (Decimal, set, custom objects), non-str dict keys, NaN/inf, integers outside the 64-bit range, strings or dict keys containing NUL (\0, decision 106), values nested more than 100 lists and dicts deep (MAX_DEPTH, under the agent’s JSON reader’s 128 levels, B76), and any other error while storing it (a model’s serializer failing, a value containing itself: output_not_serializable with the exception’s type, B67), values not matching the annotation, or values over the output size limit. The error summary names the exact location (e.g. “output of extract not serializable at [3].created: Decimal is not supported”).

Tagged extra types. datetime, date, timedelta and tuple are stored tagged, not as plain strings, so Rust can render them correctly in t-strings without Python, and a downstream task annotated Any still gets the real type back:

Type

Stored as

datetime (aware only; a naive one is a run-time error)

{"$datetime": "2026-10-19T03:00:00+00:00"} (its offset kept)

date

{"$date": "2026-10-19"}

timedelta

{"$timedelta": 3600000000} (whole microseconds: exact, simple to read in Rust)

tuple

{"$tuple": [1, "a"]}

Numbers arrive exactly (decision 105, the user’s, 2026-10-31: A; B64). Python writes a float’s shortest exact text, and the agent and the master read it back to the same bits (serde_json’s float_roundtrip). An integer is stored only in the range Rust reads exactly, -2**63 to 2**64 - 1; a larger one fails the attempt with “outside the 64-bit range … store a larger number as a str”, where the value was written, not later where it would arrive as an inexact float. The same holds for a Literal integer and for a timedelta’s microseconds (about -106,751,991 to 213,503,982 days, B131). Not chosen: B arbitrary_precision (every number kept as text through the agent and the master, a change to every place that reads one, and an integer Postgres’s jsonb keeps but other readers may not); C storing large integers tagged (a new tag, for a rare value).

No NUL in a stored string (decision 106, the user’s, 2026-10-31: A; B86). Postgres stores no NUL in text or jsonb, so a string or dict key holding one fails the attempt where the runner encodes it (“a string containing NUL (\0) can’t be stored”), instead of the master failing to store the completion and the task staying running. Not chosen: B replacing NUL silently (a different value downstream); C escaping it in storage (every reader of outputs would need to undo it).

The master stores no NUL (decision 114, the user’s, 2026-10-31: A; B105). Text a worker sends may hold NUL that no runner check refused (an exception’s message and traceback, an import error, a warning, a DAG’s own strings, or an older agent’s values): the database layer replaces it with U+FFFD in every string and key of the JSON it writes, so Postgres takes it and the attempt’s end isn’t refused for ever. JSON without NUL is written as it is (not parsed). Not chosen: B replacing it only in the runner’s error summaries (older agents and other text still refused).

A command’s output shows NUL as � (decision 110, the user’s, 2026-10-31: A; B104). The stdout and stderr of a ProcessResult are text: the agent already replaces invalid UTF-8 with U+FFFD, and replaces NUL the same way, so find -print0’s output is stored (and its names are separated by �). The log file keeps the bytes. Not chosen: B failing the attempt (every -print0 or binary-ish command would fail); A’ writing NUL as the text \0 (ambiguous with a real backslash and zero).

A dict shaped like a tag is escaped (decision 104, the user’s, 2026-10-31: A; B66). A dict of the user’s own whose only key is a tag ($datetime, $date, $timedelta, $tuple, or $dict itself) is stored as {"$dict": {...}}, so {"$date": "x"} reads back as that dict, not as a date (or an error). Only that shape is escaped; a dict with two keys, or with a key that isn’t a tag, is stored as it is. It holds for dict and TypedDict values and for dicts inside a Pydantic model’s dump. A path into the output (out["$date"], by the master, the agent or the runner) goes through the escape, and so does a literal dict written beside a reference in an argument (B122). Outputs stored before read as they did: a tag there stays a tag; only a dict of the user’s whose only key was $dict now reads as its inner dict (nothing to migrate before the first release). A worker older than this, during an upgrade, reads an escaped dict as {"$dict": {...}} (only for dicts shaped like a tag). Not chosen: B refusing such a dict as an output (a valid value refused, with no way around it but renaming the key); C storing every dict wrapped (every output larger and different from what users see).

One output per task; references can point inside it. There is no separate “multiple outputs” concept in the native API. A task has one output value, stored once per (DAG run, task, map index). A reference can address a part of it: out["rows"] (dict / TypedDict key), out.email (dataclass / Pydantic field), out[0] (list / tuple index). In the DAG JSON a reference is plain data (task + path, e.g. {"ref": "output", "task": "extract", "path": ["rows"]}); the master extracts that part from the stored value when it builds the downstream task’s inputs, so downstream tasks receive only what they use. The same reference works as a task argument, inside a t-string (rendered by Rust without Python) and in .expand().

  • Paths are checked at parse time against the annotations (unknown field or TypedDict key → parse error). Only free-form dict[str, …] keys can’t be checked; a missing key fails at run time with a clear error.

  • Indexing loses the static type (Output[Any]): Python’s type system can’t express it for a generic wrapper. The parse-time check still uses the real annotations.

  • The size limit applies to the whole value.

  • The Airflow layer’s multiple_outputs=True and output["key"] map onto this.

Outputs of command and script tasks: ProcessResult. Following the one-output rule, their output is a ProcessResult (a dataclass in the schedr package): stdout: str, stderr: str, exit_code: int, stdout_truncated: bool, stderr_truncated: bool.

  • listing.output is an Output[ProcessResult]; listing.stdout / listing.stderr are shortcuts for the paths .output.stdout / .output.stderr (Output[str]).

  • A downstream @task can take the whole result (res: ProcessResult) and gets the truncation flags and exit code explicitly.

  • “Reading a truncated output is an error” applies to .stdout / .stderr references; a task taking the whole ProcessResult has opted in and sees the flags instead. Only a ProcessResult is checked (a stored object with exactly its five fields): a user’s own dict with a data_truncated key is data, its data read as any other (B75).

  • No automatic parsing of stdout (JSON, CSV, …): a downstream @task parses it and gives it a proper type.

  • In the Airflow layer, .output stays the last line of stdout (not a ProcessResult), produced by a hidden native task (see Thin translating classes).

Output size limits.

  • Each task has an output size limit, default 1 MiB (encoded JSON for Python return values; per stream for stdout/stderr).

    • A Python task’s return value over the limit: the attempt fails (partial JSON is useless).

    • stdout/stderr over the limit: truncated to the last part and marked truncated; a downstream .stdout / .stderr reference to it gets an error.

  • A DAG author can raise the limit per task (or in StepDefaults) with max_output_size (bytes; constants KiB, MiB in schedr, e.g. @task(max_output_size=8 * MiB)), but never above the server-wide maximum. A task asking for more is rejected when the master validates the DAG (shown as a DAG error in the UI).

  • Configuration:

    • [outputs] default_max_size, default "1MiB";

    • [outputs] max_size_limit, default "16MiB" (env SCHEDR_CONFIG__OUTPUTS__MAX_SIZE_LIMIT).

  • max_size_limit above the cap on total inputs per task (default 64 MB) is a startup error: an output that big could never be passed to a downstream task.

  • The 4 MB inline threshold in AssignTask is unchanged (bigger inputs are downloaded in chunks).

Outputs of mapped tasks. Each mapped instance has its own output (stored per run, task, map index). A reference to the mapped task’s output as a whole, e.g. sizes = process.expand(path=files), is an Output[list[T]]:

  • A task that isn’t mapped receives a plain list of the instances’ outputs, in map-index order (the order of the input list, not completion order), so the result is deterministic. No lazy loading: the list counts against the receiving task’s total-inputs cap; huge fan-ins are not a goal.

  • If any instance fails (after retries), the receiving task becomes upstream_failed; it never sees a partial list.

  • Empty expansion: zero instances means the mapped task succeeds and receivers get [] (not skipped, unlike Airflow).

  • Mapping over a mapped output maps element by element: check.expand(size=sizes) gives check[i] the output of process[i].

  • Paths on a mapped output only index the list: results[0], results[0].rows. A field path applied to every element (results.rows) is always an error; to collect a field from all instances, write a small task that gathers it.

Missing outputs. In the native API a downstream task never runs after a failed upstream (upstream_failed), so an output can only be missing because its task was skipped. A parameter taking data from a task that can be skipped must allow None (parse-time check) and receives None (see Outcomes, failures and joins).

Retention. Outputs are stored with their DAG run and deleted together with it, or earlier if [retention] outputs is shorter (see State storage: Retention).

Dataclasses and Pydantic models are supported as output and input types.

  • Pydantic models: only when Pydantic is installed (detected from annotations; extra schedr[pydantic], pydantic>=2.11,<3). Never a required dependency: the schedr package shares the user’s environment and stays dependency-free, and importing Pydantic would add start-up time to every task. schedr hands validation to Pydantic (model_dump(mode="json", by_alias=False) / model_validate_json(..., by_name=True): keyed by field names, so a path out.url is by attribute name, as type checkers read it; by_name needs 2.11), so Pydantic’s own rules apply (lax by default, strict if the model says so). Built in M4.1e (2026-10-29).

    • The type is Pydantic’s JSON Schema (decision 59, the user’s, 2026-10-29: C): DAG JSON’s {"type": "model", "name", "schema"}. An output holds the serialization schema (every field marked required: model_dump writes defaults too), a parameter the validation schema (fields with defaults optional). Rust only stores it (TypeDesc::Model; its parts are Any there); the Python layer compares. schedr’s own descriptors are turned into JSON Schema for the comparison, so a model meets dataclasses and plain types in one check.

    • Strict comparison: an output fits only when every value it can be is provably accepted. A constraint, format, enum or required field the parameter has and the output lacks is refused (59.1: int into Field(ge=0), str into HttpUrl); what can’t be compared (allOf, not, if, differing patterns, schedr’s tagged tuples against Pydantic’s lists) fits only when identical (59.2). $refs are followed; recursive models fit themselves. The error names the field and both sides’ constraints.

    • A model is read back as JSON (decision 111, the user’s, 2026-10-31: A; B68): its stored data is JSON, so the runner validates it as Pydantic validates JSON (model_validate_json): a strict field takes a date as ISO text there, as from any JSON, and refuses what JSON wouldn’t give it ("3" for an int). schedr’s own tags in the data (a dataclass’s or a plain output’s) are written first as Pydantic writes those values in JSON (dates as ISO text, durations as ISO 8601 durations, tuples as lists). schedr still never imports Pydantic. Not chosen: B validating in Python mode with strict=False (it would accept coercions the author forbade).

    • A model’s dates are dates (decision 60, the user’s, 2026-10-29: B; “the user sees datetime and expects it to just work”): Pydantic writes them as text (date-time, date, duration), schedr tags its own ({"$datetime": ...}); the comparison lets each fit the other, and the runner converts when the task receives the value: text through Pydantic’s own parser (TypeAdapter), schedr’s tags written as the JSON text Pydantic writes for those values before model_validate_json. A date the model holds without a time zone stays naive: Pydantic stored it, so schedr’s own rule against naive datetimes (about what schedr stores) doesn’t apply. Plain str still doesn’t fit a datetime (no format proves it a date). Passed on, a naive value stays refused when schedr stores it (decision 63, the user’s, 2026-10-29: A), the message saying where it usually comes from: declare the field AwareDatetime, or add a zone. Not chosen: storing naive datetimes (B: schedr’s stored times are moments, shown in UTC and local time; its Rust rendering and the UI read them as timestamps; naive and aware values then meet in tasks); reading them as UTC (C: a guess). Not chosen: A refusing (strict, but the field’s type says datetime); C storing a model’s dates tagged (schedr rewriting Pydantic’s JSON, each Pydantic type needing a conversion).

    • Not chosen: A schedr’s own descriptor for a model’s fields, with Pydantic’s types mapped to what they dump as and the rest Any (less code, but Any parts go unchecked; with Rust costing the same, the user chose the strictest); B an opaque model matched by name (paths unchecked).

  • Dataclasses (standard library):

    • Encoded field by field (an asdict()-like walk guided by the annotations); decoded by calling the constructor with keyword arguments, recursively, guided by the downstream annotation. No class name is stored: the stored value is a plain JSON object, so renaming or moving a class doesn’t break lookups and no code is loaded by a name taken from stored data; a downstream task annotated Any gets a plain dict.

    • Supported: plain fields, defaults, frozen, slots, kw_only, inheritance. field(init=False) and InitVar are a parse error for now.

    • Field types are checked recursively at parse time: an unsupported field type is an import error naming the field (e.g. “Customer.tags: set[str] is not supported”). Any on a field is allowed as an explicit opt-out (run-time check only).

    • Field values are checked strictly at run time, on output and again on input, with no coercion: "5" for int and True for int are errors; int for float is allowed. A mismatch on input means the class changed between runs (e.g. a retry after a code change) and fails loudly.

    • Type checker: a DataclassInstance protocol in the Json alias makes dataclass return types accepted (verified with mypy --strict); unsupported field types are caught at parse time, not by the type checker.