Merge main (findings ledger, loop continuation) into usage-limit branch
Keeps the findings ledger, extra visits and on_exhausted=decide alongside the run budget, failure classes, quota parking and error-loop backoff. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -61,6 +61,14 @@ func parseControl(s *Stage, fields map[string]string) error {
|
||||
}
|
||||
seen[outcome] = true
|
||||
}
|
||||
switch s.Limits.OnExhausted {
|
||||
case "", "fail", "decide":
|
||||
default:
|
||||
return fmt.Errorf("on_exhausted must be fail or decide")
|
||||
}
|
||||
if s.Limits.AcceptTo != "" && s.Limits.OnExhausted != "decide" {
|
||||
return fmt.Errorf("accept_to needs \"on_exhausted\":\"decide\"")
|
||||
}
|
||||
delete(fields, "limits")
|
||||
}
|
||||
if text, ok := fields["memory"]; ok {
|
||||
@@ -86,6 +94,9 @@ func validateControl(s Stage, stages map[string]bool) error {
|
||||
return fmt.Errorf("stage %s: limit outcome %q must name a nonterminal edge", s.Key, outcome)
|
||||
}
|
||||
}
|
||||
if target := s.Limits.AcceptTo; target != "" && !protocol.IsTerminal(target) && !stages[target] {
|
||||
return fmt.Errorf("stage %s: accept_to %q is not a stage, #success or #failure", s.Key, target)
|
||||
}
|
||||
}
|
||||
for _, ref := range s.Memory {
|
||||
owner, _, _ := strings.Cut(ref, ".")
|
||||
|
||||
@@ -90,6 +90,23 @@ func Lint(g Graph) (errs, warnings []LintFinding) {
|
||||
}
|
||||
}
|
||||
}
|
||||
lintLoops(g, i, index, func(list *[]LintFinding, rule, format string, args ...any) {
|
||||
if list == nil {
|
||||
list = &warnings
|
||||
}
|
||||
add(list, s, rule, format, args...)
|
||||
}, &errs)
|
||||
if model && s.Configs["resume_session"] == "true" {
|
||||
if !reentered(g, i, index) {
|
||||
add(&warnings, s, "resume_session", "resume_session=true has no effect: no edge loops back to %s, so it never has a previous session to resume", s.Key)
|
||||
}
|
||||
if s.Configs["harness"] != stage.ClaudeBackend {
|
||||
add(&warnings, s, "resume_session", "resume_session is supported only by harness=claude; this stage starts a fresh session on every visit")
|
||||
}
|
||||
if reason := mutatingReason(s); reason == "" {
|
||||
add(&warnings, s, "resume_session", "resume_session on a read-only stage carries its earlier verdicts into later visits; keep reviewers on fresh sessions and resume only implementers")
|
||||
}
|
||||
}
|
||||
if stage.EffectiveType(s.Type) == stage.CheckType {
|
||||
for _, line := range strings.Split(s.Blocks["commands"], "\n") {
|
||||
if guard := silentGuard(line); guard != "" {
|
||||
@@ -113,6 +130,63 @@ func Lint(g Graph) (errs, warnings []LintFinding) {
|
||||
return errs, warnings
|
||||
}
|
||||
|
||||
// lintLoops checks a stage's limits block against the graph: an `on` outcome
|
||||
// must be a loop (back edge or self-loop), because `on` turns that outcome into
|
||||
// a failure on the last allowed visit; a forward `success` there makes a good
|
||||
// result fail the run. It also warns when the limits can never apply.
|
||||
func lintLoops(g Graph, i int, index map[string]int, add func(list *[]LintFinding, rule, format string, args ...any), errs *[]LintFinding) {
|
||||
s := g.Stages[i]
|
||||
if s.Limits == nil {
|
||||
return
|
||||
}
|
||||
for _, outcome := range s.Limits.On {
|
||||
target, ok := s.Edges[outcome]
|
||||
if !ok || protocol.IsTerminal(target) {
|
||||
continue
|
||||
}
|
||||
if index[target] > i {
|
||||
add(errs, "limits", "limits.on lists %q, but %s -> %s is a forward edge, not a loop back; on the last allowed visit the runner routes a listed outcome to #failure, so a %s there would fail the run. List only outcomes whose edge returns to %s or an earlier stage (for example \"rejected\"), or drop \"on\"", outcome, outcome, target, outcome, s.Key)
|
||||
continue
|
||||
}
|
||||
if limits := g.Stages[index[target]].Limits; limits != nil && index[target] != i && limits.MaxVisits < s.Limits.MaxVisits {
|
||||
add(nil, "limits", "%s has max_visits %d, lower than this stage's %d: the loop stops at %s first, so on [%q] never fires; give %s a cap at least %d or leave it unlimited", target, limits.MaxVisits, s.Limits.MaxVisits, target, outcome, target, s.Limits.MaxVisits)
|
||||
}
|
||||
}
|
||||
if !reentered(g, i, index) {
|
||||
add(nil, "limits", "limits has no effect: no edge loops back to %s, so it is visited once per run; move the limits to the stage that sends the run back, or remove them", s.Key)
|
||||
}
|
||||
if s.Limits.OnExhausted == "decide" && stage.EffectiveType(s.Type) == stage.HumanType {
|
||||
add(nil, "limits", "on_exhausted=decide on a human stage has no effect; human stages are exempt from visit caps")
|
||||
}
|
||||
}
|
||||
|
||||
// reentered reports whether stage i lies on a cycle, i.e. whether a run can
|
||||
// visit it more than once.
|
||||
func reentered(g Graph, i int, index map[string]int) bool {
|
||||
key := g.Stages[i].Key
|
||||
seen := map[string]bool{}
|
||||
var stack []string
|
||||
for _, target := range g.Stages[i].Edges {
|
||||
stack = append(stack, target)
|
||||
}
|
||||
for len(stack) > 0 {
|
||||
next := stack[len(stack)-1]
|
||||
stack = stack[:len(stack)-1]
|
||||
if next == key {
|
||||
return true
|
||||
}
|
||||
j, ok := index[next]
|
||||
if !ok || seen[next] || protocol.IsTerminal(next) {
|
||||
continue
|
||||
}
|
||||
seen[next] = true
|
||||
for _, target := range g.Stages[j].Edges {
|
||||
stack = append(stack, target)
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// mutatingReason names why a model stage can change the workspace, or "".
|
||||
func mutatingReason(s Stage) string {
|
||||
if s.Configs["delivery"] == "true" {
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
package pipeline
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestLintRejectsForwardLimitOutcomes(t *testing.T) {
|
||||
// Research runs 100/101: "on" listed the forward success edge, so a good
|
||||
// result on the last allowed visit failed the run.
|
||||
source := lintSource(
|
||||
modelStage("research", "Research.", "read", "success -> write\nretry -> research\nerror -> #failure", "```limits\n{\"max_visits\":3,\"on\":[\"success\",\"retry\"]}\n```"),
|
||||
modelStage("write", "Write.", "read", "success -> #success\nerror -> #failure", ""),
|
||||
)
|
||||
errs, _ := lintRules(t, source)
|
||||
if len(errs["limits"]) != 1 || !strings.Contains(errs["limits"][0], `limits.on lists "success", but success -> write is a forward edge`) {
|
||||
t.Fatalf("limits errors = %v", errs["limits"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestLintWarnsAboutIneffectiveLoopSettings(t *testing.T) {
|
||||
checks := "```checks\nnone: focused tests only\n```"
|
||||
source := lintSource(
|
||||
modelStage("implement", "Implement.", "read\nedit", "success -> review\nerror -> #failure", checks+"\n\n```limits\n{\"max_visits\":2}\n```"),
|
||||
modelStage("review", "Review.", "read", "approved -> land\nrejected -> implement\nerror -> #failure", "```limits\n{\"max_visits\":3,\"on\":[\"rejected\"],\"on_exhausted\":\"decide\",\"accept_to\":\"land\"}\n```"),
|
||||
modelStage("land", "Land.", "read", "success -> #success\nerror -> #failure", "```limits\n{\"max_visits\":2}\n```"),
|
||||
)
|
||||
errs, warns := lintRules(t, source)
|
||||
if len(errs["limits"]) != 0 {
|
||||
t.Fatalf("unexpected errors %v", errs)
|
||||
}
|
||||
joined := strings.Join(warns["limits"], "\n")
|
||||
for _, want := range []string{"implement has max_visits 2, lower than this stage's 3", "stage land: limits: limits has no effect"} {
|
||||
if !strings.Contains(joined, want) {
|
||||
t.Fatalf("warnings missing %q:\n%s", want, joined)
|
||||
}
|
||||
}
|
||||
if strings.Contains(joined, "stage review: limits: limits has no effect") || strings.Contains(joined, "stage implement: limits: limits has no effect") {
|
||||
t.Fatalf("review and implement are on a loop:\n%s", joined)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLintWarnsAboutResumeSession(t *testing.T) {
|
||||
stageWith := func(key, tools, edges, configs, extra string) string {
|
||||
return "# stage " + key + "\n\n```prompt\nWork.\n```\n\n```configs\nprovider=opencode-go\nmodel=deepseek-v4.1-flash\n" + configs + "\n```\n\n```tools\n" + tools + "\n```\n\n```edges\n" + edges + "\n```\n\n" + extra + "\n"
|
||||
}
|
||||
source := lintSource(
|
||||
stageWith("implement", "read\nedit", "success -> review\nerror -> #failure", "resume_session=true", "```checks\nnone: focused\n```"),
|
||||
stageWith("review", "read", "approved -> #success\nrejected -> implement\nerror -> #failure", "resume_session=true", "```limits\n{\"max_visits\":3,\"on\":[\"rejected\"]}\n```"),
|
||||
)
|
||||
_, warns := lintRules(t, source)
|
||||
joined := strings.Join(warns["resume_session"], "\n")
|
||||
for _, want := range []string{"stage implement: resume_session: resume_session is supported only by harness=claude", "stage review: resume_session: resume_session on a read-only stage"} {
|
||||
if !strings.Contains(joined, want) {
|
||||
t.Fatalf("warnings missing %q:\n%s", want, joined)
|
||||
}
|
||||
}
|
||||
if strings.Contains(joined, "has no effect") {
|
||||
t.Fatalf("both stages loop:\n%s", joined)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseValidatesExhaustionSettings(t *testing.T) {
|
||||
base := func(limits string) string {
|
||||
return lintSource(
|
||||
modelStage("implement", "Implement.", "read", "success -> review\nerror -> #failure", ""),
|
||||
modelStage("review", "Review.", "read", "approved -> #success\nrejected -> implement\nerror -> #failure", "```limits\n"+limits+"\n```"),
|
||||
)
|
||||
}
|
||||
for limits, want := range map[string]string{
|
||||
`{"max_visits":3,"on_exhausted":"ask"}`: "on_exhausted must be fail or decide",
|
||||
`{"max_visits":3,"accept_to":"implement"}`: "accept_to needs",
|
||||
`{"max_visits":3,"on_exhausted":"decide","accept_to":"nowhere"}`: "accept_to \"nowhere\" is not a stage",
|
||||
} {
|
||||
if _, err := Parse(base(limits)); err == nil || !strings.Contains(err.Error(), want) {
|
||||
t.Fatalf("%s: err = %v, want %q", limits, err, want)
|
||||
}
|
||||
}
|
||||
if _, err := Parse(base(`{"max_visits":3,"on":["rejected"],"on_exhausted":"decide","accept_to":"#success"}`)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseFindingsGateStage(t *testing.T) {
|
||||
gate := func(configs, edges string) string {
|
||||
return lintSource(
|
||||
modelStage("review", "Review.", "read", "success -> triage\nerror -> #failure", ""),
|
||||
"# stage triage\n\n```configs\ntype=findings\n"+configs+"\n```\n\n```edges\n"+edges+"\n```\n",
|
||||
modelStage("fix", "Fix.", "read", "success -> review\nerror -> #failure", ""),
|
||||
)
|
||||
}
|
||||
g, err := Parse(gate("severity=minor\norigin=any", "open -> fix\nclear -> #success"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if g.Stages[1].Type != "findings" {
|
||||
t.Fatalf("type = %q", g.Stages[1].Type)
|
||||
}
|
||||
for _, tc := range []struct{ configs, edges, want string }{
|
||||
{"severity=huge", "open -> fix\nclear -> #success", "severity must be"},
|
||||
{"origin=old", "open -> fix\nclear -> #success", "origin must be"},
|
||||
{"", "open -> fix", "requires an edge for outcome clear"},
|
||||
{"", "open -> fix\nclear -> #success\nmaybe -> fix", "outcomes are open and clear"},
|
||||
} {
|
||||
if _, err := Parse(gate(tc.configs, tc.edges)); err == nil || !strings.Contains(err.Error(), tc.want) {
|
||||
t.Fatalf("%+v: err = %v", tc, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -645,6 +645,7 @@ func deleteRunRows(ctx context.Context, tx *sql.Tx, ids []int64) error {
|
||||
{"attention_dismissals", "run_id"},
|
||||
{"run_schedule_origin", "run_id"},
|
||||
{"run_stage_skills", "run_id"},
|
||||
{"run_loop_state", "run_id"},
|
||||
{"run_steps", "run_id"},
|
||||
} {
|
||||
if err := deleteRetentionBatch(ctx, tx, table.name, table.column, ids); err != nil && !missingTable(err) {
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
package pipeline
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
// initRunLoopState records the runner-owned loop state of a run: its findings
|
||||
// ledger and the extra visits granted to its stages (by a retry with
|
||||
// --extra-visits or a "continue" exhaustion decision). One row per run, written
|
||||
// by the runner as the state changes.
|
||||
func (s *Store) initRunLoopState() error {
|
||||
_, err := s.db.Exec(`CREATE TABLE IF NOT EXISTS run_loop_state (
|
||||
run_id INTEGER PRIMARY KEY REFERENCES pipeline_runs(id),
|
||||
findings_json TEXT NOT NULL DEFAULT '[]',
|
||||
grants_json TEXT NOT NULL DEFAULT '{}')`)
|
||||
return err
|
||||
}
|
||||
|
||||
// SetRunFindings replaces a run's findings ledger.
|
||||
func (s *Store) SetRunFindings(ctx context.Context, runID int64, ledger []protocol.Finding) error {
|
||||
if ledger == nil {
|
||||
ledger = []protocol.Finding{}
|
||||
}
|
||||
encoded, err := json.Marshal(ledger)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = s.db.ExecContext(ctx, `INSERT INTO run_loop_state(run_id,findings_json) VALUES(?,?)
|
||||
ON CONFLICT(run_id) DO UPDATE SET findings_json=excluded.findings_json`, runID, string(encoded))
|
||||
return err
|
||||
}
|
||||
|
||||
// SetRunVisitGrants replaces a run's extra-visit grants.
|
||||
func (s *Store) SetRunVisitGrants(ctx context.Context, runID int64, grants map[string]int) error {
|
||||
if grants == nil {
|
||||
grants = map[string]int{}
|
||||
}
|
||||
encoded, err := json.Marshal(grants)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = s.db.ExecContext(ctx, `INSERT INTO run_loop_state(run_id,grants_json) VALUES(?,?)
|
||||
ON CONFLICT(run_id) DO UPDATE SET grants_json=excluded.grants_json`, runID, string(encoded))
|
||||
return err
|
||||
}
|
||||
|
||||
// AddRunVisitGrant adds extra visits for one stage and returns the new grants.
|
||||
func (s *Store) AddRunVisitGrant(ctx context.Context, runID int64, stageKey string, extra int) (map[string]int, error) {
|
||||
_, grants, err := runLoopState(ctx, s.db, runID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if grants == nil {
|
||||
grants = map[string]int{}
|
||||
}
|
||||
grants[stageKey] += extra
|
||||
return grants, s.SetRunVisitGrants(ctx, runID, grants)
|
||||
}
|
||||
|
||||
func runLoopState(ctx context.Context, q interface {
|
||||
QueryRowContext(context.Context, string, ...any) *sql.Row
|
||||
}, runID int64) ([]protocol.Finding, map[string]int, error) {
|
||||
var ledgerJSON, grantsJSON string
|
||||
err := q.QueryRowContext(ctx, `SELECT findings_json,grants_json FROM run_loop_state WHERE run_id=?`, runID).Scan(&ledgerJSON, &grantsJSON)
|
||||
if errors.Is(err, sql.ErrNoRows) || missingTable(err) {
|
||||
return nil, nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
var ledger []protocol.Finding
|
||||
if err := json.Unmarshal([]byte(ledgerJSON), &ledger); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
var grants map[string]int
|
||||
if err := json.Unmarshal([]byte(grantsJSON), &grants); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if len(ledger) == 0 {
|
||||
ledger = nil
|
||||
}
|
||||
if len(grants) == 0 {
|
||||
grants = nil
|
||||
}
|
||||
return ledger, grants, nil
|
||||
}
|
||||
@@ -87,6 +87,7 @@ var runDBBytesQuery = func() string {
|
||||
{"retry_checkpoints", "run_id=?1", []string{"mode", "handoff_json", "source_hash"}},
|
||||
{"run_schedule_origin", "run_id=?1", []string{"name"}},
|
||||
{"run_stage_skills", "run_id=?1", []string{"skills_json"}},
|
||||
{"run_loop_state", "run_id=?1", []string{"findings_json", "grants_json"}},
|
||||
}
|
||||
terms := make([]string, 0, len(parts))
|
||||
for _, p := range parts {
|
||||
|
||||
@@ -323,6 +323,9 @@ strftime('%Y-%m-%dT%H:%M:%SZ',started_at),COALESCE(strftime('%Y-%m-%dT%H:%M:%SZ'
|
||||
return nil, err
|
||||
}
|
||||
stepSkills(r.Steps, r.StageSkills)
|
||||
if r.Findings, r.VisitGrants, err = runLoopState(ctx, tx, id); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// The run total is one pass over the steps already loaded above: it adds no
|
||||
// query and no transcript parse.
|
||||
r.Usage = protocol.TotalUsage(r.Steps)
|
||||
|
||||
@@ -279,7 +279,33 @@ JOIN pipeline_versions v ON v.pipeline_id=r.pipeline_id AND v.version=r.version
|
||||
}
|
||||
var edges map[string]string
|
||||
found := false
|
||||
// A loop that exhausted its visits on a stage with on_exhausted=decide
|
||||
// parks the run on a decision step under that (non-human) stage's key; its
|
||||
// evidence carries the option targets.
|
||||
var exhausted map[string]any
|
||||
var latestOutput string
|
||||
if err := tx.QueryRowContext(ctx, `SELECT output_json FROM run_steps WHERE run_id=? AND stage_key=? ORDER BY sequence DESC LIMIT 1`, id, stageKey).Scan(&latestOutput); err == nil {
|
||||
var evidence map[string]any
|
||||
if json.Unmarshal([]byte(latestOutput), &evidence) == nil {
|
||||
if exhausted = protocol.ExhaustedInfo(evidence); exhausted != nil {
|
||||
edges = map[string]string{}
|
||||
if targets, ok := exhausted["targets"].(map[string]any); ok {
|
||||
for option, target := range targets {
|
||||
if text, ok := target.(string); ok {
|
||||
edges[option] = text
|
||||
}
|
||||
}
|
||||
}
|
||||
found = true
|
||||
}
|
||||
}
|
||||
} else if err != sql.ErrNoRows {
|
||||
return protocol.RunStep{}, false, err
|
||||
}
|
||||
for _, declared := range graph.Stages {
|
||||
if exhausted != nil {
|
||||
break
|
||||
}
|
||||
if declared.Key == stageKey {
|
||||
if stage.EffectiveType(declared.Type) != stage.HumanType {
|
||||
return protocol.RunStep{}, false, fmt.Errorf("stage %s is not a human decision stage", stageKey)
|
||||
@@ -327,6 +353,11 @@ JOIN pipeline_versions v ON v.pipeline_id=r.pipeline_id AND v.version=r.version
|
||||
// successful decision is not presented as a stop or error; the derived
|
||||
// verdict reads the feedback as the step's reason.
|
||||
output := map[string]any{protocol.DecisionOptionKey: option, protocol.DecisionFeedbackKey: feedback}
|
||||
if exhausted != nil {
|
||||
// Keep the marker: a decided exhaustion step is a decision, never a
|
||||
// visit, when the run's state is rebuilt from its steps.
|
||||
output[protocol.ExhaustedKey] = exhausted
|
||||
}
|
||||
encoded, err := json.Marshal(output)
|
||||
if err != nil {
|
||||
return protocol.RunStep{}, false, err
|
||||
|
||||
@@ -23,6 +23,9 @@ CREATE TABLE IF NOT EXISTS skill_files (name TEXT NOT NULL, version INTEGER NOT
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.initRunLoopState(); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.initStageSkills()
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user