feat(workflow): resume a parked run from a chosen step

Each finished stage records the run's step results; a retry may name a resume
point, and the next attempt skips the steps before it with their results
loaded. A run with a repository resumes only on its pushed branch. The canvas
offers Resume/Re-run from here on parked runs.
This commit is contained in:
sam committed 2026-10-05 13:06:30 +11:00
1 parent 317d3782fa
commit 2d2cf28b2d
37 files changed
+606 -88

No files matched your search

@@ -0,0 +1,21 @@
-- step_executions.results is the run's step results (summary and structured
-- result, by step id) after a stage the run moved past. A resumed attempt
-- starts from the results of the stage before its resume point, so steps it
-- skips still answer {{ steps.<id>.* }}. NULL means the run did not move past
-- the stage.
--
-- tasks.resume_from names the stage the next attempt starts at, and
-- tasks.resume_results the results it starts with. A retry writes both; an
-- empty resume_from runs the workflow from its first stage.
-- +goose Up
ALTER TABLE step_executions ADD COLUMN results jsonb;
ALTER TABLE tasks ADD COLUMN resume_from text NOT NULL DEFAULT '';
ALTER TABLE tasks ADD COLUMN resume_results jsonb NOT NULL DEFAULT '{}';
-- +goose Down
ALTER TABLE tasks DROP COLUMN resume_results;
ALTER TABLE tasks DROP COLUMN resume_from;
ALTER TABLE step_executions DROP COLUMN results;
@@ -24,7 +24,7 @@ func (q *Queries) CallStatusDetail(ctx context.Context, taskID int64) (string, e
const enqueueCallTask = `-- name: EnqueueCallTask :one
WITH caller AS (
SELECT t.id, t.owner, t.repo, t.issue_number, t.title, t.body, t.labels, t.status, t.workflow, t.branch, t.plan, t.notes, t.pr_number, t.tokens_used, t.iterations, t.attempt, t.park_reason, t.watch_comment_id, t.park_class, t.remediation_rounds, t.retry_count, t.source, t.identity, t.binding_id, t.binding_version, t.review_payload, t.workflow_definition_version, t.workflow_definition_digest, t.workflow_definition_yaml, t.created_at, t.updated_at, t.review_cursor, t.inputs, t.org_id, t.workspace_id, t.call_parent_task_id, t.call_depth, t.outputs, t.review_gate, t.rereview_rounds, t.retry_mode FROM tasks t WHERE t.id = $1 FOR UPDATE
SELECT t.id, t.owner, t.repo, t.issue_number, t.title, t.body, t.labels, t.status, t.workflow, t.branch, t.plan, t.notes, t.pr_number, t.tokens_used, t.iterations, t.attempt, t.park_reason, t.watch_comment_id, t.park_class, t.remediation_rounds, t.retry_count, t.source, t.identity, t.binding_id, t.binding_version, t.review_payload, t.workflow_definition_version, t.workflow_definition_digest, t.workflow_definition_yaml, t.created_at, t.updated_at, t.review_cursor, t.inputs, t.org_id, t.workspace_id, t.call_parent_task_id, t.call_depth, t.outputs, t.review_gate, t.rereview_rounds, t.retry_mode, t.resume_from, t.resume_results FROM tasks t WHERE t.id = $1 FOR UPDATE
)
INSERT INTO tasks (owner, repo, issue_number, title, body, labels, workflow, source, identity, org_id, workspace_id, inputs, call_parent_task_id, call_depth)
SELECT
@@ -41,7 +41,7 @@ SELECT
caller.id, caller.call_depth + 1
FROM caller
WHERE caller.status = 'running' AND caller.call_depth + 1 <= $7::int
RETURNING id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode
RETURNING id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results
`
type EnqueueCallTaskParams struct {
@@ -108,6 +108,8 @@ func (q *Queries) EnqueueCallTask(ctx context.Context, arg EnqueueCallTaskParams
&i.ReviewGate,
&i.RereviewRounds,
&i.RetryMode,
&i.ResumeFrom,
&i.ResumeResults,
)
return i, err
}
@@ -361,6 +361,7 @@ type StepExecution struct {
TokensUsed int64
StartedAt pgtype.Timestamptz
FinishedAt pgtype.Timestamptz
Results []byte
}
type SysAudit struct {
@@ -419,6 +420,8 @@ type Task struct {
ReviewGate string
RereviewRounds int64
RetryMode string
ResumeFrom string
ResumeResults []byte
}
type ToolCall struct {
@@ -54,7 +54,7 @@ func (q *Queries) CancelAttemptSteps(ctx context.Context, arg CancelAttemptSteps
const finishStepExecution = `-- name: FinishStepExecution :execrows
UPDATE step_executions
SET status = $1, detail = $2, tokens_used = $3, finished_at = now()
SET status = $1, detail = $2, tokens_used = $3, results = $6, finished_at = now()
WHERE id = $4 AND status = $5
`
@@ -64,6 +64,7 @@ type FinishStepExecutionParams struct {
TokensUsed int64
ID int64
Status_2 string
Results []byte
}
func (q *Queries) FinishStepExecution(ctx context.Context, arg FinishStepExecutionParams) (int64, error) {
@@ -73,6 +74,7 @@ func (q *Queries) FinishStepExecution(ctx context.Context, arg FinishStepExecuti
arg.TokensUsed,
arg.ID,
arg.Status_2,
arg.Results,
)
if err != nil {
return 0, err
@@ -157,6 +159,35 @@ func (q *Queries) InterruptAttemptSteps(ctx context.Context, arg InterruptAttemp
return items, nil
}
const latestStageResults = `-- name: LatestStageResults :one
SELECT status, results FROM step_executions
WHERE execution_id = $1 AND depth = 0 AND kind = 'stage' AND name = $2
AND status IN ('succeeded', 'failed')
ORDER BY attempt DESC, id DESC
LIMIT 1
`
type LatestStageResultsParams struct {
ExecutionID int64
Name string
}
type LatestStageResultsRow struct {
Status string
Results []byte
}
// The most recent finished run of a root stage, across attempts: a resumed
// attempt skips the stages before its resume point, so the last attempt that
// ran this stage may be an earlier one. NULL results mean that run did not
// move past the stage.
func (q *Queries) LatestStageResults(ctx context.Context, arg LatestStageResultsParams) (LatestStageResultsRow, error) {
row := q.db.QueryRow(ctx, latestStageResults, arg.ExecutionID, arg.Name)
var i LatestStageResultsRow
err := row.Scan(&i.Status, &i.Results)
return i, err
}
const listStepExecutions = `-- name: ListStepExecutions :many
SELECT id, execution_id, attempt, parent_id, depth, kind, name, status, detail, tokens_used, started_at, finished_at
FROM step_executions
@@ -316,12 +347,30 @@ SELECT id, org_id, workspace_id, execution_id, attempt, parent_id, depth, kind,
FROM step_executions WHERE id = $1 FOR UPDATE
`
type LockStepExecutionRow struct {
ID int64
OrgID string
WorkspaceID string
ExecutionID int64
Attempt int64
ParentID pgtype.Int8
Depth int32
Kind string
Name string
CalledExecutionID int64
Status string
Detail string
TokensUsed int64
StartedAt pgtype.Timestamptz
FinishedAt pgtype.Timestamptz
}
// FOR UPDATE, shared by a start's parent check and a finish's guarded write:
// the row is held for the caller's transaction, so the state a check reads is
// the state the guarded write sees.
func (q *Queries) LockStepExecution(ctx context.Context, id int64) (StepExecution, error) {
func (q *Queries) LockStepExecution(ctx context.Context, id int64) (LockStepExecutionRow, error) {
row := q.db.QueryRow(ctx, lockStepExecution, id)
var i StepExecution
var i LockStepExecutionRow
err := row.Scan(
&i.ID,
&i.OrgID,
@@ -28,7 +28,7 @@ func (q *Queries) ArchiveTaskDelete(ctx context.Context, arg ArchiveTaskDeletePa
}
const beginRemediationTask = `-- name: BeginRemediationTask :execrows
UPDATE tasks SET status = 'queued', workflow = 'remediate', park_reason = '', park_class = 'needs_human', review_payload = $2, retry_mode = 'continue_pushed_work', updated_at = now()
UPDATE tasks SET status = 'queued', workflow = 'remediate', park_reason = '', park_class = 'needs_human', review_payload = $2, retry_mode = 'continue_pushed_work', resume_from = '', resume_results = '{}', updated_at = now()
WHERE id = $1 AND status = 'pr_open'
`
@@ -51,7 +51,7 @@ func (q *Queries) BeginRemediationTask(ctx context.Context, arg BeginRemediation
const claimByIssue = `-- name: ClaimByIssue :one
UPDATE tasks SET status = 'running', attempt = attempt + 1, outputs = '', updated_at = now()
WHERE owner = $1 AND repo = $2 AND issue_number = $3 AND status = 'queued'
RETURNING id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode
RETURNING id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results
`
type ClaimByIssueParams struct {
@@ -107,6 +107,8 @@ func (q *Queries) ClaimByIssue(ctx context.Context, arg ClaimByIssueParams) (Tas
&i.ReviewGate,
&i.RereviewRounds,
&i.RetryMode,
&i.ResumeFrom,
&i.ResumeResults,
)
return i, err
}
@@ -121,7 +123,7 @@ WHERE id = (
FOR UPDATE SKIP LOCKED
LIMIT 1
)
RETURNING id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode
RETURNING id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results
`
// FOR UPDATE SKIP LOCKED replaces the SQLite single-writer assumption: two
@@ -175,6 +177,8 @@ func (q *Queries) ClaimNextTask(ctx context.Context) (Task, error) {
&i.ReviewGate,
&i.RereviewRounds,
&i.RetryMode,
&i.ResumeFrom,
&i.ResumeResults,
)
return i, err
}
@@ -285,7 +289,7 @@ VALUES (
),
$8
)
RETURNING id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode
RETURNING id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results
`
type InsertChatTaskParams struct {
@@ -360,6 +364,8 @@ func (q *Queries) InsertChatTask(ctx context.Context, arg InsertChatTaskParams)
&i.ReviewGate,
&i.RereviewRounds,
&i.RetryMode,
&i.ResumeFrom,
&i.ResumeResults,
)
return i, err
}
@@ -654,21 +660,26 @@ const retryTask = `-- name: RetryTask :execrows
UPDATE tasks SET status = 'queued', retry_count = retry_count + 1,
workflow = CASE WHEN $1::text = '' THEN workflow ELSE $1::text END,
retry_mode = $2::text,
resume_from = $3::text, resume_results = $4::jsonb,
park_reason = '', park_class = 'needs_human', updated_at = now()
WHERE id = $3 AND status = $4
WHERE id = $5 AND status = $6
`
type RetryTaskParams struct {
Workflow string
RetryMode string
ID int64
FromStatus string
Workflow string
RetryMode string
ResumeFrom string
ResumeResults []byte
ID int64
FromStatus string
}
func (q *Queries) RetryTask(ctx context.Context, arg RetryTaskParams) (int64, error) {
result, err := q.db.Exec(ctx, retryTask,
arg.Workflow,
arg.RetryMode,
arg.ResumeFrom,
arg.ResumeResults,
arg.ID,
arg.FromStatus,
)
@@ -713,7 +724,7 @@ func (q *Queries) StampTaskBinding(ctx context.Context, arg StampTaskBindingPara
}
const taskByID = `-- name: TaskByID :one
SELECT id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode FROM tasks WHERE id = $1
SELECT id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results FROM tasks WHERE id = $1
`
func (q *Queries) TaskByID(ctx context.Context, id int64) (Task, error) {
@@ -761,12 +772,14 @@ func (q *Queries) TaskByID(ctx context.Context, id int64) (Task, error) {
&i.ReviewGate,
&i.RereviewRounds,
&i.RetryMode,
&i.ResumeFrom,
&i.ResumeResults,
)
return i, err
}
const taskByIssue = `-- name: TaskByIssue :one
SELECT id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode FROM tasks WHERE owner = $1 AND repo = $2 AND issue_number = $3
SELECT id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results FROM tasks WHERE owner = $1 AND repo = $2 AND issue_number = $3
`
type TaskByIssueParams struct {
@@ -820,12 +833,14 @@ func (q *Queries) TaskByIssue(ctx context.Context, arg TaskByIssueParams) (Task,
&i.ReviewGate,
&i.RereviewRounds,
&i.RetryMode,
&i.ResumeFrom,
&i.ResumeResults,
)
return i, err
}
const taskByPR = `-- name: TaskByPR :one
SELECT id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode FROM tasks WHERE owner = $1 AND repo = $2 AND pr_number = $3 AND status = $4
SELECT id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results FROM tasks WHERE owner = $1 AND repo = $2 AND pr_number = $3 AND status = $4
`
type TaskByPRParams struct {
@@ -888,6 +903,8 @@ func (q *Queries) TaskByPR(ctx context.Context, arg TaskByPRParams) (Task, error
&i.ReviewGate,
&i.RereviewRounds,
&i.RetryMode,
&i.ResumeFrom,
&i.ResumeResults,
)
return i, err
}
@@ -40,7 +40,7 @@ FROM step_executions WHERE id = $1 FOR UPDATE;
-- name: FinishStepExecution :execrows
UPDATE step_executions
SET status = $1, detail = $2, tokens_used = $3, finished_at = now()
SET status = $1, detail = $2, tokens_used = $3, results = $6, finished_at = now()
WHERE id = $4 AND status = $5;
-- name: CancelAttemptSteps :many
-- The half of CancelExecution that cancels the current attempt's
@@ -87,3 +87,14 @@ ORDER BY attempt, id;
SELECT id, called_execution_id FROM step_executions
WHERE execution_id = $1 AND attempt = $2
AND kind = 'call' AND status IN ('pending', 'running') AND called_execution_id <> 0;
-- name: LatestStageResults :one
-- The most recent finished run of a root stage, across attempts: a resumed
-- attempt skips the stages before its resume point, so the last attempt that
-- ran this stage may be an earlier one. NULL results mean that run did not
-- move past the stage.
SELECT status, results FROM step_executions
WHERE execution_id = $1 AND depth = 0 AND kind = 'stage' AND name = $2
AND status IN ('succeeded', 'failed')
ORDER BY attempt DESC, id DESC
LIMIT 1;
@@ -155,7 +155,7 @@ RETURNING *;
-- A remediation must continue the branch its pull request lives on, so it
-- records that dispatch mode explicitly (taskstate.RetryContinuePushedWork)
-- rather than leaving prepareWorkspace to infer it from the workflow.
UPDATE tasks SET status = 'queued', workflow = 'remediate', park_reason = '', park_class = 'needs_human', review_payload = $2, retry_mode = 'continue_pushed_work', updated_at = now()
UPDATE tasks SET status = 'queued', workflow = 'remediate', park_reason = '', park_class = 'needs_human', review_payload = $2, retry_mode = 'continue_pushed_work', resume_from = '', resume_results = '{}', updated_at = now()
WHERE id = $1 AND status = 'pr_open';
-- name: UpdateReviewPayloadTask :execrows
@@ -176,6 +176,7 @@ WHERE id = @id AND status = @from_status;
UPDATE tasks SET status = 'queued', retry_count = retry_count + 1,
workflow = CASE WHEN @workflow::text = '' THEN workflow ELSE @workflow::text END,
retry_mode = @retry_mode::text,
resume_from = @resume_from::text, resume_results = @resume_results::jsonb,
park_reason = '', park_class = 'needs_human', updated_at = now()
WHERE id = @id AND status = @from_status;
@@ -0,0 +1,93 @@
package postgres_test
import (
"encoding/json"
"errors"
"os"
"testing"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgtest"
"github.com/samcharles93/archie-core/internal/taskstate"
)
func TestMain(m *testing.M) { os.Exit(pgtest.Main(m)) }
// A retry that resumes starts from the results its After stage recorded in
// its last run, and is refused when that run did not move past the stage.
func TestRetryTaskResume(t *testing.T) {
cases := []struct {
name string
resume task.Resume
want string
wantErr error
}{
{name: "after a completed stage", resume: task.Resume{From: "check", After: "analyse"}, want: `{"analyse":{"summary":"found it"}}`},
{name: "from the first stage", resume: task.Resume{From: "analyse"}, want: `{}`},
{name: "after a stage that failed", resume: task.Resume{From: "publish", After: "check"}, wantErr: storecontract.ErrResumeIncomplete},
{name: "after a stage that never ran", resume: task.Resume{From: "publish", After: "nowhere"}, wantErr: storecontract.ErrResumeIncomplete},
{name: "plain retry", want: `{}`},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
ctx := t.Context()
db := pgstore.Open(t)
if _, err := db.EnqueueChatTask(ctx, "", "", "resume", "", "tdd", "", nil); err != nil {
t.Fatal(err)
}
run, err := db.ClaimNext(ctx)
if err != nil || run == nil {
t.Fatalf("claim: %v", err)
}
finish := func(name string, to taskstate.StepStatus, results string) {
id, _, err := db.StartStep(ctx, task.StepStart{ExecutionID: run.ID, Attempt: run.Attempt, Kind: task.StepKindStage, Name: name})
if err != nil {
t.Fatal(err)
}
var raw []byte
if results != "" {
raw = []byte(results)
}
if _, err := db.FinishStep(ctx, task.StepFinish{StepID: id, ExecutionID: run.ID, From: taskstate.StepRunning, To: to, Results: raw}); err != nil {
t.Fatal(err)
}
}
finish("analyse", taskstate.StepSucceeded, `{"analyse":{"summary":"found it"}}`)
finish("check", taskstate.StepFailed, "")
if err := db.ParkTask(ctx, run.ID, taskstate.Running, "stage check failed", taskstate.ParkNeedsHuman); err != nil {
t.Fatal(err)
}
err = db.RetryTask(ctx, run.ID, taskstate.Parked, "", string(taskstate.RetryRefreshOntoBase), tc.resume)
if !errors.Is(err, tc.wantErr) {
t.Fatalf("RetryTask error = %v, want %v", err, tc.wantErr)
}
got, err := db.TaskByID(ctx, run.ID)
if err != nil {
t.Fatal(err)
}
if tc.wantErr != nil {
if got.Status != taskstate.Parked {
t.Fatalf("refused retry left the task %s, want parked", got.Status)
}
return
}
if got.ResumeFrom != tc.resume.From || !sameJSON(t, got.ResumeResults, tc.want) {
t.Fatalf("resume = %q %s, want %q %s", got.ResumeFrom, got.ResumeResults, tc.resume.From, tc.want)
}
})
}
}
func sameJSON(t *testing.T, got []byte, want string) bool {
t.Helper()
var a, b any
if json.Unmarshal(got, &a) != nil || json.Unmarshal([]byte(want), &b) != nil {
return false
}
ga, _ := json.Marshal(a)
gb, _ := json.Marshal(b)
return string(ga) == string(gb)
}
@@ -187,6 +187,7 @@ func (s *Store) FinishStep(ctx context.Context, finish task.StepFinish) (events.
n, err := q.FinishStepExecution(ctx, postgresdb.FinishStepExecutionParams{
Status: string(finish.To), Detail: clip(finish.Detail, 4000), TokensUsed: finish.TokensUsed,
ID: finish.StepID, Status_2: string(finish.From),
Results: finish.Results,
})
if err != nil {
return events.Event{}, err
+26 -1
View File
@@ -99,6 +99,8 @@ func taskFromRow(t postgresdb.Task) *workflow.Task {
ParkReason: t.ParkReason,
RetryCount: int(t.RetryCount),
RetryMode: t.RetryMode,
ResumeFrom: t.ResumeFrom,
ResumeResults: t.ResumeResults,
WatchCommentID: t.WatchCommentID,
ReviewCursor: t.ReviewCursor,
Source: t.Source,
@@ -384,14 +386,37 @@ func (s *Store) Requeue(ctx context.Context, taskID int64, fromStatus, wf string
// transaction, under the same table check Requeue applies. retryMode is the
// operator's worktree choice for the next dispatch; the store persists it
// unread so the daemon's prepareWorkspace reads the mode the operator set.
func (s *Store) RetryTask(ctx context.Context, taskID int64, fromStatus, wf, retryMode string) error {
// A resume copies the results recorded after its After stage onto the row, in
// the same transaction, so the attempt starts from what that stage left.
func (s *Store) RetryTask(ctx context.Context, taskID int64, fromStatus, wf, retryMode string, resume task.Resume) error {
return s.requeue(ctx, taskID, fromStatus, wf, "retried "+wf, func(q *postgresdb.Queries) (int64, error) {
results, err := resumeResults(ctx, q, taskID, resume)
if err != nil {
return 0, err
}
return q.RetryTask(ctx, postgresdb.RetryTaskParams{
ID: taskID, Workflow: wf, FromStatus: fromStatus, RetryMode: retryMode,
ResumeFrom: resume.From, ResumeResults: results,
})
})
}
// resumeResults reads the results a resumed attempt starts with: those of the
// After stage's most recent finished run, which must have completed.
func resumeResults(ctx context.Context, q *postgresdb.Queries, taskID int64, resume task.Resume) ([]byte, error) {
if resume.From == "" || resume.After == "" {
return []byte("{}"), nil
}
row, err := q.LatestStageResults(ctx, postgresdb.LatestStageResultsParams{ExecutionID: taskID, Name: resume.After})
if errors.Is(err, pgx.ErrNoRows) || (err == nil && row.Results == nil) {
return nil, fmt.Errorf("%w: %q", storecontract.ErrResumeIncomplete, resume.After)
}
if err != nil {
return nil, err
}
return row.Results, nil
}
// RespondReviewGate records the operator's gate answer and requeues, counting
// re-reviews against the cap under the row lock.
func (s *Store) RespondReviewGate(ctx context.Context, taskID int64, fromStatus, gate string, rereview bool, maxRounds int) error {