# 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
`** 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
`/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_timeout`s (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:` 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`) 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
`INSERT`s, 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 `** 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, `` 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 ` / `unpause ` | list DAGs; stop / resume the scheduler creating runs |
| `schedr runs trigger [--for