[v15.0/forgejo] fix: prevent jobs with unknown needs from running (#12077)

**Backport:** https://codeberg.org/forgejo/forgejo/pulls/12046

If Forgejo encounters an Actions workflow with unknown jobs in a needs definition, Forgejo will ignore those and run the job anyway. That is bad. For example, releases could be published without any testing because the name of the testing job was misspelt.

Workflow that demonstrates the problem:

```yaml
on:
  push:
  workflow_dispatch:
jobs:
  build:
    runs-on: debian
    steps:
      - run: |
          echo "OK"
  test:
    runs-on: debian
    needs: [does-not-exist]
    steps:
      - run: |
          echo "OK"
```

Now, before a workflow is run, Forgejo will check whether all jobs referenced in `needs` exist. If any of them does not, it raises a pre-execution error which fails the workflow immediately. It also displays an appropriate error to the user, for example:

```
Workflow was not executed due to an error that blocked the execution attempt.
Job with ID test references unknown jobs in `needs`: does-not-exist.
```

Futhermore, workflows with pre-execution errors can no longer be rerun, which was previously possible.

Original issue: https://code.forgejo.org/forgejo/runner/issues/977.

## Checklist

The [contributor guide](https://forgejo.org/docs/next/contributor/) contains information that will be helpful to first time contributors. All work and communication must conform to Forgejo's [AI Agreement](https://codeberg.org/forgejo/governance/src/branch/main/AIAgreement.md). There also are a few [conditions for merging Pull Requests in Forgejo repositories](https://codeberg.org/forgejo/governance/src/branch/main/PullRequestsAgreement.md). You are also welcome to join the [Forgejo development chatroom](https://matrix.to/#/#forgejo-development:matrix.org).

### Tests for Go changes

(can be removed for JavaScript changes)

- I added test coverage for Go changes...
  - [x] in their respective `*_test.go` for unit tests.
  - [ ] in the `tests/integration` directory if it involves interactions with a live Forgejo server.
- I ran...
  - [x] `make pr-go` before pushing

### Tests for JavaScript changes

(can be removed for Go changes)

- I added test coverage for JavaScript changes...
  - [ ] in `web_src/js/*.test.js` if it can be unit tested.
  - [ ] in `tests/e2e/*.test.e2e.js` if it requires interactions with a live Forgejo server (see also the [developer guide for JavaScript testing](https://codeberg.org/forgejo/forgejo/src/branch/forgejo/tests/e2e/README.md#end-to-end-tests)).

### Documentation

- [ ] I created a pull request [to the documentation](https://codeberg.org/forgejo/docs) to explain to Forgejo users how to use this change.
- [ ] I did not document these changes and I do not expect someone else to do it.

### Release notes

- [x] This change will be noticed by a Forgejo user or admin (feature, bug fix, performance, etc.). I suggest to include a release note for this change.
- [ ] This change is not visible to a Forgejo user or admin (refactor, dependency upgrade, etc.). I think there is no need to add a release note for this change.

*The decision if the pull request will be shown in the release notes is up to the mergers / release team.*

The content of the `release-notes/<pull request number>.md` file will serve as the basis for the release notes. If the file does not exist, the title of the pull request will be used instead.

Co-authored-by: Andreas Ahlenstorf <andreas@ahlenstorf.ch>
Reviewed-on: https://codeberg.org/forgejo/forgejo/pulls/12077
Reviewed-by: Mathieu Fenniak <mfenniak@noreply.codeberg.org>
Co-authored-by: forgejo-backport-action <forgejo-backport-action@noreply.codeberg.org>
Co-committed-by: forgejo-backport-action <forgejo-backport-action@noreply.codeberg.org>
This commit is contained in:
forgejo-backport-action 2026-04-10 18:22:49 +02:00 committed by Mathieu Fenniak
parent f777d93ebd
commit 3f65795f4d
18 changed files with 478 additions and 23 deletions

View file

@ -30,6 +30,7 @@ const (
ErrorCodeIncompleteWithMissingOutput
ErrorCodeIncompleteWithMissingMatrixDimension
ErrorCodeIncompleteWithUnknownCause
ErrorCodeUnknownJobInNeeds
)
func TranslatePreExecutionError(lang translation.Locale, run *ActionRun) string {
@ -69,6 +70,8 @@ func TranslatePreExecutionError(lang translation.Locale, run *ActionRun) string
return lang.TrString("actions.workflow.incomplete_with_missing_matrix_dimension", run.PreExecutionErrorDetails...)
case ErrorCodeIncompleteWithUnknownCause:
return lang.TrString("actions.workflow.incomplete_with_unknown_cause", run.PreExecutionErrorDetails...)
case ErrorCodeUnknownJobInNeeds:
return lang.TrString("actions.workflow.unknown_job_in_needs", run.PreExecutionErrorDetails...)
}
return fmt.Sprintf("<unsupported error: code=%v details=%#v", run.PreExecutionErrorCode, run.PreExecutionErrorDetails)
}

View file

@ -255,6 +255,19 @@ func (run *ActionRun) IsDispatchedRun() bool {
return run.TriggerEvent == "workflow_dispatch"
}
// IsRunnable indicates whether this ActionRun can generally be run.
func (run *ActionRun) IsRunnable() bool {
return run.PreExecutionErrorCode == 0 && run.PreExecutionError == ""
}
// CanBeRerun indicates whether this ActionRun can be rerun.
func (run *ActionRun) CanBeRerun() bool {
if !run.IsRunnable() {
return false
}
return run.Status.IsDone()
}
func actionsCountOpenCacheKey(repoID int64) string {
return fmt.Sprintf("Actions:CountOpenActionRuns:%d", repoID)
}

View file

@ -140,6 +140,15 @@ func (job *ActionRunJob) PrepareNextAttempt(initialStatus Status) error {
return nil
}
// CanBeRerun answers whether this ActionRunJob can be rerun. Returns true if it is done and the Run it belongs to
// is runnable. Returns false in all other cases, including when Run is nil.
func (job *ActionRunJob) CanBeRerun() bool {
if job.Run == nil || !job.Run.IsRunnable() {
return false
}
return job.Status.IsDone()
}
func GetRunJobByID(ctx context.Context, id int64) (*ActionRunJob, error) {
var job ActionRunJob
has, err := db.GetEngine(ctx).Where("id=?", id).Get(&job)
@ -338,3 +347,17 @@ func (job *ActionRunJob) EnableOpenIDConnect() (bool, error) {
}
return jobWorkflow.EnableOpenIDConnect, nil
}
// AllNeedsExist checks whether this ActionRunJob's Needs can theoretically be met by comparing them with the supplied
// list of all job IDs that part of a particular workflow run. Returns the list of unknown job IDs found in Needs
// alongside an indicator whether the check was successful.
func (job *ActionRunJob) AllNeedsExist(allExistingJobIDs container.Set[string]) ([]string, bool) {
unknownJobIDs := []string{}
for _, need := range job.Needs {
if !allExistingJobIDs.Contains(need) {
unknownJobIDs = append(unknownJobIDs, need)
}
}
return unknownJobIDs, len(unknownJobIDs) == 0
}

View file

@ -22,6 +22,14 @@ func (jobs ActionJobList) GetRunIDs() []int64 {
})
}
func (jobs ActionJobList) GetJobIDs() container.Set[string] {
jobIDs := container.SetOf[string]()
for _, job := range jobs {
jobIDs.Add(job.JobID)
}
return jobIDs
}
func (jobs ActionJobList) LoadRuns(ctx context.Context, withRepo bool) error {
runIDs := jobs.GetRunIDs()
runs := make(map[int64]*ActionRun, len(runIDs))

View file

@ -0,0 +1,21 @@
// Copyright 2026 The Forgejo Authors. All rights reserved.
// SPDX-License-Identifier: GPL-3.0-or-later
package actions
import (
"testing"
"forgejo.org/modules/container"
"github.com/stretchr/testify/assert"
)
func TestActionJobList_GetJobIDs(t *testing.T) {
jobs := ActionJobList{
&ActionRunJob{JobID: "job 1"},
&ActionRunJob{JobID: "job 2"},
}
assert.Equal(t, container.SetOf("job 2", "job 1"), jobs.GetJobIDs())
}

View file

@ -8,6 +8,7 @@ import (
"forgejo.org/models/db"
"forgejo.org/models/unittest"
"forgejo.org/modules/container"
"forgejo.org/modules/timeutil"
"code.forgejo.org/forgejo/runner/v12/act/jobparser"
@ -369,3 +370,126 @@ func TestIsRequestedByRunner(t *testing.T) {
assert.False(t, emptyHandleJob.IsRequestedByRunner(&differentHandle))
}
func TestAllNeedsExist(t *testing.T) {
testCases := []struct {
name string
job ActionRunJob
existingJobIDs container.Set[string]
expectedUnknownIDs []string
ok bool
}{
{
name: "no needs",
job: ActionRunJob{Needs: nil},
existingJobIDs: container.Set[string]{},
expectedUnknownIDs: []string{},
ok: true,
},
{
name: "empty needs",
job: ActionRunJob{Needs: []string{}},
existingJobIDs: container.Set[string]{},
expectedUnknownIDs: []string{},
ok: true,
},
{
name: "satisfied needs",
job: ActionRunJob{Needs: []string{"job1", "job2"}},
existingJobIDs: container.SetOf("job2", "job1"),
expectedUnknownIDs: []string{},
ok: true,
},
{
name: "unsatisfied needs",
job: ActionRunJob{Needs: []string{"unknown", "job2"}},
existingJobIDs: container.SetOf("job2", "job1"),
expectedUnknownIDs: []string{"unknown"},
ok: false,
},
{
name: "comparison is case-sensitive",
job: ActionRunJob{Needs: []string{"Job1", "job2"}},
existingJobIDs: container.SetOf("job2", "job1"),
expectedUnknownIDs: []string{"Job1"},
ok: false,
},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
unknownIDs, ok := testCase.job.AllNeedsExist(testCase.existingJobIDs)
assert.Equal(t, testCase.ok, ok)
assert.Equal(t, testCase.expectedUnknownIDs, unknownIDs)
})
}
}
func TestActionRunJob_CanBeRerun(t *testing.T) {
testCases := []struct {
name string
job ActionRunJob
canBeRerun bool
}{
{
name: "job with unknown status",
job: ActionRunJob{Run: &ActionRun{Status: StatusSuccess}, Status: StatusUnknown},
canBeRerun: false,
},
{
name: "successful job",
job: ActionRunJob{Run: &ActionRun{Status: StatusSuccess}, Status: StatusSuccess},
canBeRerun: true,
},
{
name: "failed job",
job: ActionRunJob{Run: &ActionRun{Status: StatusSuccess}, Status: StatusFailure},
canBeRerun: true,
},
{
name: "cancelled job",
job: ActionRunJob{Run: &ActionRun{Status: StatusSuccess}, Status: StatusCancelled},
canBeRerun: true,
},
{
name: "skipped job",
job: ActionRunJob{Run: &ActionRun{Status: StatusSuccess}, Status: StatusSkipped},
canBeRerun: true,
},
{
name: "waiting job",
job: ActionRunJob{Run: &ActionRun{Status: StatusSuccess}, Status: StatusWaiting},
canBeRerun: false,
},
{
name: "blocked job",
job: ActionRunJob{Run: &ActionRun{Status: StatusSuccess}, Status: StatusBlocked},
canBeRerun: false,
},
{
name: "ActionRun is nil",
job: ActionRunJob{Run: nil, Status: StatusSuccess},
canBeRerun: false,
},
{
name: "with busy run but completed job",
job: ActionRunJob{Run: &ActionRun{Status: StatusRunning}, Status: StatusSuccess},
canBeRerun: true,
},
{
name: "with run that cannot be run",
job: ActionRunJob{
Run: &ActionRun{Status: StatusRunning, PreExecutionErrorCode: ErrorCodeEventDetectionError},
Status: StatusSuccess,
},
canBeRerun: false,
},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
assert.Equal(t, testCase.canBeRerun, testCase.job.CanBeRerun())
})
}
}

View file

@ -96,6 +96,86 @@ func TestIsManualRun(t *testing.T) {
assert.False(t, pushRun.IsDispatchedRun())
}
func TestActionRun_IsRunnable(t *testing.T) {
testCases := []struct {
name string
run ActionRun
isRunnable bool
}{
{
name: "valid run",
run: ActionRun{},
isRunnable: true,
},
{
name: "with pre-execution error",
run: ActionRun{PreExecutionErrorCode: ErrorCodeIncompleteRunsOnMissingOutput},
isRunnable: false,
},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
assert.Equal(t, testCase.isRunnable, testCase.run.IsRunnable())
})
}
}
func TestActionRun_CanBeRerun(t *testing.T) {
testCases := []struct {
name string
run ActionRun
canBeRerun bool
}{
{
name: "run with unknown status",
run: ActionRun{Status: StatusUnknown},
canBeRerun: false,
},
{
name: "successful run",
run: ActionRun{Status: StatusSuccess},
canBeRerun: true,
},
{
name: "failed run",
run: ActionRun{Status: StatusFailure},
canBeRerun: true,
},
{
name: "cancelled run",
run: ActionRun{Status: StatusCancelled},
canBeRerun: true,
},
{
name: "skipped run",
run: ActionRun{Status: StatusSkipped},
canBeRerun: true,
},
{
name: "waiting run",
run: ActionRun{Status: StatusWaiting},
canBeRerun: false,
},
{
name: "blocked run",
run: ActionRun{Status: StatusBlocked},
canBeRerun: false,
},
{
name: "with pre-execution error",
run: ActionRun{PreExecutionErrorCode: ErrorCodeIncompleteRunsOnMissingOutput, Status: StatusSuccess},
canBeRerun: false,
},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
assert.Equal(t, testCase.canBeRerun, testCase.run.CanBeRerun())
})
}
}
func TestRepoNumOpenActions(t *testing.T) {
require.NoError(t, unittest.PrepareTestDatabase())
err := cache.Init()

View file

@ -547,7 +547,10 @@
"actions.workflow.incomplete_with_missing_output": "Unable to evaluate `with` of job %[1]s: job %[2]s is missing output %[3]s.",
"actions.workflow.incomplete_with_missing_matrix_dimension": "Unable to evaluate `with` of job %[1]s: matrix dimension %[2]s does not exist.",
"actions.workflow.incomplete_with_unknown_cause": "Unable to evaluate `with` of job %[1]s: unknown error.",
"actions.workflow.unknown_job_in_needs": "Job with ID %[1]s references unknown jobs in `needs`: %[2]s.",
"actions.workflow.pre_execution_error": "Workflow was not executed due to an error that blocked the execution attempt.",
"actions.workflow.rerun_impossible": "The workflow cannot be rerun.",
"actions.workflow.job_rerun_impossible": "The job cannot be rerun.",
"actions.secrets.creation.name_description": "The name of a secret can only contain letters, numbers, and underscores. It cannot start with FORGEJO_, GITEA_, GITHUB_, or a number. Forgejo will automatically convert it to uppercase.",
"actions.secrets.creation.value_description": "The value of a secret can be any text. Special characters are retained. CRLF (Windows-style line breaks) is automatically converted to LF. Encode the value with Base64 if linebreaks should be retained.",
"actions.variables.mutation.name_description": "The name of a variable can only contain letters, numbers, and underscores. It cannot be named CI or start with FORGEJO_, GITEA_, GITHUB_, or a number. Forgejo will automatically convert it to uppercase.",

View file

@ -16,4 +16,24 @@
updated: 1683636626
need_approval: false
approved_by: 0
event_payload: '{"head_commit":{"id":"5f22f7d0d95d614d25a5b68592adb345a4b5c7fd"}}'
- id: 83732
title: "not runnable"
repo_id: 1
owner_id: 5
workflow_id: "invalid.yaml"
index: 138575
trigger_user_id: 1
ref: "refs/heads/branch2"
commit_sha: "985f0301dba5e7b34be866819cd15ad3d8f508ee"
event: "push"
is_fork_pull_request: false
status: 2 # failure
started: 0
stopped: 1683636626
created: 1683636108
updated: 1683636626
pre_execution_error_code: 10
need_approval: false
approved_by: 0
event_payload: '{"head_commit":{"id":"5f22f7d0d95d614d25a5b68592adb345a4b5c7fd"}}'

View file

@ -56,3 +56,18 @@
runs_on: '["fedora"]'
started: 1683636528
stopped: 1683636626
- id: 248954
run_id: 83732
repo_id: 1
owner_id: 3
commit_sha: 985f0301dba5e7b34be866819cd15ad3d8f508ee
is_fork_pull_request: false
name: job_2
attempt: 1
job_id: job_2
task_id: 47
status: 2 # failure
runs_on: '["fedora"]'
started: 1683636528
stopped: 1683636626

View file

@ -296,7 +296,7 @@ func getViewResponse(ctx *app_context.Context, req *ViewRequest, runIndex, jobIn
resp.State.Run.TitleHTML = templates.RenderCommitMessage(ctx, run.Title, metas)
resp.State.Run.Link = run.Link()
resp.State.Run.CanApprove = run.NeedApproval && ctx.Repo.CanWrite(unit.TypeActions)
resp.State.Run.CanRerun = run.Status.IsDone() && ctx.Repo.CanWrite(unit.TypeActions)
resp.State.Run.CanRerun = run.CanBeRerun() && ctx.Repo.CanWrite(unit.TypeActions)
resp.State.Run.CanDeleteArtifact = run.Status.IsDone() && ctx.Repo.CanWrite(unit.TypeActions)
resp.State.Run.Jobs = make([]*ViewJob, 0, len(jobs)) // marshal to '[]' instead of 'null' in json
resp.State.Run.Status = run.Status.String()
@ -318,7 +318,7 @@ func getViewResponse(ctx *app_context.Context, req *ViewRequest, runIndex, jobIn
ID: v.ID,
Name: v.Name,
Status: v.Status.String(),
CanRerun: v.Status.IsDone() && ctx.Repo.CanWrite(unit.TypeActions),
CanRerun: v.CanBeRerun() && ctx.Repo.CanWrite(unit.TypeActions),
Duration: v.Duration().String(),
})
}
@ -495,6 +495,10 @@ func Rerun(ctx *app_context.Context) {
ctx.Error(http.StatusInternalServerError, err.Error())
return
}
if jobIndexStr == "" && !run.CanBeRerun() {
ctx.JSONError(ctx.Locale.Tr("actions.workflow.rerun_impossible"))
return
}
// can not rerun job when workflow is disabled
cfgUnit := ctx.Repo.Repository.MustGetUnit(ctx, unit.TypeActions)
@ -523,6 +527,11 @@ func Rerun(ctx *app_context.Context) {
if jobIndexStr == "" { // rerun all jobs
var redirectURL string
for _, j := range jobs {
if !j.CanBeRerun() {
ctx.JSONError(ctx.Locale.Tr("actions.workflow.job_rerun_impossible"))
return
}
// if the job has needs, it should be set to "blocked" status to wait for other jobs
shouldBlock := len(j.Needs) > 0
if err := rerunJob(ctx, j, shouldBlock); err != nil {
@ -550,6 +559,11 @@ func Rerun(ctx *app_context.Context) {
var redirectURL string
for _, j := range rerunJobs {
if !j.CanBeRerun() {
ctx.JSONError(ctx.Locale.Tr("actions.workflow.job_rerun_impossible"))
return
}
// jobs other than the specified one should be set to "blocked" status
shouldBlock := j.JobID != job.JobID
if err := rerunJob(ctx, j, shouldBlock); err != nil {

View file

@ -520,31 +520,48 @@ func TestActionsViewRedirectToLatestAttempt(t *testing.T) {
}
func TestActionsRerun(t *testing.T) {
defer unittest.OverrideFixtures("routers/web/repo/actions/TestActionsRerun")()
unittest.PrepareTestEnv(t)
tests := []struct {
name string
runIndex int64
jobIndex int64
expectedCode int
expectedURL string
expectedBody string
}{
{
name: "rerun all",
runIndex: 138574,
jobIndex: -1,
expectedURL: "https://try.gitea.io/user2/repo1/actions/runs/138574/jobs/0/attempt/3",
name: "rerun all",
runIndex: 138574,
jobIndex: -1,
expectedCode: 200,
expectedURL: "https://try.gitea.io/user2/repo1/actions/runs/138574/jobs/0/attempt/3",
},
{
name: "rerun job",
runIndex: 138574,
jobIndex: 2,
expectedURL: "https://try.gitea.io/user2/repo1/actions/runs/138574/jobs/2/attempt/6",
name: "rerun job",
runIndex: 138574,
jobIndex: 2,
expectedCode: 200,
expectedURL: "https://try.gitea.io/user2/repo1/actions/runs/138574/jobs/2/attempt/6",
},
{
name: "rerun workflow that cannot be run",
runIndex: 138575,
jobIndex: -1,
expectedCode: 400,
expectedBody: "{\"errorMessage\":\"actions.workflow.rerun_impossible\",\"renderFormat\":\"html\"}\n",
},
{
name: "rerun job that cannot be run",
runIndex: 138575,
jobIndex: 1,
expectedCode: 400,
expectedBody: "{\"errorMessage\":\"actions.workflow.job_rerun_impossible\",\"renderFormat\":\"html\"}\n",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
defer unittest.OverrideFixtures("routers/web/repo/actions/TestActionsRerun")()
unittest.PrepareTestEnv(t)
ctx, resp := contexttest.MockContext(t, "user2/repo1/actions/runs/138574/rerun")
contexttest.LoadUser(t, ctx, 2)
contexttest.LoadRepo(t, ctx, 1)
@ -554,16 +571,22 @@ func TestActionsRerun(t *testing.T) {
}
Rerun(ctx)
require.Equal(t, http.StatusOK, resp.Result().StatusCode, "failure in Rerun(): %q", resp.Body.String())
var actual redirectObject
err := json.Unmarshal(resp.Body.Bytes(), &actual)
require.NoError(t, err)
if tt.expectedCode < 300 {
require.Equal(t, tt.expectedCode, resp.Result().StatusCode, "failure in Rerun(): %q", resp.Body.String())
// Note: this test isn't doing any functional testing of the Rerun handler's actual ability to set up a job
// rerun. This test was added when the redirect to the correct `attempt` was added and only covers that
// addition at this time.
assert.Equal(t, redirectObject{Redirect: tt.expectedURL}, actual)
var actual redirectObject
err := json.Unmarshal(resp.Body.Bytes(), &actual)
require.NoError(t, err)
// Note: this test isn't doing any functional testing of the Rerun handler's actual ability to set up a job
// rerun. This test was added when the redirect to the correct `attempt` was added and only covers that
// addition at this time.
assert.Equal(t, redirectObject{Redirect: tt.expectedURL}, actual)
} else {
require.Equal(t, tt.expectedCode, resp.Result().StatusCode)
assert.Equal(t, tt.expectedBody, resp.Body.String())
}
})
}
}

View file

@ -88,3 +88,21 @@
updated: 1683636626
need_approval: 0
approved_by: 0
-
id: 905
title: "waiting workflow_dispatch run"
repo_id: 63
owner_id: 2
workflow_id: "running.yaml"
index: 9
trigger_user_id: 2
ref: "refs/heads/main"
commit_sha: "97f29ee599c373c729132a5c46a046978311e0ee"
trigger_event: "workflow_dispatch"
is_fork_pull_request: 0
status: 5 # waiting
started: 1683636528
created: 1683636108
updated: 1683636626
need_approval: 0
approved_by: 0

View file

@ -172,3 +172,47 @@
incomplete_runs_on_matrix:
dimension: platform-oops-wrong-dimension
incomplete_matrix: true
-
id: 607
run_id: 905
repo_id: 63
owner_id: 2
commit_sha: 97f29ee599c373c729132a5c46a046978311e0ee
is_fork_pull_request: 0
name: job_1
attempt: 1
job_id: job_1
task_id: 0
status: 7 # blocked
runs_on: '["fedora"]'
needs: '[]'
workflow_payload: |
"on":
push:
jobs:
job_1:
runs-on: fedora
steps:
- run: echo "OK!"
-
id: 608
run_id: 905
repo_id: 63
owner_id: 2
commit_sha: 97f29ee599c373c729132a5c46a046978311e0ee
is_fork_pull_request: 0
name: job_2
attempt: 1
job_id: job_2
task_id: 0
status: 7 # blocked
runs_on: '["fedora"]'
needs: '["unknown","Job_1"]' # invalid capitalization of job_1
workflow_payload: |
"on":
push:
jobs:
job_2:
runs-on: fedora
steps:
- run: echo "OK!"

View file

@ -136,6 +136,10 @@ type jobStatusResolver struct {
jobMap map[int64]*actions_model.ActionRunJob
}
// unknownJobID stores the ID of an unknown job that might be referenced in the workflow. The ID can be any number as
// long it does not match the ID of an existing job.
var unknownJobID int64 = -1
func newJobStatusResolver(jobs actions_model.ActionJobList) *jobStatusResolver {
idToJobs := make(map[string][]*actions_model.ActionRunJob, len(jobs))
jobMap := make(map[int64]*actions_model.ActionRunJob)
@ -149,8 +153,14 @@ func newJobStatusResolver(jobs actions_model.ActionJobList) *jobStatusResolver {
for _, job := range jobs {
statuses[job.ID] = job.Status
for _, need := range job.Needs {
for _, v := range idToJobs[need] {
needs[job.ID] = append(needs[job.ID], v.ID)
neededJobs, ok := idToJobs[need]
if ok {
for _, v := range neededJobs {
needs[job.ID] = append(needs[job.ID], v.ID)
}
} else {
// Handles the case of an unknown job being referenced in `needs`, for example, `needs: ["unknown"]`.
needs[job.ID] = append(needs[job.ID], unknownJobID)
}
}
}

View file

@ -231,6 +231,30 @@ __metadata:
3: actions_model.StatusFailure,
},
},
{
name: "blocked if needs are unknown",
jobs: actions_model.ActionJobList{
{ID: 1, JobID: "build", Status: actions_model.StatusSuccess, Needs: []string{}},
{ID: 2, JobID: "test", Status: actions_model.StatusBlocked, Needs: []string{"build", "unknown"}},
},
want: map[int64]actions_model.Status{},
},
{
name: "blocked if needs are unknown despite always()",
jobs: actions_model.ActionJobList{
{ID: 1, JobID: "build", Status: actions_model.StatusSuccess, Needs: []string{}},
{ID: 45, JobID: "test", Needs: []string{"build", "unknown"}, Status: actions_model.StatusBlocked, WorkflowPayload: []byte(`
on: push
jobs:
test:
runs-on: ubuntu-latest
needs: [build, unknown]
if: always()
steps: []
`)},
},
want: map[int64]actions_model.Status{},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {

View file

@ -97,11 +97,17 @@ func FailRunPreExecutionError(ctx context.Context, run *actions_model.ActionRun,
// Perform pre-execution checks that would affect the ability for a job to reach an executing stage.
func consistencyCheckRun(ctx context.Context, run *actions_model.ActionRun) error {
var jobs actions_model.ActionJobList
jobs, err := actions_model.GetRunJobsByRunID(ctx, run.ID)
if err != nil {
return err
}
validJobIDs := jobs.GetJobIDs()
for _, job := range jobs {
if unknownJobIDs, ok := job.AllNeedsExist(validJobIDs); !ok {
return FailRunPreExecutionError(ctx, run, actions_model.ErrorCodeUnknownJobInNeeds,
[]any{job.JobID, strings.Join(unknownJobIDs, ", ")})
}
if stop, err := checkJobWillRevisit(ctx, job); err != nil {
return err
} else if stop {

View file

@ -137,6 +137,12 @@ func TestActions_consistencyCheckRun(t *testing.T) {
name: "consistent: matrix missing dimension but matrix is dynamic",
runID: 904,
},
{
name: "unknown job in needs",
runID: 905,
preExecutionError: actions_model.ErrorCodeUnknownJobInNeeds,
preExecutionErrorDetails: []any{"job_2", "unknown, Job_1"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {