Architecture¶
Components and roles¶
One Rust binary, five roles:
Role |
Runs |
User code? |
|---|---|---|
|
Scheduling loop, state in Postgres, internal API for workers |
Never. Its image contains no user packages. |
|
Rust agent; starts Python and Bash subprocesses for tasks and parsing |
Yes, in subprocesses |
|
The REST API used by the web UI and the CLI |
Never. |
|
The web UI, over one or more deployments’ webservers (M3, 21B) |
Never. |
|
All of the above in one process (its UI over its own API) |
Yes (local development only) |
Running the roles separately (M2.1):
schedr masterandschedr webserverneed[database] urland a schemaschedr db migratebrought up to date (an outdated one is refused);schedr workerneeds no database, only[worker] master_url(e.g.http://schedr-master:8070, envSCHEDR_CONFIG__WORKER__MASTER_URL). The master listens on[master] bind:grpc_port, the webserver on[webserver] bind:port, both0.0.0.0by default;standalonealways listens on 127.0.0.1. Not chosen: a--masterflag only (the configuration and its env mirror are how everything else is set); separate host and port keys for the worker (one URL carries the scheme, which mTLS will change).Postgres, or SQLite on one host. The roles may share one SQLite file when they run on the same host with a local disk (a VM, Docker Compose, local testing of the role split): SQLite’s file locks work across processes there, WAL lets readers and the writer pass each other, and writes rarely compete (the master writes scheduling state, the webserver only command rows, the worker nothing). Commands are then picked up by polling. The master and the webserver warn at startup on SQLite. Across hosts (a network filesystem, pods on different nodes) SQLite’s locks are unreliable, so anything distributed uses Postgres. Not chosen: Postgres only (rules out a working single-host setup).
Commands at once on Postgres: inserting a command also sends
pg_notifyonschedr_commands; the master listens on a connection of its own and ticks at once (the tick interval starts again after it; notifications that arrived meanwhile are taken by the same tick, so a burst of commands costs one tick). Polling every tick stays the fallback: a notification that fails after the command is stored is only logged (the command is there; failing the request would make a retry store it twice), and when listening fails (the database is down) the master tries again after 30 s.mTLS on the internal links (M2.7), by
[tls] mode(see Master–worker protocol):app(the default) needs[tls] ca,certandkeyon the master, the webserver and every worker, else a startup error naming the key andmode = "mesh";meshsends plain traffic for the mesh to encrypt.[worker] master_urlis checked at startup: anhttps://URL with a host inappmode,http://inmeshmode, else a configuration error rather than a worker retrying forever. Each role’s startup line says which ((mTLS)or(plain: tls modemesh)). The plain-text warning of M2.1 is gone: plain traffic now means a mesh was declared.Sign-in is a mode (M3.5, see Authentication below):
noneby default (the main deployment, behind Istio), where a webserver or UI listening beyond loopback warns at startup to keep it behind an authenticating proxy or mesh, or to bind 127.0.0.1;proxy_headerandbasic, refused at startup where they would be unsafe.SIGTERM or Ctrl-C stops a role (the server stops accepting, the loop ends; a worker drains first, see Worker lifecycle), handled from the role’s first moment. A master whose gRPC server fails ends with the error, instead of running a loop no worker can reach.
standaloneruns the same role functions as the separate commands (one code path).
standalone in one pod (M2.1b), for trying schedr on a cluster before the full
deployment (since 2.10 the chart’s standalone mode, charts/schedr/, replacing M2.1b’s
examples/kubernetes/standalone.yaml; one process runs
every role, a restart restarts master and worker together, tasks share the pod’s memory;
since 2026-10-23 also a production path, below):
schedr standalone --listen <address>opens the REST API beyond loopback (e.g.0.0.0.0behind aClusterIPService), with the no-authentication warning; the master’s gRPC stays on 127.0.0.1 (its worker is in the same process). Without it, standalone listens on 127.0.0.1 as on a laptop. Not chosen: honouring[webserver] bindin standalone (its0.0.0.0default would open every laptop’s standalone).SIGTERM stops standalone cleanly, as it stops the roles.
One standalone per data directory: standalone holds an exclusive
flockon<data_dir>/standalone.lockwhile it runs; a second one on the same data (two pods on one volume during a rolling update, which would schedule every run twice) is refused, saying to run one replica. The manifest uses aStatefulSetwithreplicas: 1. Only lock contention says so; anotherflockfailure (a filesystem without locks) is reported as it is. The lock covers the data directory and the SQLite file in it, the pod case; two standalones given one Postgres URL and different data directories aren’t caught (a developer setup, not the pod).The volume: ReadWriteOnce on block storage; SQLite’s locking (and the
flock) are unreliable on network filesystems (NFS, CephFS, most ReadWriteMany classes). The pod’sfsGroupmakes the mounted volume writable by group 0, which the image’s user is in (a mounted volume replaces the image’s group-writable directory); OpenShift’s SCC sets its ownfsGroup. A data directory that can’t be written says so, namingfsGroup.The image:
python:3.14.8-alpine3.24(Alpine 3.24, the latest; Python 3.14.8, the newest at least two weeks old) with the musllinux wheel; an arbitrary UID in group 0 works (/var/lib/schedrgroup-writable).tiniis PID 1 and reaps orphaned processes (a task’s child outliving it), which schedr, not being an init, doesn’t. A.dockerignorekeeps the build context todist/*.whl. DAG code from a git-sync sidecar (registry.k8s.io/git-sync/git-sync:v4.7.1) into a sharedemptyDir, the root renamed in[dags.roots](git-sync’s link is calledcurrent). Probes use the ops port (8090):/readyzand/healthz(2.9).Checked by hand with podman (the image as UID 54321 in group 0 on a volume: the example DAG runs through the CLI, a second container on the volume is refused, SIGTERM stops it in 2 s with exit code 0, the runs survive a restart), and in CI by the musllinux wheel’s smoke test on the same Alpine image.
Production path (decided 2026-10-23, step 2.10): standalone in one pod first, then the
full split. Production starts with standalone in one pod, first on SQLite (a test:
its state on the pod’s volume), then on Postgres (the real persistence), and moves to
the separate roles only if the load needs it. Its trade-offs are stated rather than
blockers: a restart restarts every role (an upgrade drains, termination_grace_period),
tasks share the pod’s memory (the watchdog’s budgets, below), and the REST API has no
authentication until M3 (a ClusterIP Service behind Istio or an authenticating proxy).
Works through any connection pooler (decided 2026-10-23; the user wants PgBouncer supported without knowing its mode): schedr uses no session state on Postgres, so a direct connection, PgBouncer in session pooling and in transaction pooling all behave the same. Not chosen: detecting the pool mode at start and adapting (two behaviours to keep right); requiring session pooling or a direct connection (production’s setup isn’t known).
One master per database: a lease row,
master_lease(holder: the master’s incarnation; a takeover counter; an expiry by the database’s clock), taken with oneINSERT … ON CONFLICT … WHERE expired OR mineand renewed every 10 s for 30 s (since the 2.10 review; 5 s for 15 s before); a second master waits as a standby, retrying until the lease expires (readiness “starting: master”). A master that can’t renew pauses by itself before its lease could expire (its own monotonic clock), and every write of the master is fenced by the database (below), so two never both change it. The same on SQLite, so standalone’s path is one. The data directory’s lock stays for SQLite’s volume. Not chosen: a session advisory lock (not tied to its master behind transaction pooling; the decision before PgBouncer came up); the advisory lock on a separate direct connection (needs a route production may not offer); a transaction-level lock held in one open transaction (pins a pooled connection, killed byidle_in_transaction_session_timeout); a Kubernetes Lease (API access, Kubernetes only, doesn’t stop two environments on one database); relying onreplicas: 1(one mistake means every run twice). After a crash a standby takes over within 15 s, not at once: irrelevant for one pod.Query time limit enforced by schedr, around every query in
schedr-db’s common path ([database] query_timeout, 10 s since the 2.10 review, 30 s before), replacing 2.9’sSET statement_timeouton each connection (in transaction pooling it lands on a connection other clients then get): a query over it is a database error, which a round survives since B7. Each write runs in a transaction whose statements Postgres limits too (set_config('statement_timeout', …, true): this transaction only, so pooler-safe), so a statement cut off stops there; the whole transaction gets a few limits (2; 6 for a parse’s files and a code version’s DAG changes). Reads are cut off by schedr only; a server-sidestatement_timeout(by the DBA) stops them in Postgres too. On SQLite,busy_timeoutlimits each wait for a lock; a statement cut off runs on in sqlx’s thread until it ends (sqlite3_interruptwould needunsafe).sqlx’s statement cache off on Postgres: queries use unnamed statements, which every pooler and version passes; Postgres plans each query again (small, simple queries).
Commands: polling is the guarantee (every round, 1 s);
LISTENstays a speed-up that may do nothing behind transaction pooling.A finished task wakes a round (decisions 42B and 43A, the user’s, 2026-10-28): a worker’s
Finished, once recorded, wakes the master’s loop (aNotify: a burst of them is one wake), which runs a round at once, so its downstream tasks are dispatched instead of up to[master] tick_intervallater on each step of a chain; at least 50 ms after the last round (ROUND_GAP, a constant: nothing for an idle master, at most 20 rounds a second under a stream of finishes, each taking what arrived meanwhile), so the lease’s renewals and the workers’ messages keep their turns, and the database its idle load. OnlyFinished: a new worker’s registration waits for the next tick (rare, and more code). Not chosen: no gap (A: rounds back to back under load, the risk to the lease’s renewals unmeasured), a lowertick_intervalinstead (C: every idle round costs too). Checked with stress scenarios 1 and 9, before and after.Migrations run by the lease holder, with sqlx’s own migration lock (a session advisory lock) off:
schedr db migratetakes the lease (refused while a master or another migration holds it;--waitwaits for it), andschedr standalonemigrates only with--migrate(a laptop); without it a schema not up to date is refused. The chart migrates in an init container (schedr db migrate --wait), so an upgrade migrates once, as a step of its own, and waits out a dead master’s lease (changed after the 2.10 review: standalone migrated at start; the CLI took sqlx’s lock, so the two didn’t see each other). Not chosen: migrating by default with--no-migrateto turn it off (production would still migrate on start unless someone remembers the flag); never migrating in standalone (a laptop always needs two commands).SQLite to Postgres: start fresh (phase 1 is a test; DAGs are parsed again, only run history stays behind in the SQLite file). Not chosen: a
schedr db copy(every table copied with its types, kept right as the schema changes).To the separate roles: a full switch, standalone replaced by
schedr master,webserverandworkeron the same Postgres, so the history stays; a short downtime is acceptable. Not chosen: standalone accepting extra worker pods (its gRPC beyond localhost with[tls]) for a gradual move.Memory reserve:
[worker] memory_reserve, the part of the pod’s limit not given to task budgets: 10 % forschedr worker, 25 % for standalone (whose process also runs the master and the API), default measured in 2.10 (process_resident_memory_bytes, idle and busy); budget = (limit − reserve) ÷ slots unlessmemory_budgetis set. Too small, and tasks under their budgets together exceed the limit: the kernel kills the whole pod (every tasklost, retries used); too large, and tasks are killed earlier than needed. Not chosen: keeping 10 % and requiringmemory_budget(a forgotten setting means the whole pod killed); a reserve following schedr’s measured memory (budgets changing while tasks run).How it is built (M2.10), decided before coding:
Losing the lease (no renewal in time: a database outage, a split): the master pauses (no rounds, worker messages wait in their queues); the same lease regained, it resumes; the takeover counter moved on (another master took over), its view is stale and it exits (restarted, it is a standby). Not chosen: always exiting (in standalone a few seconds of database trouble would kill every running task).
A standby standalone: the master part waits for the lease (
/readyz“starting: master”), the API serves (commands are stored and applied once it leads), its worker retries its connection. Not chosen: the whole process waiting (the API down meanwhile).[master] lease_period(30 s), renewed every third of it by a task of its own (a long round doesn’t hold renewals up); the master leads until the period less one query limit after a renewal began (a query begun while leading ends before the lease can expire); at least three[database] query_timeouts (a renewal fits a third) and shorter than[ops] loop_stall_timeout, else a startup error. Defaults 10 s / 30 s (option A after the review): a standby takes over within 30 s of a crash. Not chosen: 30 s / 90 s (a takeover up to 90 s); fixed constants.Lease unit tests (B21, 2026-10-26): a 2 s query limit, long enough that a loaded machine still finishes one statement, and a period of three limits. A renewal still leads for the period less that limit; a stall past the limit is a failed renewal and does not move the lead. The service tests that drive the lease (pause, takeover, giving it up, a long round) use that same limit and ratio. Not chosen: the old 100 ms limit, and those service tests’ 200 ms limit (they returned
QueryTimeoutunder load); subtracting 100 ms while enforcing a longer timeout (the test would stop leading before a real query must).The query limit: one timeout around every query in
schedr-db’s common path,DbError::QueryTimeout; SQLite’sbusy_timeoutstays (a file setting, not session state). Not chosen: a timeout per master round (which query was slow is lost).[worker] memory_reserve: a percentage ("25%", at most 90 %) or a size ("1GiB"); unset, 10 % forschedr workerand 25 % for standalone. A reserve leaving less than 16 MiB per task is a startup error. Measured (a release build, standalone with two example DAGs): schedr’s own process 19.6 MiB idle, 23.8 MiB at its peak during 12 runs; 25 % of even a 512 MiB pod (128 MiB) covers that and the parse runner (outside the slots), so the default stays. Not chosen: a percentage only.The image: Alpine (
python:3.14.8-alpine3.24, the musllinux wheel), for security (a smaller system: fewer packages to patch), the user’s choice. DAG libraries: pip takesmusllinuxwheels where they exist (numpy, pandas and most drivers have them); for the rest the users’ Dockerfile builds in two stages, a builder (the same Alpine withbuild-baseand the-devpackages) runningpip wheel -r requirements.txt, and the final image installing only those wheels and their runtime libraries (apk), with no compiler in it. A library that can’t build on musl shows when the image is built. Not chosen: Debian slim (glibc, every manylinux wheel, but a larger system).Images: a
schedrbase image (images/schedr/Dockerfile,make image: the binary, Python, the package,tini, a group-0-writable data directory; 108 MB); users writeFROM schedr:<version>and add their libraries (examples/kubernetes/Dockerfile, two stages; checked:pyyamlcompiled in the builder, imported in the final image, no compiler in it). CI builds it and smoke-tests it (scripts/smoke-image.sh: an arbitrary UID in group 0, ready, leading, the CLI answering, SIGTERM stopping it with exit 0); pushing to a registry comes with releases. Not chosen: installing libraries when the pod starts.The chart:
charts/schedr/(checked bymake chart-checkand CI’schartjob:helm lint,helm templatewith its main combinations of values; Helm 4.3.0 in CI),mode: standalone(distributedin 2.11): the image,database.existingSecret(a Postgres URL; without it SQLite on the volume),persistence(ReadWriteOnce),resources,terminationGracePeriodSecondsmirrored into[worker] termination_grace_period, an optional git-sync sidecar, an optionalServiceMonitor, extraSCHEDR_CONFIG__*variables; one replica (StatefulSet), probes on the ops port, no fixedrunAsUser(OpenShift), Service ports named for Istio. Not chosen: plain manifests.Tests: the lease in unit tests (SQLite) and integration tests (Postgres: a second master waits and takes over; pause and resume across an injected outage); the chart with
helm lintandhelm templateinmake checkand CI, andscripts/kind-standalone.sh(a local kind cluster, an explicit--context, run with the user’s go-ahead) installing it on SQLite and on Postgres and running a DAG.
After the 2.10 code review (2026-10-23):
The database fences the master’s writes (
Database::fenced,in_tx!): each write runs in a transaction that first checks the lease is still the master’s (holder and takeover counter), on PostgresFOR KEY SHARE, which a takeover’sFOR UPDATEwaits for and a renewal (no key change) doesn’t; a write after a takeover isDbError::NotLeading. Reads aren’t fenced. Accepted first was a check by the master’s own clock before each query, with the rule above; while building it, a write the master sends while leading can still reach Postgres after its lease expired (held in a pooler’s queue or the network), which no clock on the master’s side rules out, so the check moved into the database (the clock rule stays, for pausing in time). Cost, measured on a local Postgres in a container (the commit’s flush included in each write): a one-statement write 3.7 ms before, 8.2 ms in a transaction with the statement limit, 12.1 ms fenced; about 4 round trips more per write (begin, the limit, the check, commit), and sqlx’s ping when a pooled connection is taken.A write’s start is one message on Postgres (decided by the user after the measure, option A):
BEGIN, the statement limit and the fence sent together (begin_with; the fence aDOblock reading the lease fromset_config('schedr.holder'/'schedr.epoch', …, true)and raising SQLSTATESR001, read asDbError::NotLeading; values written in asE'…'literals, since a message of several statements takes no parameters), and no ping before each use (test_before_acquire(false): a dead pooled connection fails one query, the next round retries). A connection whose start failed is closed, not given back (it would stay in an aborted transaction: a reproducing test, failing without the close with25P02). A fenced write is one round trip more than before (theCOMMIT). Measured in one run, same machine: one statement 2.7 ms (pinged pool) / 2.6 ms (not); a transaction with the limit 4.9 ms; fenced 6.5 ms; the previous fenced write (separate round trips, pinged) 8.1 ms. The commit’s flush dominates locally (round trips there 0.15-0.3 ms); the fence’s check and row lock cost about 0.3 ms in Postgres (pgbench, within its noise); on a network with a real round trip the saving is three per write. Not chosen: B, the fence inside each statement (WITH … FOR KEY SHARE … WHERE EXISTS, autocommit) with the limit set per role (ALTER ROLE … SET statement_timeout): no extra round trip for one-statement writes, but about 30 statements rewritten, a refusal read as “0 rows” next to genuine no-ops, an install step, one limit for every write (a possible later addition for the hottest writes); C, one transaction per round step: fewer round trips in rounds, none saved on worker messages (the busiest path), a step all or nothing, messages only after its commit (reworking B7’s delivery), the lease row and, on SQLite, the write lock held for a whole step; D, triggers refusing a write of an old takeover counter: no extra round trip and enforced by the database for every path, but a counter column on every table and every statement, deletes needing a transaction setting anyway, tables written by the API too (commands) needing an exception, a check per row, and triggers in two dialects; E, leaving it.A renewal extends only the master’s own lease (
renew_lease: holder and takeover counter), never taking it back after a takeover (a dead holder would block every master for a period); a takeover on Postgres locks the row first. Every lease statement is limited by the query limit;Leadership::takeretries everything (the table too) andtry_takeis one try.Standalone ends when its master fails (taken over, or failing at start): the worker gets two stop requests (its tasks interrupted at once: no master to report to), the API stops after it, and the process exits 1; restarted, it waits as a standby.
The chart’s
fsGroup: 0 unless set, except on OpenShift (found bysecurity.openshift.io/v1), which assigns its own and refuses 0. Not chosen: anopenshiftvalue (one more thing to set right).Left:
0001edited in place (allowed before the first release).
Found by the stress suite (2.10b, 2026-10-24):
A task’s start counts when its
Startedarrives (B11): under load (stress scenario 13: 624 assignments expired for 11 successes) the master handledStartedafter the 10 s start timeout, though every one of the expired tasks had started on its worker; each expiry assigned the task again and added writes, a feedback loop. Now each stream’s reader notes theStartedandFinishedit reads (Arrivals::start_arrived), and a round doesn’t take back an attempt whose start arrived and waits to be handled. Also: a task’s inputs (FetchInputs, for inputs over 4 MiB) are read from the database without the master’s lock (dispatch::attempt_inputs).A worker’s queued messages are handled together (B12): up to
MESSAGES_PER_TURN(10) in one turn of the master’s lock, the rest in its next turn; one message per turn left a worker’s messages behind every round in between (1 task a second in scenario 13). Each task sends 2 (Started,Finished): 10 is about a round’s worth for a worker of 4 slots and short tasks, and still allows far more than the master’s writes can take. A count, not a time budget: deterministic and the same on any machine. Not chosen: no cap (a long queue holds rounds and the other workers up); a larger one (helps only a worker with many slots, at everyone else’s cost).A scheduler round reads every DAG’s runs at once (B12):
Database::run_overview(running counts, latest scheduled times, queued runs: three queries,GROUP BY dag_id) instead of three queries per DAG, so a round no longer costs round trips in proportion to the number of DAGs: with a few hundred idle DAGs it would have filled the master’s time with nothing to do. The master is the only writer of runs, so the round works from the overview until it ends. A manual trigger keeps its per-DAG queries (one DAG, rarely).DAG definitions cached by version (B13, decided 2026-10-24): a version never changes once stored, so
Database::dag_versionreads and parses each once and shares it (Arc<Dag>) with every clone of the database; the dispatcher’s ready tasks, the active DAGs, a run’s tasks and new runs carry the version and take the definition from the cache. Before, each ready task’s row brought its run’s whole DAG definition, parsed per row: a 400-task DAG cost tens of MB per round (scenario 1 never finished). Bounded: cleared at 4,096 versions (the current ones come back at once).Several writes, one transaction:
Database::atomically(decided 2026-10-24): runs a piece of work with every query of that database, reads too, through one transaction (begun with the statement limit and the fence once, committed at the end, rolled back on an error; SQLiteBEGIN IMMEDIATE). The transaction is found through a task-local, so only the work’s own future uses it, never another task on the same database (the lease’s renewals, gauge refreshes, input fetches); work inside work joins it. The query macros take their connection from it when there is one. A statement inside it that fails or is cut off voids the transaction even if the work handles the error and goes on (DbError::TransactionFailed, rolled back): on Postgres it is aborted anyway, and itsCOMMITwould roll back without an error (code review). Not chosen: a transaction slot shared by the database’s clones (it would catch those other tasks).T1: a worker message’s writes are one transaction (
Started,Rejected,Finished,CodeVersionChanged; heartbeats write at most once): stored whole or not at all, one lease check and one commit per message instead of one per write. Before, a failure partway left part stored (B7’s rules then repaired it).T1b (planned, M4B): a turn of messages is one transaction (decision 54, the user’s, 2026-10-28): a worker’s messages handled in one turn of the core lock share one transaction, each behind a
SAVEPOINTwith its memory snapshot (a failed message is rolled back to its savepoint and its memory restored; the others stay), one commit for the turn. When the commit fails, the turn’s memory is restored and its messages are redone one by one as in T1. Metrics, wakes and replies come after the commit; heartbeats and warnings are written outside it;CodeVersionChanged,DrainingandDeregisterend the batch and are handled alone (PLAN.md, M4B, has the table per message). Not chosen: rolling the whole turn back on any message’s failure and redoing it one by one (a bad message costs N+1 transactions); per-task-ID transactions (a turn’s messages rarely share a task).T2: a round’s assignments are one transaction (
Dispatcher::assign_into): stored together; on a failure the slots they reserved are given back and theirAssignTaskmessages dropped, and the step falls back to one transaction per task (A+B, decided 2026-10-24 after the code review found that one task failing every time stalled every round): a task whose own assignment fails (DbError::is_data_fault: data that won’t read, a statement refused) is set aside forSET_ASIDE(60 s), with a warning, and the others go on; an error that is the database’s (unreachable, a time limit, the lease), or every task failing, fails the step and sets nothing aside. The B7 rule (“messages already built are still sent”) stays for everything else. An idle round’s assignment step opens no transaction. Not chosen: the fallback alone (a task broken for good would make every round take the slow path); setting aside alone (it needs to know which task failed); undoing T2.Not chosen: T3, one transaction for a batch of up to 10 messages (one bad message would roll back nine others; savepoints or retries for the last bit of gain); T4,
synchronous_commit = offfor the master (cheap commits, but a Postgres crash could lose commits the master already acted on, breaking B7’s guarantees).
A stalled write doesn’t block the takeover (B10, found by reasoning, confirmed by scenario 5): a write’s opening message also sets
idle_in_transaction_session_timeoutto the query limit, for that transaction only, so Postgres ends a transaction whose master stalled between statements, and its lock on the lease’s row. Not chosen:transaction_timeout(Postgres 17 only).SQLite writes take the write lock at their start (B14, scenario 9: “database is locked”):
BEGIN IMMEDIATE, waiting for another writer under the busy timeout, where a deferred transaction that read first (the fence) failed at once.Notifications behind a pooler (B16, scenario 6: through PgBouncer in transaction mode the master’s
LISTENsent notifications into other clients’ queries, “unexpected message: NotificationResponse”; decided 2026-10-24):[database] notifications(on by default) and[database] notifications_url(a connection for listening only, straight to Postgres; with a password, from the environment only). With notifications on, the master first checks the connection it would listen through (commands::listening_is_safe): five rounds of reading one connection’s server process (pg_backend_pid()), opening a transaction on a second, and reading the first’s again; a second client on the first one’s process, or the first moved, is a pooler in transaction mode (only a pooler does either; one in session mode or none does neither). Found: a warning saying how to have immediate commands, notifications off, polling (the guarantee since 2.10). The check needs nothing beyond the database’s own user. A database error showing a notification where an answer was expected adds its likely cause (a pooler; the settings). The webserver doesn’t notify with notifications off. The chart:database.notifications,database.notificationsUrlKey. Not chosen: refusing to start behind a pooler (the user: warn and poll instead); a setting alone (a mistake shows as random query failures); detection alone (a missed pooler with no way to override); droppingLISTEN(immediate commands are worth keeping where they work).What the database user needs (the user’s setups give access to their own database only): owning it (the schema in
public, closed to others since Postgres 15), and PL/pgSQL (the fence’sDOblock; allowed to everyone by default). Nothing reads other databases,pg_stat_activityor anything a superuser grants.At most 100 waiting reasons a round (
REASONS_PER_ROUND, B18 in part; the user: “a max batch size”, 100 chosen from measurements): a burst of runs left thousands of tasks waiting and one round wrote 580 reasons (about 2 s); the rest are written in the next rounds (reasons are only shown; the waiting counts in the metrics cover every task). Not chosen: 200 (0.7 s a round), 500 (close to what hurt).From the step’s code review (fixed): a failed statement voids an
atomicallytransaction (above); a start that arrived is forgotten with its worker, or when its message can’t be queued (it protected the attempt from expiry forever); the pooler check timing out counts as a pooler (a pool of one server connection can’t pass it); an idle round’s assignment step opens no transaction;run_overviewreads on one connection; the nightly workflow’s Postgres getsmax_connections = 500and its name filter comes through the environment.Decided after the code review (2026-10-24):
T1 rolled back puts memory back (
Dispatcher::memory/restore): a worker message whose transaction fails leaves the dispatcher’s memory (worker slots, rejections, code missing) as before it; metrics already counted stay. Not chosen: making the changes only after the commit (the user’s first choice): the handlers read their own changes back within a message (Rejectedcounts the refusals it just recorded to decide unschedulable), so it would need each handler split into plan, store, apply, with an overlay of pending changes: a rewrite for the same result.A commit cut off is read back (
DbError::CommitUnknown,DbError::from_commit): aCOMMITpast the time limit or with its connection lost may have stored the work; T2 then checks one of the round’s new attempts (stored together, one is all): there, its messages go; not there, or no answer, they are dropped (a stored one expires afterSTART_TIMEOUT). A commit the database refused stays a rollback. Not chosen: treating it as rolled back (stored assignments unsent, the worker overbooked).A worker leaving gives back what it never started (B17, stress scenario 7):
Dispatcher::worker_lostends started attemptslost(a retry used) and the othersassignment_expiredwith aWorkerLeftsummary (queued again, no retry). Not chosen: a new status (withdrawn: one more everywhere for the same meaning).Per-round caps (B18; the user: cap every batch step), the rest first in the next round, so no round takes seconds: commands 50 (
COMMANDS_PER_ROUND), task instances for new runs 2,000 (INSTANCES_PER_ROUND; a run never split, one always made), due retries 100, assignments 50 (ASSIGNMENTS_PER_ROUND), expiries 50, scheduled runs 10 per DAG (SCHEDULED_PER_ROUND), waiting reasons 100. Sized from the stress measurements to a few hundred milliseconds each. The price: a burst finishes over more rounds. Not chosen: a time budget per round (machine-dependent, harder to test).Similar writes batched (the user’s idea): a new run’s instances in multi-row
INSERTs, a finished task’s downstream changes inUPDATE … FROM (VALUES …), the round’s waiting reasons oneUPDATE … WHERE id IN (…)per reason text: 500 rows a statement (well under both databases’ parameter limits; 200-2,000 would do about the same). A task’s inputs read only the outputs it uses (Database::outputs_of), not its run’s every one. Not chosen now: a round’s assignments as one batch (each message must carry its stored attempt, and the fallback must work per task: possible later, once one master’s throughput is measured); expiries batched (the cap covers them); several messages in one transaction (T3, one bad message would roll back the rest).From the second code review (fixed): a task’s own fault is told from the database’s trouble by the error’s code (
DbError::is_data_fault: on Postgres the SQLSTATE classes 40, 53, 55, 57, 08 and 58, on SQLite busy, locked, I/O, full and can’t open, are the database’s: a statement cancelled at its limit sets no task aside); “every task failed” counts only those that tried, not those waiting for a slot; a task over the round’s assignments counts as waiting (next_round); the assignments counter counts once, after the commit; a task given twice in one batched update ends as its last update, retries added up (as a statement each did); the singleset_queued_reasonis gone.Decided on the second review’s open points (2026-10-24):
D1: T1 reads back too. A worker message whose commit was cut off is read back before memory is put back: stored after all (
Finished: its attempt ended, theFinishedAcksent;Started: started;Rejected: the attempt gone, undone), memory stays as the message left it. Not chosen: leaving it (memory wrong until the worker reconnects).D2: a read-back waits for a slow commit: checked at once, then every
read_back_interval(500 ms) for up toread_back_window(3 s), holding the master’s lock: rounds and worker messages wait that long, only after a commit cut off (a database incident; never seen in the stress runs). Not seen by then: not stored (a stored round’s attempts are taken back after 10 s and run again). Not chosen: one query limit (a 10 s stop); resolving in the background (held messages, a pending state: more than this rare path needs); no wait (a commit merely slow taken as not stored).D3: listening tried again. Starting to listen failing (the pooler check timing out on a slow database, or the database unreachable) polls with a warning saying so, and tries again every
[master] listen_retry(30 min) until it listens or finds a pooler or notifications off. Not chosen: off until a restart.The times configurable (the user):
[master] set_aside(60 s),listen_retry(30 min),read_back_window(3 s),read_back_interval(500 ms). The per-round caps and the messages per turn stay constants (counts, not times).
Quiet DAGs (M2.5, decided 2026-10-24; first called “two scheduling queues”, renamed 2026-10-27 so as not to mix with task queues): built beside the current round, not reworking it. The scheduler’s work for one DAG stays one function (fire times, catch-up,
max_active_runs, starting queued runs); only which DAGs a round visits differs: busy DAGs (runs in progress, or firing often) every round, as now; quiet DAGs only when their timer fires (the next fire time, in memory) or something wakes them (a run ending, a command, a new version, an unpause), like an async executor polling only woken futures. A DAG turns quiet or busy by measurement, with hysteresis; every DAG starts busy after a restart. Changing is safe: everything happens in the round, under the master’s lock, and visiting a DAG twice creates nothing twice (a scheduled run is unique perplanned_for). A safety net also visits the quiet DAGs within an interval (built as a sweep, below): a missed wake costs at most about that interval, never a run that doesn’t start. A comparison test runs one simulated timeline through the full round and the busy / quiet split and requires the same runs. Settings (decided 2026-10-27, all configurable, the user’s):[master] quiet_dag_after(60 s: no run in progress this long, and no fire time due withinquiet_dag_wake_ahead, makes a DAG quiet),quiet_dag_wake_ahead(60 s),quiet_dag_full_pass_interval(60 s); a run starting or queued makes it busy again. A round reads only the DAGs it visits (the active DAGs and the run overview limited to them), or it would still grow with the quiet ones. Not chosen: thresholds as constants; aqueues_prefix (mixes with task queues,@task(queue=...)); ascheduling_prefix; renaming task queues (public API, Airflow’s word). Stress scenario 14 (about 1,000 daily DAGs and a few busy ones) measures it and tunes the classification. Built (M2.5.2, decided 2026-10-27):A switch:
[master] quiet_dags = true(on by default);falsevisits every DAG every round, as before. Not chosen: no switch (no way back short of a release).Wake marks, in memory (a shared set, the first reason in a round kept): a run stored queued, found by the data rather than by its code path: each round reads the DAGs with queued runs (
SELECT DISTINCT dag_id … WHERE state = 'queued', the partial index of unfinished runs), so chained, event and backfill runs (M4) need nothing more (a side note found the first build marked only the manual trigger’s path); a run ended (Execution::finish, every run’s end), a command about a DAG (trigger, pause, unpause), a new version or a DAG back (discovery’s refresh). Run-level commands need none: a cancelled or retried run wakes its DAG when it ends.The safety net is a sweep, not a full pass (the user’s choice, after a side note that one full pass a minute costs today’s round once a minute: over 1 % of rounds, so the p99 wouldn’t move, and the lock held that long): each round also visits a slice of the quiet DAGs, those visited longest ago (ties by ID), its size the share of the quiet DAGs that the time since the last round is of
quiet_dag_full_pass_interval, counted exactly in DAG-milliseconds with the remainder carried (600 DAGs, 1 s rounds: 10 a round; one DAG: once a minute; a burst of rounds sweeps the same per minute). The list is rebuilt every round from memory: a DAG joining it was just visited, so it sorts behind every DAG waiting, and none waits more than about one interval however many join (a test adds 4 a second, 120 to 600). Plus, once per interval, an ID check: one query of every active DAG’s ID and version, without definitions or runs; a DAG memory doesn’t know, or of another version, is visited, and a gone one forgotten. The first round of a leadership term still visits every DAG (memory is empty). Not chosen: one full pass per interval (the p99 stays); a rare full pass (a missed wake costs longer).Busy or quiet: a visit is active when a run is running or queued, or the round created one. A DAG seen active is busy until
quiet_dag_afterafter its last active visit; then quiet unless a fire time is withinquiet_dag_wake_ahead(a paused DAG: quiet without a timer). Its timer is its next fire time (from its start, within its end) lessquiet_dag_wake_ahead. A visit finding a DAG idle, with no fire time near, makes it quiet at once, whatever woke it, a DAG new to memory included (decided 2026-10-27, the user’s, after scenario 14 caught 600 woken DAGs busy for a minute): a master’s start, a deploy changing every DAG or a mass unpause costs one round visiting them, not a minute of such rounds. Not chosen: busy forquiet_dag_afterafter any wake (the first design’s “every DAG starts busy after a restart”).Metrics:
schedr_master_dags{state="busy"|"quiet"}andschedr_master_dag_wakes_total{reason}(timer,command,run_queued,run_ended,new_version,sweep);sweepcounts only a quiet DAG the sweep or the ID check found with something to do: a missed mark, a bug to log.A round reads only the DAGs it visits:
Database::active_dags_ofandrun_overview_of(500 IDs a query),active_dag_versionsfor the check.The comparison test: three simulated hours of rounds every 20 s, seven DAGs (daily, every 5 min, every 90 s, hourly with catch-up,
Once, manual only, unpaused midway), runs ending after 30 s, through both paths: the same runs, with the same times. It also requires timer and mark wakes and nosweepwake; dropping the unpause’s mark fails it.Scenario 14’s floors: the mean round’s ratio at most 2.0 (7.1 before; 1.25 with quiet DAGs on the quick profile), the p99’s at most 1.5. For the latter
schedr_master_tick_duration_seconds’s buckets are √2 apart (29, 1 ms to about 16 s) instead of 2x (15): one bucket worse passes (noise at an edge), two (the 2x a full pass gave) fail (the user’s choice after a side note: with 2x buckets no floor could guard the p99, the reason the sweep was chosen). Not chosen: reporting it only; the master logging each round for the scenario to read. Not chosen: reworking the round into an event-driven one (the user’s preference: a second path beside the proven one, switched by measurement); two separate engines (the per-DAG logic twice, drifting apart). It doesn’t help a few busy DAGs with many short tasks (scenario 13): that is the cost of the master’s writes (see the transaction grouping).
Scaling past one master: a federated web UI over several deployments (the user’s idea, decided 2026-10-24, milestone M3; federated from the start, the user’s decision the same day: the UI is built for a list of deployments, one being the common case, not added later in the milestone). Each deployment is what exists today (a master and its standby, workers, a webserver, a database of its own); one UI talks to several webservers and shows their DAGs, runs and workers together, sending each action to the deployment it concerns. The webserver already serves all the UI needs, workers’ logs included (it fetches them from their log endpoints), so the UI never reaches workers or databases. Write capacity adds up across deployments as it would across masters; a deployment’s master failing is covered by its own standby (2.10); nothing in the scheduler changes. What it doesn’t do: spread load by itself (which deployment runs which DAGs is chosen by hand). To work out in M3: one identity across the webservers (M3’s auth), a deployment down while the others answer (shown unavailable), paging lists merged from several, triggering a DAG of another deployment. Not chosen: several masters on one database (below): the same capacity for a far larger change. Where it lives (decision 21B, 2026-10-27): a role of its own,
schedr ui, that talks only to webservers’ JSON APIs, its own deployment’s included (a list of deployments in its configuration, one the common case); the webserver keeps serving the API. Not chosen: the webserver as the federated UI too, rendering its own deployment from its database and the others through their APIs (two paths to keep alike). To settle in M3.5 / M3.6: each webserver sees the UI, not the person who clicked, so the UI passes the user’s name on, and a webserver must take that name only from a caller proven to be the UI (its mTLS client certificate, which the deployments already issue, or a service token per deployment): otherwise anyone reaching a webserver directly could claim any name in the audit trail. Federations of standalones, in production (the user, 2026-10-28, for M3.6): the UI must take any mix of deployments: standalones on SQLite, standalones on Postgres, distributed ones. The way in production goes from a federation of standalones on SQLite, to standalones on Postgres, to distributed deployments, a deployment at a time, every stage possible and mixed stages too (a deployment moving from SQLite to Postgres starts afresh: its history stays behind, accepted). So: standalone can run without its own UI (schedr standalone --no-ui, the user’s pick over a setting: only its API on that port, one deployment of a centralschedr ui);schedr uideploys alone from the chart, over a list of deployments (standalone or distributed, in other releases or namespaces); a standalone, which has no mTLS, proves the UI’s calls by the shared token whatever[tls] modesays (decision 36’s mTLS port is a distributed webserver’s, inappmode).Not planned: several masters on one database, each with its own workers (the user’s idea, 2026-10-24, first recorded as M6, a number LDAP sign-in has since; superseded the same day by the federated view above, kept as the alternative should one deployment not carry a load that can’t be split by DAG). Today one master leads and a standby waits. The idea: masters share the database, each leading part of the work through leases of its own, with its own flock of workers; a master that dies leaves its part to be taken over by another (with its flock) once its leases expire, as the standby does now. A standalone could run without its webserver, one webserver reaching every master’s workers (simpler in the distributed deployment, where the webserver already reads workers from the registry).
Grain of the lease: one per task would add a lease row and its renewals to every task, about doubling the master’s writes, when writes are the measured limit (B18, scenario 13). One per DAG, or per bucket of DAGs (a hash of the DAG ID), keeps the cost per lease, not per task: a DAG’s runs, tasks and
max_active_runsstay with one master, so most of today’s logic applies within a share unchanged.For: the master’s write capacity adds up across masters (one does about 12-15 tasks a second locally, more on a real Postgres); every master works (no idle standby); a master’s failure stops only its share, for one lease period.
Against, or to work out: everything the master keeps in memory assumes one writer (the worker registry and slots, the dispatcher’s state, parse jobs and code versions): each would be per share or coordinated; which master applies a command (by its DAG’s share; worker commands by the worker’s master); a DAG’s tasks run only on its master’s workers, unless masters lend slots to each other; anything across DAGs (
TriggerDagOperator, chained runs) crosses shares; shares moving when masters come and go (gradually, lease by lease); the fence per share (holder and takeover counter per lease); the webserver reaching every flock’s log endpoints; and a much larger test surface (the stress suite with several masters, takeovers of part of the work).To decide it: first measure one master’s ceiling on a real Postgres with B18’s remaining parts fixed (fewer writes a task: instances in one statement, outputs read by task, batched messages). If one master meets the expected load, this stays on paper; if not, sharding by DAG is the way, and a design step of its own.
Possible later (one master’s throughput, measured first): a round’s assignments as one batch (all the attempts in one
INSERT, the tasks in oneUPDATE, the messages built from what was stored), about three statements a round instead of three an assignment.
No SQLite backup tool: SQLite is the test phase; real persistence is Postgres. Not chosen:
schedr db backup(SQLite’s online backup) for a phase that doesn’t need it.
Standalone inside an Istio mesh (step 2.11a, decided 2026-10-24). The user deploys
standalone first (the production path above), into an existing namespace that is part of
the mesh (outboundTrafficPolicy: REGISTRY_ONLY), whose ServiceAccount is reused (the user
may create a namespace but probably not a ServiceAccount). Distributed (2.11) follows, with
the same values. Without the mesh’s objects nothing reaches schedr there; leaving schedr out
of the mesh would defeat the point.
serviceAccount:create: trueby default (one holding no permissions);create: falsewith anameruns every pod as an existing account;automountToken: false(schedr never calls the Kubernetes API). Per-role names come with distributed. Not chosen:create: falseby default (a plain install on a fresh namespace would fail).istio, each object optional and off by default:enabled(the sidecar label for Istio and annotation for OpenShift Service Mesh 2;proxy.istio.io/configwithholdApplicationUntilProxyStartsandEXIT_ON_ZERO_ACTIVE_CONNECTIONS); avirtualServiceon an existing Gateway (the chart creates no Gateway); arequestAuthentication(issuer,jwksUrior inlinejwks); anauthorizationPolicy; apeerAuthentication(STRICT);serviceEntries(a name and a spec each, for Postgres or git outside the mesh). Following the user’s existing charts: the VirtualService’sprefix(other than/) rewritten to/withX-Forwarded-Prefixset (not added, so a client’s own value is replaced);forwardOriginalToken(default false: schedr doesn’t use the token yet); and in the policy, anything from the same namespace to any port (sameNamespace, default true, their charts’ default rule).v1where the cluster serves it (Istio 1.22 on), elsev1beta1(older Istio, OpenShift Service Mesh 2). Not chosen: no Istio objects, examples in the docs only (the ALLOW-policy trap below left to each user).The AuthorizationPolicy lists every port schedr serves, because an ALLOW policy denies whatever it doesn’t list: a policy for the API alone would cut off the ops port (and in distributed mode the gRPC and log ports). Rules:
/api/v1/docs,/api/v1/docs/*and/api/v1/openapi.json(GET) for everyone; the API with a valid token (requestPrincipals: ["*"],api.requireJwt, default true) carryingapi.claims(all of them, each with any of its values); callers without a token byapi.principals/api.namespaces; the ops port fromops.namespaces(empty: anyone). A RequestAuthentication alone refuses only invalid tokens, so the policy is what requires one. With a shared ServiceAccount the policy tells callers apart only by namespace or token (Istio identifies callers by account).Found while designing: (1) an init container has no proxy with classic sidecars (they start after init containers), so the
migrateinit container can’t reach Postgres through a mesh with strict mTLS orREGISTRY_ONLY:migration: initContainer | onStart,onStartrunningstandalone --migrate(it migrates only a schema not up to date, holding the lease); native sidecars (Kubernetes 1.29 on) don’t have the problem; (2) the sidecar stops 5 s after SIGTERM by default, while a drain lasts up to the grace period (600 s): results finished during a drain would never reach the database; henceEXIT_ON_ZERO_ACTIVE_CONNECTIONS(the proxy waits for schedr’s connections to close), andholdApplicationUntilProxyStarts(schedr’s first connections need the proxy). Not chosen:migration: onStartalways (the init container keeps the migration a visible step of its own where the mesh allows it); excluding Postgres’s port from the proxy (excludeOutboundPorts: the database traffic would leave the mesh’s mTLS and policy).The database from a Secret’s user and password (the user’s lab: Postgres set up by hand, its Secret with
usernameandpassword, as their other apps composeSQLALCHEMY_DATABASE_URI):database.postgres(host,port,name,params,existingSecret,userKey,passwordKey,notificationsHost/notificationsPort), the URL built by Kubernetes’$(VAR)expansion fromSCHEDR_DB_USERandSCHEDR_DB_PASSWORD(from the Secret; a task never sees them: its environment is clean). The user and password go in unencoded, so they must not contain@ : / ? # %or a space: accepted, since the user’s database passwords are plain static strings (they separate workloads, they don’t guard against outsiders).database.existingSecret(the whole URL) stays; both set is a template error. Switching from SQLite is one upgrade with these values (a fresh start on Postgres, decided in 2.10). Not chosen:[database] user/passwordin schedr, encoded into the URL (safe for any password, but a schedr change the user’s passwords don’t need); relying on sqlx readingPGUSER/PGPASSWORD(undocumented by schedr, unclear for the listener’s connection); a lab Postgres inexamples/(the user sets Postgres up).vault(the user’s charts sync Secrets with the Vault Secrets Operator; the lab sets them by hand, so off by default): a VaultAuth (kubernetesmethod,auth.role,mount, the Vaultnamespace, the pods’ ServiceAccount,tokenExpirationSeconds) and a VaultStaticSecret perstaticSecretsitem (name,secretName,path,mountkvv2,typekv-v2,refreshAfter600 s,hmacSecretData), each Vault key a Secret key (their charts’ JSON transformation left out: schedr reads plain keys; an item may pass its owntransformation);restartOnChange(default true) addsrolloutRestartTargetsfor schedr’s StatefulSet, since schedr reads its Secrets at start (a restart drains first). Not chosen: leaving the operator’s objects to a manifest beside the chart.DAGs from a folder, by the deployment process (the user: drop Python files into a folder and let
helm upgradecarry them, with no hand-made ConfigMap; outside schedr, since it’s deploying):charts/schedr/dags-values.sh <folder>prints valuesdags.files(path → base64 content), and the chart makes a ConfigMap of them (each file under its own name), mounted at/dag-filesas the rootfiles. A flat folder (the user’s choice after the review, option A): its*.pyfiles and its.schedrignore, hidden files left out; Python files in a subfolder are refused (__pycache__and hidden folders aside), helpers being top-level modules and packages going through git-sync; names only of[-._a-zA-Z0-9]. First built with subfolders: generated keys (f0000…, keys can’t hold/) and the volume’sitemsputting each back at its path; the review found the keys positional, so adding a file renumbered them and changed the pod’s spec (a restart), and until the old pod had drained the kubelet wrote the new ConfigMap through the olditems(content under the wrong names). Not chosen: stable keys from the path withitems(no wrong names, but a restart, so a drain, on every added or removed file); one archive and a sidecar unpacking it with a link swap (subfolders without restarts, but a second git-sync of our own). Otherwise: at most 512 KiB together (a ConfigMap holds 1 MiB, and so does the Secret Helm keeps a release in, whose values and manifest each carry the files in base64, gzipped: 700 KiB of Python measured 690 KB there, so 512 KiB leaves room for files that compress less; 700 KiB before the review); everything checked before anything is printed; sorted output (the same folder, the same values); bash and coreutils only (a CI image with Helm). A fixed ConfigMap name and no checksum on the pod: a DAG change doesn’t restart schedr (no drain). Helm can’t read files outside the chart (.Files), hence a step before it. The pod’s spec names no file, so adding, changing or removing one never restarts schedr. Found while building: a ConfigMap volume holds its files in a timestamped hidden folder,..datalinking to it and each top-level name a link through..data; schedr’s scan follows links (for git-sync), so it saw every DAG three times, and a DAG reached through a per-file link resolves to a path outside the name it was found by (“located at … but parsed from …”, reproduced withdags checkon that layout). The root is therefore the..datalink itself, which the kubelet switches atomically, as git-sync switches its link: inside are plain files (checked: parsed once each).dagsPath: ""leaves the image’s root out (a missing root would warn at every poll). Not chosen:schedr dags packin the CLI (the user: deploying stays outside schedr);kubectl create configmap --from-filewithdags.existingConfigMap(nothelm upgrade, flat folders only);--set-fileper file (a loop by hand); plain text values in block scalars (indentation, tabs and first lines starting with spaces need care; base64 can’t break); a.schedrignorewith..*in the ConfigMap (the per-file links still resolve outside); schedr skipping..-folders (a schedr change for a deployment detail);dags checkin the script (would bring schedr into deploying; a pipeline can run it as its own step).git-sync’s credentials:
gitSync.credentials(type: token: a user and a token for an HTTPS repository, git-sync’sGITSYNC_USERNAME/GITSYNC_PASSWORDfrom the Secret;type: ssh: a private key andknown_hostsmounted read-only,GITSYNC_SSH_KEY_FILE/GITSYNC_SSH_KNOWN_HOSTS_FILE), instead of rawgitSync.env; underREGISTRY_ONLYa repository outside the mesh needs a ServiceEntry (documented). The kind test syncs from a git server in the cluster (git daemon, no credentials); the credentials are checked by rendering only.After the 2.11a code review (2026-10-24): DAG files flat (above);
sameNamespacedocumented as letting an ingress gateway in the same namespace through without a token (set it false then; the user’s gateway is inistio-system); NOTES’ gateway URLs with the prefix,<host>for a wildcard host;make standalone’s address a variable (LISTEN,0.0.0.0as the user set it);dagsRoot: filesandnotificationsUrlKeywithdatabase.postgrestemplate errors; Swagger UI’s files served from their static bytes withCache-Control(an hour); the proxy’s settings merged into aproxy.istio.io/configofpodAnnotationsinstead of replacing it; the folder’s limit 512 KiB (above). A second review over those fixes: adagsPathroot namedfilesby its last part refused too; the script portable (bash 3.2, BSD tools: macOS), counting only*.pyfiles (a folder with only.schedrignorerefused), following links (a linked file taken, a linked subfolder refused like any); file names not starting with.but.schedrignore(Kubernetes refuses..keys, and..datais the root’s link); the description built once and sent withVary: X-Forwarded-Prefix; the guide: at most two roots (git-sync’s volume covers the image’s folder). Left:make standaloneon all addresses by default (the user’s choice).The base image’s libraries (decided 2026-10-25, the user: workers should be able to do some work out of the box; changes 2.10’s “the base image carries only schedr”): API calls (
requests,httpx,aiohttp,tenacity), data (polars,orjson,pyyaml,python-dateutil), networking (paramiko,netmiko,ncclient,dnspython,netaddr) and MongoDB (pymongo); since decision 212 alsopsycopg[binary]andpymysql[rsa], and the connections’ command-line clients; no service frameworks or ORMs (no SQLAlchemy: nothing is served from tasks).images/schedr/requirements.in, pinned with every dependency (46 packages) inrequirements.txtbymake image-requirements(uv pip compilefor musl and Python 3.14 with--exclude-newertwo weeks back, stricter than the library-age rule (a new major or minor at least 7 days old, a patch at least 3 days old, calendar days UTC), so the rule holds for the whole tree). Every package has a musllinux wheel butpymongo, which publishes none: the Dockerfile’s builder stage (build-base) compiles it with its C extensions required (PYMONGO_C_EXT_MUST_BUILD, else it would fall back to pure Python with a warning), without build isolation and with its build tools pinned too (build-requirements.txt); the final image installs only wheels (--no-index), mounted from the builder rather than copied (a copied layer kept 80 MB of wheels). Size: 108 MB → 413 MB, of which Polars’ runtime 179 MB. The smoke test imports each library, checkspymongo.has_c()and runs a Polars query. Async libraries run inside a plain task withasyncio.rununtil M4’s async task functions. Images of one’s ownFROMit still add or pin more. Polars’ engine ispolars-runtime-32, built for x86-64-v3 (avx,avx2,fma,bmi1/bmi2,lzcnt,movbe): on a CPU without themimport polarsonly warns and a task dies of SIGILL later. Checked on a node of the user’s lab (2026-10-25): all four ofavx2,fma,bmi2,movbeon its 12 cores, so it stays. A cluster without them switches topolars[rtcompat](Polars preferscompatwhen installed); setting the choice by variable would need[worker] pass_env, since tasks get a clean environment. Not chosen besides:compatonly (slower everywhere); both engines (+180 MB). Not chosen: a second “batteries” image (two images to build and keep);pandas/numpy(Polars instead); pymongo without its C extensions (slow BSON); a compiler in the final image.Tests:
make chart-checkrenders the Istio values (charts/schedr/ci/istio-values.yaml, both API versions) and checks what they produce;scripts/kind-mesh.shinstalls Istio 1.31.1 (REGISTRY_ONLY;SIDECARS=native, its default, orclassic, a plain container as older Istio and OpenShift Service Mesh 2 run it) on a local kind cluster and checks the docs open without a token, the API refused without a token (403), with a forged one (401) and without the group (403), the CLI through the gateway with--token, a DAG on Postgres migrated on start, and a pod deleted while a task runs whose result still reaches the database (one successful attempt). Both passed on 2026-10-25 (with the base image’s libraries), as didscripts/kind-standalone.sh(all its phases). Found: Istio 1.31 injects native sidecars by default (istio-proxyamong the init containers), which have neither problem above (they start before init containers and stop after schedr); the chart’s settings are for classic sidecars and harmless with native ones. Not run: the drain withoutEXIT_ON_ZERO_ACTIVE_CONNECTIONS(the run shows the settings work, not that they’re needed).
The distributed chart (step 2.11, decided 2026-10-25). mode: distributed in the same
chart, with the same values as standalone (serviceAccount, istio, vault,
database.postgres, dags.files, gitSync), so moving there is mode: distributed and the
roles’ sizes; the API’s Service keeps its name (the CLI’s URL and the VirtualService stay).
Images: master and webserver in
schedr-server:alpine:3.24,tini,ca-certificatesand the binary from the musllinux wheel (no Python; a shell forkubectl exec; no second Rust build). Workers in the base imageschedr(2.11a’s libraries) or one builtFROMit. Not chosen:scratchor distroless (no shell to debug with, certificates copied by hand).The master: a Deployment of one replica,
strategy: Recreate(the old master stops and gives up its lease before the new one starts);migration: initContainer(db migrate --wait) oronStart, through a newschedr master --migrate(as standalone’s: only a schema not up to date, holding the lease). Not chosen: a second replica as a standby (every rollout would stall: the new pod’s migration waits for the lease the old master holds); a Helm hook Job (the same stall, and hooks skipped by--no-hooks).The webserver waits for its schema instead of refusing it (its part of
/readyz“starting” until then, checked every 5 s,SCHEMA_RETRY; it says once what it waits for), so during an upgrade the old webserver serves until the new one is ready; one replica by default (webserver.replicas). Not chosen: a crash loop until the master has migrated. Built with it:lead(the lease, and with--migratethe migration) shared byschedr masterandstandalone;connect_database(no schema check) replacingopen_database.Workers: a StatefulSet (a headless Service,
log_addressthe pod’s DNS name, decided in 2.7) with a ReadWriteOnce PVC each for logs and the journal (a rescheduled pod keeps its worker ID, its journal and its logs); 2 replicas;terminationGracePeriodSeconds600 mirrored into[worker] termination_grace_period; one pod at a time on upgrades; DAGs fromgitSync(a sidecar each) and/ordags.files(the ConfigMap in each). Master and webserver get no DAG files. Not chosen:emptyDir(a rescheduled pod’s attemptslost, its logs gone).TLS:
tls.mode: appby default (schedr’s own default), a Secret per role (ca.crt,tls.crt,tls.key: cert-manager’s names), from, in order: Secrets of one’s own → cert-manager (tls.certManager.issuerRef, creatingCertificateobjects) → generated by the chart (tls.generate, on by default: Helm’sgenCA/genSignedCert, RSA 2048, both serverAuth and clientAuth, checked; the master’s naming its Service, the workers’ naming[tls] worker_name, the webserver’s a client certificate; 10 years; read back on upgrades withlookupand kept; all generated again under a new CA when one is missing; the CA’s key not kept). Generated certificates need Helm talking to the cluster:helm template, client dry runs and rendering GitOps tools (ArgoCD) see no Secrets and make new ones each render (schedr reloads them without a restart, but pods disagree on the CA for a minute or so): there, cert-manager or one’s own Secrets. Rotation: delete the Secrets,helm upgrade.tls.mode: mesh(the user’s cluster) needs none. Not chosen: one Secret for all roles (any worker could pose as the master);meshby default (plain traffic outside a mesh); an openssl script beside the chart (a step by hand); generation by schedr itself (deploying stays outside schedr); a hook Job (RBAC to create Secrets).Identity and policies: ServiceAccounts per role when created, or one existing one for all (
serviceAccount.create: false); the AuthorizationPolicy gains :8070 (from workers) and :8081 (from the webserver), by account when each role has its own, else undersameNamespace; a PodDisruptionBudget for workers (maxUnavailable: 1, on by default); theServiceMonitorover every role’s ops port. Not chosen: NetworkPolicies (overlapping Istio here; possibly later for clusters without a mesh).Values: per-role sections
master:,webserver:,worker:(replicas,resources,nodeSelector,tolerations,affinity,podAnnotations;imagefor master and webserver); standalone keeps its top-level values. Not chosen: everything per role, standalone included (standalone’s values rewritten).From standalone: the same release,
helm upgradewithmode: distributedon the same Postgres (history kept, a short downtime: decided in 2.10); standalone’s PVC left (NOTES say how to delete it); distributed requires Postgres (a template error on SQLite). Not chosen: a second release beside the first (two masters on one database: one waits, but confusing, and twice the resources).After the 2.11 code review (2026-10-25): with
tls.mode: appthe master’s gRPC port and the workers’ log port are namedtls-grpc/tls-logs(Istio’s sidecars pass schedr’s own TLS through; namedgrpc/http-logsthey parsed it as plain gRPC and HTTP, breaking the links);serviceAccount.createwith anameshares that one account across the roles, as standalone’s pod did (moving kept the account a Vault role or a policy is bound to; one per role only without a name);vault.auth.serviceAccount, by default the pods’ account (the master’s with an account per role; before, an account the chart no longer created); generated certificates made again when the names they must carry change (a fingerprint of them on each Secret);clusterDomainfor the workers’ addresses (wascluster.localfixed); the webserver says what it waits for whenever that changes (an unreachable database, then a schema to migrate);Database::require_usable_schemaandDbError::SchemaNotUsableremoved (no longer used); the guide’s lines on the schema; the kind script’s images as given. Left: the role test reading the API’s address from the log itself (a few lines of test code). Found by the mesh’s kind run: the webserver’s calls to the workers’ log endpoints went out of its sidecar as plain text: Istio reaches a headless Service through anORIGINAL_DSTcluster, without automatic mTLS (it doesn’t know the endpoints), so the calls carried no identity and the workers’ policy (by account, and by namespace too:sameNamespacereads the caller’s identity) refused them with 403. The chart now adds a DestinationRule for the workers’ Service withISTIO_MUTUAL(withistio.enabledin mode distributed, every worker having a sidecar); checked: the log read through the webserver. This corrects 2.7’s note that the headless Service “gets the mesh’s mTLS” by itself. Found on kind: WSL’sfs.inotify.max_user_instances(128) ran out with two clusters and Istio, so sidecars failed to start (raised to 512, as kind recommends); and a failedhelm upgradeleaves objectshelm uninstalldoesn’t remove, so the kind script deletes the release’s labelled objects before it starts.Tests:
make chart-checkover the distributed combinations (TLS app with each source and mesh, an existing account, Istio, git-sync,dags.files, the budget; the generated certificates’ names and key usages checked with openssl); CI buildsschedr-serverand smoke-tests it (an arbitrary UID, no Python, master and webserver starting and stopping); integration tests for the webserver waiting for its schema andmaster --migrate;scripts/kind-distributed.sh(the switch from standalone, two workers with generated certificates, a DAG run, a task’s log through the webserver, a worker drained during a task;SIDECARSnative and classic withtls.mode: meshon the mesh cluster).
Kill tests (step 2.12, decided 2026-10-25). M2’s “done when” on a cluster:
scripts/kind-kill.sh, only the local kind cluster schedr-test (context kind-schedr-test;
any other CLUSTER is refused, and the context’s server has to be loopback). It is not part
of make check or CI. A crash is kubectl delete pod --force --grace-period=0 (no SIGTERM, so
no drain). Three runs, in order:
Distributed, 2 workers, the chart’s generated certificates, Postgres database
schedr(created by the script;kind-distributed.shkeeps using thepostgresdatabase):holdsleeps 90 s withretries=0. Once it has started, the master pod is killed. The new master takes the lease when it expires (within[master] lease_period, 30 s). The same attempt finishessuccess. Neither worker becomeslost. The new master records themdisconnecteduntil they register (the lease counts from then), and both areactiveagain once the run has finished.Then
againsleeps 30 s withretries=1andretry_delayof 0 (the default is 0 retries, so without the retry the run would fail, which is the rule; the default delay is 5 minutes, so the DAG sets 0 and the check is not waiting that out). Its worker pod is killed. The StatefulSet brings that pod name back with its volume, so the journal is there. The attempt endslostwithWorkerRestartedwhen that pod is ready again within[master] lease_timeout(60 s). Past that,WorkerLostis the rule and the script prints it; the killed worker beinglostis not a failure of the check. The retry succeeds. The other worker staysactive.Then the release is installed again as standalone on SQLite. A short run (
ping) succeeds, thenagainis killed with the pod.pingis stillsuccess(the volume kept the database), andagainislost/WorkerRestarted, thensuccess(WorkerLostwhen the pod took the lease, as for the worker).
The same three checks, as commands for a release that is already installed, are in the guide
(“Killing the master or a worker”) for OpenShift. Nothing in the repository runs them: the lab
context stays untouched. Not chosen: adding the kills to kind-distributed.sh and
kind-standalone.sh (every install run would pay for them, and a kill failure would look like
an install failure); a script that only checks a cluster those two left behind
(kind-standalone.sh ends on Postgres, so the SQLite volume would be missed); a k3d cluster
(the repo’s cluster scripts are kind; the checks are kubectl and Helm); one run with both
workers busy (a slow lease takeover can let the surviving task finish before the worker is
killed); a graceful kubectl delete pod (already checked: the task finishes in the drain, one
success); letting the script take any context (one variable away from the lab cluster);
applying it to the lab cluster from here; leaving the step open until that lab run. The role
tests already cover the same rules in processes (roles.rs: a master restart continues one
attempt; a worker killed and restarted ends lost / WorkerRestarted and retries). A kill
that breaks one of these goes to BUGS.md and is not fixed in this step.
scripts/kind-lib.sh is sourced by kind-distributed.sh, kind-kill.sh,
kind-standalone.sh and kind-mesh.sh (the helpers, podman’s image prefix, the loopback
context guard, starting a stopped node, loading images, in-namespace Postgres, the fit
values, fail). Not chosen: copies in each script (they drifted apart).
Web UI and CLI¶
A web dashboard is required: live view of what is running, and access to task logs.
A CLI is required alongside the web UI.
The web UI is served by a separate process from the master scheduler (
schedr uisince M3, over webservers’ APIs, decision 21B;schedr standaloneserves it next to its own API), so the UI and the scheduler can restart, fail and scale independently.How the webserver gets state: through Postgres, for reads and actions.
Reads: the webserver queries Postgres directly, with a read-only database role. The UI keeps working (history, runs, logs) while the master restarts.
Actions (trigger, cancel, pause, drain, …): the webserver writes a command row; the master picks it up, validates and applies it in its own transaction, and marks it
appliedorrejected(with a reason). The UI shows a command as pending until then. Actions are durable: one sent while the master restarts is applied when it returns. The master stays the only writer of scheduling state (a command is a request).The master picks commands up via Postgres
LISTEN/NOTIFY(at once), with polling every few seconds as a fallback; standalone (SQLite) uses polling only.Commands so far:
trigger_run(dag_id, optionalplanned_for),cancel_run(run_id),pause_dag(dag_id,cancel_runs: the “pause and cancel runs in progress” choice),unpause_dag(dag_id); stored as the command’s JSON with its kind. Applied in request order. An applied command records what it produced ({"run_id": …}for a trigger, the attempts being stopped for a cancel, the runs cancelled by a pause), so the CLI can show it; a rejected one records the reason: an unknown DAG or run, a run already finished, a DAG that can’t run (removed, in conflict),--forin the future, a payload that doesn’t read. A database failure leaves the command pending for the next pass: a command is rejected only for what is wrong with it, never for a passing outage.Applying a command again is harmless (B7, fixed 2026-10-23): its writes and its decision are separate statements, so a failure between them leaves it pending, applied. A command is marked (
commands.applying_at) before its first write; one found pending with the mark is applied again knowing it may find its own work done: a manual run’s ID is its command’s, and the repeat looks that run up first (trigger_as; the insert would find it too); and when what it asks for already holds (the run or task already cancelled, the task already queued, the worker already resumed, whose follow-up is done again), it is decided applied, whoever did it; any other rejection (an unknown task) stays one. The mark is set before the command’s first read, so it says only that a try began; the rule needs no more. Pause, unpause and drain set a state and repeat as they are. Not chosen: one transaction per command, its writes and its decision (the cleanest, but every write of applying a command, about 15 database functions on two backends, some with transactions of their own, would take the transaction); recording the first try’s outcome (each command would report when its first write is done).A failed round still delivers what it built (B7): each message (
CancelAttempt,AssignTask,AssignParse) is built after the write it stands for, so they are sent whatever fails after them (MasterCore::tick_partial, the dispatcher’sstep_into; a lost worker’s moved parse jobs before the write that can still fail; drains and resumes decided before a failing command get their follow-up). Before, a cancel decided in a round that then failed was sent again only when its worker reconnected, an assignment waited 10 s to expire and a parse job 10 min. Kept as an option, just in case: resending the cancel of every attempt still being cancelled every few seconds, until it ends. Not built: the ways a cancel can be lost besides a failed round (the master crashing first, a broken connection) end the worker’s stream, and a reconnecting worker gets its pending cancels again; add it if a lost cancel is ever seen.The CLI waits for the decision by reading the command back (every 0.5 s, for up to 30 s), and prints the result (
triggered run … of sync for 2026-10-15 01:00 UTC (03:00 CEST) (running)); a rejection is an error (exit 1) with the master’s reason. When the master doesn’t decide in time, the CLI says so and exits 1; the command stays pending and is applied when the master runs (it is durable).No API between the webserver and the master: both are the same binary at the same version and
schedr db migrateruns first, so sharing the schema is safe.Not chosen: an API on the master for reads and actions (the UI would go dark whenever the single master is down); reads from Postgres and actions by gRPC to the master (actions would fail while the master restarts).
Live updates: Server-Sent Events (SSE). Updates only flow from the server to the browser; actions are ordinary HTTP requests (WebSockets would add complexity for nothing).
The master issues a
NOTIFYwhen state changes (task states, runs, workers); each webserver replica listens and fans events out to its browsers. Events are small (“run X changed”); the browser then fetches the details through the normal API.A comment line every ~15 s keeps proxies (e.g. the OpenShift router) from closing idle streams; reconnection is built into SSE.
Live log tail is polled by the browser, a part a second, the webserver reading the worker’s range endpoint for it (decision 175; see Task logs).
Standalone: the webserver polls the database instead of listening.
The user CLI uses the webserver’s API, the same one as the UI: one API, one place for authentication and permissions. Commands (see Runs: manual runs, backfill and pausing):
Command
Does
schedr dags list,schedr dags pause <dag>/unpause <dag>list DAGs; stop / resume the scheduler creating runs
schedr runs trigger <dag> [--for <time>] [-p …] [--params '{…}']a manual run
schedr runs backfill <dag> --from … [--to …] [--all] [-p …]a backfill
schedr runs list <dag> [--for <time>]runs, with their IDs
schedr runs show <run id>a run and its tasks; a mapped task’s instances as
fetch[0],fetch[1], … after its own row (decision 86)schedr runs cancel <run id>,schedr runs cancel --backfill <id>cancel a run; what’s left of a backfill
schedr tasks cancel <run id> <task id> [--map-index N]cancel one unfinished task, stopping it if it runs (see Task assignment)
schedr tasks retry <run id> <task id> [--map-index N]retry an
unschedulabletask of an unfinished runschedr tasks logs <run id> <task id> [--try N] [-f]an attempt’s log (the latest try by default), read from its worker;
--followuntil the attempt endsschedr tasks attempts <run id> <task id> [--map-index N]its attempts: status, worker, times, duration, exit code, error
schedr tasks output <run id> <task id> [--map-index N]its output as JSON (
--json: with its outcome); a mapped task’s gathered list without--map-indexschedr workers listthe workers and their state, gone ones included
schedr workers drain <worker>/resume <worker>maintenance drain
The master’s gRPC API stays internal to the workers.
REST with JSON; an OpenAPI description is generated from the Rust types, committed to the repository, and CI fails if it is out of date (like the JSON Schema).
Compatibility between the CLI and the server (the CLI comes from
pip install schedron a laptop or in CI and drifts from the deployed version; the UI is served by the webserver, so it always matches):Paths carry the major version (
/api/v1/...); within a major, API changes are additive only (new endpoints, new optional fields, new enum values clients treat as open), as for DAG JSON and the protocol. Clients ignore unknown fields. CI fails on a breaking change to the committed OpenAPI description within a major.Versions on every request: the CLI sends
Schedr-Client-Version, the server answers withSchedr-Server-Version. Same major, any minor: works. A command or flag the server doesn’t have yet gives a clear error (”schedr runs backfill --allneeds schedr server ≥ 1.6 (server: 1.4)”; the CLI knows which version introduced each command and flag). A CLI older than the server works (optionally a hint at most once a day that newer commands exist). A different major: the CLI refuses (“server is schedr 2.x, this CLI is 1.x:pip install 'schedr>=2,<3'”).Other API clients (scripts, OpenAPI-generated clients) follow the same rules. A request without
Schedr-Client-Versionis served; one with another major version gets a 400 with what to install.Schedr-Server-Versionis on every response, errors too.
Endpoints so far (what the CLI needs in M1):
GET /api/v1/dags,GET /api/v1/dags/{dag_id},POST …/dags/{dag_id}/pause(body{"cancel_runs": …}, optional) and…/unpause,GET …/dags/{dag_id}/runs?for=…&limit=…(newest first, default 50, at most 500),POST …/dags/{dag_id}/runs(body{"planned_for": …}, optional),GET …/runs/{run_id}(with its tasks),POST …/runs/{run_id}/cancel,GET …/runs/{run_id}/tasks/{task_id}/attempts,GET …/runs/{run_id}/tasks/{task_id}/attempts/{try}/log?from=&limit=(M2.7, see Task logs),GET …/commands/{command_id},GET /api/v1/workers(M2.2), and the OpenAPI description atGET /api/v1/openapi.json.Swagger UI at
/api/v1/docs/(2.11a, decided 2026-10-24), always on, in every webserver and in standalone:utoipa-swagger-uiwith itsvendoredfeature, the UI’s files in the binary (no download at build time, no CDN for the browser), reading/api/v1/openapi.json. The description lists an optional bearer token (security[{}, {"bearer": []}]): schedr checks none itself (until M3’s auth modes), but a mesh or proxy in front may (Istio with Keycloak), and Swagger UI’s Authorize sends it. In the chart’s Istio policy both paths are open to everyone without a token (they describe the API and do nothing; calls from the page need a token like any other). Behind a path prefix (the user’s gateways serve apps under e.g./service/<app>/, rewritten to/with anX-Forwarded-Prefixheader): the page refers to the description as../openapi.jsonand/api/v1/docsredirects todocs/, both relative, and the served description names the prefix as itsserversURL whenX-Forwarded-Prefixis a plain path (/, letters, digits,-._~; anything else ignored; it only changes the document sent back to the same caller). So schedr serves the UI’s files itself (docs.rs, the crate’sserve), not through the crate’s axum router (absolute redirect and URLs). The committedschema/openapi.jsonhas noservers. Not chosen: a setting for the prefix (one more value to keep equal to the gateway’s); relativeserversURLs (how clients resolve them varies). Not chosen besides: a setting to turn it off (the user’s choice: the description is public on the same port anyway); Scalar or RapiDoc loading their JavaScript from a CDN (blocked on many internal networks);utoipa-swagger-uidownloading Swagger UI from GitHub at build time (offline builds and CI would need it vendored by hand); copying a UI’s files into the repository (updated by hand);/swagger-uiat the root (outside/api/, a second route in a VirtualService).Actions answer
202 Acceptedwith the command (pending); the client pollsGET …/commands/{id}for the master’s decision and its result (e.g. the new run’s ID). The API itself only checks the request’s form (IDs, body); everything else is the master’s decision, so there is one place for the rules.A command is stored once per key (decision 126, the user’s, 2026-11-01, B140): an action may carry an
Idempotency-Keyheader (1-128 visible ASCII characters); the webserver stores one command per key and person, and the same request sent again gets the command stored the first time (422for the key with another command). The CLI makes a key per command and the UI one per action (made when its dialog first opens, kept in the browser’s tab until an answer says whether the command arrived); both send again under the same key, up to 3 times in all, while no answer comes or the server fails, and the UI then says the command may have arrived, never “not sent”. Not chosen: only telling “not sent” from “unknown” in the UI (a hurried second click still starts two runs); the wording now and the key later.A DAG ID is never
.or..(decision 127, the user’s, 2026-11-01, B139): such an ID is a URL path segment the client’s and browsers’ URL parsing removes (%2Etoo, by the URL standard), so the API couldn’t be asked about that DAG. Refused where every DAG ID is checked; a file defining one gets an import error saying why. Not chosen: an escape of schedr’s own in URLs (every client, the UI’s links and the API carrying it, for two names); leaving it, documented (the UI would list a DAG it can’t open).Errors are JSON,
{"error": "…"}: 400 for a malformed request, 404 for an unknown or removed DAG, run or command, 422 for a command key used before with another command, 503 for something the request needs that can’t be reached now (a worker holding a log), 500 for a database failure (details only in the webserver’s log). Times are UTC (RFC 3339); kinds and states are their model names.The user recorded on commands is the
identity_header’s value, oranonymous.The committed OpenAPI file is
schema/openapi.json, generated with the JSON Schemas (make schema) and checked for staleness by CI. The check for breaking changes within a major compares against the last release, so it starts with the first release.Not part of the user CLI:
schedr task-ctxandschedr dag-ctx(talk to the agent), server commands such asschedr db migrate/schedr db status(talk to the database), the server roles, and the local commandsschedr dags check <path> [--against <url>]andschedr dags test <dag>(dags testhas no server;--againstreads the server’s workers, see Testing DAGs).Human output is aligned columns (
DAG PAUSED TRIGGER DEFINED IN,RUN KIND STATE FOR BY; a DAG in conflict showsCONFLICT: N places;TRIGGERshows the trigger as written, thencatchupand its window as a range, either end open, e.g.0 3 * * * (Europe/Warsaw), 2025-12-31 23:00Z (local:+1h)..2026-06-30 22:00Z (local:+2h)or@daily, ..2026-12-31 00:00Z: in that column times are short, UTC with the local zone’s offset at that moment, markedlocal, instead of the local time, so the column stays readable; not chosen for the range:-(clashes with dates, negative offsets and the-placeholder),→,[a, b], ISO 8601’s/), times in UTC and the machine’s zone (TZ, else the system’s);--jsonprints the API’s JSON as it is (UTC only), for scripts.--fortakes an RFC 3339 / ISO 8601 date-time with an offset, one without (UTC, with the warning on stderr), or a date (midnight UTC).The CLI only sends credentials, it never validates them: a bearer token (
--token/SCHEDR_TOKEN, e.g. a Keycloak token required by an Istio ingress) or basic credentials (--user,SCHEDR_USER/SCHEDR_PASSWORD). From inside the namespace no credentials are needed (withauth.mode = "none").schedr login(fetching a token through OIDC’s device flow): possibly later.Frontend: server-rendered HTML with htmx (confirmed 2026-10-27, decision 26A: Rust, in the
schedr uirole of the same binary; not chosen: Python, e.g. FastAPI or Flask with Jinja2: a second runtime and image, the API’s types duplicated, template errors at run time). Pages are HTML rendered from Rust templates (askama, checked at compile time); htmx adds the interactive parts (buttons, filters, partial refreshes) and live updates (driven by a small script of our own since decision 175; its SSE extension before).No JavaScript build: no Node.js / npm, nothing new in CI. htmx and a small pan/zoom helper for the graph are vendored single files; all assets are embedded in the
schedrbinary, soschedr ui(and standalone) serves everything itself.The DAG graph is drawn as SVG on the server with a layered layout of our own (decision 22A, 2026-10-27: Sugiyama: layering, crossing reduction, x-placement; DAG graphs here are small and layered, and edge kinds and folded nodes need control; not chosen: a layout crate such as
layout-rs); logs are converted from ANSI colours to HTML on the server.Style (the user’s, 2026-10-27): very clear, nothing fancy: divs, tables, lists, dropdowns, toggles, buttons; one stylesheet of our own (spacing, rounded corners, colour only where it means something: states, outcomes, warnings), no CSS framework. Two themes, light and dark, as CSS variables defined once for each, switched by a toggle in a corner and remembered in the browser; before a choice, the system’s preference.
The live log tail (decision 23A, 2026-10-27): the server reads the worker’s range endpoint (
from) for the new bytes; no new worker endpoint. Since decision 175 the browser asks for each part (about once a second while the attempt runs) instead of the server sending them over SSE. Not chosen: a streaming mode on the worker’s endpoint (a long-lived mTLS stream per viewer to each worker).No sessions of our own (decision 24A, 2026-10-27):
basicuses the browser’s Basic auth,proxy_headerthe proxy’s session; every action from the UI (a POST) must carry a matchingOrigin/Sec-Fetch-Site, others are refused (CSRF). Not chosen: cookie sessions with a login page and CSRF tokens.The documentation inside the UI (decision 28A, 2026-10-27): the image’s build makes the Sphinx site (the guide, DAG pages, design and generated reference; not the Rust API reference nor
_sources) into/usr/share/schedr/docs;schedr ui(and standalone’s UI) serves it at/docswhen that directory exists ([ui] docs_dir, also to turn it off), linked from the header: always the running version’s, offline. Not chosen: embedded in the binary (8-10 MB more in the binary and wheel, Sphinx before every release build); a link to hosted docs (a public site per version, internet from the browser). The docs are part of the release (decision 29A, 2026-10-28): CI’s wheel and image job waits for the docs job, andmake image/make server-imagebuild the docs first, so a docs warning (the build is strict) blocks wheels and images until it is fixed. Not chosen: an image without docs when they are missing (an empty/docsshipped unnoticed); reusing a staledist/docslocally.Decided ahead for M3.2b-M3.6 (the user, 2026-10-28, all at once so the steps could run without stopping):
The run graph flows top to bottom (30A): layers down the page, task names at full width. Not chosen: left to right (Airflow’s; names squeezed, long chains scroll sideways).
A task’s details open in a panel beside the graph (31A), loaded with htmx; the same panel is a URL of its own (
…/runs/<run>?task=<id>, the whole page with it open), so links and reloads work. Not chosen: a page per task (the graph lost meanwhile).One merged runs list over every deployment (32A), with a Deployment column when there are several; one cursor (
triggered_atand run ID) pages them all, as they share that order; filters apply to each. Not chosen: a list per deployment.A task’s output: the last 64 KiB of the pretty-printed value, marked as cut, and a download of the whole (33, the user’s: the tail is the more valuable part). Not chosen: the whole output on the page; the first 64 KiB.
Live events say only what changed (34A): “run R of DAG D”, “DAG D”, “workers”; the UI re-renders that part from the API. The master
NOTIFYs on Postgres; on SQLite (standalone) the webserver polls about once a second. Not chosen: events carrying the new state (a second format beside the API’s views).Actions are confirmed in a small dialog of our own (35A, an HTML
<dialog>) saying what will happen; the result shows inline: pending, then applied or rejected with the master’s reason. Not chosen: the browser’sconfirm().The UI proves itself to webservers as master and workers do, by
[tls] mode(36, the user’s): inappmode by mTLS on a second webserver port serving the whole API, forschedr uionly (its certificate’s name checked, asworker_nameis); inmeshmode by a shared token on the public port (one per deployment in[ui] deployments, from a Secret). Only a request so proven has its forwarded user name trusted; the public port is unchanged for the CLI, ingress and standalone. Not chosen: the API port itself HTTPS with optional client certificates (changes how everything reaches it); trusting the network.The chart deploys
schedr uiby default (37A, distributed mode): one replica and a Service on 8082, its deploymentdefaultthe release’s own webserver; no Ingress, as for the webserver. Not chosen: off by default.
Smaller choices made building M3.2 (Claude’s, 2026-10-28; to revisit if wrong): the graph scrolls inside its box, no pan/zoom helper yet (the vendored one PROJECT.md mentions, when a graph needs it); long edges run straight down beside each layer’s boxes and bend only between layers (they never cut a box); a pair of tasks joined by both data and order is one line, drawn as data; the log tab shows a try’s last 256 KiB from its first whole line; the merged runs list says a deployment that doesn’t answer is missing from that page and the older ones (one cursor can’t place its runs; per-deployment cursors weren’t worth it for a degraded case); an htmx request is answered with a fragment, errors too (htmx is set to swap 4xx/5xx), a browser’s with the whole page; IDs in the API are UUIDs in the 8-4-4-4-12 form, lowercased (SQLite compares text).
How M3.3 follows changes (Claude’s, 2026-10-28, within 34A and 23A): the writes signal them themselves, by triggers in the migrations, so nothing in the master’s code has to remember to: on Postgres statement triggers on
runs,task_instances,attempts,dagsandworkersNOTIFY schedr_changesonce per changed run (run <id> <dag>), DAG (dag <id>) or the workers, sent at commit, a transaction’s duplicates dropped by Postgres; on SQLite row triggers append to achangestable (pruned to about the last 1,000 rows) that the webserver reads every second. The webserver follows them once (started by the first subscriber; listening only through a connection checked not to pass a pooler in transaction mode, as the master’s commands) and servesGET /api/v1/changes(run,dag,workers,refresh; a keep-alive comment every 15 s); when changes can’t be followed (notifications off, a pooler withoutnotifications_url) it sendsrefreshevery 5 s, and a client that fell behind getsrefresh. The UI relays one stream per deployment (reopened after 1 s, doubling to 30 s, with arefreshonce back) and serves one unfiltered stream (/events) of every change, held once per browser by a shared worker, each page choosing the changes that concern it (decision 175); htmx reloads the page’s live parts (one request; the run page’s head, graph and tasks swap together, its panel on its own, the log tab excepted). A running try’s log is followed by the page (…/tail?try=&from=, decision 175): each answer is the next part (up to 1 MiB) and the element asking for the one after it, a second later (at once when the part was full), until the attempt has ended and all of it is shown. Not chosen: the master sending the changes itself (every write path would have to); achangestable on Postgres too (writes in the master’s hot path).175. One live stream per browser (the user’s, 2026-11-03, on B31 and B32: a browser opens at most six HTTP/1.1 connections to a host, and each live page held one, so a click or a page’s reload waited in the browser’s queue, 7-10 s in Codex’s reproduction). A SharedWorker (
assets/live.js), started by the browser’s first live page of the UI and ended with its last, holds the only stream and hands each change to every page (the user’s, 2026-11-03, over the Web Lock +BroadcastChannelfirst written here: Web Locks need a secure context, so onhttp://to another host every tab would hold its own stream again). A page joining later gets the changes since it was made (the worker keeps a minute’s), orrefreshwhen it doesn’t know; a stream opened again sends every pagerefresh. A browser without SharedWorker (Chrome on Android) gives each page its own stream, given back after 10 s hidden (B25). The shared stream carries the deployments’ changes unfiltered (JSON each), and each page decides which concern it. A running try’s log tail is read by polling (about once a second while the attempt runs), holding no connection. HTTP/2 through a TLS ingress lifts the limit too: the deployment guide says so. Not chosen: hidden tabs closing their stream at once (every tab switch reloads the page, and six visible pages still fill the pool); HTTP/2 alone (only over TLS, never on a localhttp://standalone); a log stream per log page (three running logs, three connections); a localStorage lease for plain HTTP (background tabs’ timers are throttled, so two tabs may briefly both stream). htmx’s SSE extension is dropped: nothing uses it any more.How M3.4 takes actions (Claude’s, 2026-10-28, within 35A and 24A): each action is a button opening a
<dialog>that says what will happen (pause offers “also cancel its queued and running runs”; trigger takes the moment in--for’s forms, previewed in UTC and the browser’s zone as it is typed); confirming posts the form with htmx, the UI sends the API’s command and answers with the command’s fragment at the top of the page’s results, which reads the command again every second until the master has decided (applied, with a link to a triggered run; rejected, with the master’s reason, e.g. a cancel too late; or not sent, with why). Buttons only where the state allows: Trigger and Pause / Unpause on a DAG’s page, Cancel on a queued or running run, Cancel on a task that hasn’t ended and Retry on an unschedulable one (in its panel), Drain / Resume on the workers page (a new page, every deployment’s workers with their warnings, live). The Origin check of 24A came with the first POST, here, not with M3.5: a POST is taken only withSec-Fetch-Site: same-origin(ornone), or without it anOriginwhose host is the request’s (X-Forwarded-Hostbehind a proxy); anything else is 403. Commands are recorded asanonymousuntil M3.5 passes the user’s name on.Live updates on by default, with a switch (decision 38A’, the user’s, 2026-10-28, after measuring): stress scenarios 15 (Postgres) and 15b (SQLite through standalone) run scenario 1’s and 9’s loads four times, the change triggers off, on, on, off: with them on, the rounds’ mean 1.02 and 0.94 times, the tasks a second 0.97 and 0.98 times those without, within run-to-run noise (a first run, without then with on a busy machine, had shown 9%). So the triggers stay on by default, standalone included;
[database] change_notifications = falseturns them off, applied byschedr db migrate(and--migrate, holding the lease: a master doesn’t lead when it can’t be applied), never by a running master (disabled on Postgres, a switch row the triggers read on SQLite); the webserver follows what the database does (the triggers’ state), and with them off sendsrefreshevery[webserver] refresh_interval(15 s). Not chosen: off by default with live updates opt-in (B, the cautious one, picked first on the 9%); the master sending one notification per round itself, no triggers (C: cheapest “on”, but every write path must report its runs); the webserver polling a “changed since” query (D: indexes on every write, or table scans).How M3.5 signs people in (Claude’s, 2026-10-28, within the auth modes above and decision 36): one
[*.auth]section for the webserver and the UI (mode,identity_header,users_file,behind_tls_proxy,allow_remote); standalone’s UI, on its API’s port, signs in by[webserver.auth]. The safety rules refuse to start:proxy_headerbeyond a loopback address withoutallow_remote,basicthere withoutbehind_tls_proxy.basic’s users arename:bcrypt-hashlines inusers_file, a file mounted from a Secret (not an environment variable: one way, not two); bcrypt is slow on purpose and every request carries the credentials (no sessions, 24A), so a check that passed is remembered 5 minutes by a keyed hash (random key per process; never the password), a failed one never; an unknown name is checked against a real dummy hash at the file’s highest cost (about the time a known one takes). The file is followed: looked at every 5 s and read again when it changed (a changed password or a removed user takes effect, what was remembered forgotten); one that can’t be read or doesn’t parse leaves the users as they were (logged as an error: a mistake in the deployment, the user’s call, 2026-10-28), while an empty one, deliberately, signs no one in. A header sent twice (a client’s, then a proxy’s appended) names no one: the identity header,X-Schedr-User, the token,Authorization. The API refuses (403) a write a browser marks as from another site (Sec-Fetch-Site, elseOriginagainst the host, as the UI’s actions, 24A): a browser attaches remembered Basic credentials to any site’s form; requests no browser header marks (the CLI,schedr ui) pass. The UI passes the person’s name on inX-Schedr-User, taken by a webserver only from a proven UI: its certificate naming[tls] ui_name(schedr-ui) on[webserver] ui_port(8083,appmode: a server configuration whose client verifier also checks that name, so any other certificate fails the handshake; the same API there, its requests marked proven); the token of[webserver] ui_token_fileinX-Schedr-Ui-Token(at least 16 characters, compared in time depending only on the token’s length; per deployment[[ui.deployments]] token_file; it opens the API, not standalone’s own pages); or being in-process (standalone’s own UI: a request extension no client can set). Anyone else’sX-Schedr-Useris ignored. The name travels from the UI’s page to its calls in a task-local (schedr_client::USER), carried into the tasks a page spawns to ask several deployments. The API’s description and Swagger UI stay open (2.11a); the UI’s assets too (its sign-in page uses them).schedr uiloads certificates only when a deployment is reached over mTLS (https://), asappis the default mode; its client is rebuilt when the files rotate.Testing (2026-10-27): pages and fragments rendered from fixed view data and checked through an HTML parser (elements and classes, not whole-page snapshots); the UI’s router in process over the client’s in-process transport and a real API; the graph layout by property tests over generated DAGs (no overlaps, edges downward, deterministic, crossings no worse than the naive order); standalone end-to-end runs followed through the UI (SSE from M3.3); a small Playwright suite in Python (decision 27A: the theme toggle and its memory, the zone cookie, an htmx swap, a live update), run by
make test-uiand its own CI job, kept out ofmake check(the browser download). Not chosen: no browser tests.Views for M4’s features (resources, cleanup, outcomes, mapped tasks; decision 25B, 2026-10-27): built in M3 as shells, the tabs and panels there with nothing to show until M4 fills them. Not chosen: adding them with M4.
The webserver serves HTML fragments besides the JSON API used by the CLI; both use the same queries, so the HTML layer is thin.
Not chosen: a single-page app without a build step (Preact +
htm: a JavaScript application to maintain without types or tests, and a JS graph layout); a full single-page app (React / Svelte + Vite + TypeScript: Node.js in the build and CI, a second ecosystem to maintain).
What the UI shows (beyond what is decided elsewhere: DAG conflicts, import errors, parse warnings, unschedulable tasks with each worker’s reason, mixed code hashes in a run):
A task’s status at a glance: state · outcome · cleanup, each part only when it says something:
success(the only outcomeSUCCESSisn’t shown),success · Unavailable,success · cleanup failed,cleaning_up,skipped · not chosen/skipped · on Rows(why it was skipped),failed · timed out.The run’s graph (SVG): nodes coloured by state, the outcome under the task name. Edges styled by kind, with a legend: taken (solid); not taken (dashed, grey, labelled with their condition, e.g.
on Unavailable); branch selection (marked as from a branch); requirement /uses=(dotted, own colour). Generated tasks (from the Airflow translation: last-line extractor,Empty/NotEmptycheck, start anchor) are folded into their task by default, with a “show generated tasks” toggle. A mapped task is one node with a summary (e.g.120 success · 3 Unavailable · 2 skipped); clicking it lists the instances.Task details panel (on clicking a node or row), with tabs: Attempts (try number, status, duration, worker, peak memory, error summary; rejections with each worker’s reason), Output (the outcome; a preview of the output as pretty JSON, cut off after a size limit, with a download link), Cleanup (only if the task has one: its attempts, result, duration, the registered handles, masked like everything else), Logs (the task’s log with live tail; the cleanup’s log on its own sub-tab).
Resources: a Resources panel in the run view (name, setup task, users, state:
waiting for users/cleaning_up/cleaned/cleanup_failed/not needed, the cleanup’s attempts and logs); selecting a resource highlights its setup and users in the graph and dims the rest. Not chosen: drawing bands around users (hard to lay out well in SVG).Run summary: the result with a one-line reason from the run result rule (e.g.
failed: task load failed (timed out); cleanup of export failed), and the command history (the audit trail: who triggered, cancelled or paused, when, applied or rejected).History and filters: the runs list filters by result and date; a per-task history page shows one task across runs (state, outcome, cleanup, duration) with filters by outcome (e.g. runs where
fetch_primaryreturnedUnavailable).
The Deployments page (the user’s request, 2026-10-31; built in M4.4b):
/deploymentslists the deployments the UI is connected to (in standalone,defaultalone);/deployments/<name>shows that deployment’s configuration and a graph of its nodes. Each master (leader and standbys) and each worker is a rectangle in a distributed deployment; in standalone one rectangle, the process, holds a node for its master and one per worker. The database and the webserver aren’t drawn. Clicking a node shows its own configuration.Its name (decision 121, the user’s: A): Deployments, the word the UI and
[ui] deploymentsalready use. Not chosen: B Clusters (two words for one thing, or a rename everywhere).A deployment’s configuration (decision 122, the user’s: A): every node’s own, effective configuration (secrets are never in it: they come only from environment variables). A master writes its own to the database, a worker sends its own in
Register(protocol 0.1, edited in place before 1.0.0), and the webserver serves its own and those through the REST API. Not chosen: B the webserver’s own configuration and what is known already (queues, slots, versions, the lease holder): the masters’ and workers’ settings would stay unseen.Secrets masked at the source (the user’s requirement, 2026-10-31): a node masks its configuration before it leaves the process (written to the database, sent in
Register, served by the webserver), so no secret is stored or sent in clear. A URL keeps its scheme, user, host, port and path, its password shown as****(postgres://schedr:****@db:5432/schedr), and so do query parameters naming one (password,sslpassword,token,secret,key, any case); a value under a key naming one is****whole. Paths to secret files (token_file,key) are shown: they are not the secret. Every configuration field is covered by a test that fills each string with a secret-looking value and finds none of them in the output, so a field added later can’t leak by being forgotten.
Standby masters are recorded (decision 123, the user’s: A): a
masterstable, each running master (leader or standby) heartbeating its row with its role and configuration; one not heard from ages out, as a worker does. Not chosen: B the leader only (the lease holder; standbys unseen).When (decision 124, the user’s: A): M4.4b, after M4.4, before 1.0.0 (the schema and protocol still edited in place). Not chosen: before M4.4; at the end of M4.
Claude’s: the page and the configuration endpoints are reads, under the same access as the other reads; the graph’s node states update live, as the Workers page does.
Claude’s, as built (M4.4b): a master’s ID is the holder it takes the lease as (a UUID per incarnation), so its role is read from the lease (the holder whose lease hasn’t expired by the database’s clock is the leader); a process’s ID is a UUID made once per process, which standalone’s master, worker and webserver share (one rectangle). A master writes its row every 10 s, unfenced (a standby writes too); the page shows those heard from in the last 30 s; a row not written for an hour is removed. A worker’s node (
workers.master_id,process_id,config) is written atRegisterby the master it registers with. Masking happens at each node and again downstream, as defense in depth: the master masks a worker’s configuration again before storing it, and the UI masks every configuration again before showing it, so an older or altered node can’t show a secret.GET /api/v1/deploymentalso says who the request was taken as, which the Config page shows per connection.The Workers page stays, with a Master column (the user’s, 2026-10-31): the master each worker is registered with (
workers.master_id, written atRegister, so a re-registration after a takeover shows the new leader; a disconnected worker keeps the last one, greyed), linked to that master’s node on the deployment’s page. Drain and Resume name the deployment and that master in their dialog, and say that the deployment’s leading master applies the command and the drained state holds across a takeover (it is in the database), so the user knows which deployment and master a Drain targets.The navigation (the user’s, 2026-10-31): DAGs, Runs, Deployments, Config, Workers, Import errors.
The Config page (decision 125, the user’s, 2026-10-31: A):
/config, the UI’s own side: its effective configuration masked as a node’s is (122), its schedr version beside each webserver’s (a mismatch marked), each connection’s state (reachable, latency, how the UI proves itself: none, token or mTLS, the last error), and who is signed in (as[ui.auth]sees it, and as passed on to the webservers). In standalone, the process’s configuration. Not chosen: B a “This UI” section on the Deployments list; C the configuration and version only.One graph for everything (decision 128, the user’s, 2026-11-01, reviewing M4.4b):
/deploymentsis one graph: one block for the UI (its configuration, version, who is signed in, each connection’s state: the Config page’s content, so the Config page and its navigation entry go), linked by HTTP to each deployment’s webserver, and in standalone a node inside the standalone process (the same process ID); each deployment a frame holding its webserver (a process of its own, or a node of the standalone process), its masters and its workers; the webserver linked to the masters by the database (what the link is), each worker to the master it registered with (gRPC; dashed while it isn’t connected). Each worker shows its queues. A node’s configuration is shown as TOML, the format of schedr’s configuration files (a value not set is left out). Clicking any node opens its panel on the same page. Not chosen: a page per deployment besides it (removed, its routes too: the UI’s own links point at the node on the graph, so no redirect is needed); the Config page kept as a side page (it didn’t read as part of the deployments); no worker-to-master link. Supersedes 125’s page (its content kept) and the navigation: DAGs, Runs, Deployments, Workers, Import errors.A node’s problems on the graph (decision 129, the user’s, 2026-11-01): a node with a warning is yellow, with an error red, and its panel lists them. The UI: a webserver it can’t reach (error), a webserver of another version (warning). A webserver: unreachable (error). A worker: lost or offline (error; offline changed by 130), its stored warnings and the import errors of its parses (warning). A master: new, its heartbeat row carries its current problems (its lease renewal late, the change notifications off, a write failing), each a warning or an error. Not chosen: only what was known already (a master never coloured); every log line at WARN or ERROR, kept and reported by each process (noisy, the most work).
The Import errors page names the master and the worker (the user’s, 2026-11-01): a Master and a Worker column, each linking to its node on the graph; the master that stored a parse is recorded with it (
parse_files.master_id). The page stays a page of its own, in the navigation (the user’s: what people look for most); the graph only marks a worker with import errors and links to the page.An offline worker has no problem (decision 130, the user’s, 2026-11-01): grey and dashed, not red. Offline is a clean deregistration (a restart, a scale-down), and worker rows are never deleted: with pod-named workers each restart would leave another red box for good, and a real error would be lost among them. Its stale warnings and import errors don’t colour it either. Lost stays an error, disconnected a warning. Not chosen: hiding gone workers after a while (they stay on the graph and the Workers page); red as 129 had it.
A task’s log and output are masked when shown (decision 131, the user’s “go on” on option A, 2026-11-01; details Claude’s): the webserver masks them by their text, as error texts are (an address’s password, a value after
password=), so the API shows them masked too; downstream tasks get an output as returned. An output’s field is also hidden when a whole word of its name names a secret (password,api_key,apiKey,clientSecret,access_token), sopartition_key,sort_key,cache_keyare shown (the user’s, 2026-11-01, raised by side notes). Not chosen: the configuration’s rule (any name ending inkeyhidden: a task names its own fields as it likes); texts only (a secret returned as a plain field would show). A log is passed in whole lines, so no part shows half an address: a part asked from inside a line starts at the next one, a running attempt’s last line waits for its end, a line longer than the part asked for is shown to its last whitespace with a note that it is cut, the rest of it passed over (so a shortlimitor afrominside a secret reads nothing of it). Each part is masked with the 64 KiB before it, read but not shown, so a quoted value going on over lines is hidden in a part starting inside it (Grok’s review; 64 KiB the user’s, after Codex showed a value begun 5000 bytes back leaking past a 4 KiB context: a PEM key is about 3 KiB; a value open longer before a part is the documented limit; not chosen: 16 KiB, cheaper for the live tail; a quoted value ending at a newline everywhere, parts and whole agreeing but a PEM body never masked). A worker serves up to 1 MiB and 64 KiB at once. A field name’s words split at acronyms too (HTTPPassword,AWSAccessKeyId), and names are masked as texts (Codex: an output keyed by an address), in configurations too. The UI reads 1 MiB parts as the CLI does, so only a line over 1 MiB is cut (the user’s, 2026-11-01; raised by a side note). Not chosen: a long line passed in pieces, each masked with the 4 KiB before it (nothing dropped, but a secret named further back would show); cutting at 64 KiB in the UI silently. Not chosen yet: B, masking the values of the secrets a task was given (Airflow’s way), with task secrets in M4.
Authentication: as little as possible in schedr. Access is normally decided in front of schedr (e.g. Istio with Keycloak at the ingress, namespace policies inside); schedr doesn’t repeat it. Modes (
[webserver.auth] mode):Mode
How it works
Fits
noneschedr trusts whoever reaches it
behind a mesh that authenticates (the main deployment: Istio + Keycloak, the whole namespace trusted); standalone (localhost)
proxy_headeran SSO proxy in front (
oauth2-proxy, OpenShiftoauth-proxy, …) logs users in and passesX-Forwarded-User; schedr trusts itKubernetes without a mesh, with any identity provider
basicHTTP Basic against users in
users_file(name:bcrypt-hashlines, mounted from a Secret, never the config file)small setups without an identity provider (a VM, Docker Compose, a lab server)
No roles: an authenticated user can do everything (trigger, cancel, drain, …); restricting that is the job of whatever is in front.
The user name is recorded for audit on every command row and shown in the UI: the header in
proxy_header, the login inbasic, and innonean optionalidentity_header(e.g.x-forwarded-user, set by Istio from the Keycloak token). It is never used to allow or deny anything.Safety rules at startup:
proxy_headerlistens only on a loopback address unless overridden explicitly (anything reaching it around the proxy could forge the header);basicrefuses plain HTTP on a non-loopback address unlessbehind_tls_proxy = true(passwords would cross the network in the clear).Not built (possibly later, for deployments that need them):
jwt(schedr validating OIDC tokens itself), roles mapped from groups, per-DAG permissions (Airflow’saccess_controlis already kept as metadata), schedr-issued API tokens.No users of our own: ruled out deliberately (decision 39, the user’s, 2026-10-28). schedr keeps no user database and manages no users: no Users page, no admin role, no passwords set in the UI, no first-admin bootstrap, no sessions of its own (24A stands). People are managed where the organisation already manages them, its identity provider (Keycloak behind Istio in the main deployment:
nonewithidentity_header, orproxy_headerbehind an SSO proxy), andbasic’susers_filestays what it is: for labs and single machines (made withscripts/users-file.py). Why: comparable tools (Dagster, Temporal, Argo Workflows) leave identity to SSO, and those that own it (Airflow’s Flask-AppBuilder, moved out of its core in Airflow 3) carry it as a large part of their own; owning it means password resets, sessions, lockouts, an admin role and their audit for good, for the rare deployment without any identity provider. Weighed after the file proved clumsy with Helm as the only way in (no kubectl, no helm-secrets). Not chosen: users in a database managed by admins on a Users page (schedr uigiven a database, a first admin from a setup code in its log, a sign-in page and sessions). Planned instead, in M6 (the user’s, 2026-10-28, postponed from after M3): a mode of its own,mode = "ldap", checking HTTP Basic credentials against the organisation’s LDAP (a bind) with a section of its settings; users stay in the directory, schedr keeps none. Still open, if a deployment without Istio/Keycloak needs more: the chart putting oauth2-proxy in front of the UI for any OIDC provider (proxy_headerbehind it), or schedr speaking OIDC itself (jwtabove).How
schedr uiproves itself follows[tls] mode, as the master’s and workers’ links do (decision 40A, the user’s, 2026-10-28): inappmode, mTLS on the webserver’s UI port (36); inmeshmode with Istio’s AuthorizationPolicy, the same port in plain HTTP, trusting the mesh ([webserver] ui_port_in_mesh = true, refused inappmode, a warning at start): the chart sets it when the UI’s account is shared with no other role, admits the UI’s account there (andistio.authorizationPolicy.ui.principals, other releases’ UIs), and adds a DENY policy for anyone else on that port, as the namespace-wide rule would let any pod in; then no token is made. The token stays for the rest: standalones in a federation,meshmode without Istio’s policy or with a shared account. Why: the chart’s generated token is remade at everyhelm template, so Argo CD (the user’s deployments) would rotate it at each sync. Not chosen: keeping the token with Argo’signoreDifferenceson its Secret (B: configuration outside the chart), the token from Vault (C).The UI signs people in as the API does, or the API is
none(decision 41A, the user’s, 2026-10-28): ofwebserver.auth×ui.auth, only the same mode for both, or any UI mode with the API’snone(the API kept internal, people through the UI). Refused: an open UI before a guarded API (anyone acts through the UI), and two identity sources (SSO for one, a users file for the other: one person under two names). The chart refuses the others for a distributed release with its UI, andui.auth.modeleft empty takeswebserver.auth’s (one sign-in for the release); forschedr uiover other releases the rule is the guide’s advice, as nothing sees both. Not chosen: one sign-in only (B, which loses the internal-API setup), everything allowed with warnings (C).
Times and time zones: the server works only in UTC; people see UTC and local.
Server side: the database, the scheduler, the API, JSON and schedr’s own logs use UTC. Times are always stored with their zone even though it is always UTC (
timestamptzin Postgres; ISO 8601 withZin SQLite), never as naive timestamps. Cron expressions are evaluated in their schedule’s zone and converted to UTC at once.Every time shown to a person appears twice, UTC and local, e.g.
01:00 UTC (21:00 EDT). “Local” is: in the UI the browser’s zone (read by a few lines of inline JavaScript into a cookie; until then only UTC, labelled); in the CLI the machine’s zone (JSON output: UTC only); in email notifications, which have no viewer, the DAG’s schedule zone; in the task log viewer, the browser’s zone next to the UTC written in the log. Webhooks: UTC only (ISO 8601), plus the DAG’s zone name as a field.The schedule’s zone is shown with the cron expression on the DAG’s page (
0 3 * * *Europe/Warsaw), not as a third display zone.Input (
--for,--from/--to, the UI’s date fields): without an offset it is UTC, with a warning that it was interpreted as UTC; any explicit offset is accepted. The UI’s date field shows the entered time in both zones before confirming.
Live updates through VPNs and HTTP proxies: SSE responses carry
Cache-Control: no-cacheandX-Accel-Buffering: no; since some proxies buffertext/event-streamanyway, the browser falls back to polling (every few seconds) when no event, not even a keep-alive, has arrived for ~30 s.
Import errors (M4.2c)¶
Asked by the user (2026-10-29): a place in the UI for the DAG files that failed to import.
What is shown (decision 66, the user’s: A): the files of each root’s current parse that failed (their DAGs keep their last good version, listed but held: no runs until the file is fixed, decision 72; a timeout or a runner that died holds nothing and is parsed again, 72.2; see DAG code delivery), with the root, the hash, when and by which worker that file was parsed (decision 93, the user’s, 2026-10-30: A:
worker_idandparsed_aton eachparse_filesrow, a retry writing its own; not chosen: B a retry overwriting the parse’s, which would misdate the files it didn’t parse; C both, two sets to explain), the exception, message and traceback. The master writes each root’s current parse tocurrent_parseswhen it decides it (from what alive workers report), so the API (GET /api/v1/import-errors) shows exactly what is in effect without deciding again. Not chosen: B the history of earlier parses too (more API and UI).Where (decision 67, the user’s: A): a page of its own, “Import errors”, beside DAGs, Runs and Workers, merged across deployments; a count in the navigation and a notice on the DAG list, both loaded after the page (htmx), so no page waits for them. Not chosen: B a tab on the DAG list.
Errors only (decision 68, the user’s: A): parse warnings (a
TypingHint) stay adags checkmatter (57.4); nothing more is uploaded. Not chosen: B uploading and storing them.
Task logs¶
Task logs are stored on the worker’s local disk and served by the worker itself over HTTP (a small endpoint inside the worker agent, including live tail of running tasks).
What backs the log directory (volume type, StatefulSet, …) is a deployment concern, outside schedr: the worker just serves local files.
Each task attempt records which worker ran it, so its logs can be found.
The webserver proxies log requests to the worker; the browser never talks to workers directly.
Access to the log endpoint is mTLS only (
tls.mode = "app": a client needs a certificate from schedr’s CA; inmeshmode the mesh decides, the namespace is trusted). It serves logs only, never actions. Not chosen: short-lived tokens signed with a shared secret on top (the decision before M2.7): every worker would hold the key to check them, so a compromised worker could sign its own and they would add a secret and nothing else; tokens signed with a private key only the webserver holds (Ed25519) are the variant worth having, kept for when the UI’s permissions need it (M3).The worker deletes logs after N days or beyond a size limit (configurable).
When a log can’t be fetched (worker offline, file deleted, …), the UI states clearly that the log file is unavailable at this location (e.g. it may have been deleted).
How it is built (M2.7):
The worker’s endpoint:
GET /logs/{attempt_id}?from=<byte>&limit=<bytes>on[worker] log_bind:log_port(0.0.0.0:8081; 0 picks a free port) answers the bytes fromfrom, at most 1 MiB, with headersSchedr-Worker-Id(who answered),Schedr-Log-Size(the size now) andSchedr-Attempt-Running(from the journal). An ID that isn’t an attempt ID (a UUID) is 400, a log the worker doesn’t have is 404, all as JSON errors naming the worker. Reading on from the size returned follows a running task; a live stream (SSE) comes with the UI (M3). Not chosen: SSE now (the UI’s job); whole files only (a big log, and no way to follow).The address the worker sends in
Register(log_endpoint) ishttps://<host>:<port>(http://inmeshmode), the host being[worker] log_address, else the host name. The chart (2.11) runs workers as a StatefulSet with a headless Service and sets it to the pod’s DNS name (<pod>.<service>.<namespace>.svc.cluster.local): a headless Service doesn’t balance (the name resolves to that one pod), its pods are in Istio’s registry, so the call passesoutboundTrafficPolicy: REGISTRY_ONLY(the mesh’s mTLS to them needs a DestinationRule withISTIO_MUTUAL, which the chart adds: found in 2.11, see The distributed chart), and Istio routes HTTP by host name, which a raw pod IP may not match. The address is overwritten at everyRegister, so a pod restarted with a new IP is found again. Not chosen: the pod IP as the default (blocked or unrouted underREGISTRY_ONLYwithout a Service, and Istio’s handling of raw IPs varies by version); an address worked out from the connection to the master (wrong behind NAT or a sidecar).The webserver’s proxy:
GET /api/v1/runs/{run}/tasks/{task}/attempts/{try}/log?from=finds the attempt’s worker by ID and its currentlog_endpointin the database, reads the part from the worker and answers JSON:attempt_id,try_number,worker_id,from,next(where the next part starts),size,runningandcontent(UTF-8; a character cut at the end of a part is left for the next one, invalid bytes become U+FFFD). Clients never reach workers. What can go wrong, said plainly:Case
Answer
the try hasn’t started, or never did (
assignment_expired)404, “no log so far” / “never started, so it has no log”
the worker is
offlineorlost503 at once, without connecting: “worker
w1is offline: the log of try 1 is unavailable”the worker has no endpoint
503
it can’t be reached (5 s to connect, 30 s in all)
503 with the reason
it has no such file
404: “the log file is unavailable at worker
w1(it may have been deleted)”another worker answered (
Schedr-Worker-Id: an address now someone else’s, a DNS cache after a restart)503: “reached worker
w2instead ofw1at …: its address is stale; try again shortly”the worker’s and the webserver’s
[tls] modediffer503, saying to give every role the same mode
Not chosen for a stale address: relying on the 404 (it would claim the log was deleted); one certificate per worker naming its ID, checked by the webserver (needs per-pod certificates).
Requests to workers never use an HTTP proxy, whatever
HTTPS_PROXYsays (see Configuration: internal links): a proxy can’t reach pod IPs or cluster names,NO_PROXYrarely covers them, and inmeshmode a request sent to a proxy would skip the mesh’s per-destination policy. Through aCONNECTtunnel mTLS would still hold end to end, and a proxy that decrypts and re-encrypts can’t present a certificate from schedr’s CA, so the handshake fails rather than leaking anything; skipping proxies is about working connections, not secrecy. No setting for it. Not chosen:[tls] use_proxy_env(a choice nobody should make).schedr tasks logs <run> <task> [--try N] [--follow]prints the log as it is (the latest try by default;--jsonprints each part as the API’s JSON, one per line);--followreads on fromnextevery 0.5 s until the attempt ends.Retention on the worker: logs older than
[worker] log_retention(default 30 days) are deleted, and beyond[worker] log_max_size(no limit by default: volume sizes vary too much for a default) the oldest go first. A sweep runs at start and every hour. A log whose attempt is in the journal (running, or its result not yet acknowledged) is never deleted, though it counts towards the size limit (the limit is about the disk). Parse logs (parse-<root>.log) follow the same rules. Mode: logs are created[worker] log_mode, default 0600 like the journal and connection files (B182, the user’s, 2026-11-07: 0600 with a key; not chosen: 0640 fixed, which stops a shipper under an unrelated uid silently, or 0600 fixed, with no way to open them up); a shipper in the worker’s group sets"0640"; at most"0644", and the owner always reads and writes. It is set on each log as it is opened (the umask doesn’t change it), and at the worker’s start on its log folder (0700, 0750, 0755) and the logs already there. A registration over the report limits (an ID, a version, a queue over 4096 characters, over 256 queues, a configuration over 1 MiB) is refused, not cut: what it says is kept and matched on (B183, after Grok’s review). Listing gone workers for as long as their logs are kept (Worker lifecycle) waits for retention on the master (M4).
DAG code delivery¶
schedr reads DAG code from directories on the worker’s filesystem. How the code gets there is a deployment concern, outside schedr.
Currently: git-sync sidecar. Shared volumes must also work, and so must other ways of filling the directories (e.g. code baked into the image).
The directories are listed in
SCHEDR_DAG_PATH, using the usualPATHsyntax (colon-separated). A relative one is taken from the directory the role starts in (B60).Each directory is scanned recursively, so git submodules inside a DAG repository work.
Every
.pyfile is parsed, unless excluded by an ignore file.Ignore files are named
.schedrignore, use gitignore syntax, and may appear in any subdirectory (like.gitignore). Airflow’s.airflowignorefiles are not honoured.Only DAGs defined with schedr’s own APIs (the native API or a compatibility layer such as
schedr.airflow) are recognized.A
.pyfile that defines no DAG is ignored silently (helper modules are common).A file’s DAGs are only those defined in it: a module it imports may define DAGs too, found when that module’s own file is parsed, not taken as the importing file’s (B110). Parsing imports the file, so its top-level code runs on every parse; helper modules with heavy import-time work should be ignored or refactored. This will be documented.
305. Only files that mention
schedrare parsed (A, the user’s, 2026-11-05): a.pyfile whose text doesn’t containschedris shipped and hashed with its root but never loaded by the parser, as Airflow’s safe mode does: a library in a root (or linked into it) isn’t run on every parse, and a module of a package with a relative import (from .util import clean) no longer shows a false import error from being loaded by path on its own. Imported normally (import mylib.corefrom a DAG or a task) it works as ever. A file that defines DAGs must mentionschedr(the user, 2026-11-05): a file that only calls a factory (from factory import build_dag; build_dag("team_a")) is skipped and its DAGs count as removed, so the docs say it plainly: such a file needs at leastimport schedr(a# schedrcomment counts too). Not chosen: loading a file inside a package under its package name (relative imports fixed, but every library module still run on each parse);PYTHONPATH(it finds modules forimport, but the parser loads each file by its path). A file that can’t be read is parsed anyway, so the parser reports why rather than its DAGs counting as removed. The mark is the exact bytesschedr, any encoding.schedr dags checkkeeps the rule, even for a file it is named (it would otherwise pass what a deployment skips), and printsskipped <file>with why;--jsonstays what a parse reports. Found building this: a factory call defines nothing today even with the mention, as a DAG belongs to the file callingDag(...), the helper (B170); the rule holds for a file re-exportingDagthrough another.New DAGs are paused when first found; a user unpauses them from the UI or CLI.
Removed DAGs disappear. When a DAG’s file is deleted (or no longer defines that DAG), the DAG is removed from the web UI and from all listings, and its schedule stops.
When a DAG counts as removed: only when a parse of a newer hash of its root no longer contains it. A worker that simply hasn’t synced yet (rejection 6, DAG file missing) never removes a DAG.
Runs in progress: attempts already running finish; tasks not started yet are cancelled.
History stays in the database, hidden. If a DAG with the same ID appears again, its history shows again, until retention deletes it (see State storage: Retention). A DAG that comes back is paused again, like a new one (it may have been gone long enough for its schedule to surprise).
A file that fails to import keeps its DAGs at their last good version, with the import error shown; it doesn’t remove them. This covers a broken push and a DAG that doesn’t parse with a new major version of schedr alike. A DAG defined in another file in the meantime counts as a second place (a conflict) until the broken file is fixed or removed.
A DAG whose file fails to import is held (decision 72, the user’s, 2026-10-29: B): its tasks would run the current code, where the file doesn’t import, so every run would fail. While the file has an import error in its root’s current parse:
no run is created: nothing is stored, and its fire times count as missed (as when paused); once the file imports again, its trigger’s
catchupdecides about them;a manual trigger is refused: the command is
rejectedwith the reason (“DAGsyncis held, no runs are created and it can’t be triggered: its filesync.pyfails to import (ModuleNotFoundError: …), so its tasks couldn’t run. Every DAG of the file is held until it imports”);its queued runs wait until the hold lifts (72.1, the user’s: A); runs already running go on.
Shown as
heldin the API (DagView.held: the file, exception and message), a badge, a banner and a disabled Trigger in the UI, aHELDcolumn inschedr dags list, the gaugemaster_dags{state="held"}, and a log line when a hold starts and when it lifts. Backfills, chained runs and event-triggered runs follow the same rule when they come (M4.11b, M4.12).Not chosen: A keep creating runs that fail (the behaviour before: noisy, and retries burn); C pause the DAG automatically (changes a setting the user owns, and the user must remember to unpause it).
Transient parse failures (decision 72.2, the user’s, 2026-10-29): a file the agent stopped,
ParseTimeout(it took longer than the parse timeout, e.g. on a busy worker) orRunnerDied, says nothing about the code.They hold nothing: a DAG already known keeps running its last good version; a file parsed for the first time defines no DAG yet, so there is nothing to run until it loads (the import error is listed).
They are retried every time, without a limit: a parse with such files gets another parse job for the same code, after 30 s, doubling with each retry up to 10 min, given to another worker reporting that code when there is one. A retry replaces only the files that failed transiently (a file that loaded keeps its result); the DAG list is worked out again. A restarted master plans the retry when a worker reports the code again. A retry stored but not taken into the DAG list (a database error after the store) isn’t lost: its job isn’t finished, and the master forgets which parse the root is on, so the same retry uploaded again, though it stores nothing new, decides the root afresh (B100).
A file that keeps timing out never takes effect (its DAGs stay on their last good version): each failure logs a warning naming the files, and the import error stays listed.
Not chosen: holding on transient errors (a one-off timeout would stop a healthy DAG until the next commit, since each code version was parsed once); a retry limit (the user: retried every time).
schedr’s own rejections hold too (decision 72.3, the user’s, 2026-10-30: B):
InvalidDag(the file imports, but the master’s checks refuse a DAG of it),InvalidPathandParseResultTooLarge(the JSON of all the file’s DAGs together is past[grpc] max_message_size) are not parsed again (the same code gives the same result) and hold every DAG of the file: the master never got the new definitions, and running the new code with the last good version’s structure and arguments could quietly use stale data. The error is the file’s, so the reason shown (APIheld.reason, the UI’s banner and the disabled Trigger’s tooltip, a refused trigger,schedr dags list) says so and what to do: fix the invalid DAG or move it to a file of its own; move large DAGs to their own files, keep large data out of DAG arguments, or raise the setting.Not chosen: A not holding them (new code on old arguments, silently); C holding only the rejected DAGs and letting the file’s others run (per-DAG validation results, a change to the stored parse data, and the catalog’s conflicts and removals for partly valid files; the user can move the neighbours to files of their own instead).
How the DAG list is worked out: the master stores each parse as the worker reported it (table
parse_files: per file, its DAGs or its import error) and, whenever a root’s current parse changes, works the DAG list out again from the current parse of every root: new DAGs, new versions, conflicts, removals. Each DAG has one version per parse that defines it (the version records which code it came from); the newest becomes current. A root’s current parse is the parse of the hash its worker last reported; until a new hash is parsed, the previous parse stays current. A parse that arrives for a hash no longer reported is stored but not used.The master’s checks of DAG JSON (it never runs user code, so DAG JSON is all it sees): produced by a version it can read; located in the file it was parsed from; unique task IDs; edges between tasks of the DAG, no task depending on itself, no cycles; every output reference along a data edge from a task of the DAG;
max_active_runsat least 1;startnot afterend; file paths relative and inside the root. Types and paths into outputs are checked by the Python API at parse time and not again. A file with an invalid DAG is treated as a failed import (InvalidDag, listing every problem; a bad path isInvalidPath): all its DAGs keep their last good version.
326-333. How DAG files load (the user’s, 2026-11-06, from Codex’s investigation of B172: 118 scenarios through the
CLI and real workers; tests keeps them):
326. Ordinary imports, a process per file:
team/sync.pyisteam.sync, in a process of its own for each file parsed; a task’s process imports it the same way. Relative imports,__init__.py, cycles andsys.moduleswork as in Python, and parsing tests the program a task runs. A file’s top level runs once per process: parsing can repeat a helper’s. A dot in a file or folder name has no import name, and is refused. Not chosen: private names with__package__set (double loads, stdlib siblings); a private package per root (two copies of one module); one process per root with its definitions kept (it checked two DAGs that then failed as tasks, and one file’s helper state shaped another’s DAG).327. A root’s version covers what is on its
sys.path: the content hashes of the other DAG roots fold into a DAG root’s reported hash, so editing a library in another root reparses its users (B173). Conservative: any edit reparses the others; workers serving a root must agree on the roots. One root alone keeps its plain hash. Not chosen: declared import sets (configuration and dependency rules that don’t exist); only the root’s own files onsys.path.328. Names that can’t be told apart fail what uses them: a top-level name in two roots, or also a library’s (the standard library’s, an installed one, a preloaded one). Only that file and the root’s files importing it fail, with why (checked at compile time, inside functions too, so the start method can’t matter); other files and tasks go on, and a library importing that name always gets the library. Not chosen: failing the whole root (the user took it, then a side note showed a stray
queue.pywould stop every DAG and task of a deployment); Python’s first match (the wrong code, silently, by start method: B174, B175).329. A DAG belongs to the module running its
withblock: a helper’s function can build it (B170); a module imported by another still owns its own (B110). Decision 305 stays: the file must mentionschedr. Not chosen: an explicit ownership API for factories.330.
.schedrignoreis about what is shipped:dags checkreads the same filtered copy asdags testand workers, so it can’t pass what they can’t import (B179). Not chosen: a separate discovery-only list.331. Naming a file or folder inside a configured root keeps that root: so
schedr dags check team/sync.pyimportsteam.sync, with the other roots importable; a named file a worker doesn’t get is an error.332.
[dags] parse_concurrency, default 4: how many files are parsed at once, spawned or forked alike, capped at the cores the agent may use;1is one at a time.dags checkuses it, and forks when the interpreter has a fork server (“parse as the task runs”). Measured (stress scenario 22, 12 cores, 1000 files importingpydantic): spawn 585 s one at a time, 143 s four at once; fork 42 s and 14 s; peak memory about 60 MiB more spawned, 20 MiB forked. Parsing isn’t counted in task slots and each process has its own memory budget, so on a tight pod:parse_concurrency = 1or a preload list. Name clashes are looked at per name imported, cached, so a process’s start doesn’t grow with the root.333.
[worker] pass_envreaches parsing and the fork server too (the user’s, 2026-11-06, from Grok’s review): spawned tasks had aPYTHONPATHofpass_envonsys.path, while a parse and a forked task hadn’t, and imported something else. A parse and a fork server now get all ofpass_env, as a task does, so a library needing such a variable at import works in both. Not chosen: onlyPYTHONPATH. DAG authors could already read these from a task; now also at parse, so secrets don’t belong inpass_env(the guide says so), and parse tracebacks aren’t masked.Parse as the task runs (the user’s, 2026-11-06): with a fork server on, a file is parsed in a fork of it, falling back to a fresh process when it isn’t usable; off, in a fresh process. An import that breaks only after a fork shows at parse time. Fresh-process parsing costs about 0.4 s per file here, a fork about 5 ms; what isn’t preloaded is imported per file, so the preload list matters more. Measured by a stress scenario.
Plain script delivery¶
Plain Python and Bash scripts live in directories listed in
SCHEDR_SCRIPT_PATH, separate fromSCHEDR_DAG_PATH. Files there are never imported or parsed as Python.SCHEDR_SCRIPT_PATHis a normal configuration key (SCHEDR_CONFIG__SCRIPTS__PATH) withSCHEDR_SCRIPT_PATHas a short alias. SamePATHsyntax asSCHEDR_DAG_PATH.Scanned recursively;
.schedrignorefiles apply, as inSCHEDR_DAG_PATH.A script is recognized only if a script configuration file declares it. Script configuration files are TOML files named
schedr.toml, with predefined keys, and must themselves be insideSCHEDR_SCRIPT_PATH.There can be many
schedr.tomlfiles, at most one per directory.One
schedr.tomlcan declare several scripts, and can declare the same script more than once (e.g. with different schedules).Paths in a
schedr.tomlare relative to that file...is not supported, so a configuration file can only refer to scripts in its own directory or below. Absolute paths are rejected.Several
schedr.tomlfiles (e.g. a parent and a subdirectory’s) may declare the same script file. Each declaration is independent and creates its own job/task.Symlinks are allowed, including ones pointing outside the directory. This is a deliberate escape hatch.
Change detection and content hash work the same as for DAG code (polling, settle time, content hash).
Internally every job is a DAG: a declared script becomes a one-task DAG.
Every declaration in a
schedr.tomlhas a name, unique within that file (a TOML table key, e.g.[jobs.report_daily]).DAG operators refer to a declared script (via a dedicated operator,
ScriptOperator, an ordinary class in schedr’s Python API) by the location of theschedr.tomlthat declares it and the declaration’s name. The location is root-relative (see Script roots) or absolute.Script roots make references portable between environments (cluster, local development, pods with different mount paths):
Every
SCHEDR_SCRIPT_PATHentry is a root, named by default after its last path component (/git/scripts/etl-repo→etl-repo).The configuration file can rename an entry; the path must be one of the
SCHEDR_SCRIPT_PATHentries (renaming never adds directories to scan):[scripts.roots] etl = "/git/scripts/etl-repo"
Nested entries in
SCHEDR_SCRIPT_PATH(one inside another) are a startup error.Duplicate root names are a startup error, unless resolved by renaming in
[scripts.roots].Every
schedr.tomlis therefore under exactly one root. Script references and standalone jobs are stored as (root name, path ofschedr.tomlrelative to the root, job name), e.g.etl-repo:team_a/schedr.toml#report_weekly, and resolved by the worker that runs the task. This is also the job’s stable ID in the UI, CLI and run history.Absolute paths to a
schedr.tomlremain accepted inScriptOperatorreferences.
schedr.toml keys¶
One table per job under [jobs.<name>]:
[jobs.report_daily]
script = "reports/daily.py" # required; relative to this file, no "..", no absolute
interpreter = "etl-venv" # required; an [interpreters] entry
args = ["--region", "eu"] # argument list, never a shell string
env = { REPORT_MODE = "full", DB_PASSWORD = { secret = "etl/db#password" } } # env var <- secret
secrets = ["etl/api#token"] # readable only with `schedr task-ctx secret get` (not in env)
working_dir = "reports" # relative to this file; default: this file's directory
schedule = "0 3 * * *" # optional; cron or preset ("@daily")
every = "1h" # alternative to schedule
once = 2026-12-24T23:00:00 # alternative to schedule: one fire time (native Once)
timezone = "Europe/Warsaw" # default UTC
start = 2026-01-01 # TOML date/datetime
end = 2026-12-31 # optional; last scheduled run at or before it
initial_since = 2020-01-01 # optional; `since` of the first run (native initial_since)
catchup = false # default false
max_active_runs = 1 # default 1 (no overlapping runs)
notify = ["ops-slack"] # server channels; or { "ops-slack" = ["RUN_FAILED", "RUN_RECOVERED"] }
queue = "default"
retries = 2
retry_delay = "5m"
timeout = "30m"
max_output_size = "4MiB"
description = "Daily report"
tags = ["reports"]
cleanup_handles = ["ExportJob"] # optional; handle types `schedr task-ctx cleanup add` accepts
[jobs.report_daily.outcomes] # optional; same meaning as an Outcome enum
SUCCESS = 0
NO_DATA = 3
[jobs.report_daily.params] # optional; run parameters with defaults (see Run parameters)
region = "eu"
[jobs.report_daily.cleanup] # optional; per-task cleanup (see Cleanup and resources)
script = "reports/undo.sh" # required; same rules as the job's script
interpreter = "bash" # required
args = ["--region", "eu"]
timeout = "5m" # native cleanup_timeout; default: the server default
retries = 3 # the cleanup's own retries
retry_delay = "30s"
anywhere = false # native cleanup_anywhere
Same semantics as the native API (schedules, run time semantics, defaults, outcomes, output limits,
ProcessResultoutput). Unknown keys are an error.Durations as
"30s","5m","1h30m"; sizes as"4MiB"(same format as the server configuration).At most one of
schedule,every,once.notifynames server channels only, as a list (default events) or a table choosing events per channel (event names as inEvent). DAG-definedEmailChannels are Python objects, so they exist only in DAG files.No concurrency keys (
max_active_tasks,max_active,max_active_per_run): a job is a one-task DAG, somax_active_runscovers it.scheduleis optional. With a schedule (orevery/once), the declaration is a standalone job: a one-task DAG, paused when first found like any new DAG, whose ID is its reference (e.g.etl-repo:team_a/schedr.toml#report_daily); like any DAG it can also be triggered by hand, and it can also be used from DAGs. Without one, it is a script for DAGs only (decision 296): no DAG, not listed among the DAGs, used only throughScriptOperator(andScriptResource,cleanup_script). Onlyscriptandinterpreterare required; the DAG-level keys (timezone,start,end,initial_since,catchup,max_active_runs,notify,params) are an error there: they would do nothing.To use a script in a DAG, it must be declared in a
schedr.tomlinsideSCHEDR_SCRIPT_PATH, typically without a schedule. There is no way to run an undeclared script file.292. M4.9 in three steps (the user: A, 2026-11-05): M4.9a script roots, reading and checking
schedr.toml, standalone jobs,schedr dags checkfor TOML; M4.9b thescripttask kind on the worker (interpreters, rejections 3-5, theSCHEDR_*variables) andScriptOperator; M4.9cparams,outcomes,[jobs.<name>.cleanup],ScriptResourceandcleanup_script. Each reviewed and documented on its own. Not chosen: one step.293. One reader of
schedr.toml, in the agent (A): Rust checks every key and builds a standalone job’s one-task DAG, so a worker running scripts needs noschedrin Python. A DAG file’sScriptOperatorasks the agent over the runner’s socket and gets the checked declaration back; Python never reads TOML. Not chosen: a second reader in Python (tomllib) forScriptOperator(two readers drifting apart).294. A changed declaration re-parses its DAGs (A): the keys the master schedules with (
queue,retries,retry_delay,timeout,outcomes, a cleanup) come from the declaration at the DAG’s parse; a change to a script root re-parses the DAGs whoseScriptOperators refer into it (the master knows the references), so every key follows the TOML. The worker runs the script at the script root’s hash the master expects (CODE_MISMATCHas for DAG roots). Not chosen: the master’s keys frozen until the DAG’s own file changes (a raisedretriesnot applied).295. A script root a parsing worker lacks is an import error (A): “script root
etlisn’t on this worker”, naming it; workers that parse need every script root their DAGs use. Not chosen: accepted with a warning and checked at run time (the master’s keys unknown until then).296. An unscheduled declaration is a script for DAGs only (B, the user’s): see “
scheduleis optional” above. Not chosen: amanual = truekey making it a one-task DAG for manual runs (one more combination to define, withscheduletoo); every declaration a DAG, every key accepted (a declaration made forScriptOperatorlisted as a DAG, keys that do nothing accepted).298.
notifyis an import error until notifications exist (A, the user’s, 2026-11-05): “notifyisn’t available yet”, naming the job; schedr has no server channels yet. Not chosen: its shape checked and the key ignored with a warning (a key doing nothing); dropped from the design (brought back with notifications).299. A script root and a DAG root can’t share a name (A, 2026-11-05): a startup error naming both paths, as for two DAG roots;
[scripts.roots]renames one. A name means one directory in logs, the UI and references. Not chosen: names by kind (etlboth a DAG and a script root, every mention saying which).300. A standalone job’s task is named after the job (A, 2026-11-05): the DAG
etl:team_a/schedr.toml#report_dailyhas one task,report_daily; a job name is letters, digits,_and-(anything else an import error naming it), so it is a task ID too. Not chosen: a fixed task IDrunfor every job (the same name on every job’s page).301. A script root’s change reaches the DAGs through their root’s hash (A, 2026-11-05): the agent reports a DAG root’s hash with the hashes of the script roots its last parse used folded in, so a change to one of them is a new hash: the DAG root is parsed again (decision 294) and its tasks go to workers with both roots at the parsed code (
CODE_MISMATCHas ever). The master’s discovery doesn’t change. A root that starts using a script root is parsed once more after its first parse. Not chosen: every script root folded into every DAG root (any script change re-parsing every DAG root); the master re-parsing the same hash (discovery keyed on (root, hash) reworked, with a migration).302.
ScriptOperator’s overrides (A, 2026-11-05):args=replaces the declared list;env=is merged per variable, the operator’s winning;secrets=adds to the declared ones. Not chosen: every override replacing the declared value whole (anenv=dropping the TOML’s other variables).303. A worker lacking a script root a DAG root uses doesn’t report that DAG root (A, 2026-11-05): it can’t fold the same hash (301), so it leaves the root out: it neither parses it (as 295 requires) nor runs any of its tasks, and warns naming the missing script root. Not chosen: reporting a hash without it and rejecting only the script tasks (its different hash could become the root’s newest code, its parse full of 295’s import errors replacing the good one, unless discovery gained a rule against it). Refined (the user’s, 2026-11-05, after Codex’s review of M4.9b): a script root no alive worker has reported for a grace (5 minutes, counted from the master’s start too;
SCHEDR_HIDDEN__MASTER__SCRIPT_ROOT_GRACE) is left out of what the master sends (304): no worker could fold it, so every worker would withdraw the DAG root and a fix to its files (say, a typo in the root’s name) would never be parsed. A reference to it stays an import error (295). The grace keeps a restart of the workers having it, or of the master, from dropping it meanwhile. Not chosen: live workers only (a restart briefly replacing a good parse with import errors); any root ever reported, stored (a removed root withdrawing DAG roots until someone clears it).304. The master tells workers which script roots each DAG root uses (A, 2026-11-05): a parsed file records the script roots its
ScriptOperators asked for; the master sends each root’s set, from its current parse, to every worker at registration and when it changes, so every worker folds the same ones. Each stored file keeps its script roots (parse_files, in place before 1.0), so a restarted master sends the same; a file whose import failed for a missing script root (295) records it too. Not chosen: each worker learning from its own parses (a worker that never parsed the root, or just restarted, reporting the plain hash: workers disagreeing).306. A
ScriptOperator’s reference is checked by a parse only (A, the user’s, 2026-11-05): outside a parse (plain pytest,schedr.testing, a task’s runner importing its DAG file) the operator only records its reference: no agent to ask, and a task’s import must not fail on it.schedr dags checklooks references up in the configured script roots (SCHEDR_SCRIPT_PATH), so a typo is caught before deployment. Not chosen:schedr.testingchecking references itself (an idea for later); aDagHintoutside a parse (noise in every test and task import).310.
[jobs.<name>.params]: every TOML value with a clear type (A, the user’s, 2026-11-05): a string, an integer, a float, a boolean, a date, a date-time (without an offset, in the job’stimezone, asstartis), a list of one such type, a nested table as an object. An empty or mixed list, an empty table, or a time without a date is an import error naming the key: its type can’t be told. A trigger replaces a nested table whole. Names are letters, digits and_, sodag_ctx.params.xreads them. Not chosen: scalars only (jobs taking less than DAGs do).311. A declaration’s outcomes apply; routing on them needs an enum (A, the user’s, 2026-11-05):
[jobs.<name>.outcomes]names exit codes, as anOutcomeenum does, so aScriptOperatorwithoutoutcomes=still succeeds on them..on(...)and.outcometake enum members, and the TOML has none:outcomes=Checkgives one and replaces the declared ones; without it onlyDefaultOutcome.SUCCESScan be routed on, if declared, and.onof anything else or.outcomeis a parse error saying so. Not chosen:.on("NO_DATA")(no type checking, two forms of one thing).312. A resource refuses a declaration that contradicts it (A, the user’s, 2026-11-05): a resource’s setup and cleanup succeed only on exit 0, so
ScriptResourceandcleanup_scriptnaming a declaration with[outcomes]is an import error; so iscleanup_scriptnaming one with[cleanup](a cleanup of a cleanup). AScriptResourcesetup keeps[cleanup], asCommandResource(cleanup=)does: its own, for a setup failing halfway. A script for both uses is declared twice. Not chosen: ignoring those keys (a script exiting 3 fails though its file calls that a success).313. Settings of a declared cleanup and a
cleanup_script(A, the user’s, 2026-11-05): aScriptOperatororScriptResourcemay change a declared[cleanup]’s settings (cleanup_timeout,cleanup_retries,cleanup_retry_delay,cleanup_anywhere), the operator winning over the declaration, the declaration over the DAG’s defaults, asretriesdoes; its script stays the declared one, and acleanup_*on a declaration without one is a parse error. Acleanup_script’s options win over the declaration’s settings, which win over a cleanup’s defaults (3 tries, 30 s, the setup’s queue). Not chosen: no overrides (StepDefaults’ cleanup settings would need a rule of their own).314. A worker that couldn’t run a task’s cleanup script rejects the task (2026-11-05): the cleanup’s interpreter or script missing there is rejection 3 or 5, as for the task’s own, so the task isn’t run where its cleanup would fail, and a moved cleanup goes on to a worker that can. A cleanup script runs with its task’s environment and working directory (
[jobs.<name>.cleanup]has neither key). Not chosen: failing the cleanup when it starts (a failed run for a difference between workers another worker could have covered).Run information (no t-strings or other templating in TOML) is passed as environment variables, set by the agent for every
scriptandcommandtask:SCHEDR_DAG_ID,SCHEDR_RUN_ID,SCHEDR_RUN_KIND,SCHEDR_TASK_ID,SCHEDR_MAP_INDEX(mapped tasks only),SCHEDR_TRY_NUMBER,SCHEDR_PLANNED_FOR,SCHEDR_SINCE(times in ISO 8601).
ScriptOperator¶
ScriptOperator("report", job="etl:team_a/schedr.toml#report_daily",
args=["--day", t"{dag_ctx.run.planned_for}"])
Refers to a declaration by its reference string, the same format as the job ID (absolute
"/path/schedr.toml#name"also accepted). Checked at parse time (file exists, job declared); otherwise an import error.Takes everything except the DAG-level keys (
schedule,every,once,timezone,start,end,initial_since,catchup,max_active_runs,notify,params) and can overrideargs,env,secrets,queue,retries,retry_delay,timeout,max_output_size,outcomes(anOutcomeenum).In the operator,
argsandenvvalues may be t-strings / output references (rendered by the agent; argument lists, so no shell quoting needed).It is the only script operator: there is no operator that runs a script file directly.
Also exposed in
schedr.airflow, so migrated DAGs can call declared scripts without mixing APIs, atschedr.airflow.providers.schedr.operators.script(schedr as one more “provider”, following Airflow’sproviders.<provider>.operators.<module>convention; it can never collide with a real Airflow module).
SchedrScriptOperator (Airflow layer)¶
The native ScriptOperator stays as it is. A separate Airflow-like class,
SchedrScriptOperator (provider-prefixed, like SnowflakeOperator), parametrizes a
ScriptOperator and adapts its result so it behaves like a standard Airflow operator:
from schedr.airflow.providers.schedr.operators.script import SchedrScriptOperator
SchedrScriptOperator(
task_id="report",
job="etl:team_a/schedr.toml#report_daily", # forwarded to ScriptOperator
args=["--day", t"{ds}"], # forwarded (overrides)
env={"MODE": "full"}, # forwarded (overrides)
output=OutputMode.LAST_LINE, # how stdout becomes .output
skip_on_exit_code=99,
retries=2, execution_timeout=timedelta(minutes=30), default_args=..., trigger_rule=...,
)
Name:
SchedrScriptOperator(provider-prefixed, likeSnowflakeOperator), so it isn’t confused with the nativeScriptOperator.Parameters: the
ScriptOperatoroverrides (job,args,env,secrets,queue,timeout,max_output_size,outcomes) are forwarded; standardBaseOperatorarguments (task_id,retries,retry_delay,execution_timeout,trigger_rule,default_args,doc_md, …) work as on every Airflow-layer operator.Output parsing, built in (no user code):
.outputcomes from theProcessResultvia a fixed set of modes:LAST_LINE(default, likeBashOperator),STDOUT(all of it),NONE.JSONandJSON_LAST_LINEare dropped: they parse stdout, which the native API doesn’t do; no migration cost, since no Airflow DAG uses this schedr-only class; for structured output, a downstream Python task parses.stdout.LAST_LINEis produced likeBashOperator’s.output(a hidden native task, see Thin translating classes). A user-supplied Python callable (like Airflow’soutput_processor) is not supported.Reporting like Airflow:
skip_on_exit_code(default 99) skips the downstream tasks, as forBashOperator(translated onto outcomes: see Airflow compatibility,skip_on_exit_code); any other failing exit code fails the task with an Airflow-style error summary (“script returned non-zero exit code N” plus the tail of stderr) shown in the UI.
Master–worker protocol¶
gRPC over HTTP/2 (
tonic), typed with Protobuf. Internal only (workers ↔ master).Workers always open the connection to the master’s Service; the master never connects to workers. (Log requests are separate: the webserver connects to workers.)
Each worker keeps one long-lived bidirectional stream for control messages. Over it the master can send work, cancellations, etc. immediately, even though the worker opened it.
Plain request/response (unary) calls alongside the stream for bulky one-off messages (e.g. parse results with serialized DAG JSON).
Cancellation grace time (between SIGTERM and SIGKILL): owned by the master’s configuration, default 30 s. If a task finishes just as a cancel arrives, the finished result wins; the UI notes that the cancel came too late.
Delivery is at least once. Any message may arrive more than once; the attempt ID makes repeats harmless (e.g. a second
Finishedfor the same attempt is acknowledged and ignored).Protocol versioning:
major.minor. The master accepts workers with the same major and an equal or lower minor version. Upgrade order: master first, then workers, so rolling upgrades work and an old worker is never sent something it doesn’t understand.Standalone mode uses the same gRPC protocol (over localhost) as the distributed setup, not a separate in-process transport: less code, same code paths. In
standalonemode TLS is disabled (everything listens on localhost).schedr standaloneruns the master’s gRPC service ([master] grpc_port, 8070), the REST API ([webserver] port, 8080), the master’s loop ([master] tick_interval, 1 s) and one worker agent in one process, all on127.0.0.1; Ctrl-C stops them together.It migrates the database at start with
--migrate(2.10; before, always: a laptop has no separateschedr db migratestep) and, without[database] url, uses SQLite in the data directory (<data_dir>/schedr.db).The data directory (task logs, the SQLite file) is
[worker] data_dir, else$XDG_DATA_HOME/schedr, else~/.local/share/schedr.The worker’s identity and capacity:
[worker] id(else the host name),slots(2),queues(none:default),pass_env;[dags] parse_file_timeout(60 s) per file.
The largest message from a worker:
[grpc] max_message_size, 64 MiB by default, from 4 MiB to 1 GiB (decision 58A, the user’s, 2026-10-29; fixes B30), announced to each worker inRegistered(max_message_size). Not chosen for 58: B a fixed 64 MiB (nothing to raise for a very large root); C the upload split per DAG (a protocol change, andFinishedstill needs a limit).A parse upload is a stream, a file a message (decision 62, the user’s, 2026-10-29; fixes B35):
UploadParseResult(stream ParseResultPart), the header first, then each file, so only one file’s size counts, not the root’s. A single file past the limit is uploaded as its import error (ParseResultTooLarge, naming the setting), so it shows instead of the job being refused and handed out again every 10 minutes. The upload runs in a task of its own, so the worker’s heartbeats go on meanwhile (B34). Not chosen: reporting a refused upload as an import error of every file (the root’s DAGs all broken until the setting is raised).A result that can’t reach the master (decision 61, the user’s, 2026-10-29; fixes B33): a message past the limit on the worker’s stream ends the whole stream, so two checks keep results under it. When a DAG loads, a task whose
max_output_sizecan’t fit (a command’s two streams counted, 64 KiB left for the rest) is refused, naming the task and the setting. When an attempt ends, the agent turns a result past the limit into a failed attempt,output_too_large(not retried), before journalling it, so it is never sent whole, not even again inRegister. Not chosen: either check alone (the load check misses a limit lowered later; the run check lets DAGs that can never succeed load).
Mutual TLS from the start: master and workers verify each other’s certificates. Certificates are files mounted from Kubernetes Secrets (how they are issued is a deployment concern).
tls.mode = "app" | "mesh".app(the default): schedr’s own mTLS on every internal link, as below, plus signed tokens on the workers’ log endpoint.mesh: behind a service mesh that provides mTLS between pods (e.g. Istio), schedr sends plain traffic to its sidecar and does no app-level mTLS and no log tokens; the whole namespace is trusted (all schedr pods in one namespace; which other namespaces may reach it is controlled by the mesh). So schedr doesn’t repeat what the mesh does. Long-lived streams (master ↔ worker, SSE) keep alive with heartbeats (10 s / 15 s), within Envoy’s idle timeouts; no VirtualService timeouts on these routes.Each worker has a fixed number of task slots, set in its configuration. The master never assigns more concurrent tasks to a worker than it has slots. Watcher slots are separate (
[watchers] slots, see Sensors and triggers): wait steps and triggers never use task slots.Heartbeat interval, lease timeout and grace period are configurable, with defaults.
Running tasks can be cancelled from the UI (the master sends a cancel command to the worker over the stream).
Defaults: heartbeat every 10 s; a worker with no heartbeat for 60 s is considered lost; 2 slots per worker.
Cancellation (UI and CLI): SIGTERM to the task’s whole process group, then SIGKILL after a configurable timeout. The attempt ends as cancelled (not failed) and is not retried. A whole run (
schedr runs cancel) or one task (schedr tasks cancel, see Task assignment). When the main process exits first (decision 100, the user’s, 2026-10-30: A; B55): what is left of its group keeps the rest of the grace period, then is killed; with nothing left the stop ends at once. Before, the stop ended with the main process, so a child ignoring SIGTERM and holding the output open hung the attempt for ever. Not chosen: B killing what is left at once (a wrapper script’s child still shutting down cleanly would lose its grace).mTLS details: mTLS replaces any shared token; certificates are reloaded when the files change (rotation without restart); the same mTLS setup is used for every internal link (master ↔ worker, webserver → worker logs). There is no webserver → master link (see Web UI and CLI: the webserver talks to the master through Postgres).
How it is built (M2.7), crate
schedr-tls:[tls]:mode(app/mesh),ca,cert,key(PEM files, e.g. from a mounted Secret; the key may be PKCS#8, PKCS#1 or SEC1),worker_name(defaultschedr-worker),reload_interval(default 30 s). One section for every role: each pod runs one role and mounts its own Secret. Standalone never uses TLS, whatever[tls]says (nothing listens beyond localhost but the API). Not chosen:[master.tls],[worker.tls], … (the same keys three times); a third modeoff(plain traffic is whatmeshis; it would differ only by a warning).What is checked: one CA, used only by schedr. Servers (the master’s gRPC, a worker’s log endpoint) require a client certificate signed by it. A worker checks that the master’s certificate names the host of
master_url(a DNS name or an IP address); the webserver checks that a worker’s certificate names[tls] worker_name, whatever address it reached the worker at (pod IPs and pod names change, so a shared certificate can’t list them). A certificate used both ways (a worker’s) needs both theserverAuthandclientAuthextended key usages; giving every certificate both is simplest. TLS 1.3 only, with rustls and the aws-lc-rs provider (already in the build through reqwest, and it builds for musllinux). Not chosen: one certificate per pod naming its IP (needs per-pod issuance, e.g. the cert-manager CSI driver); checking only that the CA signed it (any schedr certificate could pose as the master); checking that a worker’s certificate names its worker ID (worth it only against a compromised worker posing as another).Workers are trusted, and so is the DAG code on them (decision 101, the user’s, 2026-10-30: A, on Codex’s review of B46). Tasks run as the agent’s own user in its pod, so a task can read its worker’s key and act as that worker; a worker can also register under another worker’s ID once that one’s stream is gone, and report its attempts. The checks that a message’s attempt belongs to its sender (
Started,Finishedsince B46, the journal onRegister) stop a confused or buggy worker, not a hostile one. Not chosen: B per-worker certificates naming the worker ID, checked at registration (per-pod issuance, and a task could still act as its own worker); C logging it as a bug for after 1.0.0.Reloading: the files are read again every
reload_intervaland used once all three read and go together; a broken change (a half-written file, a key of another certificate) keeps the previous material and is logged once. New connections use the new material; open ones go on (the master–worker stream keeps its session). Not chosen: inotify (Kubernetes swaps a symbolic link to update a mounted Secret; the reason DAG roots are polled too); a restart (it would interrupt tasks).The handshake is schedr’s own, around tonic and axum (a listener that hands over connections after it; a connector for the worker’s channel), because tonic’s TLS settings are fixed at startup and couldn’t be reloaded. A client that doesn’t finish its handshake within 10 s is dropped, and holds up no one. A handshake refused over a certificate is a warning in the server’s log (
TLS handshake refused, with the reason, e.g.UnknownIssuer); one that just ends (a TCP probe) only at debug level. In TLS 1.3 the client finishes its side before the server checks its certificate, so a refused worker sees the refusal on its first message, asmaster connection lostwith the alert.
Worker lifecycle¶
Identity:
Worker ID: stable across restarts; from configuration, defaulting to the hostname (the pod name in Kubernetes). The worker’s journal belongs to this ID.
Incarnation ID: random UUID generated each time the agent process starts. Lets the master tell a reconnection (same incarnation, tasks probably still running) from a restart (new incarnation).
A registration with a worker ID that already has a live stream is rejected. If the old stream is dead, the new incarnation takes over and the old incarnation’s attempts are reconciled. From then on only the new stream speaks for the worker: messages still arriving on an old stream (its transport open after its lease was lost) are dropped, and its end doesn’t disconnect the worker (B44). A stream of a worker taken for lost is ended at its next message, which changes nothing: the worker registers again.
A message the master fails to handle ends the worker’s stream (decision 108, the user’s, 2026-10-31: A; B101), a database error for instance: its effects are undone, and some messages aren’t sent again on the same stream (a code report, sent once per hash). The worker registers again, reporting its roots and its journal afresh; messages queued behind it are dropped, and the worker sends again what it still needs acknowledged. Not chosen: B the master retrying the failed message itself (a queue of failed messages per worker, kept across rounds, its order against newer messages to decide).
Only the database’s own trouble ends the stream (decision 115, the user’s, 2026-10-31: A; B106). An error of the database itself (unreachable, a time limit, a deadlock, a lock, a busy SQLite) may pass when the message comes again, so the stream ends as above. A message the database refuses for its data (a constraint, a trigger, data that won’t read:
DbError::is_data_fault) would be refused after every reconnect, the worker’s later messages behind it: aFinishedis stored instead as the attempt’s failure, kindresult_not_stored(not retried: the same result would be refused again), with “the result couldn’t be stored: …” and what ran (duration, usage) kept, and acknowledged; any other such message is logged and dropped, and the stream goes on. A registration likewise: an open attempt from the worker’s journal whose start is refused for its data is adopted without that record, its slot taken (B128), so the worker registers and sends itsFinished. Not chosen: B ending the stream on every error (decision 108 as it was: a refused result came back for ever); C dropping a refusedFinishedtoo (its attempt would stay running until its worker is lost).
States (master’s view): ACTIVE → DRAINING → OFFLINE (clean deregistration);
ACTIVE → DISCONNECTED (stream dropped) → back to ACTIVE on reconnect with the same
incarnation, or LOST after 60 s without a heartbeat (its attempts fail and are retried per
retries).
Messages:
Register (worker → master), on every connect: worker ID, incarnation ID, protocol and schedr versions, queues, task and watcher slots, log endpoint address (
[worker] log_addressand the port: the pod’s DNS name through a headless Service in the chart, see Task logs), content hashes per DAG/script root, the names of its configured secret storages (see Secret storage), and the journal summary (running attempts, unacknowledged results).Registered (master → worker): timing settings (heartbeat interval, lease timeout, cancel timeout; owned by the master’s configuration so all workers behave the same) and a decision per reported attempt: continue, kill (already abandoned/reassigned), or ack (result stored; remove from the journal). A continued attempt counts as started (its
Startedmay have been lost with the old stream; it is never taken back for want of one, B50), and is cancelled again if its run or the task itself was cancelled meanwhile (B43).Heartbeat (worker → master), every 10 s by default: free task and watcher slots and running attempts. Kept small.
CodeVersionChanged (worker → master): sent when a content hash changes (after the settle time). A new hash makes the master create a parse job.
Drain:
On SIGTERM: the worker sends
Draining; the master stops assigning to it; running tasks get until the termination grace period, then remaining ones are killed and reported as interrupted; the worker sendsDeregisterand exits.On admin request from the UI or CLI (maintenance): the same, but the worker stays running and idle and can be resumed.
Journal decisions in detail: an attempt the master doesn’t know, or that belongs to another worker: kill. One the master ended (lost, assignment expired) while the worker still runs it: kill. One whose result is stored and that the worker reports finished: ack. One still open: continue (the worker keeps its slot for it, or sends its
Finishedagain); if its run is being cancelled,CancelAttemptis sent again right afterRegistered, since a cancel sent while the worker was away was lost.Refusals: a stream must start with
Register(elseINVALID_ARGUMENT); an incompatible protocol version, a missing worker ID or a worker ID with a live stream end it withFAILED_PRECONDITIONand the reason.Messages for a worker without a live stream are dropped, not queued: an assignment then expires (no
Started), a cancel is sent again on reconnect (above), and everything else is either repeated by the worker (FinisheduntilFinishedAck: on reconnect, and while the stream stays up after one heartbeat interval, then after 2, 4, … up to 32, B41; after 8 such sends the worker reconnects, its journal then settling the result) or recomputed by the master. A worker’s outgoing stream never makes the master wait: a worker 1024 messages behind has stopped reading, and is disconnected (it registers again, its journal reconciled). AStartedorFinishedthat couldn’t be stored keeps its attempt from being taken back as never started, as one waiting for the master’s lock does; so do the attempts a registration’s journal reports while it waits.The master’s loop ticks on a timer: commands, then the scheduler, then dispatching (new runs’ tasks, retries, expired assignments, assignments), then parse jobs past their timeout and workers past their lease. A failing tick is logged and the next one goes on.
FetchInputsstreams an open attempt’s inputs in 1 MiB chunks; for an unknown or ended attempt it answersNOT_FOUND.
Rules:
When the master’s connection drops, the worker keeps running its tasks, reconnects with exponential backoff and jitter (capped at ~30 s), and journals events until it is re-registered.
Schedules missed while the master is down are created when it comes back; with
catchup=Falseonly the most recent missed run is created.Master downtime doesn’t count against workers: after the master starts, every worker’s lease clock starts again from zero.
Nor does a stalled master (B6, fixed 2026-10-23): the lease counts from when a worker’s latest message arrived, not from when the master handled it. Each worker’s stream is read by a task of its own, which records the arrival (
Arrivals, outside the master’s lock) and queues the message; messages are handled in order under the lock as before; a reconnecting worker’sRegisteris recorded as it arrives too. Before, one slow database write holding the lock left the next messages unread, and the round that got the lock first declared live workerslost(seen with 7–8 s Postgres stalls against the tests’ 4 s lease). Not chosen: stamping the arrival without a reader of its own (the messages behind the first stay unread, so only one counts); restarting every lease after a stall, as after a master restart (a worker that really died during it would get a fresh lease too); longer leases in the tests (hides it).A worker that was declared
LOSTand comes back is told to kill the attempts it still runs (they were already failed and retried).The worker’s liveness probe (
/healthzon the ops port, see Observability) checks only the agent’s own health, never whether the master is reachable (otherwise a master outage would restart every worker and kill all running tasks). Workers need no readiness probe.OFFLINEandLOSTworkers stay listed for the same period as log retention, so old logs can still be located (the UI shows them as unavailable).
How it is built (M2.2):
The worker registry is persisted in the
workerstable (state, incarnation, versions, queues, slots, registration time, last heartbeat, when it went offline or was lost). The master is its only writer: onRegister; on every change of state (draining,disconnectedwhen the stream drops,offlineonDeregister,lostpast the lease); and the last heartbeat at most once per heartbeat interval while the worker is connected (any message counts as a sign of life). Gone workers stay in the table (deleting them comes with retention).At start the master reads the registry back: every worker not gone counts as
disconnectedfrom that moment, so its lease starts from zero (master downtime doesn’t count against workers), and one that never comes back islostafter the lease, its attempts with it. Before, attempts of a worker that never returned after a master restart stayed open for ever.A new incarnation ends what its predecessor left: when a worker registers with another incarnation than the one the master knows, the attempts it had started and doesn’t report in its journal end
lost, each using a retry: the crash rule (it may have been the task’s own memory spike;interrupted, which uses no retry, stays for draining), and the same outcome as the lease running out, only sooner (those end with the error summaryWorkerLost: “workerw1stopped answering while the attempt ran”). Attempts not started yet are left to expire, without using a retry. The ended attempts get the error summaryWorkerRestarted: “workerw1restarted while the attempt ran (possibly out of memory)”. With the journal on disk (2.3) the new incarnation reports the results it had, and leaves out the attempts that were running (it stops their processes), so this rule ends those. Not chosen:interrupted(a task crashing its container every time would loop for ever).The journal on disk (M2.3) is one file per attempt,
<data_dir>/journal/<worker ID>/<attempt_id>.json(the worker ID with other bytes than letters, digits,-,_and., and a leading., as%XX, so different IDs never share a journal), holdingrunning(with the process group’s identity once it is spawned) orfinished(theFinishedmessage, protobuf-encoded, as hex). Each write goes to a temporary file, is fsynced, renamed over the old one, and the directory fsynced, before the message it backs is sent:runningbeforeStarted,finishedbeforeFinished. A file goes onFinishedAck, or on an ack or kill decision. An attempt the journal can’t record is rejected withDISK_NOT_WRITABLE; a result it can’t record is still sent (logged: it is lost if the agent restarts before the ack). What ends while the master is away is journalled at once, not when the agent reconnects. An assignment of an attempt the agent already has is ignored (its file isn’t replaced).On start the agent recovers its journal before connecting: temporary files are removed (an unreadable file is logged and removed: nothing was sent for it),
finishedresults are reported inRegisterand sent again on continue, and for eachrunningattempt the process group it left is stopped (SIGTERM, then SIGKILL after 10 s, then up to 5 s for the group to go, so the retry doesn’t start beside it) and the attempt forgotten, so the master ends itlost(above). A group that can’t be signalled stays in the journal (logged), to be tried again at the next start. A file recovery can’t remove is logged; the other records are still reported. The group is identified by its ID and its leader’s start time (field 22 of/proc/<pid>/stat), so a recycled PID is never signalled; once the leader is gone, or without/proc, nothing is stopped.One agent per journal: the agent holds an
flockon<journal>/.lock; a second worker with the same ID and data directory exits at once (its recovery would stop the first one’s tasks). Workers on one host with their own IDs can share a data directory.Not chosen for the journal: an append-only log (compaction and a torn last line to handle), SQLite on the worker (a dependency and a schema for a handful of records); adopting a task left running by the previous agent (its socket to the old agent is gone, so its result can’t arrive) or leaving it running (it would hold memory and run twice with the retry).
The agent reconnects after a backoff that doubles from 200 ms up to 30 s, with jitter (between half the backoff and all of it, so workers that lost the master together don’t return in lockstep), and starts again from 200 ms after a session in which the master registered it.
GET /api/v1/workersandschedr workers listshow every worker the master has seen, gone ones included:WORKER STATE RUNNING QUEUES LAST SEEN WARNINGS(running attempts / slots; the warnings counted, their messages under the table, M2.5.4b;--jsonfor the API’s JSON); a worker drained for maintenance showsactive (drained).Drain on SIGTERM (M2.6): the agent sends
Draining(again after any reconnect), rejects new assignments (“draining”, temporary for the master), and gives its running attempts until[worker] termination_grace_period(default 30 s, Kubernetes’ default; match the pod’sterminationGracePeriodSeconds) minus the drain’s own end: whatever still runs then gets SIGTERM, SIGKILL[worker] drain_terminate_period(3 s) later, and endsinterrupted, run again elsewhere without using a retry; the last[worker] drain_report_period(2 s) is for reporting and deregistering. Once nothing runs, it waits up to 5 s (never past the end of the grace period) for the master to acknowledge the last results, sendsDeregister(the master records itoffline) and exits 0; without a master it exits at once (the journal keeps the results). A second SIGTERM or Ctrl-C interrupts the running attempts at once. A draining worker gets no new parse jobs (one sent before the master knew is left to others), and its unfinished ones go to other workers that reported the same hash. A cancelled attempt keeps its slot until its process has ended and reported, so a drain never ends with a task still running. B9, fixed 2026-10-23: an attempt already being stopped when the drain’s time is up (cancelled, or past itsexecution_timeout, on the 30 s cancel grace) kept that grace, since its stop signal was one-shot and used: the worker outlived the pod’s deadline and never deregistered. A stop now escalates: the reasons come through one channel per attempt (supervise::Stops, which the memory watchdog sends to as well, before its SIGKILL, and which the supervisor reads first), the first decides the status and sends SIGTERM, and while the grace runs a drain’s interrupt brings SIGKILL to at mostdrain_terminate_periodfrom then (the memory watchdog to now); a repeated cancel changes nothing, and a memory kill during a cancel’s grace leaves the attemptcancelled(never retried, as it should). Not chosen: SIGKILLing every group still running at the drain’s deadline from the agent (two places signalling one process); the shorter grace only for stops begun during a drain (misses a cancel just before it). B8, fixed 2026-10-23: the interrupt used the master’s cancel grace (30 s) before SIGKILL, so a task ignoring SIGTERM outlived the pod (killed at the grace period), its attempt endedlostand used a retry (a task withretries = 0failed its run). The two times are set apart, anddrain_terminate_period+drain_report_period>termination_grace_periodis a configuration error. Not chosen: SIGTERM earlier so tasks get the full cancel grace (with the defaults, every deploy would interrupt at once); fixed times (a pod with a long shutdown hook needs more report time). The names end inperiod, liketermination_grace_period(kept: it mirrors Kubernetes’terminationGracePeriodSeconds, the value it must match). Not chosen:drain_terminate_period_before_kill/…_before_deadline(long, as keys and as environment variables);drain_kill_grace(a second meaning of “grace” in the section).schedr standalonedrains its worker first, then stops the master and the API, so interrupted tasks are recorded;schedr dags testinterrupts at once. Not chosen: interrupting at once on the first SIGTERM (every deploy would kill tasks that would finish in seconds); a 600 s default (a pod without the setting is killed at 30 s mid-drain: attempts lost, retries used).Maintenance drain (
schedr workers drain <w>,POST /api/v1/workers/{id}/drain; M2.6): a command; the worker gets no new tasks or parse jobs, its running tasks finish normally (no deadline), and it stays connected and idle (RUNNING shows when it reaches 0) untilschedr workers resume <w>. It is stored in the registry (drained) and so survives restarts of the master and of the worker until resumed, so a pod restarted during maintenance doesn’t take work by itself; tasks that wait for it say “the workers serving queueqare drained”. Resuming is a change in the set of workers:unschedulabletasks get another chance, and hashes it reported while drained get parse jobs. Draining an unknown worker, or resuming one that isn’t drained, is refused. Not chosen: a deadline as for SIGTERM (an operator wanting that cancels the tasks or sends SIGTERM); a drain that ends with the worker’s incarnation. A resume whose follow-up fails is tried again each round (decision 109, the user’s, 2026-10-31: A; B99): the command is applied once, and finding the worker’s parse jobs (a database read) can fail after it; the worker is kept and retried every round until that succeeds, or until it is drained again. The failure is logged and doesn’t fail the round. Not chosen: B the command and its follow-up in one transaction (the parse jobs are in memory, not undone by a rollback).schedr masterandschedr webserverlog the address they actually bound (port 0 binds a free port).
Task assignment¶
Worker choice: spread. Among
ACTIVEworkers serving the task’s queue with a free slot, the master picks the one with the most free slots; ties go to the least recently assigned. Keeps load even and makes heavy tasks less likely to share a pod’s memory.No separate
Acceptedmessage. Flow:AssignTask→Started(which means accepted) orRejected→Finished→FinishedAck.Queues route tasks to groups of workers. A worker registers with the queues it serves; a task names one (
queue=); the master assigns a task only to workers serving its queue.There is a default queue named
default. A worker with no queues configured serves the default queue; a task with no queue goes to the default queue.A worker with queues configured serves exactly those queues.
defaultis never added implicitly:queues = ["large"]serves onlylarge;queues = ["default", "large"]serves both.With identical worker images, queues are for e.g. different pod sizes, reserved capacity for critical DAGs, or network access restrictions; not for dependencies.
Order: ready tasks run oldest-ready first (priorities and fairness between DAGs may come later). The assignment is saved to Postgres before
AssignTaskis sent.Concurrency limits (see Native API:
max_active_runs,max_active_tasks,max_active,max_active_per_run): a ready task whose limit is reached staysqueued, with the reason shown in the UI (e.g. “waiting:max_active_per_run(10) reached”). Limits are checked when a task is assigned, against counts the master keeps in memory (decision 88A: rebuilt from the database when it starts; one master holds the lease, so two tasks can’t both take the last place); they count tasks inrunningandcleaning_up(a cleanup still holds the slot) and assigned tasks not yetStarted. When a place frees up, the order stays oldest-ready first among tasks whose limits allow them.EmptyOperatortasks and tasks skipped by branching are completed by the master, without a worker.The master resolves data; the worker renders and executes. The master supplies upstream outputs (as inputs), run information and placeholder values; the worker renders templates (the agent for commands, the Python runner for Python tasks) and runs the task. Connections are fetched on the worker; secrets never pass through the master.
No
Startedwithin ~10 s: the assignment is taken back and the task requeued without using a retry. If the worker reports it later, it is told to kill it.Retries are decided by the master. An attempt interrupted by draining does not use a retry; one ended by a lost worker or container crash does (it may have been the task’s own memory spike). Failures certain to repeat are not retried (e.g. a secret that is not found or not permitted, see Secret storage); the master learns this from the error kind in
Finished.Try number and retries: the try number counts every attempt (
dag_ctxand the UI show it); the retry budget counts only attempts that used a retry. So an attempt interrupted by draining or never started is try 2 without using upretries.Never retried (certain to repeat): the error kinds
secret_not_found,secret_denied,input_mismatch,output_not_serializable,output_too_large,result_not_stored(the database refused the result, decision 115),inputs_too_large,render_failed(a command’s templates can’t be filled in from these inputs). A secret storage that is down (secret_unavailable), an import error, a task no longer in its file (task_not_found) and a DAG file gone from the newest code (dag_file_missing) are retried: they can pass, or new code can fix them.Code that changed under a run (M2.5): a run keeps the DAG version it started with, but workers have only the newest code. A command task still runs (its command travels in
AssignTask); a Python task whose task or file is gone fails (task_not_found, ordag_file_missingwhen the worker has the root at the expected hash but not the file: the file is gone, not on its way, so it fails at once instead of waiting as “code not there yet”). When the DAG changed after the run started, the master puts that first in the error summary: “taskloadwas removed from DAGsync(etl:team/sync.py) after this run started”, “DAGsyncmoved from … to …”, or “DAGsyncwas removed from …”. The task is retried by itsretriesand then fails the run;schedr tasks cancelends itcancelledinstead. Not chosen (for now): aremovedtask state that counts as skipped, as Airflow has (the run would carry on without data a removed task would have produced; to decide with the UI, M3).While a run is being cancelled nothing runs again: an attempt that fails then is not retried (the failure counts, and the run ends
failed), and one interrupted or never started becomescancelled. A queued run that is cancelled endscancelledat once.A cancelled task cancels the tasks downstream of it (they can’t run without it, and nothing failed).
Cancelling one task (
schedr tasks cancel, M2.4) works on any unfinished task: one that hasn’t started (scheduled, queued, up for retry, unschedulable) iscancelledat once; one that runs is marked (task_instances.cancel_requested_at) and getsCancelAttempt. Whatever then ends its attempt (the cancel, a rejection, an expired assignment, a lost or restarted worker) ends the taskcancelledwithout a retry; a failure meanwhile stays a failure. The same holds while a whole run is being cancelled (an attempt lost then wasfailedbefore M2.4). The run goes on with its other tasks and ends by the run result rule. Like every action it is a command the master applies. A task of a run whose tasks don’t exist yet (a queued run) is refused: cancel the run instead. Not chosen: running tasks only (a queued task couldn’t be stopped without cancelling the whole run); turning a queued run’s task cancel into a run cancel (surprising).A rejection of a task being cancelled (the task, or its whole run) cancels it instead of queueing it again (B5, fixed in M2.4: a cancelled run whose assigned task was rejected stayed
runningfor ever, since a cancelled run’s tasks are never assigned).A task that waits says why (shown with it in
runs getand the API): “no active worker serves queuegpu”, “every active worker serving queuelargerejected it”, or “waiting for a free slot on the workers serving queuelarge”.Empty tasks are completed by the master as soon as they are ready, with outcome
SUCCESSand no output.Parse jobs are assigned with
AssignParseover the stream; the result (DAG JSON, import errors per file) is sent with a unary call. Each worker has one dedicated parse slot, not counted against task slots, with its own memory budget.Task specification (
AssignTask) contains everything needed to run one attempt:Identity: attempt ID; DAG ID, run ID, task ID, map index, try number.
Kind and what to run:
python(DAG file reference + task ID),command(command template),script(script reference: root,schedr.tomlpath, job name).Expected code hash (the worker reports a mismatch).
Inputs: upstream outputs used by the task, and run information.
Execution settings: environment variables, working directory, interpreter (scripts),
execution_timeout, cancel grace time, memory budget,setrlimitopt-in.
On the worker, before a process starts: an assignment that doesn’t read is rejected as an invalid specification; a DAG root or file missing here is “code not there yet”; no free slot is temporary. A command whose templates can’t be rendered is accepted and fails at once (
render_failed), as does a process that can’t be started (start_failed, retried: the interpreter may be fixed); a Python runner that exits 0 without reporting a result fails withrunner_failed(retried). A command’sProcessResultis its output on success and its error summary on failure. Python tasks run in their root’s directory, commands in their DAG file’s directory; each attempt’s log is<log_dir>/<attempt_id>.log.A task’s timeout counts from its launch (decision 116, the user’s, 2026-10-31: B; B56): a Python task’s runner start (up to 30 s for its hello) is part of the attempt, so its
timeoutruns from when the worker starts launching it, and a task never runs past launch plus timeout (more robust, the user). A cancel or the timeout arriving before the hello stops the runner then, as a running task is stopped (SIGTERM, the grace, SIGKILL), and the attempt endscancelledortimed_out, notstart_failed30 s later. So do waiting for a fork server (another runner’s fork may hold it; a fork abandoned midway restarts that server) and sending the request (a runner that reads nothing). Not chosen: A the timeout starting at the hello, as before (start-up bounded by the 30 s hello limit only; a tight timeout wouldn’t fail for slow imports on a busy worker).The timeout covers the whole attempt, secret and connection reads included (decision 213, the user’s, 2026-11-04; B160; extends decision 116): the process gets only what is left of
timeoutafter the worker reads the attempt’s secrets and connections. A 500 ms read and an 800 ms command with a 1 s timeout endtimed_out; with a long enough timeout they succeed. If the read uses all the time, no process starts; the attempt endstimed_outand its connection files are removed as on every other end. A command’s slow start counts too, as a runner’s does (Codex’s review). Not chosen: the timeout covering only the process, a slow storage not counting against it (a task running past launch plus timeout); a separate limit for the fetch (two limits to configure and reason about instead of one for the attempt).The worker’s journal holds running attempts and results not yet acknowledged, reported in
Registerafter a reconnect; in memory in M1, on disk since M2.3, surviving an agent restart (see Worker lifecycle).Before registering, the agent waits for each root’s first content hash (it settles too). A parse job is run only if the root still has the job’s hash; a failed parse job is logged and left to the job timeout, which gives it to another worker (or this one again).
Over the inputs cap the attempt fails at once with error kind
inputs_too_large, never retried (the same inputs always are too large). Inputs are the outputs of the upstream tasks the task’s references name, as{task_id: output}.Input size: small inputs travel inside
AssignTask; when the total exceeds a threshold (default 4 MB, gRPC’s default message limit) the worker downloads them separately in chunks with a unary call. A configurable cap on total inputs per task (default 64 MB) makes the task fail clearly instead of overloading anything.Attempt statuses (how one try ended):
Status
Meaning
Decided by
successExit code 0, or the Python function returned normally
Worker
failedNon-zero exit code or unhandled exception (incl.
ImportError)Worker
timed_outExceeded
execution_timeout; killed by the workerWorker
oom_killedKilled by the memory watchdog for exceeding its budget
Worker
cancelledCancelled by a user
Worker
interruptedKilled when a draining worker’s grace period ended
Worker
lostThe worker disappeared
Master
assignment_expiredNo
Startedwithin ~10 sMaster
How the agent decides the status: a process the agent stopped (timeout, cancel, drain, memory) gets the status of that reason, however it then ended (a task that exits 0 on SIGTERM after its timeout still
timed_out); otherwise an exit code of the task’s outcomes (default0) issuccess, any other exit code or a signal isfailed. A process killed by a signal reports exit code128 + signalin itsProcessResult, as shells do.Durations are the worker’s: the agent times each attempt with a monotonic clock and sends it in
Finished; it is stored with the attempt (duration_ms) and is what the API,dags testandrun_dagshow. The attempt’sstarted_at/ended_atare the master’s wall clock when it handledStarted/Finished(“when”, not “how long”): never subtracted, since a wall clock can step (B1: a negative duration after a WSL2 clock resync).Finishedcontains: the attempt status, the exit code or signal, the (output, outcome) pair on success (see Task results and outcomes; forcommand/scripttasks the output is aProcessResultwith stdout and stderr), the duration, the peak memory, and an error kind for failures schedr itself recognises (e.g.secret_unavailable,secret_denied,secret_not_found).When stdout/stderr exceed the output size limit, the output keeps the last part (up to the limit) and is marked
truncated. A downstream task that reads a truncated output gets an error, so partial data is never used silently. The full stdout/stderr are always in the task’s log file.Inline commands (
commandkind) produce their output the same way as scripts (aProcessResult). The Airflow layer exposes the last line of stdout through.outputfor compatibility.Failed Python tasks include a structured error summary: exception type, message and the last lines of the traceback, so the UI can show it without opening the log.
Run states:
queued(created, waiting formax_active_runs; manual, chained, event and backfill runs wait, scheduled ones are missed instead, see Runs: manual runs, backfill and pausing),running, and the resultssuccess,failed,cancelled(set once every task and cleanup has finished, by the run result rule, see Outcomes, failures and joins: Run result).Task instance states (where the task stands in its DAG run, decided by the master from attempt statuses, retries and the DAG structure):
scheduled,queued,unschedulable,running,cleaning_up(the task’s process has ended and its per-task cleanup is running; the slot is still taken and downstream tasks wait),up_for_retry,success,failed,cancelled,skipped,upstream_failed.Two attributes next to the state instead of more states: the outcome (on success) and the cleanup result (
ok,failed,didn't run: worker lost,not needed), shown together, e.g. “success ·Unavailable· cleanup failed”.Resources have their own instance per run, with their own states:
waiting for users,cleaning_up,cleaned,cleanup_failed,not needed(the setup didn’t succeed).
Plain scripts are one kind of task, whatever the language. A Bash script is treated exactly like a Python script, only run with a different interpreter. Task kinds:
python: a Python function from a DAG file (the runner imports the DAG and calls it).command: an inline command (e.g.BashOperator’sbash_command).script: a script file declared in aschedr.toml, run with an interpreter (Python, Bash, …).sensor: a wait step (@sensor,@sensor.poke), run in the worker’s watcher host on a watcher slot (see Sensors and triggers).
Interpreters are named in the configuration file, in an
[interpreters]section, so each worker image can map names to its own paths and virtualenvs:[interpreters] python = "/usr/bin/python3" bash = "/bin/bash" etl-venv = "/opt/venvs/etl/bin/python"
A
schedr.tomldeclaration picks one with aninterpreterkey naming an entry from[interpreters]. The key is required: there is no default from the file extension.Shebang lines are ignored; only the
interpreterkey counts.If the named interpreter isn’t defined on the worker, the worker rejects the task with a clear reason (e.g. “interpreter
etl-venvnot defined on worker-1”).
Task rejections¶
A worker may reject an assigned task (Rejected instead of Started). A rejection never
uses up a retry. Reasons and how the master reacts:
# |
Reason |
Example |
Reaction |
|---|---|---|---|
1 |
No free slot |
Master’s view of slots momentarily out of date |
Temporary: requeue immediately, any worker |
2 |
Worker draining |
Drain arrived just as the task was assigned |
Temporary: requeue immediately, any worker |
3 |
Interpreter not defined |
|
Worker-specific: don’t offer this attempt to this worker again |
4 |
Script root unknown |
Root not in this worker’s |
Worker-specific |
5 |
Script reference not found |
|
Code not there yet: retry after a short delay, any worker |
6 |
DAG file missing |
The |
Code not there yet |
7 |
Memory budget too large |
Task asks for more than this worker’s pod limit allows |
Worker-specific |
8 |
Disk not writable |
Journal or log directory full or read-only |
Worker-specific; also a warning on the worker in the UI |
9 |
Invalid specification |
Message can’t be decoded, unknown task kind |
Worker-specific (bug or version mismatch) |
Worker-specific reasons: the master tries other eligible workers. When every eligible worker has rejected the attempt, the task instance becomes unschedulable, shown in the UI with each worker’s reason. It is tried again only when the set of workers changes or a user retries it (
schedr tasks retry, or the UI). Retry is allowed only forunschedulabletasks of a run not yet finished; it doesn’t conflict with “no clear”, which is about re-running finished runs.Code not there yet (e.g. git-sync on that pod hasn’t pulled the new commit): retry after roughly the sync interval plus settle time, workers that haven’t said so asked first. Marked unschedulable once every eligible worker said so (or rejected it for a worker-specific reason: both count) and the code has been missing for
[master] code_wait(default 10 min), with each worker’s detail. Which workers rejected a task is forgotten once it starts somewhere, so a later retry waits afresh. Not chosen: the wait alone (a worker that has the code but was busy would be ignored).A rejection takes the assignment back: the attempt isn’t kept (it was never a try) and the try number goes back; the reason is shown on the task (e.g. “waiting for the code on the workers: …”, or for
unschedulableevery worker’s reason). Which workers rejected a task for a worker-specific reason is kept in the master’s memory: a master restart, or a change in the set of workers (a new worker, or a restarted one), gives the task another chance. Code not there yet retries after 35 s (the default poll interval plus the settle time), and becomesunschedulableafter the code wait (above).schedr tasks retryqueues anunschedulabletask of an unfinished run again and forgets which workers rejected it; anything else is refused with what to do instead (a failed task is retried by itsretries; a finished run needs a new run).A
Startedfor an attempt that was taken back (noStartedin time), ended, or belongs to another worker is answered withCancelAttempt.An import error in a DAG file is not a rejection: the agent can’t detect it without starting Python, so it is an ordinary task failure with the
ImportErrorin the error summary.
Worker memory protection and crash recovery¶
All tasks on a worker share the pod’s memory limit. On cgroup v2 (current OpenShift / Kubernetes 1.28+), an out-of-memory event kills every process in the container: all tasks and the worker agent. schedr therefore uses both:
Memory watchdog in the worker agent: about once a second it measures each task’s memory (summed over the task’s process tree, from
/proc) and kills only the task that exceeds its memory budget, reporting the exact reason (e.g. “exceeded memory budget 2 GiB”). Needs no privileges; negligible overhead. The watcher host is watched the same way as one process with its own budget ([watchers] memory_budget); killing it stops every wait step and trigger on it (see Sensors and triggers).Journal on the worker’s disk of the attempts it is running and of finished results not yet acknowledged by the master. If the container dies anyway (memory spike faster than the watchdog, node failure, eviction), the restarted agent reads the journal, stops the task processes left running and doesn’t report their attempts: the master ends them
lostwith the error summaryWorkerRestarted: “worker restarted while the attempt ran (possibly out of memory)”, each using a retry. Finished results saved on disk are not lost.
Watchdog budget: by default (pod memory limit − reserve for the agent, about 10 %) ÷ slots.
The limit is read from /sys/fs/cgroup/memory.max (no privileges needed). Configurable per
worker, later per task via the API; the check interval is configurable.
Optional hard cap per task with setrlimit (RLIMIT_DATA / RLIMIT_AS): opt-in per
task, off by default. It is crude (counts reserved, not used, memory; breaks programs that
reserve a lot up front), but fails the allocation inside the task immediately.
Per-task cgroups are ruled out: they need write access to the cgroup filesystem, which OpenShift’s restricted security policy doesn’t grant.
How it is built (M2.8), crates/schedr-agent/src/memory.rs:
What is measured: the PSS (
/proc/<pid>/smaps_rollup) of every process in the task’s process group (what SIGTERM and SIGKILL reach), RSS (/proc/<pid>/statm) where PSS can’t be read, except for a task forked from a fork server (M2.5.4a): its RSS counts the pages it shares with the server, so a sample without every PSS is skipped instead (a zombie, holding no memory, counts as nothing; B54). PSS splits shared pages between the processes sharing them, so a task with many processes isn’t counted many times, and the fork server (M2.5) needs it anyway. A process that leaves the group (setsid) isn’t counted, as it isn’t cancelled. Not chosen: RSS (shared libraries counted once per process); the tree by parent PID (the group is what is killed).The limit: the smallest cgroup v2
memory.maxfrom the agent’s own cgroup (/proc/self/cgroup) up to the root, so a pod and a host alike. None found (max, cgroup v1, macOS): nothing is killed and peak memory is still measured; the worker’s startup line says which (“memory budget 1.8 GiB per task” or “no memory limit found: task memory is measured, never limited”). Not chosen: the machine’s total memory as a fallback (a laptop would kill tasks for memory it has); cgroup v1 (OpenShift 4.14+ and current Kubernetes use v2).The budget:
[worker] memory_budget(a size per task), else (limit − 10 %) ÷ slots; sampled every[worker] memory_check_interval(1 s). The parse runner gets the same budget. A budget below 16 MiB (no Python starts in it) or an interval of 0 is a startup error. Each process is watched from its spawn until it has ended: a runner’s start and a stopped task’s grace period after SIGTERM are covered, and the watch is dropped with the attempt, so a group ID the kernel reuses is never watched. Each watch scans/procon its own (a pod has few processes and a handful of slots); one shared sampler can come if 2.9’s metrics show a cost. Not chosen: ÷ (slots + 1) for the parse slot (smaller budgets for a slot mostly idle); a configurable reserve (memory_budgetcovers unusual pods).Over the budget: the group gets SIGKILL at once (a spike can’t wait for a grace period: the kernel would kill everything first), the attempt ends
oom_killed(using a retry) with the error summaryMemoryBudgetExceeded: “exceeded memory budget 100 MiB (130 MiB used)”. A parse runner keeps every module it imported, so a file that crosses the budget after others in the same runner is tried again first in a fresh runner; only over the budget alone is it an import error (“the runner stopped while importing the file (the runner exceeded memory budget …)”), and parsing goes on with the next file. Not chosen: SIGTERM first, with the cancel grace or a short one.Peak memory: the highest sample goes in
Finished.peak_memory_bytes, is stored with the attempt (0, not measured, as none) and shown in the API’s attempts (peak_memory_bytes).setrlimitwaits for M4, with per-task budgets in the native API: no DAG can opt in before. Setting it in the child needspre_exec, which isunsafe(forbidden here), andprlimitfrom the parent leaves the process unlimited for a moment, so (decision 50A, the user’s, 2026-10-28) a limited task is started throughschedritself: an internal subcommand (schedr task-exec --data-limit … -- <command>) sets the limit on its own process with safe Rust (therlimitcrate) andexecs the task, which inherits it; no window without the limit, one moreexec(about 1 ms) only for tasks that opt in. A task forked from the fork server sets it in the forked child, our own code, before user code. Not chosen: Python tasks only (B: commands couldn’t opt in);prlimitfrom outside (C: the unlimited window). TheAssignTaskfields stay. Watchdog metrics (kills, peak memory) come with the ops port (2.9); the watcher host’s budget with M4.
Worker environment¶
All workers use the same image. There are no worker pools with different images, so any worker can parse any DAG and run any task.
Tasks and DAG files can use only the Python libraries installed in the worker environment. Any additional code must come through the DAG or script roots (e.g. a git submodule, or a symlink).
Task processes get a clean environment by default. They do not inherit the worker agent’s environment variables. A task process gets only: a small allow-list (
PATH,HOME,LANG,LC_*,TZ,TMPDIR), theSCHEDR_*run variables, and the task’s ownenv(with secret placeholders filled in; declaredsecrets=are not in the environment, see Secret storage). The agent’s own variables (configuration, certificate paths, Vault auth, anything from the pod spec) are passed only if listed in the worker configuration ([worker] pass_env = ["HTTP_PROXY", ...]). Layers, later ones winning: the allow-list (and everyLC_*),pass_env, the task’senv, theSCHEDR_*run variables.SCHEDR_*names are reserved: a task’senvsetting one fails the attempt. In the Airflow layer,append_env=True(BashOperator) means “add the allow-listed worker variables”, never the whole agent environment.Each DAG root is added to
sys.pathwhen parsing DAGs and running Python tasks, so helper modules and code from submodules inside a root can be imported.
Expected workload¶
A mix: mainly a synchronization scheduler (many short tasks), plus some heavier or longer tasks (downloads, longer-running commands). No big-data workloads. Starting a fresh Python process per task is acceptable; warm Python worker processes are not needed for tasks. (The one long-lived Python process is the watcher host, for wait steps and triggers, which mostly wait: see Sensors and triggers.) Tasks run on long-running workers (not pod-per-task) because schedr can’t count on permission to create pods.
Rust/Python integration¶
Separate processes. Rust and Python never share a process as a way of integrating schedr: the Rust worker agent starts Python as a subprocess and they talk over a local channel (details below).
The master never runs Python (and neither does the webserver).
DAG parsing runs in a Python subprocess on a worker (
AssignParse, parse slot).Python tasks run in their own Python processes (see How Python tasks are started).
Python talks only to its local worker agent; only the agent talks to the master.
Rejected as the integration mechanism:
Embedding Python in the Rust binary (PyO3): user-code crashes would take the scheduler or agent down, and one Python environment would be forced on every DAG.
A Rust extension module that connects Python to the scheduler.
The Python runner is a module of the
schedrpackage, started by the agent as<interpreter> -m schedr.runner parse,... task,... cleanupor... watchers(-m, so it works with any configured interpreter executable, whatever virtualenv it belongs to). Only the mode and the socket’s descriptor are passed on the command line / environment; everything else comes from the agent over the channel, so no secrets appear in the command line.parse: gets the root and file list from the agent, puts every DAG root onsys.path(a root imports only from itself: decision 103), imports the files one at a time (native API calls only record DAGs), and sends back the DAG JSON and per-file import errors.task: gets the task specification from the agent, imports the DAG file (from the agent’s copy of the root’s current code, decision 102), finds the task by ID, fills in t-strings (secrets fetched by the agent), calls the function, and sends back the output or a structured error summary; exit code 0 or non-zero. Python resource setups (@resource) run in this mode too: a setup is a task.cleanup: liketask, for a per-task cleanup (gets the task’s inputs and the attempt’s handles) or a Python resource cleanup (@<resource>.cleanup, gets the setup’s output).watchers: the worker’s watcher host, one long-lived asyncio process running every wait step and trigger assigned to the worker as coroutines, multiplexed over one socket (see Sensors and triggers). The only long-lived runner; the others handle one request and exit.The runner does not decide retries, enforce timeouts, watch memory or write log files. The agent supervises it from outside (process group, stdout/stderr to the log file, watchdog, SIGTERM/SIGKILL).
Interpreter for parsing and Python tasks: a configuration key naming an
[interpreters]entry, defaultpython:[dags] interpreter = "etl-venv"
The same interpreter is used for parsing and for tasks, so a DAG can’t parse in one environment and fail to import in another.
That environment must have
schedrinstalled at the same version as the agent, plus everything the DAG files import.Plain script tasks don’t use the runner: they run with the interpreter from their
schedr.tomldeclaration, which doesn’t needschedrinstalled.Possible later: an interpreter per DAG root (in
[dags.roots]).
Agent ↔ runner channel: a Unix domain socket pair per runner process. The agent creates a connected pair and the runner inherits its end as an open descriptor, named by
SCHEDR_AGENT_FD; the runner makes it non-inheritable at once, so processes the task starts don’t get it. Files are not enough because a running task can ask for things not known in advance (Connection.get(conn_id), secrets). Messages:task specification and inputs (agent → runner, on request);
secret / connection requests and answers;
outputs, or a structured error summary (runner → agent);
for parsing: per-file progress and results (DAG JSON, import errors).
Why a socket pair, not a path: no socket file, no directory to choose or clean up, no path-length limit (a socket path is limited to about 108 bytes, data directories can be deep), no connect race or timeout, and no other process can connect, not even one of the same user: a runner gets secrets over this channel. Works on Linux and macOS.
Processes are started one at a time (a lock in the agent): the runner’s descriptor is made inheritable only while its own process starts, so it can’t leak into a task started at the same moment. A start takes milliseconds.
More connections (M4.5b, decision 143): a
commandtask’s processes (schedr dag-ctx,schedr.script, several calls at once) get a context channel of their own, a datagram socket (SCHEDR_CTX_FD); each call makes a fresh socket pair and sends one end to the agent over it (SCM_RIGHTS), so it gets a connection of its own. Still no path.Not chosen: a socket file in a short directory (
$XDG_RUNTIME_DIR//tmp, mode0700): a file to clean up, a writable/tmpneeded, and any process of the same user could connect while it exists; an abstract socket (Linux): no file, but no permissions either, safe only with a check of the peer’s process ID, and Linux only.
Encoding on the socket: length-prefixed JSON. Simple to write from Python with no dependencies; messages are small. (Protobuf would add a dependency to the Python package.)
Framing: a 4-byte big-endian length, then that many bytes of UTF-8 JSON: an object tagged by
type. Either side refuses a message over 64 MiB (the cap on inputs per task). The shapes are Rust types inschedr-model(runner), generated intoschema/runner.schema.json.Handshake: the runner sends
hello { schedr_version, mode }; the agent answerswelcome, orrefused { reason }when the versions differ (they must be equal), and the runner exits with code 2.Parse mode: the agent sends
parse { root, root_dir, files, sys_path }; for each file the runner sendsfile_started { path }(the agent times files from it) and thenfile_parsed { path, dags, error }(error: the exception’s class, message and the last 20 lines of the traceback); thenparse_finished.Task mode (one attempt of a Python task): the agent sends
task { dag_file { root, root_dir, path }, dag_id, task, inputs, run, sys_path }: the task as in the DAG JSON, the upstream outputs it references (stored JSON, by task ID) and the run information (dag_id,run_id,kind,planned_for,since,try_number,map_index). The runner imports the file (from the agent’s copy of the code it reported last, decision 102), finds the task’s function, builds each argument from its stored form decoded against the parameter’s type (templates rendered as on the agent), calls it and answerstask_succeeded { output, outcome }(encoded against the return type; outcomeSUCCESSuntil outcome types arrive in M4) ortask_failed { error, kind }.kindis what schedr recognised:task_not_found(the DAG or the task is no longer in the file),input_mismatch(a stored input doesn’t fit the parameter, or a referenced path is missing or truncated),import_failed,output_not_serializable,output_too_large(overmax_output_size), ornullfor the task’s own exception (includingSystemExit). The runner doesn’t enforce timeouts or memory: the agent does.Runner exit codes: 0 done (in task mode: the task succeeded); 1 a failed task or a failure on the channel; 2 a wrong start (unknown mode, no
SCHEDR_AGENT_FD, refused handshake).Module names: each DAG file is imported under a stable name derived from its root and path (e.g.
_schedr_dag_etl_repo_team_a_sync_1a2b3c4d) and kept insys.modules, so dataclasses defined in DAG files resolve; task mode imports a file under the same name.
Parsing granularity: one parse process per parse job (a root whose hash changed), importing files one at a time and reporting progress per file. A per-file timeout (configurable) is enforced by the agent: on timeout it kills the process, records an import error (“timed out”) for that file and starts a new process for the remaining files. A fresh process per parse job avoids stale cached modules.
The import error of a file that timed out is
ParseTimeout; of a file during which the runner died (closed the socket, e.g. a crash in a C extension oros._exit),RunnerDied.The per-file timeout also covers waiting outside a file (starting, the handshake, between files); silence or a closed socket there can’t be blamed on a file and fails the parse job, as do messages out of order.
Trust boundary: a worker is one trust domain. All tasks on a worker run under the same UID, so they are not isolated from each other (a task can read another task’s environment or files), nor from the agent (its key, its Vault login: decision 173). Teams that must be isolated get separate deployments (decision 173). This is stated in the documentation.
Shared model and schemas. Rust types are the reference. Protobuf for gRPC. A JSON Schema generated from the Rust types (
schemars) describes the DAG JSON and the agent ↔ runner messages; it is committed to the repository and CI fails if it is out of date. Python tests validate what Python produces against it. Python-side types are written by hand (no code generation) for now.Compiled Rust extensions as ordinary libraries are fine. A Python package (a user’s dependency, or possibly schedr’s own Python package) may contain a compiled Rust extension used as a library inside the Python process. That is not an integration channel with the scheduler; it just runs inside the task’s or parser’s own process.
How Python tasks are started¶
Now: a fresh process per task. The agent starts a new Python process for every task attempt; it imports the DAG file, runs one task and exits. A straight
1 >> 2 >> 3 >> 4 >> 5DAG starts five processes, possibly on five workers. Main cost: re-importing the DAG file and its libraries for each task.M2.5 (designed, see Roadmap): a fork server as an optional start method. A parent process imports libraries once and forks one child per task attempt, so each task is still its own process (the memory watchdog, timeouts, signal-based cancellation and the journal work unchanged). The runner and the agent ↔ runner protocol must not depend on how the process was started, so this can be added without changing them.
Two fork servers per worker and interpreter, both started upfront (decided 2026-10-27, the user’s): a preloaded one (the
preloadlist imported) and a bare one (onlyschedr), so both are ready when needed. A task or parse job forks from the preloaded one; when it is off (a failed preload, a thread after preloading, crashed and restarting) from the bare one; spawn only when both are off. A task can pick the bare one with@task(preload=False)(also inStepDefaults), for code that misbehaves next to preloaded libraries. Per interpreter because each[interpreters]entry may be a different virtualenv and a child must come from a parent with the same environment; today a worker runs one interpreter ([dags] interpreter), so one pair. Not chosen: one fork server (a bad preload drops every task to spawn); the bare one only as a fallback, or only by choice (C, both, was picked); parse jobs from the bare one and tasks from the preloaded one (parsing imports the same libraries).It preloads only a configured list of libraries, never DAG code; each task child imports its DAG file itself. So the fork server never goes stale on a code push (libraries change only with the image, which restarts the pod), its memory doesn’t grow with the number of DAGs, and no user top-level code runs before
fork().The memory watchdog must measure a forked task’s own memory (PSS/USS from
/proc/<pid>/smaps_rollup), not RSS, so memory shared with the parent isn’t counted against every task.Not planned: a fork server per DAG (memory multiplied by the number of DAGs, restarts on every push to its root, user code run before
fork()).Configuration: per interpreter, off by default. An
[interpreters]entry may be a table; a plain string means spawn:[interpreters] python = "/usr/bin/python3" [interpreters.etl-venv] path = "/opt/venvs/etl/bin/python" fork_server = true preload = ["schedr", "pandas", "sqlalchemy"]
What uses it: Python tasks, Python cleanups and resource setups (runner
task/cleanup), and parse jobs (a fresh child per parse job imports the DAG files; the parent never sees DAG code).scripttasks always spawn, even with a Python interpreter (a plain script expects a fresh interpreter:__main__,sys.argv,atexit; and needs noschedr);commandtasks aren’t Python. A task can opt out with@task(fresh_process=True)(also inStepDefaults), for code that misbehaves after a fork.Process model (decided 2026-10-27, replacing “the agent is a child subreaper”): the agent starts
<interpreter> -m schedr.runner fork_serverwhen the worker starts (the first task is fast; a failing preload shows at once). It shakes hands like any runner (hellowith the modefork_server,welcome), then sendsfork_serverwith the preload list; the fork server imports it, callsgc.freeze(), checks it is single-threaded and answersfork_server_readyorfork_server_disabled(the reason and the threads’ names). Per attempt the agent sendsfork(an ID, the runner mode, the task’s clean environment and working directory) with four descriptors over the socket (SCM_RIGHTS): the task’s own channel (a socket-pair end), the agent’s output pipes as stdout / stderr (as spawn’s pipes: log collection and the kept tail are unchanged; decided 2026-10-27, replacing log file descriptors) and a status socket. The fork server answersforkedorfork_failed(with the reason; tasks then fall back).A shim per task (decision 13A): the fork server forks a shim, the shim forks the task. Both call
setpgid(task, task)(as shells do); the shim’s own call comes before it reportsprocess_started(the PID), so the group exists by then on the status socket; the agent records the PID only then (before it, the group would still be the fork server’s, and a kill or the watchdog would hit the server). The shim waits for the task withwaitid(WNOWAIT), sendsprocess_exited(the exit code or the signal), and reaps the task only after the agent closes its end: until then the zombie keeps the PID and the group, so akillpgfrom the agent can’t reach a reused PID. The shim isn’t in the task’s group: the task’s signals and the watchdog don’t reach or count it (about 0.7 MB USS). It isn’t a subreaper (a task’s leftover processes aren’t collected, as with spawn). The fork server reaps its shims (aSIGCHLDhandler; it never ignoresSIGCHLD, which would lose its children’s statuses).The shim only observes (decision 14A, 2026-10-27): with
process_exitedit reports whether the process dumped core and what it used (ProcessUsage, the parent’srusage, with the children it reaped: user and system CPU, peak RSS, major faults, voluntary and involuntary context switches), for the Attempts tab and the attempts API (M2.5.4b; spawned processes: 18A). The peak RSS of a forked process includes the pages it shares with the fork server (the watchdog’s PSS doesn’t). Keeping the zombie rules outwait4, so it is the rawwaitidsystem call withWNOWAIT(throughctypes: Python’sos.waitiddoesn’t pass therusage; proved 2026-10-27 to give whatwait4gives after reaping). It must never break the shim:ctypesis loaded in the fork server before any fork; the call comes only after the exit was seen (it returns at once); an unknown CPU architecture (the call’s number is known for x86-64 and arm64), a failing call or any exception givesusage: null, and the exit status is reported regardless. The shim never kills, watches memory or handles logs: those stay with the agent. Not chosen: also reporting the processes a task left running (14B).Usage of spawned processes (decision 18A, 2026-10-27): the workspace forbids
unsafeand no safe crate returns a child’srusage, so the agent reads the zombie’s/proc/<pid>/statandstatusbefore reaping it (waitidwithWNOWAITon the blocking pool, one parked thread per running spawned process:AsyncFdon apidfdneedsunsafesince tokio 1.54): CPU time (reaped children included) and major faults (checked 2026-10-27 to matchwait4); peak RSS and the context switches are null for a spawned process (a zombie’s memory is gone; itsstatushas its leader thread’s context switches only, not its other threads’ or reaped children’s: found by Grok’s review of M2.5.4b, 2,711 switches reported as 24;Finished’speak_memory_bytes, the watchdog’s sampled PSS, covers both methods). Unreadable:usagenull. Not chosen: one auditedunsafemodule for the rawwaitid(relaxingunsafe_code = "forbid"); usage for forked processes only.What survives what: a fork server that crashes leaves its shims to
tini(PID 1), and they keep reporting: running tasks and their exit statuses are unaffected. A shim that dies closes the status socket withoutprocess_exited: the agent kills the task’s group and records the attempt as failed with an unknown status. The agent is not a subreaper and uses nopidfd: an agent adopting orphans would need awaitpid(-1)sweep, which Grok measured stealing 38–40 of 40 tokio children’s exit statuses; apidfdon a non-child can’t give the exit status (kernel 6.6) or signal a group (from 6.9), so groups are signalled withkillpg, as for spawn. Not chosen: the fork server as the task’s parent (one fork fewer, about 4 ms faster: 4.1 against 8.5 ms to running at p50, measured 2026-10-27, but exit statuses lost while a fork server is down); the agent as subreaper (above).The task’s child process:
setpgid(0, 0), notsetsid()(a task in an orphaned session discardsSIGTSTP; spawn’sprocess_group(0)issetpgid), the fork server’sSIGCHLDhandler reset (the shim resets it; handlers a preload installed stay, as a spawned process importing the same library would have them), the output pipes on descriptors 1 and 2 and/dev/nullon 0, its environment replaced, the working directory changed, the fork server’s socket and the status socket closed, then the normal runner code with its own channel; it ends withos._exit. Descriptors a preloaded library opened stay open (decided 2026-10-27): their Python objects own them, so closing the raw numbers would let a later garbage collection close a file the task reopened under the same number; the task sees them as if it had imported the library itself. Not chosen: closing every inherited descriptor.The watchdog (M2.5.4a): a forked task shares the fork server’s pages, so its RSS is about 97 % of the server’s; for a forked task whose PSS can’t be read the watchdog skips the kill instead of falling back to RSS.
Safety checks: after preloading, the parent must be single-threaded (checked in
/proc/self/task; forking with threads, e.g. BLAS pools or database drivers, can deadlock the child). A second thread or a failing preload disables that fork server with a worker warning, and tasks fall back (to the bare one, then to spawn): a task never fails because of the fork server’s setup. Linux only: on macOSfork_server = trueis ignored with a warning (fork is unsafe there), like the memory watchdog.State after fork: the child is set up as a spawned interpreter would be from the task’s environment:
randomreseeded (Python’s own at-fork handler), the time zone (time.tzset()),LC_CTYPEfrom the environment and the other locale categoriesC,tempfile’s cached directory cleared (TMPDIR),sys.stdin/stdout/stderrthe interpreter’s own on descriptors 0-2 (a preloaded library may have replaced them), the descriptors blocking whatever the agent made its ends; the libraries’os.register_at_forkhandlers run. Before each fork the server flushes Python’s and C’s stdio buffers (a preloaded extension’s unflushedprintfwould appear in every task’s log).loggingis left as the preload set it (decided 2026-10-27, replacing “resetslogginghandlers”): a spawned task importing the same library would have the same handlers, andloggingre-creates its locks after a fork itself. The server keeps descriptors 0-2 open (/dev/nullif it was started without one), so no received descriptor takes their numbers. Shutting down as an interpreter (decision 15A, 2026-10-27): the process ends withos._exit(it must never return into the fork server’s code), which skips the interpreter’s shutdown, so it does the shutdown’s steps itself, in CPython’s order: it waits for its threads that aren’t daemons, then runs its own exit handlers. When it starts it drops the handlers the fork server registered (atexit._clear(): a preloaded library’s handler may act on the server’s state, e.g. remove a directory it made at import) and keeps two per process, as every interpreter has them:logging’s shutdown (flushes and closes the handlers) andweakref.finalize’s hook, for its own finalizers only (the server’s objects are marked not to run). The order was checked against a spawned interpreter running the same code. A preloaded library’s exit handler doesn’t run per task (in a spawned process it would). Not chosen: every inherited handler (the server’s state); none (a task’satexitflush, a thread left working, a bufferinglogginghandler would be lost). The parent callsgc.freeze()after preloading, so the garbage collector doesn’t copy shared pages in every child (keeps each task’s PSS small).Crashes and versions: a crashed fork server is restarted by the agent with backoff (1 s doubling to 5 min, from 1 s again after 10 min up); running children are unaffected, and meanwhile tasks fall back as above. It reports its
schedrversion like any runner; a mismatch disables it. It can’t go stale (libraries change only with the image, which restarts the pod).A disabled fork server (decisions 19A and 20A, 2026-10-27): one whose preloaded library fails to import is retried with the same backoff for
[worker] fork_server_import_retry(default20m, from the first failure;0s: never), for what isn’t ready when the pod starts (a sidecar’s network, a mount); a failure still there after it is lasting (a missing package, a typo), and the server stays disabled until the pod restarts. Threads after preloading and a version mismatch are never retried: they don’t change until the image does. The log warns on the first failure and when the reason changes, and once more on giving up; the metric showsdisabledthroughout. Not chosen: retrying every cause (a pointless preload every 5 min for the lasting ones); no retry (a passing import failure would make every task of the pod spawn for its life).Visibility: each attempt records its start method (
spawn/fork), shown in the Attempts tab and the attempts API; metrics: fork server up / down per interpreter and kind (preloaded / bare), process start time by start method (built first, in M2.5.1: M2 has no such metric), fallbacks by reason. The start-time metric (M2.5.1, decided 2026-10-27): one histogram,schedr_worker_task_start_seconds{method, phase}(10 ms to about 40 s),methodspawn/fork,phaserunner(from starting the process to the runner’s hello: the interpreter andschedr) andimport(from sending the task to the runner’stask_imported: the DAG file imported and the arguments built; not observed when that fails). Every phase is timed on the agent’s clock: the runner sendstask_imported, a message of no fields, rather than timing itself. The attempts API showsstart_method. Not chosen: two histograms (two reference entries for one question); the import time as a field of the runner’s result (its own clock, and nothing for a task that never returns). A disabled fork server is a worker warning in the REST API’s worker view andschedr workers list(decided 2026-10-27; M3’s UI shows the same field), as well as a metric and a log line. Not chosen: logs and a metric only until M3. How (M2.5.4b): the agent sendsWarnings(all of them,[{kind, interpreter, message}],kindfork_server_disabled, the message saying what it means for tasks) after everyRegisterand whenever they change; the master replaces the worker’s stored list with each report (a failed write is logged, as for the heartbeat); the worker view haswarnings, andschedr workers listaWARNINGScount column with the messages under the table. Usage (14A, 18A):Finishedcarriesusageandcore_dumped, stored with the attempt and shown in the attempts API (usagenull when not read).The chart turns it on for its workers (decided 2026-10-27):
worker.forkServer, the preload list defaulting to the worker image’s libraries exceptpolars, overridable per deployment. Polars starts threads on import (measured 2026-10-27 with Polars 2.0: twojemalloc_bg_thd, which_RJEM_MALLOC_CONF=background_thread:falsestops, and apolars-ooc-cleaout-of-core cleaner, which no setting found stops), so it would fail the single-thread check and turn the preloaded server off on every worker; a Polars task imports it in the child (~1 s). The image’s build runs the same check: it imports the default list and fails if a thread starts, catching a library update that starts one. How (M2.5.5b): the list isimages/schedr/preload.txt(module names:requests,httpx,aiohttp,tenacity,orjson,yaml,dateutil,paramiko,netmiko,ncclient,dns,netaddr,pymongo; 1.7 s to import together, measured 2026-10-27, one thread); the image’s build imports it with schedr’s ownthread_names();worker.forkServer(enabled: true,path: /usr/local/bin/python3, the image’s Python,preload) sets the DAG interpreter’s table form (config.DAGS__INTERPRETER,pythonby default) throughSCHEDR_CONFIG__INTERPRETERS__<NAME>__{PATH,FORK_SERVER,PRELOAD}, for the distributed workers and standalone’s own; the chart refuses to render when that interpreter is also set inconfig(the chart’s path would replace the one given there, found by Grok’s review);make chart-checkfails if the chart’s default list isn’t the file’s (scripts/check-preload-list.py). When the check fails on a worker, the worker’s warning says so, e.g.preloaded fork server off (python): 3 threads after preloading (jemalloc_bg_thd, polars-ooc-clea); tasks fork from the bare server, shown in the API,schedr workers listand M3’s UI. Not chosen: allowing known thread names (a thread holding a lock atfork()deadlocks the child, the failure the check exists for; an allowlist to keep up with each release). The config’s default stays off. Who sets the list: the image’s maintainer (the default, kept with the image’s requirements) and the deployment’s operator (their values); a DAG author only opts a task out (preload=False,fresh_process=True). The guide: preload a library that is slow to import and used by most tasks; never one that starts threads (the log line and the worker warning name its threads; the fallback metric givesdisabled). Not chosen:["schedr"]only (the two servers would hardly differ); off in the chart.
Rejected:
Warm worker pools (long-lived Python processes reused across tasks): globals, leaked memory and old code carry over between tasks; the watchdog can’t tell whose task used the memory.
One process per DAG run or per chain of tasks: breaks per-task retries, timeouts, memory budgets and queues.
Subinterpreters (
concurrent.interpreters) and threads/asyncio in one process: one address space, so no per-task memory limit or signal-based cancellation; a C-extension crash kills every task.Python embedded in the worker agent: user code could crash the agent and every task on the worker.
Checkpoint/restore (CRIU): needs privileges OpenShift’s restricted policy doesn’t grant.
In-task CLI: schedr task-ctx and schedr dag-ctx¶
Commands that only work inside a running task (they talk to the agent over the task’s
context channel, SCHEDR_CTX_FD, each call on a connection of its own; see below), for
command / script tasks, their cleanups and resource setups.
Python tasks use the Python API instead, and plain Python scripts the same objects through
schedr.script (below).
Milestone M4: schedr dag-ctx and schedr.script’s dag_ctx came with M4.5b; schedr task-ctx (secrets, cleanup handles, resource values) comes later in M4, on the same channel.
(It was labelled M1 since the M0 command skeleton, before the channel was designed; M1 never
included it.)
How M4.5b builds it (decisions 143-148, the user’s, 2026-11-01):
143. The caller sends its own end. A
commandtask inherits one end of a datagram socket pair (SCHEDR_CTX_FD, a descriptor number), and so does every process it starts. Each call makes a fresh stream socket pair, sends one end to the agent over the datagram socket (SCM_RIGHTS, one datagram) and talks on its own end: the length-prefixed JSON of the runner channel,hellowith its protocol (decision 148), thenparams_get/run_get(schema/ctx.schema.json). The agent never answers on the shared socket, so concurrent callers can’t take each other’s answers; only the task’s processes hold the descriptor, so no other process can call (the property the runner’s channel has). The agent serves a task’s connections until the attempt ends (at most 64 at once; a datagram not carrying exactly one Unix stream socket is dropped and its descriptors closed); a call after that is told the task has ended. Linux and macOS. Not chosen: the agent sending ends on request (callers racing for answers on the shared socket).144. Scope:
dag-ctxonly.schedr dag-ctx params get [--field F]andschedr dag-ctx run get [--field F](dag_id,id,kind,planned_for,since);params getprints the JSON form--paramstakes (dates as text, a duration as ISO 8601, a tuple as a list).task-ctxcomes later on the same channel.145.
schedr.scriptdecodes, as in a task:from schedr.script import dag_ctxloads the run’s context from the channel the first time it is read (one connection, two requests); a date is adate, a duration atimedelta, a tuple a tuple. A script doesn’t know the declared class:dag_ctx.params.xis the field decoded by its stored form (an object is adict), anddag_ctx.params(Cls)decodes strictly intoCls. Inside a Python task the task’s own values are used.146. Command tasks only. A
commandtask and every process it starts get the channel; a Python task’s processes don’t (a Python task hasdag_ctxitself), soschedr dag-ctxthere fails with “must be run inside a schedr task”. A process whose parent closed the descriptor (Python’ssubprocessdoes, unless givenpass_fds) is told so, with the number to pass.147. The one
unsafeblock is in a crate of its own,schedr-fd(the user’s, 2026-11-01): Rust can only refer to an inherited descriptor known by number withunsafecode (BorrowedFd::borrow_raw), and the workspace forbids it.schedr-fd(its lints: the workspace’s, withunsafe_codedenied instead of forbidden, and allowed by an#[expect]at the one site) borrows the number only to check it (open, a Unix datagram socket) and duplicate it close-on-exec; it never owns or closes the inherited descriptor. Every other crate keepsforbid. Not chosen:forbidrelaxed todenyworkspace-wide (any crate could opt in);pidfd_getfdon itself, safe in rustix (Linux 5.6+ only, and refused under theRuntimeDefaultseccomp profile withoutCAP_SYS_PTRACE: checked in a kind cluster, 2026-11-01; OpenShift’srestricted-v2sets that profile); a third-party crate doing the same (the sameunsafe, outside our review); a socket file in a private directory (any process of the user could connect, needs a peer check);schedr dag-ctxdelegating to Python (a Python environment in every command task).148. A caller is accepted by the protocol it speaks, not its schedr version (the user’s, 2026-11-01, after a review note):
hello { protocol, schedr_version }; the agent accepts protocol 1 from any schedr, and refuses another naming both versions. A command task’sschedr(another onPATH) or a script’s own environment (a pinned schedr) can differ from the worker’s, unlike the runner, which is the worker’s own install; an exact match would break them at every worker upgrade. Within a protocol, changes are only additions (a request, a field; either side ignores fields it doesn’t know, and a request the agent doesn’t know is answerederror); anything else, a new value of an enumerated field included, is a new protocol. Not chosen: the exact version (as the runner); no check (errors that say nothing about versions).
How the channel holds against its own task (after Grok’s review and Codex’s, 2026-11-02): the
agent reads and writes a received end with MSG_DONTWAIT on each call, never relying on its
O_NONBLOCK flag (the sender shares the open file description and could clear it, holding one
of the runtime’s threads in a blocking read); it reads up to 253 descriptors from a datagram
(Linux’s limit per message), so none is left unread, and rustix 1.1.6 clamps a truncated
control message’s length (macOS leaves it unshortened); at its limit of 64 connections it says
so on the new connection before closing it, and callers read that answer even when their hello
couldn’t be sent. schedr-fd duplicates the inherited number before checking anything, so what
it checks is what it returns. Callers send their end with MSG_DONTWAIT, waiting for room in
the shared datagram queue only until their 30 s deadline (Python’s socket.send_fds drops its
flags, so schedr.script calls sendmsg itself).
Plain Python scripts:
schedr.script(decided 2026-10-23, M4;dag_ctxsince M4.5b,task_ctxwithschedr task-ctx):from schedr.script import dag_ctx, task_ctxgives a plain script (ascripttask, a command runningpython …) the same objects as a Python task, holding values:task_ctx.secret(...),dag_ctx.params,dag_ctx.run, cleanup and resource calls. Not a second mechanism: the same agent channel and requests asschedr task-ctx/schedr dag-ctxand the Python runner, the same types and rules (declared secrets and prefixes only, masked by the agent), only loaded from the channel when first used instead of set by the runner; outside a task it fails like the CLI. Templates are a different step and stay one: placeholders and t-strings are filled by the agent before the process starts, for a task’s arguments,envand commands; these calls read values while it runs. Not chosen: only the CLI through a subprocess; a Python API of its own for scripts (secret(),params()), a second set of names for the same data.Namespace
schedr task-ctx, separate from the user CLI (listing DAGs, triggering runs) and the server roles and commands (schedr master,schedr worker,schedr db migrate), andschedr dag-ctxfor the run’s context (see Run parameters and the DAG context). Outside a task they fail with “must be run inside a schedr task”.Noun, then verb, the same verbs everywhere:
add/listfor collections,set/getfor single values.Purpose
Command
Used in
Register a per-task cleanup handle
schedr task-ctx cleanup add ExportJob job_id="$id"the task
Read the handles
schedr task-ctx cleanup list [ExportJob] [--field job_id]its cleanup
Report the resource value
schedr task-ctx resource set cluster_id="$id" size:=8a
CommandResource/ScriptResourcesetupRead the resource value
schedr task-ctx resource get [--field cluster_id]a command / script resource cleanup
Read a declared secret
schedr task-ctx secret get 'ci/deploy#token'any command / script task
Read the run’s parameters
schedr dag-ctx params get [--field region]any command / script of the run
Read the run information
schedr dag-ctx run get [--field planned_for]any command / script of the run
Field syntax (from HTTPie):
key=value(a string),key:=json(a raw JSON value:size:=8,enabled:=true),--json '{...}'(a whole object). Checked against the declared type with no coercion (size=8into anintfield is an error).Output: JSON by default (JSON Lines for lists);
--field NAMEprints raw values, one per line (not for values that can contain newlines: use the JSON output for those). Not chosen: a-0(NUL-separated) flag (only matters for file paths with newlines; JSON already handles any value).Exit codes:
0success,1error,2wrong usage; messages on stderr.Per command:
cleanup add: synchronous (when it returns, the handle is journaled and forwarded to the master); the type must be incleanup_handles=if declared; not allowed inside a cleanup.cleanup list: only inside a cleanup; registration order; optional type filter;--fieldon a type without that field is an error.resource set: only in a resource setup, once per attempt; validated againstvalue=at once; a setup exiting 0 without it fails (“resource value not reported”).resource get: only in a resource cleanup.secret get: only secrets declared in the task’ssecrets=; printed without a trailing newline; masked by the agent like placeholders.
# 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 (its cleanup)
schedr task-ctx cleanup list ExportJob --field job_id |
while read -r id; do warehouse cancel-if-running "$id"; done
# create_cluster.sh (a resource setup)
id=$(cloud create-cluster --size "$2")
schedr task-ctx resource set cluster_id="$id" size:=8
# deploy.sh
curl -H "Authorization: Bearer $(schedr task-ctx secret get 'ci/deploy#token')" ...
Default deployment size¶
2 workers by default, 2 slots each (4 concurrent tasks). To be tuned per deployment.
Watchers: 500 watcher slots and a 1 GiB watcher host per worker by default (see Sensors and triggers); the pod’s memory limit must cover the tasks’ budgets plus the host’s.
Ports¶
All configurable; none clashes with Istio’s sidecar ports (15000–15090).
Port |
Role |
Default |
|---|---|---|
webserver HTTP (UI and REST API) |
webserver |
8080 |
master gRPC (workers connect) |
master |
8070 |
worker log endpoint |
worker |
8081 |
ops ( |
every role |
8090 |
Standalone uses 8080 and 8090, and 8070 / 8081 on localhost (it keeps the gRPC protocol
internally). Not chosen: 9090 for ops (Prometheus’s own port: a clash in standalone next to a
local Prometheus, and confusing in a ServiceMonitor).
DAG roots¶
DAG files are referenced the same way as scripts, so references are portable between workers and environments:
Every
SCHEDR_DAG_PATHentry is a root, named by default after its last path component.The configuration file can rename an entry in a
[dags.roots]section (the path must be one of theSCHEDR_DAG_PATHentries).Nested entries are a startup error; duplicate root names are a startup error unless resolved by renaming.
A DAG file is referenced as (root name, path relative to the root) and resolved by the worker that runs the task.
DAG ID conflicts¶
A DAG ID must be defined in exactly one place. When it isn’t, the DAG is in conflict:
Same ID in two places on one worker (two files in one folder, two folders, two roots): none of the definitions can run. The UI shows the DAG as in conflict, with every place that defines it.
Different workers on different code (e.g. worker A still has the DAG in
a.py, worker B, already synced, has it inb.py): not a conflict (M2.5). Only the newest code runs: a root’s DAGs come from the parse of the newest hash an alive worker reports, and its tasks go only to workers that have the root at that hash (see Code versions and change detection). A worker on older code gets none of the root’s tasks until it has synced, so it can’t put a DAG in conflict and doesn’t block it. Not chosen: the rule before M2.5 (a conflict until every relevant worker, those serving the DAG’s queues, has parsed the same place), which blocked the whole DAG, no runs, no assignments, during every git-sync lag; and pinning a worker on old code to the runs that started on it until they finish (git-sync replaces its files anyway, a pinned pod is capacity lost for the run’s length, and if it dies no worker has that code: runs pinned to their code would need versioned code, e.g. a checkout per git commit, which schedr doesn’t keep).The same file at different code versions on different workers is not a conflict either; the master logs a warning while workers report different hashes of a root (see Code versions and change detection).
No duplicate parsing. Workers report a content hash per root; each (root, hash) is parsed once per schedr version (see Upgrades and compatibility), by any
ACTIVEworker that reported that hash.While a DAG is in conflict, no new runs are created and no tasks are assigned. In runs already in progress, running attempts finish; tasks not yet started wait until the conflict is resolved.
When the conflict is resolved, the DAG becomes runnable again on its own (its paused or unpaused setting is unchanged).
A conflict resolved while the file left fails to import stays a conflict until that file imports, when the version stored is the removed file’s (decision 107, the user’s, 2026-10-31: A; B95). Otherwise the removed file’s code would run again, under a DAG its file no longer defines, and the import error would hold nothing (holds follow the stored version’s file). The master logs a warning saying so: the DAG stays in conflict, only one file defines it, that file failed to import, and it runs again once the file imports. When the stored version is the file left’s own, it is kept, as for any file that fails. Not chosen: B removing the DAG until the file imports (its history hidden, and paused again when it comes back); C keeping the removed file’s version but holding it under the file left (code from a file that no longer exists, runnable once the hold lifts).
The same ID twice in one file is a conflict too (both places are the same file).
A DAG first seen in conflict is stored paused and with no version; it gets one when the conflict is resolved.
Conflicts are decided within the current parse of each root (and across roots): the same ID in two places there is a conflict, whatever the workers report.
Code versions and change detection¶
Tasks run on the latest code the worker has: the copy of the hash it reported last, taken when the task starts (decision 102). schedr keeps no other old code versions; a copy goes once nothing running uses it.
Only the newest code runs (M2.5). Workers may report different hashes of a root while git-sync catches up. The root’s current hash is the newest one an alive worker (registered, not lost or deregistered) reports, newest meaning the hash workers switched to most recently (table
root_hashes, so a master restart decides the same; a switch’s time is never before the root’s latest one, so a clock stepped back doesn’t reorder them, B93). A switch is decided by the move itself (decision 113, the user’s, 2026-10-31: A; replacing this morning’s “away from the newest recorded hash”, which ignored a revert once the newest hash’s workers had left): a worker moving to a hash not recorded yet (new code) or to one recorded before the hash it left (a revert) switches, and that hash is newest; moving to a hash recorded later is catching up and changes nothing (B102: after a restart a lagging worker reporting first, then catching up, would otherwise rank above the newest code). Compared with what the worker reported before, also across a reconnect; a hash never seen before is newest when first reported. Not chosen: the newest among the hashes reported now (B102 again: the lagging worker may be the only one reporting); away from the current hash (B102 again). A worker that registers again reports its roots afresh (a root it no longer has stops counting). The current hash’s parse defines the root’s DAGs, and the root’s tasks go only to workers at that hash, or at a newer one whose parse is on its way (newer code still, so the root’s tasks don’t stall while it is parsed):AssignTaskcarries the hash the worker reported asexpected_code_hash, and a worker whose root is at another hash by then rejects the task withCODE_MISMATCH(“code not there yet”, tried again in 35 s). Until a root has a current parse (its first parse on its way) no hash is sent and nothing is checked. A revert made while the master was down isn’t seen as a switch (the master doesn’t keep what each worker reported). Not chosen: newest as first parsed most recently (a revert would lose to the code it reverted); any change of a worker’s hash as a switch (a lagging worker passing through older revisions would roll the code back). A task waiting for that says so: “waiting for workers serving queuedefaultto have the newest code of rootetl”. A root no alive worker reports keeps its current parse. The cost: right after a push, a root’s tasks run only on the workers that have synced.The mixed-code warning: the master logs a warning when workers report different hashes of a root (once per change of the set), naming the hashes and the workers; and a run whose attempts ran on different code (the root changed during the run) lists its code hashes in the API (
code_hashes), the attempt recording the hash its worker ran.schedr computes a content hash of the DAG code and records it for each task attempt. When tasks in the same DAG run used different content hashes, schedr shows a warning.
Changes are detected by polling on a schedule (interval set in configuration), not by filesystem notifications (which are unreliable on network volumes and with git-sync’s symlink switching).
Defaults: poll every 30 s, settle time 5 s.
After a change is seen, schedr waits for a settle time (configurable; no further changes) before computing the new content hash, so half-written files are never parsed.
What is scanned: each root recursively, following symbolic links (git-sync switches a link to each new checkout; the root is resolved on every scan), skipping what
.schedrignorefiles exclude,.gitand__pycache__directories and*.pycfiles..gitignoreand.airflowignoreare not honoured. A scan compares each file’s path, size and modification time with the previous scan.What is hashed: every scanned file, not only
.pyfiles (tasks read SQL, configuration and other files next to their DAG files):sha256:and the hex SHA-256 of each file’s relative path, length and bytes, in path order. The hash depends only on paths and contents, so every worker with the same code gets the same hash; only.pyfiles are parsed.Settling in detail: a changed scan must stay the same for the settle time; a further change restarts it, and going back to the last settled scan cancels it. The first scan after the agent starts settles too. After hashing, the root is scanned again and a change during hashing restarts the settle time. Only a new hash is reported: files touched without changing (same contents) report nothing. A scan that fails (a file removed during the scan, a dangling link, a path that isn’t UTF-8) is retried at the next poll.
The code that runs is the code hashed (decision 102, the user’s, 2026-10-31; B58, B59). When a root’s scan settles, the agent copies its scanned files into its own data directory (
<data_dir>/code/<worker ID>/<root>-…/sha256-…) and hashes the bytes it copied, read once for both: the hash reported is the copy’s. Parse jobs and task attempts import from that copy (the DAG file, the working directory, the root’ssys.pathentry), never through the configured path, so git-sync moving its link and deleting the old checkout (by default in the same loop that publishes the new one,--stale-worktree-timeout0), or an edit in place, can’t change the code a job runs. A followed link is copied as its target’s contents. Only the scanned files are copied: what.schedrignoreexcludes,.gitand__pycache__aren’t there (the user: A), so a task reading one by a relative path doesn’t find it. The copy is read-only (executable bits kept; the user: A): attempts of one hash share it, so a task writes its files elsewhere. A copy is removed once a newer hash replaced it and no running parse or attempt imports from it; the same code again (a commit outside the root) reuses its copy. Tracebacks,__file__and a task’s working directory show the copy’s path. Code under a root is also imported from its source, never from bytecode, and no.pycis written there: Python’s check (modification time in whole seconds, and size) misses an edit of the same length within a second. Not chosen (the user first chose A, then the copy once git-sync’s cleanup showed A’s weakness; Codex recommended the copy independently): A importing from git-sync’s resolved checkout (the checkout can be deleted before the next scan; an edit in place still changes the code), B the checkout for parse jobs only (a task’s recorded hash could be another’s), C the configured path with a full re-hash after each parse and at each task’s start (each re-hash reads the whole root, and the code can still change after the check); hard links instead of a copy (an edit in place shows through); for bytecode, hash-checked.pycfiles (Python decides the check when it writes one, so a timestamp.pycalready there is still trusted).A root imports only from itself (decision 103, the user’s, 2026-10-31: B; B90). Every DAG root is on
sys.path, the parsed or run root at its copy and the others at their configured paths, so a module of another root is imported from that root’s live checkout: not the code hashed, not recorded with the attempt, and not reparsing this root when it changes. A root’s code depends only on itself and installed packages; code shared between roots is a package (installed in the image or the interpreter’s environment), or kept in each root. Not chosen: A pinning every root at its copy for each parse and attempt, kept while it runs (copies kept per attempt; the user preferred the rule); C only the root’s own copy onsys.path(a cross-root import fails at once, breaking setups that rely on it).
Upgrades and compatibility¶
Upgrading schedr doesn’t change a root’s content hash, and the upgrade order (master first, then workers) means a new master works with old workers for a while.
DAG JSON carries the schedr version that produced it (
major.minor). The master accepts DAG JSON of the same major and an equal or lower minor version (the protocol’s rule): between the master and worker upgrades, every parse comes from old workers. Within a major version, DAG JSON changes are additive only (new optional fields), so a newer master reads older JSON with no migration code.Parse jobs live in the master’s memory (after a restart, workers report their hashes again). A job goes to the first
ACTIVEworker that reported the hash; if that worker is lost or the job isn’t finished within 10 minutes, it goes to the next worker that reported the same hash (or the same worker again). An upload is accepted by its (root, hash, schedr version) whatever job it answers, so a restart of the master loses nothing; the first parse stored wins. In the protocol an import error is structured (ImportError: exception, message, traceback).Re-parse after an upgrade: parse jobs are keyed by (root, hash, schedr version). When a worker of a newer version reports a hash that has only an older parse, the master creates a parse job, once per root, so existing DAGs get the new checks and features. Until it is stored the old parse stays in use; runs in progress keep the DAG version they started with.
A DAG that becomes invalid after an upgrade:
Within a major version this must not happen: a minor release accepts every DAG the previous minor accepted; a new check starts as a parse warning and becomes an error only in the next major.
Across a major upgrade the new parse records an import error and the last good version keeps running, with the error shown in the UI (“doesn’t parse with schedr 2.0”); not treated as a removed DAG (the code didn’t change, schedr did).
Checking before an upgrade:
schedr dags check <path>(from the newpip install schedr) parses DAG files andschedr.tomlfiles locally, without a cluster, and reports import errors and parse warnings; also for CI.
Rolling upgrade: a task is assigned only to workers whose version is at least the version of the parse in use (a DAG parsed by a new runner may use a feature only the new
schedrpackage has), compared asmajor.minor: the run’s parse and the parse of the root’s current code (the code that actually runs), whichever is newer. Until enough workers are upgraded such tasks wait asqueued(“no worker with schedr ≥ 1.5 serves queuedefault”); old workers keep running tasks of DAGs on older parses, so an upgrade needs no downtime. Of a hash’s parses, the one of the newest schedr version an alive worker reporting the hash has is used: the new parse takes over once stored, and if only old workers are left, theirs is used again. Not chosen: comparing the patch level too (patches add no features); keeping the old parse until most workers are upgraded (new checks arrive late, and “most” needs a threshold).Other stored data: the database schema is upgraded by
schedr db migrate(see State storage). Outputs, cleanup handles and resource values (tagged JSON) also change only additively within a major version: a new runner must decode what an old one stored, since a run started before the upgrade continues after it.
End-to-end flow: running a native-API DAG¶
What happens from the moment a DAG file written with the native Python API lands in
SCHEDR_DAG_PATH (already on the worker) until its run finishes. Each step is tagged:
[D] decided elsewhere in this file.
Running example: /git/dags/etl-repo/team_a/sync.py defines DAG sync with two Python tasks,
extract → load, scheduled daily; load takes extract’s output as input.
Phase 1: Discovery (worker)
Poll. Every 30 s the worker agent scans each
SCHEDR_DAG_PATHroot recursively, skipping whatever.schedrignorefiles exclude, and notices that rootetl-repochanged. [D]Settle. The agent waits 5 s with no further changes, so half-written files are never read. [D]
Hash. It computes a new content hash
H2for rootetl-repo. [D]Report. It sends
CodeVersionChanged(root=etl-repo, hash=H2)over its stream to the master. [D] Every worker sees the change on its own, so the master gets one report per worker; it creates only one parse job per (root, hash, schedr version) (see DAG ID conflicts; Upgrades and compatibility). [D]
Phase 2: Parsing (master → worker → master)
Why the DAG structure travels to the master (steps 8–10): the master schedules (when runs are due, task order, retries, trigger rules) but never runs user code and has no Python, and the DAG code is only on the workers. A Python DAG file can’t be read without running it, so a worker runs it once and sends the result as plain data. The webserver also needs it (graph view, task list) and likewise has no Python.
Parse job. The master creates a parse job for
etl-repo@H2and sendsAssignParseto anyACTIVEworker that reportedH2. That worker uses its dedicated parse slot. [D]Runner start. The agent starts
<python> -m schedr.runner parse[D] with a Unix socket [D]. Every DAG root is onsys.path(a root imports only from itself, decision 103). [D]Import. The runner imports every
.pyfile in the root, one at a time;team_a/sync.pyis one of them.Native API calls only record the DAG: tasks, edges, schedule, retries, t-strings as literal text plus references. Nothing runs.
Files that define no DAG are ignored silently. [D]
Each file’s progress is reported to the agent; a file that hangs gets a per-file timeout. [D]
Serialize. The runner turns each DAG into DAG JSON in the shared model, along with the import errors for each file, and sends it all to the agent. [D]
Upload. The agent sends the result to the master with a unary call. [D]
Store. The master validates the JSON (template references, cycles, unknown task kinds) and stores the DAG version for
syncwith hashH2. Import errors are stored and shown in the UI. [D in outline] A newly found DAG is stored paused until a user unpauses it. [D] A DAG that disappeared from the root is removed from the UI and listings. [D] A DAG ID defined in more than one place, or defined differently by different workers, is marked as in conflict and can’t run (see DAG ID conflicts). [D]
Phase 3: Creating a run (master)
Trigger. The master’s scheduling loop finds that
syncis due by its schedule; missed fire times follow thecatchuprules. [D] The master creates a DAG run in Postgres (kindscheduled, ID a UUIDv7) withplanned_for= the fire time andsince= the previous fire time; the run covers(since, planned_for]. [D] A run can also be created by a person (schedr runs trigger, a backfill, the UI): the command is validated and applied by the master, and the run may wait asqueuedformax_active_runs. [D]Task instances. The master creates
extractandloadin statescheduled.extracthas no upstream tasks, so it is ready and moves toqueued. [D]
Phase 4: Assignment (master → worker)
Choose a worker. Among
ACTIVEworkers serving the task’s queue (heredefault) with a free slot, the master picks the one with the most free slots. [D]Save first. The assignment is written to Postgres before anything is sent. [D]
AssignTaskgoes over the worker’s stream: attempt ID; DAG, run and task IDs, try number; kindpythonwith the DAG file referenceetl-repo:team_a/sync.pyand the task ID; expected hashH2; inputs (none forextract) and run information; timeout and memory budget. [D]Checks. The agent checks that it has a free slot, isn’t draining, has the file and has the interpreter.
If a check fails, it sends
Rejectedwith a reason, and the master reacts according to the rejection table (see Task rejections). [D]If all checks pass, it writes the attempt to its journal on disk and sends
Started, which also means the task is accepted. [D]If no
Startedarrives within about 10 s, the master takes the assignment back. [D]
Phase 5: Execution (worker)
Start. The agent starts
<python> -m schedr.runner task[D] in a new process group. stdout and stderr go to the task’s log file on the worker’s disk. [D]Fetch the spec. The runner asks the agent over the socket for the task specification and inputs. [D]
Prepare. The runner imports
team_a/sync.pyagain (the latest code on the worker: the agent’s copy ofH2or a newer hash, taken at the start and kept while the task runs [D]) and finds taskextract. It fills in t-strings; anysecrets[...]values are fetched from secret storage by the agent and passed over the socket. [D]Run. The runner calls the task’s function. Meanwhile the agent’s memory watchdog checks the process tree’s memory about once a second. [D]
Report. The runner sends the return value (the output) or a structured error summary over the socket, then exits. [D]
Finish. The agent masks secret values in the log and outputs, records the attempt status and exit code (
success,failed,timed_out,oom_killed, …), and saves the result in its journal. [D]
Phase 6: Result and what happens next (worker → master)
Finishedgoes to the master: status, output and outcome, duration, peak memory. Delivery is at least once; the attempt ID makes repeats harmless. [D]Store and acknowledge. The master stores the attempt result and the (output, outcome) pair under (run,
extract), then sendsFinishedAck; the agent removes the attempt from its journal. [D]Decide.
On success,
extract→success.load’s upstream condition is now met, so it goes through steps 13–24; itsAssignTaskcarriesextract’s output as input.On failure, the master either retries (
up_for_retryafterretry_delay) or marks the taskfailed, and downstream tasks becomeupstream_failed. [D]
Run complete. When every task instance is in a final state and every cleanup has finished, the DAG run gets its result by the run result rule:
failedif anything unexpected went wrong (a task or a cleanup failed after its last retry),cancelledif a user cancelled it and nothing failed, otherwisesuccess(see Outcomes, failures and joins: Run result). [D] The UI shows the run; logs come from the worker through the webserver proxy. If tasks in the run used different code hashes, the UI shows a warning. [D]
Observability¶
Ops port on every role (master, worker, webserver): a separate plain-HTTP port,
[ops] port(default 8090, see Ports), serving only/healthz,/readyzand/metrics, never data or actions, so no TLS or authentication. Needed because a kubelet’s probe and Prometheus can’t present a client certificate to the mTLS log port (tls.mode = "app"). Not chosen:/healthzon the worker’s log port (fails under mTLS).Health endpoints. Liveness never depends on another component (otherwise a database outage would restart the master and the webserver in a loop); readiness doesn’t check the database either (with one master, or webserver replicas sharing one database, taking pods out of the Service helps nobody: the UI shows a “database unavailable” banner, workers keep retrying the master).
Role
/healthz(liveness)/readyz(readiness)master
the process is up and the scheduling loop is ticking (an iteration started within
[ops] loop_stall_timeout, default 2 min, whether or not the database answered; every database query has a timeout below it, default 30 s, so one hung query doesn’t look like a stuck loop): catches a stuck schedulerstartup finished (schema checked, listening for workers)
webserver
the process is up
startup finished
worker
the agent’s own health (see Worker lifecycle)
not needed
Metrics: Prometheus format on
/metrics(scraped e.g. by OpenShift’s user-workload monitoring through aServiceMonitor).Role
Examples
master
scheduling loop duration; runs by state and kind; triggers by state, events received / dropped as repeats, back-pressure stops; tasks
queuedby reason (max_active_*, no free slot);unschedulabletasks; assignments and rejections by reason; parse jobs and durations; command apply latency; workers by state; notifications sent / failedworker
slots used / free; attempts by status; watchdog kills; peak memory per task (histogram); journal size; log disk usage; secret fetches, errors by kind, cache hits; watcher host: watcher slots used / free, event loop lag, blocked-loop kills, host restarts, memory, idle restarts of triggers
webserver
HTTP requests by route and status; open SSE streams; log proxy errors
Labels:
dag_idon run-level metrics (bounded, useful for alerts); nevertask_id,run_id,attempt_id(unbounded; per-task detail is in the database and the UI).OpenTelemetry (OTLP push, traces of a run across master and workers): possibly later.
How it is built (M2.9):
The ops server is a few axum routes on the role’s own runtime (no process, thread or dependency of its own), on
[ops] bind(default0.0.0.0) :port, started first in every role, before the database, so/readyzanswers 503 while the role starts. Port 0 picks a free port; the address is logged (schedr master: ops on http://…). Standalone runs one ops port for all its parts, on its--listenaddress (else 127.0.0.1), so a standalone pod can be probed; it listens before the database is migrated. Bodies are plain text:ok, or why (“the scheduling loop hasn’t turned for 150 s (limit 120 s)”, “starting: master”).Liveness watches loops: the master’s scheduling loop and the worker agent’s event loop each beat on a monotonic clock (a wall clock that steps never makes a loop look stuck) at every turn and at least every 5 s while they wait, never while a turn is stuck (the agent’s messages to the master go through an unbounded channel, so a master that stops reading never blocks its loop);
/healthzfails once a loop hasn’t turned for[ops] loop_stall_timeout. A loop not started yet counts as starting, so alive. The webserver has no loop: it is alive while it answers. Readiness: each part (master, webserver, worker) says when it has started (the master after its schema check, registry restore and gRPC listening; the worker after its journal is recovered).Query time limits:
[database] query_timeout(10 s) is Postgres’sstatement_timeout(set withSETon each new connection, which poolers such as PgBouncer accept, unlike theoptionsstartup parameter; but only in session pooling: in transaction pooling theSETlands on a server connection other clients then get; replaced in 2.10 by a limit schedr enforces itself, see Components and roles: production path), the pool’s wait for a connection and SQLite’s busy timeout; it must be at least 1 ms (Postgres reads 0 as no limit) and shorter thanloop_stall_timeout, else a startup error (standalone too). Migrations (schedr db migrate, standalone’s start) run without it: a long migration must finish. A database that answers (with errors, or by cancelling slow statements) or refuses connections keeps every tick short, so liveness doesn’t fail for it. A server that goes silent mid-query (a network partition) leaves the query with no limit on this side (sqlx has no TCP keepalive setting): the loop stops beating, liveness fails afterloop_stall_timeout, and the restart is the recovery (workers keep running, and master downtime doesn’t count against their leases). Not chosen: abandoning a tick after a time limit (a tick cut between applying a command and recording its decision applies it twice, and one cut before delivering a cancel leaves the task running, see B7, fixed by making both safe to repeat (Web UI and CLI: commands); a restart reads everything back instead). The gauge refresh only reads, so it is abandoned after half ofloop_stall_timeout.Metrics with
prometheus-client(Prometheus’s own Rust client; 2 small new crates in the build): each crate has its metrics (MasterMetrics,AgentMetrics,ApiMetrics) registered in the process’s registry underschedr_. Counters and histograms are updated where things happen; the gauges that need the database (runs, tasks and workers by state) are refreshed by the master’s loop every 15 s with one query ofGROUP BYs (a state seen before and now empty reads 0 rather than vanishing); log disk usage comes from the hourly retention sweep. A scrape reads only the registry: never the database, never the master’s lock. Not chosen: hand-written exposition (zero crates, but ~250 lines of format code for no measurable saving: both are an atomic per update and tens of KiB in all);metrics+metrics-exporter-prometheus(a global recorder, string labels, ~8 crates); OpenTelemetry (the heaviest; for traces, if ever); theprometheuscrate (stale, global registry); querying the database at scrape time.Role
Metrics
master
schedr_master_tick_duration_seconds(histogram),schedr_runs{state,kind},schedr_runs_finished_total{dag_id,result},schedr_tasks{state}(unfinished runs;unschedulableamong them),schedr_tasks_waiting{reason}(no_worker,drained,schedr_version,newest_code,rejected,no_slot, at the last assignment pass),schedr_assignments_total,schedr_rejections_total{reason},schedr_attempts_ended_total{status},schedr_parse_jobs_started_total,schedr_parse_jobs_finished_total,schedr_parse_duration_seconds,schedr_commands_total{kind,decision},schedr_command_latency_seconds,schedr_workers{state}worker
schedr_worker_slots,schedr_worker_slots_used,schedr_worker_attempts_total{status},schedr_worker_task_start_seconds{method,phase},schedr_worker_watchdog_kills_total,schedr_worker_journal_records,schedr_worker_log_bytes,schedr_worker_log_swept_bytes_totalwebserver
schedr_http_requests_total{route,status}(the route template, never a raw path;unmatchedfor no route; requests the version check refuses included),schedr_log_proxy_errors_total{kind}(missing,stale_address,unreachable,worker_gone,no_endpoint)every role
process_resident_memory_bytes,process_cpu_seconds_total,process_open_fds,process_start_time_seconds(from/proc/selfat the scrape),schedr_build_info{version}Trimmed for now: a request duration histogram (until the UI), a peak memory histogram (the peak is on every attempt in the API); the metrics of features not built yet (triggers, SSE, secrets, notifications, the watcher host) come with them.
schedr’s own logs go to stdout/stderr (collected by Kubernetes), separate from task logs (files on the worker, see Task logs).
[log] format = "auto" | "json" | "text":autowrites JSON when stdout isn’t a terminal (pods) and readable text in a terminal (standalone, development).[log] level, with per-module filters in theRUST_LOGstyle (e.g."info,schedr::scheduler=debug"); thetracingcrate.Context fields where they apply:
dag_id,run_id,task_id,attempt_id,worker_id(“everything about run X” is one search).No secrets: configuration secrets are never logged; task values are already masked by the agent.