stage: retry pre-admission harness reach failures and widen repair deadline

Treat a failure to reach the harness before any prompt or tool call is
admitted (connecting or creating the session) as a distinct retryable
reach failure, so a transport blip at the first stage no longer ends a
mutating run; keep post-admission readback/poll/agent failures retried
only on an explicit read-only stage and never replay admitted tool work.
Preserve the true cause when the context is already done (join ctx.Err
with the typed transport error) and report a sanitized unknown provider
error name/status instead of a blanket summary.

Make the isolated format-repair deadline proportional to the stage
timeout (floored, capped and clamped to remaining minus a margin) so a
slow-but-repairable result is recovered without ever extending the stage
deadline; the bounded ladder, value guard, deny-all formatter session,
cumulative usage accounting and no-tool-replay rule are unchanged.

Update docs/model-results.md, docs/pipeline-performance-review.md and the
packaged skill references; add stage, opencode and server fixtures.
This commit is contained in:
2026-10-17 14:51:09 +01:00
parent 5adc961f88
commit 7b72b8f20f
15 changed files with 563 additions and 63 deletions
+5 -2
View File
@@ -55,7 +55,8 @@ func (c *AgentClient) Generate(ctx context.Context, config ModelConfig, prompt s
if c.command == nil {
connection, err := opencode.Open(ctx, opencode.Executable(), c.Directory, c.Backend)
if err != nil {
return "", err
// Connecting to the service failed before any session existed.
return "", harnessUnreachable(err)
}
defer connection.Close()
c.connection = connection
@@ -64,7 +65,9 @@ func (c *AgentClient) Generate(ctx context.Context, config ModelConfig, prompt s
rules := c.permissionRules()
data, err := c.call(ctx, "post", "/api/session", map[string]any{"title": "Pipeline audited agent stage", "agent": "build", "location": map[string]string{"directory": c.Directory}, "model": map[string]string{"providerID": config.Provider, "id": config.Model}, "permissions": rules})
if err != nil {
return "", err
// No prompt or tool call was admitted: a request failure here is a
// reachable retry rather than a reason to end the run.
return "", harnessUnreachable(err)
}
var created struct {
Data struct {
+40 -9
View File
@@ -27,15 +27,42 @@ const (
// diagnostics. It states the retained side effects and the cost of a full retry.
const finalResultGuidance = "completed edits and tool side effects are retained and not undone; a full retry repeats work"
// harnessTransportFailure is the single classifier shared by both transport
// sentinels and the typed OpenCode error: a request, poll or readback failure
// that reports as the fixed HARNESS TRANSPORT category. A bare context deadline
// is classified separately so a genuine stage overrun is never relabeled as a
// transport failure.
func harnessTransportFailure(err error) bool {
var openCode *openCodeError
return errors.Is(err, ErrHarnessUnreachable) || errors.Is(err, ErrHarnessTransport) || errors.As(err, &openCode)
}
// harnessReachFailure reports whether err is a pre-admission harness reach
// failure. It is distinct from a post-admission ErrHarnessTransport failure: no
// session or prompt was admitted, so the retry replays no work.
func harnessReachFailure(err error) bool {
return errors.Is(err, ErrHarnessUnreachable)
}
// admittedWorker is implemented by a client that can admit tool work before its
// final result is read, so the retry loop can refuse to replay it without a
// per-client type switch.
type admittedWorker interface{ workAdmitted() bool }
// workAdmitted reports whether the client admitted any prompt or tool call, so
// the retry loop may retry a transport failure on any stage only when it is
// false, and only a read-only stage otherwise.
func (c *AgentClient) workAdmitted() bool { return c.WorkStarted }
func (c *PiClient) workAdmitted() bool { return c.WorkStarted }
// modelFailureCategory classifies a stage failure using error identity only, so
// the label stays sanitized and bounded. Validation is checked first: a
// structured-output failure is never reported as a transport failure and vice versa.
func modelFailureCategory(err error) string {
var openCode *openCodeError
switch {
case errors.Is(err, ErrInvalidModelResult):
return finalResultValidation
case errors.Is(err, ErrHarnessTransport), errors.As(err, &openCode), errors.Is(err, context.DeadlineExceeded):
case harnessTransportFailure(err), errors.Is(err, context.DeadlineExceeded):
return harnessTransport
default:
return ""
@@ -294,15 +321,19 @@ func (m ModelStage) Run(ctx context.Context, def Definition, input Values) (Resu
break
}
replayPostAdmission = safeToReplay(def) && replayablePostAdmission(err)
// Never blindly replay admitted tool work: only a read-only stage may
// retry a post-admission deadline or transport failure.
if agent, ok := client.(*AgentClient); ok && agent.WorkStarted && !replayPostAdmission {
// A reach failure observed before any work was admitted replays
// nothing, so it is retryable within the existing budget for any
// stage. After admission, only an explicit read-only stage may
// retry; admitted tool work is never replayed.
workStarted := false
if worker, ok := client.(admittedWorker); ok {
workStarted = worker.workAdmitted()
}
if workStarted && !replayPostAdmission {
break
}
if pi, ok := client.(*PiClient); ok && pi.WorkStarted && !replayPostAdmission {
break
}
if attempt == spec.Config.Retries || (!retryableModelError(err) && !errors.Is(err, context.DeadlineExceeded) && !replayPostAdmission) {
preAdmissionReach := !workStarted && harnessReachFailure(err)
if attempt == spec.Config.Retries || (!retryableModelError(err) && !errors.Is(err, context.DeadlineExceeded) && !replayPostAdmission && !preAdmissionReach) {
break
}
}
+17
View File
@@ -18,6 +18,23 @@ var ErrInvalidModelResult = errors.New("invalid model stage result")
// validation and never replay admitted tool work.
var ErrHarnessTransport = errors.New("harness transport failure")
// ErrHarnessUnreachable marks a request/transport failure observed before the
// harness admitted any agent work: connecting to the service, or creating the
// session. Nothing was executed or admitted, so re-attempting replays no prompt
// or tool call and is safe for any stage, mutating or not. Post-admission
// readback, poll and agent-execution failures stay ErrHarnessTransport so the
// single fixed HARNESS TRANSPORT category and the no-tool-replay rule are
// unchanged.
var ErrHarnessUnreachable = errors.New("harness unreachable")
// harnessUnreachable marks err as a pre-admission reach failure. It is the single
// wrap shared by the connect and session-create paths of both client types, so
// they cannot drift: the sentinel and the underlying cause are always both
// preserved.
func harnessUnreachable(err error) error {
return fmt.Errorf("%w: %w", ErrHarnessUnreachable, err)
}
func modelPrompt(def Definition, spec ModelSpec, input Values) (string, error) {
outcomes := make([]string, 0, len(def.Edges))
for name := range def.Edges {
+20 -9
View File
@@ -97,10 +97,14 @@ func (c OpenCodeClient) call(ctx context.Context, method, path string, body any)
evidenceStatus = c.connection.LastHTTPStatus
}
c.Operations.record(OperationEvidence{Operation: method + " " + path, Backend: c.Backend, Executable: opencode.Executable(), Directory: c.Directory, ExitCode: -1, HTTPStatus: evidenceStatus, NativeOperation: c.connection.LastHTTPOperation, Diagnostic: err.Error(), Stdout: string(data)}, started)
if ctx.Err() != nil {
return nil, ctx.Err()
transport := &openCodeError{operation: method + " " + path, status: status, cause: err, diagnostic: err.Error()}
if ctxErr := ctx.Err(); ctxErr != nil {
// Keep the transport shape (operation/status) with the context
// cause: a deadline that fired while the request was in flight is
// both, and neither may be discarded.
return nil, errors.Join(ctxErr, transport)
}
return nil, &openCodeError{operation: method + " " + path, status: status, cause: err, diagnostic: err.Error()}
return nil, transport
}
return data, nil
}
@@ -146,14 +150,18 @@ func (c OpenCodeClient) call(ctx context.Context, method, path string, body any)
code = exit.ExitCode()
}
c.Operations.record(OperationEvidence{Operation: method + " " + path, Backend: c.Backend, Executable: cmd.Path, Directory: directory, ExitCode: code, HTTPStatus: status, Diagnostic: safeCommandDiagnostic(err, stdout.Bytes()), Stdout: stdout.String(), Stderr: stderr.String()}, started)
if ctx.Err() != nil {
return nil, ctx.Err()
}
// Do not embed provider responses, prompts, credentials, or CLI logs in errors.
// Keep the raw cause so errors.Is(err, exec.ErrWaitDelay) still holds while
// Error() stays sanitized. This branch is only reached with a non-nil Run
// error, so valid-looking partial stdout is never returned as success.
return nil, &openCodeError{operation: method + " " + path, status: status, cause: err, diagnostic: safeCommandDiagnostic(err, stdout.Bytes())}
transport := &openCodeError{operation: method + " " + path, status: status, cause: err, diagnostic: safeCommandDiagnostic(err, stdout.Bytes())}
if ctxErr := ctx.Err(); ctxErr != nil {
// Keep the sanitized transport detail (operation/status/exit) together
// with errors.Is(err, context.DeadlineExceeded) so the true cause is
// not replaced by a bare context error.
return nil, errors.Join(ctxErr, transport)
}
return nil, transport
}
if stdout.overflow {
return nil, fmt.Errorf("OpenCode response exceeds 1 MiB limit")
@@ -259,7 +267,8 @@ func (c *OpenCodeClient) Generate(ctx context.Context, config ModelConfig, promp
if c.command == nil {
connection, err := opencode.Open(ctx, opencode.Executable(), c.Directory, c.Backend)
if err != nil {
return "", err
// Connecting to the service failed before any session existed.
return "", harnessUnreachable(err)
}
defer connection.Close()
c.connection = connection
@@ -288,7 +297,9 @@ func (c *OpenCodeClient) Generate(ctx context.Context, config ModelConfig, promp
"permissions": []map[string]string{{"action": "*", "resource": "*", "effect": "deny"}},
})
if err != nil {
return "", err
// No prompt or tool call was admitted: a request failure here is a
// reachable retry rather than a reason to end the run.
return "", harnessUnreachable(err)
}
var session struct {
Data struct {
+13 -11
View File
@@ -129,14 +129,15 @@ func repairModelResult(ctx context.Context, client ModelGenerator, config ModelC
return Result{}, fmt.Errorf("%w; no isolated format repair available; recovery status %s", parseError, repairStatusUnrecoverable)
}
// One formatter request, independent of execution/transport retries. The
// deadline is derived from the payload size and the attempt's own remaining
// budget rather than a fixed short constant, so a larger result is not
// guaranteed to time out while the attempt context remains the outer bound.
// deadline is derived from the payload size, the stage timeout and the
// attempt's own remaining budget rather than a fixed short constant, so a
// larger or slower result is not guaranteed to time out while the attempt
// context remains the outer bound.
remaining := time.Hour
if deadline, ok := ctx.Deadline(); ok {
remaining = time.Until(deadline)
}
repairCtx, cancel := context.WithTimeout(ctx, repairDeadline(len(original), remaining))
repairCtx, cancel := context.WithTimeout(ctx, repairDeadline(len(original), remaining, config.Timeout))
defer cancel()
candidate, err := formatter.RepairFormat(repairCtx, config, original, parseError)
if err := ctx.Err(); err != nil {
@@ -291,9 +292,10 @@ func lexemeOffsets(text string, tokens []string) ([]int, bool) {
}
// Isolated formatter deadline bounds. The allowance grows by one second per KiB
// of payload up to a ceiling, is floored for ordinary payloads, and is clamped
// to the attempt's remaining budget so the stage/attempt context stays the outer
// bound and a large result is not guaranteed to time out.
// of payload up to a ceiling and by a share of the stage timeout, is floored for
// ordinary payloads, and is clamped to the attempt's remaining budget so the
// stage/attempt context stays the outer bound and a large or slow result is not
// guaranteed to time out.
const (
repairDeadlineFloor = 30 * time.Second
repairDeadlineMax = 10 * time.Minute
@@ -301,13 +303,13 @@ const (
)
// repairDeadline derives the formatter deadline. It is O(1) and monotonic
// non-decreasing in payloadBytes; it never exceeds remaining and, when the
// remaining budget allows, never drops below repairDeadlineFloor.
func repairDeadline(payloadBytes int, remaining time.Duration) time.Duration {
// non-decreasing in payloadBytes and stageTimeout; it never exceeds remaining
// and, when the remaining budget allows, never drops below repairDeadlineFloor.
func repairDeadline(payloadBytes int, remaining, stageTimeout time.Duration) time.Duration {
if remaining <= 0 {
return 0
}
allowance := repairDeadlineFloor + time.Duration(payloadBytes/1024)*time.Second
allowance := repairDeadlineFloor + time.Duration(payloadBytes/1024)*time.Second + stageTimeout/4
if allowance > repairDeadlineMax {
allowance = repairDeadlineMax
}
+17 -6
View File
@@ -306,26 +306,37 @@ func TestPresentationStrippingBeforeDeterministicRepair(t *testing.T) {
// TestRepairDeadlineIsMonotonicFlooredAndClamped proves the derived deadline, not
// a fixed constant, bounds the single formatter request.
func TestRepairDeadlineIsMonotonicFlooredAndClamped(t *testing.T) {
if got := repairDeadline(0, time.Hour); got != repairDeadlineFloor {
if got := repairDeadline(0, time.Hour, time.Minute); got < repairDeadlineFloor || got > repairDeadlineMax {
t.Fatalf("floor not applied: %s", got)
}
if got := repairDeadline(1<<30, 24*time.Hour); got != repairDeadlineMax {
if got := repairDeadline(1<<30, 24*time.Hour, time.Hour); got != repairDeadlineMax {
t.Fatalf("ceiling not applied: %s", got)
}
if got := repairDeadline(10, 0); got != 0 {
if got := repairDeadline(10, 0, time.Hour); got != 0 {
t.Fatalf("zero remaining should yield zero: %s", got)
}
if clamped := repairDeadline(1<<20, 5*time.Second); clamped != 5*time.Second-repairDeadlineMargin || clamped > 5*time.Second {
if clamped := repairDeadline(1<<20, 5*time.Second, time.Hour); clamped != 5*time.Second-repairDeadlineMargin || clamped > 5*time.Second {
t.Fatalf("remaining budget was not the bound: %s", clamped)
}
previous := time.Duration(0)
for size := 0; size <= 64<<10; size += 1024 {
got := repairDeadline(size, time.Hour)
got := repairDeadline(size, time.Hour, time.Minute)
if got < previous {
t.Fatalf("deadline not monotonic at %d: %s < %s", size, got, previous)
t.Fatalf("deadline not monotonic in payload at %d: %s < %s", size, got, previous)
}
previous = got
}
previous = time.Duration(0)
for stage := time.Duration(0); stage <= 2*time.Hour; stage += time.Minute {
got := repairDeadline(64<<10, time.Hour, stage)
if got < previous {
t.Fatalf("deadline not monotonic in stage timeout at %s: %s < %s", stage, got, previous)
}
previous = got
}
if got := repairDeadline(8<<10, time.Hour, time.Hour); got < repairDeadlineFloor {
t.Fatalf("ordinary payload was not floored: %s", got)
}
}
// TestShellStageRecoverableMalformedResultDoesNotFailRun proves a shell-enabled
+197
View File
@@ -0,0 +1,197 @@
package stage
import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"sync/atomic"
"testing"
"time"
"git.a-wan.net/alan/pipelines/internal/opencode"
)
// TestPreAdmissionReachFailureRetriesOnMutatingStage proves a failure to reach
// the harness before any prompt or tool call is admitted retries within the
// existing budget even on an edit stage, with a fresh session and no replayed
// prompt. Nothing was admitted, so no admitted work can be replayed.
func TestPreAdmissionReachFailureRetriesOnMutatingStage(t *testing.T) {
def := modelDefinition()
def.Blocks["tools"] = "edit"
def.Configs["retries"] = "1"
var sessions, prompts atomic.Int64
agent := &AgentClient{OpenCodeClient: OpenCodeClient{command: func(_ context.Context, _ string, args ...string) ([]byte, error) {
path := args[2]
switch {
case path == "/api/session":
if sessions.Add(1) == 1 {
return nil, errors.New("connection refused")
}
return []byte(`{"data":{"id":"ses_reach_2"}}`), nil
case strings.HasSuffix(path, "/prompt"):
prompts.Add(1)
return []byte(`{}`), nil
case path == "/api/session/active":
return []byte(`{"data":{}}`), nil
case strings.HasSuffix(path, finalAssistantReadback):
return []byte(`{"data":[{"finish":"stop","content":[{"type":"text","text":"{\"outcome\":\"success\",\"output\":{\"summary\":\"done\"}}"}]}]}`), nil
}
return nil, fmt.Errorf("unexpected path %s", path)
}}}
result, err := (ModelStage{Client: agent}).Run(context.Background(), def, nil)
if err != nil || result.Output["summary"] != "done" {
t.Fatalf("pre-admission reach failure was not retried to success: %v %v", result, err)
}
if sessions.Load() != 2 || prompts.Load() != 1 || agent.SessionID != "ses_reach_2" {
t.Fatalf("reach retry did not use exactly one fresh session: sessions=%d prompts=%d session=%q", sessions.Load(), prompts.Load(), agent.SessionID)
}
}
// TestPostAdmissionReadbackFailureRetriesOnlyOnReadOnlyStage proves a readback
// transport failure observed after the prompt was admitted is retried only on an
// explicit read-only stage; an edit, shell or legacy-bundle stage never replays
// the admitted prompt and ends with a HARNESS TRANSPORT failure.
func TestPostAdmissionReadbackFailureRetriesOnlyOnReadOnlyStage(t *testing.T) {
run := func(name string, setTools bool, tools string) (Result, error, int64, int64) {
t.Helper()
def := modelDefinition()
if setTools {
def.Blocks["tools"] = tools
}
def.Configs["retries"] = "1"
var sessions, prompts, readbacks atomic.Int64
agent := &AgentClient{OpenCodeClient: OpenCodeClient{command: func(_ context.Context, _ string, args ...string) ([]byte, error) {
path := args[2]
switch {
case path == "/api/session":
n := sessions.Add(1)
return []byte(fmt.Sprintf(`{"data":{"id":"ses_rb_%d"}}`, n)), nil
case strings.HasSuffix(path, "/prompt"):
prompts.Add(1)
return []byte(`{}`), nil
case path == "/api/session/active":
return []byte(`{"data":{}}`), nil
case strings.HasSuffix(path, finalAssistantReadback):
if readbacks.Add(1) == 1 {
// Truncated readback: a post-admission transport failure.
return []byte(`{"data":[{"finish":"stop","content":[{"type":"text","text":"{\"outcome\":`), nil
}
return []byte(`{"data":[{"finish":"stop","content":[{"type":"text","text":"{\"outcome\":\"success\",\"output\":{\"summary\":\"ok\"}}"}]}]}`), nil
case strings.HasSuffix(path, "/interrupt"):
return []byte(`{}`), nil
}
return nil, fmt.Errorf("unexpected path %s", path)
}}}
result, err := (ModelStage{Client: agent}).Run(context.Background(), def, nil)
return result, err, sessions.Load(), prompts.Load()
}
result, err, sessions, prompts := run("read-only", true, "read")
if err != nil || result.Output["summary"] != "ok" || sessions != 2 || prompts != 2 {
t.Fatalf("read-only readback failure was not retried: %v %v sessions=%d prompts=%d", result, err, sessions, prompts)
}
for _, tc := range []struct {
name string
setTools bool
tools string
}{
{"edit", true, "edit"},
{"shell", true, "shell"},
{"legacy", false, ""},
} {
result, err, sessions, prompts := run(tc.name, tc.setTools, tc.tools)
if !errors.Is(err, ErrHarnessTransport) || sessions != 1 || prompts != 1 {
t.Fatalf("%s stage replayed admitted work on a readback failure: err=%v sessions=%d prompts=%d", tc.name, err, sessions, prompts)
}
if result.Output != nil {
t.Fatalf("%s stage retained a partial result", tc.name)
}
if !strings.Contains(err.Error(), "HARNESS TRANSPORT") {
t.Fatalf("%s failure lost the transport category: %v", tc.name, err)
}
}
}
// TestExpiredContextDuringCLITransportKeepsTransportDetailAndDeadline proves an
// expired context during a real CLI request keeps both the sanitized transport
// detail (operation/exit) and errors.Is(err, context.DeadlineExceeded) instead
// of returning a bare context error that discards the cause.
func TestExpiredContextDuringCLITransportKeepsTransportDetailAndDeadline(t *testing.T) {
dir := t.TempDir()
executable := filepath.Join(dir, "opencode")
if err := os.WriteFile(executable, []byte("#!/bin/sh\nexec sleep 30\n"), 0700); err != nil {
t.Fatal(err)
}
t.Setenv("PIPELINES_OPENCODE", executable)
client := OpenCodeClient{Directory: dir}
ctx, cancel := context.WithTimeout(context.Background(), 40*time.Millisecond)
defer cancel()
_, err := client.call(ctx, "post", "/api/session", nil)
if err == nil || !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("expired transport call lost the context cause: %v", err)
}
var typed *openCodeError
if !errors.As(err, &typed) || typed.operation != "post /api/session" {
t.Fatalf("expired transport call discarded the typed transport error: %v", err)
}
if !strings.Contains(err.Error(), "OpenCode post /api/session") {
t.Fatalf("expired transport call discarded the operation detail: %v", err)
}
if !harnessTransportFailure(err) {
t.Fatalf("expired transport call was not classified as transport: %v", err)
}
}
// TestExpiredContextDuringNativeTransportKeepsTransportDetailAndDeadline proves
// the native V1 branch keeps both the typed transport error (the operation
// detail) and errors.Is(err, context.DeadlineExceeded) when the request failed
// under an expired context, instead of returning a bare context error that
// discards the transport shape. The native request path folds an in-flight
// deadline into ctx.Err(), so the retained transport detail is the operation and
// the parsed HTTP status is 0; the important invariant is that both shapes
// survive the join.
func TestExpiredContextDuringNativeTransportKeepsTransportDetailAndDeadline(t *testing.T) {
client := OpenCodeClient{Backend: "v1", connection: &opencode.Connection{Backend: "v1", URL: "http://127.0.0.1:1"}}
ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(-time.Second))
defer cancel()
_, err := client.call(ctx, "post", "/api/session/ses_native/generate", map[string]any{"prompt": "task"})
if err == nil || !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("expired native transport call lost the context cause: %v", err)
}
var typed *openCodeError
if !errors.As(err, &typed) || typed.operation != "post /api/session/ses_native/generate" {
t.Fatalf("expired native transport call discarded the typed transport error: %v", err)
}
if !strings.Contains(err.Error(), "post /api/session/ses_native/generate") {
t.Fatalf("expired native transport call discarded the operation detail: %v", err)
}
if !harnessTransportFailure(err) {
t.Fatalf("expired native transport call was not classified as transport: %v", err)
}
}
// TestHarnessTransportSentinelsShareOneClassifierAndCategory proves the two
// transport shapes share one classifier and the single HARNESS TRANSPORT label
// while a bare stage deadline stays distinct from a pre-admission reach failure.
func TestHarnessTransportSentinelsShareOneClassifierAndCategory(t *testing.T) {
unreachable := harnessUnreachable(errors.New("connect refused"))
if !harnessTransportFailure(unreachable) || !harnessReachFailure(unreachable) {
t.Fatal("pre-admission reach failure was not classified")
}
if !strings.Contains(wrapModelStageFailure("worker", unreachable).Error(), "HARNESS TRANSPORT") {
t.Fatalf("pre-admission reach failure lost the transport category: %v", wrapModelStageFailure("worker", unreachable))
}
post := fmt.Errorf("%w: final assistant readback was malformed or incomplete", ErrHarnessTransport)
if !harnessTransportFailure(post) || harnessReachFailure(post) {
t.Fatal("post-admission transport failure was misclassified as a pre-admission reach failure")
}
if !strings.Contains(wrapModelStageFailure("worker", post).Error(), "HARNESS TRANSPORT") {
t.Fatal("post-admission transport failure lost the transport category")
}
if harnessTransportFailure(context.DeadlineExceeded) || harnessReachFailure(context.DeadlineExceeded) {
t.Fatal("a bare stage deadline must not be a transport or reach failure")
}
}