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

@@ -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 {