chain-rdeveloper portal
build

The Scheduler

For most of this platform's life there was no scheduler, and three features were shaped around its absence — each saying so in its own docstring:

  • dashboard widgets refreshed when a board was viewed;

  • review-flag retention was enforced when the queue was read;

  • nothing could alert, because nothing ran unprompted.

This is the runner that replaces the first two and unblocks the third.

Where it runs

In svc-core's own process, not a new container.

The deployment is deliberately segmented — every service on its own network, every outbound path explicit — so adding a container is an architectural decision, not a convenience. A scheduler needs exactly what svc-core already has: the core database, the widget registry, the rule engine. Giving it its own image would mean duplicating all three across a network boundary in order to run two functions that already live here.

The cost is stated rather than hidden: a job runs in svc-core's thread pool, so a slow job occupies a worker thread that would otherwise serve requests. DashboardRefreshJob.MAX_PER_TICK is the bound on that, and a job heavy enough to need more is the signal to revisit this decision rather than to raise the ceiling.

SettingDefault
SCHEDULER_TICK_SECONDS60Bounds every job's resolution.

One leader, elected by Postgres

svc-core can run as several replicas. Two both purging retention is harmless; two both refreshing the same widget is an LLM call paid for twice. So a replica holds a session-level advisory lock for as long as it schedules, on a connection of its own.

Session-level rather than the transactional form app/migrations.py uses, because the lock must outlive a single statement. The important property is what happens when a leader dies: its connection drops, Postgres releases the lock, and the next replica to tick picks it up. There is no lease to expire and no heartbeat to get wrong — which is the failure mode hand-rolled leader election usually has.

The lock id is distinct from the migration runner's. A replica must be able to hold one without the other; sharing an id would make migrations and scheduling exclude each other for no reason.

A replica that loses the election serves requests normally, and the opportunistic paths still work there. Losing costs nothing.

The tick

The loop sleeps after each tick rather than firing on a fixed schedule, so a tick that runs long delays the next one instead of stacking a second copy on top of it. Jobs are therefore never re-entered while still running in this process, which is what lets each be written as a plain synchronous function.

Due-ness is measured from when a run started, not when it finished — a job taking 50s on a 60s interval should still run every 60s, not every 110s.

A job with no row has never run and is due immediately. That is what makes a newly deployed job take effect without first waiting out its own interval.

Jobs

One class per job in app/services/scheduler/jobs.py, registered with a decorator — the same shape as widget types, rule actions and stat metrics.

KeyEveryDoes
review_retention1hDeletes review flags whose retention period has passed, across every owner.
quick_try_retention1hDeletes unsaved Quick try comparisons older than the retention window.
background_retention1hDeletes background_events rows older than BACKGROUND_EVENT_RETENTION_DAYS, across every owner.
knowledge_turn_retention1hClears the request text, gaps and file names from knowledge_turns rows older than KNOWLEDGE_TURN_TEXT_RETENTION_DAYS (180), across every owner; the counts stay.
knowledge_reindex60sRebuilds the search index after the embedding model changes (Titan on Bedrock, OpenAI on direct): per knowledge base whose collection another model built, recreates it at the new size and re-embeds every document from what is stored, 45 seconds a tick. Probes the model first, holds at 90% of the spending ceiling, keeps no state of its own. Registered before the crawls, the bot sync and the benchmark, which waits for the guide. See bedrock-migration.md.
chainr_bot_sync1hRe-provisions CHAINR Bot from code and indexes the user guide it answers from, re-indexing a document only when its text changed or its last indexing did not finish. See chainr-bot.md.
web_knowledge_refresh15mStarts crawls of website knowledge sources due on their daily or weekly cadence. Only claims them — the crawl runs on its own pool, so a minutes-long crawl never holds up the tick. See web-knowledge.md.
platform_benchmark10mRuns the platform benchmark (CHAINR Bot and each maker's strongest model on the gold datasets) when something that decides a score changed. It only starts work: the runs go to one dedicated worker thread, one at a time, and a tick while they run does nothing. Each tick first releases runs a restart cut off, and a fresh process starts nothing for 5 minutes. The lifespan stops the worker on shutdown. Registered after chainr_bot_sync. Only where DEPLOY_ID is set. See evaluation.md.
economics_export1hWrites each finished UTC day's model spend (by workspace, source and model) and what it bought, for the host to ship to S3 and CloudWatch. A day is written once, an hour after it ends; a run catches up missed days a week at a time within ECONOMICS_EXPORT_LOOKBACK_DAYS. Off where ECONOMICS_EXPORT_DIR is unset. See cost-monitoring.md.

Which tiles a tick refreshes

refresh.due_widgets reads only the dynamic types (widgets.dynamic_types(), from the registry), and only the columns that say when each is due (refresh.scheduled_due_at): a tile never filled at once; one being refreshed only once its claim is plainly abandoned; one that failed an hour later (FAILED_RETRY_AFTER), or sooner if its own interval is shorter; a ready one when its interval has passed; one with no interval never — a person refreshes it. The most overdue go first.

Until 21 October 2026 the job took the 100 widgets of any type with the oldest cache and filtered those. Static tiles never set a cache time, so a deployment with 100 of them filled every window and no tile was refreshed on schedule again; and a failed tile was due on every tick, a paid call a minute when it failed after its model had run. Tiles refresh one after another, and an agent's may take minutes (widgets.TILE_TIMEOUT_S, 300 s), so a tick stops claiming once it has spent TICK_BUDGET_SECONDS and leaves the rest to the next. A board's view still refreshes a failed tile at once (is_stale): that is a person asking.

Every job must be idempotent

The scheduler makes no at-most-once promise and is not written to. A replica can lose the lock mid-tick and another can pick the job up; a restart re-runs anything due. Both jobs are safe under that because they ask the database what still needs doing rather than tracking what they have done — is_stale gates a refresh, and an expired flag either still exists or does not.

A job that cannot be written that way needs a claim mechanism of its own, and run is the wrong place to invent one.

A job never raises

run returns a JobResult and the runner records it. An exception that escaped would end the tick and take every other job's schedule down with it — a wedged job silently ending retention enforcement for the whole platform is the failure a scheduler is supposed to prevent, not cause. The runner catches anyway, so a job author cannot forget, and rolls the session back so the next job does not inherit a poisoned transaction.

Ran-and-found-nothing is not did-not-run

JobResult.nothing_to_do() records skipped, distinct from ok. In a log the two look identical and mean opposite things when somebody is asking whether retention is being enforced.

The opportunistic paths stay

Refresh-on-view and purge-on-read were not deleted. They are:

  • what makes a newly added tile fill in immediately rather than waiting a tick;

  • the whole mechanism wherever the scheduler is disabled;

  • the fallback on every replica that is not the leader.

They cannot double-refresh a widget. mark_refreshing claims one by committing its status before generation starts, and is_stale will not pick up a claimed widget until STUCK_REFRESH_TIMEOUT has passed — so whichever path arrives first, the other steps over it.

What changed for retention is the gap: it used to be "until somebody next opens the queue", and is now at most an hour. A retention period is still "deleted no earlier than" rather than "deleted exactly at"; over-retention remains the safer direction to be wrong in.

Observing it

GET /monitoring/scheduler reports whether this replica is scheduling, and every registered job with its last run — status, detail, duration, cumulative run and failure counts.

"Has the retention purge been running?" is an audit question, and a scheduler observable only through container logs is one nobody can answer it about. Every registered job is listed whether or not it has ever run, so a job that has never fired is visible as such rather than simply absent.

Two details worth knowing when reading it:

  • leader: false is normal. Exactly one replica leads. False on every replica is the condition worth alerting on.

  • last_error is not cleared by a later success. "Working now but failed at 03:00" is a different statement from "has never failed", and only one of them is worth waking somebody for. last_status tells you about now; last_error and failure_count tell you about the history.

State lives in scheduled_jobs — one row per job, upserted. That is the deliberate difference from governance_usage, governance_events and review_flags, which are all append-only: those record evidence about a user's data, this records operational state. An append-only run log would grow without bound and need a retention policy enforced by… a scheduled job.

What it did for each user — background_events

scheduled_jobs answers an operator ("dashboard_refresh refreshed 12 widgets"). A user asks something else — what happened to my things while I was away — so the work is also recorded per subject in background_events (migration 66, app/services/background_activity.py) and read by the Activity page's Background category through GET /app/activity/background, scoped to the subject's owner:

KindWritten byOne row per
knowledge_crawlweb_crawl._finish / expire_abandonedfinished or abandoned crawl
review_retentionthe review_retention jobowner whose flags were deleted
platform_benchmarkevaluation.benchmarkbenchmark run (with its measured cost), or a deploy's budget reached. Ownerless, so on no user's Activity page

Each row carries a trigger — scheduled, view (a board load found the tile stale), manual, created or updated — because refresh-on-view and "Refresh now" do the same work as the scheduler and belong in the same record. The row is written in the same transaction as the change it describes and never raises into it.

A generated tile's LLM call is on svc-ai's invocation trace separately, as purpose="dashboard_widget" with the board and tile in its reference, and on the usage ledger as execution_type="dashboard". It used to inherit evaluation from the execution target it borrows, so every refresh read as an experiment run. A caller that reuses those targets must call target.attribute(...).

Because a busy board refreshes constantly, the Activity feed stacks consecutive repeats, the way a phone stacks notifications: three or more items in a row with the same stack key (stackKeyOf in fe-core's Activity.tsx, folded by util/feedStack.ts) draw as the newest one with an "N more" toggle that expands the rest in place. A tile's refresh and its dashboard_widget call share a key, because they arrive interleaved; other background kinds and LLM calls stack by kind and purpose. A failure never stacks — it breaks the run so it cannot be folded away. Runs, resource changes, generations and evaluation runs don't stack either. Stacking is display only: filters, search and the event count still see every row.

The feed is paged, not capped. Each of its capped sources (LLM calls, resource changes, generations, experiment runs, background work) is read 100 rows at a time by offset, newest first (hooks/useFeedSource.ts), and the merged stream is drawn 50 events per numbered page. The merge is complete only down to a horizon: the newest of the oldest rows loaded from each source that still has more (util/pagedFeed.ts). Anything older is held back, because a source that has not been read that far could still have rows that belong above it. Asking for a page past the horizon loads the next page of the source that set it. Only the sources the current category draws from count, and a background kind filter is sent to the server, so looking for one crawl never means reading through thousands of refreshes in the browser. The feed and the detail panel are fixed-height panes that scroll separately, so opening an event far down the list shows its detail beside it.

Retention

Unlike scheduled_jobs this table is append-only, and a tile on a 60-second interval writes 1,440 rows a day. The background_retention job deletes rows older than BACKGROUND_EVENT_RETENTION_DAYS (default 30; 0 keeps them forever) every hour, across every owner. It deletes in chunks of 5,000 with a commit after each, so it never holds a long lock on a table the refresh job writes to every minute. It stops at 100,000 rows per run, so a backlog clears over several runs. Migration 72 indexes finished_at so the age-only scan does not read the whole table. The job writes no background event of its own: an hourly "deleted 1,400 refresh records" per owner would be the clutter it removes, and its scheduled_jobs row already records it.

The feed applies the same window on read, so a row the job has not reached yet is never served, even with the scheduler off. The feed response carries retention_days, and the Activity page shows it under the list, so missing older work reads as a policy rather than a gap.

What this does not do yet

  • No alerting. The scheduler is the piece alerting was waiting on, but a threshold needs somewhere to send its result and the stack has no notification channel — no mail service, and webhook tools are an agent capability rather than a platform one. That is the next decision, and it is a design question rather than a missing loop.

  • No per-job schedule control. Intervals are declared in code. A job's row could carry an override, but nothing needs one yet and a setting nobody changes is a setting nobody maintains.

  • No manual trigger over HTTP. run_named exists and is used by tests; it is not exposed, because "run this job now" from a browser is a privileged operation and RBAC is still coarse (Phase 4).

  • Evaluation suites still do not re-run on a timer. The runner could do it — that is a job class — but "which suites, how often, and against what" is an evaluation design question, not a scheduling one.

See also: governance.md (the reviewer queue and its retention), statistics.md (the dashboards the refresh job keeps current).