Skip to content
Closed
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
110 changes: 100 additions & 10 deletions pkg/behaviourtest/drivers/ci/githubactions/githubactions.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,6 @@ import (

const (
pollInterval = 15 * time.Second
dispatchWait = 12 * time.Minute
dispatchPoll = 5 * time.Second
dispatchMaxTry = 48

artifactRunPoll = 5 * time.Second
Expand All @@ -29,6 +27,12 @@ const (
assertNoWorkflowDelay = 10 * time.Second
)

// Overridable in tests so timeout / fail-fast paths do not burn wall clock.
var (
dispatchWait = 12 * time.Minute
dispatchPoll = 5 * time.Second
)

// Driver implements ci.Driver against GitHub Actions.
type Driver struct {
Client forge.Client
Expand Down Expand Up @@ -432,6 +436,12 @@ func readLimited(r io.Reader, limit int64) ([]byte, error) {
}

// WaitForHarnessAgent waits for a successful harness-run workflow and artifact for agent.
//
// When the harness fails before uploading an artifact (for example missing
// agent files after scaffold deletion), polling artifacts alone yields an
// opaque timeout. This method fail-fasts on completed non-success workflow
// runs after the trigger time and includes recent-run diagnostics on
// timeout so flakes self-explain (#5707).
func (d *Driver) WaitForHarnessAgent(ctx context.Context, owner, repo, agent string, after time.Time) (*forge.WorkflowRun, error) {
artifactName := "fullsend-" + agent
deadline := time.Now().Add(dispatchWait)
Expand All @@ -446,22 +456,102 @@ func (d *Driver) WaitForHarnessAgent(ctx context.Context, owner, repo, agent str
continue
}
art := selectRepositoryArtifactAfter(arts, artifactName, after)
if art == nil {
if art != nil {
run, err := d.Client.GetWorkflowRun(ctx, owner, repo, art.WorkflowRunID)
if err != nil {
continue
}
if run.Status != "completed" {
continue
}
if run.Conclusion != "success" {
return nil, fmt.Errorf("harness run for %q concluded with %q%s", agent, run.Conclusion, formatWorkflowRunRef(run))
}
return run, nil
}
if failed := selectFailedWorkflowRunAfter(d.listRecentRuns(ctx, owner, repo), after); failed != nil {
return nil, fmt.Errorf("harness agent %q did not complete successfully: workflow run %d concluded with %q%s%s",
agent, failed.ID, failed.Conclusion, formatWorkflowRunRef(failed), formatRecentRunsDiag(d.listRecentRuns(ctx, owner, repo), after))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[medium] redundant-api-call

d.listRecentRuns(ctx, owner, repo) is called twice in the fail-fast error path: once as input to selectFailedWorkflowRunAfter, and again inside formatRecentRunsDiag within the same fmt.Errorf. This doubles API load and introduces a TOCTOU window where the two calls may return different results.

Suggested fix: Store the result in a local variable and pass the same slice to both selectFailedWorkflowRunAfter and formatRecentRunsDiag.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[low] edge-case

selectFailedWorkflowRunAfter operates on all runs returned by ListRecentWorkflowRuns without filtering by workflow name. An unrelated workflow failure could cause a false fail-fast.

}
}
return nil, fmt.Errorf("harness agent %q did not complete successfully%s",
agent, formatRecentRunsDiag(d.listRecentRuns(ctx, owner, repo), after))
}

func (d *Driver) listRecentRuns(ctx context.Context, owner, repo string) []forge.WorkflowRun {
runs, err := d.Client.ListRecentWorkflowRuns(ctx, owner, repo, 30)
if err != nil {
return nil
}
return runs
}

// selectFailedWorkflowRunAfter returns the newest completed non-success
// workflow run created at or after after that indicates a real harness
// failure.
//
// "skipped" is intentionally ignored: GitHub concurrency cancel-in-progress
// and path-filter skips produce skipped conclusions while a newer run is
// still in progress. Treating skipped as terminal caused false fail-fasts
// during behaviour tests (#5707).
func selectFailedWorkflowRunAfter(runs []forge.WorkflowRun, after time.Time) *forge.WorkflowRun {
var best *forge.WorkflowRun
for i := range runs {
run := &runs[i]
if run.Status != "completed" || !isHarnessFailureConclusion(run.Conclusion) {
continue
}
run, err := d.Client.GetWorkflowRun(ctx, owner, repo, art.WorkflowRunID)
if err != nil {
runTime, parseErr := time.Parse(time.RFC3339, run.CreatedAt)
if parseErr != nil || runTime.Before(after) {
continue
}
if run.Status != "completed" {
if best == nil || run.ID > best.ID {
best = run
}
}
return best
}

func isHarnessFailureConclusion(conclusion string) bool {
switch conclusion {
case "failure", "timed_out", "startup_failure":
return true
default:
// skipped/cancelled often come from concurrency cancel-in-progress
// while a newer run is still active — do not fail-fast on those.
return false
}
}

func formatWorkflowRunRef(run *forge.WorkflowRun) string {
if run == nil {
return ""
}
if run.HTMLURL != "" {
return fmt.Sprintf(" (%s)", run.HTMLURL)
}
return ""
}

// formatRecentRunsDiag lists recent workflow runs after after for timeout
// / fail-fast error messages.
func formatRecentRunsDiag(runs []forge.WorkflowRun, after time.Time) string {
var parts []string
for _, run := range runs {
runTime, parseErr := time.Parse(time.RFC3339, run.CreatedAt)
if parseErr != nil || runTime.Before(after) {
continue
}
if run.Conclusion != "success" {
return nil, fmt.Errorf("harness run for %q concluded with %q", agent, run.Conclusion)
ref := fmt.Sprintf("id=%d name=%q status=%s conclusion=%q", run.ID, run.Name, run.Status, run.Conclusion)
if run.HTMLURL != "" {
ref += " url=" + run.HTMLURL
}
return run, nil
parts = append(parts, ref)
}
if len(parts) == 0 {
return fmt.Sprintf("; no workflow runs after %s", after.Format(time.RFC3339))
}
return nil, fmt.Errorf("harness agent %q did not complete successfully", agent)
return "; recent runs after " + after.Format(time.RFC3339) + ": " + strings.Join(parts, "; ")
}

// CountHarnessDispatches returns the number of fullsend-{agent} artifacts
Expand Down
107 changes: 107 additions & 0 deletions pkg/behaviourtest/drivers/ci/githubactions/githubactions_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -271,3 +271,110 @@ func TestWaitForHarnessAgent_FromRepositoryArtifact(t *testing.T) {
require.NotNil(t, run)
assert.Equal(t, 99, run.ID)
}

func TestWaitForHarnessAgent_FailFastOnFailedRun(t *testing.T) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[low] test-fragility

New tests mutate package-level dispatchWait/dispatchPoll vars. No race with existing t.Parallel() tests (Go serializes sequential tests before releasing parallel tests), but the pattern is fragile if someone later adds t.Parallel().

// Mutates package-level dispatchWait/dispatchPoll — not parallel-safe.
prevWait, prevPoll := dispatchWait, dispatchPoll
dispatchWait = 2 * time.Second
dispatchPoll = 10 * time.Millisecond
t.Cleanup(func() {
dispatchWait, dispatchPoll = prevWait, prevPoll
})

after := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)
client := forge.NewFakeClient()
client.RepositoryArtifacts = map[string][]forge.RepositoryArtifact{
"org/repo": {},
}
client.RecentWorkflowRuns = map[string][]forge.WorkflowRun{
"org/repo": {
{
ID: 42,
Name: "Dispatch",
Status: "completed",
Conclusion: "failure",
HTMLURL: "https://github.com/org/repo/actions/runs/42",
CreatedAt: "2026-01-02T00:00:00Z",
},
},
}

d := &Driver{Client: client}
_, err := d.WaitForHarnessAgent(context.Background(), "org", "repo", "fork-pr-sync", after)
require.Error(t, err)
assert.Contains(t, err.Error(), `workflow run 42 concluded with "failure"`)
assert.Contains(t, err.Error(), "https://github.com/org/repo/actions/runs/42")
assert.Contains(t, err.Error(), "recent runs after")
}

func TestWaitForHarnessAgent_TimeoutIncludesRecentRunsDiag(t *testing.T) {
// Mutates package-level dispatchWait/dispatchPoll — not parallel-safe.
prevWait, prevPoll := dispatchWait, dispatchPoll
dispatchWait = 50 * time.Millisecond
dispatchPoll = 10 * time.Millisecond
t.Cleanup(func() {
dispatchWait, dispatchPoll = prevWait, prevPoll
})

after := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)
client := forge.NewFakeClient()
client.RepositoryArtifacts = map[string][]forge.RepositoryArtifact{
"org/repo": {},
}
client.RecentWorkflowRuns = map[string][]forge.WorkflowRun{
"org/repo": {
{
ID: 7,
Name: "Dispatch",
Status: "in_progress",
Conclusion: "",
HTMLURL: "https://github.com/org/repo/actions/runs/7",
CreatedAt: "2026-01-02T00:00:00Z",
},
},
}

d := &Driver{Client: client}
_, err := d.WaitForHarnessAgent(context.Background(), "org", "repo", "issue-ping", after)
require.Error(t, err)
assert.Contains(t, err.Error(), `harness agent "issue-ping" did not complete successfully`)
assert.Contains(t, err.Error(), "id=7")
assert.Contains(t, err.Error(), "status=in_progress")
}

func TestSelectFailedWorkflowRunAfter(t *testing.T) {
t.Parallel()

after := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)
runs := []forge.WorkflowRun{
{ID: 1, Status: "completed", Conclusion: "failure", CreatedAt: "2025-12-31T00:00:00Z"},
{ID: 2, Status: "completed", Conclusion: "success", CreatedAt: "2026-01-02T00:00:00Z"},
{ID: 3, Status: "completed", Conclusion: "failure", CreatedAt: "2026-01-02T01:00:00Z"},
{ID: 4, Status: "completed", Conclusion: "skipped", CreatedAt: "2026-01-02T02:00:00Z"},
{ID: 5, Status: "completed", Conclusion: "cancelled", CreatedAt: "2026-01-02T02:30:00Z"},
{ID: 6, Status: "in_progress", Conclusion: "", CreatedAt: "2026-01-02T03:00:00Z"},
}
got := selectFailedWorkflowRunAfter(runs, after)
require.NotNil(t, got)
assert.Equal(t, 3, got.ID)
assert.Equal(t, "failure", got.Conclusion)
}

func TestSelectFailedWorkflowRunAfter_IgnoresSkipped(t *testing.T) {
t.Parallel()

after := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)
runs := []forge.WorkflowRun{
{ID: 1, Status: "completed", Conclusion: "skipped", CreatedAt: "2026-01-02T00:00:00Z"},
{ID: 2, Status: "in_progress", Conclusion: "", CreatedAt: "2026-01-02T01:00:00Z"},
}
assert.Nil(t, selectFailedWorkflowRunAfter(runs, after))
}

func TestFormatRecentRunsDiag_NoRuns(t *testing.T) {
t.Parallel()

after := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)
got := formatRecentRunsDiag(nil, after)
assert.Contains(t, got, "no workflow runs after")
}
19 changes: 16 additions & 3 deletions pkg/behaviourtest/steps/dispatch.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,13 +91,26 @@ func givenCustomHarness(w *world.World, name, doc string) error {
}
w.DispatchAgent = name

ctx := context.Background()
cfgOwner := w.Install.ConfigOwner()
cfgRepo := w.Install.ConfigRepo()

harnessPath := filepath.Join(".fullsend", "harness", name+".yaml")
if err := w.SCM.CommitFile(context.Background(), w.Install.ConfigOwner(), w.Install.ConfigRepo(), harnessPath, fmt.Sprintf("behaviour: add harness %s", name), []byte(doc)); err != nil {
if err := w.SCM.CommitFile(ctx, cfgOwner, cfgRepo, harnessPath, fmt.Sprintf("behaviour: add harness %s", name), []byte(doc)); err != nil {
return fmt.Errorf("committing harness: %w", err)
}

// Scaffold agent files were removed in #5552. Local harnesses still
// reference relative paths like agents/triage.md, which resolve under
// .fullsend/ at runtime. Commit minimal fixtures so clean pool repos
// do not fail with "stat .../.fullsend/agents/triage.md: no such file".
prefix := w.Install.ConfigPathPrefix()
if _, err := commitRelativeResources(ctx, w, cfgOwner, cfgRepo, name, doc, prefix); err != nil {
return fmt.Errorf("committing harness relative resources: %w", err)
}

cfgPath := filepath.Join(".fullsend", "config.yaml")
cfgData, err := w.SCM.GetFileContent(context.Background(), w.Install.ConfigOwner(), w.Install.ConfigRepo(), cfgPath)
cfgData, err := w.SCM.GetFileContent(ctx, cfgOwner, cfgRepo, cfgPath)
if err != nil {
return fmt.Errorf("reading config: %w", err)
}
Expand All @@ -123,7 +136,7 @@ func givenCustomHarness(w *world.World, name, doc string) error {
if err != nil {
return err
}
if err := w.SCM.CommitFile(context.Background(), w.Install.ConfigOwner(), w.Install.ConfigRepo(), cfgPath, fmt.Sprintf("behaviour: register harness %s", name), merged); err != nil {
if err := w.SCM.CommitFile(ctx, cfgOwner, cfgRepo, cfgPath, fmt.Sprintf("behaviour: register harness %s", name), merged); err != nil {
return fmt.Errorf("updating config: %w", err)
}
return nil
Expand Down
15 changes: 15 additions & 0 deletions pkg/behaviourtest/steps/dispatch_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,21 @@ func TestGivenCustomHarness_Validation(t *testing.T) {
require.Error(t, givenCustomHarness(w, "agent", ""))
}

func TestGivenCustomHarness_CommitsAgentFixture(t *testing.T) {
scm := &fakeURLSCM{files: map[string][]byte{
"test-org/test-repo/.fullsend/config.yaml": []byte("version: \"1\"\nagents: []\n"),
}}
w := &world.World{
Install: &fakeURLInstall{owner: "test-org", repo: "test-repo"},
SCM: scm,
}
err := givenCustomHarness(w, "issue-ping", "agent: agents/triage.md\nrole: triage\nslug: issue-ping")
require.NoError(t, err)
assert.Equal(t, "issue-ping", w.DispatchAgent)
assert.Equal(t, minimalAgentContent, string(scm.files["test-org/test-repo/.fullsend/agents/triage.md"]))
assert.Contains(t, string(scm.files["test-org/test-repo/.fullsend/harness/issue-ping.yaml"]), "agent: agents/triage.md")
}

func TestDispatchSteps_RequireScenarioStart(t *testing.T) {
w := &world.World{}
require.Error(t, thenHarnessWorkflowCompletes(w, "agent"))
Expand Down
Loading
Loading