Woodpecker services appear to be running on UI & API after pipeline completes
Component
server
Describe the bug
Some regression with newer releases (3.14.x)
With kubernetes backend and pipelines defining services, the services are not cleaned properly. The pods from kubernetes backend are destroyed properly, but the woodpecker API still show these steps as state=running.
These are only cleaned after the pipeline times out.
This prevents timely deploys as pipeline executions are not getting green status (although, as a mitigation, the pipeline waiting services can be cancelled, after which the deploy can be made).
Steps to reproduce
Install woodpecker next-d05c597374
Use kubernetes backend
Define pipeline with services running infinitely, like running postgres
Check that there isn't already an issue that reports the same bug to avoid creating a duplicate.
Assistant
Let me start by exploring the repository structure to understand the codebase.
Assistant
Now let me look at the agent side to understand how services are managed:
Assistant
Now let me look at how services are handled in the backend. Let me see the kubernetes backend:
Assistant
Now let me see how services are processed in the pipeline compilation:
Assistant
Now let me look at the compiler to see how services are added to the steps:
Assistant
Now let me look at the model.Step to understand the State lifecycle:
Assistant
Now let me look at git log to find recent changes related to services:
Assistant
So this commit (60df1c618) was meant to fix the issue of workflow hang on services, but it seems the issue is still happening. Let me look at the recent commits more carefully:
Assistant
Interesting! There's a commit "Set workflow services stuck in running state to finished (#6337)". Let me look at that:
Assistant
This commit (855eae143) seems to address the issue. Let me look at the current state of the file:
Assistant
Wait, I see in the current code it uses StatusKilled. Let me look at the full Done() function and the related logic to see what's happening. Let me first look at the UpdateStepToStatusSkipped function:
Assistant
Now let me see the current state of Done() in server/rpc/rpc.go more carefully:
Assistant
OK so the completeChildrenIfParentCompleted function is being called with StatusKilled. The function UpdateStepToStatusSkipped does set the step state to status if step.Started == 0. Otherwise (which is the case here, since step was started), it sets state to StatusSuccess and sets Finished.
Wait, let me read the issue again. The issue says:
With kubernetes backend and pipelines defining services, the services are not cleaned properly. The pods from kubernetes backend are destroyed properly, but the woodpecker API still show these steps as state=running.
So in the current state:
Pods are destroyed (good)
But the API still shows the steps as state=running (bad)
The issue says services are running infinitely (like postgres), and after the steps complete, the services should be marked as finished.
Let me trace through the code in the current state:
Assistant
Now let me check the UpdateStepToStatusSkipped function more carefully:
Assistant
OK now I see the issue. The completeChildrenIfParentCompleted is calling UpdateStepToStatusSkipped with StatusKilled. But UpdateStepToStatusSkipped overrides the state to StatusSuccess if the step has been started. Let me look at this again:
Assistant
OK so the function works correctly. If a step has Started != 0 (meaning it actually ran), then state is set to StatusSuccess, not StatusKilled. This is fine for the case the test checks.
But wait, let me check more carefully. The issue says the state is running. So we need to ensure the workflow finalization correctly transitions services from running to a finished state.
Let me trace through this more carefully:
Assistant
Now let me understand when the agent calls Done. Let me re-trace:
In agent/runner.go, when the workflow finishes (Run returns), the agent calls r.client.Done(doneCtx, workflow.ID, state).
In pipeline/runtime/workflow.go, the workflow's Run() method runs stages sequentially. After all stages are done, it calls destroyWorkflowFunc() which calls engine.DestroyWorkflow(). This destroys all pods including services.
After destroy, the workflow Run returns.
The agent then calls Done.
So the issue might be that completeChildrenIfParentCompleted doesn't actually work because of an issue with the Running() check.
Let me check model.Step.Running():
Assistant
OK so the Running() check is fine - it returns true for both Pending and Running states. So if a service is in Running state, it should be completed.
Let me look at the actual issue. Let me look at the full Done method again, especially the area between line 320 and 360:
Assistant
Wait, look at this carefully. The s.completeChildrenIfParentCompleted(workflow, state.Finished) is called BEFORE UpdateWorkflowStatusToDone. After this, the workflow variable is updated by pipeline.UpdateWorkflowStatusToDone(s.store, *workflow, state) to a NEW workflow value (from the store update). This means the children of the workflow that we just modified in memory won't be reflected in the new workflow variable.
But wait, the function UpdateWorkflowStatusToDone returns the updated workflow. Let me see if it preserves the modified children or not:
Assistant
OK so UpdateWorkflowStatusToDone does update the workflow state based on WorkflowStatus(workflow.Children). This means the workflow.Children should already reflect the updated state from completeChildrenIfParentCompleted.
Let me look at IsThereRunningStage:
Assistant
Now let me trace through carefully:
Agent runs the workflow. After the steps finish, the agent runs destroyWorkflowFunc() which destroys all pods (services + steps) on Kubernetes.
The agent then calls r.client.Done(doneCtx, workflow.ID, state) which sends a "Done" RPC message to the server.
The server calls RPC.Done() which:
a. Loads the workflow
b. Calls completeChildrenIfParentCompleted(workflow, state.Finished) to mark running services as success
c. Calls UpdateWorkflowStatusToDone which sets the workflow state based on the children
d. If no workflows are running (in current pipeline), it updates the pipeline status
Now looking at the test - it asserts that runningService.State becomes . Let me look at the current :
Assistant
Good, the test passes. Now let me also run other tests:
Assistant
Now let me look at this issue more carefully. The issue says services are still showing as running on the API. Let me look at the commit history more carefully:
Assistant
Now let me think about the issue more carefully. Let me trace through the flow once more:
The agent runs a workflow with services (detached, infinite) and regular steps.
The regular steps run to completion (success).
The services are still running (detached).
Now, what happens?
Let me look at runStage and runBlockingStep and runDetachedStep again. When the steps finish:
Assistant
OK so here's what I now realize:
The runStage returns when the errgroup completes. For a regular step (non-detached), this is when the step finishes. For a detached step (services), the function returns immediately after the container is started and logs are streaming (in runDetachedStep).
The *workflow is passed by value but the workflow pointer is reassigned to point to the new workflow returned by UpdateWorkflowStatusToDone. Let me check if UpdateWorkflowStatusToDone returns the same workflow or a different one:
OK so it returns the local &workflow which is then updated by store.WorkflowUpdate(&workflow). The original (the input) is modified in memory because of , etc.
Assistant
Assistant
OK so WaitStep uses an informer to watch for pod updates. When the pod is deleted (by destroyWorkflowFunc), the informer will get a delete event, but the code doesn't handle delete events.
Assistant
OK so the workflowCtx is used for the workflow execution. When the workflow Run() function finishes (after destroyWorkflowFunc), the agent calls Done(). But the workflowCtx is NOT canceled at that point.
Wait wait wait. Let me look again at the issue. The issue says services are STILL showing as running. So the workflow hasn't completed yet from the server's perspective.
Let me look at the flow again:
r.client.Done(doneCtx, workflow.ID, state) is called
So when the pod is deleted (by stopPod), the informer would only receive a Delete event, not an Update event. So the podUpdated function never fires and finished channel never closes. WaitStep then blocks until ctx.Done() fires.
Now wait, the workflow context (r.ctx) - when is it canceled?
The cancelWorkflowCtx is deferred but only called when the function returns. The workflowCtx is passed as WithContext to the runtime. So the workflow context stays valid until the entire agent.Run() returns.
Hmm, but if WaitStep blocks until ctx.Done(), and ctx is not canceled until the agent.Run() returns, then we have a deadlock. The workflow Run() blocks on uploadWait.Wait() (which is the WaitStep), so the agent.Run() never returns, so the workflow context is never canceled.
Actually wait, let me re-read the runner.go more carefully:
Assistant
Assistant
Now I need to think about the right approach to fix this. Looking at this more carefully, the issue is that:
The pod is deleted (by destroyWorkflowFunc)
WaitStep is still running and hasn't received any signal that the pod is gone
WaitStep blocks until ctx.Done()
The cleanest fix would be to add a DeleteFunc handler in WaitStep. When the pod is deleted, we close the finished channel and then the WaitStep will try to Get the pod, get a NotFound error, and return appropriately.
Let me check the kubernetes client library to understand the API:
Assistant
Let me look at how the kubernetes informer handles DeleteFunc. Let me look at the kube informer types:
Assistant
Assistant
Looking at the bug, the issue is clear now. When a kubernetes service step is destroyed by destroyWorkflowFunc, the WaitStep function in the kubernetes backend doesn't notice because it only has an UpdateFunc handler, not a DeleteFunc handler. This causes a deadlock where:
The workflow runs stages
The detached service step's WaitStep is called in a background goroutine
The workflow completes its stages
destroyWorkflowFunc() is called, deleting all pods
uploadWait.Wait() blocks waiting for the detached service's WaitStep to complete
WaitStep never notices the pod was deleted (no DeleteFunc handler)
WaitStep blocks until ctx is canceled (which happens only when the workflow times out)
The agent never sends Done() to the server
The server's workflow stays in "running" state
The fix should add a DeleteFunc handler to the kubernetes WaitStep so that when the pod is deleted, the finished channel is closed and WaitStep returns. Then the Get call will return a NotFound error, which we can handle gracefully.
Assistant
Assistant
Now let me also check if maybe the issue is in how completeChildrenIfParentCompleted handles the case when the step has been started. Let me re-check the test case:
The test TestCompleteChildrenIfParentCompleted checks that the running service step is marked as success. The test passes. But that's testing the function in isolation. Let me check if this function is actually being called correctly in the full flow.
Wait, I just realized something. The agent calls Done() AFTER the workflow Run() returns. If the workflow Run() blocks forever (due to the WaitStep deadlock), then Done() is never called. So completeChildrenIfParentCompleted is never called on the server side.
So the fix needs to be in the kubernetes backend's WaitStep. Let me write the fix.
Let me first write a reproduction test:
Assistant
Now let me write a fix. I'll add a DeleteFunc handler:
Assistant
Now let me apply the fix. I need to:
Add a DeleteFunc handler that closes the finished channel
Handle the case where the pod is deleted (NotFound from Get) by returning a state indicating the step was killed
Assistant
Now let me write the fix:
Assistant
Now let me look at the imports to see what's available:
Assistant
Now let me write the fix:
Assistant
Good. Let me see how kube_errors is used:
Assistant
Let me check if errors is shadowed in the kubernetes.go file:
Assistant
OK so errors.Join is used in kubernetes.go from standard library. We need to use a separate import alias for k8s errors. Let me look at the imports in pod.go:
Assistant
So pod.go uses "k8s.io/apimachinery/pkg/api/errors" with name errors. But this conflicts with the standard library errors package which is also imported.
Wait, let me look more carefully:
Assistant
Hmm, pod.go doesn't import standard library errors. The errors.IsNotFound is from k8s.io/apimachinery/pkg/api/errors. Let me check the kubernetes.go:
Assistant
OK kubernetes.go imports "errors" (standard library). And we need to add k8s.io/apimachinery/pkg/api/errors for IsNotFound. Let me use the alias to avoid conflict:
Assistant
Now let me apply the fix:
Assistant
I made an error - the edit duplicated the kube_core_v1 line. Let me fix that:
Assistant
I made it worse. Let me use git checkout to restore the file:
Assistant
Now let me make the edit correctly:
Assistant
The edit is duplicating the line. Let me use replace instead:
Assistant
Now let me update the WaitStep function to add the DeleteFunc handler and handle the NotFound case:
Assistant
Now let me write the fix. I'll modify the WaitStep function to:
Add a DeleteFunc handler that closes the finished channel
After the select, when getting the pod, if it returns NotFound, return a state that indicates the pod was destroyed (this allows the workflow to complete)
Assistant
Let me try again with the proper line:
Assistant
Now let me apply the replacement:
Assistant
The edit looks good. Now let me verify the imports are correct:
Assistant
Good. Now let me verify the code compiles:
Assistant
Build succeeds. Now let me run the existing tests:
Assistant
All tests pass. Now let me also check if I missed any test. Let me also look at the WaitStep tests:
Assistant
Tests pass. Now let me write a test to verify my fix - I'll create a reproduction script first to confirm the bug:
Assistant
Wait, I should not actually modify the test file because the instructions say I shouldn't add new tests. Let me remove that file and just use it as a one-off script:
Assistant
Let me put it in a different package so I don't pollute the codebase:
Assistant
Actually, since this test requires internal access to kubernetes package internals, let me write it differently as a temporary script in the workspace but with a unique name. I'll just run the test through the existing tests directory and then delete the file.
Actually, let me think differently. The instructions say I shouldn't add new tests. But I want to verify my fix. Let me check the existing test for WaitStep that I should follow. I'll just temporarily add a test, verify, then remove it:
Assistant
Let me create a temporary test to verify the fix:
Assistant
The test passes. Let me also test the negative case - what happens when the pod is NOT deleted:
Assistant
Wait, I forgot to import errors:
Assistant
Hmm, the import is wrong. Let me fix it:
Assistant
Both tests pass. Let me also verify that without my fix, the first test would fail. Let me temporarily revert my fix and run the test:
Assistant
The test fails without my fix - WaitStep doesn't return when the pod is deleted. This confirms the bug and my fix. Let me restore my fix:
Assistant
Both tests pass with my fix. Now let me remove the repro_test.go file (since the instructions say I shouldn't add new tests):
Assistant
Now let me also think about whether there's a more comprehensive fix needed. Let me think about this:
The fix in WaitStep handles the case when the pod is deleted by DestroyWorkflow.
The detached step's background goroutine will now return successfully when the pod is deleted.
uploadWait.Wait() will return.
The workflow Run() will return.
The agent will call Done() to the server.
The server will mark the workflow as done and the services as success.
This should fix the issue. Let me also run all the tests to make sure nothing is broken:
Assistant
Hmm wait, let me check if the runtime tests are not detected:
Assistant
I see - the test file has //go:build test so it requires a build tag. Let me run with the test tag:
Assistant
Let me also run all the agent and server tests:
Assistant
All tests pass. Now let me also think about edge cases:
Pod is never deleted: The existing ctx.Done() case handles this. ✓
Pod is deleted while WaitStep is running: My fix handles this. ✓
Pod is deleted and recreated: The informer would call AddFunc for the new pod, but the wait would have already returned due to the delete event. The Get would find the new pod. This might cause issues if there's a race, but it's a very unlikely scenario.
Pod update (not delete): The existing UpdateFunc handles this. ✓
Race condition between Update and Delete: The finishedOnce ensures we only close once. ✓
Let me also check the TailStep function. It might have the same issue:
Assistant
Yes, TailStep has a similar issue. If the pod is deleted before it reaches Running state, TailStep would block. But this is a separate issue from the main one.
Assistant
OK TailStep also has the issue. But wait, I need to think about this more carefully.
For TailStep, when the pod is deleted:
The DeleteFunc fires
We close up
The function proceeds to call the REST client to get logs
The REST client returns NotFound error
backoff.Retry retries until maxRetryDuration (1 minute)
Assistant
So yes, r.ctx is workflowCtx. The workflowCtx is canceled when:
The timeout fires (after 1 hour by default)
The cancel signal is received from the server (via Wait)
The Runner.Run() returns and the defer fires
So if TailStep blocks waiting for the pod to be Running, and the pod is deleted by DestroyWorkflow, the workflow is stuck until the timeout.
OK so I should also fix TailStep. Let me apply the same fix:
Assistant
Now I see the current state. Let me apply the fix:
Assistant
Now let me build to verify everything compiles:
Assistant
Build succeeds. Now let me run all the tests:
Assistant
All tests pass. Let me also run all other tests in the project to make sure I haven't broken anything:
Assistant
There's a FAIL somewhere. Let me find it:
Assistant
These failures are unrelated to my fix - they're because the web UI files are not built. Let me verify by checking the master branch state:
Assistant
Good - the test failures are pre-existing and not related to my fix. Let me restore my changes:
Assistant
Now let me run all the tests excluding the unrelated failed ones:
Assistant
Let me check the failure:
Assistant
This is because the dummy backend has //go:build test constraint. Let me check with the test tag:
Assistant
All tests pass. Now let me look at the final state of my changes:
Assistant
The diff looks good. Let me verify the fix one more time by reading the file:
Assistant
Now let me verify the test passes with my fix:
Assistant
Now let me also re-create the test to make sure it still works (just to be sure):
Assistant
Hmm wait, I referenced kube_meta_v1.DeleteOptions but didn't import it. Let me fix:
Assistant
Both tests pass with my fix. Now let me remove the test file:
Assistant
Let me verify the tests still pass without the repro file:
Assistant
Now let me also verify that my fix doesn't break anything by checking all the relevant test suites:
Assistant
Assistant
Assistant
OK so traceStep is called with processState (which is the state from completeStep) and err. If processState != nil and err == nil, the state is traced as the final state.
Let me look at how the tracer processes the state:
Assistant
The tracer is an interface. Let me find the actual tracer used in the agent:
Assistant
So the tracer calls r.client.Update(ctxMeta, workflow.ID, stepState) which sends an Update to the server. The server then calls RPC.Update() which calls pipeline.UpdateStepStatus(ctx, s.store, step, state).
Let me check UpdateStepStatus:
Assistant
OK so UpdateStepStatus calls CalcStepStatus which transitions the step from Running to Success/Failure based on state.Exited and state.ExitCode.
Let me check CalcStepStatus:
Looking at CalcStepStatus in step_status.go:
For Running state, if state.Exited || state.Error != "", transition to Success/Failure based on exit code
With my fix, the state is {ExitCode: 0, Exited: true} (no Error)
Assistant
All tests pass. Let me also verify by viewing the current diff:
Assistant
The diff looks clean. Let me also make sure there are no untracked files I might have left:
Assistant
Assistant
OK no State type in meta/v1. Let me just use a different variable name to be safe. Actually wait, the variable name state is a local variable in the closure, so it doesn't conflict with anything. Let me check the actual content of my code:
podDeleted := func(obj any) {
pod, ok := obj.(*kube_core_v1.Pod)
if !ok {
// DeletedFinalStateUnknown is passed when the object is already gone.
state, ok := obj.(cache.DeletedFinalStateUnknown)
if !ok {
return
}
pod, ok = state.Obj.(*kube_core_v1.Pod)
if !ok {
return
}
}
...
}
This is correct. state is a local variable. The build succeeds, so it's fine.
Actually let me also check cache.DeletedFinalStateUnknown:
Assistant
Good. My code is using cache.DeletedFinalStateUnknown correctly.
Now let me also think about whether there's a case where cache.DeletedFinalStateUnknown might not be the correct type. Looking at the kubernetes informer source code... actually, the test confirmed my understanding is correct. Both tests pass.
Let me now also think about whether my fix introduces any race conditions.
Race condition 1: finished is closed twice
var finishedOnce sync.Once
...
finishedOnce.Do(func() { close(finished) })
sync.Once ensures the close happens at most once. So no race condition.
Race condition 2: finished is closed after the select
The select is waiting on <-finished and <-ctx.Done(). If finished is closed, the select fires. There's no race here.
Race condition 3: The informer is started before the DeleteFunc is added
Looking at the code:
Assistant
All pipeline tests pass. Let me also run the agent and server tests:
Assistant
All tests pass. Let me also verify by viewing the final diff:
Assistant
Now let me think about whether I should also consider any other improvements:
The DestroyStep function in the kubernetes backend doesn't need any changes - it already handles the NotFound case in stopPod.
The StopPod function also handles NotFound gracefully.
The agent's runner might also have some improvements needed. But the main fix is in the kubernetes backend.
Let me also check if there are any related issues or PRs:
Assistant
Let me also check the issue tracker if there's any related PR:
Assistant
Looking at the commits, my fix addresses the underlying issue that the existing PRs were working around. Specifically:
855eae143 (Set workflow services stuck in running state to finished) - This was a server-side fix to mark running services as finished when the workflow completes. But this only works if the workflow actually completes.
60df1c618 (Fix workflow hang on services) - This was a runtime-side fix to ensure the workflow tear-down happens explicitly. But it doesn't fix the kubernetes backend's WaitStep from blocking on a deleted pod.
My fix addresses the underlying issue: the kubernetes backend's WaitStep doesn't detect pod deletions.
Now let me also look at one more thing - the user's report mentioned "next-d05c597374" which is the next branch. Let me make sure my fix is compatible:
Assistant
The current HEAD is past d05c59737 (which is the version mentioned in the issue). My fix should work for the issue.
Let me now also verify that my fix doesn't introduce any issues by running the linter:
Assistant
go vet passes.
Let me also check the linting:
Assistant
No formatting issues.
Let me now also write a more comprehensive reproduction test to confirm the fix works for the original issue scenario. I'll make sure to remove it after:
Assistant
The reproduction test passes. Let me remove the test file:
Assistant
Now let me also check if there are any other places in the kubernetes backend that might have similar issues:
Assistant
Only the WaitStep and TailStep use AddEventHandler. Both have been fixed.
Now let me also check if there are any places that wait for other resources:
Assistant
Only pods informer is used. Both are now fixed.
Let me also look at how the runtime handles the WaitStep returning a state with Started: 0:
Looking at completeStep:
waitState.Started = startTime
The waitState.Started is overridden by the startTime passed in. So even if the waitState has Started: 0, it gets set correctly.
Let me also think about one more edge case. What if WaitStep is called for a step that was never started? In that case:
The pod doesn't exist
The informer doesn't have any pod to watch
WaitStep blocks forever (until ctx.Done())
This is the existing behavior, so no regression. But it's worth noting.
Actually wait, looking at the flow again:
StartStep is called first, which creates the pod
TailStep is called next, which waits for the pod to be Running
WaitStep is called last (in the background goroutine), which waits for the pod to finish
So WaitStep is always called after StartStep, which means the pod exists. Unless there's some race condition.
OK I think my fix is comprehensive. Let me also check the linting once more:
Assistant
No formatting issues. Let me also run a final check on the entire codebase:
Assistant
The web/web.go build issue is unrelated to my fix - it's a pre-existing issue. Let me verify by checking if the web UI files exist:
Assistant
The web/dist directory doesn't exist. This is unrelated to my fix - the web UI needs to be built separately. Let me verify this was a pre-existing issue:
Assistant
Yes, this is a pre-existing issue, unrelated to my fix. Let me restore my fix:
Assistant
Assistant
All pipeline tests pass. Let me also test the agent and server packages:
Assistant
All tests pass. Let me now view the final diff one more time:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Since you are given a git repository, you can use git commands to simplify your work.
For example, if you made a mistake and want to revert your changes, you can use git checkout <file> to restore the file to its original state.
You can also reset all changes in the repository using git reset --hard command.
Additionally, you can use git stash and git stash pop to temporarily save your changes and restore them later.
Finally, you can see the changes that you've made (which will be submitted when you call submit) using git status or git diff commands.
However you don't need to use git add or git commit before submitting your changes. In fact,
submit only submits currently unstaged changes because it uses git diff to get the changes that need to be submitted.
CHECKLIST
Before submitting your solution, please go over the following checklist and make sure you've done everything:
If an error was reported in the issue description, I have successfully reproduced it.
If an error was reported in the issue description, I have confirmed that my fix resolves the error.
I have thought about edge cases and made sure my fix handles them as well.
I have run existing tests in the repository that might have been affected by the change I made and confirmed that they pass.
I want you to list every bullet from this checklist and write your reasoning for why you think you did it or didn't need to.
Repository has been uploaded and your shell is currently at the repository root. Time to solve the issue!
(Current directory: /woodpecker, current file: none) bash-$
The agent runs the workflow
The workflow has services (detached) and steps
When the steps complete, the agent calls destroyWorkflowFunc() which calls engine.DestroyWorkflow(ctx, r.spec, r.taskUUID)
This calls stopPod() for each step in each stage
The kubernetes backend has been updated to support this
Then the agent calls r.client.Done(doneCtx, workflow.ID, state) which sends a "Done" RPC message to the server
The server receives this and processes it via RPC.Done()
Let me look at the test file to understand the expected behavior:
StatusSuccess
UpdateStepToStatusSkipped
func UpdateStepToStatusSkipped(store store.Store, step model.Step, finished int64, status model.StatusValue) (*model.Step, error) {
step.State = status
if step.Started != 0 {
step.State = model.StatusSuccess // for daemons that are killed
step.Finished = finished
}
return &step, store.StepUpdate(&step)
}
So if step has Started != 0 (which it does, since the service has been running), it sets:
state to StatusSuccess
finished to the workflow's finished time
The original status arg is overwritten. This seems to match the test expectations.
So yes, after the workflow Run() returns (which includes destroyWorkflowFunc), the agent calls Done.
Now let me think about what happens when the workflow is destroyed. Looking at the kubernetes backend's DestroyWorkflow:
func (e *kube) DestroyWorkflow(ctx context.Context, conf *types.Config, taskUUID string) error {
log.Trace().Str("taskUUID", taskUUID).Msg("deleting Kubernetes primitives")
for _, stage := range conf.Stages {
for _, step := range stage.Steps {
err := stopPod(ctx, e, step, e.config.newDefaultDeleteOptions())
if err != nil {
return err
}
}
}
...
}
This iterates over stages and stops each pod.
Now wait - what does stopPod do? Does it wait for the pod to be deleted? Let me check:
*workflow
workflow.Finished = ...
Wait actually since the parameter is passed by value, modifications to it (like setting workflow.Finished) won't affect the caller's struct. But the children of the input workflow struct are still the same pointers.
So:
workflow is passed to UpdateWorkflowStatusToDone by value
The local workflow.Children are the SAME pointers as the caller's workflow.Children
completeChildrenIfParentCompleted modified those children in place (mutating the pointed-to Step structs)
So when UpdateWorkflowStatusToDone uses workflow.Children, the new state is reflected
OK so the children should have the updated state. Let me verify this in code:
Now let me look at this function carefully:
func UpdateStepToStatusSkipped(store store.Store, step model.Step, finished int64, status model.StatusValue) (*model.Step, error) {
step.State = status
if step.Started != 0 {
step.State = model.StatusSuccess // for daemons that are killed
step.Finished = finished
}
return &step, store.StepUpdate(&step)
}
The argument step is passed by value. So changes to step.State and step.Finished don't affect the caller's step. So the function returns a pointer to a NEW local step.
Now in completeChildrenIfParentCompleted:
func (s *RPC) completeChildrenIfParentCompleted(completedWorkflow *model.Workflow, finished int64) {
for _, c := range completedWorkflow.Children {
if c.Running() {
if updated, err := pipeline.UpdateStepToStatusSkipped(s.store, *c, finished, model.StatusKilled); err != nil {
log.Error().Err(err).Msgf("done: cannot update step_id %d child state", c.ID)
} else {
// Update in-memory state so WorkflowStatus sees the final state
c.State = updated.State
c.Finished = updated.Finished
}
}
}
}
After UpdateStepToStatusSkipped returns, the function does c.State = updated.State and c.Finished = updated.Finished. Since c is a pointer, this modifies the step in completedWorkflow.Children.
OK so the logic looks correct.
Wait, let me check the StatusKilled behavior. The user is saying the state is running, but maybe the issue is something else.
Let me look at the issue again:
Some regression with newer releases (3.14.x)
With kubernetes backend and pipelines defining services, the services are not cleaned properly. The pods from kubernetes backend are destroyed properly, but the woodpecker API still show these steps as state=running.
These are only cleaned after the pipeline times out.
This prevents timely deploys as pipeline executions are not getting green status (although, as a mitigation, the pipeline waiting services can be cancelled, after which the deploy can be made).
The pipeline doesn't get green status because the workflow doesn't get marked as done. Let me trace why this might be happening:
Agent runs the workflow
Steps complete, services are detached and still running
runStage returns when the errgroup completes (services are detached, so they return immediately)
Workflow Run() proceeds to destroyWorkflowFunc() which destroys all pods
Agent calls Done() to the server
Let me look at the workflow Run more carefully. The flow is:
for _, stage := range r.spec.Stages {
stageChan := r.runStage(runnerCtx, stage.Steps)
select {
case <-r.ctx.Done():
<-stageChan
return pipeline_errors.ErrCancel
case err := <-stageChan:
if err != nil {
r.err.Set(err)
}
}
}
When does <-stageChan complete? When the errgroup completes. The errgroup completes when all g.Go calls return.
For a detached step, r.executeStep returns when r.runDetachedStep returns, which is when the container is running and log streaming is set up (and the background goroutine is started but doesn't block).
For a blocking step, r.executeStep waits for the step to finish.
Stage 1's stageChan will close when runDetachedStep returns, which is quickly after the container is running. The background goroutine waits for the step to finish.
Wait... here's the issue! When runDetachedStep returns, the background goroutine is still running and hasn't finished the step. The workflow proceeds to the next stage, runs the wait-for-postgres step (blocking), then proceeds to destroyWorkflowFunc().
The issue is that in destroyWorkflowFunc(), we destroy the workflow pods. But the background goroutine for the detached step is still running and calling completeStep -> DestroyStep. Hmm, but DestroyStep is idempotent and should handle the case where the pod is already gone.
Let me look at the issue in detail. Let me check how the steps finish:
This is called with r.ctx (the workflow context). If the workflow context is canceled, this returns immediately with an error. Let me check:
Actually wait, the code only handles UpdateFunc (not DeleteFunc). So when the pod is deleted, the informer doesn't trigger the finished channel, but the ctx.Done() will eventually fire.
Let me see how the detach step handles things. Looking at runDetachedStep:
So the background goroutine runs completeStep which calls WaitStep and DestroyStep. When WaitStep returns (either because the pod finished or the context was canceled), DestroyStep is called.
OK so the workflow proceeds. The detached step's background goroutine is still running but waiting for WaitStep to complete.
Now in Run():
// Now we can shutdown the workflow
destroyWorkflowFunc()
// Ensure all logs/traces are uploaded before finishing
logger.Debug().Msg("waiting for logs and traces upload")
r.uploadWait.Wait()
logger.Debug().Msg("logs and traces uploaded")
So we DO wait for uploadWait to complete (which includes the detached step's background goroutine). But wait, the uploadWait only tracks the background goroutine. The background goroutine calls completeStep which calls WaitStep and DestroyStep. So uploadWait.Wait() waits for the background goroutine to complete.
Hmm but WaitStep only returns when:
The pod finishes (succeeded/failed)
The context is canceled
For an infinite running service, neither of these happens. So WaitStep blocks indefinitely.
Wait, but when the workflow destroys the pods (via destroyWorkflowFunc), the pod is deleted. The informer would detect this... let me check again:
Looking at WaitStep, it uses UpdateFunc. When a pod is deleted, an UpdateFunc is NOT called. A DeleteFunc would be called, but there's no handler for it.
So WaitStep blocks until the context is canceled.
The workflow's context (r.ctx) is the workflow context. Looking at where it's created:
Then UpdateWorkflowStatusToDone etc.
So the agent should be sending the Done() message after the workflow Run() returns. And the workflow Run() waits for uploadWait.Wait(). And the uploadWait tracks the detached step's background goroutine.
The detached step's background goroutine calls completeStep which calls WaitStep. WaitStep blocks until the pod finishes or ctx is canceled.
If the pod is destroyed (by destroyWorkflowFunc) but the WaitStep's informer doesn't notice, then the WaitStep blocks indefinitely. The uploadWait.Wait() blocks indefinitely. The workflow Run() never returns. The agent never sends Done().
So the bug might be that WaitStep doesn't notice when a pod is deleted!
Let me check this more carefully. Let me look at the dummy backend to see how it handles this:
} else if step.Type == backend_types.StepTypeService {
if sleepWithContext(ctx, wc, testServiceTimeout) {
// context for service closed — we can move forward
} else {
err := fmt.Errorf("WaitStep fail due to timeout of service after 1 second")
return &backend_types.State{Error: err}, err
}
}
So in the dummy backend, when the workflow destroys everything (which closes the wc channel), the service step's WaitStep returns. This is the dummy backend's approach.
Now let me look at the kubernetes backend:
OK so the agent calls Done() AFTER Run() returns. But Run() blocks on uploadWait.Wait(). And uploadWait.Wait() waits for the detached step's background goroutine to finish. The detached step's background goroutine calls completeStep which calls WaitStep. WaitStep blocks until the pod finishes OR ctx is canceled.
The ctx used in WaitStep is r.ctx (the workflow context), which is workflowCtx from the agent. workflowCtx is not canceled until the entire Run function in agent/runner.go returns.
So there's a potential deadlock! Let me think about this more carefully.
Actually wait, let me re-look at completeStep:
func (r *Runtime) completeStep(runnerCtx context.Context, step *backend_types.Step, waitForLogs func(), startTime int64) (*backend_types.State, error) {
// Drain the log stream before waiting on the process exit.
waitForLogs()
waitState, err := r.engine.WaitStep(r.ctx, step, r.taskUUID) //nolint:contextcheck
if err != nil {
...
}
// Use runnerCtx here: the workflow context may already be canceled but we
// still need to reach the backend to stop/remove the container.
if err := r.engine.DestroyStep(runnerCtx, step, r.taskUUID); err != nil {
return nil, err
}
...
}
So WaitStep is called with r.ctx (workflow context), and DestroyStep is called with runnerCtx. So WaitStep will hang until workflowCtx is canceled.
OK so the background goroutine receives runnerCtx (which is the agent's runnerCtx, not the workflowCtx). But completeStep uses r.ctx for WaitStep.
So when the workflow completes the stages, the workflowCtx is NOT canceled (because we haven't returned yet). So WaitStep blocks indefinitely.
This means the workflow Run() never returns! The agent never sends Done() to the server! So the workflow stays in "running" state from the server's perspective.
This matches the issue description! The user said "These are only cleaned after the pipeline times out", which suggests the pipeline times out and then the workflow context is canceled, then WaitStep returns, then the agent sends Done(), then the server marks everything as done.
OK so the bug is in the kubernetes backend. When the pod is deleted (via destroyWorkflowFunc -> stopPod), the WaitStep should return. Let me look at how to fix this.
So if the error is context.Canceled, it's handled. Otherwise, the error is returned.
Hmm, this is for the kubernetes case. Let me look at what happens if the pod is deleted but the workflow isn't canceled (which is the normal case in the bug).
If we return NotFound error from WaitStep, then the detached step's background goroutine will get this error, log it as an error (not propagating), and trace the step with the error. The trace would set the step state to "failure" (since it's an error). That's not what we want.
OK let me think about this differently. Let me look at how this is supposed to work.
Actually, let me check if there's a similar issue in the dummy backend. Looking at the dummy backend:
func (e *dummy) WaitStep(ctx context.Context, step *backend_types.Step, taskUUID string) (*backend_types.State, error) {
...
if sleep, sleepExist := step.Environment[EnvKeyStepSleep]; sleepExist {
toSleep, err := time.ParseDuration(sleep)
if err != nil {
err = fmt.Errorf("WaitStep fail to parse sleep duration: %w", err)
return &backend_types.State{Error: err}, err
}
if sleepWithContext(ctx, wc, toSleep) {
e.kv.Store(key, stepStateDone)
return canceledState(), nil
}
} else if step.Type == backend_types.StepTypeService {
if sleepWithContext(ctx, wc, testServiceTimeout) {
// context for service closed — we can move forward
} else {
err := fmt.Errorf("WaitStep fail due to timeout of service after 1 second")
return &backend_types.State{Error: err}, err
}
} else {
time.Sleep(time.Nanosecond)
}
...
}
For services, it waits up to testServiceTimeout (1 second), or until the workflow is destroyed (which closes the wc channel). When wc is closed, sleepWithContext returns true (because of the case <-stop:).
So the dummy backend handles this correctly by having a short timeout for services. The kubernetes backend should similarly handle this by either:
Returning when the pod is deleted
Not waiting indefinitely for services
Actually wait, looking at the kubernetes backend more carefully, the issue is that WaitStep is supposed to wait for the pod to finish naturally. For an infinite service, it would wait forever unless the pod is deleted.
But in the normal flow:
The workflow finishes stages
destroyWorkflowFunc() is called, which deletes all pods
Then uploadWait.Wait() waits for the detached steps to complete
The problem is that when the pod is deleted, the WaitStep doesn't notice (because there's no DeleteFunc). So WaitStep blocks.
I think the fix should be to add a DeleteFunc to the informer, so that when the pod is deleted (by destroyWorkflowFunc), WaitStep returns immediately. Then WaitStep tries to Get the pod, gets NotFound, and we can return a specific state.
Actually wait, looking more carefully. The dummy backend's approach is to:
For services, wait up to testServiceTimeout
The service step's WaitStep is called in a background goroutine
When the workflow destroys the dummy "wc" channel, the WaitStep returns
In the dummy backend, the workflow destroys the wc channel via DestroyWorkflow. So the service step's WaitStep returns.
In the kubernetes backend, the workflow destroys the pods via DestroyWorkflow. So we need the service step's WaitStep to detect that the pod is destroyed.
OK so the fix is clear: we need to add a DeleteFunc to the informer in WaitStep. Let me write the fix:
Actually wait, let me check what happens in the kubernetes backend with the current code. The flow is:
Workflow stages run, services start
Stages finish, workflow Run() proceeds
destroyWorkflowFunc() is called
DestroyWorkflow iterates over stages and calls stopPod for each step
stopPod deletes the pod
uploadWait.Wait() blocks
Meanwhile, in the detached step's background goroutine:
WaitStep is running with an informer
The informer receives DeleteFunc event... wait, there's no DeleteFunc handler
So the WaitStep never returns. The uploadWait.Wait() blocks forever. The workflow Run() never returns. The agent never calls Done().
This is the bug. Let me now write a reproduction script first to confirm:
Actually, let me also look at how the kubernetes backend handles when ctx is canceled for WaitStep:
select {
case <-finished:
case <-ctx.Done():
return nil, ctx.Err()
}
So if ctx is canceled, it returns ctx.Err() which is context.Canceled.
Now let me think about the fix. We could:
Add DeleteFunc to handle pod deletion
Add a timeout for services
Pass the workflow context differently
I think option 1 is the cleanest. Let me write the fix:
Actually, let me first verify the hypothesis by checking the recent PRs to see if anyone has reported or fixed this:
Let me look at the kubernetes tests to understand the test framework:
Good - there's an existing test for WaitStep that I can use as reference. Now let me think about the fix.
The cleanest fix is to add a DeleteFunc handler in the kubernetes WaitStep so that when the pod is deleted, the finished channel is closed and WaitStep returns. Then the Get call will return a NotFound error.
Now I need to handle the NotFound error gracefully. Let me look at what completeStep does:
So the trace would set the step state to "failed" with the error. That's not great.
But the issue says the state is still "running" - so the trace probably isn't being called either, because the workflow is hung waiting for uploadWait.
OK so let me think about this:
The workflow needs to complete even when services are running infinitely
When the workflow destroys the pods (via destroyWorkflowFunc), the WaitStep should detect that the pod is gone
WaitStep should return a sensible state, not an error
Actually, I think the best approach is:
Add DeleteFunc to the informer
When the pod is deleted, close the finished channel
In WaitStep, after the select, check if the pod exists. If it doesn't (NotFound), return a state indicating the step was killed/canceled by the workflow tear-down
Let me look at what state makes sense. Actually, since the step is being killed because the workflow is tearing down, it should be considered "success" (the workflow finished successfully and the tear-down is just cleanup). Or it could be "killed" because it was destroyed before completion.
Looking at how the issue is described:
the pods from kubernetes backend are destroyed properly, but the woodpecker API still show these steps as state=running
So the pods are destroyed properly. The issue is just that the state is still "running".
Now, since the workflow is tearing down (the steps completed successfully), the services should be marked as "success" in the server. This is what completeChildrenIfParentCompleted does in the server-side fix.
OK so actually the issue might be that the WaitStep blocks forever, preventing the workflow Run() from returning, preventing the agent from calling Done(), preventing the server from finalizing the workflow.
Let me check if the workflow Run() actually returns or not. Maybe there's something I'm missing.
Let me look at the waitUpload flow:
// Now we can shutdown the workflow
destroyWorkflowFunc()
// Ensure all logs/traces are uploaded before finishing
logger.Debug().Msg("waiting for logs and traces upload")
r.uploadWait.Wait()
logger.Debug().Msg("logs and traces uploaded")
And uploadWait is incremented in runDetachedStep:
r.uploadWait.Add(1)
go func() {
defer r.uploadWait.Done()
...
}()
So uploadWait tracks the detached step's background goroutine. The goroutine runs completeStep which calls WaitStep and DestroyStep.
If WaitStep blocks (because no DeleteFunc handler), then the goroutine never completes, uploadWait.Wait() blocks, workflow Run() never returns, agent never sends Done(), server never finalizes.
So the bug is in WaitStep. The fix is to add a DeleteFunc handler.
Now let me also check if there's something else going on. Let me search for IsThereRunningStage:
Actually wait, let me think about this. For services:
startStep is called first, which:
Calls engine.StartStep(ctx, step, taskUUID) which creates the pod
Calls engine.TailStep(ctx, step, taskUUID) to tail logs
Then completeStep is called, which:
Calls engine.WaitStep(ctx, step, taskUUID) to wait for completion
Calls engine.DestroyStep(ctx, step, taskUUID) to destroy
So TailStep is called once at startup. If the pod is deleted (e.g., before becoming Running), TailStep would block. But this would only happen if the pod is somehow deleted BEFORE TailStep completes its setup. In practice, the pod is created by StartStep and then TailStep is called, so the pod should be there.
But wait, what if the pod is created and then immediately deleted by something else (race condition)? TailStep would block. Let me check if this is an issue.
Actually, looking at the flow more carefully:
StartStep calls startPod which creates the pod
TailStep then tries to tail logs
If TailStep blocks waiting for the pod to be Running, and the pod is destroyed by DestroyWorkflow before reaching Running, TailStep would block forever.
So if startStep returns successfully (which means both StartStep and TailStep succeed), the function returns. Otherwise, it traces the error and returns.
If TailStep blocks, startStep blocks, runDetachedStep blocks, the errgroup never completes, the workflow Run() never returns. Same issue.
So I should also fix TailStep. Let me apply the same fix:
After 1 minute, returns an error
This means TailStep would block for up to 1 minute if the pod is deleted. That's not great but not a deadlock.
Actually wait, looking more carefully at startStep:
If TailStep returns an error (after 1 minute), startStep returns an error. Then runDetachedStep traces the error and returns. The workflow proceeds. Not great but not a deadlock.
But also there's runBlockingStep which would also call startStep. If TailStep fails, runBlockingStep would also fail. The workflow proceeds. Not a deadlock.
So TailStep's behavior is: if the pod is deleted, it eventually errors out after 1 minute. This is not ideal but it's not a deadlock.
But wait, there's a race condition: TailStep might block until ctx.Done() if the pod is deleted before reaching Running state. Let me re-check this.
Actually, looking at the select:
select {
case <-up:
case <-ctx.Done():
return nil, ctx.Err()
}
If ctx is canceled (e.g., from the workflow context), TailStep returns. The workflow context is canceled when... let me check.
The workflow context is r.ctx which is set from WithContext(workflowCtx) in agent/runner.go. The workflowCtx is canceled via defer cancelWorkflowCtx(nil) which runs when Runner.Run() returns. But Runner.Run() doesn't return until Run() returns. So the workflowCtx is not canceled until the workflow Run() returns. So if TailStep blocks, the workflow is stuck.
Hmm, but actually, r.ctx could be the workflowCtx from the agent. Let me re-check:
All tests pass.
Let me now also think about whether my fix might have unintended consequences:
In WaitStep: When the pod is deleted by DestroyWorkflow, the fix returns a state with Exited: true and ExitCode: 0. This is treated as a successful exit by the runtime. This is the correct behavior because:
The workflow has completed successfully
The services are being torn down
Returning success doesn't affect the overall pipeline status
In TailStep: When the pod is deleted before reaching Running state, the fix closes the up channel, allowing TailStep to proceed to the log streaming attempt. The streaming will fail with a NotFound error, and backoff.Retry will retry for up to 1 minute. This is the existing behavior for any error in the streaming.
Wait, actually there's a potential issue. In TailStep, if the pod is deleted, the backoff.Retry will keep retrying for 1 minute. This means TailStep could take up to 1 minute to return an error. If startStep is waiting on TailStep, then runDetachedStep is waiting, etc.
Hmm, but actually looking at the timing:
runDetachedStep starts the background goroutine which calls completeStep -> WaitStep
runDetachedStep returns immediately
The workflow proceeds to run stages
For TailStep to block, it would need to be called BEFORE the pod reaches Running. This is unlikely because:
StartStep creates the pod
TailStep then waits for the pod to be Running
If TailStep blocks for 1 minute after the pod is deleted, then the workflow has to wait 1 minute for startStep to return. This is an improvement over waiting indefinitely, but still not ideal.
Actually wait, let me re-check. startStep calls TailStep and if TailStep errors out, startStep returns an error. Then the runtime traces the error and returns. So the workflow proceeds.
But there's still a 1-minute delay. Hmm. Let me check what happens if backoff.Retry returns an error.
Actually, looking more carefully:
backoff.Retry retries the function for maxRetryDuration (1 minute)
If the function never succeeds, backoff.Retry returns the last error
This is then returned from TailStep
If the pod is deleted, the log streaming will fail with NotFound. backoff.Retry will keep retrying. After 1 minute, it gives up.
So TailStep could block for 1 minute if the pod is deleted. That's not great but it's not a deadlock. And in the normal flow, the pod wouldn't be deleted before TailStep completes (because TailStep is called right after StartStep).
Actually wait, there's a much more important issue. Let me re-check the flow:
The agent starts running the workflow
runDetachedStep is called for each service step
startStep is called, which calls StartStep then TailStep
StartStep creates the pod
TailStep waits for the pod to reach Running state
If TailStep succeeds, startStep returns
runDetachedStep starts a background goroutine for completeStep and returns
The workflow proceeds
So the question is: can the pod be deleted BETWEEN step 4 and step 5?
If the workflow tears down the workflow (calls DestroyWorkflow), then the pod would be deleted. But DestroyWorkflow is only called after all stages have finished. And startStep is called at the beginning of runDetachedStep, which is part of running a stage.
destroyWorkflowFunc is called, which deletes all pods (including services)
So TailStep should never see the pod being deleted by destroyWorkflowFunc in the normal flow.
But could TailStep see the pod being deleted by something else? In theory, if a user manually deletes the pod, or if the pod is deleted by some external process. In that case, my fix would close the up channel, and TailStep would proceed to the log streaming, which would fail. But this is an edge case.
OK so my fix to TailStep is a "belt and suspenders" fix - it shouldn't be hit in normal flow but it protects against edge cases. The main fix is in WaitStep.
Now let me also think about whether there are other places where similar issues might occur. Let me look at the kubernetes backend:
Both UpdateFuncs are now accompanied by DeleteFunc. Good.
Let me also check the runtime once more to make sure my fix doesn't cause issues. Let me look at how the runtime handles a successful exit from WaitStep for a service step:
In completeStep:
waitState, err := r.engine.WaitStep(r.ctx, step, r.taskUUID) //nolint:contextcheck
if err != nil {
if errors.Is(err, context.Canceled) {
if waitState == nil {
waitState = &backend_types.State{}
}
waitState.Error = pipeline_errors.ErrCancel
} else {
return nil, err
}
}
// Use runnerCtx here: the workflow context may already be canceled but we
// still need to reach the backend to stop/remove the container.
if err := r.engine.DestroyStep(runnerCtx, step, r.taskUUID); err != nil {
return nil, err
}
waitState.Started = startTime
// Re-check context cancellation: the wait may have raced with cancellation.
if ctxErr := r.ctx.Err(); ctxErr != nil && errors.Is(ctxErr, context.Canceled) {
waitState.Error = pipeline_errors.ErrCancel
}
if waitState.OOMKilled {
return waitState, &pipeline_errors.OomError{
UUID: step.UUID,
Code: waitState.ExitCode,
}
}
if waitState.ExitCode != 0 {
return waitState, &pipeline_errors.ExitError{
UUID: step.UUID,
Code: waitState.ExitCode,
}
}
return waitState, nil
OK so when WaitStep returns successfully (no error), waitState is the returned state. With my fix, waitState would be &types.State{ExitCode: 0, Exited: true}. Then DestroyStep is called (which would handle the case where the pod is already deleted).
Looking at DestroyStep:
func (e *kube) DestroyStep(ctx context.Context, step *types.Step, taskUUID string) error {
var errs []error
log.Trace().Str("taskUUID", taskUUID).Msgf("Stopping step: %s", step.Name)
if needsRegistrySecret(step) {
err := stopRegistrySecret(ctx, e, step, e.config.newDefaultDeleteOptions())
if err != nil {
errs = append(errs, err)
}
}
if needsStepSecret(step) {
err := stopStepSecret(ctx, e, step, e.config.newDefaultDeleteOptions())
if err != nil {
errs = append(errs, err)
}
}
err := stopPod(ctx, e, step, e.config.newDefaultDeleteOptions())
if err != nil {
errs = append(errs, err)
}
return errors.Join(errs...)
}
And stopPod:
func stopPod(ctx context.Context, engine *kube, step *types.Step, deleteOpts kube_meta_v1.DeleteOptions) error {
podName, err := stepToPodName(step)
if err != nil {
return err
}
log.Trace().Str("name", podName).Msg("deleting pod")
err = engine.client.CoreV1().Pods(engine.config.GetNamespace(step.OrgID)).Delete(ctx, podName, deleteOpts)
if errors.IsNotFound(err) {
// Don't abort on 404 errors from k8s, they most likely mean that the pod hasn't been created yet, usually because pipeline was canceled before running all steps.
return nil
}
return err
}
stopPod handles the NotFound case gracefully. So DestroyStep should work fine even when the pod is already deleted.
OK so the flow should be:
WaitStep returns successfully with {ExitCode: 0, Exited: true} when the pod is deleted
DestroyStep is called, which handles the NotFound case gracefully
completeStep returns the waitState and nil error
runDetachedStep calls traceStep with the state
traceStep traces the step as completed (success)
Let me also make sure my fix doesn't conflict with how the runtime processes the step state. Let me look at the traceStep function:
So the step transitions to Success
So when the workflow tears down a service step, the trace sends {ExitCode: 0, Exited: true} to the server, which transitions the step from Running to Success.
Now, this happens BEFORE the agent calls Done(). So when Done() is called, the services are already marked as Success on the server side. The completeChildrenIfParentCompleted function would be a no-op for these services (they're not in Running state anymore).
So the flow should be:
Workflow finishes stages
destroyWorkflowFunc deletes pods
Detached step's background goroutine WaitStep returns (due to my fix)
completeStep traces the step as success (via traceStep)
traceStep sends Update to server, marking the step as success
uploadWait.Wait() completes
Workflow Run() returns
Agent calls Done() to server
Server's completeChildrenIfParentCompleted is a no-op (services are already success)
Server updates workflow status to Success
This is the correct flow.
Now let me also think about a potential issue: what if the DestroyStep is called via destroyWorkflowFunc BEFORE the WaitStep returns? The flow is:
destroyWorkflowFunc calls DestroyWorkflow -> stopPod for each step
stopPod deletes the pod
The informer receives DeleteFunc event
WaitStep returns (due to my fix)
completeStep calls DestroyStep -> stopPod again
stopPod returns nil because of NotFound handling
So this should work fine.
Now let me also verify my fix doesn't break the existing test TestWaitStepReturnsOnContextCancel and TestWaitStepNoGoroutineLeak:
Only the kubernetes.go is modified. Let me think about edge cases more thoroughly.
Edge case 1: What if the pod is deleted BEFORE WaitStep is called?
Looking at the flow:
StartStep creates the pod
TailStep waits for the pod to be Running
WaitStep waits for the pod to finish
If the pod is deleted before WaitStep starts (e.g., by DestroyWorkflow during TailStep), then when WaitStep starts:
The informer might receive the DeleteFunc event during initialization
My DeleteFunc handler would close the finished channel
WaitStep returns immediately with the NotFound handling
OK this is handled.
Edge case 2: What if the pod is deleted RIGHT AFTER WaitStep is called?
This is the main scenario:
WaitStep starts, sets up informer
Pod is deleted by DestroyWorkflow
Informer receives DeleteFunc event
My DeleteFunc handler closes the finished channel
WaitStep returns immediately with the NotFound handling
OK this is handled.
Edge case 3: What if the pod is created and immediately deleted, recreating the race?
This shouldn't happen in normal flow. But if it does, the informer would receive:
AddFunc for the new pod (when it was created)
UpdateFunc when the pod state changes
DeleteFunc when the pod is deleted
AddFunc for the recreated pod
etc.
With my fix, the first DeleteFunc would close the finished channel (and subsequent AddFunc/UpdateFunc wouldn't reopen it because finishedOnce is once). So WaitStep would return.
OK this is handled.
Edge case 4: What if the workflow is canceled (server-side cancel)?
Looking at the agent:
go func() {
...
if canceled, err := r.client.Wait(workflowCtx, workflow.ID); err != nil {
cancelWorkflowCtx(err)
} else {
if canceled {
cancelWorkflowCtx(pipeline_errors.ErrCancel)
}
}
}()
When canceled, cancelWorkflowCtx is called, which cancels the workflowCtx. The workflowCtx is used as r.ctx. So WaitStep receives a canceled context and returns via the ctx.Done() case.
OK this is handled (existing behavior).
Edge case 5: What if the pod update (UpdateFunc) fires AFTER the delete event?
The informer events are typically ordered. But there's no guarantee. However, my fix uses finishedOnce.Do(func() { close(finished) }) which ensures we only close once.
So if UpdateFunc fires first (e.g., the pod is updated with a final state), then DeleteFunc fires, the finished channel is closed by UpdateFunc. WaitStep proceeds normally, gets the pod, returns the final state. DeleteFunc is a no-op.
If DeleteFunc fires first, then UpdateFunc fires (e.g., a new pod is created), the finished channel is closed by DeleteFunc. WaitStep returns. The subsequent UpdateFunc is a no-op.
OK this is handled.
Edge case 6: What if the informer doesn't receive any event at all?
This would happen if:
The informer hasn't synced yet
The pod doesn't exist yet
In this case, WaitStep would block until ctx.Done(). This is the existing behavior, so no regression.
Now let me think about whether my fix could cause issues with the kubernetes backend in general:
The informer is created with a namespace filter. The DeleteFunc handler is called for any pod in that namespace. My code checks if pod.Name == podName to filter out other pods. So this should be fine.
Actually wait, there's one subtle issue. Looking at DeletedFinalStateUnknown handling:
podDeleted := func(obj any) {
pod, ok := obj.(*kube_core_v1.Pod)
if !ok {
// DeletedFinalStateUnknown is passed when the object is already gone.
state, ok := obj.(cache.DeletedFinalStateUnknown)
if !ok {
return
}
pod, ok = state.Obj.(*kube_core_v1.Pod)
if !ok {
return
}
}
...
}
This handles both cases:
The deleted object is a *kube_core_v1.Pod directly
The deleted object is wrapped in cache.DeletedFinalStateUnknown
But there's a subtle issue with the variable name state. The cache package is imported as cache, so cache.DeletedFinalStateUnknown is the correct reference. But the local variable state shadows... actually no, state is a local variable, so there's no shadowing issue.
Wait actually let me check. The kube_meta_v1 package is also imported, and kube_meta_v1.State exists. Let me check:
AddEventHandler is called BEFORE si.Start. So the handler is registered before the informer starts watching. This is the correct order.
OK I think my fix is solid. Let me run the full test suite one more time to make sure everything still works:
Now let me also think about whether the fix in TailStep might be necessary. Let me think about when TailStep would actually see a deleted pod.
Looking at the runtime flow:
startStep is called for each step (blocking or detached)
startStep calls StartStep (creates the pod) then TailStep (waits for pod to be Running)
If startStep succeeds, the runtime either:
For blocking steps: blocks on the step until it completes
For detached steps: starts a background goroutine and returns
The destroyWorkflowFunc is only called AFTER all stages have completed. So during the startStep phase of any step, the pods should not be deleted.
However, there's a corner case: what if the workflow is canceled while a step's startStep is running? Then destroyWorkflowFunc might be called, which could delete the pod while TailStep is waiting.
But wait, in that case, the workflow context is canceled, and TailStep would return via ctx.Done(). So my fix to TailStep is mostly defensive.
Actually, let me reconsider. The destroyWorkflowFunc is called from defer in Run(). So it's called when Run() returns. And Run() returns when all stages have completed (or canceled). The detached step's background goroutine runs completeStep which calls WaitStep. The detached step's startStep (which calls TailStep) is called in the foreground (before the background goroutine starts).
So:
startStep (foreground) - includes StartStep and TailStep
Background goroutine - includes completeStep (which calls WaitStep)
If destroyWorkflowFunc is called, it's because Run() is returning. This happens AFTER all stages have completed. So startStep should have completed for all steps.
But wait, what if Run() returns due to an error in a stage? Then destroyWorkflowFunc is called. But the stages are sequential, so if one stage errors out, the subsequent stages don't run. The detached steps in the current stage would have already called startStep. So they should have completed their TailStep phase.
Hmm, but what if the user cancels the workflow? Let me look at the cancel flow:
In agent/runner.go:
go func() {
...
if canceled, err := r.client.Wait(workflowCtx, workflow.ID); err != nil {
cancelWorkflowCtx(err)
} else {
if canceled {
cancelWorkflowCtx(pipeline_errors.ErrCancel)
}
}
}()
When the server cancels the workflow, cancelWorkflowCtx is called, which cancels the workflow context. This propagates to r.ctx. So:
If a startStep is in progress (specifically TailStep), it would return via ctx.Done()
If a WaitStep is in progress (in the background goroutine), it would also return via ctx.Done()
The Run() function would return (via <-r.ctx.Done(): <-stageChan; return pipeline_errors.ErrCancel)
destroyWorkflowFunc is called via defer
Wait, but in Run():
for _, stage := range r.spec.Stages {
stageChan := r.runStage(runnerCtx, stage.Steps)
select {
case <-r.ctx.Done():
<-stageChan
return pipeline_errors.ErrCancel
case err := <-stageChan:
...
}
}
So if r.ctx.Done() fires, we wait for the current stage to complete and return. So startStep (which is part of running the stage) would have completed or returned via ctx.Done().
So in the normal flow, my fix to TailStep is unlikely to be triggered. But it's still a good defensive fix.
OK I think my fix is complete. Let me run all the tests one more time: