04 Runtime flows
Status: Current Last verified: 604c95a
The main paths through the system, step by step. Routes are listed in generated/routes.md and specified in API_REFERENCE.md.
A scheduled backup, self-hosted
The owner's machines hold DATABASE_URL and write through src/platform/runstore directly.
sequenceDiagram
autonumber
participant T as Timer (systemd, launchd, cron)
participant W as Worker
participant DB as PostgreSQL
participant GH as GitHub
participant S as User's storage
T->>W: run --scheduled (hourly, at a minute fixed per machine)
W->>DB: the account's slot, last full run and pending requests
alt slot not due and nothing pending
W-->>T: skip
else slot not due, requests pending
Note over W: run only the requests (full_run false)
end
W->>DB: take the account's lease (worker_run_lease)
W->>GH: list repositories (every page)
W->>DB: load worker_repo_state
Note over W: plan: a reason code per repository (new, pushed, archive_missing, unchanged ...)
loop each repository to back up
W->>GH: clone (bare)
W->>S: upload the bundle or tarball
W->>DB: record its state (after the upload succeeded)
end
W->>DB: results, logs, snapshot, completion (telemetry)
W->>DB: release the lease
A listing error aborts the run before anything is written or deleted. Unchanged repositories cost no git call. The lease (10 minute expiry, renewed every minute) lets one machine run each account's backup at a time; once it expires nobody holds it, its last holder included, so a machine that slept past the expiry loses its run and the next check runs it again.
A scheduled backup, linked
A machine linked to an account holds an agent token and no database connection. The steps are the same; the transport is the API.
sequenceDiagram
autonumber
participant W as Worker
participant API as Backup API (/v1)
participant DB as PostgreSQL
W->>API: GET /v1/schedule (If-None-Match: the kept ETag)
API->>DB: runs.account_versions (one primary-key read)
API-->>W: 304, or the schedule with its ETag
Note over W: skip, run only the requests, or a full run when the slot is due
W->>API: POST /v1/runs (creates the run, takes the lease)
API->>DB: runstore, for the token's account
API-->>W: run id, heartbeat interval, research consent
par every heartbeat
W->>API: POST /v1/runs/:id/heartbeat
and batches every 2 s
W->>API: POST /v1/runs/:id/logs, /results, /progress
end
W->>API: POST /v1/runs/:id/research (only with consent)
W->>API: POST /v1/runs/:id/snapshot
W->>API: POST /v1/runs/:id/complete (releases the lease)
Only the lease holder may write into a run (409 RUN_NOT_HELD otherwise), and an expired lease counts as taken (409 LEASE_LOST on the heartbeat). A run that stops reporting is failed by the API's abandoned-run job. POST /v1/runs answers 402 PLAN_REQUIRED, before it takes the lease, for an account without a paid plan (ADR 0022); a run already going finishes.
A run's events
A run that ends, by its completion or by the abandoned-run job, writes run.completed or run.failed into runs.outbox in the same transaction (ADR 0005). The services pass it on through jobs on the queue port (ADR 0011):
sequenceDiagram
autonumber
participant R as runs (intake or reaper)
participant O as runs.outbox
participant RR as runs' job runner
participant Q as platform_jobs
participant IR as insights' job runner
participant I as insights.account_rollups
participant OR as Observatory's job runner
R->>O: the event, with the run's update (one transaction)
R->>RR: kick (same process)
RR->>O: up to 100 unpublished events (SKIP LOCKED)
RR->>Q: one insights.rollup job per event (and an observatory.run_failed and a notify.event job per run.failed), keyed by its id, and mark them published (one transaction)
IR->>Q: claim insights.rollup jobs (every 2 minutes while in use)
IR->>I: recompute the account's rollup, store it if not older
OR->>Q: claim observatory.run_failed jobs (Python, the same statements, ADR 0013)
OR->>OR: index the failure (next section)
notify's part of a run.failed, and of run.missed, is in An alert.
A runner runs when kicked after a commit in its own process, and otherwise every 2 minutes only while its database pool is already in use, so it never wakes a database that scaled to zero; a job may wait until its service has traffic. Delivery is at least once, so the rollup is recomputed, never incremented. The bundle runs both Go runners' work in one process. On a queue other than PostgreSQL's (QUEUE_BACKEND), runs queues no Observatory job and warns at startup.
An alert
Alerts follow the events of runs (and, once billing relays its outbox, of billing) through the same queue (ADR 0017):
sequenceDiagram
autonumber
participant RR as runs' job runner
participant O as runs.outbox (events_v1)
participant Q as platform_jobs
participant NR as notify's job runner
participant N as notify tables
participant X as Slack, Discord, webhook
RR->>RR: missed-run check (at most hourly): run.missed for each account whose slot passed 24 h ago without a full run
RR->>Q: relay: notify.event for each run.failed and run.missed
NR->>Q: claim notify.event
NR->>O: read the event (runs.events_v1); none published: the job fails
NR->>N: the event, one delivery per channel of the account's rules, and their jobs (one transaction, under the account's lock)
NR->>Q: claim notify.deliver (due now, or when quiet hours end)
NR->>X: send (webhooks: public addresses only, signed)
NR->>N: sent; or attempts and the error, retried with the queue's backoff; failed and the channel failing after the last attempt
- Who decides what. The runs service writes
run.missed(it owns the schedule); notify only reads events. A delivery issuppressedwithin its rule's minimum interval,heldbeyond 20 an hour per account (anotify.digestjob sends a channel's held alerts as one message an hour later), and waits inpendingwithnot_beforeduring the rule's quiet hours. - Once. A delivery is unique per event and channel, so a job run twice sends once; an event is unique per run and outcome (
run.failed:<run>) or per account and missed slot. - When. In the bundle the run's completion kicks the runner, which relays and sends in the same pass. Apart, notify's runner passes every 2 minutes while its pool is in use and otherwise after 12 hours, which an alert may wait.
- A channel's test (
POST /api/alerts/channels/:id/test) sends from the request, once, and records its delivery. There are no e-mail channels and nothing mails a confirmation link (ADR 0020, migration000042).
Indexing a failure
The Observatory indexes run failures, failed results, fixes and its own completed investigations (ADR 0008), from background jobs on public.platform_jobs (ADR 0013):
sequenceDiagram
autonumber
participant OR as Observatory's job runner
participant API as insights API
participant J as observatory.embedding_jobs
participant LLM as OpenRouter (server key pool)
participant C as observatory.embedding_chunks
OR->>OR: observatory.run_failed for account A, run R
OR->>API: GET /api/backups/R and a page of /api/backup-fixes, its credential + X-Account-Id: A
OR->>J: queue the failure, the failed results and the fixes with their text, account A, every generation being indexed
OR->>LLM: embed a batch (the drain: within the hourly cap and the background share of slots)
OR->>C: store the chunks under account A; the jobs drop their text
- When the runner passes. The Observatory runs its jobs in process: a pass runs when kicked, every
JOB_POLL_SECONDSwhile the Observatory's database pool is open, and afterJOB_MAX_IDLE_SECONDSwithout one. The pool closes its connections afterDB_POOL_LINGER_SECONDSunused, so an idle Observatory leaves the database alone. - Writes queue too. An investigation is queued in its turn's transaction, and a fix after the runs API stored it.
- A new generation. It queues the investigations; its backfill pages through the enabled accounts, then each account's failed runs and fixes, through the same API.
- Nothing to do. A run or an account that is gone or disabled queues nothing.
- Rate limits. A rate-limited embedding call gives its jobs back without counting an attempt.
Buying a plan
- The pricing page reads
GET /public/billing/plans: each plan's cohorts with the seats sold, and the refund terms. - The signed-in customer sends
POST /api/billing/checkoutwith the plan and their billing details. Billing refuses the EU and the UK, picks the currency from the country (INR in India, USD elsewhere) and the price of the cohort on sale, stores the details and apendingsubscription, and asks the provider for a payment page (billing.Provider.StartCheckout): a Razorpay Subscription for rupees, a Payment Link for dollars. The answer is the page's URL. - The customer pays on the provider's page and returns to
APP_URL/billing. - The provider calls
POST /webhooks/razorpay. Billing checks the signature, records the delivery under the provider's event id, and in one transaction marks the subscriptionactivewith its period, stores the payment and its invoice (numbered per financial year), and writesbilling.subscription_activatedandbilling.entitlement_changedtobilling.outbox. - Billing's relay queues
identity.entitlement_changed; identity readsbilling.entitlements_v1and sets the account's plan topro. - Renewals arrive the same way (
subscription.charged, or a one-time customer paying a renewal checkout in the last 30 days of the year), asbilling.subscription_renewed. A failed renewal ispast_due(billing.payment_failed) and, when the provider stops retrying,ended. The maintenance job ends periods that ran out and publishesbilling.renewal_due14 days before a one-time year ends. POST /api/billing/refundwithin 14 days, with at most one completed run, refunds the payment less 15%; the provider'srefund.processedends the subscription, issues a credit note when the invoice stated tax, and sets the plan back tofree.
Deleting an account
sequenceDiagram
autonumber
participant D as Dashboard
participant ID as identity
participant Q as platform_jobs
participant R as runs' job runner
participant I as insights' job runner
participant N as notify's job runner
D->>ID: DELETE /api/me (session, login typed)
ID->>ID: delete identity's and the Observatory's rows, write account.deleted (one transaction), kick
ID->>Q: relay: runs.account_deleted, insights.account_deleted and notify.account_deleted jobs
R->>Q: claim (kicked, while in use, or after 12 h idle)
R->>R: account gone from accounts_v1? delete its runs rows in batches; a second sweep in 5 minutes
I->>Q: claim
I->>I: account gone? delete its rollup
N->>Q: claim
N->>N: account gone? delete its alert channels, rules, events and deliveries; a second sweep in 5 minutes
The answer comes after identity's transaction, with "pending": ["runs", "insights", "notify"]. A forged job for a live account deletes nothing.
Linking a machine
sequenceDiagram
autonumber
participant W as Worker (link)
participant API as Backup API
participant U as User
participant D as Dashboard (/link)
W->>API: POST /v1/agent/link
API-->>W: device code, user code (10 minutes)
W->>U: open APP_URL/link, enter the code
U->>D: enter the code
D->>API: POST /api/agents/link/lookup, then /approve (session)
loop every 5 s
W->>API: POST /v1/agent/link/token
end
API-->>W: agent token (kept in the OS keychain or a 0600 file)
The approval needs a paid plan, or the deployment owner's account: without one it answers 402 PLAN_REQUIRED and the code stays pending until it expires, so the user can buy a plan and approve it (ADR 0022).
Reading from the dashboard
sequenceDiagram
autonumber
participant B as Browser
participant D as Dashboard server
participant API as Backup API
participant DB as PostgreSQL
B->>D: GET /api/proxy/backup/api/backups (session cookie)
D->>API: same path, Authorization: Bearer <session JWT>, X-Forwarded-For
API->>API: authenticate (principal cache 30 s; revocations read at most every 2 s), rate limit per account
API->>DB: SELECT ... WHERE account_id = $1 (keyset pages)
API-->>D: JSON
D-->>B: JSON
The dashboard's totals (/api/dashboard/stats, /api/metrics, the repository count of /api/repos) read the account's rollup in one batch with the endpoint's own statements: when the rollup's version equals the account's runs_version it is served as stored, otherwise it is recomputed from the runs and stored. The runs in progress and the last run are added live; totals from results count a run once it ended.
The browser never talks to the API or the Observatory directly, and never holds a token: the session lives in an httpOnly cookie that the dashboard turns into a Bearer token.
Live logs
The dashboard opens /api/proxy/backup/api/logs/stream (Server-Sent Events), which the API serves from one poller (livefeed) that runs only while someone listens. The poller reads new execution_logs rows once for every subscriber and hands each subscriber its own account's rows; a row committed late (after rows with higher ids were read) is still delivered. /ws/live serves the same rows over a WebSocket for other clients. Details: STREAMING_ARCHITECTURE.md.
A chat turn
sequenceDiagram
autonumber
participant B as Browser
participant D as Dashboard server
participant O as Observatory
participant DB as PostgreSQL + pgvector
participant LLM as OpenRouter
B->>D: POST /api/proxy/agent/chat/stream
D->>O: same, Bearer <session JWT>
O->>DB: context: hybrid search (full text + vectors, reciprocal rank fusion)
O->>LLM: question, context, tools
LLM-->>O: tool call (search, metrics, runs)
O->>DB: run the tool for the caller's account
O->>LLM: tool results
LLM-->>O: answer tokens
O-->>D: SSE tokens
D-->>B: SSE tokens
A tool listed in CONFIRMATION_REQUIRED_TOOLS asks the user first: the turn yields a confirm_id, and only the user who started the turn can approve it within 120 seconds. No tool needs it today: none sends anything, and a report is the answer itself, which the dashboard downloads as Markdown from the message (ADR 0020). Each turn has a 280 second deadline.
The context search reads only the index: when no chunk matches, nothing is searched in the runs tables (ADR 0008); the tools still read live runs through the API. Per process, an account runs at most two turns at once (the third gets 429 before the stream starts), LLM calls wait for one of a few slots (503 SERVICE_BUSY after 10 s), and one model message runs at most four tools at a time.