Skip to content

Deploy without losing in-flight work

A deploy restarts the SupaCloud server. The server no longer kills the agent runs it hosts the moment it receives the stop signal. It drains first: it stops taking new work, asks every running agent to save its work on the task branch, waits a bounded time, and only then stops the agent containers. The next boot puts the interrupted rounds back in the queue. This guide shows what the drain does, how to switch the maintenance window on yourself, how a deploy pipeline waits for the drain, and which settings and metrics belong to it.

  1. The server process starts draining. On SIGTERM (a docker stop, a compose recreate, a host shutdown) this server process marks itself as draining: its /readyz answers 503, so a load balancer stops sending it traffic. The drain is local to this process. It does not turn the instance-wide maintenance switch on, so with several replicas the others keep taking work while one restarts.

  2. It refuses every new launch. From that moment a launch on this server process is refused with 403 and a message that starts with draining:, whether a person or an automation started it. No container is started and nothing is charged. The run the refused launch had opened is recorded as failed at once, with that draining: message as its reason: it is terminal immediately, so it never holds the drain open for its budget and is never counted as interrupted or as killed at the deadline. Start the task again once the server is back.

  3. It asks each running agent to checkpoint. Every agent run this server process hosts receives a system message (a run another replica hosts is never touched): commit the working tree as wip: checkpoint before a hub restart, push it to the task branch and end the turn, without opening a pull request.

  4. It waits. The server waits until those runs have ended, for at most SUPACLOUD_SHUTDOWN_DRAIN_SECONDS (600 seconds by default).

  5. It stops what is left. Only then are the agent containers stopped. A run that is still alive at the deadline is stopped too and counted in supacloud_runs_killed_by_shutdown_total.

A run that ended because of the drain is recorded as interrupted, not as failed and not as completed. Its reason reads “Checkpointed for a hub restart (SC-14 drain); the round resumes on its branch”, or “Drain deadline reached before the checkpoint landed; the container was stopped” when the deadline stopped it. An interrupted run gets no completion work: no issue comment, no workflow advance and no closeout proposal, because its work is a checkpoint and not a finished round.

A run is recorded as checkpointed only when the instruction actually reached its agent. If the message cannot be delivered, the run keeps its normal ending: when it finishes inside the window it is recorded as completed, with its completion work. It is only marked interrupted if it is still running at the deadline.

When the new server boots:

  • A backlog implement round is re-queued. Its backlog item goes from in progress back to queued at the same round, with a resume note that names the task branch. The item’s workflow run is cancelled. The next dispatch starts the round again from the head of that branch, so the checkpoint commit is where the agent picks up. Each interrupted run is re-queued once: a second boot changes nothing.
  • Any other task stays interrupted until someone resumes it (see Resume an interrupted task).
  • A run whose checkpoint was requested but whose process died before it ended is recorded as interrupted too, not as abandoned.
  • Maintenance is switched off again if a deploy hook set it. A maintenance window a person switched on stays on (see below).

Runs on a runner are not part of the drain: their containers live on the runner host, which a server restart does not touch. For them a restart used to cost the run in three other places, and all three are covered now:

  • The runner is not declared dead at boot. A runner cannot send heartbeats while the server is down, so after an outage every runner looked stale and the first liveness sweep failed its work. The server now waits SUPACLOUD_LIVENESS_BOOT_GRACE_SECONDS (300 seconds by default) after it booted before the sweep may demote a runner. A runner that is still missing after the grace plus the normal stale window (SUPACLOUD_RUNNER_STALE_SECS) is demoted as before.
  • Messages reach the run after the restart. An intervention, a tool-approval answer or an interrupt sent to a runner’s run is stored in the database until the runner picks it up, so it is delivered even when the server restarted in between. At most 16 undelivered controls wait per run; a 17th is refused with an error instead of being dropped, and counted in supacloud_runner_controls_dropped_total.
  • Upgrade the server before the runners, and expect a cancelled run to stop fast only once the runner carries the same build. Cancelling a task that runs on a runner sends the runner a stop control; only a runner that advertises that capability in its heartbeat receives one. The heartbeats the runners send during the upgrade window do not advertise it yet, so a cancel issued in that window writes nothing to the run’s control queue and the run stops on its next lease observation (the behaviour before the capability existed — a few minutes, never silently unhandled). The runner upgrade is what turns on the prompt stop, and no further action is needed: the next heartbeat advertises the capability and every later cancel stops the container within the control poll. A rolled-back runner clears the capability on its next heartbeat, so a stop is never queued for a control loop that would drop it.
  • The run’s events reach the server after the restart. The runner writes every event it relays from the agent container to a durable spool on its own disk before it sends it, and retries with a capped backoff until a server replica accepts it; a runner restart resumes from the spool. An event that arrives twice is recognised by its id and stored once. The spool lives in SUPACLOUD_RUNNER_RELAY_SPOOL_DIR and is capped by SUPACLOUD_RUNNER_RELAY_SPOOL_MAX_MB; events refused at that ceiling are logged, named in the run’s log and counted in supacloud_runner_relay_events_total{outcome="lost_runner_spool_full"}. Before the runner reports a run finished it waits for that run’s spooled events for as long as the server keeps accepting them (60 seconds without progress end the wait, an unreachable server ends it at once), so a backlog after an outage drains in full and the real final event lands before the report.

The maintenance switch is the instance-wide maintenance window. Unlike the other switches it has negative meaning: enabled means maintenance is on. It is off by default and appears in the operator console with the other global switches.

While maintenance is on, automated work pauses and work people start does not:

Paused Not paused
Backlog dispatch: the dispatcher starts nothing in any workspace. Runs that are already running.
Due schedules: each is moved to its next time instead of firing, and its last error starts with maintenance:. A task a person starts in the web app, the web terminal or chat.
Incoming triggers: webhooks, git events, email and IMAP, Telegram, Discord and App runs that start workflows are refused with 403 and a message that starts with maintenance:. Running a schedule by hand.

Every user sees a banner while maintenance is on, which says that automated work is paused and that they can still start a task themselves. The banner can be dismissed for the current browser session.

  1. Sign in as an instance admin and open the Switches tab of the operator console (/operator).

  2. Enter a reason. A switch change without one is refused, and the reason is written to the audit trail.

  3. Toggle the maintenance row.

The same change over HTTP, with an operator token:

Terminal window
curl -fsS -X PUT \
-H "Authorization: Bearer $SUPACLOUD_OPERATOR_TOKEN" \
-H "Content-Type: application/json" \
-d '{"enabled": true, "reason": "planned maintenance"}' \
https://supacloud.example.com/api/operator/v1/switches/maintenance

Only the operator surface can change this switch: an instance admin’s session or an operator token. A workspace token and a Management API token cannot. Every change made there writes an audit row with the actor type operator.

  • The server itself, at boot, when the row was set by the deploy hook (actor system:deploy-hook). A restart therefore never leaves the instance paused.
  • A person, when a person switched it on. A maintenance window you set yourself survives a restart and stays on until someone switches it off.

A deploy pipeline asks the server whether it has finished draining:

Terminal window
curl -fsS -H "Authorization: Bearer $SUPACLOUD_OPERATOR_TOKEN" \
https://supacloud.example.com/api/operator/v1/drain
{
"active_local_runs": 1,
"active_fleet_runs": 2,
"oldest_started_at": "2026-09-22T09:14:03Z",
"drain_complete": false,
"maintenance": true,
"maintenance_origin": "deploy_hook",
"draining": false
}
Field Meaning
active_local_runs Agent runs the server hosts itself that have not ended. These are the runs a restart would stop.
active_fleet_runs Open assignments on runners. A server restart does not stop them.
oldest_started_at When the oldest active local run started, or null.
drain_complete true when active_local_runs is 0.
maintenance Whether the maintenance switch is on.
maintenance_origin Who holds the maintenance window on, or null while it is off: deploy_hook or shutdown_drain (the next server start switches it off) or operator (it stays on across a restart).
draining Whether this server process is in its shutdown drain.

The answer contains counts only, no workspace, project or task, so an operator token learns nothing about tenants from it. It takes the same authorization as the switch: an instance admin’s session or an operator token. The operator console shows the same numbers under the switch list and refreshes them every 10 seconds while the tab is open.

  1. Run your image verification first. If the deploy can still be refused, refuse it before you switch maintenance on: a deploy that stops after the next step leaves the instance paused with no restart coming to clear it.

  2. Switch maintenance on with PUT /api/operator/v1/switches/maintenance.

  3. Poll GET /api/operator/v1/drain every few seconds until drain_complete is true or your budget (for example 10 minutes) runs out.

  4. Deploy. The new server switches maintenance off at boot when the deploy hook set it.

Let the hook fail open: if the server is unreachable, the token is missing or the budget runs out, continue with the deploy. The server’s own shutdown drain still protects the running work.

The deploy hook of the Blockworx deployments

Section titled “The deploy hook of the Blockworx deployments”

Stage and prod run this pipeline as a deploy hook (/opt/bw/supacloud-drain/drain, installed by bw-infra roles/supacloud_drain_hook). It behaves as follows, which is what its lines in the Periphery or Ansible log ([supacloud-drain] …) report:

  • It drains only when the deploy replaces the server image. It compares the supacloud-server image in the compose file of the deploy with the image of the running container. When they are equal (another service changed, or an apply without a new image pin) it logs keeps image …; this deploy does not replace it, nothing to drain and does nothing: that deploy does not restart the server, so no restart would switch maintenance off again. If such a deploy recreates the server anyway, the server’s own shutdown drain still applies.
  • It leaves a maintenance window that is already on exactly as it was set. When the drain endpoint reports "maintenance": true, it does not write the switch again, so an operator’s window keeps its actor and survives the restart. Otherwise it switches maintenance on with the reason pre-deploy drain; that exact reason records the change under the actor system:deploy-hook, which the new server clears at boot.
  • It fails open, except for live agent work on prod. A missing container, a missing operator token or an unreachable drain endpoint each log a line and let the deploy continue. An elapsed budget does the same on stage; on prod the hook refuses the restart instead (see below). Every HTTP call runs inside the server container, so the token never leaves it.
  • Stage: Komodo runs it in the pre_deploy of the SupaCloud stack, after verify-stack, so a deploy that the image signature check refuses stops before maintenance is on. The operator token comes from the SOPS secret bw_stage_supacloud_operator_token through the Komodo variable STAGE_SUPACLOUD_OPERATOR_TOKEN.
  • Prod: the Ansible role runs it after the image signature check and before the stack is recreated, and never under --check. The operator token is stored in OpenBao at supacloud/operator, key token. On prod the hook refuses the restart when agent containers are still working once the budget has elapsed (bw_supacloud_drain_refuse_while_active: true): it logs REFUSING the restart: agent work is still active, exits 1, and the apply stops before the stack is recreated. To restart anyway, run the apply again with -e bw_supacloud_force_restart=true.

The server’s stop_grace_period on both deployments is 11 minutes, longer than the 10-minute shutdown drain, so Docker does not stop the server in the middle of it.

Variable Default Bounds
SUPACLOUD_SHUTDOWN_DRAIN_SECONDS 600 At least 30, at most 3600. How long the shutdown drain waits for the checkpointed runs before it stops their containers.
SUPACLOUD_LIVENESS_BOOT_GRACE_SECONDS 300 At least 90. How long after boot the runner liveness sweep demotes no runner.

An unparseable or non-positive value falls back to the default; a value outside the bounds is moved to the nearest bound.

To get the pre-drain behaviour back (stop agents almost at once), set SUPACLOUD_SHUTDOWN_DRAIN_SECONDS=30.

The server exports six series on /metrics (see Observability: Prometheus, Grafana and the nightly load checks):

Series Type Meaning
supacloud_runs_checkpointed_by_drain_total counter Runs that ended inside the drain budget.
supacloud_runs_killed_by_shutdown_total counter Runs still alive at the drain deadline, whose container was stopped.
supacloud_runner_controls_dropped_total{reason="over_ceiling"} counter Controls refused because a runner’s run already had 16 undelivered ones.
supacloud_runner_relay_events_total{outcome} counter Events runners relayed, by what the server did with them: ingested, redelivered (a duplicate, stored once), late_terminal_skipped, refused_not_owned, refused_stale_epoch, refused_closed, refused_gate_not_persisted (a relayed gate whose durable approval row could not be written; the batch fails so the runner re-delivers), skipped_unpersistable (an event the database refused for its content; a marker line in the run’s log names the count), or lost_runner_spool_full / lost_runner_spool_expired / lost_runner_oversized (reported by the runner).
supacloud_maintenance_mode gauge 1 while the maintenance switch is on, else 0.
supacloud_maintenance_origin{origin} gauge 1 for the origin that holds the window on (deploy_hook, shutdown_drain or operator), 0 for the others; all 0 while maintenance is off.

A rising supacloud_runs_killed_by_shutdown_total means agents do not finish their checkpoint inside the budget: either the budget is too short for your agents, or they ignore the instruction. A supacloud_maintenance_origin{origin="deploy_hook"} that stays at 1 means the deploy stopped after the hook switched maintenance on and no server start has cleared it; switch it off in the operator console. An operator window is intentional and stays on until a person switches it off.

A merge to main does not restart prod on its own. The two deployments take a build in two separate steps:

  1. Stage deploys on every merge. Once the deploy gate is green, the bump-supacloud-images job of build-push.yml opens the stage pin change in bw-infra and merges it. Komodo deploys it behind the drain described above.

  2. The prod pin change waits. The same job opens the prod pin change in bw-infra (chore(prod-supacloud): bump to <commit>) with the label promotion-pending and does not merge it. Its description ends with two lines the promotion step reads: stage_commit: <commit> and opened_at: <time in UTC>.

  3. The promotion step merges it once every condition holds. The last step of the same job, Promote prod-supacloud bumps whose stage soak elapsed (scripts/ci/promote-prod-supacloud.sh), promotes a waiting change only when all of these hold:

    • the time is inside the deploy window, 06:00 to 20:00 UTC;
    • stage answers /health with the global_dispatch switch enabled;
    • stage’s /version.json names the commit the change pins;
    • the stage core-loop check has passed on that commit (see below);
    • the change has waited at least 60 minutes (the soak).

    It then adds auto-merge, merges the change once its checks succeed, and closes the older waiting changes that this one replaces, so an older build can never reach prod later. When a condition does not hold, the step writes a notice and the change waits.

The promotion step runs whenever the job runs: on the next merge to main, or when you start build-push.yml by hand with workflow_dispatch. On a quiet day a soaked change therefore waits for the next merge or a manual run.

The stage core-loop check. The smoke-e2e job of e2e-nightly.yml (daily at 06:00 UTC, and on workflow_dispatch) signs in to stage as a synthetic user and runs the core-loop journeys read-only: the task list and one task, the web terminal, the backlog and one run. It records the result for the commit stage served during the whole check as the Forgejo generic package supacloud-stage-core-loop/<commit>/result.json, with the fields commit, passed, ran_at and run_url. A commit that reached stage after the morning run can be promoted once you start e2e-nightly.yml by hand and the check passes. The check needs the secrets STAGE_SYNTHETIC_EMAIL and STAGE_SYNTHETIC_PASSWORD; without them it records nothing, and no prod change is promoted.

Promote by hand. Start build-push.yml with workflow_dispatch so the promotion step checks again, or add the label auto-merge to the waiting prod change in bw-infra yourself. A rollback is a hand-written change that moves the tag and all three digests together.

Force a prod restart. While agent containers are still working after the drain budget, the prod apply refuses the restart. Run it again with -e bw_supacloud_force_restart=true to restart anyway. The runs the drain could not checkpoint are stopped, and their rounds are put back in the queue at the next boot.

Alerts. Prometheus raises SupacloudRestartChurn when supacloud-server has started more than six times in a day on one host (changes(container_start_time_seconds{name="supacloud-server"}[1d]) > 6), and SupacloudRunsKilledByShutdown when supacloud_runs_killed_by_shutdown_total has increased within an hour. The second alert needs a Prometheus scrape of the server’s /metrics.

A task whose run was interrupted and that is not a backlog item shows the status Interrupted and a Resume button on its detail page. Resume restarts the same task on the same branch (it uses the existing restart, POST /api/tasks/{id}/restart), so the agent continues from the checkpoint commit. Backlog items need no action: the boot puts them back in the queue.