From 020272caad768964e691986dbdd2c1e6c1946975 Mon Sep 17 00:00:00 2001 From: fullsend-code <278716306+fullsend-ai-coder[bot]@users.noreply.github.com> Date: Thu, 5 Nov 2026 16:46:48 +0000 Subject: [PATCH 1/2] ci(#9128): harden behaviour-test dispatch and jobs-listing reads Re-land the behaviour-test reliability slice that #9084 carried and then reverted in 7fae148f7 as scope drift. This commit is the inverse of that revert, which applies cleanly to main; the other differences between #9084 and main in these files belong to the trace-context work and are not included. Forge layer: - Add RunAttempt to WorkflowRun and WorkflowJob, populated by the GitHub adapter from run_attempt. - Add ErrJobsListingNotFoundFirstPage. The GitHub and GitLab ListWorkflowRunJobs adapters attach it only to a page-1 not-found (the shape tracked in #9124). GitHub errors now name the repository, run, and page. GitHub Actions behaviour driver: - settleHarnessDispatchCount and AssertNoHarnessAgentArtifact list runs through the paginated, time-bounded listing and ignore skipped runs. - Runs that have not started (queued/requested/pending) are counted as pending without reading their jobs. - classifyJobsError(status, err) maps listing errors to skip, retryLater, or fatal for both paths. The count path keeps skip and retryLater runs pending; the one-shot negative path skips only runs that have not started and fails closed otherwise. - CountHarnessDispatches caches a completed run's jobs across polls only when a decisive counted agent match exists and every job belongs to the run's known attempt. Tests: dispatch_reads_test.go and workflow_attempt_test.go come back with the original regressions. Added cases in github_test.go, methods_test.go, and githubactions_test.go cover first-page vs later-page 404s and the error context. Closes #9128 Co-Authored-By: Claude Opus 5.5 --- docs/contributing/forge-abstraction.md | 10 + internal/forge/forge.go | 15 + internal/forge/github/github.go | 23 +- internal/forge/github/github_test.go | 129 +++++++ .../forge/github/workflow_attempt_test.go | 59 +++ internal/forge/gitlab/ci.go | 8 + internal/forge/gitlab/methods_test.go | 41 ++ .../ci/githubactions/dispatch_reads_test.go | 359 ++++++++++++++++++ .../drivers/ci/githubactions/githubactions.go | 114 +++++- .../ci/githubactions/githubactions_test.go | 32 +- 10 files changed, 776 insertions(+), 14 deletions(-) create mode 100644 internal/forge/github/workflow_attempt_test.go create mode 100644 pkg/behaviourtest/drivers/ci/githubactions/dispatch_reads_test.go diff --git a/docs/contributing/forge-abstraction.md b/docs/contributing/forge-abstraction.md index 380dcea2fa..308540e7a1 100644 --- a/docs/contributing/forge-abstraction.md +++ b/docs/contributing/forge-abstraction.md @@ -14,6 +14,16 @@ All git forge operations (GitHub API calls, PR comments, issue creation, workflo **FakeClient coverage:** Every exported `FakeClient` method must have an entry in `fakeClientCalls` in [`internal/forge/fake_test.go`](../../internal/forge/fake_test.go). `TestFakeClient_ErrorInjection` uses that table to assert each method returns its injected error, `TestFakeClient_ThreadSafety` runs it concurrently under `-race`, and `TestFakeClient_CoversAllMethods` fails when an entry is missing or stale. Fake methods must return copies, never slices, maps, or pointers into the fake's own storage: callers read results without holding the fake's lock. Likewise, store copies of caller-supplied slices and maps that a fake method later changes in place: callers keep their own reference. +**Workflow attempts:** `WorkflowRun.RunAttempt` and `WorkflowJob.RunAttempt` +identify executions when a forge reuses a run ID for reruns. Zero means the +attempt is unavailable. The GitHub Actions dispatch-count assertion reuses +completed job listings only within that assertion, for unchanged run metadata +and completed jobs whose known attempt matches the run. Reuse also requires +a matching agent job with a nonempty, non-skipped, non-cancelled conclusion: +that job already establishes a counted dispatch. Listings without that +evidence, unknown attempts, and unfinished jobs are read again on subsequent +polls because an absent job may become visible later. + **When reviewing PRs:** Flag any direct `exec.Command("gh", ...)`, raw GitHub API calls, or other forge-specific operations outside `internal/forge/github/` as a medium-severity or higher finding. This is an architectural violation, not a style preference. **Composite action (`action.yml`):** The forge abstraction extends to `action.yml` bash scripts. New GitHub API operations in action steps should be implemented as `fullsend` CLI subcommands (under `internal/cli/`) that use `forge.Client`, not as inline `gh api` calls. Existing `gh api` calls in `action.yml` that predate this rule are grandfathered but should be migrated when touched. diff --git a/internal/forge/forge.go b/internal/forge/forge.go index 7010800d25..7b4513fd6a 100644 --- a/internal/forge/forge.go +++ b/internal/forge/forge.go @@ -259,6 +259,19 @@ func ValidatePipelineVarOverrideRole(role string) error { // ErrNotFound indicates a requested resource was not found on the forge. var ErrNotFound = errors.New("not found") +// ErrJobsListingNotFoundFirstPage reports that a workflow run's jobs +// listing returned not found on its first page. Forges have been observed +// to do this for runs that have not started; the cause is unverified (see +// https://github.com/fullsend-ai/fullsend/issues/9124). The sentinel +// describes the response shape only and does not establish that the +// listing — or the run — is absent: callers may treat it as absence only +// when the run status independently shows the run has not started. +// +// Adapters attach it only to first-page not-founds. A not-found on a later +// page means the listing was already partially readable and may hold a +// completed job, so it never carries this sentinel. +var ErrJobsListingNotFoundFirstPage = errors.New("workflow run jobs listing not found on first page") + // IsNotFound reports whether err indicates a resource was not found. func IsNotFound(err error) bool { return errors.Is(err, ErrNotFound) @@ -536,6 +549,7 @@ type PullRequestInfo struct { // WorkflowRun represents a CI/CD workflow execution. type WorkflowRun struct { ID int + RunAttempt int // Attempt number for a rerunnable execution; zero when unavailable. Name string Event string // GitHub trigger event, e.g. "issues", "issue_comment" Status string // "queued", "in_progress", "completed" @@ -547,6 +561,7 @@ type WorkflowRun struct { // WorkflowJob represents a job within a workflow run. type WorkflowJob struct { ID int + RunAttempt int // Execution attempt containing this job; zero when unavailable. Name string Status string // "queued", "in_progress", "completed" Conclusion string // "success", "failure", "cancelled", etc. diff --git a/internal/forge/github/github.go b/internal/forge/github/github.go index dfce9debc9..58df0a4663 100644 --- a/internal/forge/github/github.go +++ b/internal/forge/github/github.go @@ -3226,6 +3226,7 @@ func (c *LiveClient) GetLatestWorkflowRun(ctx context.Context, owner, repo, work var result struct { WorkflowRuns []struct { ID int `json:"id"` + RunAttempt int `json:"run_attempt"` Name string `json:"name"` Event string `json:"event"` Status string `json:"status"` @@ -3245,6 +3246,7 @@ func (c *LiveClient) GetLatestWorkflowRun(ctx context.Context, owner, repo, work run := result.WorkflowRuns[0] return &forge.WorkflowRun{ ID: run.ID, + RunAttempt: run.RunAttempt, Name: run.Name, Event: run.Event, Status: run.Status, @@ -3263,6 +3265,7 @@ func (c *LiveClient) GetWorkflowRun(ctx context.Context, owner, repo string, run var run struct { ID int `json:"id"` + RunAttempt int `json:"run_attempt"` Name string `json:"name"` Event string `json:"event"` Status string `json:"status"` @@ -3276,6 +3279,7 @@ func (c *LiveClient) GetWorkflowRun(ctx context.Context, owner, repo string, run return &forge.WorkflowRun{ ID: run.ID, + RunAttempt: run.RunAttempt, Name: run.Name, Event: run.Event, Status: run.Status, @@ -4298,6 +4302,7 @@ func (c *LiveClient) ListWorkflowRuns(ctx context.Context, owner, repo, workflow var result struct { WorkflowRuns []struct { ID int `json:"id"` + RunAttempt int `json:"run_attempt"` Name string `json:"name"` Event string `json:"event"` Status string `json:"status"` @@ -4313,6 +4318,7 @@ func (c *LiveClient) ListWorkflowRuns(ctx context.Context, owner, repo, workflow for i, r := range result.WorkflowRuns { runs[i] = forge.WorkflowRun{ ID: r.ID, + RunAttempt: r.RunAttempt, Name: r.Name, Event: r.Event, Status: r.Status, @@ -4341,6 +4347,7 @@ func (c *LiveClient) ListWorkflowRunsSince(ctx context.Context, owner, repo, wor var result struct { WorkflowRuns []struct { ID int `json:"id"` + RunAttempt int `json:"run_attempt"` Name string `json:"name"` Event string `json:"event"` Status string `json:"status"` @@ -4365,6 +4372,7 @@ func (c *LiveClient) ListWorkflowRunsSince(ctx context.Context, owner, repo, wor } all = append(all, forge.WorkflowRun{ ID: r.ID, + RunAttempt: r.RunAttempt, Name: r.Name, Event: r.Event, Status: r.Status, @@ -4391,6 +4399,7 @@ func (c *LiveClient) ListRecentWorkflowRuns(ctx context.Context, owner, repo str var result struct { WorkflowRuns []struct { ID int `json:"id"` + RunAttempt int `json:"run_attempt"` Name string `json:"name"` Event string `json:"event"` Status string `json:"status"` @@ -4406,6 +4415,7 @@ func (c *LiveClient) ListRecentWorkflowRuns(ctx context.Context, owner, repo str for i, r := range result.WorkflowRuns { runs[i] = forge.WorkflowRun{ ID: r.ID, + RunAttempt: r.RunAttempt, Name: r.Name, Event: r.Event, Status: r.Status, @@ -4439,6 +4449,7 @@ func (c *LiveClient) ListWorkflowRunJobs(ctx context.Context, owner, repo string var result struct { Jobs []struct { ID int `json:"id"` + RunAttempt int `json:"run_attempt"` Name string `json:"name"` Status string `json:"status"` Conclusion string `json:"conclusion"` @@ -4446,8 +4457,17 @@ func (c *LiveClient) ListWorkflowRunJobs(ctx context.Context, owner, repo string } path := fmt.Sprintf("/repos/%s/%s/actions/runs/%d/jobs?per_page=%d&page=%d", url.PathEscape(owner), url.PathEscape(repo), runID, perPage, page) + label := fmt.Sprintf("list workflow run jobs for %s/%s run %d page %d", owner, repo, runID, page) if err := c.getCachedJSON(ctx, path, &result); err != nil { - return nil, fmt.Errorf("list workflow run jobs page %d: %w", page, err) + if page == 1 && forge.IsNotFound(err) { + // GitHub has been observed to 404 the first page for runs + // that have not started; the cause is unverified (#9124). + // Report the shape only — absence still depends on the run + // status. A later-page 404 is a partially readable listing + // and never carries the sentinel. + return nil, fmt.Errorf("%s: %w: %w", label, forge.ErrJobsListingNotFoundFirstPage, err) + } + return nil, fmt.Errorf("%s: %w", label, err) } if len(result.Jobs) == 0 { return jobs, nil @@ -4455,6 +4475,7 @@ func (c *LiveClient) ListWorkflowRunJobs(ctx context.Context, owner, repo string for _, j := range result.Jobs { jobs = append(jobs, forge.WorkflowJob{ ID: j.ID, + RunAttempt: j.RunAttempt, Name: j.Name, Status: j.Status, Conclusion: j.Conclusion, diff --git a/internal/forge/github/github_test.go b/internal/forge/github/github_test.go index 79e12ee87f..8b0e2f8450 100644 --- a/internal/forge/github/github_test.go +++ b/internal/forge/github/github_test.go @@ -5059,6 +5059,104 @@ func TestListWorkflowRunJobs_APIError(t *testing.T) { require.Error(t, err) } +func TestListWorkflowRunJobs_NotFound(t *testing.T) { + for _, tt := range []struct { + name string + status int + failures int + }{ + {name: "404 is not presumed transient", status: http.StatusNotFound, failures: 1}, + {name: "persistent 404 fails immediately", status: http.StatusNotFound, failures: 5}, + {name: "permission failure is not retried", status: http.StatusForbidden, failures: 5}, + } { + t.Run(tt.name, func(t *testing.T) { + calls := 0 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + calls++ + assert.Equal(t, "/repos/org/repo/actions/runs/42/jobs", r.URL.Path) + assert.Equal(t, "1", r.URL.Query().Get("page")) + if calls <= tt.failures { + w.WriteHeader(tt.status) + return + } + _, _ = io.WriteString(w, `{"jobs":[{"id":1,"name":"dispatch / Fix","status":"completed","conclusion":"success"}]}`) + })) + defer srv.Close() + + waits := 0 + client := newTestClient(t, srv).WithAfterFunc(func(time.Duration) <-chan time.Time { + waits++ + ch := make(chan time.Time, 1) + ch <- time.Now() + return ch + }) + jobs, err := client.ListWorkflowRunJobs(context.Background(), "org", "repo", 42) + assert.Equal(t, 1, calls) + assert.Zero(t, waits, "jobs errors must not add retry delays") + require.Error(t, err) + assert.Nil(t, jobs) + assert.Contains(t, err.Error(), "org/repo") + assert.Contains(t, err.Error(), "run 42") + assert.Contains(t, err.Error(), "page 1") + var apiErr *APIError + require.ErrorAs(t, err, &apiErr) + assert.Equal(t, tt.status, apiErr.StatusCode) + assert.Equal(t, tt.status == http.StatusNotFound, forge.IsNotFound(err)) + if tt.status == http.StatusNotFound { + assert.ErrorIs(t, err, forge.ErrJobsListingNotFoundFirstPage) + } else { + assert.NotErrorIs(t, err, forge.ErrJobsListingNotFoundFirstPage) + } + }) + } +} + +// TestListWorkflowRunJobs_LaterPageNotFoundDoesNotCarrySentinel is a +// regression test: a 404 on a later pagination page means the listing was +// partially readable — page 1 may already hold jobs — so it must not carry +// ErrJobsListingNotFoundFirstPage, which callers tolerate only when the run +// status independently shows the run has not started. +func TestListWorkflowRunJobs_LaterPageNotFoundDoesNotCarrySentinel(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Query().Get("page") { + case "1": + jobs := make([]map[string]any, 100) // full page forces page 2 + for i := range jobs { + jobs[i] = map[string]any{"id": i + 1, "name": "dispatch / Harness run (fix)", "status": "completed", "conclusion": "success"} + } + json.NewEncoder(w).Encode(map[string]any{"jobs": jobs}) + default: + w.WriteHeader(http.StatusNotFound) + } + })) + defer srv.Close() + + client := newTestClient(t, srv) + jobs, err := client.ListWorkflowRunJobs(context.Background(), "org", "repo", 42) + require.Error(t, err) + assert.Nil(t, jobs) + assert.True(t, forge.IsNotFound(err), "the 404 stays classified as not found") + assert.NotErrorIs(t, err, forge.ErrJobsListingNotFoundFirstPage, "a partially readable listing never carries the sentinel") + assert.Contains(t, err.Error(), "page 2") +} + +func TestListWorkflowRunJobs_CancelledContext(t *testing.T) { + calls := 0 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + calls++ + w.WriteHeader(http.StatusNotFound) + })) + defer srv.Close() + ctx, cancel := context.WithCancel(context.Background()) + cancel() + client := newTestClient(t, srv) + + jobs, err := client.ListWorkflowRunJobs(ctx, "org", "repo", 42) + require.ErrorIs(t, err, context.Canceled) + assert.Nil(t, jobs) + assert.Zero(t, calls) +} + // TestListWorkflowRunJobs_PaginatesBeyondFirstPage is a regression test // (#7996 review): ListWorkflowRunJobs previously issued a single // per_page=100 request with no pagination, so a run with more than 100 @@ -5108,6 +5206,37 @@ func TestListWorkflowRunJobs_PaginatesBeyondFirstPage(t *testing.T) { assert.Len(t, pageRequests, 2, "pagination must stop once a short page is seen") } +func TestListWorkflowRunJobs_MissingPageFailsWithoutPartialResults(t *testing.T) { + var pages []string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + page := r.URL.Query().Get("page") + pages = append(pages, page) + assert.Equal(t, "/repos/org/repo/actions/runs/42/jobs", r.URL.Path) + if page == "1" { + jobs := make([]forge.WorkflowJob, 100) + for i := range jobs { + jobs[i].ID = i + 1 + } + _ = json.NewEncoder(w).Encode(map[string]any{"jobs": jobs}) + return + } + assert.Equal(t, "2", page) + if len(pages) == 2 { + w.WriteHeader(http.StatusNotFound) + return + } + _, _ = io.WriteString(w, `{"jobs":[{"id":101,"name":"dispatch / Fix"}]}`) + })) + defer srv.Close() + + jobs, err := newTestClient(t, srv).ListWorkflowRunJobs(context.Background(), "org", "repo", 42) + require.Error(t, err) + assert.True(t, forge.IsNotFound(err)) + assert.Contains(t, err.Error(), "org/repo run 42 page 2") + assert.Equal(t, []string{"1", "2"}, pages) + assert.Nil(t, jobs, "an incomplete listing must not look like absence of an agent") +} + // TestListWorkflowRunJobs_PaginationExceeded guards the maxPages safety // valve: if every page is full, pagination must stop with an error instead // of looping indefinitely. diff --git a/internal/forge/github/workflow_attempt_test.go b/internal/forge/github/workflow_attempt_test.go new file mode 100644 index 0000000000..dd62a804d3 --- /dev/null +++ b/internal/forge/github/workflow_attempt_test.go @@ -0,0 +1,59 @@ +package github + +import ( + "context" + "fmt" + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/fullsend-ai/fullsend/internal/forge" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestWorkflowReaders_RunAttempt(t *testing.T) { + const run = `{"id":42,"run_attempt":2,"status":"completed","created_at":"2026-01-01T00:00:00Z"}` + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/repos/org/repo/actions/runs/42": + fmt.Fprint(w, run) + case "/repos/org/repo/actions/runs/42/jobs": + fmt.Fprintf(w, `{"jobs":[%s]}`, run) + default: + fmt.Fprintf(w, `{"workflow_runs":[%s]}`, run) + } + })) + defer srv.Close() + c := newTestClient(t, srv) + ctx := context.Background() + for name, read := range map[string]func() ([]forge.WorkflowRun, error){ + "latest": func() ([]forge.WorkflowRun, error) { + r, err := c.GetLatestWorkflowRun(ctx, "org", "repo", "fullsend.yaml") + require.NoError(t, err) + return []forge.WorkflowRun{*r}, nil + }, + "by ID": func() ([]forge.WorkflowRun, error) { + r, err := c.GetWorkflowRun(ctx, "org", "repo", 42) + require.NoError(t, err) + return []forge.WorkflowRun{*r}, nil + }, + "workflow": func() ([]forge.WorkflowRun, error) { return c.ListWorkflowRuns(ctx, "org", "repo", "fullsend.yaml") }, + "since": func() ([]forge.WorkflowRun, error) { + return c.ListWorkflowRunsSince(ctx, "org", "repo", "fullsend.yaml", time.Time{}) + }, + "recent": func() ([]forge.WorkflowRun, error) { return c.ListRecentWorkflowRuns(ctx, "org", "repo", 10) }, + } { + t.Run(name, func(t *testing.T) { + runs, err := read() + require.NoError(t, err) + require.Len(t, runs, 1) + assert.Equal(t, 2, runs[0].RunAttempt) + }) + } + jobs, err := c.ListWorkflowRunJobs(ctx, "org", "repo", 42) + require.NoError(t, err) + require.Len(t, jobs, 1) + assert.Equal(t, 2, jobs[0].RunAttempt) +} diff --git a/internal/forge/gitlab/ci.go b/internal/forge/gitlab/ci.go index 7c825bb298..3c738a362a 100644 --- a/internal/forge/gitlab/ci.go +++ b/internal/forge/gitlab/ci.go @@ -924,6 +924,14 @@ func (c *LiveClient) ListWorkflowRunJobs(ctx context.Context, owner, repo string proj, runID, perPage, page) resp, err := c.get(ctx, path) if err != nil { + if page == 1 && forge.IsNotFound(err) { + // GitLab has been observed to 404 the first page for + // pipelines that have not started; the cause is unverified + // (#9124). Report the shape only — absence still depends on + // the run status. A later-page 404 is a partially readable + // listing and never carries the sentinel. + return nil, fmt.Errorf("list pipeline jobs page %d: %w: %w", page, forge.ErrJobsListingNotFoundFirstPage, err) + } return nil, fmt.Errorf("list pipeline jobs page %d: %w", page, err) } var jobs []glJob diff --git a/internal/forge/gitlab/methods_test.go b/internal/forge/gitlab/methods_test.go index 436a2f2391..4fa3028885 100644 --- a/internal/forge/gitlab/methods_test.go +++ b/internal/forge/gitlab/methods_test.go @@ -4006,6 +4006,47 @@ func TestListWorkflowRunJobs_Error(t *testing.T) { }) _, err := client.ListWorkflowRunJobs(context.Background(), "o", "r", 10) require.Error(t, err) + assert.NotErrorIs(t, err, forge.ErrJobsListingNotFoundFirstPage) +} + +// TestListWorkflowRunJobs_FirstPageNotFoundCarriesSentinel covers the +// not-found classification adapters attach to a first-page 404, and the +// later-page 404 that must not carry it: page 1 was already readable and +// may hold a completed job. +func TestListWorkflowRunJobs_FirstPageNotFoundCarriesSentinel(t *testing.T) { + t.Run("first page 404 carries the sentinel", func(t *testing.T) { + client, mux := setupTest(t) + mux.HandleFunc("/api/v4/projects/o%2Fr/pipelines/10/jobs", func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusNotFound) + }) + _, err := client.ListWorkflowRunJobs(context.Background(), "o", "r", 10) + require.Error(t, err) + assert.ErrorIs(t, err, forge.ErrNotFound) + assert.ErrorIs(t, err, forge.ErrJobsListingNotFoundFirstPage) + }) + t.Run("later page 404 does not carry it", func(t *testing.T) { + client, mux := setupTest(t) + mux.HandleFunc("/api/v4/projects/o%2Fr/pipelines/10/jobs", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + switch r.URL.Query().Get("page") { + case "1": + jobs := make([]string, 100) + for i := range jobs { + jobs[i] = fmt.Sprintf(`{"id":%d,"name":"job-%d","status":"success"}`, i+1, i+1) + } + w.Header().Set("X-Next-Page", "2") + fmt.Fprint(w, "["+strings.Join(jobs, ",")+"]") + default: + w.WriteHeader(http.StatusNotFound) + } + }) + jobs, err := client.ListWorkflowRunJobs(context.Background(), "o", "r", 10) + require.Error(t, err) + assert.Nil(t, jobs) + assert.ErrorIs(t, err, forge.ErrNotFound, "the 404 stays classified as not found") + assert.NotErrorIs(t, err, forge.ErrJobsListingNotFoundFirstPage, "a partially readable listing never carries the sentinel") + assert.Contains(t, err.Error(), "page 2") + }) } func TestListWorkflowRunArtifacts_Error(t *testing.T) { diff --git a/pkg/behaviourtest/drivers/ci/githubactions/dispatch_reads_test.go b/pkg/behaviourtest/drivers/ci/githubactions/dispatch_reads_test.go new file mode 100644 index 0000000000..b8c886c461 --- /dev/null +++ b/pkg/behaviourtest/drivers/ci/githubactions/dispatch_reads_test.go @@ -0,0 +1,359 @@ +package githubactions + +import ( + "context" + "errors" + "fmt" + "testing" + "time" + + "github.com/fullsend-ai/fullsend/internal/forge" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// dispatchReadsClient measures requests while two runs settle over six polls. +type dispatchReadsClient struct { + *forge.FakeClient + polls int + jobReads map[int]int +} + +func (c *dispatchReadsClient) ListWorkflowRunsSince(ctx context.Context, owner, repo, workflow string, after time.Time) ([]forge.WorkflowRun, error) { + c.polls++ + runs, err := c.FakeClient.ListWorkflowRunsSince(ctx, owner, repo, workflow, after) + for i := range runs { + if runs[i].ID > 30 && c.polls >= 6 { + runs[i].Status = "completed" + } + } + return runs, err +} + +func (c *dispatchReadsClient) ListWorkflowRuns(ctx context.Context, owner, repo, workflow string) ([]forge.WorkflowRun, error) { + runs, err := c.ListWorkflowRunsSince(ctx, owner, repo, workflow, time.Time{}) + if len(runs) > 10 { + runs = runs[:10] + } + return runs, err +} + +func (c *dispatchReadsClient) ListWorkflowRunJobs(ctx context.Context, owner, repo string, runID int) ([]forge.WorkflowJob, error) { + c.jobReads[runID]++ + return c.FakeClient.ListWorkflowRunJobs(ctx, owner, repo, runID) +} + +func newDispatchReadsClient(after time.Time) *dispatchReadsClient { + fake := forge.NewFakeClient() + var runs []forge.WorkflowRun + jobs := make(map[int][]forge.WorkflowJob) + for id := 32; id > 0; id-- { + run := forge.WorkflowRun{ID: id, RunAttempt: 1, Status: "completed", Conclusion: "success", CreatedAt: after.Add(time.Duration(id) * time.Second).Format(time.RFC3339)} + switch { + case id > 30: + run.Status = "in_progress" + case id > 10: + run.Conclusion = "skipped" + } + runs = append(runs, run) + jobs[id] = []forge.WorkflowJob{{ID: id, RunAttempt: 1, Name: "dispatch / Route", Status: "completed", Conclusion: "success"}} + } + // The target dispatch is older than the ten newest runs. + jobs[1] = []forge.WorkflowJob{{ID: 1, RunAttempt: 1, Name: "dispatch / Harness run (fix)", Status: "completed", Conclusion: "success"}} + fake.WorkflowRunsList = map[string][]forge.WorkflowRun{"org/repo/fullsend.yaml": runs} + fake.WorkflowRunJobs = jobs + return &dispatchReadsClient{FakeClient: fake, jobReads: make(map[int]int)} +} + +func TestHarnessDispatchAssertions_RequestCounts(t *testing.T) { + t.Parallel() + after := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) + t.Run("count across six polls", func(t *testing.T) { + client := newDispatchReadsClient(after) + d := &Driver{Client: client, afterFunc: instantAfter} + count, err := d.CountHarnessDispatches(context.Background(), "org", "repo", "fix", after) + require.NoError(t, err) + var total int + for _, calls := range client.jobReads { + total += calls + } + t.Logf("list calls=%d jobs calls=%d unique jobs URLs=%d count=%d", client.polls, total, len(client.jobReads), count) + assert.Equal(t, 1, count, "the older dispatch must still be counted") + assert.Equal(t, 6, client.polls) + assert.Equal(t, 67, total, "one decisive match once, nine inconclusive and two active runs on six polls") + assert.Equal(t, 12, len(client.jobReads), "skipped workflows need no jobs lookup") + }) + t.Run("negative assertion", func(t *testing.T) { + client := newDispatchReadsClient(after) + d := &Driver{Client: client} + require.NoError(t, d.AssertNoHarnessAgentArtifact(context.Background(), "org", "repo", "absent", after)) + t.Logf("list calls=%d jobs calls=%d", client.polls, len(client.jobReads)) + assert.Len(t, client.jobReads, 12) + for _, calls := range client.jobReads { + assert.Equal(t, 1, calls) + } + }) +} + +func TestHarnessDispatchAssertions_SkippedRunNeedsNoJobs(t *testing.T) { + t.Parallel() + after := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) + fake := forge.NewFakeClient() + fake.WorkflowRunsList = map[string][]forge.WorkflowRun{"org/repo/fullsend.yaml": { + {ID: 1, Status: "completed", Conclusion: "skipped", CreatedAt: after.Format(time.RFC3339)}, + }} + fake.Errors["ListWorkflowRunJobs"] = errors.New("jobs must not be requested for a skipped workflow") + d := &Driver{Client: fake} + count, err := d.CountHarnessDispatches(context.Background(), "org", "repo", "fix", after) + require.NoError(t, err) + assert.Zero(t, count) + require.NoError(t, d.AssertNoHarnessAgentArtifact(context.Background(), "org", "repo", "fix", after)) +} + +func TestHarnessDispatchAssertions_NotStartedRunJobs(t *testing.T) { + t.Parallel() + after := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) + for _, status := range []string{"queued", "waiting", "requested", "pending"} { + t.Run(status, func(t *testing.T) { + t.Parallel() + fake := forge.NewFakeClient() + fake.WorkflowRunsList = map[string][]forge.WorkflowRun{"org/repo/fullsend.yaml": { + {ID: 1, Status: status, CreatedAt: after.Format(time.RFC3339)}, + }} + // A queued run is pending without a jobs read; a waiting run + // reads the listing and stays pending when it 404s on page 1. + fake.Errors["ListWorkflowRunJobs"] = forge.ErrJobsListingNotFoundFirstPage + d := &Driver{Client: fake} + + count, pending, err := d.settleHarnessDispatchCount(context.Background(), "org", "repo", "fix", after, nil) + require.NoError(t, err) + assert.Zero(t, count) + assert.Equal(t, 1, pending) + + // The negative assertion reads the listing and tolerates the + // first-page 404 only for a run that has not started. A waiting + // run can already hold a completed agent job, so an unreadable + // listing must fail the assertion rather than skip the run. + if status == "waiting" { + require.ErrorIs(t, d.AssertNoHarnessAgentArtifact(context.Background(), "org", "repo", "fix", after), forge.ErrJobsListingNotFoundFirstPage) + } else { + require.NoError(t, d.AssertNoHarnessAgentArtifact(context.Background(), "org", "repo", "fix", after)) + } + + // A 404 on a later page means the listing was partially read — + // page 1 may hold a completed agent job — so it is never + // absence, even for a not-started run. + fake.Errors["ListWorkflowRunJobs"] = fmt.Errorf("list workflow run jobs page 2: %w", forge.ErrNotFound) + require.ErrorIs(t, d.AssertNoHarnessAgentArtifact(context.Background(), "org", "repo", "fix", after), forge.ErrNotFound, + "a partially readable listing must fail the assertion") + + // A waiting run can follow jobs that already ran (environment + // approval), so returned jobs are checked, never skipped. + delete(fake.Errors, "ListWorkflowRunJobs") + fake.WorkflowRunJobs = map[int][]forge.WorkflowJob{1: { + {ID: 1, RunAttempt: 1, Name: "dispatch / Harness run (fix)", Status: "completed", Conclusion: "success"}, + }} + require.Error(t, d.AssertNoHarnessAgentArtifact(context.Background(), "org", "repo", "fix", after), + "a run awaiting approval can already hold a completed agent job") + + // Any other listing error stays fatal on the negative path. + lookupErr := errors.New("jobs lookup failed") + fake.Errors["ListWorkflowRunJobs"] = lookupErr + require.ErrorIs(t, d.AssertNoHarnessAgentArtifact(context.Background(), "org", "repo", "fix", after), lookupErr) + }) + } +} + +// TestCountHarnessDispatches_WaitingRunHoldsCompletedAgentJob pins the +// count-side rule: a workflow waiting on an environment approval can +// already hold a completed agent job, which is conclusive dispatch +// evidence — the count must not wait out the whole run. +// TestClassifyJobsError pins the full status × listing-error table that +// both dispatch paths route through. Changing an entry here is a +// semantic decision about run statuses, not a mechanical drift fix. +func TestClassifyJobsError(t *testing.T) { + t.Parallel() + firstPage404 := fmt.Errorf("list workflow run jobs page 1: %w: %w", forge.ErrJobsListingNotFoundFirstPage, forge.ErrNotFound) + laterPage404 := fmt.Errorf("list workflow run jobs page 2: %w", forge.ErrNotFound) + otherErr := errors.New("jobs lookup failed") + for _, tc := range []struct { + name string + status string + err error + want jobsReadOutcome + }{ + {"queued first-page 404 skips", "queued", firstPage404, jobsSkipRun}, + {"requested first-page 404 skips", "requested", firstPage404, jobsSkipRun}, + {"pending first-page 404 skips", "pending", firstPage404, jobsSkipRun}, + {"waiting first-page 404 retries later", "waiting", firstPage404, jobsRetryLater}, + {"in_progress first-page 404 is fatal", "in_progress", firstPage404, jobsFatal}, + {"completed first-page 404 is fatal", "completed", firstPage404, jobsFatal}, + {"queued later-page 404 is fatal", "queued", laterPage404, jobsFatal}, + {"waiting later-page 404 is fatal", "waiting", laterPage404, jobsFatal}, + {"completed later-page 404 is fatal", "completed", laterPage404, jobsFatal}, + {"queued other error is fatal", "queued", otherErr, jobsFatal}, + {"waiting other error is fatal", "waiting", otherErr, jobsFatal}, + {"completed other error is fatal", "completed", otherErr, jobsFatal}, + } { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tc.want, classifyJobsError(tc.status, tc.err)) + }) + } +} + +func TestCountHarnessDispatches_WaitingRunHoldsCompletedAgentJob(t *testing.T) { + t.Parallel() + after := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) + for _, tc := range []struct { + name string + job forge.WorkflowJob + count int + pend int + }{ + { + name: "completed agent job counts", + job: forge.WorkflowJob{ID: 1, RunAttempt: 1, Name: "dispatch / Harness run (fix)", Status: "completed", Conclusion: "success"}, + count: 1, + }, + { + name: "running agent job stays pending", + job: forge.WorkflowJob{ID: 1, RunAttempt: 1, Name: "dispatch / Harness run (fix)", Status: "in_progress"}, + pend: 1, + }, + { + name: "no agent job yet stays pending", + job: forge.WorkflowJob{ID: 1, RunAttempt: 1, Name: "dispatch / Route", Status: "completed", Conclusion: "success"}, + pend: 1, + }, + } { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + fake := forge.NewFakeClient() + fake.WorkflowRunsList = map[string][]forge.WorkflowRun{"org/repo/fullsend.yaml": { + {ID: 1, RunAttempt: 1, Status: "waiting", CreatedAt: after.Format(time.RFC3339)}, + }} + fake.WorkflowRunJobs = map[int][]forge.WorkflowJob{1: {tc.job}} + d := &Driver{Client: fake} + count, pending, err := d.settleHarnessDispatchCount(context.Background(), "org", "repo", "fix", after, nil) + require.NoError(t, err) + assert.Equal(t, tc.count, count) + assert.Equal(t, tc.pend, pending) + }) + } + t.Run("absent jobs listing stays pending", func(t *testing.T) { + t.Parallel() + fake := forge.NewFakeClient() + fake.WorkflowRunsList = map[string][]forge.WorkflowRun{"org/repo/fullsend.yaml": { + {ID: 1, RunAttempt: 1, Status: "waiting", CreatedAt: after.Format(time.RFC3339)}, + }} + fake.Errors["ListWorkflowRunJobs"] = forge.ErrJobsListingNotFoundFirstPage + d := &Driver{Client: fake} + count, pending, err := d.settleHarnessDispatchCount(context.Background(), "org", "repo", "fix", after, nil) + require.NoError(t, err) + assert.Zero(t, count) + assert.Equal(t, 1, pending) + }) +} + +func TestCountHarnessDispatches_CompletedRunJobsBecomeVisible(t *testing.T) { + t.Parallel() + after := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) + for _, firstJob := range []string{"dispatch / Route", "dispatch / Harness run (${{ matrix.agent }})", "dispatch / Fix", "dispatch / Harness run (fix)"} { + t.Run(firstJob, func(t *testing.T) { + client := newDispatchReadsClient(after) + run := client.WorkflowRunsList["org/repo/fullsend.yaml"][31] + client.WorkflowRunJobs[1] = []forge.WorkflowJob{{ID: 1, RunAttempt: 1, Name: firstJob, Status: "completed", Conclusion: "skipped"}} + if firstJob == "dispatch / Route" { + client.WorkflowRunJobs[1][0].Conclusion = "success" + } + d := &Driver{Client: client, afterFunc: func(time.Duration) <-chan time.Time { + if client.polls == 1 { + client.WorkflowRunJobs[1] = append(client.WorkflowRunJobs[1], forge.WorkflowJob{ + ID: 100, RunAttempt: 1, Name: "dispatch / Harness run (fix)", Status: "completed", Conclusion: "success", + }) + } + return instantAfter(0) + }} + count, err := d.CountHarnessDispatches(context.Background(), "org", "repo", "fix", after) + require.NoError(t, err) + assert.Equal(t, 1, count, "a lagging listing must not permanently hide the completed agent job") + assert.Equal(t, 2, client.jobReads[1], "reread the inconclusive listing, then cache the decisive match") + assert.Equal(t, 6, client.polls, "a pending sibling keeps the assertion polling") + assert.Equal(t, run, client.WorkflowRunsList["org/repo/fullsend.yaml"][31], "completed run metadata stays unchanged") + }) + } +} + +func TestHarnessDispatchAssertions_RelevantJobsErrorsRemainFatal(t *testing.T) { + t.Parallel() + after := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) + for _, run := range []forge.WorkflowRun{ + {Status: "completed", Conclusion: "success"}, + {Status: "completed", Conclusion: "failure"}, + {Status: "completed", Conclusion: "cancelled"}, + {Status: "in_progress", Conclusion: "skipped"}, + {}, + } { + t.Run(run.Status+"/"+run.Conclusion, func(t *testing.T) { + fake := forge.NewFakeClient() + run.ID, run.CreatedAt = 1, after.Format(time.RFC3339) + fake.WorkflowRunsList = map[string][]forge.WorkflowRun{"org/repo/fullsend.yaml": {run}} + lookupErr := errors.New("jobs lookup failed") + fake.Errors["ListWorkflowRunJobs"] = lookupErr + d := &Driver{Client: fake} + _, err := d.CountHarnessDispatches(context.Background(), "org", "repo", "fix", after) + require.ErrorIs(t, err, lookupErr) + require.ErrorIs(t, d.AssertNoHarnessAgentArtifact(context.Background(), "org", "repo", "fix", after), lookupErr) + }) + } +} + +func TestCountHarnessDispatches_CompletedJobCache(t *testing.T) { + t.Parallel() + after := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) + for _, name := range []string{"rerun", "unknown run attempt", "unknown job attempt", "mismatched job attempt", "unfinished job", "unfinished conclusion", "empty jobs", "assertion local", "changed conclusion"} { + t.Run(name, func(t *testing.T) { + client := newDispatchReadsClient(after) + run := &client.WorkflowRunsList["org/repo/fullsend.yaml"][31] + job := &client.WorkflowRunJobs[1][0] + switch name { + case "unknown run attempt": + run.RunAttempt = 0 + case "unknown job attempt": + job.RunAttempt = 0 + case "mismatched job attempt": + job.RunAttempt = 2 + case "unfinished job": + job.Status = "queued" + case "unfinished conclusion": + job.Conclusion = "" + case "empty jobs": + client.WorkflowRunJobs[1] = nil + } + d := &Driver{Client: client, afterFunc: func(time.Duration) <-chan time.Time { + if client.polls == 1 { + switch name { + case "rerun": + run.RunAttempt = 2 + job.RunAttempt = 2 + case "changed conclusion": + run.Conclusion = "cancelled" + } + client.WorkflowRunJobs[1] = []forge.WorkflowJob{{ID: 100, RunAttempt: run.RunAttempt, Name: "dispatch / Harness run (fix)", Status: "completed", Conclusion: "cancelled"}} + } + return instantAfter(0) + }} + count, err := d.CountHarnessDispatches(context.Background(), "org", "repo", "fix", after) + require.NoError(t, err) + if name == "assertion local" { + assert.Equal(t, 1, count, "the completed attempt is reused within the first assertion") + assert.Equal(t, 1, client.jobReads[1]) + count, err = d.CountHarnessDispatches(context.Background(), "org", "repo", "fix", after) + require.NoError(t, err) + } + assert.Zero(t, count, "a changed or uncertified job listing must be fetched again") + assert.GreaterOrEqual(t, client.jobReads[1], 2) + }) + } +} diff --git a/pkg/behaviourtest/drivers/ci/githubactions/githubactions.go b/pkg/behaviourtest/drivers/ci/githubactions/githubactions.go index a2fd69a4e4..97bab4f9ca 100644 --- a/pkg/behaviourtest/drivers/ci/githubactions/githubactions.go +++ b/pkg/behaviourtest/drivers/ci/githubactions/githubactions.go @@ -1705,8 +1705,9 @@ func (d *Driver) failedHarnessPollOnce(ctx context.Context, remaining time.Durat // cancellation is still in progress. func (d *Driver) CountHarnessDispatches(ctx context.Context, owner, repo, agent string, after time.Time) (int, error) { deadline := d.now().Add(dispatchWait) + completedJobs := make(map[forge.WorkflowRun][]forge.WorkflowJob) for { - count, pending, err := d.settleHarnessDispatchCount(ctx, owner, repo, agent, after) + count, pending, err := d.settleHarnessDispatchCount(ctx, owner, repo, agent, after, completedJobs) if err != nil { return 0, err } @@ -1729,6 +1730,60 @@ func (d *Driver) CountHarnessDispatches(ctx context.Context, owner, repo, agent } } +// runUnstarted reports whether a workflow run is queued before any job +// can run. Its jobs listing cannot classify a dispatch and can still 404 +// while the run sits in the queue. +func runUnstarted(status string) bool { + switch status { + case "queued", "requested", "pending": + return true + } + return false +} + +// jobsReadOutcome classifies a workflow run whose jobs listing could not +// be read. +type jobsReadOutcome int + +const ( + // jobsSkipRun: the run cannot hold agent work yet, so the caller + // ignores it — no dispatch, no violation. + jobsSkipRun jobsReadOutcome = iota + // jobsRetryLater: the run may hold agent work but its listing is not + // readable yet. A settling caller keeps the run pending; a one-shot + // caller fails closed, because an unreadable listing is not evidence + // that no agent job ran. + jobsRetryLater + // jobsFatal: the listing error is unexpected and must fail the caller. + jobsFatal +) + +// classifyJobsError is the only place that maps a run's status and a +// jobs-listing error to a tolerance rule. The dispatch-count and +// negative-assertion paths both route their listing errors through it +// and must not grow status predicates of their own. +// +// A run that has not started cannot hold agent work, and its listing has +// been observed to 404 on the first page before the run starts, so that +// shape skips the run. A waiting run — one held on an environment +// approval — can already hold a completed agent job, so its unreadable +// listing is retry material, never evidence of absence. Any other error +// is fatal; in particular a later-page 404 means page 1 was already +// readable and may hold a completed agent job, so it is never tolerated. +func classifyJobsError(status string, err error) jobsReadOutcome { + if !errors.Is(err, forge.ErrJobsListingNotFoundFirstPage) { + return jobsFatal + } + switch { + case runUnstarted(status): + return jobsSkipRun + case status == "waiting": + return jobsRetryLater + default: + return jobsFatal + } +} + // settleHarnessDispatchCount classifies harness runs created after the // trigger time into counted dispatches and pending runs. A run is pending // when its agent job exists but has not completed, or when the run itself @@ -1746,21 +1801,51 @@ func (d *Driver) CountHarnessDispatches(ctx context.Context, owner, repo, agent // computing the matrix (#7957 review, third pass — mirrors // harnessRoundPollOnce's guard; cancelled static jobs added #7996 review; // success/failure built-in matches added #7996 review, second pass). -func (d *Driver) settleHarnessDispatchCount(ctx context.Context, owner, repo, agent string, after time.Time) (count, pending int, err error) { - allRuns, err := d.Client.ListWorkflowRuns(ctx, owner, repo, harnessWorkflowFile) +func (d *Driver) settleHarnessDispatchCount(ctx context.Context, owner, repo, agent string, after time.Time, completedJobs map[forge.WorkflowRun][]forge.WorkflowJob) (count, pending int, err error) { + allRuns, err := d.listHarnessRunsAfterPaginated(ctx, owner, repo, after) if err != nil { return 0, 0, err } for _, r := range allRuns { - runTime, parseErr := time.Parse(time.RFC3339, r.CreatedAt) - if parseErr != nil || runTime.Before(after) { + if r.Status == "completed" && r.Conclusion == "skipped" { continue } - jobs, err := d.Client.ListWorkflowRunJobs(ctx, owner, repo, r.ID) - if err != nil { - return 0, 0, err + if runUnstarted(r.Status) { + // classifyJobsError would skip these runs anyway; skipping + // before the read also avoids a listing call that 404s while + // the run sits in the queue. + pending++ + continue + } + jobs, cached := completedJobs[r] + if !cached { + jobs, err = d.Client.ListWorkflowRunJobs(ctx, owner, repo, r.ID) + if err != nil { + // Settling, so both skippable and retryable runs stay + // pending rather than fail the count. + if outcome := classifyJobsError(r.Status, err); outcome == jobsSkipRun || outcome == jobsRetryLater { + pending++ + continue + } + return 0, 0, err + } } hasJob, job := matchAgentJob(jobs, agent) + if !cached { + // Only a counted terminal match is decisive; missing jobs can still become visible. + cacheable := r.Status == "completed" && r.RunAttempt > 0 && hasJob && + job.Conclusion != "" && !isConcurrencySuperseded(job.Conclusion) + // Reruns reuse IDs; only reuse completed jobs from the same known attempt. + for _, job := range jobs { + if job.Status != "completed" || job.RunAttempt != r.RunAttempt { + cacheable = false + break + } + } + if cacheable && completedJobs != nil { + completedJobs[r] = jobs + } + } switch { case hasJob && job.Status != "completed": pending++ @@ -1922,18 +2007,23 @@ func isConcurrencySuperseded(conclusion string) bool { // than artifacts so that sibling runs for other agents are not mistaken // for evidence. func (d *Driver) AssertNoHarnessAgentArtifact(ctx context.Context, owner, repo, agent string, after time.Time) error { - allRuns, err := d.Client.ListWorkflowRuns(ctx, owner, repo, harnessWorkflowFile) + allRuns, err := d.listHarnessRunsAfterPaginated(ctx, owner, repo, after) if err != nil { return err } for _, r := range allRuns { - runTime, parseErr := time.Parse(time.RFC3339, r.CreatedAt) - if parseErr != nil || runTime.Before(after) { + if r.Status == "completed" && r.Conclusion == "skipped" { continue } jobs, err := d.Client.ListWorkflowRunJobs(ctx, owner, repo, r.ID) if err != nil { - return err + // One-shot, so only a run that cannot hold agent work yet is + // skipped: an unreadable listing is not evidence that no + // agent job ran, so retryable and fatal both fail closed. + if classifyJobsError(r.Status, err) != jobsSkipRun { + return err + } + continue } // Every matching job is inspected independently here, rather than // through matchAgentJob's single "best" match: a job list can diff --git a/pkg/behaviourtest/drivers/ci/githubactions/githubactions_test.go b/pkg/behaviourtest/drivers/ci/githubactions/githubactions_test.go index 40b1ada8dc..36ba0f450d 100644 --- a/pkg/behaviourtest/drivers/ci/githubactions/githubactions_test.go +++ b/pkg/behaviourtest/drivers/ci/githubactions/githubactions_test.go @@ -568,6 +568,36 @@ func (c *truncatingListWorkflowRunsClient) ListWorkflowRuns(_ context.Context, _ return append([]forge.WorkflowRun(nil), c.truncated...), nil } +func TestHarnessDispatchAssertions_IncludeRunsBeyondFirstPage(t *testing.T) { + t.Parallel() + + after := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) + fake := forge.NewFakeClient() + var runs []forge.WorkflowRun + for id := range 11 { + runs = append(runs, forge.WorkflowRun{ + ID: id + 1, Status: "completed", Conclusion: "success", + CreatedAt: after.Add(time.Duration(id+1) * time.Minute).Format(time.RFC3339), + }) + } + fake.WorkflowRunsList = map[string][]forge.WorkflowRun{"org/repo/fullsend.yaml": runs} + fake.WorkflowRunJobs = map[int][]forge.WorkflowJob{ + 1: {{ID: 1, Name: "dispatch / Harness run (fix)", Status: "completed", Conclusion: "success"}}, + } + d := newTestDriver(&truncatingListWorkflowRunsClient{FakeClient: fake, truncated: runs[1:]}) + + t.Run("exact count", func(t *testing.T) { + count, err := d.CountHarnessDispatches(context.Background(), "org", "repo", "fix", after) + require.NoError(t, err) + assert.Equal(t, 1, count, "newer unrelated runs must not hide a dispatch") + }) + t.Run("negative assertion", func(t *testing.T) { + err := d.AssertNoHarnessAgentArtifact(context.Background(), "org", "repo", "fix", after) + require.Error(t, err) + assert.Contains(t, err.Error(), "workflow run 1") + }) +} + // TestWaitForHarnessAgentRound_SelectsEarliestEligibleRunBeyondTruncatedPage // is a regression test (#7996 review): listHarnessRunsAfter's shared // listing (used by WaitForHarnessAgent's latest-eligible-run selection) @@ -2890,7 +2920,7 @@ func TestSettleHarnessDispatchCount_SuccessfulBuiltinMatrixUnresolvedPending(t * } d := &Driver{Client: fake} - count, pending, err := d.settleHarnessDispatchCount(context.Background(), "org", "repo", "triage", after) + count, pending, err := d.settleHarnessDispatchCount(context.Background(), "org", "repo", "triage", after, nil) require.NoError(t, err) assert.Equal(t, 0, count, "a successful built-in match must not be counted while the custom matrix remains unresolved") assert.Equal(t, 1, pending, "the run must be classified as pending until the real matrix job appears") From ae9b74024bc8a0df7ac7c81e40a41a30ec273e86 Mon Sep 17 00:00:00 2001 From: fullsend-fix <278716306+fullsend-ai-coder[bot]@users.noreply.github.com> Date: Thu, 5 Nov 2026 17:07:23 +0000 Subject: [PATCH 2/2] fix: address review feedback on PR #9129 Move the count-side test doc comment next to its test function so godoc no longer merges it with TestClassifyJobsError, and place ErrJobsListingNotFoundFirstPage after IsNotFound so the ErrNotFound sentinel/predicate pair stays adjacent. Note: pre-commit could not fetch remote hook repositories (certificate verification failure); the applicable hooks (whitespace check, gofmt, go vet) were run directly and passed. Addresses #9129 Co-Authored-By: Claude Sonnet 5.5 --- internal/forge/forge.go | 10 +++++----- .../drivers/ci/githubactions/dispatch_reads_test.go | 8 ++++---- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/internal/forge/forge.go b/internal/forge/forge.go index 7b4513fd6a..022941837f 100644 --- a/internal/forge/forge.go +++ b/internal/forge/forge.go @@ -259,6 +259,11 @@ func ValidatePipelineVarOverrideRole(role string) error { // ErrNotFound indicates a requested resource was not found on the forge. var ErrNotFound = errors.New("not found") +// IsNotFound reports whether err indicates a resource was not found. +func IsNotFound(err error) bool { + return errors.Is(err, ErrNotFound) +} + // ErrJobsListingNotFoundFirstPage reports that a workflow run's jobs // listing returned not found on its first page. Forges have been observed // to do this for runs that have not started; the cause is unverified (see @@ -272,11 +277,6 @@ var ErrNotFound = errors.New("not found") // completed job, so it never carries this sentinel. var ErrJobsListingNotFoundFirstPage = errors.New("workflow run jobs listing not found on first page") -// IsNotFound reports whether err indicates a resource was not found. -func IsNotFound(err error) bool { - return errors.Is(err, ErrNotFound) -} - // ErrAlreadyExists indicates that the resource already exists. var ErrAlreadyExists = errors.New("already exists") diff --git a/pkg/behaviourtest/drivers/ci/githubactions/dispatch_reads_test.go b/pkg/behaviourtest/drivers/ci/githubactions/dispatch_reads_test.go index b8c886c461..d5987c3b59 100644 --- a/pkg/behaviourtest/drivers/ci/githubactions/dispatch_reads_test.go +++ b/pkg/behaviourtest/drivers/ci/githubactions/dispatch_reads_test.go @@ -164,10 +164,6 @@ func TestHarnessDispatchAssertions_NotStartedRunJobs(t *testing.T) { } } -// TestCountHarnessDispatches_WaitingRunHoldsCompletedAgentJob pins the -// count-side rule: a workflow waiting on an environment approval can -// already hold a completed agent job, which is conclusive dispatch -// evidence — the count must not wait out the whole run. // TestClassifyJobsError pins the full status × listing-error table that // both dispatch paths route through. Changing an entry here is a // semantic decision about run statuses, not a mechanical drift fix. @@ -202,6 +198,10 @@ func TestClassifyJobsError(t *testing.T) { } } +// TestCountHarnessDispatches_WaitingRunHoldsCompletedAgentJob pins the +// count-side rule: a workflow waiting on an environment approval can +// already hold a completed agent job, which is conclusive dispatch +// evidence — the count must not wait out the whole run. func TestCountHarnessDispatches_WaitingRunHoldsCompletedAgentJob(t *testing.T) { t.Parallel() after := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)