Skip to content

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

feat: task_run attempt for optimistic locking (#7987)

p0ny4a1ccf33d9a9
diff --git a/backend/api/v1/rollout_service.go b/backend/api/v1/rollout_service.go
index fee123a19f..e7d70f334a 100644
--- a/backend/api/v1/rollout_service.go
+++ b/backend/api/v1/rollout_service.go
@@ -514,7 +514,7 @@ func (s *RolloutService) BatchRunTasks(ctx context.Context, request *v1pb.BatchR
})
if err := s.store.CreatePendingTaskRuns(ctx, taskRunCreates...); err != nil {
- return nil, status.Errorf(codes.Internal, "failed to create pending task runs")
+ return nil, status.Errorf(codes.Internal, "failed to create pending task runs, error %v", err)
}
if err := s.activityManager.BatchCreateActivitiesForRunTasks(ctx, tasksToRun, issue, request.Reason, user.ID); err != nil {
diff --git a/backend/migrator/migration/dev/LATEST.sql b/backend/migrator/migration/dev/LATEST.sql
index a9613ab177..85440cc078 100644
--- a/backend/migrator/migration/dev/LATEST.sql
+++ b/backend/migrator/migration/dev/LATEST.sql
@@ -637,6 +637,7 @@ CREATE TABLE task_run (
updater_id INTEGER NOT NULL REFERENCES principal (id),
updated_ts BIGINT NOT NULL DEFAULT extract(epoch from now()),
task_id INTEGER NOT NULL REFERENCES task (id),
+ attempt INTEGER NOT NULL,
name TEXT NOT NULL,
status TEXT NOT NULL CHECK (status IN ('PENDING', 'RUNNING', 'DONE', 'FAILED', 'CANCELED')),
code INTEGER NOT NULL DEFAULT 0,
@@ -646,6 +647,8 @@ CREATE TABLE task_run (
CREATE INDEX idx_task_run_task_id ON task_run(task_id);
+CREATE UNIQUE INDEX uk_task_run_task_id_attempt ON task_run (task_id, attempt);
+
ALTER SEQUENCE task_run_id_seq RESTART WITH 101;
CREATE TRIGGER update_task_run_updated_ts
diff --git a/backend/migrator/migration/prod/2.8/0000##task_run_attempt.sql b/backend/migrator/migration/prod/2.8/0000##task_run_attempt.sql
new file mode 100644
index 0000000000..78f6e07e95
--- /dev/null
+++ b/backend/migrator/migration/prod/2.8/0000##task_run_attempt.sql
@@ -0,0 +1,19 @@
+ALTER TABLE task_run DISABLE TRIGGER update_task_run_updated_ts;
+
+ALTER TABLE task_run ADD COLUMN IF NOT EXISTS attempt INTEGER;
+
+DROP INDEX IF EXISTS uk_task_run_task_id_attempt;
+
+UPDATE task_run
+SET attempt = task_run_group.sequence - 1
+FROM (
+ SELECT id, row_number() over (PARTITION BY task_id ORDER BY id ASC) as sequence
+ FROM task_run ORDER BY id ASC
+) task_run_group
+WHERE task_run.id = task_run_group.id;
+
+ALTER TABLE task_run ALTER COLUMN attempt SET NOT NULL;
+
+CREATE UNIQUE INDEX IF NOT EXISTS uk_task_run_task_id_attempt ON task_run (task_id, attempt);
+
+ALTER TABLE task_run ENABLE TRIGGER update_task_run_updated_ts;
diff --git a/backend/migrator/migration/prod/LATEST.sql b/backend/migrator/migration/prod/LATEST.sql
index cd60d22b01..a768950e9e 100644
--- a/backend/migrator/migration/prod/LATEST.sql
+++ b/backend/migrator/migration/prod/LATEST.sql
@@ -636,6 +636,7 @@ CREATE TABLE task_run (
updater_id INTEGER NOT NULL REFERENCES principal (id),
updated_ts BIGINT NOT NULL DEFAULT extract(epoch from now()),
task_id INTEGER NOT NULL REFERENCES task (id),
+ attempt INTEGER NOT NULL,
name TEXT NOT NULL,
status TEXT NOT NULL CHECK (status IN ('PENDING', 'RUNNING', 'DONE', 'FAILED', 'CANCELED')),
code INTEGER NOT NULL DEFAULT 0,
@@ -645,6 +646,8 @@ CREATE TABLE task_run (
CREATE INDEX idx_task_run_task_id ON task_run(task_id);
+CREATE UNIQUE INDEX uk_task_run_task_id_attempt ON task_run (task_id, attempt);
+
ALTER SEQUENCE task_run_id_seq RESTART WITH 101;
CREATE TRIGGER update_task_run_updated_ts
diff --git a/backend/migrator/migrator_test.go b/backend/migrator/migrator_test.go
index 8397c26937..98c52a0e0a 100644
--- a/backend/migrator/migrator_test.go
+++ b/backend/migrator/migrator_test.go
@@ -241,5 +241,5 @@ func TestMigrationCompatibility(t *testing.T) {
func TestGetCutoffVersion(t *testing.T) {
releaseVersion, err := getProdCutoffVersion()
require.NoError(t, err)
- require.Equal(t, semver.MustParse("2.7.9"), releaseVersion)
+ require.Equal(t, semver.MustParse("2.8.0"), releaseVersion)
}
diff --git a/backend/store/task.go b/backend/store/task.go
index 1117e05ecd..65e2b0a103 100644
--- a/backend/store/task.go
+++ b/backend/store/task.go
@@ -5,7 +5,6 @@ import (
"database/sql"
"fmt"
"strings"
- "time"
"github.com/jackc/pgtype"
"github.com/pkg/errors"
@@ -534,120 +533,6 @@ func (s *Store) UpdateTaskV2(ctx context.Context, patch *api.TaskPatch) (*TaskMe
return task, nil
}
-// UpdateTaskStatusV2 updates the status of a task.
-func (s *Store) UpdateTaskStatusV2(ctx context.Context, patch *api.TaskStatusPatch) (*TaskMessage, error) {
- task, err := s.GetTaskV2ByID(ctx, patch.ID)
- if err != nil {
- return nil, err
- }
- if task == nil {
- return nil, &common.Error{Code: common.NotFound, Err: errors.Errorf("task ID not found: %d", patch.ID)}
- }
-
- tx, err := s.db.BeginTx(ctx, nil)
- if err != nil {
- return nil, err
- }
- defer tx.Rollback()
-
- taskRunFind := &TaskRunFind{
- TaskID: &task.ID,
- StatusList: &[]api.TaskRunStatus{
- api.TaskRunRunning,
- },
- }
- taskRun, err := s.getTaskRunTx(ctx, tx, taskRunFind)
- if err != nil {
- return nil, err
- }
- if taskRun == nil {
- if patch.Status == api.TaskRunning {
- if err := s.createTaskRunImpl(ctx, tx,
- &TaskRunMessage{
- TaskUID: task.ID,
- Name: fmt.Sprintf("%s %d", task.Name, time.Now().Unix()),
- },
- api.TaskRunRunning,
- patch.UpdaterID,
- ); err != nil {
- return nil, err
- }
- }
- } else {
- if patch.Status == api.TaskRunning {
- return nil, errors.Errorf("task is already running: %v", task.Name)
- }
- taskRunStatusPatch := &TaskRunStatusPatch{
- ID: taskRun.ID,
- UpdaterID: patch.UpdaterID,
- Code: patch.Code,
- Result: patch.Result,
- }
- switch patch.Status {
- case api.TaskDone:
- taskRunStatusPatch.Status = api.TaskRunDone
- case api.TaskFailed:
- taskRunStatusPatch.Status = api.TaskRunFailed
- case api.TaskPending, api.TaskPendingApproval:
- // Do nothing.
- case api.TaskCanceled:
- taskRunStatusPatch.Status = api.TaskRunCanceled
- }
- if _, err := s.patchTaskRunStatusImpl(ctx, tx, taskRunStatusPatch); err != nil {
- return nil, err
- }
- }
-
- // Updates the task
- // Build UPDATE clause.
- set, args := []string{"updater_id = $1"}, []any{patch.UpdaterID}
- set, args = append(set, "status = $2"), append(args, patch.Status)
- var payloadSet []string
- if v := patch.Skipped; v != nil {
- payloadSet, args = append(payloadSet, fmt.Sprintf(`jsonb_build_object('skipped', to_jsonb($%d::BOOLEAN))`, len(args)+1)), append(args, *v)
- }
- if v := patch.SkippedReason; v != nil {
- payloadSet, args = append(payloadSet, fmt.Sprintf(`jsonb_build_object('skippedReason', to_jsonb($%d::TEXT))`, len(args)+1)), append(args, *v)
- }
- if len(payloadSet) != 0 {
- set = append(set, fmt.Sprintf(`payload = payload || %s`, strings.Join(payloadSet, "||")))
- }
-
- updatedTask := &TaskMessage{}
- // Execute update query with RETURNING.
- if err := tx.QueryRowContext(ctx, `
- UPDATE task
- SET `+strings.Join(set, ", ")+`
- WHERE id = `+fmt.Sprintf("%d", patch.ID)+`
- RETURNING id, creator_id, created_ts, updater_id, updated_ts, pipeline_id, stage_id, instance_id, database_id, name, status, type, payload, earliest_allowed_ts
- `,
- args...,
- ).Scan(
- &updatedTask.ID,
- &updatedTask.CreatorID,
- &updatedTask.CreatedTs,
- &updatedTask.UpdaterID,
- &updatedTask.UpdatedTs,
- &updatedTask.PipelineID,
- &updatedTask.StageID,
- &updatedTask.InstanceID,
- &updatedTask.DatabaseID,
- &updatedTask.Name,
- &updatedTask.Status,
- &updatedTask.Type,
- &updatedTask.Payload,
- &updatedTask.EarliestAllowedTs,
- ); err != nil {
- return nil, err
- }
-
- if err := tx.Commit(); err != nil {
- return nil, err
- }
-
- return updatedTask, nil
-}
-
// BatchSkipTasks batch skip tasks.
func (s *Store) BatchSkipTasks(ctx context.Context, taskUIDs []int, comment string, updaterUID int) error {
query := `
diff --git a/backend/store/task_run.go b/backend/store/task_run.go
index bbff46e7b7..fb7212532c 100644
--- a/backend/store/task_run.go
+++ b/backend/store/task_run.go
@@ -4,6 +4,7 @@ import (
"context"
"database/sql"
"fmt"
+ "sort"
"strings"
"github.com/pkg/errors"
@@ -215,28 +216,39 @@ func (s *Store) UpdateTaskRunStatus(ctx context.Context, patch *TaskRunStatusPat
// CreatePendingTaskRuns creates pending task runs.
func (s *Store) CreatePendingTaskRuns(ctx context.Context, creates ...*TaskRunMessage) error {
- tx, err := s.db.BeginTx(ctx, &sql.TxOptions{
- Isolation: sql.LevelSerializable,
- })
- if err != nil {
- return errors.Wrapf(err, "failed to begin tx")
+ if len(creates) == 0 {
+ return nil
}
- defer tx.Rollback()
+
+ sort.Slice(creates, func(i, j int) bool {
+ return creates[i].TaskUID < creates[j].TaskUID
+ })
var taskIDs []int
for _, create := range creates {
taskIDs = append(taskIDs, create.TaskUID)
}
+ tx, err := s.db.BeginTx(ctx, nil)
+ if err != nil {
+ return errors.Wrapf(err, "failed to begin tx")
+ }
+ defer tx.Rollback()
+
exist, err := s.checkTaskRunsExist(ctx, tx, taskIDs, []api.TaskRunStatus{api.TaskRunPending, api.TaskRunRunning, api.TaskRunDone})
if err != nil {
return errors.Wrapf(err, "failed to check if task runs exist")
}
if exist {
- return errors.Wrapf(err, "cannot create pending task runs because some of them already exist")
+ return errors.Errorf("cannot create pending task runs because there are pending/running/done task runs")
+ }
+
+ attempts, err := s.getTaskNextAttempt(ctx, tx, taskIDs)
+ if err != nil {
+ return errors.Wrapf(err, "failed to get task next attempt")
}
- if err := s.createPendingTaskRunsTx(ctx, tx, creates...); err != nil {
+ if err := s.createPendingTaskRunsTx(ctx, tx, attempts, creates); err != nil {
return errors.Wrapf(err, "failed to create pending task runs")
}
@@ -247,10 +259,45 @@ func (s *Store) CreatePendingTaskRuns(ctx context.Context, creates ...*TaskRunMe
return nil
}
-func (s *Store) createPendingTaskRunsTx(ctx context.Context, tx *Tx, creates ...*TaskRunMessage) error {
+func (*Store) getTaskNextAttempt(ctx context.Context, tx *Tx, taskIDs []int) ([]int, error) {
+ query := `
+ WITH tasks AS (
+ SELECT id FROM unnest(CAST($1 AS INTEGER[])) AS id
+ )
+ SELECT
+ (SELECT COALESCE(MAX(attempt)+1, 0) FROM task_run WHERE task_run.task_id = tasks.id)
+ FROM tasks ORDER BY tasks.id ASC;
+ `
+
+ rows, err := tx.QueryContext(ctx, query, taskIDs)
+ if err != nil {
+ return nil, errors.Wrap(err, "failed to query")
+ }
+ defer rows.Close()
+
+ var attempts []int
+ for rows.Next() {
+ var attempt int
+ if err := rows.Scan(&attempt); err != nil {
+ return nil, errors.Wrap(err, "failed to scan")
+ }
+ attempts = append(attempts, attempt)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, errors.Wrap(err, "failed to scan rows")
+ }
+
+ return attempts, nil
+}
+
+func (s *Store) createPendingTaskRunsTx(ctx context.Context, tx *Tx, attempts []int, creates []*TaskRunMessage) error {
+ if len(attempts) != len(creates) {
+ return errors.Errorf("length of attempts and creates are different")
+ }
+
// TODO(p0ny): batch create.
- for _, create := range creates {
- if err := s.createTaskRunImpl(ctx, tx, create, api.TaskRunPending, create.CreatorID); err != nil {
+ for i, create := range creates {
+ if err := s.createTaskRunImpl(ctx, tx, create, attempts[i], api.TaskRunPending, create.CreatorID); err != nil {
return err
}
}
@@ -274,20 +321,22 @@ func (*Store) checkTaskRunsExist(ctx context.Context, tx *Tx, taskIDs []int, sta
}
// createTaskRunImpl creates a new taskRun.
-func (*Store) createTaskRunImpl(ctx context.Context, tx *Tx, create *TaskRunMessage, status api.TaskRunStatus, creatorID int) error {
+func (*Store) createTaskRunImpl(ctx context.Context, tx *Tx, create *TaskRunMessage, attempt int, status api.TaskRunStatus, creatorID int) error {
query := `
INSERT INTO task_run (
creator_id,
updater_id,
task_id,
+ attempt,
name,
status
- ) VALUES ($1, $2, $3, $4, $5)
+ ) VALUES ($1, $2, $3, $4, $5, $6)
`
if _, err := tx.ExecContext(ctx, query,
creatorID,
creatorID,
create.TaskUID,
+ attempt,
create.Name,
status,
); err != nil {
@@ -296,19 +345,6 @@ func (*Store) createTaskRunImpl(ctx context.Context, tx *Tx, create *TaskRunMess
return nil
}
-func (s *Store) getTaskRunTx(ctx context.Context, tx *Tx, find *TaskRunFind) (*TaskRunMessage, error) {
- taskRuns, err := s.findTaskRunImpl(ctx, tx, find)
- if err != nil {
- return nil, err
- }
- if len(taskRuns) == 0 {
- return nil, nil
- } else if len(taskRuns) > 1 {
- return nil, &common.Error{Code: common.Conflict, Err: errors.Errorf("found %d task runs with filter %+v, expect 1", len(taskRuns), find)}
- }
- return taskRuns[0], nil
-}
-
// patchTaskRunStatusImpl updates a taskRun status. Returns the new state of the taskRun after update.
func (*Store) patchTaskRunStatusImpl(ctx context.Context, tx *Tx, patch *TaskRunStatusPatch) (*TaskRunMessage, error) {
set, args := []string{"updater_id = $1"}, []any{patch.UpdaterID}