Merge branch 'cleanup/low-batch': low-priority sweep (L1/L3/L4/L5/L10)
tokens image accounting, Qwen usage stats, one-time degraded-persistence warning (AppendEntry+Rewrite), RunSync abort surfacing, retry classifier bounded 429/529 forms + typed Gemini APIError path.
This commit is contained in:
commit
34435736c5
9 files changed
+181
-7
No files matched your search
+26
-6
@@ -6,6 +6,7 @@ import (
|
||||
|
||||
anthropic "github.com/anthropics/anthropic-sdk-go"
|
||||
openai "github.com/sashabaranov/go-openai"
|
||||
"google.golang.org/genai"
|
||||
)
|
||||
|
||||
// IsRetryableModelError reports whether err is a transient capacity
|
||||
@@ -14,14 +15,17 @@ import (
|
||||
//
|
||||
// - Anthropic 429 (rate limit) and 529 (overloaded)
|
||||
// - OpenAI 429 (rate limit) and 5xx (server / overloaded)
|
||||
// - Gemini 429 (quota/RESOURCE_EXHAUSTED) and 5xx (overloaded/unavailable),
|
||||
// recognized via a typed genai.APIError path (Gemini's error string
|
||||
// "Error 429, ... Status: RESOURCE_EXHAUSTED" does not match the
|
||||
// bounded substring forms, so the typed path is required).
|
||||
//
|
||||
// Anything else (including 4xx auth/validation errors) returns false:
|
||||
// retrying with a different model wouldn't fix the underlying problem.
|
||||
//
|
||||
// Errors from local providers (Ollama, etc.) and Gemini are NOT
|
||||
// classified as retryable here; their failure modes are different
|
||||
// and a model swap rarely helps. Add cases as new providers
|
||||
// accumulate retry experience.
|
||||
// Errors from local providers (Ollama, etc.) are NOT classified as
|
||||
// retryable here; their failure modes are different and a model swap
|
||||
// rarely helps. Add cases as new providers accumulate retry experience.
|
||||
func IsRetryableModelError(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
@@ -47,13 +51,29 @@ func IsRetryableModelError(err error) bool {
|
||||
return openaiReqErr.HTTPStatusCode == 429 ||
|
||||
(openaiReqErr.HTTPStatusCode >= 500 && openaiReqErr.HTTPStatusCode < 600)
|
||||
}
|
||||
// genai.APIError.Error() is a value receiver, so the error interface is
|
||||
// satisfied by the value; errors.As targets the value type.
|
||||
var genaiErr genai.APIError
|
||||
if errors.As(err, &genaiErr) {
|
||||
return genaiErr.Code == 429 ||
|
||||
(genaiErr.Code >= 500 && genaiErr.Code < 600)
|
||||
}
|
||||
|
||||
// Last-ditch: substring match on common SDK error wrappers that
|
||||
// don't unwrap cleanly to typed errors. Cheap belt-and-braces;
|
||||
// only reached when no typed match found above.
|
||||
msg := strings.ToLower(err.Error())
|
||||
if strings.Contains(msg, "429") || strings.Contains(msg, "529") ||
|
||||
strings.Contains(msg, "rate limit") || strings.Contains(msg, "overloaded") {
|
||||
// Bounded forms so a bare "429"/"529" inside a request id or unrelated
|
||||
// digits doesn't trigger a retry. Word matches stay as-is (specific).
|
||||
for _, sig := range []string{
|
||||
"status 429", "code: 429", "code:429", " 429 ", "429 too many requests",
|
||||
"status 529", "code: 529", "code:529", " 529 ", "529 overloaded",
|
||||
} {
|
||||
if strings.Contains(msg, sig) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
if strings.Contains(msg, "rate limit") || strings.Contains(msg, "overloaded") {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
|
||||
@@ -8,8 +8,26 @@ import (
|
||||
anthropic "github.com/anthropics/anthropic-sdk-go"
|
||||
openai "github.com/sashabaranov/go-openai"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"google.golang.org/genai"
|
||||
)
|
||||
|
||||
func TestIsRetryable_Gemini429(t *testing.T) {
|
||||
// Mirror genai.APIError's real shape.
|
||||
err := genai.APIError{Code: 429, Message: "Resource has been exhausted (e.g. check quota).", Status: "RESOURCE_EXHAUSTED"}
|
||||
require.True(t, IsRetryableModelError(err))
|
||||
}
|
||||
|
||||
func TestIsRetryable_Gemini503(t *testing.T) {
|
||||
err := genai.APIError{Code: 503, Message: "The model is overloaded.", Status: "UNAVAILABLE"}
|
||||
require.True(t, IsRetryableModelError(err))
|
||||
}
|
||||
|
||||
func TestIsRetryable_Gemini400NotRetryable(t *testing.T) {
|
||||
err := genai.APIError{Code: 400, Message: "Invalid argument", Status: "INVALID_ARGUMENT"}
|
||||
require.False(t, IsRetryableModelError(err))
|
||||
}
|
||||
|
||||
func TestIsRetryableModelErrorAnthropic429(t *testing.T) {
|
||||
err := &anthropic.Error{StatusCode: 429}
|
||||
assert.True(t, IsRetryableModelError(err))
|
||||
@@ -89,3 +107,13 @@ func TestIsRetryableModelErrorUnrelatedError(t *testing.T) {
|
||||
err := errors.New("some other failure")
|
||||
assert.False(t, IsRetryableModelError(err))
|
||||
}
|
||||
|
||||
func TestRetry_DigitsInRequestIDNotRetryable(t *testing.T) {
|
||||
err := errors.New("request failed: req_abc429def something went wrong")
|
||||
require.False(t, IsRetryableModelError(err))
|
||||
}
|
||||
|
||||
func TestRetry_RealStatus429Retryable(t *testing.T) {
|
||||
err := errors.New("openai: error, status 429 too many requests")
|
||||
require.True(t, IsRetryableModelError(err))
|
||||
}
|
||||
@@ -206,8 +206,9 @@ func (p *QwenProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (<-c
|
||||
openaiReq := openai.ChatCompletionRequest{
|
||||
Model: model,
|
||||
Messages: msgs,
|
||||
MaxTokens: maxTokens,
|
||||
MaxCompletionTokens: maxTokens,
|
||||
Stream: true,
|
||||
StreamOptions: &openai.StreamOptions{IncludeUsage: true},
|
||||
}
|
||||
|
||||
if len(tools) > 0 {
|
||||
|
||||
@@ -896,6 +896,37 @@ func TestRun_AbortMidDispatchProducesPairedSession(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestRunSync_ReturnsErrorOnAbort verifies that RunSync surfaces an aborted run
|
||||
// as a non-nil error (context.Canceled) rather than returning (partialText,
|
||||
// nil). Cron/sync callers must be able to distinguish a completed run from a
|
||||
// cancelled one. Reuses the same abort scaffolding as
|
||||
// TestRun_AbortMidDispatchProducesPairedSession (a tool batch + cancelOnNth).
|
||||
func TestRunSync_ReturnsErrorOnAbort(t *testing.T) {
|
||||
threeToolCalls := []llm.ToolCall{
|
||||
{ID: "tc_0", Name: "noop", Input: json.RawMessage(`{}`)},
|
||||
{ID: "tc_1", Name: "noop", Input: json.RawMessage(`{}`)},
|
||||
{ID: "tc_2", Name: "noop", Input: json.RawMessage(`{}`)},
|
||||
}
|
||||
llmFake := &threeToolCallLLM{toolCalls: threeToolCalls}
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
count := 0
|
||||
exec := &cancelOnNthExecutor{n: 1, cancel: cancel, count: &count}
|
||||
|
||||
r := &Runtime{
|
||||
LLM: llmFake,
|
||||
Tools: exec,
|
||||
Session: session.NewSession("a", "k"),
|
||||
AgentID: "a",
|
||||
Model: "test-model",
|
||||
MaxTurns: 5,
|
||||
}
|
||||
|
||||
_, err := r.RunSync(ctx, "go", nil)
|
||||
require.Error(t, err)
|
||||
require.ErrorIs(t, err, context.Canceled)
|
||||
}
|
||||
|
||||
// threeToolCallLLM emits the configured tool_calls as one assistant turn,
|
||||
// then EventDone. On the next call (after tool results, if the runtime
|
||||
// loops back), emits only EventDone with no tool_calls so Run terminates.
|
||||
|
||||
@@ -849,6 +849,8 @@ func (r *Runtime) RunSync(ctx context.Context, userMsg string, images []llm.Imag
|
||||
switch event.Type {
|
||||
case EventTextDelta:
|
||||
response.WriteString(event.Text)
|
||||
case EventAborted:
|
||||
return response.String(), context.Canceled
|
||||
case EventError:
|
||||
return response.String(), event.Error
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
)
|
||||
|
||||
@@ -24,6 +25,17 @@ type SessionInfo struct {
|
||||
type Store struct {
|
||||
baseDir string
|
||||
mu sync.Mutex
|
||||
degraded atomic.Bool
|
||||
}
|
||||
|
||||
// markDegraded emits a single warning the first time session persistence
|
||||
// fails, so a user notices that in-memory state may not survive a restart.
|
||||
// Subsequent failures stay at their existing Error level to avoid log spam.
|
||||
func (s *Store) markDegraded(reason string, err error) {
|
||||
if s.degraded.CompareAndSwap(false, true) {
|
||||
slog.Warn("session persistence degraded; in-memory state may not survive restart",
|
||||
"reason", reason, "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
// NewStore creates a new session store.
|
||||
@@ -94,6 +106,7 @@ func (s *Store) AppendEntry(sess *Session, entry SessionEntry) {
|
||||
|
||||
dir := s.sessionDir(sess.AgentID)
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
s.markDegraded("create session dir", err)
|
||||
slog.Error("failed to create session dir", "error", err)
|
||||
return
|
||||
}
|
||||
@@ -101,6 +114,7 @@ func (s *Store) AppendEntry(sess *Session, entry SessionEntry) {
|
||||
path := s.sessionPath(sess.AgentID, sess.Key)
|
||||
f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600)
|
||||
if err != nil {
|
||||
s.markDegraded("open session file", err)
|
||||
slog.Error("failed to open session file", "error", err)
|
||||
return
|
||||
}
|
||||
@@ -114,6 +128,7 @@ func (s *Store) AppendEntry(sess *Session, entry SessionEntry) {
|
||||
|
||||
data = append(data, '\n')
|
||||
if _, err := f.Write(data); err != nil {
|
||||
s.markDegraded("write session entry", err)
|
||||
slog.Error("failed to write session entry", "error", err)
|
||||
}
|
||||
}
|
||||
@@ -252,6 +267,7 @@ func (s *Store) Rewrite(sess *Session) {
|
||||
|
||||
dir := s.sessionDir(sess.AgentID)
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
s.markDegraded("create session dir", err)
|
||||
slog.Error("failed to create session dir", "error", err)
|
||||
return
|
||||
}
|
||||
@@ -260,6 +276,7 @@ func (s *Store) Rewrite(sess *Session) {
|
||||
|
||||
f, err := os.Create(path)
|
||||
if err != nil {
|
||||
s.markDegraded("create session file for rewrite", err)
|
||||
slog.Error("failed to create session file for rewrite", "error", err)
|
||||
return
|
||||
}
|
||||
@@ -277,6 +294,7 @@ func (s *Store) Rewrite(sess *Session) {
|
||||
}
|
||||
|
||||
if err := w.Flush(); err != nil {
|
||||
s.markDegraded("flush session file", err)
|
||||
slog.Error("failed to flush session file", "error", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package session
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestStore_DegradedPersistenceWarnsOnce(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
prev := slog.Default()
|
||||
slog.SetDefault(slog.New(slog.NewTextHandler(&buf, &slog.HandlerOptions{Level: slog.LevelWarn})))
|
||||
defer slog.SetDefault(prev)
|
||||
|
||||
// Make a path where the agent dir cannot be created: a regular FILE used
|
||||
// as baseDir means sessionDir(agentID) = <file>/<agentID> and MkdirAll fails.
|
||||
tmp := t.TempDir()
|
||||
blocker := filepath.Join(tmp, "blocker")
|
||||
require.NoError(t, os.WriteFile(blocker, []byte("x"), 0o600))
|
||||
s := NewStore(blocker)
|
||||
|
||||
sess := &Session{AgentID: "a", Key: "k"}
|
||||
s.AppendEntry(sess, SessionEntry{})
|
||||
s.AppendEntry(sess, SessionEntry{})
|
||||
s.AppendEntry(sess, SessionEntry{})
|
||||
|
||||
require.Equal(t, 1, strings.Count(buf.String(), "session persistence degraded"),
|
||||
"degraded warning must fire exactly once across multiple failures")
|
||||
}
|
||||
|
||||
func TestStore_RewriteDegradedWarns(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
prev := slog.Default()
|
||||
slog.SetDefault(slog.New(slog.NewTextHandler(&buf, &slog.HandlerOptions{Level: slog.LevelWarn})))
|
||||
defer slog.SetDefault(prev)
|
||||
|
||||
tmp := t.TempDir()
|
||||
blocker := filepath.Join(tmp, "blocker")
|
||||
require.NoError(t, os.WriteFile(blocker, []byte("x"), 0o600))
|
||||
s := NewStore(blocker)
|
||||
|
||||
sess := &Session{AgentID: "a", Key: "k"}
|
||||
s.Rewrite(sess)
|
||||
|
||||
require.Equal(t, 1, strings.Count(buf.String(), "session persistence degraded"),
|
||||
"Rewrite failure must emit the degraded warning")
|
||||
}
|
||||
@@ -21,6 +21,10 @@ func Estimate(msgs []llm.Message, systemPrompt string, tools []llm.ToolDef) int
|
||||
for _, tc := range m.ToolCalls {
|
||||
total += len(tc.ID) + len(tc.Name) + len(tc.Input)
|
||||
}
|
||||
// Images are not part of Content (Images is json:"-"); approximate
|
||||
// each attached image's token cost. perImageTokens is expressed in
|
||||
// tokens, so multiply by 4 to survive the final divide-by-4.
|
||||
total += len(m.Images) * perImageTokens * 4
|
||||
}
|
||||
for _, t := range tools {
|
||||
total += len(t.Name) + len(t.Description) + len(t.Parameters)
|
||||
@@ -33,6 +37,12 @@ func Estimate(msgs []llm.Message, systemPrompt string, tools []llm.ToolDef) int
|
||||
// since the final divide-by-4 maps it back to tokens.
|
||||
const perMessageOverhead = 3
|
||||
|
||||
// perImageTokens approximates the token cost of one attached image. Vision
|
||||
// models bill images by tiles/resolution; ~1500 tokens is a deliberately
|
||||
// conservative flat estimate so image-heavy sessions trigger preventive
|
||||
// compaction rather than hitting a reactive overflow.
|
||||
const perImageTokens = 1500
|
||||
|
||||
// ContextWindow returns the maximum input tokens for the given
|
||||
// "provider/model" identifier.
|
||||
//
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/sausheong/harness/llm"
|
||||
)
|
||||
@@ -97,6 +98,17 @@ func TestContextWindowProxyProviderDetectedByModelFamily(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestEstimate_CountsImages(t *testing.T) {
|
||||
textOnly := []llm.Message{{Role: "user", Content: "hello"}}
|
||||
withImg := []llm.Message{{Role: "user", Content: "hello", Images: []llm.ImageContent{
|
||||
{MimeType: "image/png", Data: []byte("x")},
|
||||
{MimeType: "image/png", Data: []byte("y")},
|
||||
}}}
|
||||
base := Estimate(textOnly, "", nil)
|
||||
withImages := Estimate(withImg, "", nil)
|
||||
require.GreaterOrEqual(t, withImages-base, 2*perImageTokens)
|
||||
}
|
||||
|
||||
func TestContextWindowOllamaDefault(t *testing.T) {
|
||||
// Without RegisterOllamaContext call, ollama models fall back to a sane default
|
||||
assert.Equal(t, 32000, ContextWindow("local/qwen2.5:3b-instruct"))
|
||||
|
||||
Reference in new issue
Block a user