Architecture

Components and roles

One Rust binary, five roles:

Role

Runs

User code?

schedr master

Scheduling loop, state in Postgres, internal API for workers

Never. Its image contains no user packages.

schedr worker

Rust agent; starts Python and Bash subprocesses for tasks and parsing

Yes, in subprocesses

schedr webserver

The REST API used by the web UI and the CLI

Never.

schedr ui

The web UI, over one or more deployments’ webservers (M3, 21B)

Never.

schedr standalone

All of the above in one process (its UI over its own API)

Yes (local development only)

Running the roles separately (M2.1):

  • schedr master and schedr webserver need [database] url and a schema schedr db migrate brought up to date (an outdated one is refused); schedr worker needs no database, only [worker] master_url (e.g. http://schedr-master:8070, env SCHEDR_CONFIG__WORKER__MASTER_URL). The master listens on [master] bind : grpc_port, the webserver on [webserver] bind : port, both 0.0.0.0 by default; standalone always listens on 127.0.0.1. Not chosen: a --master flag 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_notify on schedr_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, cert and key on the master, the webserver and every worker, else a startup error naming the key and mode = "mesh"; mesh sends plain traffic for the mesh to encrypt. [worker] master_url is checked at startup: an https:// URL with a host in app mode, http:// in mesh mode, else a configuration error rather than a worker retrying forever. Each role’s startup line says which ((mTLS) or (plain: tls mode mesh)). 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): none by 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_header and basic, 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.

  • standalone runs 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.0 behind a ClusterIP Service), 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] bind in standalone (its 0.0.0.0 default would open every laptop’s standalone).

  • SIGTERM stops standalone cleanly, as it stops the roles.

  • One standalone per data directory: standalone holds an exclusive flock on <data_dir>/standalone.lock while 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 a StatefulSet with replicas: 1. Only lock contention says so; another flock failure (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’s fsGroup makes 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 own fsGroup. A data directory that can’t be written says so, naming fsGroup.

  • 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/schedr group-writable). tini is PID 1 and reaps orphaned processes (a task’s child outliving it), which schedr, not being an init, doesn’t. A .dockerignore keeps the build context to dist/*.whl. DAG code from a git-sync sidecar (registry.k8s.io/git-sync/git-sync:v4.7.1) into a shared emptyDir, the root renamed in [dags.roots] (git-sync’s link is called current). Probes use the ops port (8090): /readyz and /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 one INSERT … ON CONFLICT … WHERE expired OR mine and 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 by idle_in_transaction_session_timeout); a Kubernetes Lease (API access, Kubernetes only, doesn’t stop two environments on one database); relying on replicas: 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’s SET statement_timeout on 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-side statement_timeout (by the DBA) stops them in Postgres too. On SQLite, busy_timeout limits each wait for a lock; a statement cut off runs on in sqlx’s thread until it ends (sqlite3_interrupt would need unsafe).

  • 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); LISTEN stays 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 (a Notify: 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_interval later 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. Only Finished: 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 lower tick_interval instead (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 migrate takes the lease (refused while a master or another migration holds it; --wait waits for it), and schedr standalone migrates 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-migrate to 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, webserver and worker on 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 % for schedr 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 unless memory_budget is set. Too small, and tasks under their budgets together exceed the limit: the kernel kills the whole pod (every task lost, retries used); too large, and tasks are killed earlier than needed. Not chosen: keeping 10 % and requiring memory_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 QueryTimeout under 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’s busy_timeout stays (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 % for schedr worker and 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 takes musllinux wheels 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 with build-base and the -dev packages) running pip 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 schedr base image (images/schedr/Dockerfile, make image: the binary, Python, the package, tini, a group-0-writable data directory; 108 MB); users write FROM schedr:<version> and add their libraries (examples/kubernetes/Dockerfile, two stages; checked: pyyaml compiled 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 by make chart-check and CI’s chart job: helm lint, helm template with its main combinations of values; Helm 4.3.0 in CI), mode: standalone (distributed in 2.11): the image, database.existingSecret (a Postgres URL; without it SQLite on the volume), persistence (ReadWriteOnce), resources, terminationGracePeriodSeconds mirrored into [worker] termination_grace_period, an optional git-sync sidecar, an optional ServiceMonitor, extra SCHEDR_CONFIG__* variables; one replica (StatefulSet), probes on the ops port, no fixed runAsUser (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 lint and helm template in make check and CI, and scripts/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 Postgres FOR KEY SHARE, which a takeover’s FOR UPDATE waits for and a renewal (no key change) doesn’t; a write after a takeover is DbError::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 a DO block reading the lease from set_config('schedr.holder'/'schedr.epoch', …, true) and raising SQLSTATE SR001, read as DbError::NotLeading; values written in as E'…' 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 with 25P02). A fenced write is one round trip more than before (the COMMIT). 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::take retries everything (the table too) and try_take is 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 by security.openshift.io/v1), which assigns its own and refuses 0. Not chosen: an openshift value (one more thing to set right).

    • Left: 0001 edited in place (allowed before the first release).

  • Found by the stress suite (2.10b, 2026-10-24):

    • A task’s start counts when its Started arrives (B11): under load (stress scenario 13: 624 assignments expired for 11 successes) the master handled Started after 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 the Started and Finished it 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_version reads 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; SQLite BEGIN 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 its COMMIT would 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 SAVEPOINT with 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, Draining and Deregister end 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 their AssignTask messages 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 for SET_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 = off for 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_timeout to 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 LISTEN sent 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); dropping LISTEN (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’s DO block; allowed to everyone by default). Nothing reads other databases, pg_stat_activity or 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 atomically transaction (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_overview reads on one connection; the nightly workflow’s Postgres gets max_connections = 500 and 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 (Rejected counts 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): a COMMIT past 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 after START_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_lost ends started attempts lost (a retry used) and the others assignment_expired with a WorkerLeft summary (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 in UPDATE … FROM (VALUES …), the round’s waiting reasons one UPDATE … 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 single set_queued_reason is 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, the FinishedAck sent; 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 to read_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 per planned_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 within quiet_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; a queues_ prefix (mixes with task queues, @task(queue=...)); a scheduling_ 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); false visits 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_after after its last active visit; then quiet unless a fire time is within quiet_dag_wake_ahead (a paused DAG: quiet without a timer). Its timer is its next fire time (from its start, within its end) less quiet_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 for quiet_dag_after after any wake (the first design’s “every DAG starts busy after a restart”).

      • Metrics: schedr_master_dags{state="busy"|"quiet"} and schedr_master_dag_wakes_total{reason} (timer, command, run_queued, run_ended, new_version, sweep); sweep counts 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_of and run_overview_of (500 IDs a query), active_dag_versions for 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 no sweep wake; 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 central schedr ui); schedr ui deploys 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] mode says (decision 36’s mTLS port is a distributed webserver’s, in app mode).

    • 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_runs stay 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 one UPDATE, 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: true by default (one holding no permissions); create: false with a name runs every pod as an existing account; automountToken: false (schedr never calls the Kubernetes API). Per-role names come with distributed. Not chosen: create: false by 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/config with holdApplicationUntilProxyStarts and EXIT_ON_ZERO_ACTIVE_CONNECTIONS); a virtualService on an existing Gateway (the chart creates no Gateway); a requestAuthentication (issuer, jwksUri or inline jwks); an authorizationPolicy; a peerAuthentication (STRICT); serviceEntries (a name and a spec each, for Postgres or git outside the mesh). Following the user’s existing charts: the VirtualService’s prefix (other than /) rewritten to / with X-Forwarded-Prefix set (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). v1 where the cluster serves it (Istio 1.22 on), else v1beta1 (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) carrying api.claims (all of them, each with any of its values); callers without a token by api.principals / api.namespaces; the ops port from ops.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 migrate init container can’t reach Postgres through a mesh with strict mTLS or REGISTRY_ONLY: migration: initContainer | onStart, onStart running standalone --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; hence EXIT_ON_ZERO_ACTIVE_CONNECTIONS (the proxy waits for schedr’s connections to close), and holdApplicationUntilProxyStarts (schedr’s first connections need the proxy). Not chosen: migration: onStart always (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 username and password, as their other apps compose SQLALCHEMY_DATABASE_URI): database.postgres (host, port, name, params, existingSecret, userKey, passwordKey, notificationsHost / notificationsPort), the URL built by Kubernetes’ $(VAR) expansion from SCHEDR_DB_USER and SCHEDR_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 / password in schedr, encoded into the URL (safe for any password, but a schedr change the user’s passwords don’t need); relying on sqlx reading PGUSER / PGPASSWORD (undocumented by schedr, unclear for the listener’s connection); a lab Postgres in examples/ (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 (kubernetes method, auth.role, mount, the Vault namespace, the pods’ ServiceAccount, tokenExpirationSeconds) and a VaultStaticSecret per staticSecrets item (name, secretName, path, mount kvv2, type kv-v2, refreshAfter 600 s, hmacSecretData), each Vault key a Secret key (their charts’ JSON transformation left out: schedr reads plain keys; an item may pass its own transformation); restartOnChange (default true) adds rolloutRestartTargets for 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 upgrade carry them, with no hand-made ConfigMap; outside schedr, since it’s deploying): charts/schedr/dags-values.sh <folder> prints values dags.files (path → base64 content), and the chart makes a ConfigMap of them (each file under its own name), mounted at /dag-files as the root files. A flat folder (the user’s choice after the review, option A): its *.py files 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’s items putting 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 old items (content under the wrong names). Not chosen: stable keys from the path with items (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, ..data linking 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 with dags check on that layout). The root is therefore the ..data link 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 pack in the CLI (the user: deploying stays outside schedr); kubectl create configmap --from-file with dags.existingConfigMap (not helm upgrade, flat folders only); --set-file per 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 .schedrignore with ..* in the ConfigMap (the per-file links still resolve outside); schedr skipping ..-folders (a schedr change for a deployment detail); dags check in 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’s GITSYNC_USERNAME / GITSYNC_PASSWORD from the Secret; type: ssh: a private key and known_hosts mounted read-only, GITSYNC_SSH_KEY_FILE / GITSYNC_SSH_KNOWN_HOSTS_FILE), instead of raw gitSync.env; under REGISTRY_ONLY a 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); sameNamespace documented as letting an ingress gateway in the same namespace through without a token (set it false then; the user’s gateway is in istio-system); NOTES’ gateway URLs with the prefix, <host> for a wildcard host; make standalone’s address a variable (LISTEN, 0.0.0.0 as the user set it); dagsRoot: files and notificationsUrlKey with database.postgres template errors; Swagger UI’s files served from their static bytes with Cache-Control (an hour); the proxy’s settings merged into a proxy.istio.io/config of podAnnotations instead of replacing it; the folder’s limit 512 KiB (above). A second review over those fixes: a dagsPath root named files by its last part refused too; the script portable (bash 3.2, BSD tools: macOS), counting only *.py files (a folder with only .schedrignore refused), following links (a linked file taken, a linked subfolder refused like any); file names not starting with . but .schedrignore (Kubernetes refuses .. keys, and ..data is the root’s link); the description built once and sent with Vary: X-Forwarded-Prefix; the guide: at most two roots (git-sync’s volume covers the image’s folder). Left: make standalone on 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 also psycopg[binary] and pymysql[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) in requirements.txt by make image-requirements (uv pip compile for musl and Python 3.14 with --exclude-newer two 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 but pymongo, 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, checks pymongo.has_c() and runs a Polars query. Async libraries run inside a plain task with asyncio.run until M4’s async task functions. Images of one’s own FROM it still add or pin more. Polars’ engine is polars-runtime-32, built for x86-64-v3 (avx, avx2, fma, bmi1/bmi2, lzcnt, movbe): on a CPU without them import polars only warns and a task dies of SIGILL later. Checked on a node of the user’s lab (2026-10-25): all four of avx2, fma, bmi2, movbe on its 12 cores, so it stays. A cluster without them switches to polars[rtcompat] (Polars prefers compat when installed); setting the choice by variable would need [worker] pass_env, since tasks get a clean environment. Not chosen besides: compat only (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-check renders the Istio values (charts/schedr/ci/istio-values.yaml, both API versions) and checks what they produce; scripts/kind-mesh.sh installs Istio 1.31.1 (REGISTRY_ONLY; SIDECARS=native, its default, or classic, 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 did scripts/kind-standalone.sh (all its phases). Found: Istio 1.31 injects native sidecars by default (istio-proxy among 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 without EXIT_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-certificates and the binary from the musllinux wheel (no Python; a shell for kubectl exec; no second Rust build). Workers in the base image schedr (2.11a’s libraries) or one built FROM it. Not chosen: scratch or 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) or onStart, through a new schedr 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 --migrate the migration) shared by schedr master and standalone; connect_database (no schema check) replacing open_database.

  • Workers: a StatefulSet (a headless Service, log_address the 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; terminationGracePeriodSeconds 600 mirrored into [worker] termination_grace_period; one pod at a time on upgrades; DAGs from gitSync (a sidecar each) and/or dags.files (the ConfigMap in each). Master and webserver get no DAG files. Not chosen: emptyDir (a rescheduled pod’s attempts lost, its logs gone).

  • TLS: tls.mode: app by 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, creating Certificate objects) → generated by the chart (tls.generate, on by default: Helm’s genCA / 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 with lookup and 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); mesh by 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 under sameNamespace; a PodDisruptionBudget for workers (maxUnavailable: 1, on by default); the ServiceMonitor over 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; image for 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 upgrade with mode: distributed on 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: app the master’s gRPC port and the workers’ log port are named tls-grpc / tls-logs (Istio’s sidecars pass schedr’s own TLS through; named grpc / http-logs they parsed it as plain gRPC and HTTP, breaking the links); serviceAccount.create with a name shares 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); clusterDomain for the workers’ addresses (was cluster.local fixed); the webserver says what it waits for whenever that changes (an unreachable database, then a schema to migrate); Database::require_usable_schema and DbError::SchemaNotUsable removed (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 an ORIGINAL_DST cluster, 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: sameNamespace reads the caller’s identity) refused them with 403. The chart now adds a DestinationRule for the workers’ Service with ISTIO_MUTUAL (with istio.enabled in 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’s fs.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 failed helm upgrade leaves objects helm uninstall doesn’t remove, so the kind script deletes the release’s labelled objects before it starts.

  • Tests: make chart-check over 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 builds schedr-server and smoke-tests it (an arbitrary UID, no Python, master and webserver starting and stopping); integration tests for the webserver waiting for its schema and master --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; SIDECARS native and classic with tls.mode: mesh on 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.sh keeps using the postgres database): hold sleeps 90 s with retries=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 finishes success. Neither worker becomes lost. The new master records them disconnected until they register (the lease counts from then), and both are active again once the run has finished.

  • Then again sleeps 30 s with retries=1 and retry_delay of 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 ends lost with WorkerRestarted when that pod is ready again within [master] lease_timeout (60 s). Past that, WorkerLost is the rule and the script prints it; the killed worker being lost is not a failure of the check. The retry succeeds. The other worker stays active.

  • Then the release is installed again as standalone on SQLite. A short run (ping) succeeds, then again is killed with the pod. ping is still success (the volume kept the database), and again is lost / WorkerRestarted, then success (WorkerLost when 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 ui since M3, over webservers’ APIs, decision 21B; schedr standalone serves 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 applied or rejected (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, optional planned_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), --for in 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’s step_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 migrate runs 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 NOTIFY when 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 unschedulable task of an unfinished run

    schedr tasks logs <run id> <task id> [--try N] [-f]

    an attempt’s log (the latest try by default), read from its worker; --follow until the attempt ends

    schedr 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-index

    schedr workers list

    the 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 schedr on 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 with Schedr-Server-Version. Same major, any minor: works. A command or flag the server doesn’t have yet gives a clear error (”schedr runs backfill --all needs 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-Version is served; one with another major version gets a 400 with what to install. Schedr-Server-Version is 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 at GET /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-ui with its vendored feature, 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 an X-Forwarded-Prefix header): the page refers to the description as ../openapi.json and /api/v1/docs redirects to docs/, both relative, and the served description names the prefix as its servers URL when X-Forwarded-Prefix is 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’s serve), not through the crate’s axum router (absolute redirect and URLs). The committed schema/openapi.json has no servers. Not chosen: a setting for the prefix (one more value to keep equal to the gateway’s); relative servers URLs (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-ui downloading 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-ui at the root (outside /api/, a second route in a VirtualService).

  • Actions answer 202 Accepted with the command (pending); the client polls GET …/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-Key header (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 (422 for 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 (%2E too, 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, or anonymous.

  • 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-ctx and schedr dag-ctx (talk to the agent), server commands such as schedr db migrate / schedr db status (talk to the database), the server roles, and the local commands schedr dags check <path> [--against <url>] and schedr dags test <dag> (dags test has no server; --against reads 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 shows CONFLICT: N places; TRIGGER shows the trigger as written, then catchup and 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, marked local, 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); --json prints the API’s JSON as it is (UTC only), for scripts. --for takes 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 (with auth.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 ui role 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 schedr binary, so schedr 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): basic uses the browser’s Basic auth, proxy_header the proxy’s session; every action from the UI (a POST) must carry a matching Origin / 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 /docs when 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, and make image / make server-image build 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 /docs shipped unnoticed); reusing a stale dist/docs locally.

    • 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_at and 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’s confirm().

      • The UI proves itself to webservers as master and workers do, by [tls] mode (36, the user’s): in app mode by mTLS on a second webserver port serving the whole API, for schedr ui only (its certificate’s name checked, as worker_name is); in mesh mode 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 ui by default (37A, distributed mode): one replica and a Service on 8082, its deployment default the 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, dags and workers NOTIFY schedr_changes once 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 a changes table (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 serves GET /api/v1/changes (run, dag, workers, refresh; a keep-alive comment every 15 s); when changes can’t be followed (notifications off, a pooler without notifications_url) it sends refresh every 5 s, and a client that fell behind gets refresh. The UI relays one stream per deployment (reopened after 1 s, doubling to 30 s, with a refresh once 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); a changes table 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 + BroadcastChannel first written here: Web Locks need a secure context, so on http:// 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), or refresh when it doesn’t know; a stream opened again sends every page refresh. 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 local http:// 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 with Sec-Fetch-Site: same-origin (or none), or without it an Origin whose host is the request’s (X-Forwarded-Host behind a proxy); anything else is 403. Commands are recorded as anonymous until 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 = false turns them off, applied by schedr 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 sends refresh every [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_header beyond a loopback address without allow_remote, basic there without behind_tls_proxy. basic’s users are name:bcrypt-hash lines in users_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, else Origin against 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 in X-Schedr-User, taken by a webserver only from a proven UI: its certificate naming [tls] ui_name (schedr-ui) on [webserver] ui_port (8083, app mode: 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_file in X-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’s X-Schedr-User is 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 ui loads certificates only when a deployment is reached over mTLS (https://), as app is 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-ui and its own CI job, kept out of make 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 outcome SUCCESS isn’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 / NotEmpty check, 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_primary returned Unavailable).

  • The Deployments page (the user’s request, 2026-10-31; built in M4.4b): /deployments lists the deployments the UI is connected to (in standalone, default alone); /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] deployments already 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 masters table, 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 at Register by 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/deployment also 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 at Register, 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): /deployments is 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), so partition_key, sort_key, cache_key are shown (the user’s, 2026-11-01, raised by side notes). Not chosen: the configuration’s rule (any name ending in key hidden: 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 short limit or a from inside 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

    none

    schedr trusts whoever reaches it

    behind a mesh that authenticates (the main deployment: Istio + Keycloak, the whole namespace trusted); standalone (localhost)

    proxy_header

    an SSO proxy in front (oauth2-proxy, OpenShift oauth-proxy, …) logs users in and passes X-Forwarded-User; schedr trusts it

    Kubernetes without a mesh, with any identity provider

    basic

    HTTP Basic against users in users_file (name:bcrypt-hash lines, 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 in basic, and in none an optional identity_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_header listens only on a loopback address unless overridden explicitly (anything reaching it around the proxy could forge the header); basic refuses plain HTTP on a non-loopback address unless behind_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’s access_control is 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: none with identity_header, or proxy_header behind an SSO proxy), and basic’s users_file stays what it is: for labs and single machines (made with scripts/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 ui given 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_header behind it), or schedr speaking OIDC itself (jwt above).

    • How schedr ui proves itself follows [tls] mode, as the master’s and workers’ links do (decision 40A, the user’s, 2026-10-28): in app mode, mTLS on the webserver’s UI port (36); in mesh mode with Istio’s AuthorizationPolicy, the same port in plain HTTP, trusting the mesh ([webserver] ui_port_in_mesh = true, refused in app mode, 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 (and istio.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, mesh mode without Istio’s policy or with a shared account. Why: the chart’s generated token is remade at every helm template, so Argo CD (the user’s deployments) would rotate it at each sync. Not chosen: keeping the token with Argo’s ignoreDifferences on 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): of webserver.auth × ui.auth, only the same mode for both, or any UI mode with the API’s none (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, and ui.auth.mode left empty takes webserver.auth’s (one sign-in for the release); for schedr ui over 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 (timestamptz in Postgres; ISO 8601 with Z in 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-cache and X-Accel-Buffering: no; since some proxies buffer text/event-stream anyway, 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_id and parsed_at on each parse_files row, 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 to current_parses when 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 a dags check matter (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; in mesh mode 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 from from, at most 1 MiB, with headers Schedr-Worker-Id (who answered), Schedr-Log-Size (the size now) and Schedr-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) is https://<host>:<port> (http:// in mesh mode), 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 passes outboundTrafficPolicy: REGISTRY_ONLY (the mesh’s mTLS to them needs a DestinationRule with ISTIO_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 every Register, so a pod restarted with a new IP is found again. Not chosen: the pod IP as the default (blocked or unrouted under REGISTRY_ONLY without 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 current log_endpoint in 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, running and content (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 offline or lost

    503 at once, without connecting: “worker w1 is 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 w2 instead of w1 at …: its address is stale; try again shortly”

    the worker’s and the webserver’s [tls] mode differ

    503, 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_PROXY says (see Configuration: internal links): a proxy can’t reach pod IPs or cluster names, NO_PROXY rarely covers them, and in mesh mode a request sent to a proxy would skip the mesh’s per-destination policy. Through a CONNECT tunnel 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; --json prints each part as the API’s JSON, one per line); --follow reads on from next every 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 usual PATH syntax (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 .py file 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 .airflowignore files 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 .py file 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 schedr are parsed (A, the user’s, 2026-11-05): a .py file whose text doesn’t contain schedr is 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.core from a DAG or a task) it works as ever. A file that defines DAGs must mention schedr (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 least import schedr (a # schedr comment 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 for import, 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 bytes schedr, any encoding. schedr dags check keeps the rule, even for a file it is named (it would otherwise pass what a deployment skips), and prints skipped <file> with why; --json stays what a parse reports. Found building this: a factory call defines nothing today even with the mention, as a DAG belongs to the file calling Dag(...), the helper (B170); the rule holds for a file re-exporting Dag through 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 catchup decides about them;

    • a manual trigger is refused: the command is rejected with the reason (“DAG sync is held, no runs are created and it can’t be triggered: its file sync.py fails 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 held in the API (DagView.held: the file, exception and message), a badge, a banner and a disabled Trigger in the UI, a HELD column in schedr dags list, the gauge master_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) or RunnerDied, 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), InvalidPath and ParseResultTooLarge (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 (API held.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_runs at least 1; start not after end; 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 is InvalidPath): 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.py is team.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 and sys.modules work 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 on sys.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.py would 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 with block: a helper’s function can build it (B170); a module imported by another still owns its own (B110). Decision 305 stays: the file must mention schedr. Not chosen: an explicit ownership API for factories.

  • 330. .schedrignore is about what is shipped: dags check reads the same filtered copy as dags test and 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.py imports team.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; 1 is one at a time. dags check uses it, and forks when the interpreter has a fork server (“parse as the task runs”). Measured (stress scenario 22, 12 cores, 1000 files importing pydantic): 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 = 1 or 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_env reaches parsing and the fork server too (the user’s, 2026-11-06, from Grok’s review): spawned tasks had a PYTHONPATH of pass_env on sys.path, while a parse and a forked task hadn’t, and imported something else. A parse and a fork server now get all of pass_env, as a task does, so a library needing such a variable at import works in both. Not chosen: only PYTHONPATH. DAG authors could already read these from a task; now also at parse, so secrets don’t belong in pass_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 from SCHEDR_DAG_PATH. Files there are never imported or parsed as Python.

  • SCHEDR_SCRIPT_PATH is a normal configuration key (SCHEDR_CONFIG__SCRIPTS__PATH) with SCHEDR_SCRIPT_PATH as a short alias. Same PATH syntax as SCHEDR_DAG_PATH.

  • Scanned recursively; .schedrignore files apply, as in SCHEDR_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 inside SCHEDR_SCRIPT_PATH.

  • There can be many schedr.toml files, at most one per directory.

  • One schedr.toml can declare several scripts, and can declare the same script more than once (e.g. with different schedules).

  • Paths in a schedr.toml are 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.toml files (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.toml has 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 the schedr.toml that 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_PATH entry 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_PATH entries (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.toml is therefore under exactly one root. Script references and standalone jobs are stored as (root name, path of schedr.toml relative 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.toml remain accepted in ScriptOperator references.

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, ProcessResult output). 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.

  • notify names server channels only, as a list (default events) or a table choosing events per channel (event names as in Event). DAG-defined EmailChannels 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, so max_active_runs covers it.

  • schedule is optional. With a schedule (or every / 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 through ScriptOperator (and ScriptResource, cleanup_script). Only script and interpreter are 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.toml inside SCHEDR_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 check for TOML; M4.9b the script task kind on the worker (interpreters, rejections 3-5, the SCHEDR_* variables) and ScriptOperator; M4.9c params, outcomes, [jobs.<name>.cleanup], ScriptResource and cleanup_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 no schedr in Python. A DAG file’s ScriptOperator asks 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) for ScriptOperator (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 whose ScriptOperators 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_MISMATCH as for DAG roots). Not chosen: the master’s keys frozen until the DAG’s own file changes (a raised retries not applied).

  • 295. A script root a parsing worker lacks is an import error (A): “script root etl isn’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 “schedule is optional” above. Not chosen: a manual = true key making it a one-task DAG for manual runs (one more combination to define, with schedule too); every declaration a DAG, every key accepted (a declaration made for ScriptOperator listed as a DAG, keys that do nothing accepted).

  • 298. notify is an import error until notifications exist (A, the user’s, 2026-11-05): “notify isn’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 (etl both 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_daily has 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 ID run for 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_MISMATCH as 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 (an env= 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 check looks references up in the configured script roots (SCHEDR_SCRIPT_PATH), so a typo is caught before deployment. Not chosen: schedr.testing checking references itself (an idea for later); a DagHint outside 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’s timezone, as start is), 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 _, so dag_ctx.params.x reads 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 an Outcome enum does, so a ScriptOperator without outcomes= still succeeds on them. .on(...) and .outcome take enum members, and the TOML has none: outcomes=Check gives one and replaces the declared ones; without it only DefaultOutcome.SUCCESS can be routed on, if declared, and .on of anything else or .outcome is 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 ScriptResource and cleanup_script naming a declaration with [outcomes] is an import error; so is cleanup_script naming one with [cleanup] (a cleanup of a cleanup). A ScriptResource setup keeps [cleanup], as CommandResource(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): a ScriptOperator or ScriptResource may 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, as retries does; its script stays the declared one, and a cleanup_* on a declaration without one is a parse error. A cleanup_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 script and command task: 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 override args, env, secrets, queue, retries, retry_delay, timeout, max_output_size, outcomes (an Outcome enum).

  • In the operator, args and env values 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, at schedr.airflow.providers.schedr.operators.script (schedr as one more “provider”, following Airflow’s providers.<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, like SnowflakeOperator), so it isn’t confused with the native ScriptOperator.

  • Parameters: the ScriptOperator overrides (job, args, env, secrets, queue, timeout, max_output_size, outcomes) are forwarded; standard BaseOperator arguments (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): .output comes from the ProcessResult via a fixed set of modes: LAST_LINE (default, like BashOperator), STDOUT (all of it), NONE. JSON and JSON_LAST_LINE are 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_LINE is produced like BashOperator’s .output (a hidden native task, see Thin translating classes). A user-supplied Python callable (like Airflow’s output_processor) is not supported.

  • Reporting like Airflow: skip_on_exit_code (default 99) skips the downstream tasks, as for BashOperator (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 Finished for 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 standalone mode TLS is disabled (everything listens on localhost).

    • schedr standalone runs 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 on 127.0.0.1; Ctrl-C stops them together.

    • It migrates the database at start with --migrate (2.10; before, always: a laptop has no separate schedr db migrate step) 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 in Registered (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, and Finished still 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_size can’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 in Register. 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 (default schedr-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 mode off (plain traffic is what mesh is; 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 the serverAuth and clientAuth extended 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, Finished since B46, the journal on Register) 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_interval and 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, as master connection lost with 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: a Finished is stored instead as the attempt’s failure, kind result_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 its Finished. Not chosen: B ending the stream on every error (decision 108 as it was: a refused result came back for ever); C dropping a refused Finished too (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:

  1. Register (worker → master), on every connect: worker ID, incarnation ID, protocol and schedr versions, queues, task and watcher slots, log endpoint address ([worker] log_address and 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).

  2. 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 Started may 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).

  3. Heartbeat (worker → master), every 10 s by default: free task and watcher slots and running attempts. Kept small.

  4. CodeVersionChanged (worker → master): sent when a content hash changes (after the settle time). A new hash makes the master create a parse job.

  5. 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 sends Deregister and 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 Finished again); if its run is being cancelled, CancelAttempt is sent again right after Registered, since a cancel sent while the worker was away was lost.

  • Refusals: a stream must start with Register (else INVALID_ARGUMENT); an incompatible protocol version, a missing worker ID or a worker ID with a live stream end it with FAILED_PRECONDITION and 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 (Finished until FinishedAck: 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). A Started or Finished that 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.

  • FetchInputs streams an open attempt’s inputs in 1 MiB chunks; for an unknown or ended attempt it answers NOT_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=False only 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’s Register is 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 workers lost (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 LOST and comes back is told to kill the attempts it still runs (they were already failed and retried).

  • The worker’s liveness probe (/healthz on 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.

  • OFFLINE and LOST workers 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 workers table (state, incarnation, versions, queues, slots, registration time, last heartbeat, when it went offline or was lost). The master is its only writer: on Register; on every change of state (draining, disconnected when the stream drops, offline on Deregister, lost past 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 disconnected from that moment, so its lease starts from zero (master downtime doesn’t count against workers), and one that never comes back is lost after 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 summary WorkerLost: “worker w1 stopped answering while the attempt ran”). Attempts not started yet are left to expire, without using a retry. The ended attempts get the error summary WorkerRestarted: “worker w1 restarted 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), holding running (with the process group’s identity once it is spawned) or finished (the Finished message, 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: running before Started, finished before Finished. A file goes on FinishedAck, or on an ack or kill decision. An attempt the journal can’t record is rejected with DISK_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), finished results are reported in Register and sent again on continue, and for each running attempt 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 it lost (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 flock on <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/workers and schedr workers list show 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; --json for the API’s JSON); a worker drained for maintenance shows active (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’s terminationGracePeriodSeconds) minus the drain’s own end: whatever still runs then gets SIGTERM, SIGKILL [worker] drain_terminate_period (3 s) later, and ends interrupted, 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, sends Deregister (the master records it offline) 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 its execution_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 most drain_terminate_period from then (the memory watchdog to now); a repeated cancel changes nothing, and a memory kill during a cancel’s grace leaves the attempt cancelled (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 ended lost and used a retry (a task with retries = 0 failed its run). The two times are set apart, and drain_terminate_period + drain_report_period > termination_grace_period is 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 in period, like termination_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 standalone drains its worker first, then stops the master and the API, so interrupted tasks are recorded; schedr dags test interrupts 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) until schedr 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 queue q are drained”. Resuming is a change in the set of workers: unschedulable tasks 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 master and schedr webserver log the address they actually bound (port 0 binds a free port).

Task assignment

  • Worker choice: spread. Among ACTIVE workers 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 Accepted message. Flow: AssignTask → Started (which means accepted) or Rejected → 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. default is never added implicitly: queues = ["large"] serves only large; 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 AssignTask is 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 stays queued, 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 in running and cleaning_up (a cleanup still holds the slot) and assigned tasks not yet Started. When a place frees up, the order stays oldest-ready first among tasks whose limits allow them.

  • EmptyOperator tasks 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 Started within ~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_ctx and 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 up retries.

  • 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, or dag_file_missing when 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: “task load was removed from DAG sync (etl:team/sync.py) after this run started”, “DAG sync moved from … to …”, or “DAG sync was removed from …”. The task is retried by its retries and then fails the run; schedr tasks cancel ends it cancelled instead. Not chosen (for now): a removed task 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 becomes cancelled. A queued run that is cancelled ends cancelled at 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) is cancelled at once; one that runs is marked (task_instances.cancel_requested_at) and gets CancelAttempt. Whatever then ends its attempt (the cancel, a rejection, an expired assignment, a lost or restarted worker) ends the task cancelled without a retry; a failure meanwhile stays a failure. The same holds while a whole run is being cancelled (an attempt lost then was failed before 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 running for ever, since a cancelled run’s tasks are never assigned).

  • A task that waits says why (shown with it in runs get and the API): “no active worker serves queue gpu”, “every active worker serving queue large rejected it”, or “waiting for a free slot on the workers serving queue large”.

  • Empty tasks are completed by the master as soon as they are ready, with outcome SUCCESS and no output.

  • Parse jobs are assigned with AssignParse over 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.toml path, 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, setrlimit opt-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 with runner_failed (retried). A command’s ProcessResult is 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 timeout runs 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 ends cancelled or timed_out, not start_failed 30 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 timeout after the worker reads the attempt’s secrets and connections. A 500 ms read and an 800 ms command with a 1 s timeout end timed_out; with a long enough timeout they succeed. If the read uses all the time, no process starts; the attempt ends timed_out and 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 Register after 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

    success

    Exit code 0, or the Python function returned normally

    Worker

    failed

    Non-zero exit code or unhandled exception (incl. ImportError)

    Worker

    timed_out

    Exceeded execution_timeout; killed by the worker

    Worker

    oom_killed

    Killed by the memory watchdog for exceeding its budget

    Worker

    cancelled

    Cancelled by a user

    Worker

    interrupted

    Killed when a draining worker’s grace period ended

    Worker

    lost

    The worker disappeared

    Master

    assignment_expired

    No Started within ~10 s

    Master

  • 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 (default 0) is success, any other exit code or a signal is failed. A process killed by a signal reports exit code 128 + signal in its ProcessResult, 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 test and run_dag show. The attempt’s started_at / ended_at are the master’s wall clock when it handled Started / Finished (“when”, not “how long”): never subtracted, since a wall clock can step (B1: a negative duration after a WSL2 clock resync).

  • Finished contains: the attempt status, the exit code or signal, the (output, outcome) pair on success (see Task results and outcomes; for command / script tasks the output is a ProcessResult with 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 (command kind) produce their output the same way as scripts (a ProcessResult). The Airflow layer exposes the last line of stdout through .output for 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 for max_active_runs; manual, chained, event and backfill runs wait, scheduled ones are missed instead, see Runs: manual runs, backfill and pausing), running, and the results success, 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’s bash_command).

    • script: a script file declared in a schedr.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.toml declaration picks one with an interpreter key naming an entry from [interpreters]. The key is required: there is no default from the file extension.

  • Shebang lines are ignored; only the interpreter key counts.

  • If the named interpreter isn’t defined on the worker, the worker rejects the task with a clear reason (e.g. “interpreter etl-venv not 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

etl-venv not in this worker’s [interpreters]

Worker-specific: don’t offer this attempt to this worker again

4

Script root unknown

Root not in this worker’s SCHEDR_SCRIPT_PATH

Worker-specific

5

Script reference not found

schedr.toml, job name or script file missing

Code not there yet: retry after a short delay, any worker

6

DAG file missing

The python task’s DAG file isn’t on this worker

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 for unschedulable tasks 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 unschedulable every 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 becomes unschedulable after the code wait (above).

  • schedr tasks retry queues an unschedulable task 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 its retries; a finished run needs a new run).

  • A Started for an attempt that was taken back (no Started in time), ended, or belongs to another worker is answered with CancelAttempt.

  • 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 ImportError in 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 lost with the error summary WorkerRestarted: “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.max from 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 /proc on 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_budget covers 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 summary MemoryBudgetExceeded: “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).

  • setrlimit waits for M4, with per-task budgets in the native API: no DAG can opt in before. Setting it in the child needs pre_exec, which is unsafe (forbidden here), and prlimit from the parent leaves the process unlimited for a moment, so (decision 50A, the user’s, 2026-10-28) a limited task is started through schedr itself: an internal subcommand (schedr task-exec --data-limit … -- <command>) sets the limit on its own process with safe Rust (the rlimit crate) and execs the task, which inherits it; no window without the limit, one more exec (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); prlimit from outside (C: the unlimited window). The AssignTask fields 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), the SCHEDR_* run variables, and the task’s own env (with secret placeholders filled in; declared secrets= 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 every LC_*), pass_env, the task’s env, the SCHEDR_* run variables. SCHEDR_* names are reserved: a task’s env setting 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.path when 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 schedr package, started by the agent as <interpreter> -m schedr.runner parse, ... task, ... cleanup or ... 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 on sys.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: like task, 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, default python:

    [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 schedr installed 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.toml declaration, which doesn’t need schedr installed.

    • 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 command task’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, mode 0700): a file to clean up, a writable /tmp needed, 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 in schedr-model (runner), generated into schema/runner.schema.json.

    • Handshake: the runner sends hello { schedr_version, mode }; the agent answers welcome, or refused { 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 sends file_started { path } (the agent times files from it) and then file_parsed { path, dags, error } (error: the exception’s class, message and the last 20 lines of the traceback); then parse_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 answers task_succeeded { output, outcome } (encoded against the return type; outcome SUCCESS until outcome types arrive in M4) or task_failed { error, kind }. kind is 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 (over max_output_size), or null for the task’s own exception (including SystemExit). 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 in sys.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 or os._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 >> 5 DAG 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 preload list imported) and a bare one (only schedr), 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 in StepDefaults), 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). script tasks always spawn, even with a Python interpreter (a plain script expects a fresh interpreter: __main__, sys.argv, atexit; and needs no schedr); command tasks aren’t Python. A task can opt out with @task(fresh_process=True) (also in StepDefaults), 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_server when the worker starts (the first task is fast; a failing preload shows at once). It shakes hands like any runner (hello with the mode fork_server, welcome), then sends fork_server with the preload list; the fork server imports it, calls gc.freeze(), checks it is single-threaded and answers fork_server_ready or fork_server_disabled (the reason and the threads’ names). Per attempt the agent sends fork (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 answers forked or fork_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 reports process_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 with waitid(WNOWAIT), sends process_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 a killpg from 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 (a SIGCHLD handler; it never ignores SIGCHLD, which would lose its children’s statuses).

      • The shim only observes (decision 14A, 2026-10-27): with process_exited it reports whether the process dumped core and what it used (ProcessUsage, the parent’s rusage, 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 out wait4, so it is the raw waitid system call with WNOWAIT (through ctypes: Python’s os.waitid doesn’t pass the rusage; proved 2026-10-27 to give what wait4 gives after reaping). It must never break the shim: ctypes is 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 gives usage: 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 unsafe and no safe crate returns a child’s rusage, so the agent reads the zombie’s /proc/<pid>/stat and status before reaping it (waitid with WNOWAIT on the blocking pool, one parked thread per running spawned process: AsyncFd on a pidfd needs unsafe since tokio 1.54): CPU time (reaped children included) and major faults (checked 2026-10-27 to match wait4); peak RSS and the context switches are null for a spawned process (a zombie’s memory is gone; its status has 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’s peak_memory_bytes, the watchdog’s sampled PSS, covers both methods). Unreadable: usage null. Not chosen: one audited unsafe module for the raw waitid (relaxing unsafe_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 without process_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 no pidfd: an agent adopting orphans would need a waitpid(-1) sweep, which Grok measured stealing 38–40 of 40 tokio children’s exit statuses; a pidfd on a non-child can’t give the exit status (kernel 6.6) or signal a group (from 6.9), so groups are signalled with killpg, 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), not setsid() (a task in an orphaned session discards SIGTSTP; spawn’s process_group(0) is setpgid), the fork server’s SIGCHLD handler 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/null on 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 with os._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 macOS fork_server = true is 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: random reseeded (Python’s own at-fork handler), the time zone (time.tzset()), LC_CTYPE from the environment and the other locale categories C, tempfile’s cached directory cleared (TMPDIR), sys.stdin / stdout / stderr the 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_fork handlers run. Before each fork the server flushes Python’s and C’s stdio buffers (a preloaded extension’s unflushed printf would appear in every task’s log). logging is left as the preload set it (decided 2026-10-27, replacing “resets logging handlers”): a spawned task importing the same library would have the same handlers, and logging re-creates its locks after a fork itself. The server keeps descriptors 0-2 open (/dev/null if 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 with os._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) and weakref.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’s atexit flush, a thread left working, a buffering logging handler would be lost). The parent calls gc.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 schedr version 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 (default 20m, 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 shows disabled throughout. 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), method spawn / fork, phase runner (from starting the process to the runner’s hello: the interpreter and schedr) and import (from sending the task to the runner’s task_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 sends task_imported, a message of no fields, rather than timing itself. The attempts API shows start_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 and schedr 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 sends Warnings (all of them, [{kind, interpreter, message}], kind fork_server_disabled, the message saying what it means for tasks) after every Register and 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 has warnings, and schedr workers list a WARNINGS count column with the messages under the table. Usage (14A, 18A): Finished carries usage and core_dumped, stored with the attempt and shown in the attempts API (usage null 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 except polars, overridable per deployment. Polars starts threads on import (measured 2026-10-27 with Polars 2.0: two jemalloc_bg_thd, which _RJEM_MALLOC_CONF=background_thread:false stops, and a polars-ooc-clea out-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 is images/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 own thread_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, python by default) through SCHEDR_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 in config (the chart’s path would replace the one given there, found by Grok’s review); make chart-check fails 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 list and M3’s UI. Not chosen: allowing known thread names (a thread holding a lock at fork() 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 gives disabled). 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 command task 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, hello with its protocol (decision 148), then params_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-ctx only. schedr dag-ctx params get [--field F] and schedr dag-ctx run get [--field F] (dag_id, id, kind, planned_for, since); params get prints the JSON form --params takes (dates as text, a duration as ISO 8601, a tuple as a list). task-ctx comes later on the same channel.

  • 145. schedr.script decodes, as in a task: from schedr.script import dag_ctx loads the run’s context from the channel the first time it is read (one connection, two requests); a date is a date, a duration a timedelta, a tuple a tuple. A script doesn’t know the declared class: dag_ctx.params.x is the field decoded by its stored form (an object is a dict), and dag_ctx.params(Cls) decodes strictly into Cls. Inside a Python task the task’s own values are used.

  • 146. Command tasks only. A command task and every process it starts get the channel; a Python task’s processes don’t (a Python task has dag_ctx itself), so schedr dag-ctx there fails with “must be run inside a schedr task”. A process whose parent closed the descriptor (Python’s subprocess does, unless given pass_fds) is told so, with the number to pass.

  • 147. The one unsafe block 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 with unsafe code (BorrowedFd::borrow_raw), and the workspace forbids it. schedr-fd (its lints: the workspace’s, with unsafe_code denied 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 keeps forbid. Not chosen: forbid relaxed to deny workspace-wide (any crate could opt in); pidfd_getfd on itself, safe in rustix (Linux 5.6+ only, and refused under the RuntimeDefault seccomp profile without CAP_SYS_PTRACE: checked in a kind cluster, 2026-11-01; OpenShift’s restricted-v2 sets that profile); a third-party crate doing the same (the same unsafe, outside our review); a socket file in a private directory (any process of the user could connect, needs a peer check); schedr dag-ctx delegating 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’s schedr (another on PATH) 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 answered error); 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_ctx since M4.5b, task_ctx with schedr task-ctx): from schedr.script import dag_ctx, task_ctx gives a plain script (a script task, a command running python …) 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 as schedr task-ctx / schedr dag-ctx and 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, env and 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), and schedr dag-ctx for 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 / list for collections, set / get for 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:=8

    a CommandResource / ScriptResource setup

    Read 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=8 into an int field is an error).

  • Output: JSON by default (JSON Lines for lists); --field NAME prints 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: 0 success, 1 error, 2 wrong 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 in cleanup_handles= if declared; not allowed inside a cleanup.

    • cleanup list: only inside a cleanup; registration order; optional type filter; --field on a type without that field is an error.

    • resource set: only in a resource setup, once per attempt; validated against value= 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’s secrets=; 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 (/healthz, /readyz, /metrics)

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_PATH entry 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 the SCHEDR_DAG_PATH entries).

  • 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 in b.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 ACTIVE worker 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): AssignTask carries the hash the worker reported as expected_code_hash, and a worker whose root is at another hash by then rejects the task with CODE_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 queue default to have the newest code of root etl”. 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 .schedrignore files exclude, .git and __pycache__ directories and *.pyc files. .gitignore and .airflowignore are 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 .py files (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 .py files 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’s sys.path entry), 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-timeout 0), 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 .schedrignore excludes, .git and __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 .pyc is 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 .pyc files (Python decides the check when it writes one, so a timestamp .pyc already 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 on sys.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 ACTIVE worker 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 new pip install schedr) parses DAG files and schedr.toml files 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 schedr package has), compared as major.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 as queued (“no worker with schedr ≥ 1.5 serves queue default”); 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)

  1. Poll. Every 30 s the worker agent scans each SCHEDR_DAG_PATH root recursively, skipping whatever .schedrignore files exclude, and notices that root etl-repo changed. [D]

  2. Settle. The agent waits 5 s with no further changes, so half-written files are never read. [D]

  3. Hash. It computes a new content hash H2 for root etl-repo. [D]

  4. 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.

  1. Parse job. The master creates a parse job for etl-repo@H2 and sends AssignParse to any ACTIVE worker that reported H2. That worker uses its dedicated parse slot. [D]

  2. Runner start. The agent starts <python> -m schedr.runner parse [D] with a Unix socket [D]. Every DAG root is on sys.path (a root imports only from itself, decision 103). [D]

  3. Import. The runner imports every .py file in the root, one at a time; team_a/sync.py is 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]

  4. 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]

  5. Upload. The agent sends the result to the master with a unary call. [D]

  6. Store. The master validates the JSON (template references, cycles, unknown task kinds) and stores the DAG version for sync with hash H2. 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)

  1. Trigger. The master’s scheduling loop finds that sync is due by its schedule; missed fire times follow the catchup rules. [D] The master creates a DAG run in Postgres (kind scheduled, ID a UUIDv7) with planned_for = the fire time and since = 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 as queued for max_active_runs. [D]

  2. Task instances. The master creates extract and load in state scheduled. extract has no upstream tasks, so it is ready and moves to queued. [D]

Phase 4: Assignment (master → worker)

  1. Choose a worker. Among ACTIVE workers serving the task’s queue (here default) with a free slot, the master picks the one with the most free slots. [D]

  2. Save first. The assignment is written to Postgres before anything is sent. [D]

  3. AssignTask goes over the worker’s stream: attempt ID; DAG, run and task IDs, try number; kind python with the DAG file reference etl-repo:team_a/sync.py and the task ID; expected hash H2; inputs (none for extract) and run information; timeout and memory budget. [D]

  4. 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 Rejected with 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 Started arrives within about 10 s, the master takes the assignment back. [D]

Phase 5: Execution (worker)

  1. 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]

  2. Fetch the spec. The runner asks the agent over the socket for the task specification and inputs. [D]

  3. Prepare. The runner imports team_a/sync.py again (the latest code on the worker: the agent’s copy of H2 or a newer hash, taken at the start and kept while the task runs [D]) and finds task extract. It fills in t-strings; any secrets[...] values are fetched from secret storage by the agent and passed over the socket. [D]

  4. 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]

  5. Report. The runner sends the return value (the output) or a structured error summary over the socket, then exits. [D]

  6. 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)

  1. Finished goes to the master: status, output and outcome, duration, peak memory. Delivery is at least once; the attempt ID makes repeats harmless. [D]

  2. Store and acknowledge. The master stores the attempt result and the (output, outcome) pair under (run, extract), then sends FinishedAck; the agent removes the attempt from its journal. [D]

  3. Decide.

    • On success, extract → success. load’s upstream condition is now met, so it goes through steps 13–24; its AssignTask carries extract’s output as input.

    • On failure, the master either retries (up_for_retry after retry_delay) or marks the task failed, and downstream tasks become upstream_failed. [D]

  4. 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: failed if anything unexpected went wrong (a task or a cleanup failed after its last retry), cancelled if a user cancelled it and nothing failed, otherwise success (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, /readyz and /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: /healthz on 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 scheduler

    startup 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 a ServiceMonitor).

    Role

    Examples

    master

    scheduling loop duration; runs by state and kind; triggers by state, events received / dropped as repeats, back-pressure stops; tasks queued by reason (max_active_*, no free slot); unschedulable tasks; assignments and rejections by reason; parse jobs and durations; command apply latency; workers by state; notifications sent / failed

    worker

    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_id on run-level metrics (bounded, useful for alerts); never task_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 (default 0.0.0.0) : port, started first in every role, before the database, so /readyz answers 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 --listen address (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); /healthz fails 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’s statement_timeout (set with SET on each new connection, which poolers such as PgBouncer accept, unlike the options startup parameter; but only in session pooling: in transaction pooling the SET lands 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 than loop_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 after loop_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 of loop_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 under schedr_. 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 of GROUP 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); the prometheus crate (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; unschedulable among 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_total

    webserver

    schedr_http_requests_total{route,status} (the route template, never a raw path; unmatched for 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/self at 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": auto writes JSON when stdout isn’t a terminal (pods) and readable text in a terminal (standalone, development).

    • [log] level, with per-module filters in the RUST_LOG style (e.g. "info,schedr::scheduler=debug"); the tracing crate.

    • 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.