diff --git a/.quality/baseline.json b/.quality/baseline.json index ca893fb..76f32e7 100644 --- a/.quality/baseline.json +++ b/.quality/baseline.json @@ -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": { "lines": 87.88, "metric": "statement coverage of cmd/ and internal/ without tests, as go tool cover -func totals it" }, + "coverage": { "lines": 89.19, "metric": "statement coverage of cmd/ and internal/ without tests, as go tool cover -func totals it" }, "functionsMeasured": 59, "functionsOverCrap10": 10, "functionsOverCrap10List": [ diff --git a/CHANGELOG.md b/CHANGELOG.md index 68f8f63..c2bb66c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,7 @@ the major version is 0, a minor release may change configuration (each such chan - The GitHub CLI (`gh` 2.102.0, pinned by version and sha256) in every image variant, so a job can open or comment on issues without a GitHub-hosted runner. Nothing is logged in: a job passes `GH_TOKEN`. ### Fixed +- A queued job whose run GitHub's `runs?status=queued` list leaves out gets a runner. GitHub left such a run out for 25 minutes on 2026-11-21 and its job never got a runner. Each cycle now also reads the 20 newest runs of each repository without the status filter, and serves the queued jobs of any run that is not completed and was not already listed. `/healthz` reports `unlisted_jobs`, the `cycle` log line carries `unlisted`, and each such job is logged at warn. If the extra read fails (a 5xx, or a 403 at the rate limit), the jobs from the filtered lists are still served: the failure is logged at warn with the repository and status, counted as `unlisted_read_failures` on `/healthz` and `unlisted_read_failed` on the `cycle` line, and does not fail the scope. On an idle repository the extra read is an unchanged `304`, which does not count against the rate limit. - A scope in `RUNNER_SCOPES` that GitHub answers 404 for (a deleted repository, for example) no longer fails every cycle and turns `/healthz` 503: it is counted in `unreadable_scopes`, logged at warn once a cycle and left out of the failing alert, while the other scopes keep getting runners. After `ALERT_FAILED_CYCLES` cycles in a row such a scope raises one alert of its own, and one more when it reads again. When every scope answers 404 (the App uninstalled, for example), the cycle still fails. In an org scope, a repository or run that vanishes mid-cycle is skipped instead of hiding the whole org. Other GitHub errors still fail the cycle. - `/healthz` answers at once while a cycle runs, with the previous cycle's status; it waited for the cycle to end (about a minute with many repositories) and health checks timed out. - Jobs queued in a run that GitHub reports as `pending` (for example while it waits on a concurrency group) are served; the controller listed only `queued` and `in_progress` runs and left such jobs waiting forever. diff --git a/README.md b/README.md index ba4d544..72d728c 100644 --- a/README.md +++ b/README.md @@ -104,7 +104,7 @@ RUNNER_LABEL=railway MAX_RUNNERS=2 ``` -`/healthz` answers 200 once a cycle has completed, and 503 when the last cycle is older than three polls or `ALERT_FAILED_CYCLES` cycles in a row have failed. Its JSON: `last_cycle`, `last_success`, `consecutive_failures`, `unreadable_scopes`, `services`, `queued`, `error`. `/healthz` is public, so `unreadable_scopes` is only how many scopes the last cycle could not read; their names are in the controller's log lines and in the failing alert, which only the operator sees. A scope GitHub answers 404 for (a deleted repository, a typo in `RUNNER_SCOPES`, or an App no longer installed there) is counted in `unreadable_scopes` and logged at warn each cycle, but does not fail the cycle; after `ALERT_FAILED_CYCLES` cycles in a row it raises one alert of its own, and one more when it reads again. When every scope answers 404 (the App uninstalled, for example) the cycle fails, since nothing can be served. Any other read error fails the cycle too. `github_rate_limits` shows the requests GitHub last reported left per installation account (a warning is logged once per window below a tenth). The log line `controller up` shows the scopes, +`/healthz` answers 200 once a cycle has completed, and 503 when the last cycle is older than three polls or `ALERT_FAILED_CYCLES` cycles in a row have failed. Its JSON: `last_cycle`, `last_success`, `consecutive_failures`, `unreadable_scopes`, `services`, `queued`, `unlisted_jobs`, `unlisted_read_failures`, `error`. `unlisted_jobs` counts the queued jobs the last cycle found only through the unfiltered run list, because GitHub's `status=` filter left their run out; each one is also logged at warn with its repository and job id, and the `cycle` line carries `unlisted`. `unlisted_read_failures` counts the repositories whose unfiltered run list the last cycle could not read (a 5xx, or a 403 at the rate limit); those repositories are still served from the filtered lists, each failure is logged at warn with its repository and status, and the `cycle` line carries `unlisted_read_failed`. `/healthz` is public, so `unreadable_scopes` is only how many scopes the last cycle could not read; their names are in the controller's log lines and in the failing alert, which only the operator sees. A scope GitHub answers 404 for (a deleted repository, a typo in `RUNNER_SCOPES`, or an App no longer installed there) is counted in `unreadable_scopes` and logged at warn each cycle, but does not fail the cycle; after `ALERT_FAILED_CYCLES` cycles in a row it raises one alert of its own, and one more when it reads again. When every scope answers 404 (the App uninstalled, for example) the cycle fails, since nothing can be served. Any other read error fails the cycle too. `github_rate_limits` shows the requests GitHub last reported left per installation account (a warning is logged once per window below a tenth). The log line `controller up` shows the scopes, label, prefix, image and limits it runs with. ### 4. Use it in a workflow @@ -264,7 +264,9 @@ default images stay sudo-free. roughly 230 jobs an hour at the default poll; two controllers sharing one token share 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. + unchanged list (`304`) does not count against the limit. Prefer `repo:` scopes for large organizations: + the cache of unchanged lists holds 2,000 entries, four run lists per repository plus the jobs lists, + so past about 500 repositories every read counts. * **Cold start** is the Railway deploy plus the image pull: about 20 s when the host has the image, longer on a host's first pull of a large image (see `docs/spike.md`). @@ -296,6 +298,7 @@ pin a version (or a digest, `image@sha256:...`) so a runner never changes under | `/healthz` 503 | no cycle has completed yet, the last one is older than three polls, or cycles keep failing (`consecutive_failures`, `unreadable_scopes`); the `cycle failed` log lines say why and name the scopes | | `/healthz` 200 but `unreadable_scopes` above 0 | GitHub answers 404 for a scope (the warn line below names it): the repository was deleted, the name in `RUNNER_SCOPES` is wrong, or the App is no longer installed there. See the `scope not found on GitHub; skipped` warn line and the `not found on GitHub for N cycles in a row` alert, then fix or remove the scope. If every scope answers 404, the cycles fail and `/healthz` goes 503: check the App is still installed. A renamed or transferred repository answers a redirect instead, which fails the cycle until `RUNNER_SCOPES` has the new name | | `/healthz` `"error": true` | the last cycle failed; the `cycle failed` log line says why (often a GitHub or Railway API error, which the next cycle retries) | +| A job stays queued, and its run is missing from `GET /repos/{repo}/actions/runs?status=queued` | GitHub's status filter sometimes leaves a queued run out. Each cycle also reads the 20 newest runs without the filter and serves their queued jobs (`unlisted_jobs` on `/healthz`, a warn line per job). A run pushed out of the 20 newest is never found that way: cancel it and re-run it | | A job stays queued | the job's labels must all be among `self-hosted`, `linux`, `x64` and your label; its repository must be in `RUNNER_SCOPES` and the App installed on it; `MAX_RUNNERS` may be reached | | How often cycles run, and what they cost | every cycle logs one `cycle` line: `duration`, `github_calls`, `railway_calls`, `created`, `reaped`, `failed` | | Runner services pile up | each should go about a minute after its job ends ("runner gone" in the log); check the Railway token can delete services | diff --git a/docs/deploy.md b/docs/deploy.md index d2fa77e..fbdb1ec 100644 --- a/docs/deploy.md +++ b/docs/deploy.md @@ -146,8 +146,14 @@ touched (tested in `internal/railway`). Still: calls (create, configure, deploy, delete) and every cycle one list call; 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, two run lists, the jobs of each - active run and the runner list; unchanged lists come back as `304` and do not count. `/healthz` + every scope of that installation. A cycle reads, per repository, four run lists (`queued`, + `pending`, `in_progress`, and the 20 newest runs unfiltered, since GitHub's status filter can leave + a queued run out), the jobs of each active run and the runner list; unchanged lists come back as + `304` and do not count. A repository with recent activity changes its unfiltered page, so that read + counts once a cycle. When that unfiltered read fails (a 5xx, or a 403 at the rate limit), the + repository is still served from its filtered lists for that cycle, and the failure is logged and + counted rather than failing the scope. The cache of unchanged lists holds 2,000 entries, so past about 500 + repositories in one controller every read counts; prefer `repo:` scopes there. `/healthz` shows `github_rate_limits`, and a warning is logged below a tenth. * **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. diff --git a/internal/controller/controller.go b/internal/controller/controller.go index d4ac375..10b092b 100644 --- a/internal/controller/controller.go +++ b/internal/controller/controller.go @@ -90,6 +90,8 @@ type Status struct { ConsecutiveFailures int LastSuccess time.Time UnreadableScopes int // how many scopes the last cycle could not read; /healthz is public, so no names + UnlistedJobs int // queued jobs the last cycle found only because GitHub's status filter left their run out + UnlistedReadFailed int // repositories whose unfiltered run list the last cycle could not read; their listed jobs were still served Failing bool // ConsecutiveFailures reached FailAlertAfter } @@ -213,16 +215,19 @@ func (c *Controller) Cycle(ctx context.Context) (err error) { now := c.now() began, ghBefore, rwBefore := time.Now(), calls(c.gh), calls(c.rw) created, reaped := 0, 0 + var gap unlistedGap // set once the scopes are read; the log line below reads it when the cycle ends defer func() { c.cfg.Log.Info("cycle", "duration", time.Since(began).Round(time.Millisecond).String(), "github_calls", calls(c.gh)-ghBefore, - "railway_calls", calls(c.rw)-rwBefore, "created", created, "reaped", reaped, "failed", err != nil) + "railway_calls", calls(c.rw)-rwBefore, "created", created, "reaped", reaped, "unlisted", gap.jobs, + "unlisted_read_failed", gap.readFailed, "failed", err != nil) }() rd := c.readScopes(ctx) + gap = unlistedGap{jobs: c.warnUnlisted(rd.jobs), readFailed: rd.unlistedReadFailed} errs, queued, runners, jobsOf, readable := rd.errs, rd.queued, rd.runners, rd.jobs, rd.readable all, err := c.rw.List(ctx) if err != nil { errs = append(errs, err) - c.record(now, errs, 0, 0) + c.record(now, errs, 0, 0, gap) return errors.Join(errs...) } ok := map[string]bool{} @@ -269,7 +274,7 @@ func (c *Controller) Cycle(ctx context.Context) (err error) { for _, n := range queued { total += n } - c.record(now, errs, len(services)+len(plan.Create)-len(plan.Reap), total) + c.record(now, errs, len(services)+len(plan.Create)-len(plan.Reap), total, gap) return errors.Join(errs...) } @@ -280,6 +285,36 @@ type scopeReads struct { runners map[string][]reconcile.Runner jobs map[string][]ghapp.Job errs []error // the errors that fail the cycle + + unlistedReadFailed int // repositories whose fallback read failed; it does not fail the cycle +} + +// unlistedGap is how the last cycle saw GitHub's status-filter gap: the jobs found only through +// the unfiltered run list, and the repositories whose unfiltered list could not be read. +type unlistedGap struct{ jobs, readFailed int } + +// warnUnlisted logs each queued job found only because GitHub's status filter left its run out, so +// the gap on GitHub's side stays visible, and returns how many there were. +func (c *Controller) warnUnlisted(jobs map[string][]ghapp.Job) int { + n := 0 + for _, js := range jobs { + for _, j := range js { + if j.Unlisted { + n++ + c.cfg.Log.Warn("queued job missing from GitHub's status-filtered run list", "job", j.ID, "repo", j.Repo) + } + } + } + return n +} + +// warnUnlistedRead logs each repository whose fallback read failed (repository and status only) and +// returns how many there were. The scope's listed jobs are still served: the fallback only adds jobs. +func (c *Controller) warnUnlistedRead(e *ghapp.UnlistedReadError) int { + for _, f := range e.Failed { + c.cfg.Log.Warn("unfiltered run list unreadable; serving the status-filtered jobs only", "repo", f.Repo, "status", f.Status) + } + return len(e.Failed) } // readScopes reads every scope, records how each went, and raises or clears the missing-scope alerts. @@ -287,6 +322,11 @@ func (c *Controller) readScopes(ctx context.Context) scopeReads { rd := scopeReads{queued: map[string]int{}, runners: map[string][]reconcile.Runner{}, jobs: map[string][]ghapp.Job{}} for _, s := range c.cfg.Scopes { jobs, rs, err := c.readScope(ctx, s) + var ue *ghapp.UnlistedReadError + if errors.As(err, &ue) { + rd.unlistedReadFailed += c.warnUnlistedRead(ue) + err = nil + } if fail := c.noteRead(s.Key(), err); fail != nil { rd.errs = append(rd.errs, fmt.Errorf("%s: %w", s.Key(), fail)) } @@ -363,24 +403,26 @@ func (c *Controller) noteRead(key string, err error) error { } } -// readScope reads the scope's queued jobs and its runners. +// readScope reads the scope's queued jobs and its runners. When only the fallback read failed +// (an *ghapp.UnlistedReadError), the jobs and runners come with that error. func (c *Controller) readScope(ctx context.Context, s reconcile.Scope) ([]ghapp.Job, []reconcile.Runner, error) { - jobs, err := c.gh.QueuedJobs(ctx, s) - if err != nil { - return nil, nil, err + jobs, jobsErr := c.gh.QueuedJobs(ctx, s) + var ue *ghapp.UnlistedReadError + if jobsErr != nil && !errors.As(jobsErr, &ue) { + return nil, nil, jobsErr } rs, err := c.gh.Runners(ctx, s) if err != nil { return nil, nil, err } - return jobs, rs, nil + return jobs, rs, jobsErr } // record keeps the cycle's outcome for /healthz and raises the failing and recovered alerts: one // alert when FailAlertAfter cycles in a row have failed, naming the scopes unreadable for that long, // and one message when a cycle succeeds again. A failed cycle still stamps LastCycle (the loop is // alive); ConsecutiveFailures is what tells a failing controller from a working one. -func (c *Controller) record(now time.Time, errs []error, services, queued int) { +func (c *Controller) record(now time.Time, errs []error, services, queued int, gap unlistedGap) { if len(errs) > 0 { c.failures++ } else { @@ -389,7 +431,8 @@ func (c *Controller) record(now time.Time, errs []error, services, queued int) { } unreadable, stuck := c.unreadableScopes() st := &Status{LastCycle: now, Services: services, Queued: queued, ConsecutiveFailures: c.failures, - LastSuccess: c.lastSuccess, UnreadableScopes: unreadable, Failing: c.failures >= c.cfg.FailAlertAfter} + LastSuccess: c.lastSuccess, UnreadableScopes: unreadable, UnlistedJobs: gap.jobs, + UnlistedReadFailed: gap.readFailed, Failing: c.failures >= c.cfg.FailAlertAfter} if len(errs) > 0 { st.LastError = errors.Join(errs...).Error() } @@ -520,7 +563,8 @@ func (c *Controller) HealthHandler() http.Handler { } body := map[string]any{"last_cycle": st.LastCycle, "services": st.Services, "queued": st.Queued, "error": st.LastError != "", "consecutive_failures": st.ConsecutiveFailures, "last_success": lastSuccess, - "unreadable_scopes": st.UnreadableScopes} + "unreadable_scopes": st.UnreadableScopes, "unlisted_jobs": st.UnlistedJobs, + "unlisted_read_failures": st.UnlistedReadFailed} if rl, ok := c.gh.(RateLimiter); ok { body["github_rate_limits"] = rl.RateLimits() } diff --git a/internal/controller/summary_test.go b/internal/controller/summary_test.go index 4168a39..9791dae 100644 --- a/internal/controller/summary_test.go +++ b/internal/controller/summary_test.go @@ -33,7 +33,7 @@ func (r *countedRW) Calls() int64 { return r.n } // Every cycle logs one summary line: how long it took, the API calls it made to GitHub and // Railway, and what it created and reaped, so the cycle rate and its cost can be read from logs. func TestEveryCycleLogsOneSummaryLine(t *testing.T) { - gh := &countedGH{fakeGH: fakeGH{jobs: map[string][]ghapp.Job{repo.Key(): {{ID: 1, Repo: "acme/app", CreatedAt: now}}}}} + gh := &countedGH{fakeGH: fakeGH{jobs: map[string][]ghapp.Job{repo.Key(): {{ID: 1, Repo: "acme/app", CreatedAt: now}}}}, n: 100} rw := &countedRW{n: 10} var buf bytes.Buffer c := newC(&gh.fakeGH, &rw.fakeRW) diff --git a/internal/controller/unlisted_test.go b/internal/controller/unlisted_test.go new file mode 100644 index 0000000..769cb45 --- /dev/null +++ b/internal/controller/unlisted_test.go @@ -0,0 +1,126 @@ +package controller + +import ( + "bytes" + "context" + "errors" + "log/slog" + "strings" + "testing" + "time" + + "github.com/farzai/github-runner-railway/internal/ghapp" + "github.com/farzai/github-runner-railway/internal/reconcile" +) + +// A job GitHub's status filter left out (found only through the unfiltered runs list) gets a runner +// like any other, and the gap stays visible: the cycle line counts it, a warning names it, and +// /healthz counts the last cycle's. +func TestAnUnlistedJobGetsARunnerAndIsCountedOnHealthzAndInTheLog(t *testing.T) { + gh := &fakeGH{jobs: map[string][]ghapp.Job{ + repo.Key(): {{ID: 310, Repo: "acme/app", CreatedAt: now, Unlisted: true}, {ID: 2, Repo: "acme/app", CreatedAt: now}}, + }} + rw := &fakeRW{} + var buf bytes.Buffer + c := newC(gh, rw) + c.cfg.Log = slog.New(slog.NewTextHandler(&buf, nil)) + if err := c.Cycle(context.Background()); err != nil { + t.Fatal(err) + } + if len(rw.created) != 2 { + t.Fatalf("created %v, want a runner for each job, the unlisted one included", rw.created) + } + out := buf.String() + for _, want := range []string{"unlisted=1", "job=310", "repo=acme/app", "failed=false"} { + if !strings.Contains(out, want) { + t.Errorf("log %q lacks %s", out, want) + } + } + _, body := health(t, c) + if body["unlisted_jobs"] != float64(1) { + t.Fatalf("healthz %v, want unlisted_jobs 1", body) + } + + gh.jobs[repo.Key()] = nil + _ = c.Cycle(context.Background()) + if _, body = health(t, c); body["unlisted_jobs"] != float64(0) { + t.Fatalf("healthz %v once served, want 0", body) + } +} + +type failingListRW struct{ fakeRW } + +func (*failingListRW) List(context.Context) ([]reconcile.Service, error) { + return nil, errors.New("railway down") +} + +// A cycle that fails on Railway still reports the unlisted jobs it found on GitHub. +func TestACycleThatFailsOnRailwayStillCountsUnlistedJobs(t *testing.T) { + gh := &fakeGH{jobs: map[string][]ghapp.Job{repo.Key(): {{ID: 310, Repo: "acme/app", CreatedAt: now, Unlisted: true}}}} + rw := &failingListRW{} + var buf bytes.Buffer + c := newC(gh, &rw.fakeRW) + c.rw = rw + c.cfg.Log = slog.New(slog.NewTextHandler(&buf, nil)) + if err := c.Cycle(context.Background()); err == nil { + t.Fatal("want the Railway failure reported") + } + if !strings.Contains(buf.String(), "failed=true") || !strings.Contains(buf.String(), "unlisted=1") { + t.Errorf("log %q: want the cycle line to say it failed and count the unlisted job", buf.String()) + } + _, body := health(t, c) + if body["unlisted_jobs"] != float64(1) || body["error"] != true || body["services"] != float64(0) || body["queued"] != float64(0) { + t.Fatalf("healthz %v, want unlisted_jobs 1, the error, and no services or queue claimed from a failed read", body) + } +} + +// A failed fallback read (the unfiltered run list answering 500 or 403) does not fail the scope: the +// jobs the filtered lists found still get their runners, each failure is logged at warn with its +// repository and status, and the cycle line and /healthz count them. The next clean cycle clears it. +func TestAFailedFallbackReadKeepsTheListedJobsAndIsCounted(t *testing.T) { + gh := &fakeGH{ + jobs: map[string][]ghapp.Job{repo.Key(): {{ID: 2, Repo: "acme/app", CreatedAt: now}}}, + jobsErr: map[string]error{repo.Key(): &ghapp.UnlistedReadError{Failed: []ghapp.UnlistedReadFailure{ + {Repo: "acme/app", Status: 500}, {Repo: "acme/lib", Status: 403}}}}, + } + rw := &fakeRW{} + var buf bytes.Buffer + c := newC(gh, rw) + c.cfg.Log = slog.New(slog.NewTextHandler(&buf, nil)) + if err := c.Cycle(context.Background()); err != nil { + t.Fatalf("err %v, want a failed fallback read not to fail the cycle", err) + } + if len(rw.created) != 1 { + t.Fatalf("created %v, want a runner for the listed job", rw.created) + } + out := buf.String() + for _, want := range []string{"unlisted_read_failed=2", "failed=false", "repo=acme/app status=500", "repo=acme/lib status=403"} { + if !strings.Contains(out, want) { + t.Errorf("log %q lacks %s", out, want) + } + } + code, body := health(t, c) + if code != 200 || body["unlisted_read_failures"] != float64(2) || body["unreadable_scopes"] != float64(0) || body["consecutive_failures"] != float64(0) { + t.Fatalf("healthz %d %v, want 200, unlisted_read_failures 2 and the scope readable", code, body) + } + + gh.jobsErr = nil + _ = c.Cycle(context.Background()) + if _, body = health(t, c); body["unlisted_read_failures"] != float64(0) { + t.Fatalf("healthz %v after a clean cycle, want 0", body) + } +} + +// /healthz counts the services left after the cycle: a reaped one is gone. +func TestHealthzServicesLeaveOutAReapedService(t *testing.T) { + name := "rr-" + repo.Hash() + "-aaaaaa" + gh := &fakeGH{runners: map[string][]reconcile.Runner{repo.Key(): {{ID: 7, Name: name}}}} + rw := &fakeRW{services: []reconcile.Service{{ID: "s1", Name: name, ScopeHash: repo.Hash(), CreatedAt: now.Add(-time.Hour)}}} + c := newC(gh, rw) + if err := c.Cycle(context.Background()); err != nil { + t.Fatal(err) + } + if _, body := health(t, c); len(rw.deleted) != 1 || body["services"] != float64(0) { + t.Fatalf("deleted %v healthz %v, want the idle service reaped and services 0", rw.deleted, body) + } +} diff --git a/internal/ghapp/conditional_test.go b/internal/ghapp/conditional_test.go index 84511de..c7f9ae5 100644 --- a/internal/ghapp/conditional_test.go +++ b/internal/ghapp/conditional_test.go @@ -40,8 +40,8 @@ func TestASecondIdenticalReadIsConditionalAndReusesTheBody(t *testing.T) { if err != nil || len(second) != 1 || second[0].ID != first[0].ID { t.Fatalf("second %v %v, want the same job as the first", second, err) } - if len(conditional) != 4 { - t.Fatalf("304s for %v, want the three run lists (queued, pending, in_progress) and the jobs list", conditional) + if len(conditional) != 5 { + t.Fatalf("304s for %v, want the four run lists (queued, pending, in_progress, unfiltered) and the jobs list", conditional) } } diff --git a/internal/ghapp/ghapp.go b/internal/ghapp/ghapp.go index 1e0c2ad..78de1d8 100644 --- a/internal/ghapp/ghapp.go +++ b/internal/ghapp/ghapp.go @@ -199,9 +199,27 @@ func (c *Client) call(ctx context.Context, method, rawURL, bearer string, body a // statusError is the error for an answer that is not a success; a 404 wraps ErrNotFound. func statusError(method, path string, code int) error { if code == http.StatusNotFound { - return fmt.Errorf("%w: %s %s: HTTP 404", ErrNotFound, method, path) + return &httpError{code: code, err: fmt.Errorf("%w: %s %s: HTTP 404", ErrNotFound, method, path)} } - return fmt.Errorf("ghapp: %s %s: HTTP %d", method, path, code) + return &httpError{code: code, err: fmt.Errorf("ghapp: %s %s: HTTP %d", method, path, code)} +} + +// httpError is an answer that is not a success, keeping its status for the caller. +type httpError struct { + code int + err error +} + +func (e *httpError) Error() string { return e.err.Error() } +func (e *httpError) Unwrap() error { return e.err } + +// statusOf is the HTTP status behind err, or 0 when GitHub gave no answer. +func statusOf(err error) int { + var he *httpError + if errors.As(err, &he) { + return he.code + } + return 0 } // keep stores a GET answer for conditional requests, pruning entries unused for an hour once the @@ -397,11 +415,34 @@ type Job struct { ID int64 Repo string CreatedAt time.Time + Unlisted bool // found only through the unfiltered runs list: GitHub's status filter left its run out +} + +// UnlistedReadFailure is one repository whose fallback read failed, with the HTTP status (0: no answer). +type UnlistedReadFailure struct { + Repo string + Status int +} + +// UnlistedReadError is QueuedJobs' answer when every read but the fallback for runs the status +// filter left out worked. The fallback only adds jobs, so the jobs returned with it are what the +// scope served before the fallback existed: the caller serves them and logs the failures. +type UnlistedReadError struct { + Failed []UnlistedReadFailure +} + +func (e *UnlistedReadError) Error() string { + parts := make([]string, len(e.Failed)) + for i, f := range e.Failed { + parts[i] = fmt.Sprintf("%s (HTTP %d)", f.Repo, f.Status) + } + return "ghapp: the unfiltered run list could not be read for " + strings.Join(parts, ", ") } // QueuedJobs are the queued jobs with our label in the scope's repositories: every repository // the installation holds under the org, or the one repository of a repo scope. A repo scope that // answers 404 is ErrNotFound; in an org scope a repository that vanished after the listing is skipped. +// When only fallback reads failed, the jobs come with an *UnlistedReadError naming them. func (c *Client) QueuedJobs(ctx context.Context, s reconcile.Scope) ([]Job, error) { tok, err := c.installToken(ctx, s) if err != nil { @@ -413,8 +454,14 @@ func (c *Client) QueuedJobs(ctx context.Context, s reconcile.Scope) ([]Job, erro return nil, err } } + return c.reposJobs(ctx, s, repos, tok) +} + +// reposJobs are the queued jobs of the scope's repositories, as QueuedJobs answers them. +func (c *Client) reposJobs(ctx context.Context, s reconcile.Scope, repos []string, tok string) ([]Job, error) { seen := map[int64]bool{} var out []Job + var failed []UnlistedReadFailure for _, repo := range repos { jobs, err := c.repoJobs(ctx, repo, tok, seen) if errors.Is(err, ErrNotFound) && s.Kind == "org" { @@ -423,7 +470,14 @@ func (c *Client) QueuedJobs(ctx context.Context, s reconcile.Scope) ([]Job, erro if err != nil { return nil, err } - out = append(out, jobs...) + unlisted, err := c.unlistedJobs(ctx, repo, tok, jobs.listed, seen) + if err != nil { + failed = append(failed, UnlistedReadFailure{Repo: repo, Status: statusOf(err)}) + } + out = append(append(out, jobs.jobs...), unlisted...) + } + if failed != nil { + return out, &UnlistedReadError{Failed: failed} } return out, nil } @@ -449,10 +503,19 @@ func (c *Client) orgRepos(ctx context.Context, s reconcile.Scope, tok string) ([ return repos, err } -// repoJobs are the queued jobs with our label in one repository, skipping the ids in seen and -// adding its own. A run that vanished after the runs listing is skipped. -func (c *Client) repoJobs(ctx context.Context, repo, tok string, seen map[int64]bool) ([]Job, error) { +// listedJobs are what the status-filtered lists of one repository found: the queued jobs and every +// run they listed. +type listedJobs struct { + jobs []Job + listed map[int64]bool +} + +// repoJobs are the queued jobs with our label that the status-filtered lists of one repository +// find, skipping the ids in seen and adding its own. A run that vanished after the runs listing is +// skipped. +func (c *Client) repoJobs(ctx context.Context, repo, tok string, seen map[int64]bool) (listedJobs, error) { var out []Job + listed := map[int64]bool{} // A run waiting to start reports "pending" (behind a concurrency group, say) while its // jobs are already queued, so pending runs are read too. for _, status := range []string{"queued", "pending", "in_progress"} { @@ -466,18 +529,58 @@ func (c *Client) repoJobs(ctx context.Context, repo, tok string, seen map[int64] func() any { runs.Runs = nil; return &runs }, func() { for _, r := range runs.Runs { runIDs = append(runIDs, r.ID) + listed[r.ID] = true } }) if err != nil { - return nil, err + return listedJobs{}, err } - for _, id := range runIDs { - jobs, err := c.runJobs(ctx, repo, id, tok, seen) - if err != nil && !errors.Is(err, ErrNotFound) { - return nil, err - } - out = append(out, jobs...) + jobs, err := c.jobsOfRuns(ctx, repo, runIDs, tok, seen) + if err != nil { + return listedJobs{}, err } + out = append(out, jobs...) + } + return listedJobs{jobs: out, listed: listed}, nil +} + +// unlistedJobs are the queued jobs of runs that GitHub's status filter left out of every listing +// (it did on 2026-11-21, for 25 minutes): it reads the first page of the unfiltered runs list, the +// newest runs, once with no paging, and the jobs of each run that is not completed and was not +// listed. A run pushed off that page by newer runs is never found here. It only adds jobs, so its +// error never costs the jobs the filtered lists found. +func (c *Client) unlistedJobs(ctx context.Context, repo, tok string, listed, seen map[int64]bool) ([]Job, error) { + var runs struct { + Runs []struct { + ID int64 `json:"id"` + Status string `json:"status"` + } `json:"workflow_runs"` + } + if _, _, err := c.call(ctx, http.MethodGet, fmt.Sprintf("%s/repos/%s/actions/runs?per_page=20", c.cfg.BaseURL, repo), tok, nil, &runs); err != nil { + return nil, err + } + var runIDs []int64 + for _, r := range runs.Runs { + if r.Status != "completed" && !listed[r.ID] { + runIDs = append(runIDs, r.ID) + } + } + jobs, err := c.jobsOfRuns(ctx, repo, runIDs, tok, seen) + for i := range jobs { + jobs[i].Unlisted = true + } + return jobs, err +} + +// jobsOfRuns are the queued jobs with our label in the runs, skipping a run that vanished. +func (c *Client) jobsOfRuns(ctx context.Context, repo string, runIDs []int64, tok string, seen map[int64]bool) ([]Job, error) { + var out []Job + for _, id := range runIDs { + jobs, err := c.runJobs(ctx, repo, id, tok, seen) + if err != nil && !errors.Is(err, ErrNotFound) { + return nil, err + } + out = append(out, jobs...) } return out, nil } diff --git a/internal/ghapp/unlisted_test.go b/internal/ghapp/unlisted_test.go new file mode 100644 index 0000000..26ec747 --- /dev/null +++ b/internal/ghapp/unlisted_test.go @@ -0,0 +1,226 @@ +package ghapp + +import ( + "context" + "errors" + "io" + "net/http" + "strings" + "testing" +) + +// unlistedFake is a GitHub whose status filter leaves run 31 out: only the unfiltered runs list +// shows it. Run 30 is a stale run the queued filter still lists but whose jobs are all done, and +// run 32 was cancelled. Run 34 waits for an approval: not completed, but nothing of it is queued. +func unlistedFake(t *testing.T) *fake { + return &fake{h: func(w http.ResponseWriter, r *http.Request) { + status := r.URL.Query().Get("status") + switch { + case strings.HasSuffix(r.URL.Path, "/actions/runs") && status == "queued": + io.WriteString(w, `{"total_count":1,"workflow_runs":[{"id":30,"status":"queued"}]}`) + case strings.HasSuffix(r.URL.Path, "/actions/runs") && status != "": + io.WriteString(w, `{"total_count":0,"workflow_runs":[]}`) + case strings.HasSuffix(r.URL.Path, "/actions/runs"): + if r.URL.Query().Get("per_page") != "20" { + t.Errorf("unfiltered list %s, want one page of 20", r.URL.RequestURI()) + } + io.WriteString(w, `{"total_count":5,"workflow_runs":[{"id":33,"status":"completed"},{"id":32,"status":"completed"},{"id":34,"status":"waiting"},{"id":31,"status":"queued"},{"id":30,"status":"queued"}]}`) + case strings.HasSuffix(r.URL.Path, "/runs/30/jobs"): + io.WriteString(w, `{"total_count":1,"jobs":[{"id":300,"status":"completed","labels":["self-hosted","railway"]}]}`) + case strings.HasSuffix(r.URL.Path, "/runs/34/jobs"): + io.WriteString(w, `{"total_count":1,"jobs":[{"id":340,"status":"waiting","labels":["railway"]}]}`) + case strings.HasSuffix(r.URL.Path, "/runs/31/jobs"): + io.WriteString(w, `{"total_count":2,"jobs":[{"id":310,"status":"queued","labels":["self-hosted","linux","x64","railway"],"created_at":"2026-11-21T18:38:55Z"},{"id":311,"status":"queued","labels":["ubuntu-latest"]}]}`) + default: + t.Errorf("unexpected %s", r.URL.RequestURI()) + w.WriteHeader(404) + } + }} +} + +// The 2026-11-21 incident: GitHub's runs?status=queued left a queued run out (and still listed a +// stale one with nothing to run), so its job never got a runner. One page of the unfiltered list is +// read too, and the job is found, marked unlisted. +func TestAQueuedRunTheStatusFilterLeavesOutIsFoundThroughTheUnfilteredList(t *testing.T) { + f := unlistedFake(t) + jobs, err := newGH(t, f).QueuedJobs(context.Background(), repo) + if err != nil { + t.Fatal(err) + } + if len(jobs) != 1 || jobs[0].ID != 310 || !jobs[0].Unlisted || jobs[0].Repo != "acme/app" || jobs[0].CreatedAt.IsZero() { + t.Fatalf("jobs %+v, want only job 310 of the unlisted run, marked unlisted", jobs) + } + for _, r := range f.reqs { + if strings.Contains(r, "/runs/32/") || strings.Contains(r, "/runs/33/") { + t.Errorf("request %q: a completed run has nothing to serve and must not be read", r) + } + } + reads := 0 + for _, r := range f.reqs { + if strings.Contains(r, "/runs/30/jobs") { + reads++ + } + } + if reads != 1 { + t.Errorf("run 30 jobs read %d times, want once: a run the filter already listed is not read again", reads) + } +} + +// The unfiltered page is read even when the filtered lists found a job of ours, so a run they left +// out gets its runner in the same cycle; the job they found is not counted again. +func TestTheUnfilteredListIsReadEvenWhenAQueuedJobWasFound(t *testing.T) { + f := &fake{h: func(w http.ResponseWriter, r *http.Request) { + switch { + case strings.HasSuffix(r.URL.Path, "/actions/runs") && r.URL.Query().Get("status") == "queued": + io.WriteString(w, `{"workflow_runs":[{"id":11,"status":"queued"}]}`) + case strings.HasSuffix(r.URL.Path, "/actions/runs") && r.URL.Query().Get("status") != "": + io.WriteString(w, `{"workflow_runs":[]}`) + case strings.HasSuffix(r.URL.Path, "/actions/runs"): + io.WriteString(w, `{"workflow_runs":[{"id":31,"status":"queued"},{"id":11,"status":"queued"}]}`) + case strings.HasSuffix(r.URL.Path, "/runs/11/jobs"): + io.WriteString(w, `{"jobs":[{"id":1,"status":"queued","labels":["railway"]}]}`) + case strings.HasSuffix(r.URL.Path, "/runs/31/jobs"): + io.WriteString(w, `{"jobs":[{"id":310,"status":"queued","labels":["railway"]}]}`) + default: + t.Errorf("unexpected %s", r.URL.RequestURI()) + w.WriteHeader(404) + } + }} + jobs, err := newGH(t, f).QueuedJobs(context.Background(), repo) + if err != nil || len(jobs) != 2 || jobs[0].ID != 1 || jobs[0].Unlisted || jobs[1].ID != 310 || !jobs[1].Unlisted { + t.Fatalf("jobs %+v err %v, want job 1 listed and job 310 unlisted", jobs, err) + } +} + +// A run that vanishes between the unfiltered list and its jobs read is skipped, like a listed one. +// Any other failure of the fallback (a 5xx, a 403 rate limit, on the list or on an unlisted run's +// jobs) keeps the jobs the filtered lists found: it comes back as an UnlistedReadError naming the +// repository and the status, which the caller logs and counts, never as a failed scope. +func TestTheFallbackSkipsAVanishedRunAndKeepsTheListedJobsOnOtherErrors(t *testing.T) { + for _, tc := range []struct { + list, jobs int + failed int // the status the error names; 0 when the fallback worked + }{{200, 404, 0}, {200, 500, 500}, {500, 200, 500}, {403, 200, 403}, {200, 403, 403}} { + f := &fake{h: func(w http.ResponseWriter, r *http.Request) { + switch { + case strings.HasSuffix(r.URL.Path, "/actions/runs") && r.URL.Query().Get("status") == "queued": + io.WriteString(w, `{"workflow_runs":[{"id":11}]}`) + case strings.HasSuffix(r.URL.Path, "/actions/runs") && r.URL.Query().Get("status") != "": + io.WriteString(w, `{"workflow_runs":[]}`) + case strings.HasSuffix(r.URL.Path, "/actions/runs"): + w.WriteHeader(tc.list) + io.WriteString(w, `{"workflow_runs":[{"id":31,"status":"queued"},{"id":11,"status":"queued"}]}`) + case strings.HasSuffix(r.URL.Path, "/runs/11/jobs"): + io.WriteString(w, `{"jobs":[{"id":1,"status":"queued","labels":["railway"]}]}`) + default: + w.WriteHeader(tc.jobs) + io.WriteString(w, `{"jobs":[{"id":310,"status":"queued","labels":["railway"]}]}`) + } + }} + jobs, err := newGH(t, f).QueuedJobs(context.Background(), repo) + if len(jobs) != 1 || jobs[0].ID != 1 || jobs[0].Unlisted { + t.Errorf("list %d jobs %d: jobs %+v, want the listed job 1 kept and nothing else", tc.list, tc.jobs, jobs) + } + var ue *UnlistedReadError + if tc.failed == 0 { + if err != nil { + t.Errorf("list %d jobs %d: err %v, want none: a vanished run is skipped", tc.list, tc.jobs, err) + } + continue + } + if !errors.As(err, &ue) || len(ue.Failed) != 1 || ue.Failed[0].Repo != "acme/app" || ue.Failed[0].Status != tc.failed { + t.Errorf("list %d jobs %d: err %#v, want an UnlistedReadError naming acme/app and HTTP %d", tc.list, tc.jobs, err, tc.failed) + } + } +} + +// A fallback that fails with no answer at all (the connection dropped) names status 0. +func TestAFallbackWithNoAnswerNamesStatusZero(t *testing.T) { + f := &fake{h: func(w http.ResponseWriter, r *http.Request) { + switch { + case strings.HasSuffix(r.URL.Path, "/actions/runs") && r.URL.Query().Get("status") != "": + io.WriteString(w, `{"workflow_runs":[]}`) + default: + hj, _ := w.(http.Hijacker) + conn, _, _ := hj.Hijack() + conn.Close() + } + }} + _, err := newGH(t, f).QueuedJobs(context.Background(), repo) + var ue *UnlistedReadError + if !errors.As(err, &ue) || len(ue.Failed) != 1 || ue.Failed[0].Status != 0 || !strings.Contains(ue.Error(), "acme/app") { + t.Fatalf("err %#v, want an UnlistedReadError for acme/app with status 0", err) + } +} + +// A jobs read that fails on a run the filtered lists found fails the read, as it always has. +func TestAFailedJobsReadOfAListedRunFailsTheRead(t *testing.T) { + f := &fake{h: func(w http.ResponseWriter, r *http.Request) { + switch { + case strings.HasSuffix(r.URL.Path, "/actions/runs") && r.URL.Query().Get("status") == "queued": + io.WriteString(w, `{"workflow_runs":[{"id":11}]}`) + case strings.HasSuffix(r.URL.Path, "/actions/runs"): + io.WriteString(w, `{"workflow_runs":[]}`) + default: + w.WriteHeader(500) + } + }} + if jobs, err := newGH(t, f).QueuedJobs(context.Background(), repo); err == nil { + t.Fatalf("jobs %+v, want the 500 on the jobs read reported", jobs) + } +} + +// orgFallbackFake is an org of three repositories, each with one queued job in the filtered lists. +// The fallback read of acme/a answers 500 and that of acme/b 403; listC is what acme/c's filtered +// queued list answers. +func orgFallbackFake(t *testing.T, listC int) *fake { + return &fake{h: func(w http.ResponseWriter, r *http.Request) { + status := r.URL.Query().Get("status") + switch { + case r.URL.Path == "/installation/repositories": + io.WriteString(w, `{"total_count":3,"repositories":[{"name":"a","owner":{"login":"acme"}},{"name":"b","owner":{"login":"acme"}},{"name":"c","owner":{"login":"acme"}}]}`) + case r.URL.Path == "/repos/acme/c/actions/runs" && status == "queued" && listC != 200: + w.WriteHeader(listC) + case strings.HasSuffix(r.URL.Path, "/actions/runs") && status == "queued": + io.WriteString(w, `{"workflow_runs":[{"id":11}]}`) + case strings.HasSuffix(r.URL.Path, "/actions/runs") && status != "": + io.WriteString(w, `{"workflow_runs":[]}`) + case r.URL.Path == "/repos/acme/a/actions/runs": + w.WriteHeader(500) + case r.URL.Path == "/repos/acme/b/actions/runs": + w.WriteHeader(403) + case strings.HasSuffix(r.URL.Path, "/actions/runs"): + io.WriteString(w, `{"workflow_runs":[]}`) + case strings.HasSuffix(r.URL.Path, "/runs/11/jobs"): + io.WriteString(w, `{"jobs":[{"id":1,"status":"queued","labels":["railway"]}]}`) + default: + t.Errorf("unexpected %s", r.URL.RequestURI()) + } + }} +} + +// In an org scope a failed fallback in one repository does not stop the others: every repository is +// still read, and every failed fallback is named in the one UnlistedReadError. +func TestAnOrgNamesEveryFailedFallbackAndKeepsEveryListedJob(t *testing.T) { + jobs, err := newGH(t, orgFallbackFake(t, 200)).QueuedJobs(context.Background(), org) + if len(jobs) != 1 || jobs[0].ID != 1 || jobs[0].Repo != "acme/a" { + t.Errorf("jobs %+v, want job 1 once (the same id in every repository is one job)", jobs) + } + var ue *UnlistedReadError + if !errors.As(err, &ue) || len(ue.Failed) != 2 || + ue.Failed[0] != (UnlistedReadFailure{Repo: "acme/a", Status: 500}) || ue.Failed[1] != (UnlistedReadFailure{Repo: "acme/b", Status: 403}) { + t.Fatalf("err %#v, want acme/a 500 and acme/b 403 named", err) + } + if msg := ue.Error(); !strings.Contains(msg, "acme/a") || !strings.Contains(msg, "acme/b") || !strings.Contains(msg, "403") { + t.Errorf("message %q, want both repositories and their status", msg) + } +} + +// A real read failure in a later repository still fails the scope, whatever fallbacks failed before it. +func TestAFailedFilteredListAfterAFailedFallbackStillFailsTheScope(t *testing.T) { + jobs, err := newGH(t, orgFallbackFake(t, 500)).QueuedJobs(context.Background(), org) + var ue *UnlistedReadError + if err == nil || errors.As(err, &ue) || jobs != nil { + t.Fatalf("jobs %+v err %v, want the 500 on acme/c's filtered list to fail the scope", jobs, err) + } +}