Add stage execution limits and result-first workflow views
This commit is contained in:
@@ -2,6 +2,7 @@ package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"maps"
|
||||
@@ -157,7 +158,7 @@ func (r *runner) start(request protocol.Message, retryOf ...int64) (*protocol.Ru
|
||||
return nil, err
|
||||
}
|
||||
if created {
|
||||
ctx, cancel := context.WithTimeout(r.ctx, 30*time.Minute)
|
||||
ctx, cancel := context.WithCancel(r.ctx)
|
||||
r.active[id] = cancel
|
||||
r.wg.Add(1)
|
||||
go func() {
|
||||
@@ -242,6 +243,7 @@ func (r *runner) run(ctx context.Context, id int64, d *protocol.PipelineDetail,
|
||||
input := stage.Values(request.Input)
|
||||
key := d.Graph.Stages[0].Key
|
||||
visits := map[string]int{}
|
||||
budgets := map[string]*stage.Budget{}
|
||||
finish := func(status, outcome, diagnostic string) {
|
||||
c, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
@@ -305,10 +307,27 @@ func (r *runner) run(ctx context.Context, id int64, d *protocol.PipelineDetail,
|
||||
}
|
||||
var result stage.Result
|
||||
var err error
|
||||
stageCtx := ctx
|
||||
var modelConfig stage.ModelConfig
|
||||
if stage.EffectiveType(def.Type) == stage.ModelType {
|
||||
spec, specErr := (stage.ModelStage{}).Spec(def)
|
||||
if specErr != nil {
|
||||
finish("failed", "error", specErr.Error())
|
||||
return
|
||||
}
|
||||
modelConfig = spec.Config
|
||||
if budgets[key] == nil {
|
||||
budgets[key] = stage.NewBudget(modelConfig.BudgetUSD, modelConfig.BudgetTokens)
|
||||
}
|
||||
stageCtx = stage.WithBudget(ctx, budgets[key])
|
||||
}
|
||||
if r.execute != nil {
|
||||
result, err = r.execute(ctx, def, input)
|
||||
timeout, _ := stage.StageTimeout(def)
|
||||
executeCtx, cancel := context.WithTimeout(stageCtx, timeout)
|
||||
result, err = r.execute(executeCtx, def, input)
|
||||
cancel()
|
||||
} else if useAgent {
|
||||
result, err = (stage.ModelStage{Client: client}).Run(ctx, def, input)
|
||||
result, err = (stage.ModelStage{Client: client}).Run(stageCtx, def, input)
|
||||
} else if stage.EffectiveType(def.Type) == stage.ModelType {
|
||||
plain := &stage.OpenCodeClient{Directory: workspace, Operations: operations}
|
||||
plain.OnGenerationSession = func(session, backend, reference string, active bool) error {
|
||||
@@ -316,12 +335,15 @@ func (r *runner) run(ctx context.Context, id int64, d *protocol.PipelineDetail,
|
||||
defer cancel()
|
||||
return r.store.RunSession(c, id, sequence, session, active, backend, reference)
|
||||
}
|
||||
result, err = (stage.ModelStage{Client: plain}).Run(ctx, def, input)
|
||||
result, err = (stage.ModelStage{Client: plain}).Run(stageCtx, def, input)
|
||||
client.Transcript = plain.FormatAudit
|
||||
} else {
|
||||
result, err = stage.DefaultRegistry().Run(ctx, def, input)
|
||||
}
|
||||
step := protocol.RunStep{Sequence: sequence, Stage: key, Status: "completed", Outcome: result.Outcome, Output: result.Output, Transcript: operations.Transcript(client.Transcript)}
|
||||
if budget := budgets[key]; budget != nil {
|
||||
step.Transcript = stage.BudgetTranscript(step.Transcript, budget, modelConfig.Timeout, modelConfig.Retries)
|
||||
}
|
||||
if err != nil {
|
||||
step.Status = "failed"
|
||||
step.Diagnostic = err.Error()
|
||||
@@ -343,7 +365,7 @@ func (r *runner) run(ctx context.Context, id int64, d *protocol.PipelineDetail,
|
||||
}
|
||||
}
|
||||
input = stage.Values(step.Output)
|
||||
if useAgent {
|
||||
if useAgent || errors.Is(err, stage.ErrStageCleanup) {
|
||||
sessions, checkErr := r.store.ActiveAgentSessions(context.Background())
|
||||
if checkErr != nil || len(sessions) > 0 {
|
||||
finish("failed", "error", "agent quiescence not confirmed; inspect retained session before further work")
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/cli"
|
||||
"git.a-wan.net/alan/pipelines/internal/pipeline"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
"git.a-wan.net/alan/pipelines/internal/stage"
|
||||
)
|
||||
|
||||
func TestStageBudgetAcrossVisitsThroughCLIAndWebsocket(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
dir := t.TempDir()
|
||||
executable := filepath.Join(dir, "opencode")
|
||||
script := fmt.Sprintf(`#!/bin/sh
|
||||
if [ "$1" = "--help" ]; then echo ' api'; exit 0; fi
|
||||
case "$3" in
|
||||
/api/session)
|
||||
n=0; if [ -f %q/count ]; then n=$(cat %q/count); fi
|
||||
n=$((n+1)); echo "$n" > %q/count
|
||||
printf '{"data":{"id":"ses_budget_%%s"}}' "$n" ;;
|
||||
*/generate)
|
||||
id=${3#/api/session/}; id=${id%%/generate}
|
||||
touch %q/"$id"
|
||||
echo '{"data":{"text":"{\"outcome\":\"success\",\"output\":{\"summary\":\"done\"}}"}}' ;;
|
||||
*/interrupt) echo '{}' ;;
|
||||
/api/session/ses_budget_*)
|
||||
id=${3#/api/session/}; cost=0; tokens=0
|
||||
if [ -f %q/"$id" ]; then cost=0.4; tokens=3; fi
|
||||
printf '{"data":{"id":"%%s","cost":%%s,"tokens":{"input":%%s,"output":0,"reasoning":0,"cache":{"read":0,"write":0}}}}' "$id" "$cost" "$tokens" ;;
|
||||
*) exit 99 ;;
|
||||
esac
|
||||
`, dir, dir, dir, dir, dir)
|
||||
if err := os.WriteFile(executable, []byte(script), 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv("PIPELINES_OPENCODE", executable)
|
||||
store, err := pipeline.Open(filepath.Join(dir, "runs.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer store.Close()
|
||||
source := pipeline.Template([]string{"worker"}, true)
|
||||
source = strings.Replace(source, "success -> #success", "success -> worker", 1)
|
||||
source = strings.Replace(source, "timeout=1h", "timeout=1h\nbudget_usd=1\nbudget_tokens=5", 1)
|
||||
if _, err := store.Submit(ctx, "budget", source); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
handler := Handler(ctx, store)
|
||||
defer func() { cancel(); WaitRuns(handler) }()
|
||||
srv := httptest.NewServer(handler)
|
||||
defer srv.Close()
|
||||
url := "ws" + strings.TrimPrefix(srv.URL, "http") + "/connect"
|
||||
var out bytes.Buffer
|
||||
app := cli.App{Out: &out, Err: &out, In: strings.NewReader("")}
|
||||
if err := app.Run(ctx, []string{"--url", url, "run", "budget", "task", "--yes", "--json", "--wait", "--timeout", "10s", "--workspace", dir}); err == nil || !strings.Contains(err.Error(), "run ended failed") {
|
||||
t.Fatal(err, out.String())
|
||||
}
|
||||
var response protocol.Message
|
||||
if err := json.Unmarshal(out.Bytes(), &response); err != nil {
|
||||
t.Fatal(err, out.String())
|
||||
}
|
||||
detail := response.RunDetail
|
||||
if detail == nil || detail.ResultPreview != "done" || detail.CompletedSteps != 1 {
|
||||
t.Fatal("partial results missing from run summary", out.String())
|
||||
}
|
||||
if detail == nil || detail.Status != "failed" || len(detail.Steps) != 2 || detail.Steps[0].SessionID == detail.Steps[1].SessionID || detail.Steps[1].AgentActive || !strings.Contains(detail.Steps[1].Diagnostic, "stage budget exceeded") {
|
||||
t.Fatal("budget run/audit incorrect", out.String())
|
||||
}
|
||||
var audit struct {
|
||||
Limits struct {
|
||||
Timeout string
|
||||
Retries int
|
||||
Budget stage.BudgetSnapshot
|
||||
} `json:"stage_limits"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(detail.Steps[1].Transcript), &audit); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if audit.Limits.Timeout != time.Hour.String() || audit.Limits.Retries != 2 || audit.Limits.Budget.Attempts != 2 || audit.Limits.Budget.UsedTokens != 6 {
|
||||
t.Fatal("limits not persisted across visits", audit)
|
||||
}
|
||||
count, err := os.ReadFile(filepath.Join(dir, "count"))
|
||||
if err != nil || strings.TrimSpace(string(count)) != "2" {
|
||||
t.Fatal("budget failed to block further work", string(count), err)
|
||||
}
|
||||
stored, err := store.GetRun(ctx, detail.ID)
|
||||
if err != nil || stored.Steps[1].Transcript != detail.Steps[1].Transcript {
|
||||
t.Fatal("evidence was not retained", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunnerStageTimeoutAndNoShortOuterDeadline(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
store, err := pipeline.Open(filepath.Join(t.TempDir(), "runs.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer store.Close()
|
||||
source := pipeline.Template([]string{"worker"}, true)
|
||||
if _, err := store.Submit(ctx, "default", source); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
items, _ := store.List(ctx)
|
||||
r, err := newRunner(ctx, store)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.execute = func(ctx context.Context, _ stage.Definition, _ stage.Values) (stage.Result, error) {
|
||||
deadline, ok := ctx.Deadline()
|
||||
if !ok || time.Until(deadline) < time.Hour-time.Second {
|
||||
t.Error("outer run deadline truncated default stage timeout")
|
||||
}
|
||||
return stage.Result{Outcome: "success", Output: stage.Values{}}, nil
|
||||
}
|
||||
if _, err := r.start(protocol.Message{PipelineID: items[0].ID, Version: 1, RequestKey: "default", Input: map[string]any{"prompt": "task"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.wg.Wait()
|
||||
source = strings.Replace(source, "timeout=1h", "timeout=20ms", 1)
|
||||
if _, err := store.Submit(ctx, "short", source); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
items, _ = store.List(ctx)
|
||||
var id int64
|
||||
for _, item := range items {
|
||||
if item.Name == "short" {
|
||||
id = item.ID
|
||||
}
|
||||
}
|
||||
r.execute = func(ctx context.Context, _ stage.Definition, _ stage.Values) (stage.Result, error) {
|
||||
<-ctx.Done()
|
||||
return stage.Result{}, ctx.Err()
|
||||
}
|
||||
run, err := r.start(protocol.Message{PipelineID: id, Version: 1, RequestKey: "short", Input: map[string]any{"prompt": "task"}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.wg.Wait()
|
||||
detail, err := store.GetRun(ctx, run.ID)
|
||||
if err != nil || detail.Status != "failed" || !strings.Contains(detail.Steps[0].Diagnostic, "deadline exceeded") {
|
||||
t.Fatal("per-stage timeout not persisted", detail, err)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user