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
52 changes: 52 additions & 0 deletions forks/woodpecker/cmd/server/orphan_reaper_test.go
Original file line number Diff line number Diff line change
@@ -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
})
}
30 changes: 19 additions & 11 deletions forks/woodpecker/cmd/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
})
}

Expand Down
14 changes: 14 additions & 0 deletions forks/woodpecker/server/pipeline/pending_timeout.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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)
Expand All @@ -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))))
Expand Down
102 changes: 102 additions & 0 deletions forks/woodpecker/server/pipeline/pending_timeout_test.go
Original file line number Diff line number Diff line change
@@ -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)
})
}
}
Loading