Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

cancel running task runs on restart (#7505)

p0ny815246d380fd
diff --git a/backend/runner/taskrun/schedulerv2.go b/backend/runner/taskrun/schedulerv2.go
index 9f50173528..ff5148e0b1 100644
--- a/backend/runner/taskrun/schedulerv2.go
+++ b/backend/runner/taskrun/schedulerv2.go
@@ -397,3 +397,28 @@ func (s *SchedulerV2) runTaskRunOnce(ctx context.Context, taskRun *store.TaskRun
return
}
}
+
+// ClearRunningTaskRuns changes all RUNNING taskRuns to CANCELED.
+// When there are running taskRuns and Bytebase server is shutdown, these task executors are stopped, but the taskRuns' status are still RUNNING.
+// When Bytebase is restarted, the task scheduler will re-schedule those RUNNING tasks, which should be CANCELED instead.
+// So we change their status to CANCELED before starting the scheduler.
+// And corresponding taskRuns are also changed to CANCELED.
+func (s *SchedulerV2) ClearRunningTaskRuns(ctx context.Context) error {
+ runningTaskRuns, err := s.store.ListTaskRunsV2(ctx, &store.FindTaskRunMessage{
+ Status: &[]api.TaskRunStatus{api.TaskRunRunning},
+ })
+ if err != nil {
+ return errors.Wrap(err, "failed to list running task runs")
+ }
+
+ if len(runningTaskRuns) > 0 {
+ var taskRunIDs []int
+ for _, taskRun := range runningTaskRuns {
+ taskRunIDs = append(taskRunIDs, taskRun.ID)
+ }
+ if err := s.store.BatchPatchTaskRunStatus(ctx, taskRunIDs, api.TaskRunCanceled, api.SystemBotID); err != nil {
+ return errors.Wrapf(err, "failed to change task run %v's status to %s", taskRunIDs, api.TaskRunCanceled)
+ }
+ }
+ return nil
+}
diff --git a/backend/server/server.go b/backend/server/server.go
index 8b79890691..ad0e3507a8 100644
--- a/backend/server/server.go
+++ b/backend/server/server.go
@@ -962,14 +962,17 @@ func (s *Server) Run(ctx context.Context, port int) error {
ctx, cancel := context.WithCancel(ctx)
s.cancel = cancel
if !s.profile.Readonly {
- if err := s.TaskScheduler.ClearRunningTasks(ctx); err != nil {
- return errors.Wrap(err, "failed to clear existing RUNNING tasks before starting the task scheduler")
- }
// runnerWG waits for all goroutines to complete.
if s.profile.DevelopmentUseV2Scheduler {
+ if err := s.TaskSchedulerV2.ClearRunningTaskRuns(ctx); err != nil {
+ return errors.Wrap(err, "failed to clear existing RUNNING tasks before starting the task scheduler")
+ }
s.runnerWG.Add(1)
go s.TaskSchedulerV2.Run(ctx, &s.runnerWG)
} else {
+ if err := s.TaskScheduler.ClearRunningTasks(ctx); err != nil {
+ return errors.Wrap(err, "failed to clear existing RUNNING tasks before starting the task scheduler")
+ }
s.runnerWG.Add(1)
go s.TaskScheduler.Run(ctx, &s.runnerWG)
}