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
schedrpackage (see Native API).Compatibility APIs: look-alikes of other orchestrators’ APIs, each in its own subpackage named after the orchestrator.
schedr.airflowis 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 ( |
Edges between task IDs |
Master: dependency resolution |
Trigger rules |
A per-task field |
Master: when a task is ready, skipped or |
Branching |
A |
Master: skips the branches not chosen and propagates the skip |
Task groups |
Flattened to |
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 ( |
t-strings |
Literal text plus typed references |
Agent / runner: filled in at run time |
|
An |
Master completes it, no worker |
|
A |
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@dagdecorator: 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
@taskmust annotate its return type (-> Nonefor a task without output). A missing annotation is a parse error.-> Anyis 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@taskfunction 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@taskreturningTgivesT, so it passes to a task takingTand its fields are typed, in mypy--strictand pyright / basedpyright alike, without a plugin. Python’s typing can’t say “anOutput[T]is also aT” (no intersection types, no mapping over aParamSpec’s parameters), so the DAG methods come from the value’s side:Outcome classes derive from
schedr.Data(adataclass_transformbase: the subclass is a dataclass, options as class keywords,class Rows(Data, frozen=True)) orschedr.pydantic.Model(aBaseModel, imported only with Pydantic; one base, as basedpyright refusesBaseModeland 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)(typedCls), and loading the file raises aschedr.TypingHintwarning naming the class, whichschedr dags checkprints (57.4: the runner returns the warnings an import raised with the file’s result, aswarningsonfile_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
NonegivesDone(chosen by@task’s overloads, so a wrong argument is still a plain argument error), a@branchcallChosen,.on(None)and an enum outcome’s.on(member)Done; each has>>.Outcomeenums declare.on,.outcome(typed as the enum) and>>;CommandOperatoris generic in itsoutcomes=enum (.ontakes its members,.outcomeis one;.on(...),.outputaProcessResult,.stdoutastr);ProcessResultdeclares>>.Task(a branch’s return annotation) isobject.dag_ctxfields 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 readrowsas the value and accept them),Nonefrom 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) needschain(); a branch’s returned handles aren’t checked (Taskisobject; the branch fails when it runs);.partial(),.expand()and.expand_kwargs()takeobject(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 lintruns mypy--strictand basedpyright (its default, strictest mode, withreportUnusedExpressionandreportUnusedCallResultoff:a >> band an operator alone on a line are statements on purpose) over the example DAGs andpython/tests/typing/dag_types.py, whose expected mistakes carry ignore comments that must stay needed (57.3). basedpyright is pointed atpyproject.toml(--project): apyrightconfig.jsonin a parent directory would win otherwise. An editor runs basedpyright on every file it opens: an execution environment forpython/turns off there the rules basedpyright alone enforces (the library and its tests are mypy’s and ruff’s),python/tests/typingkeeping the strict ones, so the editor shows whatmake lintchecks (the user, 2026-11-03: Zed flagged the library’s wrapped messages).Not chosen: B
Outputtyped as a subclass ofAny(accepted everywhere: no argument checked); D′ calls kept asOutput[T]with.valuefor each data pass and.on(Cls)typedCls(every plain pass grows); C a mypy plugin (mypy only: editors on pyright get nothing); atypes-schedrstubs package (the same typing language, so no more expressive, plus drift); a per-task@task(typed=False)typedAny(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
@taskand is required for operators. Duplicate IDs are a parse error. Using a@taskfunction more than once in a DAG (e.g. in a loop):fn.override(task_id= "load_eu")(Airflow’s name), which can also overrideretries,retry_delay,timeout,queue,max_output_size; the duplicate-ID error points to it.@taskfunctions declare each parameter:*args/**kwargsand 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) andinitial_since(onDag) without a time zone (start="2026-01-01", adate, a naivedatetime) are read in the trigger’s time zone, like the cron expression (UTC forEveryand 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. OneDagparameter, a typed object, for everything that starts runs besides people and other DAGs: a time trigger,Cron("0 3 * * *"),Every(timedelta(hours=1))orOnce("2026-12-24T23:00")(a single fire time), plus preset constants (DAILY, …); an event trigger, a@triggerfunction called with its arguments (trigger=new_files(prefix="s3://in/"), M4, see Sensors and triggers); orNone(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@triggerfunctions.catchupbelongs to the time triggers that have fire times to miss:Cron(..., catchup=True),Every(..., catchup=True).Once, event triggers andNonehave none, so acatchupthat would mean nothing can’t be written.startandendbelong 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, andEverycounts its fire times fromstart, so they are part of the trigger.NoneandOncehave no window, so astart/endthat 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 checksstartnot afterendas before; the Python API checks it at parse time too.initial_sincestays onDag: it sets the window of the DAG’s first run, which matters for manual-only DAGs andOncetoo, so it is about runs, not the trigger.Not chosen for
start/end: keeping them onDagas “the DAG’s active period” (familiar from Airflow, but allows combinations that mean nothing, and tiesDag’s arguments to the trigger’s time zone).Custom triggers are event triggers only. The master never runs Python, and fire times,
catchup, backfill andsincecome 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); theschedr.tomlkeysschedule/every/once/catchup/start/end(flat keys read naturally in TOML, and jobs have no event triggers); the Airflow layer’sschedule=(Airflow’s name, translated).Not chosen:
schedule=(the earlier name: it named half of what it took, and event triggers needed aWhen(...)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, andtrigger=pairs with@trigger.Onceis 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 usingsincemust setinitial_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 fromstart, or from the Unix epoch without one (soEvery(timedelta(hours=1))fires on the hour, UTC); fire times beforestartexist 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@hourlyare); anything else (*, a step, a range, a list) is not, for the overlap rule. The expression is matched against wall-clock times bycroner; 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) anddag_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 afterstart.catchupdefaults to False. (Airflow 3 moved the same way: cron schedules run at the fire time.)Without
startthe 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; withcatchup=Trueevery fire time since it was first stored gets a run.max_active_runscounts running runs; queued runs wait outside it. A scheduler pass creates at most 100 runs per DAG (acatchupbacklog with no limit continues in the next pass).end(optional, mirror ofstart): the last scheduled run is the last fire time at or beforeend(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:startandendapply only to runs of kindscheduled; manual and backfill runs may be for any time, beforestartor afterend(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 thecatchuprules decide: withcatchup=False, when a run finishes only the most recent missed fire time gets a run (a slow DAG never builds a backlog); withcatchup=Truethe missed ones get runs in order, still at mostmax_active_runsat a time. Scheduled fire times never queue (they are missed); only manual and backfill runs wait, asqueued. 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).tagsanddescription: 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_taskson theDag(defaultNone, 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_runon a task (defaultNone): 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_activeon a task (defaultNone): 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.tomljobs need no key (one-task DAGs:max_active_runscovers 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_runfrom 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
-1row never does.90,
max_active_per_runon an unmapped task (A): a parse-time warning shown bydags check(it limits nothing: one instance a run), not for a value fromStepDefaults. 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_run10, 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 ofdefault_args={...}. Groups can set their own defaults; a task’s own arguments win.Routing: outcomes first,
@branchfor 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))
@branchchooses 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): underNoneFailedit still runs if another of its edges succeeded, underAllSucceededit is skipped. The empty subset is allowed: returning[]skips the direct downstream tasks that have no other edge (Noneis 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.branchfollows this rule, and the translation’s notes say so for a target with other upstream tasks (give itAllSucceededto 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 groupsouter.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 >> publishwithout listing whatloadholds); 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_ifon 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 >> grouplinksxto the group’s roots (its tasks with no upstream inside the group),group >> ylinks the group’s leaves (no downstream inside it) toy, as Airflow’sTaskGroupdoes. 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 thewith 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: witha >> bandcinload,start >> loadgivesstart >> a,start >> c, andload >> publishgivesb >> publish,c >> publish. Edges count in trigger rules (55B), so this lets skips flow along the group’s own chain: a skippedaskipsb, which doesn’t also hang onstart. 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 forx >> groupand the leaves forgroup >> y(neither rule’s simplicity).Built in M4.2b (2026-10-29):
with group("load", defaults=StepDefaults(...), run_if=...) as load:(schedr.group, aGrouphandle); a group’s name is one ID part; it may not repeat in its parent nor be a task’s ID; the same@taskfunction 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 >> thenjoins the set of the group’s last tasks to the tasks after it with plain order edges, a@branchamong them included: it counts as having run, whatever it chose, and each task after it applies its ownrun_ifover 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@branchto 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, sothenwas 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
groupslist ({id, parent}, outer before inner) and an optionalgroupon 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’sprefix_group_id=Falsecan be represented. Not chosen: B membership from the ID’s prefix (nothing to store, butprefix_group_id=Falsecan’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_dagper instance.@taskfunctions only for now (operators’.partial()/.expand(), which M5’sBashOperatorneeds, later). For type checkers.expand(...)returnslist[R].DAG JSON (decision 69, the user’s, 2026-10-29: A): the fixed arguments stay in
arguments(.partial), and anexpandfield 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 insidearguments(every reader ofargumentswould 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@branchcan’t be mapped. A reference to a mapped task’s output is alistof its output type: indexing is allowed (results[0]), a field of every element (results.rows) refused;.on(...)and.outcomeon 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) hasNonefor them: the receiving type must allow it. Not underrun_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]getsprocess[i]’s output. Not chosen: B startingcheck[i]as soon asprocess[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. Soproductis an ordered list in DAG JSON. Not chosen: B the parameters’ names in alphabetical order (no format change, but renaming a parameter would reordermap_index).Lanes: mapping over a mapped output (decision 70 revised, the user’s, 2026-10-30: B):
check.expand(n=sizes)over the mappedsizecreatescheck’s instances as soon assizehas expanded (its count is known then), andcheck[i]waits only forsize[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, sosize >> checknext to the expansion restores the barrier (A’s behaviour: nothing ofcheckstarts before all ofsizehas finished, nothing of it runs ifsizefailed); M5’s Airflow layer adds that edge itself. A reference tosizeanywhere else incheck(.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 ofsize, then skips each instance whosesize[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, andreport’s ownrun_ifdecides over them with its other edges:NONE_FAILED(the default) runs it when any instance endedRows,ALL_SUCCEEDEDonly 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,Rowswas compared with the whole task’s own outcome andreportwas 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 = -1row. 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:scheduleduntil its upstream is ready,runningonce expanded, then its state from its instances. Expansion adds the instances0..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_failedwhen only lanes failed), its downstreamupstream_failed. Otherwise, once every instance has finished, the task applies its ownrun_ifto its instances as if they were its edges (75b: D):NONE_FAILED(default) skipped when every instance was skipped, else success withNonefor the skipped ones;ALL_SUCCEEDEDskipped 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 wholeRows | Missingdoesn’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_outcomesfor 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 inAssignTask, 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_indexorder,Nonefor a skipped instance. Not chosen: B storing the list on the-1row 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
-1row is listed too, as the task as a whole (map_index: -1,instances: N,nullfor an unmapped task, andreasonwhen it failed without an attempt), then its instances0..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 (Nonefor 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=Non 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_numberandtask_ctx.map_index(Nonefor an unmapped task) while a task runs: the object secrets and connections join later. Not chosen: Bdag_ctx.run.map_index(not the run’s); C theSCHEDR_MAP_INDEXvariable only.85,
run_dag:result.tasks["fetch"]is the task as a whole (its.outputthe gathered list);result.tasks["fetch"][1](and.instances) each instance’s result. Not chosen: B"fetch[1]"keys.86, the CLI:
--map-index Nontasks logs / attempts / output / cancel / retry;runs showanddags testlist instances asfetch[0],fetch[1], … after the task’s own row. Not chosen: Bfetch[1]as the task argument.
Why a task failed with no attempt (decision 78, the user’s: A): a nullable
reasonontask_instances(more instances thanmax_instances; a mapped list that isnullor not a list when it expands). Not chosen: B reusingqueued_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 outside0..N-1is a 400, on every endpoint (cancel included); a result that arrives after the step already failed is ignored (the instance endscancelled, 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 (noNoneto allow).An element written with a t-string or
dag_ctxis 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
TypeErrorwhen 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_failureedges, no failure trigger rules, no callbacks). A failed task fails; its downstream tasks becomeupstream_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 acommand/scripttask; 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_failedorall_doneevaluated 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 theProcessResultof a failed command/script (stderr, exit code) are stored and shown. They are not available to other tasks as inputs.Process outcomes for
command/scripttasks: an enum (Python tasks have outcomes too: see Task results and outcomes). The user declares anIntEnumsubclass ofschedr.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 memberSUCCESS = 0) whenoutcomesisn’t given: 0 is success, everything else is a failure.A custom enum replaces the default entirely;
0is 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 becomesupstream_failedif any upstream task failed. Without skipped upstream tasks this is exactly Airflow’sall_success; after a branch, joins work with nothing to configure.AllSucceeded(opt-in:@task(run_if=RunIf.ALL_SUCCEEDED), also on operators, groups and inStepDefaults; enumRunIf { NONE_FAILED, ALL_SUCCEEDED }, defaultNONE_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_failedwithout waiting for the others; forAllSucceeded, a skip decides once no other edge can still fail (a failure wins).Upstream tasks…
NoneFailedAllSucceededall succeeded
runs
runs
some skipped, the rest succeeded
runs
skipped
all skipped
skipped
skipped
any failed
upstream_failedupstream_failedData from a skipped upstream task
None(parameter must allowNone)never happens
A
NoneFailedtask taking data from a task that can be skipped (downstream of a branch or outcome) must have a parameter type that allowsNone, or it’s a parse error. AnAllSucceededtask never receivesNonefrom upstream, so it needs noOptional. Order-only dependencies (>>) need nothing.In the native API skips come only from
@branchand.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’sone_success). Its main use, redundant sources (“if A is down, use B”), is an expected problem: the source task returns it as an outcome andNoneFailedjoins 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
failedif anything unexpected went wrong in it, otherwisesuccess. 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_failedno
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
Unavailableno
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_successdecides 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 (cancelledis a final state, so all users are done). The run ends ascancelled, unless an unexpected failure happened in it (including a cleanup failing during the cancel): thenfailed, 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
Eventenum):Event
When
Default
RUN_FAILEDa run ended
failed(see Run result); includes cleanup failures, named in the messageyes
TASK_FAILEDa task failed after its last retry (earlier than
RUN_FAILED; Airflow’semail_on_failure)opt-in
TASK_RETRYan attempt failed and will be retried (Airflow’s
email_on_retry; noisy)opt-in
RUN_CANCELLEDa run was cancelled by a user
opt-in
RUN_SUCCEEDEDa run ended
success(“the report is ready”)opt-in
RUN_RECOVEREDa run succeeded after the DAG’s previous run failed (“it’s fixed”)
opt-in
TRIGGER_FAILINGthe DAG’s trigger raised
[triggers] failing_aftertimes 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 redopt-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;Eventis 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
EmailChannelholding 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
NameErrorat 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 inlineEmail("a@x.com")innotify=(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.regionis 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 earlierschedr.templates.runplaceholder.)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 asSCHEDR_*environment variables, see Plain script delivery).Values at run time: while the runner calls a task’s function,
dag_ctxgives the values (planned_for/sinceas awaredatetimes 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.tomljobs:[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 |
manual, 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 |
|
t-strings (commands, script |
a reference, rendered by the agent |
|
Python task code (also cleanups, resource setups) |
read at run time, decoded strictly into the dataclass passed |
|
scripts and commands (incl. |
|
|
plain Python scripts |
|
|
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.xis 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
datestays adate).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
@branchdecides); 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
jsonschemacrate (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 astitle,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
Paramcomes 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
paramsholds the class’s type descriptor, a standard JSON Schema of it (a dataclass’s written by schedr: dates asformat: date/date-time, atimedeltaas ISO 8601 duration text (the master checks it as it stores it), a tuple asprefixItems; 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 withoutparamstakes none (-prefused).
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 anintfield, stored as1: JSON Schema’sintegertakes it, so refusing it after that check was inconsistent. Not chosen: refused.141. The master checks
format: durationitself, as ISO 8601 (fractions of a second included:PT1H0.5S, as Pydantic writes atimedelta); thejsonschemacrate’s own is RFC 3339’s, without fractions, and refused such a model’s defaults. Not chosen: droppingformat: durationfrom 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}) getsparams: 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 aLiteral’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 meaningNone(ambiguous forstr | 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
--paramstakes); 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 (rows10 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 |
|---|---|
|
the JSON Schema ( |
|
|
|
|
|
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:
Time: every run has
dag_ctx.run.planned_for, the moment the run is for (renamed fromscheduled_at, which promised a schedule a manual run doesn’t have; notplanned_at:*_atnames say when something happened, liketriggered_at, so it would read as the time the run was planned), anddag_ctx.run.since; the run covers(since, planned_for]. Both are always set (neverNone), 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_forsinceplanned_foris a fire time: scheduled, backfill,trigger --for <fire time>the fire time
the previous fire time of the schedule
plain
triggerthe trigger time
the
planned_forof the nearest earlier run of any kindtrigger --for <other time>that time
the
planned_forof the nearest earlier run of any kindDAG without a schedule (only manual runs)
the trigger time or
--forthe
planned_forof the nearest earlier runOne 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
--forre-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_runsreached) 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=Trueon 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 besidescatchup=True/False; windows would depend on which runs exist, so a backfill or--forrun couldn’t get one clean period).Failed runs still count:
sincedoesn’t depend on how other runs ended (a failed day stays failed until re-run with--foror a backfill). Not chosen: “since the last successful run” (windows would depend on other runs’ results and timing).First run: on a
Cron/Everyschedule the rule above already gives one ordinary period (the cron has a previous fire time even beforestart). A DAG can setinitial_since=(a datetime) for the run on its first fire time at or afterstart, e.g. to load history on the first run. A DAG without a schedule (its first run) or with aOnceschedule (no previous fire time) whose references usesincemust setinitial_since(a parse error otherwise). Not chosen:-inf(no such datetime in Python;datetime.minbreaks many systems, e.g. MySQL’sDATETIMEstarts at year 1000;Nonewould bringOptionalinto 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 noinitial_sincegets an empty window (since=planned_for); the Python API makes that a parse error when a task usessince(“set initial_since=”). A manual run not on a fire time with no earlier run usesinitial_since, else the previous fire time, else an empty window.A manual run is stored
queuedand 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:triggeredfor runs of another DAG andsensedfor 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 indag_ctx: a task using it would behave differently on a re-run of the same day. It differs fromplanned_forfor missed runs, catchup, re-runs and backfills.Parameters from
-p/--params/ the UI form.Airflow’s
ds/logical_date/data_interval_endtranslate ontoplanned_for,data_interval_startontosince. Scripts getSCHEDR_PLANNED_FORandSCHEDR_SINCE.--for(option ofschedr runs trigger, and a field in the UI’s trigger form) setsplanned_for; without it the run is for now.--forin the future is rejected (”--formust 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(...), orstart/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/enddon’t limit manual runs. They are data of the scheduled runs: the check is made by the run’s kind, only forkind = scheduled. A manual trigger or a backfill may be for any time, beforestartor afterend, by design: a person chose that date (e.g. backfilling December for a DAG deployed in January, without movingstart, which withcatchup=Truewould make the scheduler create those runs itself). Fire times beforestartare 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--foris 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
--forrun for a fire time missed while the master was down: the scheduler still creates its own run). Uniqueness: (DAG,planned_for) is unique forkind = 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).
Backfill:
schedr runs backfill report --from … --to … [-p …]: one run (kindbackfill) per fire time in the range, each liketrigger --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”);--allfor 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/--toinclusive, time zone as for--for(UTC without an offset, with a warning);--tooptional, 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/enddon’t limit it (point 1).Order: oldest first, at most
max_active_runsat a time (competition with scheduled runs: point 3).Parameters: the
-p/--paramsvalues 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}/backfillsanswers 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-runcounts 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).
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 andcatchupdecides; a person’s request doesn’t recur). Several runs with the sameplanned_forare allowed.Run state
queued, next torunning,success,failed,cancelled, with the reason in the UI (“waiting:max_active_runs(1) reached”). Cancelling a queued run ends it ascancelledwithout starting any task.Who gets a freed place: by kind, then oldest first within each kind: scheduled (a missed fire time, per the
catchuprules) → 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, changemax_active_runsin the DAG.With
max_active_runs=Nonenothing waits: every manual and backfill run starts at once (a 365-day backfill starts 365 runs, limited only bymax_active_tasks, worker slots and queues; documented).
Identity: an opaque, globally unique, time-ordered run ID, a UUIDv7 (RFC 9562; Postgres stores it natively as
uuid), asdag_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 forchained,triggerforeventruns, 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 sameplanned_forare told apart by kind andtriggered_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:00lists 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_triggereddoesn’t exist, Assets being out of scope).
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=Falsegives the most recent one a run,catchup=Truegives 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 withcatchup=True: “unpausing will create 290 runs”). Not chosen: skipping them for good (would breakcatchup=True’s “every period runs”).Manual runs and backfills of a paused DAG run normally, with a confirmation in the UI (”
sync_ordersis paused; run anyway?”): pausing limits the scheduler, asstart/enddo. 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’splanned_for(same day),sinceby the usual rules for the target’s schedule (see Runs: manual runs, backfill and pausing). It counts towards the target’smax_active_runsand waits asqueuedwith the priority of manual runs; it runs even if the target is paused (like a manual run).paramsmay 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 staysrunninguntil 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 formax_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=Falsethe 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
RunOfnode gives, withwait=Trueor not; the target’s output is read with@sensor(wait_for=RunOf(...))or the API. Not chosen: aRunResult[T](richer than the node, so the two would differ; I first misdescribed it as the node’s).A failed target (359): as the
RunOfnode,Failedis an outcome where the DAG routes it (.on(Failed)), otherwise the task fails and the run goes red; a cancelled (or skipped) target counts asFailed, its state in it. Replaces “fails if it failed or was cancelled”. Not chosen: always a task failure.max_wait=(360): past it, aTimedOutoutcome, 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, sotimeoutdoesn’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’slogical_datemaps 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, whichRunOfruns don’t have (Claude’s, noted for later).
Airflow:
TriggerDagRunOperator:trigger_dag_id→dag,conf→params,logical_date→planned_forof the new run,wait_for_completion→wait(Airflow’s defaultFalseis set explicitly);reset_dag_run=Trueis an error (no “clear”); non-defaultallowed_states/failed_statesare an error;poke_intervalis 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, theFinishedmessage and storage, whatever the task kind. The output may beNone. 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 memberSUCCESS) for ordinary return types,emptytasks and commands withoutoutcomes=; a declaredOutcomeenum (-> 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
Anygets a plaindict), 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): aTypedDictis a plaindict,boolis a subclass ofint,list[int]andlist[str]are the same class. Any other return type (int,Rows,int | None,int | str,Rows | int) is ordinary data with the single outcomeSUCCESS; to route on such a value, return an outcome instead, or use@branch.Without data: an
Outcomeenum, the same kind as forcommand/scripttasks:def check() -> Check, then.on(Check.CHANGED). The member values (exit codes) are ignored for Python tasks; the output isNoneand 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
Outcomeenum, never both; for “data or nothing”, use an empty dataclass (-> Rows | NoData) orNone.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 |
|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
also |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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@branchtask and the requirement edge added byuses=(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
@branchtaken 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 toX(typeddef on[T](self, kind: type[T]) -> Output[T], so the narrowing is checked statically). Edges whose outcome didn’t happen are not taken..outcomepasses the outcome itself as data (Output[Check]), for enum tasks andcommand/scripttasks.
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 |
|---|---|---|---|---|
|
any outcome |
|
the value, decoded into the member the outcome names |
n/a |
|
any outcome |
— |
nothing (order only) |
n/a |
|
|
|
the |
data rule |
|
|
— |
nothing (order only) |
data rule (no data involved) |
|
|
|
the value |
data rule |
|
|
|
the field of the |
data rule |
|
— |
parse error |
|
— |
|
|
in a t-string |
the rendered value |
data rule ( |
|
any outcome |
|
|
n/a |
|
|
— |
nothing |
data rule (no data involved) |
|
any outcome |
|
the member, e.g. |
n/a |
|
|
|
the |
data rule |
|
|
|
stdout (an error if truncated) |
data rule |
|
any outcome |
|
the member |
n/a |
|
|
|
|
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 underNoneFailedand is skipped underAllSucceeded.A path on an outcome union needs narrowing first:
f.rowsis a parse error,f.on(Rows).rowsis fine (the parse-time path check: a field must exist on the referenced type)..outcomeon a union task is a parse error: its type would be an inventedLiteral["Rows", "Unavailable"], and the value’s class already says it. On a plain task it is alwaysDefaultOutcome.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 isDefaultOutcome(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 namedSUCCESS(membership is checked, not names).
@branch and outcomes.
Outcomes cover “route on what happened” (exactly one outcome per result, routing in the DAG structure);
@branchcovers 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/BranchPythonOperatortranslate 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.branchwould 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))givescheck[i]the output ofprocess[i]when its outcome wasRows; otherwise the edge tocheck[i]isn’t taken andcheck[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))(withxnot mapped) has no single clear meaning (filter the list and lose the alignment with map indexes; replace non-matches withNone; 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
Nonefor skipped instances, in map-index order, so the element type must allowNone(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 isasync: 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.runinside 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 withblocks 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
aprefix,await task_ctx.asecret(...),await task_ctx.asecret_value(...)andawait acleanup_handle(...). The sync calls still work in async code, blocking its loop while they wait. Not chosen: the same name returning something both astrand awaitable (type checkers can’t describe it withoutAny); sync calls only, wrapped by the author inasyncio.to_thread.uvloopwhenever it is installed (decision 316, the user’s, 2026-11-06): an optional speed-up. Async tasks and the watcher host run onuvloopwhenever 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 useasyncio’s own loop, soschedrkeeps no required dependencies. So installinguvloopfor 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);uvloopas a required dependency, the only loop (one loop to test, but the first compiled package every install must take); asyncio for tasks anduvloopfor watchers only (they share the interpreter, and would behave differently).Async connections:
@connectionon anasync defgenerator gives anAsyncConnection, opened withasync with; its@name.checkmay beasync def, andconnections testruns 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’sload(extract())must check, soawait task()is flagged..fngives what the function returns (Nonefor-> None, which isDonein a DAG). Afunctools.wrapsdecorator keeps it: the kind is read through the wrapper..fnis 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 deftask outside a DAG returns the coroutine, toawaitin tests (task_contextandrun_dagrun it); async cleanups and resource setups / cleanups are supported like sync ones; background tasks still running when the main coroutine returns are cancelled, asasyncio.rundoes, 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 theTimedOutoutcome. 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 hastrigger=new_files(...)instead of a time trigger.
Wait step (inside a run) |
Trigger (starts runs) |
|
|---|---|---|
Full control |
|
|
Poke |
|
|
Used as |
a task in the graph |
|
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 (
sensorin DAG JSON, next topython,command,empty, withmode: 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_YETmarker (so a legitimateNoneis never “not yet”); the output type is the return annotation withoutNotYet. schedr calls it everyevery, each call limited toevery(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 intoNOT_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 itseveryis 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 asNOT_YET(it looks like a normal wait untilTimedOut); a separatecall_timeout=(one more option to explain).max_wait: a wait step that hasn’t finished within itsmax_wait(or[sensors] default_timeout, 24 h) ends with theTimedOutoutcome, 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=6hmeans the run waits at most about 6 h, whatever happens to workers. Not chosen: per attempt, as a task’s (max_wait=6hwith 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 orTimedOut(schedr’s, never written in the function’s return type), so the timeout shows where the value is used.load(file)withpath: stris 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 parameterstr | TimedOutgets either (.on(str, TimedOut)for type checkers, which can’t readWaited[str]as that union). One rule of its own: a plain>>from a wait step means “when it has its value”, sincewait >> processis the commonest use and must not run without the file;.on(str, TimedOut)runs after either. A value orTimedOut, not a failure: a failed wait step’s downstream tasks areupstream_failedas usual. With another upstream task, an edge not taken is as for any.on(...):run_ifdecides. Not chosen: a plain>>on any outcome, as for other tasks (no rule of its own, butwait >> processsilently runs after a timeout); a call reading asTwith plain edges only on a value (shorter, but the timeout is invisible in the code). NamedTimedOut(the user’s): notSensorTimeout(reads wrong on approvals), norNoEvent(an event is what a trigger yields).Options:
@task’s, exceptcleanup=and its settings (a parse error saying to usefinally; 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), andpreload/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 andTimedOuthas no element-wise routing yet. The list a mapped task gets can come from one, or be mapped over one’s value.max_wait, andStepDefaults(decision 325, the user’s, 2026-11-06): a wait step’s limit has its own name, astimeoutmeans “fail if the work runs too long” on a task and “stop waiting, not a failure” here;timeout=on a wait step, andmax_wait=on a task, are errors.TaskDefaultsis renamedStepDefaults, for a DAG’s or group’s steps, tasks and wait steps:retries,queueand the like apply to both,timeoutto tasks,max_waitto 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:timeoutfor both (StepDefaults(timeout=5m)would silently cut waits short; not inheriting it was unclear too);TaskDefaultsandSensorDefaultson a shared base (shared settings written twice, and a parameter more onDag, groups); a plainDefaults(“defaults for what?”); a narrowerTaskDefaultsbesideStepDefaults(two ways to setretries).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);datahas a type (Event[T], checked like outputs). The master stores every event in aneventstable, 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 asafterwhenever 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);afteris filled in by schedr.Runs it creates: kind
event;dag_ctx.event.key,.data,.at(references in the DAG body, values at run time, likedag_ctx.run);planned_for= the event’sat, or when the master received it;since= the previous event’splanned_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.pokedoesn’t need it (each call is limited toevery).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 amanualrun, and it never writes toevents(a supplied key there would make the real event a duplicate later). The data is checked as JSON when the command is applied, and againstEvent[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.modulesand onesys.pathfor 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_budgetis 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, laterevent_ackfrom the agent;watcher_messagefrom the host, around what a task’s runner would send,watcher_logandwatcher_cancelledbesides, laterevent,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
awaitwithin 30 s ([watchers] block_limit); one watcher callingtime.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 reportsloop_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 kindblocked_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
lostand 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 (
CancelledErrorat its nextawait), 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
printandloggingare 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 fromdag_ctxandtask_ctx, neverSCHEDR_*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, theirmax_waitandtimeoutrunning 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 isparse_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 endlost, error kindwatcher_host_lost, each using a retry.[watchers] memory_budgetkills 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.pokefinishes 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@sensorstays 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_foundif the task is gone). Not chosen: nothing moves (a poke’s bug fix waits up to itsmax_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@sensortoo (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_threadbelongs 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, hasStepEndedError(aBaseException) raised in its thread withPyThreadState_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: refusingto_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_afterin a row (default 3), new attempts fail at once with error kindswitched_offand 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, nottasks: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. Ato_threadstop 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
lostuses 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
TimedOutby 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_threadcalls 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 stayssuccess, 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_timeoutnot fittingtermination_grace_periodis said once, at the worker’s start, and a task’s owncleanup_timeoutonce 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=andconnections=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 itsstart/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 afterSCHEDR_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’smax_output_size(1 MiB by default), secrets masked by the agent as in an output: what breaks that fails the trigger withevent_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 istrigger_returned, stopped until its version or code changes. At[triggers] max_queued_eventsqueued event runs (0: no limit) it is stopped and starts again once none is queued.restart_if_idlestops 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_aftermakes itfailinginmaster_triggers, and forTRIGGER_FAILINGonce notifications exist (none are built yet; theirEventenum will need another name,Eventis 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-ontakes a trigger’s function too, assensors switched-offlists it. A manual run bringsevent(a stored key) orevent_keyandevent_data(--event,--event-key,--event-data,dags testlikewise), amanualrun that never writes toevents. For tests,run_trigger(new_files(...), after=None, take=3, timeout=)in the process, andtask_context(event=).[retention] eventscomes 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_reportis a node the master ends, as it doesempty: 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_failedwhen 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 bodyreport(first_of(a.on(str), b.on(str)))passes the value on, andvalue, 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:.valueand.winneron 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 typedWinnerfilled in by itself, hidden wiring).at_least(n, a, b, c)(the user’s, built on the same count) waits fornand gives the list of values, withwith_winner=Truealso 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 failsoutput_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; amax_output_size=on the node). Refused: fewer than two different tasks, a part of an output, a mapped task, andx >> 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). Withlag, the run whoseplanned_foris this one’s minuslag, and of several such only the newest (bytriggered_at): its result decides, a failed newer run givesFailedthough an older one succeeded (the user’s, 2026-11-07, option C: schedr has no clear, so redoingordersfor a day is a new run for that moment, and areportrerun afterwards must read it; not chosen: A, any success at once, which let a rerun ofreportbuild on the run being redone; B, waiting while any of them runs, then the newest success, which hid a failed redo; re-runningreportby itself whenordersis redone is M4.12’s chained runs, ortrigger=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 nodewait_for(RunOf(...), max_wait=...), which the master ends with no slot and no polling, passing the other run’s ID, orFailedwhen it (or its task) didn’t succeed (skipped and cancelled too), orTimedOut.Failedis an outcome only where the DAG routes it (an edge from the node onFailed); 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)).TimedOutstays 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 aRunResult[T](its run’s ID, DAG,planned_for, state, end, and withtask=its state, outcome and output asT). A sensor returningNOT_YETwaits for the next matching run, untilmax_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 negativelag(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 setsdags.live_sincein 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 thetriggersrow, kept with theRunOfit was made for, so a deleted event row or an earlier trigger’s state never starts a run again; a pass queues no more thanmax_queued_eventsleaves 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.lagis at most 10 years either way, forwait_fortoo, so a planned moment plus it stays a time (Claude’s, after the reviews). ARunOfnaming a DAG or task not loaded says so in the waiting step’s reason (parse warnings aren’t stored); the step waits untilmax_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’sRunResultonce that run ends; a trigger function sees every run that ends (succeeded, failed, cancelled), the no-code form covering successes; it returnsEvent[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; abool; 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.pokecan’t takewait_for=(option A; not chosen: both, a timer and a run calling one function);NOT_YETmeans “not this run”, waiting for a later match untilmax_wait: withlaga 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: noNOT_YETthere). The master holds such a sensor queued, recording on its instance since when it waits (itsmax_waitruns 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;Tis narrowed by the task’s outcome; a retry gets the same run; a run that ended withinmax_waitis handed, its call given at leastSCHEDR_HIDDEN__MASTER__HANDED_CALL_MIN(1 min); the wait starts at the instance’sready_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-inrun_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’sRunResult(masked) the literal value of its first parameter; one call at a time. It returnsEvent[T] | None: the event’s key is the run’s ID unless it gives one, itsatthe run’splanned_forpluslagunless it gives one (lagcan’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 thetriggersrow 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=Npasses a run it raised on after N more tries, the reason kept as its last error; without it,schedr triggers skip <dag>(the API’sPOST .../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 totimeout=(10 minutes by default; the user’s, 2026-11-07, after a side agent saw that a hungawaitheld 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,restartthenskipby 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_retriesandtimeoutare 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 ofmax_wait, hours, so a hungawaitread 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_waitfirst still givesTimedOut. Both forms keep it inwait_for.timeout_ms(the user’s, option A:settings.timeout_msstays the agent’s hard stop of a wait step; not chosen: insideRunOf, 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_sizefails the call (a sensorinputs_too_large, a trigger a failed call thatrun_retriesand 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_sizeto[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 afterfailing_afterfailures, 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) andplanned_for_with_offset=(long), for what islaginsideRunOf;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_ofsit 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 postsPOST /api/v1/events {name, key, data, at}(orschedr events post), and the four forms ofRunOftake it:trigger=EventNamed("order-created")(a run per event), the nodewait_for(EventNamed("approved", key=...)), and@sensor(wait_for=EventNamed(...))/@trigger(wait_for=EventNamed(...))with theEventas the first parameter (option A; not chosen: anevent="name"keyword besidewait_for=RunOf, with no node form; only the no-code forms). A waiting step wakes on an event of its name whose key equals itskey=(nokey=: 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:atdefaults 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 itsIdempotency-Key(after a side agent saw that “stored once” left a rerun waiting for ever). The change stream the UI follows moved fromGET /api/v1/eventstoGET /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 behindmax_active_runskeeps what comes meanwhile; the trigger’s cursor (the last event seen, by when it was posted and its ID) is kept asRunOf’s, of its name, from when the DAG was live, at most what[triggers] max_queued_eventsleaves 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 noFailedoutcome: nothing happened elsewhere); its value is theEvent[Json], its data’s tag-shaped dicts escaped.Jsonreads asAnyin output and parameter types (it heldMapping[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 backSCHEDR_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 asinceafter itsplanned_for(an event for an earlier moment has an empty window); an event’satat 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’smax_waitcounts. 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, wheredag_ctxand outputs are references (not chosen: a per-call form; a reservedkey=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 itsmax_wait,NOT_YETwaiting 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 (nokey=), the event it returns keyed and timed as that event unless it says; what it passed is kept intrigger_passed, read back a minute behind the last, so one stored late is still called for, once;SensorWaitForholdsrun_oforevent, 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;RunOfsince 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 beforereturned_event(only a development build: a released 0.1.0 worker can’t runwait_fortriggers); logged: B185 (a sensor’sNOT_YETcursor has no lookback), B186 (trigger_passednever 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 readsdag_ctx.eventfor 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).delayanduntil: plain wait steps in Python (decision 355, the user’s, 2026-11-08; built in M4.11g): two@sensors schedr ships inschedr.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’splanned_forplus that (adatetimewith 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 itsmax_waitcounts from), the host gives it the step (TaskValues.first_started, not ontask_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 (adatetime); IDsdelayanduntil, numbered from the second on; adelaygiven atimedeltawaits up to that and a minute (max_wait) unless told, as a long delay would otherwise endTimedOutat the default;untilkeeps the usual default; a run parameter can give either; they aren’t inschedr’s top level (untilis a common name); the first try’s start isn’t ontask_ctx. Not chosen: aNonevalue (a downstream task couldn’t say when it was released); the usualmax_waitfordelay(a two-day delay would endTimedOutat 24 h); top-level names (untilclashes);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’sdelayrestarted 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 adatetimeholds (a parameter of millions of days) raised and failed the attempt; now it ends at itsmax_wait, one before year 1 at once. Not fixed: a new worker under a master withoutfirst_started(the upgrade order is master first). Kept for later:by_deadline(a, b, at=...)andfirst_of(..., cancel_rest=True);approval(...)goes to M6 (human in the loop);none_ofdropped (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): oneClient, two transports. Inside a running task or trigger (and a command task’s script, andschedr 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, answeredApiAnswer), and the master runs it through the API’s own router in process, astask:<dag>/<run>/<task>[i]ortrigger:<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:POSTandGET /api/v1/eventsfor now (any event name). The agent resends unanswered calls on a new stream (anIdempotency-Keymakes a resend one event) and gives up after a minute (503: send it again with the same key); an answer over[grpc] max_message_sizeis 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, thehttpextra) toSCHEDR_SERVER, as the CLI; aSchedrApiconnection type (kind = "schedr":server,tokenoruser/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_contextposts to a fake (posted_events);schedr dags testandrun_dagneed 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@triggeror@sensoris the author’s own code and can batch as it sees fit, by yielding one event holding the group, so they take nobatch=. It is the special case of@triggerwhere 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, soafterkeeps its meaning; the window starts at the first item and an empty one starts no run; a batch goes early nearmax_output_size; a restart finds the items again from the bookmark, which a poke that consumes what it reads can’t. A run readsdag_ctx.event.dataaslist[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 atimedelta);tuple[list[T], list[Event]](each item stored twice). Built (Claude’s, as noted above, and):batch_mson the trigger’s sensor task, the host gathering; a batch’s event has noatof 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_idleisn’t checked againstbatch(Codex’s docs round: a poke is never restarted as idle; first built as a check, then removed);schedr.testing.run_triggergives 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’smax_output_sizechecked 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_ifstarts 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,Nonefor “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_threadleft 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 (wrappingThread.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), sodags checksays so: its compiled code is read forsubprocess,os.system,os.fork,os.spawn*,os.exec*,pty,multiprocessing,ProcessPoolExecutor,asyncio.create_subprocess_*,threading.Thread,threading.Timer,ThreadPoolExecutorand_thread, also through the author’s own functions and classes, and using one is aTypeError: the file’s import error. Libraries aren’t read: they may start threads, and so doesasyncio.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 raisesProcessInWaitStepError, a normal failure:subprocess,os.system,os.fork,os.spawn*,os.posix_spawnandmultiprocessingthrough an audit hook, and the loop’s ownsubprocess_execasuvloopisn’t audited;asyncio.to_threadincluded, as it inherits the context. Allowed (Claude’s call, for the user to look at): the standard library’splatform,ctypes.utilanduuidhelpers, 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, missesuvloopand grandchildren, a partial guarantee looking like a whole one). Asyncio tasks a step left running are cancelled and awaited before its end is told, asasyncio.rundoes. 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(...)andasecret_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 witha connection asks for its values the same way. Plaintask_ctx.secretstill works in a coroutine: one declared by name was fetched already, and only one under aSecretPrefixholds the loop.Code:
AssignTaskcarries 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
queuedwith the reason shown.Triggers: queue from
.override(queue=…), else the DAG’s default queue, elsedefault; 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] slotsper 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 kindevent(the trigger’s name, literal arguments, queue,restart_if_idle),dag_ctxfieldsevent_key/event_data/event_at, theEventtype in the type model, theTimedOutoutcome.States and storage: run kind
event; tableseventsandtriggers(instance, worker, state, bookmark, last error, consecutive failures); error kindblocked_event_loop.Protocol:
AssignTaskfor wait steps;AssignTrigger,CancelTrigger,TriggerEvent/TriggerEventAck,TriggerStopped; watcher slots inRegisterandHeartbeat.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 testtakes--event-key/--event-datafor event-triggered DAGs.Airflow layer:
BaseSensorOperator,PythonSensor,@task.sensor,FileSensormap onto@sensor.poke(poke_interval→every,timeout→timeout,soft_fail=True→ theTimedOutoutcome;modeis irrelevant: no slot is held either way); a synchronouspoke()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 plainasynccode.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 (ExternalTaskSensorwithout 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(...)andask(...)are declared in Python and become a task of kindaskin 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,timeoutandTimedOut), 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.pokefor an answer kept in another system (a ticket approved in an issue tracker): sensors cover that already. Not chosen: a@sensorfor 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:
approvea yes or no;ask(answer=...)aLiteralorEnum(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
Rejectedoutcome, not a failure:.on(Rejected)branches on it, plain>>downstream tasks are skipped, as withTimedOut. 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=Truekeeps whoever triggered the run from answering. Not chosen: no narrowing.287. Timeout (A):
timeout=, else[ask] default_timeout(7 days), ending with theTimedOutoutcome. 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 aWAITING_FOR_ANSWERnotification (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):
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).
It never changes the result: a failure stays a failure, the run still fails and notifications are still sent.
It can’t see the failure: no failure status, no routing on it (otherwise it becomes error handling).
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 |
|
setup / teardown, |
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’sdefer; 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 plushandles; the element type follows the outcome-union rules) and at registration (a handle of another type fails the attempt at once).cleanup_handleaccepts 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
exceptblock, against principle 3); an injected, typedCleanup[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 cleanupfor a Python task, the cleanup command for acommand/scripttask), 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
finallyblock: downstream tasks and retries start only then (task instance statecleaning_upmeanwhile). The worker reports the task’s result when its process ends and the cleanup’s inFinished(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_timeoutper task (and inStepDefaults), 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_timeoutamong 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’scleanup_timeoutdoesn’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, |
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
exportfailed”, 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 ascommand), a script for a script job ([jobs.<name>.cleanup]withscript,interpreter,args). It gets the same environment as the task (SCHEDR_*run variables, the task’senv, its declaredsecrets, working directory); its arguments may use t-strings.ScriptOperatorcan override itsargs/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). Nojqneeded, no size limit, nothing in the environment or on disk; works unchanged withcleanup_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, needsjq) or in a JSON Lines file (needsjq, 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
@resourcemarks 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>.cleanupmarks 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 inStepDefaults: 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 isupstream_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 underNoneFailedbecause the setup succeeded. A data edge from the setup (transform(c)) stays an ordinary edge. UnderAllSucceedednothing changes.Typing:
@cluster.cleanuptakes 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=andcleanup_handle(...)on the setup task). Handles are for attempts, setup outputs for resources.Done means every user is in a final state:
success,failedafter 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: thetrystarts only once creation succeeded). It then receives the setup’s output, neverNone, 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 withT | None(putsNonein 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 ofcleanupforResource[..., None]keeps it typed); users declareuses=[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 anemptytask, no process), its value isNone, the cleanup takes no parameter, users declareuses=[tmp]. Use: “once these tasks are done, deletes3://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 declaredvalue=type. The command reports the value withschedr task-ctx resource set(see In-task CLI) over the agent socket; validated againstvalueat 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. Withoutvalue=, the resource has no value (typeNone) and nothing is reported.Users receive the value (
Output[ClusterInfo]), not theProcessResult(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 withschedr 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)andCommandOperator(cleanup=...), withcleanup_timeout,cleanup_retries,cleanup_retry_delay(also inStepDefaults),cleanup_handles=for a command;cleanup_handle(x)andschedr task-ctx cleanup add|list;TaskEndedwhen the process ends, moving the instance tocleaning_up, andFinishedwith the task’s result and the cleanup’s. Small decisions: a cleanup is a task request withcleanupset, 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_contextyields.handles, whatcleanup_handleregistered.
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 inStepDefaults. 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_anywherefails 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 tocleanup_anywhere. Not chosen:not neededwithout handles (a real leak would give a green run).221. A
cleanup_anywherecleanup with no worker to take it waits, shownunschedulable; the task’s retry waits too. Not chosen: giving up aftercleanup_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_anywheregets different data); refusing at registration (a common value likeadminwould 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.
.expandon 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
secretsandconnectionsand may add its own (@cluster.cleanup( secrets=[...]); a staticResource("tmp")has only its own);queuedefaults 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 learnscleaning_upfrom it, and a worker lost during the cleanup leaves the tasksuccesswithdidn't run: worker lost, not run again. Replaces “oneFinishedcarries both”. Not chosen: a bareCleanupStartedwith the result inFinished(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=Falsefor downstream tasks (cleaning_upwould 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 adddoesn’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 forcleanup_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 asunschedulable(how decision 221 is shown). Not chosen: a realunschedulablestate (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 + 1it endsworker_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 toRegister, 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_timeoutdoesn’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_lostand the drain; M4.8b2 handles to the master andcleanup_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:
Continueruns it,Killdrops 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_anywhereending 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
HeartbeatwithHeartbeatAck, 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>.cleanuphas 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. Aresource_instancestable 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 retrynow (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 >> afterwaits for the cleanup of each resource set up ing, by an order edge from the cleanup, unlessafteror anything after it uses that resource: then it keeps the resource alive, and waiting would be a circle. A failed cleanup stopsafterlike any failed upstream task (upstream_failed).@res.cleanup( blocking=False)(defaultTrue) 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 explicitcluster.cleaned >> afterwith 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 andResource(name). It says what decision 267 says, matches the task IDcluster.cleanupand 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/finallyfor 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 afteryieldwith its locals gone);@conn.closeto match resources (state forced through a return value, for nothing).270. A run keeps its
max_active_runsslot until its cleanups end, withblocking=Falsetoo: 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([...])andcluster.cleanup_script(job=...), withblocking=, as decision 268. Not chosen:CommandCleanup(cluster, ...)andScriptCleanup(...)as first designed (two styles for one thing).272. The graph shows what a cleanup holds back: with
blocking=Truethe 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. Withblocking=Falsethey 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
unschedulableuser, up tounschedulable_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 isfailed, with the reason “no worker within 1 h”, what follows it isupstream_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:unschedulablecounting as done (a latertasks retrymeets a deleted resource); the userskipped(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, latercommandorscript); its role comes fromDag.resourcesand is shown as “cleanup ofcluster”. Amends 261. Not chosen: a kindresource_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: aresource_instancestable (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, orfailedif a cleanup fails;schedr tasks cancelrefuses 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 ignoresmax_active_tasks,max_activeandmax_active_per_run(StepDefaultswould hand it limits otherwise);blockingandunschedulable_timeoutare in the DAG JSON’s resource entry.278. A resource’s cleanup without a
timeoutgets[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 itsmax_active_runsslot, 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 shortertimeout=). 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 cancelstops 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 iscleanup_cancelled(what its setup made may be left) and the run endscancelled(failedif 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 endingfailed(a deliberate act read as an error);success(a possible leftover hidden).280. A task without
cleanup_anywheremay 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 onlycleanup_anywheretasks (252); a master that is up marks the cut worker’s attemptslostat 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, acleanup_anywhereone 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, acleanup_anywheretask’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-inexclusive=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_anywheretask) 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: aRegisteredolder 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 aRegistersees 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
Finishedin the journal of itsRegisteris answeredContinue, notKill, 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
/readyzwith 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 whoseRegisterwaited 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
Registersays 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
lostresult 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_RESTwithcleanup_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’sok, tries and time add up; the instance’s cleanup result takes a failed orokrest (a failure fails the run if it is still open; an ended run becomes a yellowSUCCESS, decision 309). An attempt still open combines its end with the rest added. The rest’sCleanupResultsays 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 endedSUCCESSand 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 turnedfailed(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_RESTwithcleanup_from,CleanupResult.rest, a waiting move given back (take_back_cleanup),cleanup_origin,rest_cleanedand the merge of a rest into the attempt’s cleanup (failedandworker_lostwin); the run’slate_failure(API, UI in yellow, CLI) andschedr_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 andworker_lostoverwritten: 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 nightlystress.ymlruns 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.pyis 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’sFinishedof a cleanup waiting to move was answeredKill(282); a master paused while aRegisterwaited 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 asRootKind::Script; a name shared with a DAG root a startup error (299). Their parse jobs read everyschedr.tomlin 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) anInvalidScriptConfigimport 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. Thescripttask kind is in the model; workers reject it until M4.9b.schedr dags checkreads aschedr.tomlor 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 withoutschedr.tomlimported by the check, a DAG root with a strayschedr.tomlnot checked, a linkedschedr.tomlor 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
scripttask kind runs: the job’s interpreter ([interpreters]) on the script, made absolute, from its script root’s copy, args rendered one argument each,PYTHONPATHthe 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 checklooking it up inSCHEDR_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 markedscript: B167), a worker lacking one withdraws the DAG root (an emptyCodeVersionChanged, 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_handlesand[jobs.<name>.cleanup]inschedr.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 onScriptOperator. 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. Onlynotifyis still not available.Built (M4.9d; decision 305): the real executor parses only the
.pyfiles holding the bytesschedr(scan::mentions_schedr, in the copy being parsed), and starts no runner for a root with none;schedr dags checkthe same, naming what it skips.Built (M4.8c1; decisions 259-269):
@resource,Resource(name),@res.cleanup,uses=on tasks, operators and groups, therequirementedge kind andDag.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>.cleanupfrom 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 (unschedulableisn’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), andschedr tasks cancelrefuses one. Ready cleanups come first and no concurrency limit holds them. Each dispatch round fails a userunschedulablepast its resources’ shortestunschedulable_timeout(an index onunschedulableinstances).ResourceState::ofderives 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 endedsuccess(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 againstDag.resources(a command setup must be aCommandResource, its value noProcessResult). 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):setchecks it against the declared type withparams::to_stored(no coercion; a Pydantic model’s value isn’t checked in Rust), masks it, and takes it once;getworks only in a resource’s command cleanup and prints the value as--paramstakes it. A setup exiting 0 without a value fails,resource_not_reported. Small decisions (Claude’s, to be overruled):.valueon an@resourcesetup and aCommandResourceis the value as a reference typed as the value, resolved when the DAG sets the resource up (a module-level@resourcehas no task ID before), so a command cleanup writest"{cluster.value.cluster_id}"; aCommandResourcealso takest"{cluster.cluster_id}"as planned.run_daggives aCommandResourcesetup’s output as JSON (its class isn’t recorded). With this every CLI command works: the “milestone” test of the last one went. ScriptResource andcleanup_scriptmoved 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 owncleanup=no longer took the setup’s role (it failed as “not reported”); in a union a model orAnyis tried last (it took a tuple untagged);resource set --jsontakes 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 whatresource getcan answer (about 1 MiB stored);resource getreadsnull(an optional value, or none); dates and times only in Python’s years 0001-9999 (also for run parameters);CommandResourceoverloads, so mypy takesCommandResource[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 itscleanupresult, and a run itsresources(setup, cleanup, users,blockingand the stateResourceState::ofderives from its two tasks).schedr dags test --jsoncarries them, andrun_daggivesAttempt.cleanup(schedr.testing.Cleanup, its handles as stored),TaskResult.cleanupandRunResult.resources(ResourceResult);task_context’sctx.handleswas there since M4.8a. The UI fills its shells: a task’s status isstate · 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 readsusers) instead of the setup’s own link; withblocking=Truethe edges from the users to what follows the group are left out (the cleanup’s edge says it), withblocking=Falsethe users’ link to the cleanup is dashed. Small decisions (Claude’s, to be overruled): handles stay as stored JSON inrun_dag(decoding them needs the cleanup’s types); a cleanup’sworker_lostreadscleanup lostin the status; a mapped task’s row shows the worst of its instances’ cleanups (failed, thenworker_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), sorun_dagand 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 withblocking=Falsegets its dashed link; the Cleanup tab no longer claims a task without rows has nocleanup=; 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_runsslot, waited for ever.Execution::cancel_taskno longer refuses one (TaskCancel:: ResourceCleanupgone;RunTasks::cancelsalready honoured an instance’s own cancel);ResourceState::CleanupCancelledwhen its setup didn’t fail, elsenot_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 setsAssignTask.resource_cleanup, the agent fillstimeout_msinplan(AttemptSpec:: default_timeout). Codex’s review (1, fixed): the dialog promisedcancelledwhen a task had failed (the run endsfailed).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, beforeStarted) and<attempt_id>.handles(a line each, on disk before the task hears of it) in the journal, and acleaningrecord 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 forContinue: a task that was running islost, its end reported withTaskEnded, one in its cleanup keeps its result, and the cleanup starts over with all its tries and its secrets read again.Killdrops it. An entry staysrunninginRegister: 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 keepsTaskEnded’s result inattempts.task_result; an attempt whose worker is lost, or isn’t reported after a restart, ends with it (elselost), withworker_lostas 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 onContinue) intocleanup_handles: the first at each place stands, up to 1 MiB of bytes per attempt, only from the attempt’s own worker. Withcleanup_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 noStartedcomes 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 withcleanup_anywherecan start on another worker while the task still runs, and the old worker runs it too when the task ends there orKillcancels 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 withcleanup_anywhererunning, at the lease stops them (CutOff,lost) and ends the session, so that the answer to itsRegistersettles 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 keepscleanup_not_beforeon the attempt. ARegisteredolder 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.
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:
Type checker (editing time).
@taskonly 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(notlist/dict, which are invariant) so that e.g.list[int]is accepted;Mapping[str, object](notMapping[str, Json]) because aTypedDictis only aMapping[str, object]to type checkers, so dict values aren’t checked statically (the parse-time check does). Verified withmypy --strict:TypedDicts and dataclasses are accepted;set[int],dict[int, str]andobjectare rejected. Only as good as the user’s tooling, andSequencelets a few wrong types through (e.g.bytes), so it is a help, not the guarantee.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. “taskextract: return typedict[int, str]: output keys must bestr”); the DAG is not registered. The same type model checks inputs: passing anOutput[T]to a parameter whose annotation doesn’t acceptTis 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, ...](uselist[T]), a baretuple, recursive types (a dataclass referring to itself), generictypealiases with parameters,set,bytes,Decimal,objectand other classes. Pydantic models have their own descriptor (M4.1e, decision 59; below).Compatibility of an output with a parameter:
intfitsfloat;booldoesn’t fitint(no coercion, as at run time); containers are checked element by element; a union fits if each member fits; aLiteralfits if each value fits; dataclasses andTypedDicts 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))fortuple[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).
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-strdict 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_serializablewith 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 ofextractnot serializable at[3].created:Decimalis 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 |
|---|---|
|
|
|
|
|
|
|
|
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
TypedDictkey → parse error). Only free-formdict[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=Trueandoutput["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.outputis anOutput[ProcessResult];listing.stdout/listing.stderrare shortcuts for the paths.output.stdout/.output.stderr(Output[str]).A downstream
@taskcan 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/.stderrreferences; a task taking the wholeProcessResulthas opted in and sees the flags instead. Only aProcessResultis checked (a stored object with exactly its five fields): a user’s own dict with adata_truncatedkey is data, itsdataread as any other (B75).No automatic parsing of stdout (JSON, CSV, …): a downstream
@taskparses it and gives it a proper type.In the Airflow layer,
.outputstays the last line of stdout (not aProcessResult), 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/.stderrreference to it gets an error.
A DAG author can raise the limit per task (or in
StepDefaults) withmax_output_size(bytes; constantsKiB,MiBinschedr, 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"(envSCHEDR_CONFIG__OUTPUTS__MAX_SIZE_LIMIT).
max_size_limitabove 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
AssignTaskis 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)givescheck[i]the output ofprocess[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: theschedrpackage 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 pathout.urlis by attribute name, as type checkers read it;by_nameneeds 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_dumpwrites defaults too), a parameter the validation schema (fields with defaults optional). Rust only stores it (TypeDesc::Model; its parts areAnythere); 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:
intintoField(ge=0),strintoHttpUrl); 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 anint). 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 withstrict=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
datetimeand 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 beforemodel_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. Plainstrstill doesn’t fit adatetime(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 fieldAwareDatetime, 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 saysdatetime); 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, butAnyparts 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 annotatedAnygets a plaindict.Supported: plain fields, defaults,
frozen,slots,kw_only, inheritance.field(init=False)andInitVarare 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”).Anyon 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"forintandTrueforintare errors;intforfloatis 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
DataclassInstanceprotocol in theJsonalias makes dataclass return types accepted (verified withmypy --strict); unsupported field types are caught at parse time, not by the type checker.