fix(actions): pick waiting jobs in run order (#40441)

Runners picked the waiting job that became ready first, so a job
released by `needs` queued again behind jobs of newer runs, and a run
with several stages waited out the backlog once per stage. Runners now
pick waiting jobs in the order their runs were triggered, then by job
id, so a run keeps its place across its stages, including reusable
workflow children and dynamic matrix jobs created once their `needs`
finish. A rerun is a new trigger and queues behind. Under load, a new
push waits longer for its first job, and jobs released late by approval
or a concurrency group go ahead of newer runs. The job queue page lists
jobs in the same order, and the `pickup` index becomes `(task_id,
status, run_attempt_id, id)` to serve it.

Fixes: https://github.com/go-gitea/gitea/issues/40430
Assisted-by: Claude Code:claude-opus-5-5

---------

Co-authored-by: silverwind <me@silverwind.io>
Co-authored-by: Zettat123 <zettat123@gmail.com>
This commit is contained in:
authored and GitHub committed 2026-12-01 04:29:31 +00:00
1 parent d25a2dcaf8
commit 3ad403dc09
5 files changed
+40 -31

No files matched your search

+11 -3
View File
@@ -21,6 +21,7 @@ import (
webhook_module "gitea.dev/modules/webhook"
"xorm.io/builder"
"xorm.io/xorm/schemas"
)
// MaxJobNumPerRun is the maximum number of jobs in a single run.
@@ -51,10 +52,10 @@ type ActionRunJob struct {
Needs []string `xorm:"JSON TEXT"`
RunsOn []string `xorm:"JSON TEXT"`
TaskID int64 `xorm:"index(pickup)"` // the task created by this job in its own attempt
TaskID int64 // the task created by this job in its own attempt
SourceTaskID int64 `xorm:"NOT NULL DEFAULT 0"` // SourceTaskID points to a historical task when this job reuses an earlier attempt's result.
Status Status `xorm:"index index(pickup) index(repo_status)"`
Status Status `xorm:"index index(repo_status)"`
RawConcurrency string `xorm:"TEXT"` // raw concurrency from job YAML's "concurrency" section
@@ -132,7 +133,14 @@ type ActionRunJob struct {
Started timeutil.TimeStamp
Stopped timeutil.TimeStamp
Created timeutil.TimeStamp `xorm:"created"`
Updated timeutil.TimeStamp `xorm:"updated index index(pickup)"`
Updated timeutil.TimeStamp `xorm:"updated index"`
}
// TableIndices declares pickup for CreateTaskForRunner, struct tags would order its columns by field and put id first.
func (*ActionRunJob) TableIndices() []*schemas.Index {
pickupIndex := schemas.NewIndex("pickup", schemas.IndexType)
pickupIndex.AddColumn("task_id", "status", "run_attempt_id", "id")
return []*schemas.Index{pickupIndex}
}
// ActionRunAttemptJobIDIndex backs the run-wide AttemptJobID counter, keyed by ActionRun.ID.
+10 -9
View File
@@ -70,19 +70,20 @@ func TestFindJobQueueJobs(t *testing.T) {
ctx := t.Context()
const repoID int64 = 987654
insert := func(status Status, taskID int64, reusable bool, updated timeutil.TimeStamp) int64 {
job := &ActionRunJob{RepoID: repoID, Status: status, TaskID: taskID, IsReusableCaller: reusable, Updated: updated}
insert := func(status Status, taskID int64, reusable bool, runAttemptID int64, updated timeutil.TimeStamp) int64 {
job := &ActionRunJob{RepoID: repoID, Status: status, TaskID: taskID, IsReusableCaller: reusable, RunAttemptID: runAttemptID, Updated: updated}
_, err := db.GetEngine(ctx).NoAutoTime().Insert(job)
require.NoError(t, err)
return job.ID
}
queuedA := insert(StatusWaiting, 0, false, 200)
queuedB := insert(StatusWaiting, 0, false, 300)
queuedC := insert(StatusWaiting, 0, false, 100)
running := insert(StatusRunning, 998, false, 0)
cancelling := insert(StatusCancelling, 999, false, 0)
insert(StatusWaiting, 999, false, 0)
insert(StatusWaiting, 0, true, 0)
// id, updated and attempt order all differ, so only the attempt order passes
queuedA := insert(StatusWaiting, 0, false, 2, 100)
queuedB := insert(StatusWaiting, 0, false, 2, 300)
queuedC := insert(StatusWaiting, 0, false, 1, 200)
running := insert(StatusRunning, 998, false, 0, 0)
cancelling := insert(StatusCancelling, 999, false, 0, 0)
insert(StatusWaiting, 999, false, 0, 0)
insert(StatusWaiting, 0, true, 0, 0)
find := func(status Status, page, pageSize int) (ids []int64, total int64) {
jobs, total, err := FindJobQueueJobs(ctx, JobQueueOptions{RepoID: repoID, Status: status}, page, pageSize)
+1 -1
View File
@@ -51,7 +51,7 @@ func (opts JobQueueOptions) statusCond() builder.Cond {
// active jobs first by start time, then queued jobs in pickup order
var jobQueueOrderBy = fmt.Sprintf(
"CASE WHEN `action_run_job`.status IN (%d, %d) THEN 0 ELSE 1 END ASC, CASE WHEN `action_run_job`.status IN (%d, %d) THEN `action_run_job`.started ELSE `action_run_job`.updated END ASC, `action_run_job`.id ASC",
"CASE WHEN `action_run_job`.status IN (%d, %d) THEN 0 ELSE 1 END ASC, CASE WHEN `action_run_job`.status IN (%d, %d) THEN `action_run_job`.started ELSE 0 END ASC, `action_run_job`.run_attempt_id ASC, `action_run_job`.id ASC",
StatusRunning, StatusCancelling, StatusRunning, StatusCancelling)
// FindJobQueueJobs returns one page of the job queue and its total count.
+9 -18
View File
@@ -240,30 +240,18 @@ func CreateTaskForRunner(ctx context.Context, runner *ActionRunner) (task *Actio
// TODO: a more efficient way to filter labels
log.Trace("runner labels: %v", runner.AgentLabels)
// Page through the waiting jobs oldest-first instead of loading the whole backlog into memory on every poll.
// Keyset pagination on (updated, id) is safe under concurrent claims:
// updated only moves forward, so the advancing cursor never skips a still-waiting job even as claimed jobs drop out.
var cursorUpdated timeutil.TimeStamp
var cursorID int64
// Page through the waiting jobs in run attempt order, so jobs inserted once their parent got ready keep their run's place.
// A job that turns waiting behind the cursor bumps the tasks version so the next poll finds it.
var cursorAttemptID, cursorID int64
for {
sess := JobQueueOptions{RepoID: runner.RepoID, OwnerID: runner.OwnerID, Status: StatusWaiting}.session(ctx)
if cursorID > 0 {
sess.And(builder.Or(
builder.Gt{"updated": cursorUpdated},
builder.And(builder.Eq{"updated": cursorUpdated}, builder.Gt{"id": cursorID}),
))
sess.And(builder.Gte{"run_attempt_id": cursorAttemptID}, builder.Or(builder.Gt{"run_attempt_id": cursorAttemptID}, builder.Gt{"id": cursorID}))
}
var jobs []*ActionRunJob
if err := sess.Asc("updated", "id").Limit(pickTaskBatchSize).Find(&jobs); err != nil {
if err := sess.Asc("run_attempt_id", "id").Limit(pickTaskBatchSize).Find(&jobs); err != nil {
return nil, cancelledJobs, err
}
// A short page means no waiting jobs remain beyond it.
isLastPage := len(jobs) < pickTaskBatchSize
if !isLastPage {
last := jobs[len(jobs)-1] // read before a lost claim bumps Updated
cursorUpdated, cursorID = last.Updated, last.ID
}
for _, v := range jobs {
if !runner.CanMatchLabels(v.RunsOn) {
@@ -279,9 +267,12 @@ func CreateTaskForRunner(ctx context.Context, runner *ActionRunner) (task *Actio
// Another runner claimed this job concurrently, or it was cancelled. Try the next one.
}
if isLastPage {
// A short page means no waiting jobs remain beyond it.
if len(jobs) < pickTaskBatchSize {
return nil, cancelledJobs, nil
}
last := jobs[len(jobs)-1]
cursorAttemptID, cursorID = last.RunAttemptID, last.ID
}
}
+9
View File
@@ -318,10 +318,16 @@ func TestReleaseTaskForRunner(t *testing.T) {
}
}
attempt := &ActionRunAttempt{RepoID: run.RepoID, RunID: run.ID, Attempt: 1, TriggerUserID: 2, Status: StatusWaiting}
require.NoError(t, db.Insert(t.Context(), attempt))
newerAttemptCreatedEarlier := &ActionRunJob{RunID: run.ID, RepoID: run.RepoID, OwnerID: run.OwnerID, RunAttemptID: attempt.ID + 1, Status: StatusWaiting, RunsOn: []string{"ubuntu-latest"}}
require.NoError(t, db.Insert(t.Context(), newerAttemptCreatedEarlier))
job := &ActionRunJob{
RunID: run.ID,
RepoID: run.RepoID,
OwnerID: run.OwnerID,
RunAttemptID: attempt.ID,
CommitSHA: run.CommitSHA,
Name: tt.jobName,
Attempt: 1,
@@ -331,6 +337,9 @@ func TestReleaseTaskForRunner(t *testing.T) {
WorkflowPayload: []byte("on: push\njobs:\n " + tt.jobName + ":\n runs-on: ubuntu-latest\n steps:\n - run: echo hi\n"),
}
require.NoError(t, db.Insert(t.Context(), job))
readyEarlierCreatedLater := &ActionRunJob{RunID: run.ID, RepoID: run.RepoID, OwnerID: run.OwnerID, RunAttemptID: job.RunAttemptID, Status: StatusWaiting, RunsOn: job.RunsOn, Updated: 1}
_, err := db.GetEngine(t.Context()).NoAutoTime().Insert(readyEarlierCreatedLater)
require.NoError(t, err)
runner := &ActionRunner{
UUID: tt.name + "-runner-uuid",