Compare commits

...
Author SHA1 Message Date
ji ruo 48ae0ef22e fix(llm): recognize OpenCode Go usage limit errors for quota failover
- Add account/plan usage-limit exhaustion markers (`gousagelimiterror`, `usage limit reached`, `usage_limit_reached`, `usage limit exceeded`, `exceeded your usage limit`, `reached your usage limit`) to `agent.IsQuotaExhaustedMessage`.
- Preserve `transientQuotaLimit` filtering so RPM/TPM/rate_limit_error/too many requests remain transient.
- Add regression tests covering quota classification, 429->402 normalization without retry, and non-streaming task failover.

Fixes #184
2026-11-27 14:47:47 +08:00
3 changed files with 124 additions and 2 deletions

No files matched your search

+5 -2
View File
@@ -337,8 +337,9 @@ func (c Config) newProvider(client *http.Client, limiter *RequestLimiter) (llm.P
}
// IsQuotaExhaustedMessage deliberately recognizes only explicit balance,
// billing, credit, or quota-exhaustion signals. Generic 429/rate-limit text,
// authentication failures, network errors, and server failures are excluded.
// billing, credit, quota, or account/plan usage-limit exhaustion signals.
// Generic 429/rate-limit text, authentication failures, network errors, and
// server failures are excluded.
var nonFailoverHTTPStatus = regexp.MustCompile(`(?:status(?:\s+code)?|http(?:\s+status)?)\s*[=:]?\s*(?:401|403|5\d\d)\b`)
var transientQuotaLimit = regexp.MustCompile(`(?i)(?:\b(?:rpm|tpm|rpd|qps)\b|quota[_\s-]*metric|rate[_\s-]*limit|too many requests|(?:requests?|tokens?)\s+(?:per|/)\s*(?:second|minute)|(?:per|/)\s*(?:second|minute)\s+(?:requests?|tokens?)|generate[_\s-]*requests[_\s-]*per[_\s-]*(?:minute|second)|tokens?[_\s-]*per[_\s-]*(?:minute|second))`)
@@ -360,6 +361,8 @@ func IsQuotaExhaustedMessage(message string) bool {
"exceeded your current quota", "billing_hard_limit_reached",
"billing hard limit", "billing_not_active", "credit balance", "insufficient credit",
"insufficient balance", "balance is too low", "payment required", "status 402",
"gousagelimiterror", "usage limit reached", "usage_limit_reached",
"usage limit exceeded", "exceeded your usage limit", "reached your usage limit",
"余额不足", "额度不足", "额度已用尽", "欠费",
}
for _, marker := range markers {
+44
View File
@@ -25,6 +25,11 @@ func TestIsQuotaExhaustedMessage(t *testing.T) {
`billing_not_active`,
`credit balance is too low`,
`账户余额不足,请充值`,
`{"type":"error","error":{"type":"GoUsageLimitError","message":"OpenCode Go usage limit reached (5-hour, resets in 2h 9m). To keep going now, turn on Extra Usage or upgrade to Go Plus at https://opencode.ai/console/wrk_01KZNXXXXXXXXXXXXXXXDJFJH/go."},"metadata":{"workspace":"wrk_01KZNXXXXXXXXXXXXXXXXTEDJFJH","limitName":"5 hour"}}`,
`{"error":{"code":"usage_limit_reached","message":"plan window exhausted"}}`,
`monthly usage limit exceeded`,
`You have exceeded your usage limit`,
`You have reached your usage limit`,
}
for _, message := range positive {
if !IsQuotaExhaustedMessage(message) {
@@ -40,6 +45,10 @@ func TestIsQuotaExhaustedMessage(t *testing.T) {
`RESOURCE_EXHAUSTED: TPM quota exceeded`,
`tokens per minute quota exceeded`,
`rate_limit_exceeded: requests per second`,
`rate_limit_error: usage limit reached`,
`too many requests: usage limit exceeded`,
`RPM usage limit exceeded`,
`requests per minute usage limit reached`,
`status 401: invalid api key`,
`status 401: insufficient_quota`,
`HTTP 403: billing_hard_limit_reached`,
@@ -63,6 +72,12 @@ func TestQuotaAwareTransportOnlyNormalizesExplicitQuota429(t *testing.T) {
wantStatus int
}{
{name: "quota", status: http.StatusTooManyRequests, body: `{"code":"insufficient_quota"}`, wantStatus: http.StatusPaymentRequired},
{
name: "opencode go usage limit",
status: http.StatusTooManyRequests,
body: `{"type":"error","error":{"type":"GoUsageLimitError","message":"OpenCode Go usage limit reached (5-hour, resets in 2h 9m)."},"metadata":{"limitName":"5 hour"}}`,
wantStatus: http.StatusPaymentRequired,
},
{name: "ordinary rate limit", status: http.StatusTooManyRequests, body: `{"message":"rate limit exceeded"}`, wantStatus: http.StatusTooManyRequests},
{name: "server error", status: http.StatusInternalServerError, body: `insufficient_quota`, wantStatus: http.StatusInternalServerError},
}
@@ -129,3 +144,32 @@ func TestProviderDoesNotRetryExplicitQuota429(t *testing.T) {
t.Fatalf("explicit quota request retried %d times, want exactly one request", got)
}
}
func TestProviderCompleteDoesNotRetryOpenCodeGoUsageLimit429(t *testing.T) {
t.Parallel()
var requests atomic.Int32
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
requests.Add(1)
w.Header().Set("content-type", "application/json")
w.WriteHeader(http.StatusTooManyRequests)
_, _ = io.WriteString(w, `{"type":"error","error":{"type":"GoUsageLimitError","message":"OpenCode Go usage limit reached (5-hour, resets in 2h 9m). To keep going now, turn on Extra Usage or upgrade to Go Plus at https://opencode.ai/console/wrk_01KZNXXXXXXXXXXXXXXXDJFJH/go."},"metadata":{"workspace":"wrk_01KZNXXXXXXXXXXXXXXXXTEDJFJH","limitName":"5 hour"}}`)
}))
defer upstream.Close()
provider, err := ConfigFrom("openai", "test-model", upstream.URL, "test-key", "").NewProvider()
if err != nil {
t.Fatal(err)
}
_, _, _, err = provider.Complete(context.Background(), llm.CompletionRequest{
Messages: []llm.Message{llm.UserText("ping")},
})
if err == nil || !IsQuotaExhaustedMessage(err.Error()) {
t.Fatalf("expected explicit quota error, got %v", err)
}
if !strings.Contains(err.Error(), "status 402") {
t.Fatalf("expected 429 normalized to status 402, got %v", err)
}
if got := requests.Load(); got != 1 {
t.Fatalf("OpenCode Go usage limit 429 retried %d times, want 1", got)
}
}
+75
View File
@@ -5,9 +5,13 @@ import (
"encoding/json"
"errors"
"fmt"
"io"
"iter"
"net/http"
"net/http/httptest"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
@@ -119,6 +123,8 @@ func TestIsQuotaExhaustedError(t *testing.T) {
`HTTP status 402 Payment Required`,
`账户余额不足,请充值`,
`credit balance is too low`,
`openai: status 429: {"type":"error","error":{"type":"GoUsageLimitError","message":"OpenCode Go usage limit reached (5-hour, resets in 2h 9m)."}}`,
`openai: status 402: {"error":{"code":"usage_limit_reached"}}`,
}
for _, message := range positive {
if !isQuotaExhaustedError(errors.New(message)) {
@@ -131,6 +137,8 @@ func TestIsQuotaExhaustedError(t *testing.T) {
`RESOURCE_EXHAUSTED: rate limit exceeded`,
`HTTP status 429: quota exceeded for quota metric GenerateRequestsPerMinutePerProjectPerBaseModel`,
`RESOURCE_EXHAUSTED: TPM quota exceeded`,
`HTTP status 429: rate_limit_error: usage limit reached`,
`HTTP status 429: too many requests: usage limit exceeded`,
`HTTP status 401: invalid api key`,
`HTTP status 401: insufficient_quota`,
`HTTP status 403: forbidden`,
@@ -275,6 +283,73 @@ func TestTaskLLMStreamRetriesPreStreamQuotaOnNextProfile(t *testing.T) {
}
}
func TestTaskLLMCompleteFailsOverOnOpenCodeGoUsageLimit(t *testing.T) {
t.Parallel()
var firstCalls, secondCalls atomic.Int32
firstServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
firstCalls.Add(1)
w.Header().Set("content-type", "application/json")
w.WriteHeader(http.StatusTooManyRequests)
_, _ = io.WriteString(w, `{"type":"error","error":{"type":"GoUsageLimitError","message":"OpenCode Go usage limit reached (5-hour, resets in 2h 9m). To keep going now, turn on Extra Usage or upgrade to Go Plus at https://opencode.ai/console/wrk_01KZNXXXXXXXXXXXXXXXDJFJH/go."},"metadata":{"workspace":"wrk_01KZNXXXXXXXXXXXXXXXXTEDJFJH","limitName":"5 hour"}}`)
}))
defer firstServer.Close()
secondServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
secondCalls.Add(1)
w.Header().Set("content-type", "application/json")
w.WriteHeader(http.StatusOK)
_, _ = io.WriteString(w, `{"id":"chatcmpl-1","object":"chat.completion","choices":[{"index":0,"message":{"role":"assistant","content":"fallback-ok"},"finish_reason":"stop"}],"usage":{"prompt_tokens":1,"completion_tokens":1}}`)
}))
defer secondServer.Close()
firstProv, err := agent.ConfigFrom("openai", "test-model", firstServer.URL, "key-1", "").NewProvider()
if err != nil {
t.Fatal(err)
}
secondProv, err := agent.ConfigFrom("openai", "test-model", secondServer.URL, "key-2", "").NewProvider()
if err != nil {
t.Fatal(err)
}
active := int64(11)
transitions := 0
var exhaustCause error
hooks := taskLLMStreamHooks{
current: func() (taskLLMSelection, error) {
if active == 11 {
return taskLLMSelection{profileID: 11, provider: firstProv}, nil
}
return taskLLMSelection{profileID: 22, provider: secondProv}, nil
},
exhaust: func(selection taskLLMSelection, cause error) (db.TaskLLMTransition, error) {
if selection.profileID != 11 {
t.Fatalf("unexpected exhausted profile %d", selection.profileID)
}
exhaustCause = cause
active = 22
next := active
return db.TaskLLMTransition{PreviousProfileID: 11, NextProfileID: &next, Advanced: true}, nil
},
transition: func(taskLLMSelection, db.TaskLLMTransition, error) { transitions++ },
}
msg, _, _, err := completeTaskLLM(context.Background(), "9", llm.CompletionRequest{
Messages: []llm.Message{llm.UserText("ping")},
}, hooks)
if err != nil {
t.Fatalf("expected failover to succeed, got %v", err)
}
if got := msg.Text(); got != "fallback-ok" {
t.Fatalf("reply=%q, want fallback-ok", got)
}
if firstCalls.Load() != 1 || secondCalls.Load() != 1 || transitions != 1 {
t.Fatalf("calls first=%d second=%d transitions=%d, want 1/1/1", firstCalls.Load(), secondCalls.Load(), transitions)
}
if exhaustCause == nil || !strings.Contains(exhaustCause.Error(), "status 402") {
t.Fatalf("exhaustCause=%v, want normalized status 402", exhaustCause)
}
}
func TestTaskLLMStreamRetriesAfterNonContentStartEvent(t *testing.T) {
t.Parallel()
quota := errors.New("anthropic: status 402: insufficient credit balance")