forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.09.2 MiBbcaef90Tahinli1 month ago164 commits

ci.md39.8 KiBHistoryRawDownload

CI

forge runs CI workflows defined in .forge/ci.toml at the root of a repository. Jobs run on separate runners, which are forge runner on machines you control. The forge never connects to a runner. Runners pull jobs over HTTPS.

What v1 has: jobs with needs, secrets, artifacts, a build cache, live logs, commit statuses, and manual, push, tag and pull request triggers. What it does not have: YAML. The workflow file is TOML.

Jobs run in a rootless sandbox, with no container tool needed. The runner pulls and unpacks the image itself, and runs each job in its own container built with libcontainer, the crate behind youki. Each job gets its own container, its own workspace, and a read-only token. Podman is still supported as an option (executor = "podman").

Format reference

The file is limited to 64 KiB. Parsing is forward-compatible: an unknown key at any level (top level, [on], [jobs.<name>], [release]) is ignored, not rejected, so a ci.toml that uses a newer feature still runs on an older forge. The run page shows the ignored keys in a warning banner, and the run's jobs get a [forge] warning: unknown key ... line at the start of their logs. For example on.schedule is not supported and shows up this way. Known keys keep full validation: their types, globs, limits and other checks still make the file an error. A file with a parse error still creates a run, in state error, with the message shown on the run page and a ci/config status set to error.

Top level

Key Type Default Meaning
name string none The workflow's name, used as the label of the status badge. 1 to 40 characters after trimming, no control characters.

[on]

Key Type Default Meaning
push array of string [] Branch globs. A push to a matching refs/heads/* starts a run.
tags array of string [] Tag globs. A push of a matching refs/tags/* starts a run.
pull_request bool false Start a run when a pull request is opened, updated or reopened. The config is read at the head commit.
manual bool true Writers can start a run on an existing branch from the CI tab.
cancel_superseded bool true A push to a branch cancels the queued and running runs for older commits on that branch (see Superseded runs).
schedule array of string [] Cron expressions (5 fields, UTC). See Scheduled runs. Max 8.
merge_queue bool false Run the workflow on each merge queue candidate of a branch that requires the queue. Without it, a candidate runs the push jobs of its target branch. See Merge queue.

[jobs.<name>]

There must be at least one job, and at most 20.

Key Type Default Rules
image string none Required. Non-empty, no whitespace. Image reference, pulled by the runner.
run string none Required. Non-empty. Runs as sh -eu -c "<run>" in /workspace.
needs array of string [] Job names that must succeed first. Must exist. No cycles.
secrets array of string [] Repo secret names, each ^[A-Z_][A-Z0-9_]{0,63}$. Exported as env vars.
env table of string {} Plain env vars. Names match the same pattern. A secret with the same name wins.
artifacts array of string [] Relative globs in the workspace. No .., no leading /.
runs_on array of string [] Runner labels. Every label must be present on the runner.
cache array of string [] Workspace-relative directories to keep between runs. Max 8. See Cache.
timeout_minutes integer 60 Range 1 to 360.
memory string none The job's expected peak memory, such as 4g or 512m. 64m to 1024g. See Memory.
matrix table none Expands the job into one job per combination. See Matrix builds.
network bool true false gives the job an empty network namespace (loopback only). true shares the runner host's network namespace. Read the caveats.

Job names match ^[a-z0-9][a-z0-9_-]{0,39}$.

The job's workspace is a fresh checkout of the exact commit, at /workspace. The job starts in that directory.

Memory

memory is optional. You do not need it: the runner reacts to real memory use instead of trusting a number. When you set it, it is a hint for admission and an explicit cap for the job.

[jobs.build]
image = "docker.io/library/rust:1"
run = "cargo build --release"
memory = "4g"   # optional

What the runner does without it:

  • Optimistic admission. A job without memory reserves the runner's default (limits.reserve_memory, 1g unless an admin changed it) and may use up to the whole memory budget of the runner. The runner tells the forge how much memory its box has left with every claim, and the forge hands out the first queued job whose reservation fits. A smaller job may run before a bigger one that has to wait. To keep the big job from starving, a job that does not fit and has waited 5 minutes stops smaller jobs from passing it on that runner. A job that asks for more than the runner's whole budget runs alone.
  • Pause and park. The runner puts all job cgroups in one box (forge-jobs) capped at the memory budget. When two or more jobs run and the box nears its cap, the runner freezes the youngest job and pushes its memory to swap, and logs runner: paused: memory pressure, waiting for <job> and runner: parked <n> MiB in swap in that job. The older job keeps its RAM and finishes. The parked job thaws when the box has room for what is in its swap or nothing else runs, and logs runner: resumed after <time>. The time a job spent frozen does not count toward its timeout_minutes. While a job is parked the runner claims no new job.
  • Requeue. If the parked job's memory does not go to swap (the host has no free swap, or the kernel refuses), the runner kills it and gives it back to the queue, keeping its place. It is not reported as failed.
  • A lone job is never paused. It may use the whole box, and if it runs out of memory it is OOM-killed and reported as below.

With memory set:

  • The job's cgroup memory.max (podman --memory) is memory plus slack (1/16, at least 256 MiB), and swap is off for the job (memory.swap.max is 0) while it runs. A job that goes over is OOM-killed inside its own cgroup. Without memory, the limit is the box budget. Podman jobs keep the larger of the runner's limits.memory and limits.reserve_memory.
  • The reservation is memory instead of the default, which keeps a job that you know is heavy from being started next to another one.
  • It is the same for every job in a matrix.

Host requirements for pausing: swap must be present (a parked job lives in swap), and the user the runner runs as needs the memory, cpu and pids cgroup v2 controllers delegated (see Check the host). Without delegated controllers, or on the podman executor, the runner works as before: no box, no pausing.

OOM kills are reported. When a job ends, the builtin executor reads the job cgroup's memory.events before the cgroup is deleted, and the runner sends oom_killed and oom_kills in the finish request. A job where rustc was killed still ends with exit 101 and only a signal: 9 line in its log, so the exit code never showed it. The job page then says "killed: out of memory", and the admin alert for killed jobs fires. The counters are the kernel's oom_kill (processes of the cgroup killed by any OOM killer, a host-wide one included, since Linux 4.13) and oom (the cgroup hit its own limit). A process killed outside the job's cgroup is not counted. The podman executor does not report this.

A forge that predates requeue answers the runner's requeue call with an error. The runner then fails that job instead.

Example

[on]
push = ["main", "release/*"]
tags = ["v*"]
pull_request = true
manual = true

[jobs.test]
image = "docker.io/library/rust:1"
run = "cargo test --workspace"
timeout_minutes = 30

[jobs.package]
image = "docker.io/library/rust:1"
needs = ["test"]
run = """
cargo build --release
mkdir -p dist
cp target/release/forge dist/
"""
artifacts = ["dist/*"]

[jobs.deploy]
image = "docker.io/library/alpine:3"
needs = ["package"]
runs_on = ["linux", "x86_64"]
secrets = ["DEPLOY_KEY"]
env = { TARGET = "staging" }
network = true
run = "sh ./deploy.sh"

Artifacts are stored under the flattened name: dist/forge is stored as dist_forge.

Triggers and glob rules

  • Branch and tag globs use * and ** with / as a separator. * matches within one path segment and does not cross /. ** matches across segments.
    • release/* matches release/1.2, but not release/1.2/hotfix.
    • release/** matches both.
    • main matches only main.
  • Artifact globs follow the same rule. out/*.txt matches out/a.txt, not out/sub/a.txt.
  • Jobs whose needs fail or are skipped are marked skipped. A skipped job gets the status ci/<job> = error with the description skipped.

Scheduled runs

[on]
schedule = ["0 3 * * *", "30 12 * * 1"]

Each entry is a standard 5-field cron expression, minute hour day-of-month month day-of-week, evaluated in UTC. A server-side scheduler checks once a minute. When an expression matched since its last check, it reads .forge/ci.toml from the head of the default branch and queues one run of that commit. The run's trigger is schedule (shown as "scheduled") and its ref is the default branch.

  • The config is read from the default branch at each tick, so a schedule change takes effect without a push, and a schedule on any other branch is ignored.
  • Catch-up happens at most once. If the forge was down across several matches, it queues a single run when it comes back, not one per missed match.
  • A repo is looked at for the first time from now on, so adding a schedule does not run anything until its next match.
  • Archived repos are skipped, and nothing is queued while CI is disabled in the server settings.
  • A ci.toml that does not parse queues no scheduled run.
  • The repo's CI page shows the next scheduled run, from the earliest match of all entries.
  • An expression with 6 fields (seconds) is rejected. Use */5 * * * * for the fastest practical rate; there is no minimum interval, so a * * * * * schedule queues a run every minute.

Matrix builds

[jobs.test]
image = "docker.io/rust:${{ matrix.rust }}"
run = "cargo +${{ matrix.rust }} test --target $MATRIX_TARGET"
matrix = { rust = ["stable", "1.85"], target = ["x86_64", "aarch64"] }

A job with matrix is expanded when the file is parsed, into one job per combination of the axis values (here 4). The jobs are named test (1.85, aarch64), test (1.85, x86_64), test (stable, aarch64) and test (stable, x86_64): the values joined with , , with the axes in alphabetical order of their names. Each one is an ordinary job, with its own log, status (ci/test (stable, x86_64)) and runner. The run page lists them together under the base name.

  • Axis names match ^[a-z][a-z0-9_]{0,31}$. Values are strings, integers or booleans (read as text), 1 to 64 characters, with no control characters, commas or parentheses.

  • Every combination gets the env vars MATRIX_<KEY> (the axis name in upper case), for example MATRIX_RUST=stable. A matrix value overrides an env entry with the same name.

  • ${{ matrix.key }} and the shorter ${matrix.key} are replaced in image, run and runs_on. A key that is not an axis (or an include key) is an error. Any other ${...}, such as ${HOME}, is left to the shell.

  • exclude is a list of tables. A combination that agrees on every key of an entry is dropped. An entry may name just one axis, which drops every combination with that value.

  • include is a list of tables. Each adds one combination, so it must set every axis, and it may carry more keys, which become MATRIX_<KEY> env vars too but are not part of the job name. An entry that repeats an existing combination adds nothing.

    matrix = { rust = ["stable", "1.85"], target = ["x86_64", "aarch64"], exclude = [{ rust = "1.85", target = "aarch64" }], include = [{ rust = "nightly", target = "x86_64", flag = "-Zunstable" }] }
    
  • needs = ["test"] on another job waits for all combinations of test. A matrix job's own needs apply to each of its combinations.

  • [release] assets = ["test:*.tar"] selects the artifacts of every combination of test.

  • The 20 job limit counts expanded jobs. A matrix that alone expands past it, or a workflow that reaches it through expansion, is rejected with an error that names the job and the count.

Fail fast

When a job fails or errors, the forge cancels every other job in the run at once: queued and blocked jobs become cancelled, and jobs that are already running are told to stop through their heartbeat, so the runner aborts them and they end cancelled. The run ends failure, so no release is published and no self-update happens. A long build does not keep compiling after test fails.

Superseded runs

By default ([on] cancel_superseded = true), a push to a branch cancels the runs that are still queued or running for older commits of the same branch when its own run is created. Queued and blocked jobs become cancelled at once and running jobs are told to stop through their heartbeat, as with the run's Cancel button. Only runs that were started by a push are cancelled: manual, tag and pull request runs are left alone, and so are runs that have already finished. The key is read from the new commit's ci.toml, and it is on by default. Set cancel_superseded = false to keep every run.

Re-running

A finished run has three re-run controls on its page (writers only):

  • Re-run creates a new run with every job of the original run.
  • Re-run failed jobs creates a new run with only the jobs that ended failure, error or cancelled, plus every job that depends on them, directly or not. Jobs that succeeded are not run again. A needs entry that points at a job that is not in the new run is dropped, since that job already succeeded.
  • Re-run this job (on the job page, and on each job row of the run page) creates a new run with that finished job and the jobs that depend on it.

A re-run always uses the original specs: the same commit, ref, trigger and job definitions as stored when the original run was created. It does not read ci.toml again, so an edit to the file does not change a re-run. The config warnings of the original run are carried over. To pick up a changed ci.toml, push a commit or start a manual run.

Artifacts

The run page lists the artifacts of all its jobs, each with a download link, and Download all (.zip) which serves every artifact in one zip with a folder per job (<job>/<artifact>). Anyone who can read the repo can download them. A run whose artifacts add up to more than 256 MiB offers the single downloads only.

Job logs

The job page renders the log with ANSI colours (the sixteen named colours follow the theme, so they read in light and dark), numbered lines with #L123 anchors, and a search box (Enter and Shift+Enter move between matches). A line that is exactly ::group::name starts a collapsible section and ::endgroup:: ends it. The markers themselves are not shown. Streaming keeps working while the job runs. The page shows the last 512 KiB; the full log is at log.txt.

Releases

A [release] table publishes a release from a tag run. It needs at least one glob in [on] tags.

When a tag push matches on.tags and every job in the run succeeds, the forge creates the release for that tag and attaches the selected artifacts. If a release for that tag already exists, for example one you made by hand, the forge updates it: the existing title and notes are kept, and the selected artifacts are attached, replacing any asset with the same name. A run where any job fails or is skipped creates no release. The job needs no token and no curl.

This holds when jobs run in parallel. If the job that produces the artifacts (say build) finishes green while another job (say test) is still running or later fails, nothing is published: the release waits for the whole run to be success. The forge's own server self-update follows the same rule and only deploys a run whose every job succeeded.

For scripted control, use the REST API with a personal access token stored as a repo secret. See api.md.

The release list and each release page update live: a release created, edited or deleted by CI or by hand, an asset added or removed, and a download count moving all appear without a reload.

Key Type Default Meaning
assets array of string [] "<job>:<glob>" entries. The glob matches that job's flattened artifact names (see below). Max 32. A job named here must exist and declare artifacts.
prerelease "auto", true, false "auto" "auto" marks the release a prerelease when its tag contains -, e.g. v1.2.0-rc1.
draft bool false Create the release as a draft.
notes "commits" or "none" "commits" "commits" writes one line per commit since the previous release tag. "none" writes no notes.
title string "{tag}" Release title. {tag} is replaced by the tag name. It is the only placeholder. 1 to 200 characters after trimming, no control characters.

Asset globs follow the glob rules. Artifact names are flattened, so the glob cannot contain /. dist/forge-linux-x86_64 is stored as dist_forge-linux-x86_64, so it is selected with build:dist_forge-*. A [release] table with no assets creates a release with notes only.

The notes list at most 200 commits, newest first, and end with a Full changelog: <previous>...<tag> line when a previous tag is known. The previous tag is the newest other published release whose commit is an ancestor of the tag, or else the closest git tag reachable from it. If the release is made, the release is attributed to the run's actor. A system run, such as a mirror update, falls back to the repo owner, and to the ghost account when the owner is an organization.

The outcome is written as a [forge] Published release <tag> with N assets. line at the end of the log of the run's last job. A failed asset is listed on that line, and the release still stands.

Example. The build job packages binaries into dist/, and test must also pass before any release is made:

name = "release"

[on]
tags = ["v*"]

[jobs.test]
image = "docker.io/library/rust:1"
run = "cargo test --workspace"

[jobs.build]
image = "docker.io/library/rust:1"
needs = ["test"]
run = """
cargo build --release
mkdir -p dist
cp target/release/forge dist/forge-linux-x86_64
cp target/release/forge-runner dist/forge-runner-linux-x86_64
cd dist && sha256sum forge-linux-x86_64 forge-runner-linux-x86_64 > SHA256SUMS
"""
artifacts = ["dist/*"]

[release]
assets = [
  "build:dist_forge-linux-*",
  "build:dist_forge-runner-linux-*",
  "build:dist_SHA256SUMS",
]
prerelease = "auto"
draft = false
notes = "commits"
title = "forge {tag}"

With this file, pushing v1.2.0-rc1 creates a prerelease titled forge v1.2.0-rc1 with the three files attached. The dist_ prefix comes from flattening dist/.

Commit statuses

Every job reports one status on the commit it ran on. Its context is ci/<job name>. A run whose config failed to parse reports ci/config.

Job state Status state Description
queued, blocked, running pending
success success
failure failure
error, cancelled error
skipped error skipped

Pull request runs from forks, or from authors without write access, wait for approval. Their statuses are pending with the description Waiting for approval.

Status badge

/{owner}/{repo}/badge.svg shows the newest run on a branch: ?branch= picks the branch, and the default is the default branch. Add &job=<name> to show one job's state instead. A private repo's badge needs read access, like the rest of the repo.

The left half of the badge, its label, is picked in this order:

  1. ?label=<text>, for example ?label=Nightly. Spaces around it are dropped. An empty value is ignored. Labels are cut at 64 characters.
  2. The job name, when &job= is given.
  3. The name from .forge/ci.toml at the run's commit.
  4. build.

With no run on the branch the badge says no status, and the label is ?label=, or the job name, or build.

Security model

Fork pull requests need approval and get no secrets

A pull request run needs approval when its head repository is a fork, or when the author has no write access to the base repository. Such a run stays in waiting_approval, and no job is queued until a writer clicks Approve and run on the run page.

Even after approval, a run from a fork gets no secrets. The runner receives an empty secret map for that job, so $MY_SECRET is unset. A job from a fork still gets its plain env values, and it runs on a runner like any other job, so review the workflow file in the pull request before you approve.

Masking limits

The forge and the runner both mask secret values in logs, replacing each occurrence with ***. Read these limits before you rely on masking:

  • Values shorter than 4 characters are not masked. A secret of abc will appear in the log.
  • Masking covers the raw value and its standard base64 encoding. It does not cover any other transformation. A hex, URL-encoded, reversed or truncated copy of a secret is printed as is.
  • A value is masked only where the whole value appears in the output. Printing the secret one character at a time is not caught.
  • Masking is applied while the stream is read, so a value split across two output chunks is still masked.

Treat job logs as sensitive. Never echo a secret, even though it is masked.

Job tokens

Each claimed job gets its own token. The token:

  • is read-only. It can fetch the job's repository, and its wiki (<repo>.wiki), through smart HTTP with the user name ci-job and the password <job id>:<token>. Every write is refused;
  • only works while the job is running. Once the job finishes, the token stops working for logs, artifacts, heartbeat, finish and git reads;
  • is masked in the log, along with the secrets.

Secrets at rest

Secret values are sealed with the instance key (forge.key), like mirror credentials. The secrets page shows only names and the time each was last updated. Values are write-only, and writing a value is audited by name.

Runner install

A runner is the forge binary, run as forge runner. The forge and the runner ship as one binary, so an operator deploys one file. The default builtin executor needs nothing else.

The forge-runner binary is a development and test convenience only. It has the same subcommands, but operators should use forge runner, which the examples below show.

1. Check the host

The builtin executor needs:

  • Linux 5.11 or newer. Overlayfs inside a user namespace needs it. On an older kernel, jobs still run, but each one gets a full copy of the image instead of an overlay.
  • Unprivileged user namespaces. Check that /proc/sys/user/max_user_namespaces is above 0. On distributions that gate them, kernel.unprivileged_userns_clone must be 1.
  • cgroup v2 delegation for limits. The cpu, memory and pids controllers must be delegated to your user. systemd does this for user sessions on current distributions. Without it, jobs run without [limits], and each job log gets a resource limits unavailable line.

Run the check:

forge runner check

It runs one trivial job through the real sandbox. It prints ok or FAIL for each requirement, with the reason, and exits non-zero when a check fails. Pass --work-dir to test the filesystem that your jobs will use.

Subordinate ids

The builtin executor can give a job a range of uids and gids, so that package managers which change file ownership (apt, apk add, useradd) work. Inside the job, uid 0 is your user, and ids 1 to n are your subordinate range, where n is the smaller of the uid and gid range sizes, at most 65536.

It needs:

  • newuidmap and newgidmap, from the shadow-utils package. They are setuid helpers in /usr/bin.
  • An entry for your user in /etc/subuid and /etc/subgid. The podman command below adds one.

Set the mode with [sandbox] userns in runner.toml:

[sandbox]
userns = "auto"   # "auto" (the default), "subuid", or "single"
  • auto uses the subordinate range when the host has it. Otherwise it uses your own uid and gid only (single mode), and logs sandbox ids: single uid ... at startup.
  • subuid requires the range. A host without it fails at startup.
  • single always uses your own uid and gid only.

forge runner check prints the mode it resolved. In subuid mode it also checks that a job can chown a file in /tmp to 1000:1000.

Optional: podman

Set executor = "podman" in runner.toml to run jobs with rootless podman instead. Install podman with your distribution's package manager, for example sudo dnf install podman.

Rootless podman needs subordinate user and group ranges for your user:

grep "^$USER:" /etc/subuid /etc/subgid

If either line is missing, add a range (it must not overlap any existing one):

sudo usermod --add-subuids 100000-165535 --add-subgids 100000-165535 "$USER"
podman system migrate

Check that podman runs without root:

podman run --rm docker.io/library/alpine:3 echo ok

2. Keep the runner alive after logout

Systemd user services stop when the user logs out, unless lingering is enabled:

sudo loginctl enable-linger "$USER"

3. Register the runner

Create a registration token on the forge admin page at /admin/runners. It is shown once, works once, and expires after registration_token_hours (default 24). Then run on the runner machine:

forge runner register \
  --url https://forge.example \
  --token <token> \
  --name build-1 \
  --labels linux,x86_64

This writes ~/.config/forge-runner/runner.toml with mode 0600, because it holds the runner secret. Job workspaces go under ~/.cache/forge-runner/work unless you pass --work-dir.

--url must be the forge's public base URL, and the runner must reach it over HTTPS.

The config file looks like this:

url = "https://forge.example"
runner_id = "..."
runner_secret = "..."   # keep private
name = "build-1"
labels = ["linux", "x86_64"]
work_dir = "/home/ci/.cache/forge-runner/work"
concurrency = 1
executor = "builtin"   # or "podman"
auto_update = true     # replace the runner binary with the forge's when idle

[limits]
memory = "4g"       # the job cgroup's memory.max when the job declares no `memory`, or podman --memory
reserve_memory = "1g"   # what a job without `memory` reserves, and the floor of its cgroup limit (live)
memory_budget = "auto"  # all running jobs together may reserve this much (live), or a size like "6g"
memory_headroom = "1g"  # in auto mode: kept for the host, the larger of this and 10% of MemTotal
budget_swap_percent = 0 # in auto mode: percent of swap that counts toward the budget
cpus = "2"          # the job cgroup's cpu.max, or podman --cpus
pids = 4096         # the job cgroup's pids.max, or podman --pids-limit
image_max_gb = 20   # cap on the unpacked size of one image (builtin)

[images]
keep_days = 7       # images unused for this many days are deleted (builtin)

[[registry]]        # optional login for private images, matched by registry host
host = "ghcr.io"
username = "bot"
password = "..."    # keep private, the file is mode 0600

auto_update (default true) lets the runner keep its binary in step with the forge. Claim responses tell the runner which binary the forge serves. When it differs from the runner's, and no jobs are running, the runner stops claiming, replaces its binary, and exits with status 75 so systemd restarts it. It is skipped when the forge's binary is for a different OS or architecture. Set auto_update = false to pin the binary by hand.

concurrency is the number of jobs run in parallel. The default is 1. An admin can change it per runner on the runners page (/admin/runners) with no restart: type a number from 1 to 64 and save. The runner picks it up on its next claim or job heartbeat, grows or shrinks its job slots, and logs runner: concurrency 1 -> 2 (set from server). Lowering it never kills a running job; the extra slots retire as those jobs finish. The precedence is the UI value first, then runner.toml. "Use runner.toml value" removes the UI value and the runner goes back to its file. The page also shows the jobs running now, the last contact, and the runner's version, CPU count and memory, to help choose a number. Jobs without needs between them (for example test and build in this repo's own ci.toml) only run at the same time when the forge has capacity for both: set concurrency = 2 on the runner or register a second runner. Otherwise they queue and run one after the other. Each concurrent job needs its own RAM, so a second Rust build alongside the first needs several more GB even with CARGO_BUILD_JOBS=1. Each job runs with no capabilities and no_new_privileges. The builtin executor also runs each job under a seccomp profile that denies calls such as mount, ptrace, bpf and unshare.

Memory-aware admission. Concurrency only counts jobs, and several Rust compiles at once can need more RAM than the host has, which ends in the kernel's OOM killer picking a victim, often rustc in the middle of a build. So a runner also has a memory budget. By default the budget is the host's MemTotal minus a headroom, the larger of memory_headroom and 10%: a 7.6 GiB host gets about 6.6 GiB. Swap does not count unless budget_swap_percent says so, because a build that runs in swap is slower than one that waits. Each running job holds a reservation (its memory from ci.toml, see Memory, or reserve_memory), and a job starts only when the reservations of the running jobs plus its own fit the budget. concurrency stays as a second cap, so both must have room. The runner page shows the budget, what is reserved and what is free to admit. The budget and reserve_memory are live: an admin can change them on the runner's Limits tab and the runner applies them on its next claim, logging runner: memory budget .... Reservations are promises and nothing measures real use; the per-job cgroup limit is what holds a job to its word.

Every runner.toml field is visible on the runner's page (/admin/runners/<id>), with its value and whether it comes from runner.toml or the UI. The runner reports its effective config when it starts, with the secret and registry passwords left out. Fields come in three kinds:

  • Live: concurrency, labels, limits.reserve_memory and limits.memory_budget, applied on the runner's next check-in.
  • Restart needed: auto_update, executor, work_dir, sandbox.userns, the limits.* values, images.keep_days and cache_max_gib. The forge stores the value now and the runner applies it to its in-memory config when it next starts, so runner.toml on disk is never rewritten. The row says "restart needed" until the runner has started with it.
  • Read-only: name, url, runner_id, runner_secret and registry, because changing them from the forge could lock the runner out.

A UI value beats runner.toml and "Use runner.toml value" clears it. Old runners and old forges still work together: an old runner just never reports, and an old forge never sends overrides.

Image garbage collection runs at startup and then daily. Unpacked images are kept under work_dir/oci.

Builtin executor caveats

Read these before you run untrusted or sensitive jobs on a runner:

  • network = true shares the host's network namespace. The builtin executor does not set up a separate network, so a job with network = true can reach every service that the runner host can reach, including services bound to the host's localhost. Use network = false for any job that does not need the network. It gets only a loopback interface.
  • Subordinate ids are mapped in subuid mode. Container ids 1 to n map to your subordinate range, so a command can change file ownership to another user or group, as apt and useradd do. This needs the setup in Subordinate ids. Without it, the runner falls back to single mode, where only your own uid and gid exist in a job and such commands fail.
  • Image files on the host are owned by subordinate ids. Unpacked images under work_dir/oci have the ownership a job sees. A file that is owner 1000 inside a job is owned by start + 999 on the host, for example 525287 with the range 524288. ls -ln shows the numbers. The runner removes these files through a helper, so it can still clean them up.
  • With network = true, /sys is the host's /sys, bind-mounted read-only. The job can read host hardware and kernel details from it.
  • The job cgroup is placed in the parent slice. It is named forge-job-<job id>-<helper pid> and sits next to the runner's own cgroup, not under it. The runner's cgroup is never used for a job, because stopping a job kills everything in its cgroup.

4. Run it under systemd

Create ~/.config/systemd/user/forge-runner.service, with the forge binary in ~/.local/bin:

[Unit]
Description=forge CI runner
After=network-online.target
Wants=network-online.target

[Service]
ExecStart=%h/.local/bin/forge runner run --config %h/.config/forge-runner/runner.toml
Restart=on-failure
RestartSec=10
TimeoutStopSec=120

[Install]
WantedBy=default.target

Then enable and start it:

systemctl --user daemon-reload
systemctl --user enable --now forge-runner.service
journalctl --user -u forge-runner.service -f

On shutdown the runner stops claiming, and it cancels and reports any job still running. A job whose runner disappears without reporting is failed as runner lost after about two minutes, with no heartbeat.

Labels

A job with runs_on = ["linux", "x86_64"] is only claimed by a runner that has both labels. Jobs with no runs_on can go to any runner.

Cache

A job can keep directories between runs, such as a Rust target directory:

[jobs.test]
image = "docker.io/rust:1"
cache = ["target"]
run = "cargo test --workspace"

Each entry is a path relative to the workspace (/workspace). Rules:

  • At most 8 entries per job, each at most 200 characters, with no duplicates.
  • No leading /, no \, no .., no . components, no empty components, no glob characters (*?[]{}), no control characters.
  • Nothing under .git.

The runner keeps cache entries on its own disk, keyed by repo, job name and scope: a branch, a tag, or a pull request. Two jobs never share a cache, and two repos never do either.

  • A push, tag or manual run writes the cache of its own ref, such as refs/heads/main. It reads the default branch's cache when its own ref has none, unless it is the default branch.
  • A pull request run writes only its own cache, keyed by the pull request number. It reads its base branch's cache, then the default branch's cache. A pull request never writes a branch cache, so a change under review cannot leave a cache that a later build of main will use.
  • When a branch is reused, its cache is moved to the new run, not copied. Only one run owns it at a time.
  • The runner caps the total size of its caches. When the cap is reached, the least recently used entries are evicted first. The cap is the runner config key cache_max_gib, default 20.

A cache is a speed-up, not a source of truth. A job must still build correctly from an empty cache.

Rust tip

Cache the build directory, and optionally the cargo home:

[jobs.test]
image = "docker.io/rust:1"
cache = ["target", ".cargo-home"]
run = """
export CARGO_HOME=/workspace/.cargo-home
cargo test --workspace
"""

Setting CARGO_HOME to a path inside the workspace keeps the downloaded crates in the cache too.

Forge limits ([ci])

The [ci] section of forge.toml controls CI on the forge. These are the defaults:

[ci]
enabled = true
max_log_mb = 16                 # a log past this is cut with "[log truncated]"
max_artifact_mb = 512           # per artifact
max_artifacts_per_job = 50
log_retention_days = 90
artifact_retention_days = 30
registration_token_hours = 24

Retention runs once a day. Logs older than log_retention_days are deleted. The job rows stay, so statuses and run pages still work. Artifacts older than artifact_retention_days are deleted from the blob store.

Runner protocol

The runner talks to the forge only over HTTPS. JSON bodies are defined in forge-ci::proto.

Method and path Auth Purpose
POST /api/v1/ci/runners/register registration token Exchange a single-use token for a runner id and secret.
POST /api/v1/ci/runners/claim Bearer runner secret Long-poll (up to about 25 s) for a job. Returns the job assignment, or 204. Disabled runners get 403.
POST /api/v1/ci/jobs/{id}/logs Bearer job token Append a log chunk. The header X-Forge-Log-Offset must equal the current size. A mismatch returns 409 with X-Forge-Log-Size, and the runner resumes from there.
POST /api/v1/ci/jobs/{id}/heartbeat Bearer job token Sent every 10 s. The reply says whether the job was cancelled.
PUT /api/v1/ci/jobs/{id}/artifacts/{name} Bearer job token Upload one artifact as a raw body.
POST /api/v1/ci/jobs/{id}/finish Bearer job token Report success, failure, cancelled or error, with the exit code and an optional message.
POST /api/v1/ci/jobs/{id}/requeue Bearer job token Hand a running job back to the queue with a reason (runners advertise the requeue capability). The job keeps its queued_at, its log is cleared and starts with a line saying why, and the job token stops working. 409 when the job is not running.

The claim response (JobAssignment) carries the repository, the commit, the job's run script, image, env, secrets, artifact globs, timeout and network setting. Secrets are empty for fork pull request runs, and memory_bytes when the job declares memory.

The finish request (outcome, exit_code, message) may also carry oom_killed and oom_kills, see Memory. Both are optional and left out by an older runner.

A claim body also carries the runner's host facts and, for memory-aware admission, free_memory_bytes (budget minus the running jobs' reservations), memory_budget_bytes and reserve_memory_bytes. All of these are optional. Without free_memory_bytes the forge takes the oldest queued job whose labels match, as before. The claim response may carry the headers Forge-Runner-Memory-Budget and Forge-Runner-Reserve-Memory when an admin changed those settings.

For the workspace, the runner runs git fetch --depth=1 on the clone URL with the job token, then git checkout --detach <commit>. The token goes in an HTTP header, never on the command line.

Browsers and other clients read job logs with GET /{owner}/{repo}/ci/jobs/{id}/log.txt. It streams the file as it grows and ends when the job finishes.