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

+14 -3
View File
@@ -1732,7 +1732,9 @@ type ApplyOperatorTaskActionRequest struct {
// (taskstate.RetryMode): refresh onto the base branch or continue the work
// already pushed on the task's branch. It is empty for every other action,
// and chat carries no mode syntax -- an empty value means refresh_onto_base.
RetryMode string `protobuf:"bytes,8,opt,name=retry_mode,json=retryMode,proto3" json:"retry_mode,omitempty"`
RetryMode string `protobuf:"bytes,8,opt,name=retry_mode,json=retryMode,proto3" json:"retry_mode,omitempty"`
// resume_from is the stage a retry starts at; empty runs every stage.
ResumeFrom string `protobuf:"bytes,9,opt,name=resume_from,json=resumeFrom,proto3" json:"resume_from,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
@@ -1823,6 +1825,13 @@ func (x *ApplyOperatorTaskActionRequest) GetRetryMode() string {
return ""
}
func (x *ApplyOperatorTaskActionRequest) GetResumeFrom() string {
if x != nil {
return x.ResumeFrom
}
return ""
}
type ApplyOperatorTaskActionResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
TaskId int64 `protobuf:"varint,1,opt,name=task_id,json=taskId,proto3" json:"task_id,omitempty"`
@@ -3056,7 +3065,7 @@ const file_gateway_v1_chat_proto_rawDesc = "" +
"\x17ApplyTaskActionResponse\x12\x17\n" +
"\atask_id\x18\x01 \x01(\x03R\x06taskId\x12\x16\n" +
"\x06action\x18\x02 \x01(\tR\x06action\x12\x18\n" +
"\amessage\x18\x03 \x01(\tR\amessage\"\x8d\x02\n" +
"\amessage\x18\x03 \x01(\tR\amessage\"\xae\x02\n" +
"\x1eApplyOperatorTaskActionRequest\x12\x17\n" +
"\atask_id\x18\x01 \x01(\x03R\x06taskId\x12\x16\n" +
"\x06action\x18\x02 \x01(\tR\x06action\x12\x19\n" +
@@ -3067,7 +3076,9 @@ const file_gateway_v1_chat_proto_rawDesc = "" +
"\finstructions\x18\x06 \x01(\tR\finstructions\x12\x1a\n" +
"\bfindings\x18\a \x03(\tR\bfindings\x12\x1d\n" +
"\n" +
"retry_mode\x18\b \x01(\tR\tretryMode\"l\n" +
"retry_mode\x18\b \x01(\tR\tretryMode\x12\x1f\n" +
"\vresume_from\x18\t \x01(\tR\n" +
"resumeFrom\"l\n" +
"\x1fApplyOperatorTaskActionResponse\x12\x17\n" +
"\atask_id\x18\x01 \x01(\x03R\x06taskId\x12\x16\n" +
"\x06action\x18\x02 \x01(\tR\x06action\x12\x18\n" +
+67 -15
View File
@@ -1743,7 +1743,11 @@ type Task struct {
// action writes it and the daemon's prepareWorkspace reads it, so it must
// cross the wire for a retry to land on the source the operator chose. The
// empty string reads as refresh_onto_base.
RetryMode string `protobuf:"bytes,41,opt,name=retry_mode,json=retryMode,proto3" json:"retry_mode,omitempty"`
RetryMode string `protobuf:"bytes,41,opt,name=retry_mode,json=retryMode,proto3" json:"retry_mode,omitempty"`
// resume_from is the stage the next attempt starts at; empty runs every
// stage. resume_results are the step results (JSON) it starts with.
ResumeFrom string `protobuf:"bytes,42,opt,name=resume_from,json=resumeFrom,proto3" json:"resume_from,omitempty"`
ResumeResults []byte `protobuf:"bytes,43,opt,name=resume_results,json=resumeResults,proto3" json:"resume_results,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
@@ -2066,6 +2070,20 @@ func (x *Task) GetRetryMode() string {
return ""
}
func (x *Task) GetResumeFrom() string {
if x != nil {
return x.ResumeFrom
}
return ""
}
func (x *Task) GetResumeResults() []byte {
if x != nil {
return x.ResumeResults
}
return nil
}
// Event mirrors internal/events.Event. Data is carried as a JSON object
// string (matching the store's own on-disk representation) rather than
// google.protobuf.Struct, to stay a direct mirror of the existing column.
@@ -3995,12 +4013,15 @@ type FinishStepRequest struct {
// execution_id names the run the step belongs to. The grant check verifies
// it against the credential, and the store verifies the step really is that
// execution's, so a caller cannot move another run's step by naming it.
ExecutionId int64 `protobuf:"varint,1,opt,name=execution_id,json=executionId,proto3" json:"execution_id,omitempty"`
StepId int64 `protobuf:"varint,2,opt,name=step_id,json=stepId,proto3" json:"step_id,omitempty"`
From string `protobuf:"bytes,3,opt,name=from,proto3" json:"from,omitempty"`
To string `protobuf:"bytes,4,opt,name=to,proto3" json:"to,omitempty"`
Detail string `protobuf:"bytes,5,opt,name=detail,proto3" json:"detail,omitempty"`
TokensUsed int64 `protobuf:"varint,6,opt,name=tokens_used,json=tokensUsed,proto3" json:"tokens_used,omitempty"`
ExecutionId int64 `protobuf:"varint,1,opt,name=execution_id,json=executionId,proto3" json:"execution_id,omitempty"`
StepId int64 `protobuf:"varint,2,opt,name=step_id,json=stepId,proto3" json:"step_id,omitempty"`
From string `protobuf:"bytes,3,opt,name=from,proto3" json:"from,omitempty"`
To string `protobuf:"bytes,4,opt,name=to,proto3" json:"to,omitempty"`
Detail string `protobuf:"bytes,5,opt,name=detail,proto3" json:"detail,omitempty"`
TokensUsed int64 `protobuf:"varint,6,opt,name=tokens_used,json=tokensUsed,proto3" json:"tokens_used,omitempty"`
// results is the run's step results (JSON, by step id) after a stage the
// run moves past; empty otherwise. A resumed attempt starts from them.
Results []byte `protobuf:"bytes,7,opt,name=results,proto3" json:"results,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
@@ -4077,6 +4098,13 @@ func (x *FinishStepRequest) GetTokensUsed() int64 {
return 0
}
func (x *FinishStepRequest) GetResults() []byte {
if x != nil {
return x.Results
}
return nil
}
type FinishStepResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
// event is the transition's stage_finish row, already persisted.
@@ -5214,7 +5242,11 @@ type RetryTaskRequest struct {
Workflow string `protobuf:"bytes,3,opt,name=workflow,proto3" json:"workflow,omitempty"`
// retry_mode is the operator's worktree choice (taskstate.RetryMode) the
// requeue persists. Empty reads as refresh_onto_base.
RetryMode string `protobuf:"bytes,4,opt,name=retry_mode,json=retryMode,proto3" json:"retry_mode,omitempty"`
RetryMode string `protobuf:"bytes,4,opt,name=retry_mode,json=retryMode,proto3" json:"retry_mode,omitempty"`
// resume_from is the stage the attempt starts at, and resume_after the
// stage before it whose recorded results it starts with (task.Resume).
ResumeFrom string `protobuf:"bytes,5,opt,name=resume_from,json=resumeFrom,proto3" json:"resume_from,omitempty"`
ResumeAfter string `protobuf:"bytes,6,opt,name=resume_after,json=resumeAfter,proto3" json:"resume_after,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
@@ -5277,6 +5309,20 @@ func (x *RetryTaskRequest) GetRetryMode() string {
return ""
}
func (x *RetryTaskRequest) GetResumeFrom() string {
if x != nil {
return x.ResumeFrom
}
return ""
}
func (x *RetryTaskRequest) GetResumeAfter() string {
if x != nil {
return x.ResumeAfter
}
return ""
}
type RetryTaskResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
unknownFields protoimpl.UnknownFields
@@ -13008,8 +13054,7 @@ const file_state_v1_state_proto_rawDesc = "" +
"\x06tokens\x18\x01 \x03(\v2\x17.state.v1.PersonalTokenR\x06tokens\",\n" +
"\x1aRevokePersonalTokenRequest\x12\x0e\n" +
"\x02id\x18\x01 \x01(\tR\x02id\"\x1d\n" +
"\x1bRevokePersonalTokenResponse\"\xea\n" +
"\n" +
"\x1bRevokePersonalTokenResponse\"\xb2\v\n" +
"\x04Task\x12\x0e\n" +
"\x02id\x18\x01 \x01(\x03R\x02id\x12\x14\n" +
"\x05owner\x18\x02 \x01(\tR\x05owner\x12\x12\n" +
@@ -13065,7 +13110,10 @@ const file_state_v1_state_proto_rawDesc = "" +
"reviewGate\x12'\n" +
"\x0frereview_rounds\x18( \x01(\x03R\x0erereviewRounds\x12\x1d\n" +
"\n" +
"retry_mode\x18) \x01(\tR\tretryMode\"\xf8\x02\n" +
"retry_mode\x18) \x01(\tR\tretryMode\x12\x1f\n" +
"\vresume_from\x18* \x01(\tR\n" +
"resumeFrom\x12%\n" +
"\x0eresume_results\x18+ \x01(\fR\rresumeResults\"\xf8\x02\n" +
"\x05Event\x12\x0e\n" +
"\x02id\x18\x01 \x01(\x03R\x02id\x12*\n" +
"\x02at\x18\x02 \x01(\v2\x1a.google.protobuf.TimestampR\x02at\x12\x12\n" +
@@ -13237,7 +13285,7 @@ const file_state_v1_state_proto_rawDesc = "" +
"\x13called_execution_id\x18\x06 \x01(\x03R\x11calledExecutionId\"S\n" +
"\x11StartStepResponse\x12\x17\n" +
"\astep_id\x18\x01 \x01(\x03R\x06stepId\x12%\n" +
"\x05event\x18\x02 \x01(\v2\x0f.state.v1.EventR\x05event\"\xac\x01\n" +
"\x05event\x18\x02 \x01(\v2\x0f.state.v1.EventR\x05event\"\xc6\x01\n" +
"\x11FinishStepRequest\x12!\n" +
"\fexecution_id\x18\x01 \x01(\x03R\vexecutionId\x12\x17\n" +
"\astep_id\x18\x02 \x01(\x03R\x06stepId\x12\x12\n" +
@@ -13245,7 +13293,8 @@ const file_state_v1_state_proto_rawDesc = "" +
"\x02to\x18\x04 \x01(\tR\x02to\x12\x16\n" +
"\x06detail\x18\x05 \x01(\tR\x06detail\x12\x1f\n" +
"\vtokens_used\x18\x06 \x01(\x03R\n" +
"tokensUsed\";\n" +
"tokensUsed\x12\x18\n" +
"\aresults\x18\a \x01(\fR\aresults\";\n" +
"\x12FinishStepResponse\x12%\n" +
"\x05event\x18\x01 \x01(\v2\x0f.state.v1.EventR\x05event\"Y\n" +
"\x16CancelExecutionRequest\x12\x17\n" +
@@ -13320,14 +13369,17 @@ const file_state_v1_state_proto_rawDesc = "" +
"fromStatus\x12%\n" +
"\x05audit\x18\x03 \x01(\v2\x0f.state.v1.EventR\x05audit\"0\n" +
"\x13ArchiveTaskResponse\x12\x19\n" +
"\bevent_id\x18\x01 \x01(\x03R\aeventId\"\x87\x01\n" +
"\bevent_id\x18\x01 \x01(\x03R\aeventId\"\xcb\x01\n" +
"\x10RetryTaskRequest\x12\x17\n" +
"\atask_id\x18\x01 \x01(\x03R\x06taskId\x12\x1f\n" +
"\vfrom_status\x18\x02 \x01(\tR\n" +
"fromStatus\x12\x1a\n" +
"\bworkflow\x18\x03 \x01(\tR\bworkflow\x12\x1d\n" +
"\n" +
"retry_mode\x18\x04 \x01(\tR\tretryMode\"\x13\n" +
"retry_mode\x18\x04 \x01(\tR\tretryMode\x12\x1f\n" +
"\vresume_from\x18\x05 \x01(\tR\n" +
"resumeFrom\x12!\n" +
"\fresume_after\x18\x06 \x01(\tR\vresumeAfter\"\x13\n" +
"\x11RetryTaskResponse\"\x96\x01\n" +
"\x18RespondReviewGateRequest\x12\x17\n" +
"\atask_id\x18\x01 \x01(\x03R\x06taskId\x12\x1f\n" +
@@ -86,9 +86,11 @@ type TaskArchiver interface {
// TaskRetryer atomically requeues recoverable work and accounts for the new
// attempt so a partial write cannot evade the retry cap. retryMode is the
// operator's worktree choice for the next dispatch (taskstate.RetryMode),
// persisted on the row so the daemon reads it instead of inferring it.
// persisted on the row so the daemon reads it instead of inferring it. resume
// is where the attempt starts; a resume whose After stage did not complete in
// its last run is refused with ErrResumeIncomplete.
type TaskRetryer interface {
RetryTask(ctx context.Context, taskID int64, fromStatus, workflow, retryMode string) error
RetryTask(ctx context.Context, taskID int64, fromStatus, workflow, retryMode string, resume task.Resume) error
}
// ReviewGateResponder records the operator's review-gate answer. A re-review
@@ -401,6 +403,9 @@ var (
// store does not record or a step whose identifying fields do not resolve.
// Distinct from the transition sentinels, which cover a row's state.
ErrInvalidStep = errors.New("store: invalid step execution request")
// ErrResumeIncomplete is returned when a retry resumes after a stage whose
// last run did not complete, so there are no results to start from.
ErrResumeIncomplete = errors.New("store: the step before the resume point did not complete in its last run")
// ErrBindingNotFound is returned when a binding ID does not exist.
ErrBindingNotFound = errors.New("store: binding not found")
// ErrBindingOverlap is returned when a binding's matcher overlaps an
+60 -2
View File
@@ -5,9 +5,11 @@ import (
"context"
"errors"
"fmt"
"slices"
"strings"
"github.com/samcharles93/archie-core/internal/domain/identity"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
workflowtask "github.com/samcharles93/archie-core/internal/domain/workflow/task"
"github.com/samcharles93/archie-core/internal/events"
"github.com/samcharles93/archie-core/internal/taskstate"
@@ -43,6 +45,9 @@ type Task struct {
// service reads it to refuse a re-review at the cap before the guarded
// write, and the write itself re-checks it in the row.
RereviewRounds int
// Stages are the pinned definition's stage names in order, the resume
// points a retry may name.
Stages []string
// Attempt is the run the operator acted on. It is stamped onto the event
// this action records so an intervention is attributable to the run it
// changed course -- without it a retry or a stop is indistinguishable
@@ -66,6 +71,9 @@ type ActionPayload struct {
// task's branch. It is empty -- the explicit default, refresh -- for every
// other action.
RetryMode taskstate.RetryMode
// ResumeFrom is the stage a retry starts at, keeping the results of the
// stages before it. Empty runs every stage.
ResumeFrom string
}
// Actor is who performed an action and the principal whose authority allowed
@@ -169,7 +177,7 @@ type Store interface {
Requeue(context.Context, int64, string, string) error
// RetryTask requeues a parked task, records the operator's worktree mode
// for the next dispatch and increments retry_count in one guarded write.
RetryTask(context.Context, int64, string, string, string) error
RetryTask(context.Context, int64, string, string, string, workflowtask.Resume) error
// RespondReviewGate is the guarded review gate response write
// (internal/domain/storecontract.ReviewGateResponder): it records the
// answered document, and for a re-review increments rereview_rounds and
@@ -376,6 +384,17 @@ func (s Service) applyRetry(ctx context.Context, task *Task, actor Actor, o outc
if !ok {
return o, fmt.Errorf("unknown retry mode %q: %w", requested, ErrConflict)
}
resume, err := resumePoint(task.Stages, payload.ResumeFrom)
if err != nil {
return o, fmt.Errorf("%w: %w", err, ErrConflict)
}
// The skipped steps' work must be on the branch the attempt continues.
if resume.From != "" && task.Owner != "" {
if strings.TrimSpace(task.Branch) == "" {
return o, fmt.Errorf("resuming from %q needs the earlier steps' work pushed, and task %d has no pushed branch: %w", resume.From, task.ID, ErrConflict)
}
mode = taskstate.RetryContinuePushedWork
}
if mode == taskstate.RetryContinuePushedWork && strings.TrimSpace(task.Branch) == "" {
return o, fmt.Errorf("task %d has no pushed branch to continue: %w", task.ID, ErrConflict)
}
@@ -393,12 +412,51 @@ func (s Service) applyRetry(ctx context.Context, task *Task, actor Actor, o outc
}
return o, fmt.Errorf("%w: %s", ErrConflict, reason)
}
err := s.Store.RetryTask(ctx, task.ID, "parked", "", string(mode))
err = s.Store.RetryTask(ctx, task.ID, "parked", "", string(mode), resume)
if errors.Is(err, storecontract.ErrResumeIncomplete) {
err = fmt.Errorf("%q did not complete in its last run, so there is nothing to resume from: %w", resume.After, ErrConflict)
}
o.event.Kind, o.event.Detail = events.KindTaskRetried, actor.describe("retried")
o.event.Data = map[string]any{"retry_count": task.RetryCount + 1, "previous_reason": task.ParkReason, "retry_mode": string(mode)}
if resume.From != "" {
o.event.Data["resume_from"] = resume.From
}
return o, err
}
// resumePoint resolves a resume stage against the pinned definition's stages.
// Stage names are how runs are recorded, so a name two stages share cannot
// say which one to resume.
func resumePoint(stages []string, from string) (workflowtask.Resume, error) {
if from == "" {
return workflowtask.Resume{}, nil
}
at := slices.Index(stages, from)
if at < 0 {
return workflowtask.Resume{}, fmt.Errorf("the pinned workflow has no step %q", from)
}
resume := workflowtask.Resume{From: from}
if at > 0 {
resume.After = stages[at-1]
}
for _, name := range []string{resume.From, resume.After} {
if name != "" && countOf(stages, name) > 1 {
return workflowtask.Resume{}, fmt.Errorf("several steps run as %q; give each an id to resume there", name)
}
}
return resume, nil
}
func countOf(stages []string, name string) int {
n := 0
for _, stage := range stages {
if stage == name {
n++
}
}
return n
}
func (s Service) applyStop(ctx context.Context, task *Task, actor Actor, o outcome) (outcome, error) {
if s.CancelTask == nil {
return o, ErrUnavailable
+14
View File
@@ -96,6 +96,20 @@ func ParseDefinition(src string, registry StepRegistry) (YAMLDefinition, error)
return definition, nil
}
// StageNames returns the names a definition's steps run under, in order. It
// reads a definition already pinned, so it decodes without validating.
func StageNames(src string) ([]string, error) {
var definition YAMLDefinition
if err := yaml.Unmarshal([]byte(src), &definition); err != nil {
return nil, fmt.Errorf("parse workflow YAML: %w", err)
}
names := make([]string, len(definition.Steps))
for i, step := range definition.Steps {
names[i] = step.StageName()
}
return names, nil
}
// ParseAndCompile validates and compiles one definition in a single operation.
func ParseAndCompile(src string, registry StepRegistry) (Workflow, error) {
definition, err := ParseDefinition(src, registry)
+4 -2
View File
@@ -33,7 +33,8 @@ steps:
type: gate.repository
settings:
expect: test-failure
- type: repo.commit
- id: commit-repro
type: repo.commit
settings:
message: "test: failing repro"
reference: Refs
@@ -53,7 +54,8 @@ steps:
</analysis>
The full quality gate must pass. Make the smallest fix that makes the repro tests pass without changing them. Call finish with status "passed" and a summary for the PR reviewer: root cause, the fix, and verification.
- type: repo.commit
- id: commit-fix
type: repo.commit
settings:
message: "fix: {{ task.title }} (archie)"
reference: Fixes
+16 -6
View File
@@ -171,7 +171,7 @@ func compileStep(step StepRecord, registry StepRegistry) (Stage, error) {
return Stage{}, fmt.Errorf("build workflow step %q: %w", step.Type, err)
}
// Settings are built per run, with every reference resolved.
return wrapStep(step, step.Type, func(ctx context.Context, tc *TaskContext) error {
return wrapStep(step, func(ctx context.Context, tc *TaskContext) error {
stage, err := factory(renderSettings(step.Settings, tc))
if err != nil {
return fmt.Errorf("step %q settings: %w", step.Type, err)
@@ -180,12 +180,22 @@ func compileStep(step StepRecord, registry StepRegistry) (Stage, error) {
}), nil
}
// StageName is the name a step runs and is recorded under: its id, else its
// type, else "parallel".
func (step StepRecord) StageName() string {
switch {
case step.ID != "":
return step.ID
case step.Parallel != nil:
return "parallel"
}
return step.Type
}
// wrapStep applies the controls every step shares around its body: when,
// retry, and recording its result under its id.
func wrapStep(step StepRecord, name string, body func(context.Context, *TaskContext) error) Stage {
if step.ID != "" {
name = step.ID
}
func wrapStep(step StepRecord, body func(context.Context, *TaskContext) error) Stage {
name := step.StageName()
// ParseDefinition has already refused a condition or backoff that does
// not parse.
when, _ := parseCondition(step.When)
@@ -241,7 +251,7 @@ func compileParallel(step StepRecord, registry StepRegistry) (Stage, error) {
branches[i] = append(branches[i], stage)
}
}
return wrapStep(step, "parallel", func(ctx context.Context, tc *TaskContext) error {
return wrapStep(step, func(ctx context.Context, tc *TaskContext) error {
clones := make([]*TaskContext, len(branches))
errs := make([]error, len(branches))
var wg sync.WaitGroup
+11
View File
@@ -60,6 +60,17 @@ type StepFinish struct {
// TokensUsed is the usage the step itself accounted. Stages record none;
// the agent runtime records its own calls' usage.
TokensUsed int64
// Results is the run's step results as JSON after a stage the run moves
// past; nil otherwise. A resumed attempt starts from them.
Results []byte
}
// Resume is where a retried attempt starts: at stage From, with the results
// recorded after stage After, the one before it. After is empty when From is
// the first stage. An empty From runs the workflow from its first stage.
type Resume struct {
From string
After string
}
// StepExecution is one recorded step: ListSteps' read, the dashboard run
+5
View File
@@ -64,6 +64,11 @@ type Task struct {
// RetryMode is the worktree mode for the next dispatch; empty means
// RefreshOntoBase.
RetryMode string `json:"retry_mode"`
// ResumeFrom is the stage this attempt starts at; empty runs every stage.
// ResumeResults are the step results (JSON, by step id) the attempt starts
// with, so steps it skips still answer their references.
ResumeFrom string `json:"resume_from,omitempty"`
ResumeResults json.RawMessage `json:"resume_results,omitempty"`
// WatchCommentID is the poll backstop's high-water mark over forge
// review-comment IDs for this task (pr-review-remediation.md decision
// 2's persisted per-task cursor; the comment-watch design it was
+41 -2
View File
@@ -3,10 +3,12 @@ package workflow
import (
"context"
"encoding/json"
"fmt"
"log/slog"
"maps"
"regexp"
"slices"
"strings"
"time"
"unicode/utf8"
@@ -301,7 +303,12 @@ func Run(ctx context.Context, wf Workflow, tc *TaskContext) {
tc.runInterface, tc.runInterfaceSet = wf.Interface, true
log := tc.Log.With("workflow", wf.Name, "repo", tc.Repo.FullName(), "issue", t.IssueNumber)
for _, stage := range wf.Stages {
stages, err := tc.resumeStages(wf.Stages)
if err != nil {
park(ctx, tc, err.Error())
return
}
for _, stage := range stages {
tc.Stage = stage.Name
if err := tc.Store.Update(ctx, t); err != nil {
park(ctx, tc, fmt.Sprintf("persist task before stage %s: %v", stage.Name, err))
@@ -359,7 +366,7 @@ func Run(ctx context.Context, wf Workflow, tc *TaskContext) {
// failed recording write parks the execution, like a failed start.
finishEvent, recordErr := tc.Store.FinishStep(ctx, StepFinish{
StepID: stepID, ExecutionID: t.ID,
From: taskstate.StepRunning, To: finishTo, Detail: finishDetail,
From: taskstate.StepRunning, To: finishTo, Detail: finishDetail, Results: tc.resultsAfter(stage, err),
})
if recordErr != nil {
stageLog.Error("stage finish could not be recorded", "stage", stage.Name, "err", recordErr)
@@ -377,6 +384,38 @@ func Run(ctx context.Context, wf Workflow, tc *TaskContext) {
finish(ctx, tc, log)
}
// resultsAfter is what a stage records for a later attempt resumed after it:
// the results so far when the run moves past the stage, else nothing.
func (tc *TaskContext) resultsAfter(stage Stage, err error) []byte {
if err != nil && !stage.ContinueOnFailure {
return nil
}
// StepResult holds strings and decoded JSON values, which always marshal.
results, _ := json.Marshal(tc.stepResults)
return results
}
// resumeStages returns the stages this attempt runs: all of them, or those
// from the task's resume point on, with the results the stages before it
// recorded loaded so their references still resolve.
func (tc *TaskContext) resumeStages(stages []Stage) ([]Stage, error) {
from := tc.Task.ResumeFrom
if from == "" {
return stages, nil
}
at := slices.IndexFunc(stages, func(s Stage) bool { return s.Name == from })
if at < 0 {
return nil, fmt.Errorf("resume point %q is not a step of this workflow", from)
}
if len(tc.Task.ResumeResults) > 0 {
if err := json.Unmarshal(tc.Task.ResumeResults, &tc.stepResults); err != nil {
return nil, fmt.Errorf("resume results: %w", err)
}
}
tc.Log.Info("resuming", "from", from, "skipped", at)
return stages[at:], nil
}
// endsRun applies a recorded stage's result: a failure parks unless the stage
// continues on failure, and an outcome finishes the run.
func endsRun(ctx context.Context, tc *TaskContext, stage Stage, err error, log, stageLog *slog.Logger) bool {
@@ -103,6 +103,7 @@ func (c *Client) ApplyOperatorTaskAction(ctx context.Context, actor taskactions.
Instructions: res.Instructions,
Findings: res.Findings,
RetryMode: string(res.RetryMode),
ResumeFrom: res.ResumeFrom,
})
if err != nil {
return messaging.TaskActionResult{}, taskActionError(err)
@@ -112,6 +112,7 @@ func (s *server) ApplyOperatorTaskAction(ctx context.Context, r *pb.ApplyOperato
Instructions: r.Instructions,
Findings: r.Findings,
RetryMode: taskstate.RetryMode(r.RetryMode),
ResumeFrom: r.ResumeFrom,
})
if err != nil {
return nil, taskActionStatus(err)
@@ -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 {
+6 -3
View File
@@ -150,7 +150,7 @@ func (c *Client) CancelExecution(ctx context.Context, taskID int64, reason, to s
func (c *Client) FinishStep(ctx context.Context, s task.StepFinish) (events.Event, error) {
r, err := c.client.FinishStep(ctx, &pb.FinishStepRequest{
ExecutionId: s.ExecutionID, StepId: s.StepID,
From: string(s.From), To: string(s.To), Detail: s.Detail, TokensUsed: s.TokensUsed,
From: string(s.From), To: string(s.To), Detail: s.Detail, TokensUsed: s.TokensUsed, Results: s.Results,
})
if err != nil {
return events.Event{}, unmapError(err)
@@ -207,8 +207,11 @@ func (c *Client) ArchiveTask(ctx context.Context, taskID int64, fromStatus strin
return r.EventId, nil
}
func (c *Client) RetryTask(ctx context.Context, taskID int64, fromStatus, wf, retryMode string) error {
_, err := c.client.RetryTask(ctx, &pb.RetryTaskRequest{TaskId: taskID, FromStatus: fromStatus, Workflow: wf, RetryMode: retryMode})
func (c *Client) RetryTask(ctx context.Context, taskID int64, fromStatus, wf, retryMode string, resume task.Resume) error {
_, err := c.client.RetryTask(ctx, &pb.RetryTaskRequest{
TaskId: taskID, FromStatus: fromStatus, Workflow: wf, RetryMode: retryMode,
ResumeFrom: resume.From, ResumeAfter: resume.After,
})
return unmapError(err)
}
+2 -2
View File
@@ -252,7 +252,7 @@ func (s *server) FinishStep(ctx context.Context, r *pb.FinishStepRequest) (*pb.F
event, err := s.deps.Steps.FinishStep(ctx, task.StepFinish{
StepID: r.StepId, ExecutionID: r.ExecutionId,
From: taskstate.StepStatus(r.From), To: taskstate.StepStatus(r.To),
Detail: r.Detail, TokensUsed: r.TokensUsed,
Detail: r.Detail, TokensUsed: r.TokensUsed, Results: r.Results,
})
if err != nil {
return nil, s.logErr("FinishStep", err)
@@ -335,7 +335,7 @@ func (s *server) ArchiveTask(ctx context.Context, r *pb.ArchiveTaskRequest) (*pb
}
func (s *server) RetryTask(ctx context.Context, r *pb.RetryTaskRequest) (*pb.RetryTaskResponse, error) {
if err := s.deps.Tasks.RetryTask(ctx, r.TaskId, r.FromStatus, r.Workflow, r.RetryMode); err != nil {
if err := s.deps.Tasks.RetryTask(ctx, r.TaskId, r.FromStatus, r.Workflow, r.RetryMode, task.Resume{From: r.ResumeFrom, After: r.ResumeAfter}); err != nil {
return nil, s.logErr("RetryTask", err)
}
return &pb.RetryTaskResponse{}, nil
+5 -2
View File
@@ -64,7 +64,8 @@ func taskProto(t *task.Task) *pb.Task { //nolint:dupl // mirror-image field-by-f
Workflow: t.Workflow, Branch: t.Branch, Plan: t.Plan, Notes: t.Notes,
PrNumber: int64(t.PRNumber), TokensUsed: int64(t.TokensUsed), Iterations: int64(t.Iterations),
Attempt: int64(t.Attempt), ParkReason: t.ParkReason, RetryCount: int64(t.RetryCount),
RetryMode: t.RetryMode,
RetryMode: t.RetryMode,
ResumeFrom: t.ResumeFrom, ResumeResults: t.ResumeResults,
WatchCommentId: t.WatchCommentID, Source: t.Source, Identity: t.Identity,
BindingId: t.BindingID, BindingVersion: int64(t.BindingVersion),
InputsJson: inputsJSON(t.Inputs),
@@ -95,7 +96,8 @@ func taskValue(t *pb.Task) *task.Task { //nolint:dupl // see taskProto above
Workflow: t.Workflow, Branch: t.Branch, Plan: t.Plan, Notes: t.Notes,
PRNumber: int(t.PrNumber), TokensUsed: int(t.TokensUsed), Iterations: int(t.Iterations),
Attempt: int(t.Attempt), ParkReason: t.ParkReason, RetryCount: int(t.RetryCount),
RetryMode: t.RetryMode,
RetryMode: t.RetryMode,
ResumeFrom: t.ResumeFrom, ResumeResults: t.ResumeResults,
WatchCommentID: t.WatchCommentId, Source: t.Source, Identity: t.Identity,
BindingID: t.BindingId, BindingVersion: int(t.BindingVersion),
Inputs: inputsValue(t.InputsJson),
@@ -482,6 +484,7 @@ var wireErrors = []struct {
{access.ErrPolicyLockout, codes.FailedPrecondition, access.ErrPolicyLockout.Error()},
{storecontract.ErrIllegalTransition, codes.FailedPrecondition, msgIllegalTransition},
{storecontract.ErrInvalidStep, codes.InvalidArgument, msgInvalidStep},
{storecontract.ErrResumeIncomplete, codes.FailedPrecondition, storecontract.ErrResumeIncomplete.Error()},
{storecontract.ErrBindingOverlap, codes.FailedPrecondition, msgBindingOverlap},
{storecontract.ErrBindingTransition, codes.FailedPrecondition, msgBindingTransition},
{storecontract.ErrSourceSigningStale, codes.FailedPrecondition, msgSourceSigning},
@@ -35,6 +35,7 @@ type actionRequest struct {
Instructions string `json:"instructions,omitempty"`
Findings []string `json:"findings,omitempty"`
RetryMode taskstate.RetryMode `json:"retry_mode,omitempty"`
ResumeFrom string `json:"resume_from,omitempty"`
}
type actorPayload struct {
@@ -120,6 +121,7 @@ func Register(nc *nats.Conn, service taskactions.Service, log *slog.Logger) (fun
Instructions: req.Instructions,
Findings: req.Findings,
RetryMode: req.RetryMode,
ResumeFrom: req.ResumeFrom,
})
natsrpc.Respond(msg, log, "taskactions", actionResponse{
Envelope: natsrpc.NewEnvelope(err),
@@ -153,6 +155,7 @@ func (c Client) ApplyChatTaskAction(ctx context.Context, scope *string, actor ta
Instructions: res.Instructions,
Findings: res.Findings,
RetryMode: res.RetryMode,
ResumeFrom: res.ResumeFrom,
Actor: &actorPayload{
ID: string(actor.Identity),
Kind: string(actor.Kind),
+4 -1
View File
@@ -8,6 +8,7 @@ import (
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/domain/taskactions"
"github.com/samcharles93/archie-core/internal/domain/workflow"
)
type Store struct{ storecontract.TaskStore }
@@ -17,7 +18,9 @@ func (s Store) TaskByID(ctx context.Context, id int64) (*taskactions.Task, error
if err != nil || t == nil {
return nil, err
}
return &taskactions.Task{ID: t.ID, Owner: t.Owner, Repo: t.Repo, Identity: t.Identity, Status: t.Status, ParkReason: t.ParkReason, IssueNumber: t.IssueNumber, RetryCount: t.RetryCount, Attempt: t.Attempt, Branch: t.Branch, RetryMode: t.RetryMode, ForgeBacked: t.IsForgeBacked(), ReviewGate: t.ReviewGate, RereviewRounds: t.RereviewRounds}, nil
// A pinned definition that no longer parses offers no resume points.
stages, _ := workflow.StageNames(t.WorkflowDefinitionYAML)
return &taskactions.Task{ID: t.ID, Owner: t.Owner, Repo: t.Repo, Identity: t.Identity, Status: t.Status, ParkReason: t.ParkReason, IssueNumber: t.IssueNumber, RetryCount: t.RetryCount, Attempt: t.Attempt, Branch: t.Branch, RetryMode: t.RetryMode, ForgeBacked: t.IsForgeBacked(), ReviewGate: t.ReviewGate, RereviewRounds: t.RereviewRounds, Stages: stages}, nil
}
// CancelExecution delegates to the store.
+3 -1
View File
@@ -188,6 +188,8 @@ type taskActionRequest struct {
Findings []string `json:"findings"`
// RetryMode is the worktree mode for a retry; empty means refresh_onto_base.
RetryMode string `json:"retry_mode"`
// ResumeFrom is the step a retry starts at; empty runs every step.
ResumeFrom string `json:"resume_from"`
}
func (s *Server) handleTaskAction(w http.ResponseWriter, r *http.Request) {
@@ -251,7 +253,7 @@ func decodeTaskAction(w http.ResponseWriter, r *http.Request) (taskstate.Action,
http.Error(w, "a re-review needs instructions", http.StatusBadRequest)
return "", taskactions.ActionPayload{}, false
}
return action, taskactions.ActionPayload{Instructions: req.Instructions, Findings: req.Findings, RetryMode: taskstate.RetryMode(req.RetryMode)}, true
return action, taskactions.ActionPayload{Instructions: req.Instructions, Findings: req.Findings, RetryMode: taskstate.RetryMode(req.RetryMode), ResumeFrom: req.ResumeFrom}, true
}
func taskMutation(action taskstate.Action) bool {