From b54923f7fab3ffaf13e6354d309627bbc4380662 Mon Sep 17 00:00:00 2001 From: parsilver Date: Sun, 22 Nov 2026 02:08:52 +0700 Subject: [PATCH 1/5] test(controller): find a queued job the status-filtered run list leaves out GitHub's runs?status=queued left a queued run out on 2026-11-21 and the job sat 25 minutes with no runner. These tests pin the fallback through the unfiltered run list and the healthz and log counts. They fail until the fallback exists. --- internal/controller/unlisted_test.go | 57 ++++++++++++++ internal/ghapp/ghapp.go | 1 + internal/ghapp/unlisted_test.go | 111 +++++++++++++++++++++++++++ 3 files changed, 169 insertions(+) create mode 100644 internal/controller/unlisted_test.go create mode 100644 internal/ghapp/unlisted_test.go diff --git a/internal/controller/unlisted_test.go b/internal/controller/unlisted_test.go new file mode 100644 index 0000000..479e726 --- /dev/null +++ b/internal/controller/unlisted_test.go @@ -0,0 +1,57 @@ +package controller + +import ( + "bytes" + "context" + "log/slog" + "strings" + "testing" + + "github.com/farzai/github-runner-railway/internal/ghapp" +) + +// 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 and a warning name it, and /healthz +// counts it in the last cycle and, once per job, since the controller started. +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"} { + if !strings.Contains(out, want) { + t.Errorf("log %q lacks %s", out, want) + } + } + _, body := health(t, c) + if body["unlisted_jobs"] != float64(1) || body["unlisted_jobs_total"] != float64(1) { + t.Fatalf("healthz %v, want unlisted_jobs 1 and unlisted_jobs_total 1", body) + } + + _ = c.Cycle(context.Background()) // still waiting: the same job again is not counted again + if _, body = health(t, c); body["unlisted_jobs"] != float64(1) || body["unlisted_jobs_total"] != float64(1) { + t.Fatalf("healthz %v after the same job again, want 1 and 1", body) + } + + gh.jobs[repo.Key()] = []ghapp.Job{{ID: 2, Repo: "acme/app", CreatedAt: now}, {ID: 311, Repo: "acme/app", CreatedAt: now, Unlisted: true}, {ID: 312, Repo: "acme/app", CreatedAt: now, Unlisted: true}} + _ = c.Cycle(context.Background()) + if _, body = health(t, c); body["unlisted_jobs"] != float64(2) || body["unlisted_jobs_total"] != float64(3) { + t.Fatalf("healthz %v after two new unlisted jobs, want 2 and 3", body) + } + + gh.jobs[repo.Key()] = nil + _ = c.Cycle(context.Background()) + if _, body = health(t, c); body["unlisted_jobs"] != float64(0) || body["unlisted_jobs_total"] != float64(3) { + t.Fatalf("healthz %v once served, want 0 and 3", body) + } +} diff --git a/internal/ghapp/ghapp.go b/internal/ghapp/ghapp.go index 1e0c2ad..f1683f2 100644 --- a/internal/ghapp/ghapp.go +++ b/internal/ghapp/ghapp.go @@ -397,6 +397,7 @@ 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 } // QueuedJobs are the queued jobs with our label in the scope's repositories: every repository diff --git a/internal/ghapp/unlisted_test.go b/internal/ghapp/unlisted_test.go new file mode 100644 index 0000000..3f19591 --- /dev/null +++ b/internal/ghapp/unlisted_test.go @@ -0,0 +1,111 @@ +package ghapp + +import ( + "context" + "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. +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":4,"workflow_runs":[{"id":33,"status":"completed"},{"id":32,"status":"completed"},{"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/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. With no queued job found through +// the filtered lists, one page of the unfiltered list is read 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) + } +} + +// When the filtered lists already found a job of ours, the unfiltered list is not read. +func TestTheUnfilteredListIsNotReadWhenAQueuedJobWasFound(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") && r.URL.Query().Get("status") != "": + 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()) + w.WriteHeader(404) + } + }} + jobs, err := newGH(t, f).QueuedJobs(context.Background(), repo) + if err != nil || len(jobs) != 1 || jobs[0].Unlisted { + t.Fatalf("jobs %+v err %v, want job 1, listed", jobs, err) + } +} + +// A run that vanishes between the unfiltered list and its jobs read is skipped, like a listed one; +// any other error on the fallback fails the read. +func TestTheFallbackSkipsAVanishedRunAndFailsOnOtherErrors(t *testing.T) { + for _, tc := range []struct { + list, jobs int + wantErr bool + }{{200, 404, false}, {200, 500, true}, {500, 200, true}} { + 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":[]}`) + case strings.HasSuffix(r.URL.Path, "/actions/runs"): + w.WriteHeader(tc.list) + io.WriteString(w, `{"workflow_runs":[{"id":31,"status":"queued"}]}`) + 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 (err != nil) != tc.wantErr || len(jobs) != 0 && tc.jobs != 200 { + t.Errorf("list %d jobs %d: jobs %+v err %v, want error %v", tc.list, tc.jobs, jobs, err, tc.wantErr) + } + } +} From 90233d3d18584293531766b72d8e8d0e293c77f1 Mon Sep 17 00:00:00 2001 From: parsilver Date: Sun, 22 Nov 2026 02:11:31 +0700 Subject: [PATCH 2/5] fix(ghapp): read the unfiltered run list for runs the status filter misses GitHub's runs?status=queued can leave a queued run out, and its job then never gets a runner. Every cycle now also reads the first page of the unfiltered runs list (once, no paging) and the jobs of each run that is not completed and was not listed; those jobs are marked Unlisted. On an idle repository the page is a 304 through the ETag cache. Proven by the new unlisted tests and the ghapp suite. --- internal/controller/unlisted_test.go | 23 ++++-------- internal/ghapp/conditional_test.go | 4 +-- internal/ghapp/ghapp.go | 53 ++++++++++++++++++++++++---- internal/ghapp/unlisted_test.go | 25 ++++++++----- 4 files changed, 71 insertions(+), 34 deletions(-) diff --git a/internal/controller/unlisted_test.go b/internal/controller/unlisted_test.go index 479e726..ead6aad 100644 --- a/internal/controller/unlisted_test.go +++ b/internal/controller/unlisted_test.go @@ -11,8 +11,8 @@ import ( ) // 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 and a warning name it, and /healthz -// counts it in the last cycle and, once per job, since the controller started. +// 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}}, @@ -34,24 +34,13 @@ func TestAnUnlistedJobGetsARunnerAndIsCountedOnHealthzAndInTheLog(t *testing.T) } } _, body := health(t, c) - if body["unlisted_jobs"] != float64(1) || body["unlisted_jobs_total"] != float64(1) { - t.Fatalf("healthz %v, want unlisted_jobs 1 and unlisted_jobs_total 1", body) - } - - _ = c.Cycle(context.Background()) // still waiting: the same job again is not counted again - if _, body = health(t, c); body["unlisted_jobs"] != float64(1) || body["unlisted_jobs_total"] != float64(1) { - t.Fatalf("healthz %v after the same job again, want 1 and 1", body) - } - - gh.jobs[repo.Key()] = []ghapp.Job{{ID: 2, Repo: "acme/app", CreatedAt: now}, {ID: 311, Repo: "acme/app", CreatedAt: now, Unlisted: true}, {ID: 312, Repo: "acme/app", CreatedAt: now, Unlisted: true}} - _ = c.Cycle(context.Background()) - if _, body = health(t, c); body["unlisted_jobs"] != float64(2) || body["unlisted_jobs_total"] != float64(3) { - t.Fatalf("healthz %v after two new unlisted jobs, want 2 and 3", body) + 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) || body["unlisted_jobs_total"] != float64(3) { - t.Fatalf("healthz %v once served, want 0 and 3", body) + if _, body = health(t, c); body["unlisted_jobs"] != float64(0) { + t.Fatalf("healthz %v once served, want 0", 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 f1683f2..8f1cbcc 100644 --- a/internal/ghapp/ghapp.go +++ b/internal/ghapp/ghapp.go @@ -454,6 +454,7 @@ func (c *Client) orgRepos(ctx context.Context, s reconcile.Scope, tok string) ([ // 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) { 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"} { @@ -467,18 +468,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 } - 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 nil, err } + out = append(out, jobs...) + } + unlisted, err := c.unlistedJobs(ctx, repo, tok, listed, seen) + return append(out, unlisted...), err +} + +// 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. +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 index 3f19591..77945c0 100644 --- a/internal/ghapp/unlisted_test.go +++ b/internal/ghapp/unlisted_test.go @@ -10,7 +10,7 @@ import ( // 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 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") @@ -23,9 +23,11 @@ func unlistedFake(t *testing.T) *fake { 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":4,"workflow_runs":[{"id":33,"status":"completed"},{"id":32,"status":"completed"},{"id":31,"status":"queued"},{"id":30,"status":"queued"}]}`) + io.WriteString(w, `{"total_count":4,"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: @@ -36,8 +38,8 @@ func unlistedFake(t *testing.T) *fake { } // 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. With no queued job found through -// the filtered lists, one page of the unfiltered list is read and the job is found, marked unlisted. +// 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) @@ -63,24 +65,29 @@ func TestAQueuedRunTheStatusFilterLeavesOutIsFoundThroughTheUnfilteredList(t *te } } -// When the filtered lists already found a job of ours, the unfiltered list is not read. -func TestTheUnfilteredListIsNotReadWhenAQueuedJobWasFound(t *testing.T) { +// 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}]}`) + 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) != 1 || jobs[0].Unlisted { - t.Fatalf("jobs %+v err %v, want job 1, listed", jobs, err) + 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) } } From 3c4f6079ca27da99bec3a8502cf027f1107e8c32 Mon Sep 17 00:00:00 2001 From: parsilver Date: Sun, 22 Nov 2026 02:12:09 +0700 Subject: [PATCH 3/5] fix(controller): count jobs found only through the unfiltered run list The gap on GitHub's side must stay visible once the fallback hides it: /healthz reports unlisted_jobs, the cycle line carries unlisted, and each such job is logged at warn with its repository and id. Docs list the fourth run read and its rate-limit cost. Proven by the controller unlisted test and the full suite. --- CHANGELOG.md | 1 + README.md | 7 +++++-- docs/deploy.md | 8 ++++++-- internal/controller/controller.go | 31 ++++++++++++++++++++++++------- 4 files changed, 36 insertions(+), 11 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 68f8f63..e6424af 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. 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..6201285 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`, `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`. `/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..cf9c979 100644 --- a/docs/deploy.md +++ b/docs/deploy.md @@ -146,8 +146,12 @@ 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. 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..624cee0 100644 --- a/internal/controller/controller.go +++ b/internal/controller/controller.go @@ -90,6 +90,7 @@ 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 Failing bool // ConsecutiveFailures reached FailAlertAfter } @@ -212,17 +213,18 @@ 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 + created, reaped, unlisted := 0, 0, 0 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", unlisted, "failed", err != nil) }() rd := c.readScopes(ctx) + unlisted = c.warnUnlisted(rd.jobs) 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, unlisted) return errors.Join(errs...) } ok := map[string]bool{} @@ -269,7 +271,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, unlisted) return errors.Join(errs...) } @@ -282,6 +284,21 @@ type scopeReads struct { errs []error // the errors that fail the cycle } +// 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 +} + // readScopes reads every scope, records how each went, and raises or clears the missing-scope alerts. func (c *Controller) readScopes(ctx context.Context) scopeReads { rd := scopeReads{queued: map[string]int{}, runners: map[string][]reconcile.Runner{}, jobs: map[string][]ghapp.Job{}} @@ -380,7 +397,7 @@ func (c *Controller) readScope(ctx context.Context, s reconcile.Scope) ([]ghapp. // 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, unlisted int) { if len(errs) > 0 { c.failures++ } else { @@ -389,7 +406,7 @@ 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: unlisted, Failing: c.failures >= c.cfg.FailAlertAfter} if len(errs) > 0 { st.LastError = errors.Join(errs...).Error() } @@ -520,7 +537,7 @@ 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} if rl, ok := c.gh.(RateLimiter); ok { body["github_rate_limits"] = rl.RateLimits() } From 79ac6d17e5a2e3988e5af6de2087e38b00af47b6 Mon Sep 17 00:00:00 2001 From: parsilver Date: Sun, 22 Nov 2026 02:15:33 +0700 Subject: [PATCH 4/5] test: cover the unlisted paths and kill their surviving mutants The quality gate found two uncovered changed lines and five surviving mutants on lines this change touched. New tests cover a Railway list failure with an unlisted job, a failed jobs read on a listed run, and /healthz services after a reap; the summary test now starts the call counter above zero. Coverage baseline moves to 88.79% as the gate asks. Gate run locally: all five checks pass. --- .quality/baseline.json | 2 +- internal/controller/controller.go | 3 +- internal/controller/summary_test.go | 2 +- internal/controller/unlisted_test.go | 45 +++++++++++++++++++++++++++- internal/ghapp/unlisted_test.go | 17 +++++++++++ 5 files changed, 65 insertions(+), 4 deletions(-) diff --git a/.quality/baseline.json b/.quality/baseline.json index ca893fb..7aeef81 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": 88.79, "metric": "statement coverage of cmd/ and internal/ without tests, as go tool cover -func totals it" }, "functionsMeasured": 59, "functionsOverCrap10": 10, "functionsOverCrap10List": [ diff --git a/internal/controller/controller.go b/internal/controller/controller.go index 624cee0..226caba 100644 --- a/internal/controller/controller.go +++ b/internal/controller/controller.go @@ -213,7 +213,8 @@ 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, unlisted := 0, 0, 0 + created, reaped := 0, 0 + var unlisted int // 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, "unlisted", unlisted, "failed", err != nil) 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 index ead6aad..a4fb4db 100644 --- a/internal/controller/unlisted_test.go +++ b/internal/controller/unlisted_test.go @@ -3,11 +3,14 @@ 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 @@ -28,7 +31,7 @@ func TestAnUnlistedJobGetsARunnerAndIsCountedOnHealthzAndInTheLog(t *testing.T) 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"} { + 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) } @@ -44,3 +47,43 @@ func TestAnUnlistedJobGetsARunnerAndIsCountedOnHealthzAndInTheLog(t *testing.T) 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) + } +} + +// /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/unlisted_test.go b/internal/ghapp/unlisted_test.go index 77945c0..a4cfe5c 100644 --- a/internal/ghapp/unlisted_test.go +++ b/internal/ghapp/unlisted_test.go @@ -116,3 +116,20 @@ func TestTheFallbackSkipsAVanishedRunAndFailsOnOtherErrors(t *testing.T) { } } } + +// 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) + } +} From 31b2e66cb7873df0be18dcb6e99f0086d7838b1f Mon Sep 17 00:00:00 2001 From: parsilver Date: Sun, 22 Nov 2026 02:38:45 +0700 Subject: [PATCH 5/5] fix(ghapp): keep the listed jobs when the unfiltered run list fails The fallback read only adds jobs, so a 5xx or a 403 rate limit on it must not cost a scope the jobs its status-filtered lists found, which it did before the fallback existed. QueuedJobs now returns those jobs with an UnlistedReadError naming each repository and status; the controller logs it at warn, counts it on /healthz and the cycle line, and serves the jobs. --- .quality/baseline.json | 2 +- CHANGELOG.md | 2 +- README.md | 2 +- docs/deploy.md | 4 +- internal/controller/controller.go | 52 +++++++++---- internal/controller/unlisted_test.go | 37 +++++++++ internal/ghapp/ghapp.go | 83 +++++++++++++++++--- internal/ghapp/unlisted_test.go | 109 ++++++++++++++++++++++++--- 8 files changed, 254 insertions(+), 37 deletions(-) diff --git a/.quality/baseline.json b/.quality/baseline.json index 7aeef81..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": 88.79, "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 e6424af..c2bb66c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,7 +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. On an idle repository the extra read is an unchanged `304`, which does not count against the rate limit. +- 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 6201285..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`, `unlisted_jobs`, `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`. `/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 diff --git a/docs/deploy.md b/docs/deploy.md index cf9c979..fbdb1ec 100644 --- a/docs/deploy.md +++ b/docs/deploy.md @@ -150,7 +150,9 @@ touched (tested in `internal/railway`). Still: `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. The cache of unchanged lists holds 2,000 entries, so past about 500 + 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 diff --git a/internal/controller/controller.go b/internal/controller/controller.go index 226caba..10b092b 100644 --- a/internal/controller/controller.go +++ b/internal/controller/controller.go @@ -91,6 +91,7 @@ type Status struct { 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 } @@ -214,18 +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 unlisted int // set once the scopes are read; the log line below reads it when the cycle ends + 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, "unlisted", unlisted, "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) - unlisted = c.warnUnlisted(rd.jobs) + 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, unlisted) + c.record(now, errs, 0, 0, gap) return errors.Join(errs...) } ok := map[string]bool{} @@ -272,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, unlisted) + c.record(now, errs, len(services)+len(plan.Create)-len(plan.Reap), total, gap) return errors.Join(errs...) } @@ -283,8 +285,14 @@ 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 { @@ -300,11 +308,25 @@ func (c *Controller) warnUnlisted(jobs map[string][]ghapp.Job) int { 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. 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)) } @@ -381,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, unlisted int) { +func (c *Controller) record(now time.Time, errs []error, services, queued int, gap unlistedGap) { if len(errs) > 0 { c.failures++ } else { @@ -407,7 +431,8 @@ func (c *Controller) record(now time.Time, errs []error, services, queued, unlis } unreadable, stuck := c.unreadableScopes() st := &Status{LastCycle: now, Services: services, Queued: queued, ConsecutiveFailures: c.failures, - LastSuccess: c.lastSuccess, UnreadableScopes: unreadable, UnlistedJobs: unlisted, 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() } @@ -538,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, "unlisted_jobs": st.UnlistedJobs} + "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/unlisted_test.go b/internal/controller/unlisted_test.go index a4fb4db..769cb45 100644 --- a/internal/controller/unlisted_test.go +++ b/internal/controller/unlisted_test.go @@ -74,6 +74,43 @@ func TestACycleThatFailsOnRailwayStillCountsUnlistedJobs(t *testing.T) { } } +// 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" diff --git a/internal/ghapp/ghapp.go b/internal/ghapp/ghapp.go index 8f1cbcc..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 @@ -400,9 +418,31 @@ type Job struct { 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 { @@ -414,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" { @@ -424,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 } @@ -450,9 +503,17 @@ 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 @@ -472,22 +533,22 @@ func (c *Client) repoJobs(ctx context.Context, repo, tok string, seen map[int64] } }) if err != nil { - return nil, err + return listedJobs{}, err } jobs, err := c.jobsOfRuns(ctx, repo, runIDs, tok, seen) if err != nil { - return nil, err + return listedJobs{}, err } out = append(out, jobs...) } - unlisted, err := c.unlistedJobs(ctx, repo, tok, listed, seen) - return append(out, unlisted...), err + 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. +// 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 { diff --git a/internal/ghapp/unlisted_test.go b/internal/ghapp/unlisted_test.go index a4cfe5c..26ec747 100644 --- a/internal/ghapp/unlisted_test.go +++ b/internal/ghapp/unlisted_test.go @@ -2,6 +2,7 @@ package ghapp import ( "context" + "errors" "io" "net/http" "strings" @@ -23,7 +24,7 @@ func unlistedFake(t *testing.T) *fake { 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":4,"workflow_runs":[{"id":33,"status":"completed"},{"id":32,"status":"completed"},{"id":34,"status":"waiting"},{"id":31,"status":"queued"},{"id":30,"status":"queued"}]}`) + 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"): @@ -91,29 +92,64 @@ func TestTheUnfilteredListIsReadEvenWhenAQueuedJobWasFound(t *testing.T) { } } -// A run that vanishes between the unfiltered list and its jobs read is skipped, like a listed one; -// any other error on the fallback fails the read. -func TestTheFallbackSkipsAVanishedRunAndFailsOnOtherErrors(t *testing.T) { +// 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 - wantErr bool - }{{200, 404, false}, {200, 500, true}, {500, 200, true}} { + 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"}]}`) + 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 (err != nil) != tc.wantErr || len(jobs) != 0 && tc.jobs != 200 { - t.Errorf("list %d jobs %d: jobs %+v err %v, want error %v", tc.list, tc.jobs, jobs, err, tc.wantErr) + 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) } } @@ -133,3 +169,58 @@ func TestAFailedJobsReadOfAListedRunFailsTheRead(t *testing.T) { 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) + } +}