Retries: tell stages why the last attempt failed; resume interrupted runs
- turn.RenderPreviousAttempt: bounded "# Previous attempt" section (attempt number, failing stage, bounded diagnostic, partial-edits note). - In-stage retries (stage/model_run.go) append it instead of resending an identical prompt; run retries (resume and restart) add it to the first model visit's input.md, numbering attempts along the retry chain. - --input-file retry overrides render only the override keys in input.md, labelled "# Operator correction" (the step row keeps the merged input). - Essential memory (memory.md) inlines a revisiting stage's own last handoff, bounded, besides the previous stage's handoff. - Interrupted runs can be retried: resume reruns the interrupted visit, or starts the next stage after the last completed visit. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,111 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/pipeline"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
"git.a-wan.net/alan/pipelines/internal/stage"
|
||||
)
|
||||
|
||||
const threeStageModelSource = "# stage a\n\n```prompt\nDo A.\n```\n\n```tools\nread\n```\n\n```edges\nsuccess -> b\nerror -> #failure\n```\n\n```configs\ntype=model\nprovider=opencode-go\nmodel=deepseek-v4.1-flash\nretries=0\n```\n\n# stage b\n\n```prompt\nDo B.\n```\n\n```tools\nread\n```\n\n```edges\nsuccess -> c\nerror -> #failure\n```\n\n```configs\ntype=model\nprovider=opencode-go\nmodel=deepseek-v4.1-flash\nretries=0\n```\n\n# stage c\n\n```prompt\nDo C.\n```\n\n```tools\nread\n```\n\n```edges\nsuccess -> #success\nerror -> #failure\n```\n\n```configs\ntype=model\nprovider=opencode-go\nmodel=deepseek-v4.1-flash\nretries=0\n```\n"
|
||||
|
||||
// TestRetryResumesAnInterruptedRunAfterItsLastCompletedStep proves a run the
|
||||
// server stopped (interrupted) can be retried: it resumes after its last
|
||||
// completed step without rerunning that prefix, whether the stop came during a
|
||||
// visit (the interrupted visit runs again) or between visits (the next stage
|
||||
// starts with the completed visit's handoff).
|
||||
func TestRetryResumesAnInterruptedRunAfterItsLastCompletedStep(t *testing.T) {
|
||||
for _, midVisit := range []bool{true, false} {
|
||||
name := "between-visits"
|
||||
if midVisit {
|
||||
name = "mid-visit"
|
||||
}
|
||||
t.Run(name, func(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
store, err := pipeline.Open(filepath.Join(t.TempDir(), "interrupted.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer store.Close()
|
||||
if _, err := store.Submit(ctx, "resume", threeStageModelSource); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
items, _ := store.List(ctx)
|
||||
d, err := store.Get(ctx, items[0].ID, 1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
workspace := t.TempDir()
|
||||
id, _, err := store.CreateRun(ctx, d, "interrupted-"+name, workspace, true, nil, map[string]any{"prompt": "task"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.BeginStep(ctx, id, 1, "a", map[string]any{"prompt": "task"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.FinishStep(ctx, id, protocol.RunStep{Sequence: 1, Stage: "a", Status: "completed", Outcome: "success", Target: "b", Output: map[string]any{"handoff": "from-a"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if midVisit {
|
||||
if err := store.BeginStep(ctx, id, 2, "b", map[string]any{"handoff": "from-a"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := store.RecoverRuns(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
source, err := store.GetRun(ctx, id)
|
||||
if err != nil || source.Status != "interrupted" {
|
||||
t.Fatalf("source run was not interrupted: %+v %v", source, err)
|
||||
}
|
||||
|
||||
r, err := newRunner(ctx, store)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
calls := map[string]int{}
|
||||
r.execute = func(_ context.Context, def stage.Definition, input stage.Values) (stage.Result, error) {
|
||||
calls[def.Key]++
|
||||
switch def.Key {
|
||||
case "b":
|
||||
if input["handoff"] != "from-a" {
|
||||
t.Errorf("resumed stage lost the completed handoff: %#v", input)
|
||||
}
|
||||
data, err := os.ReadFile(def.Turn.Input)
|
||||
if err != nil {
|
||||
t.Fatalf("read input.md: %v", err)
|
||||
}
|
||||
if !strings.Contains(string(data), "# Previous attempt") || !strings.Contains(string(data), "This is attempt 2.") {
|
||||
t.Errorf("resumed stage was not told about the previous attempt:\n%s", data)
|
||||
}
|
||||
return stage.Result{Outcome: "success", Output: stage.Values{"handoff": "from-b"}}, nil
|
||||
case "c":
|
||||
return stage.Result{Outcome: "success", Output: stage.Values{"summary": "done"}}, nil
|
||||
}
|
||||
t.Errorf("unexpected stage %q", def.Key)
|
||||
return stage.Result{}, nil
|
||||
}
|
||||
retried, err := r.retry(protocol.Message{RunID: id, RequestKey: "resume-" + name})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.wg.Wait()
|
||||
retried, err = store.GetRun(ctx, retried.ID)
|
||||
if err != nil || retried.Status != "succeeded" || retried.RetrySource != id {
|
||||
t.Fatalf("interrupted run did not resume to success: %+v %v", retried, err)
|
||||
}
|
||||
if calls["a"] != 0 || calls["b"] != 1 || calls["c"] != 1 {
|
||||
t.Fatalf("resume reran the completed prefix or skipped work: %v", calls)
|
||||
}
|
||||
if len(retried.Steps) == 0 || retried.Steps[0].Stage != "b" || retried.Steps[0].Sequence != 2 {
|
||||
t.Fatalf("resume started at the wrong step: %+v", retried.Steps)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -356,6 +356,20 @@ func TestRetryResumeReusesPrefixHandoffAndReplaysRequestAfterReopen(t *testing.T
|
||||
if !strings.Contains(string(data), want) {
|
||||
t.Errorf("retry input.md missing override %q:\n%s", want, data)
|
||||
}
|
||||
// Only the override keys are shown, labelled as the operator's
|
||||
// correction; the merged input (handoff from A) is not reprinted.
|
||||
text := string(data)
|
||||
section := text[strings.Index(text, "# Operator correction"):]
|
||||
if !strings.Contains(text, "# Operator correction") || strings.Contains(section, "from-a") || strings.Contains(text, "# Retry input") {
|
||||
t.Errorf("retry input.md did not render only the operator correction:\n%s", data)
|
||||
}
|
||||
// The retried stage learns why the source attempt failed.
|
||||
wantAttempt := fmt.Sprintf("This is attempt %d.", bCalls)
|
||||
for _, want := range []string{"# Previous attempt", wantAttempt, "failed in stage b", "deliberate failure", "Partial edits"} {
|
||||
if !strings.Contains(text, want) {
|
||||
t.Errorf("retry input.md missing %q:\n%s", want, data)
|
||||
}
|
||||
}
|
||||
}
|
||||
if bCalls <= 2 {
|
||||
return stage.Result{}, fmt.Errorf("deliberate failure")
|
||||
|
||||
+97
-11
@@ -662,8 +662,9 @@ func (r *runner) retrySourceCheckpointSelected(sourceID int64, pinned *protocol.
|
||||
if err != nil {
|
||||
return retryCheckpoint{}, err
|
||||
}
|
||||
if source.Status != "failed" || source.FinishedAt == "" {
|
||||
return retryCheckpoint{}, fmt.Errorf("retry source %d is not a terminal failed run", sourceID)
|
||||
interrupted := source.Status == "interrupted"
|
||||
if (source.Status != "failed" && !interrupted) || source.FinishedAt == "" {
|
||||
return retryCheckpoint{}, fmt.Errorf("retry source %d is not a terminal failed or interrupted run", sourceID)
|
||||
}
|
||||
if source.PipelineID != pinned.ID {
|
||||
return retryCheckpoint{}, fmt.Errorf("retry source %d belongs to a different pipeline", sourceID)
|
||||
@@ -672,6 +673,28 @@ func (r *runner) retrySourceCheckpointSelected(sourceID int64, pinned *protocol.
|
||||
return retryCheckpoint{}, fmt.Errorf("retry source %d has no failed stage checkpoint", sourceID)
|
||||
}
|
||||
failed := source.Steps[len(source.Steps)-1]
|
||||
if interrupted && selectedStage == "" {
|
||||
// A server stop interrupts a run mid-visit (the visit is recorded as
|
||||
// interrupted, with the input it began with) or between visits (the
|
||||
// last recorded visit completed and routed to its next stage). Either
|
||||
// way the run resumes after its last completed step: the interrupted
|
||||
// visit runs again, or the next stage starts with the handoff the
|
||||
// completed visit produced.
|
||||
switch failed.Status {
|
||||
case "interrupted":
|
||||
failed.Target = protocol.FailureEnd
|
||||
case "completed":
|
||||
if failed.Target == "" || failed.Target == protocol.SuccessEnd || failed.Target == protocol.FailureEnd {
|
||||
return retryCheckpoint{}, fmt.Errorf("retry source %d has no unfinished stage to resume; use --mode=restart", sourceID)
|
||||
}
|
||||
failed = protocol.RunStep{Sequence: failed.Sequence + 1, Stage: failed.Target, Status: "interrupted", Target: protocol.FailureEnd, Input: failed.Output}
|
||||
if failed.Input == nil {
|
||||
failed.Input = map[string]any{}
|
||||
}
|
||||
default:
|
||||
return retryCheckpoint{}, fmt.Errorf("retry source %d has no safe interrupted-stage checkpoint; use --mode=restart", sourceID)
|
||||
}
|
||||
}
|
||||
if selectedStage != "" {
|
||||
failed = protocol.RunStep{}
|
||||
visits := 0
|
||||
@@ -705,7 +728,7 @@ func (r *runner) retrySourceCheckpointSelected(sourceID int64, pinned *protocol.
|
||||
return retryCheckpoint{}, fmt.Errorf("retry stage %q has no visit %d", selectedStage, selectedVisit)
|
||||
}
|
||||
}
|
||||
if (failed.Status != "completed" && failed.Status != "failed") || (selectedStage == "" && failed.Target != protocol.FailureEnd) {
|
||||
if (failed.Status != "completed" && failed.Status != "failed" && !(interrupted && failed.Status == "interrupted")) || (selectedStage == "" && failed.Target != protocol.FailureEnd) {
|
||||
return retryCheckpoint{}, fmt.Errorf("retry source %d has no safe failed-stage checkpoint", sourceID)
|
||||
}
|
||||
var handoff map[string]any
|
||||
@@ -813,8 +836,10 @@ func (r *runner) retry(request protocol.Message) (*protocol.RunDetail, error) {
|
||||
if original.Executing {
|
||||
return nil, fmt.Errorf("run %d is still executing; wait for it to stop completely before retrying", original.ID)
|
||||
}
|
||||
if original.Status != "failed" || original.FinishedAt == "" {
|
||||
return nil, fmt.Errorf("only failed runs can be retried (run %d is %s)", original.ID, original.Status)
|
||||
// An interrupted run (the server stopped mid-run) resumes after its last
|
||||
// completed step, like a failed run resumes its failed stage.
|
||||
if (original.Status != "failed" && original.Status != "interrupted") || original.FinishedAt == "" {
|
||||
return nil, fmt.Errorf("only failed or interrupted runs can be retried (run %d is %s)", original.ID, original.Status)
|
||||
}
|
||||
if request.RequestKey == "" {
|
||||
return nil, fmt.Errorf("retry requires an idempotency request key")
|
||||
@@ -998,6 +1023,7 @@ func (r *runner) run(ctx context.Context, id int64, d *protocol.PipelineDetail,
|
||||
return
|
||||
}
|
||||
state := rebuildRetryState(source, checkpoint.failed, storedHandoff)
|
||||
state.previousAttempt = r.previousAttemptSection(ctx, source, d.Graph, state.key)
|
||||
if override, ok := storedHandoff["override"].(map[string]any); ok {
|
||||
state.retryOverride = stage.Values(override)
|
||||
}
|
||||
@@ -1019,9 +1045,65 @@ func (r *runner) run(ctx context.Context, id int64, d *protocol.PipelineDetail,
|
||||
input := stage.Values(request.Input)
|
||||
state := newRunState(d.Graph.Stages[0].Key, input)
|
||||
state.memory["input"] = memoryValue{output: original}
|
||||
if request.RetrySource > 0 {
|
||||
// A restart from entry still tells its first model visit why the
|
||||
// source run failed.
|
||||
if source, err := r.store.GetRun(ctx, request.RetrySource); err == nil {
|
||||
state.previousAttempt = r.previousAttemptSection(ctx, source, d.Graph, state.key)
|
||||
}
|
||||
}
|
||||
r.runLoop(ctx, id, d.Graph, d.Name, workspace, request, state)
|
||||
}
|
||||
|
||||
// maxRetryChain bounds the walk that numbers a retry attempt.
|
||||
const maxRetryChain = 50
|
||||
|
||||
// previousAttemptSection renders the bounded "# Previous attempt" section for
|
||||
// a retried run whose first visit is the model stage firstStage: the attempt
|
||||
// number (counted along the retry chain), the stage the source run stopped in
|
||||
// and its diagnostic. A first visit that is not a model stage gets nothing, so
|
||||
// the note never lands on an unrelated later stage.
|
||||
func (r *runner) previousAttemptSection(ctx context.Context, source *protocol.RunDetail, graph protocol.Graph, firstStage string) string {
|
||||
if source == nil {
|
||||
return ""
|
||||
}
|
||||
model := false
|
||||
for _, declared := range graph.Stages {
|
||||
if declared.Key == firstStage {
|
||||
model = stage.EffectiveType(declared.Type) == stage.ModelType
|
||||
}
|
||||
}
|
||||
if !model {
|
||||
return ""
|
||||
}
|
||||
parentOf := func(d *protocol.RunDetail) int64 {
|
||||
if d.RetryOf > 0 {
|
||||
return d.RetryOf
|
||||
}
|
||||
return d.RetrySource
|
||||
}
|
||||
attempt := 2
|
||||
for previous := parentOf(source); previous > 0 && attempt < maxRetryChain; attempt++ {
|
||||
ancestor, err := r.store.GetRun(ctx, previous)
|
||||
if err != nil || ancestor == nil {
|
||||
break
|
||||
}
|
||||
previous = parentOf(ancestor)
|
||||
}
|
||||
failedStage, diagnostic := source.CurrentStage, ""
|
||||
if n := len(source.Steps); n > 0 {
|
||||
last := source.Steps[n-1]
|
||||
failedStage, diagnostic = last.Stage, strings.TrimSpace(last.Diagnostic)
|
||||
}
|
||||
if diagnostic == "" {
|
||||
diagnostic = strings.TrimSpace(source.Diagnostic)
|
||||
}
|
||||
if diagnostic == "" {
|
||||
diagnostic = strings.TrimSpace(source.FailureReason)
|
||||
}
|
||||
return turn.RenderPreviousAttempt(turn.PreviousAttempt{Attempt: attempt, Stage: failedStage, Diagnostic: diagnostic, Run: source.ID})
|
||||
}
|
||||
|
||||
// terminalFinish classifies a stage's resolved target. A terminal key yields the
|
||||
// run's final status, outcome and diagnostic; an empty target means the stage
|
||||
// named an undeclared outcome; any other value is a stage key and is not
|
||||
@@ -1098,7 +1180,10 @@ type runState struct {
|
||||
// retryOverride is applied once, after the selected stage's memory bindings
|
||||
// have been resolved. It is intentionally not part of run input or memory.
|
||||
retryOverride stage.Values
|
||||
priorBudgets map[string]stage.BudgetSnapshot
|
||||
// previousAttempt is the rendered "# Previous attempt" section a retried
|
||||
// run's first model visit receives; prepareTurn consumes it.
|
||||
previousAttempt string
|
||||
priorBudgets map[string]stage.BudgetSnapshot
|
||||
// adopt names the visit to re-adopt from a previous server process instead
|
||||
// of starting it; it is consumed by the loop's first iteration.
|
||||
adopt *adoptedVisit
|
||||
@@ -1779,11 +1864,12 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
|
||||
finish("failed", "error", copyErr.Error())
|
||||
return
|
||||
}
|
||||
// Keep the merged values for this visit's input.md: the model reads
|
||||
// files, not the persisted step row, so the override must be visible
|
||||
// there. A selected-stage override belongs only to this invocation,
|
||||
// not to a later visit reached through the stage graph.
|
||||
retryInput = input
|
||||
// The step row persists the merged input; input.md shows only the
|
||||
// operator's override keys: the model reads files, not the step row,
|
||||
// so the correction must be visible there, without re-printing the
|
||||
// whole input. A selected-stage override belongs only to this
|
||||
// invocation, not to a later visit reached through the stage graph.
|
||||
retryInput = state.retryOverride
|
||||
state.retryOverride = nil
|
||||
}
|
||||
if adopted == nil {
|
||||
|
||||
+29
-17
@@ -52,15 +52,25 @@ func stageTurnPaths(paths turn.Paths) stage.TurnPaths {
|
||||
// completed turn in full) before the visit starts. A failure here is a run failure: the file
|
||||
// protocol is the stage contract, not best-effort evidence.
|
||||
//
|
||||
// retryInput is the complete merged input for a selected-stage retry and nil for
|
||||
// an ordinary visit. A retry override is persisted on the step, but the model
|
||||
// reads input.md rather than the step row, so the same values must be written
|
||||
// into the file or the operator's correction is invisible to the model.
|
||||
// retryInput is the operator's override for a selected-stage retry (only the
|
||||
// keys it sets) and nil for an ordinary visit. The merged input is persisted on
|
||||
// the step, but the model reads input.md rather than the step row, so the
|
||||
// correction must be written into the file or it is invisible to the model.
|
||||
// A retried run's first visit also gets a bounded "# Previous attempt" section
|
||||
// saying why the source run failed; it is consumed here so later visits do not
|
||||
// repeat it.
|
||||
func (r *runner) prepareTurn(paths turn.Paths, state *runState, retryInput stage.Values) error {
|
||||
if err := paths.Ensure(); err != nil {
|
||||
return err
|
||||
}
|
||||
input := turnInputWithRetry(state.turnInput(), retryInput)
|
||||
if state.previousAttempt != "" {
|
||||
if !strings.HasSuffix(input, "\n") {
|
||||
input += "\n"
|
||||
}
|
||||
input += "\n" + state.previousAttempt
|
||||
state.previousAttempt = ""
|
||||
}
|
||||
history := turn.RenderHistory(state.turns)
|
||||
memory := turn.RenderEssential(turn.Essential{
|
||||
Task: state.prompt,
|
||||
@@ -82,24 +92,26 @@ func (r *runner) prepareTurn(paths turn.Paths, state *runState, retryInput stage
|
||||
return nil
|
||||
}
|
||||
|
||||
// turnInputWithRetry appends the merged retry input to the ordinary turn input.
|
||||
// It is rendered as a fenced JSON object because the values are operator data,
|
||||
// not prose; encoding/json sorts map keys so the file is deterministic.
|
||||
func turnInputWithRetry(base string, retryInput stage.Values) string {
|
||||
if len(retryInput) == 0 {
|
||||
// turnInputWithRetry appends the operator's retry override to the ordinary turn
|
||||
// input as an "Operator correction": only the keys the operator set, not the
|
||||
// whole merged input the stage already has. It is rendered as a fenced JSON
|
||||
// object because the values are operator data, not prose; encoding/json sorts
|
||||
// map keys so the file is deterministic.
|
||||
func turnInputWithRetry(base string, override stage.Values) string {
|
||||
if len(override) == 0 {
|
||||
return base
|
||||
}
|
||||
encoded, err := json.MarshalIndent(retryInput, "", " ")
|
||||
if err != nil {
|
||||
// A retry input that cannot be rendered is still shown as a visible
|
||||
// section; the stage can choose its error outcome rather than silently
|
||||
// receiving a correction it cannot see.
|
||||
return base + "\n\n# Retry input\n\nThe retry input could not be rendered.\n"
|
||||
}
|
||||
if !strings.HasSuffix(base, "\n") {
|
||||
base += "\n"
|
||||
}
|
||||
return base + "\n# Retry input\n\nThis retry was given this complete input:\n\n```json\n" + string(encoded) + "\n```\n"
|
||||
encoded, err := json.MarshalIndent(override, "", " ")
|
||||
if err != nil {
|
||||
// A correction that cannot be rendered is still shown as a visible
|
||||
// section; the stage can choose its error outcome rather than silently
|
||||
// receiving a correction it cannot see.
|
||||
return base + "\n# Operator correction\n\nThe operator's retry correction could not be rendered.\n"
|
||||
}
|
||||
return base + "\n# Operator correction\n\nThe operator retried this stage with these corrected input values; they override the earlier ones:\n\n```json\n" + string(encoded) + "\n```\n"
|
||||
}
|
||||
|
||||
// turnInput is the run prompt on the first visit; later visits carry the run
|
||||
|
||||
Reference in New Issue
Block a user