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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions docs/contributing/forge-abstraction.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
15 changes: 15 additions & 0 deletions internal/forge/forge.go
Original file line number Diff line number Diff line change
Expand Up @@ -264,6 +264,19 @@ func IsNotFound(err error) bool {
return errors.Is(err, ErrNotFound)
}

// ErrJobsListingNotFoundFirstPage reports that a workflow run's jobs
Comment thread
rh-hemartin marked this conversation as resolved.
Resolved
// 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")

// ErrAlreadyExists indicates that the resource already exists.
var ErrAlreadyExists = errors.New("already exists")

Expand Down Expand Up @@ -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"
Expand All @@ -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.
Expand Down
23 changes: 22 additions & 1 deletion internal/forge/github/github.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"`
Expand All @@ -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,
Expand All @@ -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"`
Expand All @@ -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,
Expand Down Expand Up @@ -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"`
Expand All @@ -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,
Expand Down Expand Up @@ -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"`
Expand All @@ -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,
Expand All @@ -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"`
Expand All @@ -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,
Expand Down Expand Up @@ -4439,22 +4449,33 @@ 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"`
} `json:"jobs"`
}
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
}
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,
Expand Down
129 changes: 129 additions & 0 deletions internal/forge/github/github_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down
59 changes: 59 additions & 0 deletions internal/forge/github/workflow_attempt_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
8 changes: 8 additions & 0 deletions internal/forge/gitlab/ci.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading
Loading