Ephemeral DigitalOcean droplets for Forgejo Actions and Radicle CI, from one daemon
README.md

ci-autoscaler #

Ephemeral DigitalOcean droplets for CI. It is one daemon that creates a droplet for each queued Forgejo Actions job and for each Radicle CI run, and destroys it when the work is done. Every source draws on the same capped pool of droplets in each size tier.

It replaces the six Python provisioner services on cloud04, one per forge and tier, that did this for Forgejo, and adds Radicle to the same pool.

ci-top, built beside it, shows the whole fleet in a terminal: the work waiting, the droplet each job is on, and what finished lately. See Watching it: ci-top.

The API documentation is at https://jeff.jcollie.page/ci-autoscaler/. It is generated from the doc comments.

Design #

The daemon owns the whole ephemeral fleet in one DigitalOcean team:

  • Forgejo. It polls each configured forge (an instance-admin scope or an ordinary user scope) for jobs waiting on a nixos-do-<tier> label. For each one it registers an ephemeral runner, a Forgejo 15 feature that runs exactly one job, and boots a droplet that runs forgejo-runner one-job for it.
  • Radicle. radicle-ci-broker, next to a Radicle node, runs ci-autoscaler adapter for each push or patch from a repository delegate when the commit has a .radicle/droplet.yaml. The adapter hands the commit to the daemon over a Unix socket and waits. The droplet fetches the job and the source from the daemon, and streams its log back.
  • Capacity. Each tier (for example s, m, l) has one cap on concurrent droplets, shared across all sources, and the oldest waiting work goes first.

Every droplet boots the same way, whatever it is for. Its user data holds a token minted for that one droplet and nothing else; ci-agent starts, asks the daemon over HTTPS what the droplet is for, and is handed either the Forgejo job with its runner's credentials or the Radicle run. When the work is over the agent says so, and the droplet is destroyed on the scheduler's next pass rather than when the forge is next polled. Keeping the runner's token out of the user data also keeps it out of DigitalOcean's metadata service, where anything on the droplet could read it back.

The user data also turns off DigitalOcean's vendor data. On a one-job droplet it only installs DigitalOcean's droplet agent (for the web console), sets up VPC peering routes and a resolver, and seeds entropy, and it cost every boot about 25 seconds. Without it, the droplet reaches its agent about 17 seconds after the kernel starts rather than about 42. SSH, if it is ever needed for debugging, is as ubuntu with sudo rather than as root.

resolvers names DNS resolvers for every droplet, as IP addresses: one in the droplets' own VPC, say, whose cache stays warm across jobs where a droplet's own would start empty every time. They replace the droplet's systemd-resolved list, for the runner and the agent, and go into podman's dns_servers, for the job's containers. fallback_resolvers follow them in both, so that a resolver that is down costs a timeout rather than a failed job. The network interfaces are taken off resolved's default route, so the resolver DigitalOcean puts on each of them is not asked as well.

The daemon keeps a record of every droplet in SQLite: its token, the work it is bound to, and when each step of its life happened. Its name (ci-droplet-<id>) and tags (ci-ephemeral, ci-<source>-<tier>, cidroplet-<id>) tie it to that record, and those are checked before any droplet is destroyed, so nothing the daemon did not make is ever touched.

A .radicle/droplet.yaml looks like this:

tier: l            # s | m | l
image: ...         # optional; defaults to the configured runner image
shell: |
  nix develop -c zig build test --summary all

The script runs with bash -eo pipefail in the image, in a checkout of the commit, with /dev/kvm when the droplet has it and the same NIX_CONFIG a Forgejo job gets. A file that names an unknown tier or has a key other than these three is refused, and the run fails with the reason on its page.

Seeing results #

A run starts when a delegate pushes to the default branch, or opens or updates a patch, and the commit has a .radicle/droplet.yaml. Its result can be read in three places.

The run's page, <public_url>/runs/<id>, shows the repository, the branch or patch, the commit, the result with the reason for a failure, and the full log. It reloads itself until the run ends. The log alone is at <public_url>/runs/<id>/log.txt.

The broker's report, <public_url>/reports/, lists every repository the broker has run for, with its recent runs and their results.

Your own node. The broker records each result as a job record (a xyz.radworks.job collaborative object) on the commit, signed by the CI node. A node receives these only from nodes it follows, so follow the CI node once:

$ rad follow <ci node id> --alias <ci node alias>

rad itself has no command for job records. rad job, from the separate radicle-job package in nixpkgs, reads them and prints JSON:

$ rad sync --fetch
$ rad job list                     # every commit with a result
$ rad job show <full commit id>    # one commit's runs

rad job show takes the commit's full 40-character id. Each run in its output gives its status ("Finished": "Succeeded" or "Failed") and, as log, the link to the run's page:

{
  "oid": "0d2b0335d245f58375385a9ebb076a72d9398a48",
  "runs": [
    {
      "node_id": "z6Mkrjf3TtWhMui5uyAXFUwHrMpTwYrpHtSDCgPEyrhLK3ue",
      "runs": [
        {
          "status": { "Finished": "Succeeded" },
          "log": "https://ci.jcollie.dev/runs/2"
        }
      ]
    }
  ]
}

None of these pages is for search engines: /robots.txt disallows everything, and every response carries X-Robots-Tag: noindex, nofollow. Runs and their logs are kept for retention_days, 90 by default.

For every source at once, Forgejo jobs included, use ci-top.

What runs where #

  • ci-autoscaler serve is the daemon. It serves the adapter's API on a Unix socket and the droplets' API on TCP, for a reverse proxy to put on the internet.
  • ci-autoscaler adapter is the command radicle-ci-broker runs for each event. It runs as the broker's user, reads the commit's droplet.yaml and a tarball of its tree out of the node's storage, hands them to the daemon, and waits for the result.
  • ci-agent is what every droplet runs. The droplet downloads it from the daemon at boot and checks it against a SHA-256 in its user data. It claims the droplet's work. For a Forgejo job it writes the runner's configuration and runs forgejo-runner one-job. For a Radicle run it fetches the job and source, runs the script under podman, and streams the output back. The daemon never connects to a droplet: every exchange is a request the droplet makes, with a token that names that droplet and stops working when it is destroyed.

Warm droplets #

Most of the wait for a fresh droplet is DigitalOcean making it: about 35 seconds before its kernel starts, which nothing on the droplet can shorten. A tier's warm count hides it. For warm_linger_seconds (15 minutes by default) after work last started in a tier, the daemon keeps that many idle droplets in it booted and waiting. Jobs come in bursts, the rest of a workflow or the next push, and the next piece of work is handed to one of these instead of waiting for a new droplet.

A warm droplet is created bound to nothing, tagged ci-pool-<tier>. Its agent calls /droplet/v1/claim as any droplet's does, and the daemon holds the request, 25 seconds at a time, until the scheduler gives it work. For a Forgejo job, the runner is registered at that moment. Each warm droplet still runs exactly one job and is then destroyed, so isolation between jobs is what it always was.

  • Warm droplets count against their tier's max, and queued work always comes first. A job takes a warm droplet before a new one is made, a booted one before one still booting. The pool is topped up only from the room queued work leaves.
  • When the tier goes quiet past the linger, its warm droplets are destroyed. So is one beyond the tier's count, one booted from a snapshot that has since been replaced, one whose agent never called, and one silent past heartbeat_timeout_seconds.
  • The wait phase in the metrics runs from work being seen to its droplet claiming it. It is the wait a job actually has, and the one a warm droplet shortens.

Polling Forgejo, and webhooks #

Forgejo jobs are found by polling each forge's runner API, every poll_seconds. Three things bring a poll forward.

  • A droplet says it is done. The next job of the same workflow usually becomes waiting as this one ends, so the daemon polls that forge 1, 3 and 8 seconds later.
  • A webhook arrives. Give a forge a webhook_credential (a systemd credential holding a secret), and point a webhook at <public_url>/forgejo/<forge name>/webhook, signed with that secret. A webhook of type push, create, release, pull_request, pull_request_sync or workflow_dispatch gets the same three polls. A workflow run is made from the same event, a moment later. On a Forgejo instance this is one system webhook in the site administration; on a shared one, a webhook on the account or organization.
  • The scheduler is woken by either of those, and by a new Radicle run, so none of them waits out tick_seconds.

A webhook is only a prompt to poll. Nothing is provisioned from its payload, which is not even parsed, so a forged or replayed delivery costs a few API calls and no more. Anything unsigned or wrongly signed is refused, as is a webhook for a forge with no secret, or a payload over 1 MiB.

A webhook for the job itself would be better still, but the Forgejo this runs against does not send one. Forgejo 16.0.4, checked against modules/webhook/type.go at the v16.0.4 tag, has only action_run_success, action_run_failure and the like, which fire when a whole run ends.

Forgejo's v17.0/forgejo branch adds workflow_job_* events, among them workflow_job_waiting. It is sent when a job's status becomes waiting (convertJobStatusToHookEventType in services/webhook/notifier.go). Its payload is the job and its run, and the job carries the handle and runs_on that polling reads. It can be a system webhook, covering every repository on an instance. As of 2026-09-28 the only v17 tag is v17.0.0-dev.

Once a forge runs a release with it, the webhook should prompt an immediate poll of that forge rather than provision from its payload. The forge's API stays the source of truth, a lost or forged webhook cannot create a droplet, and polling remains as the backstop. Codeberg reports its version as 16.0.0-dev-753, so whether it sends these events has to be tried rather than assumed. There, the hook would be a user webhook, not a system one.

Measuring droplets #

Each droplet's record carries a timestamp for every step:

  • when its work was first seen waiting;
  • when the droplet was asked for, and when DigitalOcean first called it active;
  • when its kernel started, from the uptime the agent reports on its first call;
  • when the agent first called, and when it was given its work;
  • when the work started and ended;
  • when the droplet was destroyed.

The first call also carries a boot report (systemd-analyze blame, cloud-init's own timings, and when each boot milestone was reached), kept in the droplet's record.

With metrics_listen set, the daemon serves Prometheus text at /metrics:

  • ci_autoscaler_droplet_phase_seconds{phase,tier,source}, a histogram of each span between those steps, observed when a droplet is destroyed. The phases are queue, active, provision, boot, claim, start, work and reap.
  • ci_autoscaler_droplets{tier,state}, the droplets standing right now.

Where the time goes between creation and a job starting can be read from these: DigitalOcean's side (provision), the guest's boot and cloud-init (boot), or the runner (start).

Building #

$ nix develop
$ zig build test --summary all
$ zig build

Dependencies are fetched by the Zig build system. nix build gets them from build.zig.zon.nix instead, which is generated. After any change to build.zig.zon, regenerate it:

$ nix develop -c zon2nix --16 --nix=build.zig.zon.nix build.zig.zon

The dependencies are:

  • zig-http, the HTTP client and server.
  • zig-dns-client, for name resolution. It reads /etc/hosts the way the C library does.
  • zig-datetime, for timestamps.
  • zqlite, for SQLite. It is linked against nixpkgs' sqlite, not the bundled amalgamation.
  • libvaxis, the terminal library ci-top draws with. Only ci-top links it.
  • known-folders, for where ci-top finds its configuration file and writes its log.
  • zig-yaml, for .radicle/droplet.yaml. It comes from a fork, jeff/zig-yaml-kubkon, whose block-scalars-0.16 branch adds | and > block scalars to upstream's zig-0.16 branch, with upstream's fix for unclosed quotes and two more crashes on malformed input that fuzzing found. Upstream's main branch needs Zig 0.17.

tests/fuzz.zig holds properties of the trigger, droplet.yaml and configuration parsers, the droplet ownership check and the cloud-init renderer. They run on their seeds under zig build test, and zig build fuzz-run drives them with mutated inputs, as CI does for half a million per target:

$ zig build fuzz-run -- --seconds 600
$ zig build fuzz-run -- --target specs --iterations 1000000

zig build docs builds the API documentation and zig build docs-serve serves it on port 8000.

Running it #

$ CREDENTIALS_DIRECTORY=/path/to/credentials ci-autoscaler serve config.json --dry-run
$ CREDENTIALS_DIRECTORY=/path/to/credentials ci-autoscaler snapshot config.json

serve runs the scheduler. snapshot bakes the prepared image that job droplets boot from (podman, the runner binary and the job image) and keeps the newest snapshot_keep. It also masks the upkeep a long-lived Ubuntu machine runs, none of which a one-job droplet needs and all of which would compete with the job: apt's timers, unattended upgrades, snapd, the message of the day's news and changelog fetches, and Ubuntu Pro's hooks. It clears cloud-init's log, so a droplet's boot report shows the droplet's own boot. Run it again whenever the job image or the runner binary changes. Both read their tokens from systemd credentials: do-token, plus each forge's credential, plus status_credential if one is set. --dry-run logs what would be created and destroyed without doing either.

The configuration is JSON. src/Config.zig documents every field, and unknown fields are refused rather than ignored.

NixOS #

The flake's nixosModules.default provides services.ci-autoscaler:

services.ci-autoscaler = {
  enable = true;
  credentials = {
    do-token = config.age.secrets.digitalocean-ci-runner-token.path;
    forge-ocjtech = config.age.secrets.forgejo-runner-provisioner-token.path;
  };
  settings = {
    region = "nyc3";
    base_image = "ubuntu-26-04-x64";
    snapshot_prefix = "forgejo-runner";
    runner_image = "git.jcollie.dev/jeff/nixos-runner:50-1-0dbdc124";
    runner_binary_url = "https://code.forgejo.org/forgejo/runner/releases/download/v13.1.0/forgejo-runner-13.1.0-linux-amd64";
    runner_binary_sha256 = "29dae21e...";
    tiers = [ { name = "s"; size = "s-2vcpu-4gb"; max = 5; } ];
    forges = [ { name = "ocjtech"; url = "https://git.jcollie.dev"; credential = "forge-ocjtech"; } ];
  };
};

This runs ci-autoscaler.service, plus ci-autoscaler-snapshot.service on a weekly timer.

Every droplet asks the daemon for its work, so publicUrl is required. Put listen ([::1]:8094 by default) behind a reverse proxy at that URL. metricsListen serves /metrics on an address of its own. statusTokenFile serves /status, for ci-top, on the public listener, to requests that present the token in it:

services.ci-autoscaler = {
  publicUrl = "https://ci.example.org";
  metricsListen = "127.0.0.1:9356";
  statusTokenFile = config.age.secrets.ci-autoscaler-status-token.path;
};

Make the token with openssl rand -hex 32. The daemon refuses one shorter than 32 bytes, since anyone who can reach the public URL can guess at it.

For Radicle, add radicle.enable and point radicle-ci-broker at the adapter:

services.ci-autoscaler.radicle.enable = true;

services.radicle.ci.broker.settings = {
  adapters.droplet.command = "${config.services.ci-autoscaler.radicle.adapterCommand}";
  triggers = [
    {
      adapter = "droplet";
      filters = [
        {
          And = [
            { HasFile = ".radicle/droplet.yaml"; }
            "AnyDelegate"
            { Or = [ "DefaultBranch" "PatchCreated" "PatchUpdated" ]; }
          ];
        }
      ];
    }
  ];
};

The module makes the adapter's socket with a .socket unit, as group radicle and mode 0660, so only the broker's user can reach it. It keeps the database of droplets and runs in /var/lib/ci-autoscaler.

Watching it: ci-top #

ci-top shows what the daemon knows, in one screen, refreshed every few seconds:

  • a line per tier, with how many of its droplets stand against its cap;
  • a line per forge, with when it was last polled and whether that failed;
  • Pending: the work waiting for a droplet, oldest first, and any whose droplet could not be created and is waiting out a backoff;
  • Running: every droplet being created, booting or at work, with the job or run it is for and the step of its life it is in;
  • Finished: droplets whose work is over, most recent first, with how it went and how long it took, and Radicle runs that ended without a droplet.

Enter on a row shows its details: the droplet's DigitalOcean id and size, the job or run, and how long each step took (the same steps as the ci_autoscaler_droplet_phase_seconds metric).

$ ci-top --url https://ci.example.org --token-file ~/.config/ci-top/token
Key Does
q, ctrl-c quit
r refresh now
tab, shift-tab (or l, h) switch list
j, k, arrows, page up and down move
g, G first, last row
enter details
esc close details

It reads GET /status on the daemon's public URL, which answers only when status_credential (NixOS: statusTokenFile) is set, and only to that token. The answer is JSON, api.status.Status in src/status_protocol.zig. ci-top never needs the DigitalOcean or forge tokens.

The daemon and ci-top are usually built at different times, so ci-top reads a document from a newer daemon rather than refusing it. It ignores fields it does not know, and shows a kind of work, a state or a result it does not know as unknown. When the document's version is newer than its own, the header says to update ci-top.

Each option is taken from the first of these that gives it:

  1. its flag: --url, --token-file, --interval (seconds, default 5), --hours of finished work to show (default 24), --limit on how many (default 50);

  2. the environment: CI_TOP_URL, and CI_TOP_TOKEN (the token itself) or CI_TOP_TOKEN_FILE;

  3. the configuration file, ci-top/config.json under the configuration directory ($XDG_CONFIG_HOME, or ~/.config), or the file --config names:

    { "url": "https://ci.example.org", "token_file": "/run/secrets/ci-top", "interval": 5, "hours": 24, "limit": 50 }
    

    Unknown fields in it are refused.

There is no flag for the token itself, so it never shows in ps. When a fetch fails, the last good answer stays on screen, marked STALE with the reason. A daemon whose scheduler has not finished a pass in two minutes is marked as well. Anything ci-top logs goes to ci-top/log under $XDG_STATE_HOME (~/.local/state), not the terminal.

Forgejo's job listing names a job by an opaque handle and, where the forge gives it, the job's name, but says nothing of its repository or run. So a Forgejo row shows the job's name or handle and has no link. A Radicle row links to its run's page.

Home Manager #

The flake's homeModules.default (also homeManagerModules.default) installs ci-top and writes its configuration file:

{
  inputs.ci-autoscaler.url = "git+https://git.jcollie.dev/jeff/ci-autoscaler.git";

  # in the Home Manager configuration:
  imports = [ inputs.ci-autoscaler.homeModules.default ];
  programs.ci-top = {
    enable = true;
    url = "https://ci.example.org";
    tokenFile = config.sops.secrets.ci-top-token.path;
  };
}

tokenFile is a string rather than a path, so the token is never copied into the store. interval, hours and limit are there too, and settings is written over all of them.

Checking connectivity #

probe makes one authenticated GET, using the same HTTP client and resolver the daemon uses, and prints the status and the start of the body:

$ CI_AUTOSCALER_TOKEN=... ci-autoscaler probe https://api.digitalocean.com /v2/account
$ ci-autoscaler probe https://git.jcollie.dev /api/v1/version token

Where this lives #

The repository is on Forgejo, which is where its CI runs and its documentation is published from:

git clone https://git.jcollie.dev/jeff/ci-autoscaler.git

It is mirrored on Tangled at https://tangled.org/jcollie.dev/ci-autoscaler.

It is also on Radicle. A Radicle repository can only be found by its ID, so here it is:

rad clone rad:z2eDxErDjXEAiYHf7SJYNDnT9Ytaa

License #

MIT. The project follows REUSE; reuse lint checks it.

References cited #

These are held in the ci-autoscaler Zotero collection.