Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .quality/baseline.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"measuredOn": "main 08061db, 2026-11-21, with the commands in .quality/README.md; the full mutation run went one file at a time with .quality/mutant-tests.sh and 2 workers; coverage remeasured 2026-11-26 for the runner pools change",
"coverage": { "lines": 90.92, "metric": "statement coverage of cmd/ and internal/ without tests, as go tool cover -func totals it" },
"measuredOn": "main 08061db, 2026-11-21, with the commands in .quality/README.md; the full mutation run went one file at a time with .quality/mutant-tests.sh and 2 workers; coverage remeasured 2026-11-30 for the runner limits change",
"coverage": { "lines": 91.18, "metric": "statement coverage of cmd/ and internal/ without tests, as go tool cover -func totals it" },
"functionsMeasured": 59,
"functionsOverCrap10": 10,
"functionsOverCrap10List": [
Expand Down
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ the major version is 0, a minor release may change configuration (each such chan
## [Unreleased]

### Added
- `RUNNER_MEMORY_GB` and `RUNNER_VCPUS` (optional): a memory and vCPU limit for each runner service, set through Railway's `serviceInstanceLimitsUpdate` after the service is created and before its first deploy. Unset (the default) changes nothing and makes no extra call. Each is independent; an unset one keeps Railway's per-service limit. If Railway refuses a limit, or does not confirm it, the service is deleted and the create fails like any other, so no runner starts without it. With either set, a job costs one more Railway call. One value applies to every pool.
- `RUNNER_POOLS`: one controller serves several runner images. It takes a JSON list of pools, each with a `label`, `image`, `prefix`, `max_runners`, `scopes` and an optional `region` (falling back to `RUNNER_REGION`). Each cycle reads every scope once, whichever pools list it, gives each queued job to the pool whose label it asks for, and plans each pool on its own, so a full pool never holds up another. The App's one webhook wakes the controller for a job of any pool, so a second image no longer needs a second controller that only polls and scans the same repositories again. Labels and prefixes must differ across pools. The single-pool variables (`RUNNER_IMAGE`, `RUNNER_SCOPES`, `RUNNER_LABEL`, `RUNNER_SERVICE_PREFIX`, `MAX_RUNNERS`) still configure one pool unchanged; setting them together with `RUNNER_POOLS` is refused. `MAX_CREATE_PER_CYCLE` applies per pool. docs/deploy.md describes moving from two controllers to one; the second-controller setup is no longer documented.
- The `sqlite3` command-line shell in every image variant, for tests and scripts that drive a SQLite database from the shell.
- `libssl-dev` in every image variant, so Rust crates that link OpenSSL (`openssl-sys`) build on the pool; the build checks that `pkg-config` finds it.
Expand Down
10 changes: 7 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,7 @@ limits. [docs/deploy.md](docs/deploy.md) has the full guide, rollout and rollbac
| `RUNNER_SERVICE_PREFIX` | Railway service-name prefix of the runners: a letter, a letter or digit, a dash, e.g. `rp-` (single pool) | `rr-` |
| `MAX_RUNNERS` | services at a time (single pool) | `8` |
| `RUNNER_REGION` | Railway region id for the runners, e.g. `us-east4-eqdc4a`, for every pool without a `region` of its own; the API's `regions` query lists them. Unset leaves placement to Railway (the workspace's preferred region) | unset |
| `RUNNER_MEMORY_GB` / `RUNNER_VCPUS` | memory (in GB) and vCPU limit of each runner service, e.g. `4` and `2` (decimals allowed), set before its first deploy; one value for every pool. Each is optional and independent: an unset one keeps Railway's per-service limit. If Railway refuses a limit (above the plan's maximum, for example), the service is deleted and the create fails, so no runner starts without it. A cap too small for a build kills the job | unset |
| `RUNNER_GROUP_ID` | the dedicated runner group of org runners; required for an `org:` scope, and the Default group (1) is refused | none |
| `MAX_CREATE_PER_CYCLE` | services one pool creates in one cycle | `4` |
| `POLL_SECONDS` | polling period (a queued-job webhook wakes a cycle sooner: after a 3 s debounce, and at least 20 s after the previous cycle started) | `120` |
Expand Down Expand Up @@ -285,10 +286,11 @@ default images stay sudo-free.
* **No sudo** in the default images, so `sudo apt-get install` fails: use `setup-*` actions, a derived
image, or the opt-in sudo variant.
* **CPU and processes:** each container is capped by your Railway plan (for example 24 vCPU, 24 GB and
about 1,000 processes and threads). `nproc` shows the host's cores, not the quota; Node's
about 1,000 processes and threads), or lower by `RUNNER_VCPUS` and `RUNNER_MEMORY_GB`. `nproc` shows the host's cores, not the quota; Node's
`os.availableParallelism()` reads the quota. Pass explicit `-j`/worker counts to be safe.
* **Railway API:** 1,000 requests an hour per token. A job costs about four calls and a cycle one, so
roughly 230 jobs an hour at the default poll; every pool, and every controller sharing the token, shares that budget.
* **Railway API:** 1,000 requests an hour per token. A job costs about four calls (five with
`RUNNER_MEMORY_GB` or `RUNNER_VCPUS` set) and a cycle one, so roughly 230 jobs an hour at the
default poll (190 with limits); every pool, and every controller sharing the token, shares that budget.
* **GitHub API:** 5,000 requests an hour per installation, shared by every scope of that installation
(one access token per installation). Run and job lists are read with `If-None-Match`, and an
unchanged list (`304`) does not count against the limit. Prefer `repo:` scopes for large organizations:
Expand All @@ -302,6 +304,8 @@ default images stay sudo-free.
Railway bills the CPU, memory and network the runner services actually use, plus a little for the
controller, which idles most of the time. A job costs roughly its duration times the CPU and memory it
uses; check your plan's prices. Keep `MAX_RUNNERS` and `MAX_JOB_MINUTES` as the real cap on spend.
Where memory is metered, `RUNNER_MEMORY_GB` also bounds what one runner can hold, the page cache of a
large build included.
Railway's usage limits are set per **workspace**, not per project, and reaching the hard limit takes
*every* workload in the workspace offline (Railway docs, usage limits, read 2026-10-17). Set a soft
limit (an email alert) for the runner fleet, and a hard limit only if the workspace holds nothing
Expand Down
3 changes: 2 additions & 1 deletion cmd/controller/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,8 @@ func main() {
log.Error("startup", "err", err.Error())
os.Exit(1)
}
rw := railway.New(railway.Config{Token: cfg.RailwayToken, ProjectID: cfg.RailwayProject, EnvironmentID: cfg.RailwayEnv, Prefixes: cfg.Prefixes()})
rw := railway.New(railway.Config{Token: cfg.RailwayToken, ProjectID: cfg.RailwayProject, EnvironmentID: cfg.RailwayEnv, Prefixes: cfg.Prefixes(),
MemoryGB: cfg.RunnerMemoryGB, VCPUs: cfg.RunnerVCPUs})
alert := func(msg string) {
log.Error("ALERT", "alert", msg) // not "msg": slog writes the message under that key
if cfg.AlertURL == "" {
Expand Down
12 changes: 10 additions & 2 deletions docs/deploy.md
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,11 @@ controller again.
3. Make every job you move Docker-free (no `docker://` actions, `docker` steps, `container:` or
`services:`) and sudo-free.
4. Add repositories to `RUNNER_SCOPES` one at a time and raise `MAX_RUNNERS` to your parallel jobs.
To cap each runner, set `RUNNER_MEMORY_GB` and/or `RUNNER_VCPUS` while `MAX_RUNNERS` is still `1`,
run one job, and check the runner service's limit in the Railway dashboard before you widen it. If
the token may not set limits, or a value is above the plan's maximum, every create fails: the
`cycle failed` log line carries Railway's message, and after `ALERT_FAILED_CYCLES` cycles the
failing alert fires and `/healthz` answers 503. Unset the variable to go back.
5. **Rollback:** set the jobs' `runs-on` back to a hosted runner, stop the controller (remove its
deployment or delete the service; `MAX_RUNNERS` cannot be 0), and delete any `<prefix>*` services
of each pool left in the runner project.
Expand Down Expand Up @@ -175,7 +180,8 @@ touched (tested in `internal/railway`). Still:
10 (Hobby) or 50 (Pro) a second (Railway docs, public API, read 2026-10-17). The limit actually
applied is in the `X-RateLimit-Limit` header of every answer; a Pro workspace was observed at 1,000 an
hour for project tokens on 2026-10-17, so plan for the header, not the table. A job costs about four
calls (create, configure, deploy, delete) and every cycle one list call, whatever the number of
calls (create, configure, deploy, delete; a fifth, the limits, when `RUNNER_MEMORY_GB` or `RUNNER_VCPUS`
is set) and every cycle one list call, whatever the number of
pools; controllers that share a token share its budget. At 1,000 an hour and the default poll that is roughly 230 jobs an hour.
* **GitHub API**: 5,000 requests an hour per installation (more above 20 repositories), shared by
every scope of that installation. A cycle reads, per repository, four run lists (`queued`,
Expand All @@ -190,5 +196,7 @@ touched (tested in `internal/railway`). Still:
* **Railway per-service limits** (Railway docs, plans, read 2026-10-17): up to 48 vCPU and 48 GB per
service on Hobby, 1,000 vCPU and 1 TB on Pro, 100 GB ephemeral storage, image size 100 GB on Hobby.
A runner service gets the workspace's default per-service limit (observed: 24 vCPU, 24 GB and a
limit of about 1,000 processes and threads, 2026-10-17). Railway documents no limit on services per
limit of about 1,000 processes and threads, 2026-10-17). `RUNNER_MEMORY_GB` and `RUNNER_VCPUS` set a
lower limit on each runner service before its first deploy. Size them for the heaviest job of every
pool, since one value applies to all: a job that needs more memory than the cap is killed. Railway documents no limit on services per
project; a fleet of a few dozen short-lived services at once has worked.
33 changes: 30 additions & 3 deletions internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ package config

import (
"encoding/json"
"errors"
"fmt"
"math"
"regexp"
"strconv"
"strings"
Expand All @@ -20,7 +22,8 @@ type Config struct {
RailwayProject, RailwayEnv string
Pools []reconcile.Pool
RunnerGroupID int
MaxCreatePerCycle int // per pool, per cycle
MaxCreatePerCycle int // per pool, per cycle
RunnerMemoryGB, RunnerVCPUs float64 // limits of each runner service; 0 is unset
Interval, StartupGrace, IdleTTL time.Duration
MaxAge, AlertAfter time.Duration
FailAlertAfter int // failed cycles in a row before an alert and a 503
Expand All @@ -38,7 +41,15 @@ func (c Config) String() string {
}
pools = append(pools, fmt.Sprintf("[label=%s prefix=%s region=%s image=%s max=%d scopes=%s]", p.Label, p.Prefix, p.Region, p.Image, p.MaxRunners, strings.Join(keys, ",")))
}
return fmt.Sprintf("pools=%s interval=%s", strings.Join(pools, " "), c.Interval)
return fmt.Sprintf("pools=%s memory_gb=%s vcpus=%s interval=%s", strings.Join(pools, " "), limitText(c.RunnerMemoryGB), limitText(c.RunnerVCPUs), c.Interval)
}

// limitText is a runner limit as the startup log shows it: the number, or unset.
func limitText(v float64) string {
if v == 0 {
return "unset"
}
return strconv.FormatFloat(v, 'g', -1, 64)
}

// Labels is every pool's label, in pool order.
Expand Down Expand Up @@ -100,7 +111,10 @@ func Load(get func(string) string) (Config, error) {
c.MaxAge = time.Duration(num("MAX_JOB_MINUTES", 360)+10) * time.Minute
c.AlertAfter = time.Duration(num("ALERT_QUEUED_MINUTES", 5)) * time.Minute
c.FailAlertAfter = num("ALERT_FAILED_CYCLES", 3)
if err != nil {
var memErr, cpuErr error
c.RunnerMemoryGB, memErr = positive(get, "RUNNER_MEMORY_GB")
c.RunnerVCPUs, cpuErr = positive(get, "RUNNER_VCPUS")
if err = errors.Join(err, memErr, cpuErr); err != nil {
return Config{}, err
}
if c.Pools, err = loadPools(get); err != nil {
Expand Down Expand Up @@ -143,6 +157,19 @@ func number(get func(string) string, name string, def int) (int, error) {
return n, nil
}

// positive reads a positive, finite number, 0 when the variable is unset.
func positive(get func(string) string, name string) (float64, error) {
v := strings.TrimSpace(get(name))
if v == "" {
return 0, nil
}
n, err := strconv.ParseFloat(v, 64)
if err != nil || !(n > 0) || math.IsInf(n, 1) {
return 0, fmt.Errorf("config: %s must be a positive number, e.g. 4 or 0.5", name)
}
return n, nil
}

// singlePoolVars are the variables of a one-pool setup, which RUNNER_POOLS replaces.
var singlePoolVars = []string{"RUNNER_IMAGE", "RUNNER_LABEL", "RUNNER_SERVICE_PREFIX", "MAX_RUNNERS", "RUNNER_SCOPES"}

Expand Down
42 changes: 42 additions & 0 deletions internal/config/limits_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package config

import (
"strings"
"testing"
)

// RUNNER_MEMORY_GB and RUNNER_VCPUS cap each runner service. Unset (0) keeps today's services,
// which have no limits of their own.
func TestTheRunnerLimitsAreOptional(t *testing.T) {
c, err := Load(env(base()))
if err != nil || c.RunnerMemoryGB != 0 || c.RunnerVCPUs != 0 {
t.Fatalf("defaults memory %g vCPUs %g err %v, want both unset", c.RunnerMemoryGB, c.RunnerVCPUs, err)
}
if s := c.String(); !strings.Contains(s, "memory_gb=unset vcpus=unset") {
t.Errorf("String() %q should show unset limits as unset, not as 0", s)
}
m := base()
m["RUNNER_MEMORY_GB"] = " 4 "
m["RUNNER_VCPUS"] = "0.25"
c, err = Load(env(m))
if err != nil || c.RunnerMemoryGB != 4 || c.RunnerVCPUs != 0.25 {
t.Fatalf("memory %g vCPUs %g err %v, want 4 and 0.25", c.RunnerMemoryGB, c.RunnerVCPUs, err)
}
if s := c.String(); !strings.Contains(s, "memory_gb=4 ") || !strings.Contains(s, "vcpus=0.25 ") {
t.Errorf("String() %q should show the limits so a startup log shows the runners' size", s)
}
}

// A limit that is not a positive number stops the controller at start, naming the variable,
// rather than creating runners Railway would refuse or kill.
func TestARunnerLimitThatIsNotAPositiveNumberIsRefused(t *testing.T) {
for _, name := range []string{"RUNNER_MEMORY_GB", "RUNNER_VCPUS"} {
for _, bad := range []string{"0", "-1", "abc", "4GB", "NaN", "Inf", "+Inf", "1e400"} {
m := base()
m[name] = bad
if _, err := Load(env(m)); err == nil || !strings.Contains(err.Error(), name) {
t.Errorf("%s=%q: err %v, want a %s error", name, bad, err, name)
}
}
}
}
125 changes: 125 additions & 0 deletions internal/railway/limits_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
package railway

import (
"context"
"strings"
"testing"
)

// limitsServer is a Railway that creates svc-9 and answers every other call with limits, the
// answer to serviceInstanceLimitsUpdate.
func limitsServer(t *testing.T, memoryGB, vCPUs float64, limits string) (*Client, *[]call) {
t.Helper()
cfg := Config{Token: "tok-secret", ProjectID: "P", EnvironmentID: "E", Prefixes: []string{"rr-"}, MemoryGB: memoryGB, VCPUs: vCPUs}
c, calls, _ := serverWith(t, cfg, func(c call) string {
switch {
case strings.Contains(c.Query, "serviceCreate"):
return `{"data":{"serviceCreate":{"id":"svc-9","name":"n"}}}`
case strings.Contains(c.Query, "serviceInstanceLimitsUpdate"):
return limits
case strings.Contains(c.Query, "serviceDelete"):
return `{"data":{"serviceDelete":true}}`
}
return `{"data":{"ok":true}}`
})
return c, calls
}

func queries(calls []call) []string {
out := make([]string, len(calls))
for i, c := range calls {
switch {
case strings.Contains(c.Query, "serviceCreate"):
out[i] = "create"
case strings.Contains(c.Query, "serviceInstanceLimitsUpdate"):
out[i] = "limits"
case strings.Contains(c.Query, "serviceInstanceUpdate"):
out[i] = "configure"
case strings.Contains(c.Query, "serviceInstanceDeployV2"):
out[i] = "deploy"
case strings.Contains(c.Query, "serviceDelete"):
out[i] = "delete"
default:
out[i] = c.Query
}
}
return out
}

// With both limits set, they are applied to the new service before its first deploy.
func TestCreateAppliesTheLimitsBeforeTheFirstDeploy(t *testing.T) {
c, calls := limitsServer(t, 4, 2, `{"data":{"serviceInstanceLimitsUpdate":true}}`)
id, err := c.Create(context.Background(), pool, "n", nil)
if err != nil || id != "svc-9" {
t.Fatalf("id %q err %v", id, err)
}
if got := strings.Join(queries(*calls), ","); got != "create,configure,limits,deploy" {
t.Fatalf("calls %s, want create,configure,limits,deploy", got)
}
in := (*calls)[2].Vars["i"].(map[string]any)
if in["serviceId"] != "svc-9" || in["environmentId"] != "E" || in["memoryGB"] != float64(4) || in["vCPUs"] != float64(2) || len(in) != 4 {
t.Errorf("limits input %+v, want svc-9 in E with 4 GB and 2 vCPUs", in)
}
}

// A limit that is not set is left out of the input, so Railway keeps its own value for it.
func TestCreateSendsOnlyTheLimitsThatAreSet(t *testing.T) {
for _, tc := range []struct {
name string
memory, vcpus float64
sent, absent string
value float64
}{
{"memory only", 0.5, 0, "memoryGB", "vCPUs", 0.5},
{"vCPUs only", 0, 0.5, "vCPUs", "memoryGB", 0.5},
} {
t.Run(tc.name, func(t *testing.T) {
c, calls := limitsServer(t, tc.memory, tc.vcpus, `{"data":{"serviceInstanceLimitsUpdate":true}}`)
if _, err := c.Create(context.Background(), pool, "n", nil); err != nil {
t.Fatal(err)
}
if got := strings.Join(queries(*calls), ","); got != "create,configure,limits,deploy" {
t.Fatalf("calls %s, want create,configure,limits,deploy", got)
}
in := (*calls)[2].Vars["i"].(map[string]any)
if _, ok := in[tc.absent]; ok || in[tc.sent] != tc.value {
t.Errorf("limits input %+v, want only %s=%g", in, tc.sent, tc.value)
}
})
}
}

// Without limits, a service is made exactly as before: no limits call at all.
func TestCreateWithoutLimitsSendsNoLimitsCall(t *testing.T) {
c, calls := limitsServer(t, 0, 0, `{"errors":[{"message":"must not be called"}]}`)
if _, err := c.Create(context.Background(), pool, "n", nil); err != nil {
t.Fatal(err)
}
if got := strings.Join(queries(*calls), ","); got != "create,configure,deploy" {
t.Errorf("calls %s, want create,configure,deploy", got)
}
}

// A runner never starts without the limits it was asked to have: when Railway refuses them, or
// answers false, the service is deleted and never deployed, and Create fails.
func TestRefusedLimitsDeleteTheServiceAndDeployNothing(t *testing.T) {
for _, tc := range []struct{ name, answer, want string }{
{"error", `{"errors":[{"message":"memoryGB above the plan limit"}]}`, "memoryGB above the plan limit"},
{"false", `{"data":{"serviceInstanceLimitsUpdate":false}}`, "limits"},
{"null", `{"data":{"serviceInstanceLimitsUpdate":null}}`, "limits"},
} {
t.Run(tc.name, func(t *testing.T) {
c, calls := limitsServer(t, 64, 0, tc.answer)
id, err := c.Create(context.Background(), pool, "n", nil)
if err == nil || id != "" || !strings.Contains(err.Error(), tc.want) {
t.Fatalf("id %q err %v, want no id and an error about %q", id, err, tc.want)
}
if got := strings.Join(queries(*calls), ","); got != "create,configure,limits,delete" {
t.Errorf("calls %s, want create,configure,limits,delete", got)
}
if del := (*calls)[3].Vars; del["i"] != "svc-9" || del["e"] != "E" {
t.Errorf("delete vars %+v, want svc-9 in E", del)
}
})
}
}
Loading
Loading