From 579c972e5458fd04449c3492b3fd0f345260268a Mon Sep 17 00:00:00 2001 From: mintaka Date: Sat, 21 Nov 2026 09:04:17 -0500 Subject: [PATCH] fix(server): wait one tick before the first queued-workflow reaper pass (RIG-11227) The orphan reaper ran once at server startup, before agents had reconnected, and could finalize workflows that were still alive. The inline loop becomes runOrphanReaper, which waits one tick before its first pass. The interval is unchanged. The finalized queued workflow log line now carries dependency_workflow_id, the dependency that blocked the workflow. Ported from RigelBuild/woodpecker#181. Co-authored-by: Matt Wilkinson --- .../cmd/server/orphan_reaper_test.go | 52 +++++++++ forks/woodpecker/cmd/server/server.go | 30 ++++-- .../server/pipeline/pending_timeout.go | 14 +++ .../server/pipeline/pending_timeout_test.go | 102 ++++++++++++++++++ 4 files changed, 187 insertions(+), 11 deletions(-) create mode 100644 forks/woodpecker/cmd/server/orphan_reaper_test.go create mode 100644 forks/woodpecker/server/pipeline/pending_timeout_test.go diff --git a/forks/woodpecker/cmd/server/orphan_reaper_test.go b/forks/woodpecker/cmd/server/orphan_reaper_test.go new file mode 100644 index 000000000..25daa8f05 --- /dev/null +++ b/forks/woodpecker/cmd/server/orphan_reaper_test.go @@ -0,0 +1,52 @@ +// Copyright 2026 Woodpecker Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package main + +import ( + "context" + "testing" + "testing/synctest" + "time" + + "github.com/stretchr/testify/assert" +) + +// A restart must not reap before one interval has passed: the first pass +// would otherwise see every workflow persisted by the previous process at once. +func TestRunOrphanReaperWaitsOneTickBeforeFirstPass(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + ctx, cancel := context.WithCancel(t.Context()) + ticks := make(chan time.Time) + passes := make(chan struct{}, 8) + done := make(chan struct{}) + go func() { + defer close(done) + runOrphanReaper(ctx, ticks, func() error { + passes <- struct{}{} + return nil + }) + }() + + synctest.Wait() + assert.Len(t, passes, 0, "reaper ran before the first tick") + + ticks <- time.Now() + synctest.Wait() + assert.Len(t, passes, 1, "one tick should run exactly one pass") + + cancel() + <-done + }) +} diff --git a/forks/woodpecker/cmd/server/server.go b/forks/woodpecker/cmd/server/server.go index 9aa22b07e..cc998d25d 100644 --- a/forks/woodpecker/cmd/server/server.go +++ b/forks/woodpecker/cmd/server/server.go @@ -86,6 +86,21 @@ var ( shutdownCtx = context.Background() ) +// runOrphanReaper runs reap once per tick until ctx ends; nothing runs before the first tick. +func runOrphanReaper(ctx context.Context, ticks <-chan time.Time, reap func() error) { + for { + select { + case <-ctx.Done(): + log.Info().Msg("orphan workflow reaper stopped") + return + case <-ticks: + } + if err := reap(); err != nil { + log.Error().Err(err).Msg("orphan workflow reaper failed") + } + } +} + func run(ctx context.Context, c *cli.Command) error { if err := logger.SetupGlobalLogger(ctx, c, true); err != nil { return err @@ -201,17 +216,10 @@ func run(ctx context.Context, c *cli.Command) error { log.Info().Msg("starting orphan workflow reaper ...") ticker := time.NewTicker(server.Config.Server.OrphanReapInterval) defer ticker.Stop() - for { - if err := pipeline.ReapOrphanedWorkflows(ctx, _store, time.Now(), server.Config.Server.OrphanReapGrace, server.Config.Server.PendingTimeout, server.Config.Server.PendingUnmatchedTimeout); err != nil { - log.Error().Err(err).Msg("orphan workflow reaper failed") - } - select { - case <-ctx.Done(): - log.Info().Msg("orphan workflow reaper stopped") - return nil - case <-ticker.C: - } - } + runOrphanReaper(ctx, ticker.C, func() error { + return pipeline.ReapOrphanedWorkflows(ctx, _store, time.Now(), server.Config.Server.OrphanReapGrace, server.Config.Server.PendingTimeout, server.Config.Server.PendingUnmatchedTimeout) + }) + return nil }) } diff --git a/forks/woodpecker/server/pipeline/pending_timeout.go b/forks/woodpecker/server/pipeline/pending_timeout.go index c6a30c94c..42f7cb631 100644 --- a/forks/woodpecker/server/pipeline/pending_timeout.go +++ b/forks/woodpecker/server/pipeline/pending_timeout.go @@ -250,6 +250,7 @@ func finalizeDeadWorkflows(ctx context.Context, storage store.Store, workflows [ if !ok || (&model.Task{RunOn: task.RunOn, DepStatus: deps}).ShouldRun() { continue } + culprit := failedDependency(task, deps) reason := "dependency-failed" if len(deleted) > 0 { reason = "dependency-deleted" @@ -267,6 +268,7 @@ func finalizeDeadWorkflows(ctx context.Context, storage store.Store, workflows [ log.Info(). Int64("workflow_id", workflow.ID). Str("reason", reason). + Str("dependency_workflow_id", culprit). Strs("labels", reasonLabels(task)). Msg("finalized queued workflow") finalized = append(finalized, workflow) @@ -276,6 +278,18 @@ func finalizeDeadWorkflows(ctx context.Context, storage store.Store, workflows [ return finalized } +// failedDependency names the first dependency that alone stops the task from running. +// It is empty when no single dependency does. +func failedDependency(task *model.Task, deps map[string]model.StatusValue) string { + for _, dep := range task.Dependencies { + alone := &model.Task{RunOn: task.RunOn, DepStatus: map[string]model.StatusValue{dep: deps[dep]}} + if !alone.ShouldRun() { + return dep + } + } + return "" +} + // deletedDependencyReason names the lowest deleted dependency ID. func deletedDependencyReason(deleted map[int64]bool) string { return fmt.Sprintf("dependency workflow %d no longer exists", slices.Min(slices.Collect(maps.Keys(deleted)))) diff --git a/forks/woodpecker/server/pipeline/pending_timeout_test.go b/forks/woodpecker/server/pipeline/pending_timeout_test.go new file mode 100644 index 000000000..1c67f2d24 --- /dev/null +++ b/forks/woodpecker/server/pipeline/pending_timeout_test.go @@ -0,0 +1,102 @@ +// Copyright 2026 Woodpecker Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package pipeline + +import ( + "bytes" + "encoding/json" + "fmt" + "testing" + + "github.com/rs/zerolog" + "github.com/rs/zerolog/log" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" + + "go.woodpecker-ci.org/woodpecker/v3/server" + "go.woodpecker-ci.org/woodpecker/v3/server/model" + scheduler_mocks "go.woodpecker-ci.org/woodpecker/v3/server/scheduler/mocks" + store_mocks "go.woodpecker-ci.org/woodpecker/v3/server/store/mocks" +) + +// A dependency-failed finalize must log the dependency that stopped the workflow. +func TestFinalizeDeadWorkflowsLogsFailedDependency(t *testing.T) { + tests := []struct { + name string + deps []int64 + states map[int64]model.StatusValue + runOn []string + culprit string + }{ + { + name: "single failed dependency", + deps: []int64{41}, + states: map[int64]model.StatusValue{41: model.StatusError}, + culprit: "41", + }, + { + name: "names the failing dependency, not the first", + deps: []int64{40, 41}, + states: map[int64]model.StatusValue{40: model.StatusSuccess, 41: model.StatusFailure}, + culprit: "41", + }, + { + name: "failure-only dependent blocked by a successful dependency", + deps: []int64{41}, + states: map[int64]model.StatusValue{41: model.StatusSuccess}, + runOn: []string{string(model.StatusFailure)}, + culprit: "41", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + var buf bytes.Buffer + prev := log.Logger + log.Logger = zerolog.New(&buf).Level(zerolog.InfoLevel) + t.Cleanup(func() { log.Logger = prev }) + + oldScheduler := server.Config.Services.Scheduler + t.Cleanup(func() { server.Config.Services.Scheduler = oldScheduler }) + schedulerMock := scheduler_mocks.NewMockScheduler(t) + server.Config.Services.Scheduler = schedulerMock + storeMock := store_mocks.NewMockStore(t) + + var deps []string + var workflows []*model.Workflow + for _, id := range tt.deps { + deps = append(deps, fmt.Sprint(id)) + workflows = append(workflows, &model.Workflow{ID: id, State: tt.states[id]}) + } + workflows = append(workflows, &model.Workflow{ID: 46, State: model.StatusPending}) + task := &model.Task{ID: "46", Dependencies: deps, RunOn: tt.runOn} + + storeMock.On("WorkflowUpdateIfState", mock.Anything, model.StatusPending, mock.Anything).Return(nil).Once() + schedulerMock.On("CancelWorkflows", mock.Anything, []string{"46"}).Return(nil).Once() + + finalized := finalizeDeadWorkflows(t.Context(), storeMock, workflows, map[string]*model.Task{"46": task}, 1_700_000_000, map[int64]*model.Workflow{}) + require.Len(t, finalized, 1) + + var line map[string]any + require.NoError(t, json.Unmarshal(buf.Bytes(), &line), buf.String()) + assert.Equal(t, "finalized queued workflow", line["message"]) + assert.Equal(t, "dependency-failed", line["reason"]) + assert.EqualValues(t, 46, line["workflow_id"]) + assert.Equal(t, tt.culprit, line["dependency_workflow_id"]) + storeMock.AssertExpectations(t) + schedulerMock.AssertExpectations(t) + }) + } +}