Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(taskfailure): classify per-minute token quota rejections as rate limits (MUL-8456) (#9775)
YANSHUO HUANGb5cd01af8a7e
diff --git a/server/pkg/taskfailure/classify.go b/server/pkg/taskfailure/classify.goindex 8ab75f8a85..0738704eb9 100644--- a/server/pkg/taskfailure/classify.go+++ b/server/pkg/taskfailure/classify.go@@ -61,6 +61,42 @@ func isUsageLimit403(lower string) bool {return httpForbiddenCodeRe.MatchString(lower) && strings.Contains(lower, "usage limit")}+// tokenRateLimitRe matches the per-minute quota labels a gateway prints on a+// rejection: TPM (tokens per minute) and RPM (requests per minute).+var tokenRateLimitRe = regexp.MustCompile(`(^|[^0-9a-z])(tpm|rpm)([^0-9a-z]|$)`)++// isTokenRateLimit reports a per-minute quota rejection. It shares the "token"+// and "limit" words that rule 1 matches ("Token usage exceeds the current model+// TPM (tokens per minute) limit 1000000"), but it is a rate limit to wait out,+// not a full context window.+func isTokenRateLimit(lower string) bool {+ return containsAny(lower, "per minute", "rate limit", "rate_limit_error") ||+ tokenRateLimitRe.MatchString(lower)+}++// isTokenQuotaRejection is the quota case of rule 1's token + limit match.+// Shared by Classify and NormalizeDaemonReason, like isUsageLimit403, so new+// and old daemons land on the same reason.+func isTokenQuotaRejection(lower string) bool {+ // A request larger than the entire TPM allowance cannot succeed after the+ // quota resets. Preserve its existing resume-unsafe overflow handling.+ return strings.Contains(lower, "token") && strings.Contains(lower, "limit") &&+ isTokenRateLimit(lower) && !strings.Contains(lower, "request too large")+}++// explicitContextOverflow reports wording that names the context window or the+// prompt size outright. It wins over the quota guard, so a real overflow that+// also mentions a limit still lands in context_overflow.+func explicitContextOverflow(lower string) bool {+ return containsAny(lower,+ "context length",+ "context_length_exceeded",+ "maximum context",+ "prompt is too long",+ "context size has been exceeded",+ ) || containsAny(lower, contextWindowExceededWitnesses...)+}+// Classify maps a free-form error string from the agent runtime / CLI// to one of the 14 agent_error.* sub-reasons. Always returns a valid// Reason; falls back to ReasonAgentUnknown when no rule matches and for@@ -128,22 +164,21 @@ func Classify(rawError string) Reason {case isUsageLimit403(lower):return ReasonAgentProviderQuotaLimit+ // 1a. Per-minute token or request quota (TPM / RPM). Rule 1's token ++ // limit clause matches this wording too, so the quota guard must come+ // first. The quota is a rate limit to wait out, not a full context+ // window; explicit overflow wording still wins.+ case isTokenQuotaRejection(lower) && !explicitContextOverflow(lower):+ return ReasonAgentProviderCapacityOrRateLimit+// 1. Context / token window overflow. Checked early so "token// limit" doesn't get swallowed by the broader "limit" / "quota"// rule below.- case containsAny(lower,- "context length",- "context_length_exceeded",- "maximum context",- "prompt is too long",- "context size has been exceeded",- ),- containsAny(lower, contextWindowExceededWitnesses...),+ case explicitContextOverflow(lower),// SQL had `%token%limit%` — ILIKE wildcard between tokens. We- // approximate with both substrings present, which catches- // "token limit", "tokens per minute limit", etc., without the- // false positives a naive `Contains("token") || Contains("limit")`- // would generate.+ // approximate with both substrings present, which catches "token+ // limit" and similar wording. Per-minute quota wording goes to rule+ // 1a above, so it never reaches this clause.strings.Contains(lower, "token") && strings.Contains(lower, "limit"):return ReasonAgentContextOverflow@@ -665,6 +700,13 @@ var legacyUsageLimit403Reasons = map[string]bool{"agent_error": true,}+// legacyTokenRateLimitReasons are the buckets an older daemon lands a+// per-minute token quota rejection in: context_overflow, from the token + limit+// clause of its rule 1 before isTokenQuotaRejection existed.+var legacyTokenRateLimitReasons = map[string]bool{+ string(ReasonAgentContextOverflow): true,+}+// NormalizeDaemonReason upgrades a failure_reason reported by an older daemon// onto the taxonomy this server understands, using the raw error text as the// witness. It returns the reason unchanged when nothing applies.@@ -696,6 +738,13 @@ func NormalizeDaemonReason(reason, rawError string) Reason {if legacyUsageLimit403Reasons[reason] && isUsageLimit403(strings.ToLower(rawError)) {return ReasonAgentProviderQuotaLimit}+ // An older daemon whose rule 1 predates the quota guard reports a TPM or RPM+ // rejection as context_overflow. Relabel it unless the text also names the+ // context window outright.+ if rawLower := strings.ToLower(rawError); legacyTokenRateLimitReasons[reason] &&+ isTokenQuotaRejection(rawLower) && !explicitContextOverflow(rawLower) {+ return ReasonAgentProviderCapacityOrRateLimit+ }if legacySkillBundleReasons[reason] &&strings.HasPrefix(strings.TrimSpace(rawError), legacySkillBundlePrefix) {return ReasonSkillBundleUnavailablediff --git a/server/pkg/taskfailure/classify_test.go b/server/pkg/taskfailure/classify_test.goindex 92ccc12007..878d5532a5 100644--- a/server/pkg/taskfailure/classify_test.go+++ b/server/pkg/taskfailure/classify_test.go@@ -672,6 +672,79 @@ func TestClassifyKeepsDeadlineExceededAsProviderNetwork(t *testing.T) {}}+// TestClassifyTokenQuotaIsCapacity pins per-minute token and request quota+// rejections to the capacity bucket. Gateways answer them with the "token" and+// "limit" words that rule 1 matches, so they are a rate limit, not a full+// context window. Explicit overflow wording still lands in context_overflow.+func TestClassifyTokenQuotaIsCapacity(t *testing.T) {+ t.Parallel()++ cases := []struct {+ name string+ in string+ want Reason+ }{+ {"TPM quota with rate_limit_error body", `API Error: Request rejected (429) · {"type":"error","error":{"type":"rate_limit_error","code":"429003","message":"Token usage exceeds the current model TPM (tokens per minute) limit 1000000. Please reduce the request frequency."}}`, ReasonAgentProviderCapacityOrRateLimit},+ {"TPM quota without status line", "Token usage exceeds the current model TPM (tokens per minute) limit 4000000", ReasonAgentProviderCapacityOrRateLimit},+ {"input tokens per minute rate limit", "This request would exceed your organization's rate limit of 30000 input tokens per minute", ReasonAgentProviderCapacityOrRateLimit},+ {"explicit overflow beats quota wording", "prompt is too long: 250000 tokens > 200000 maximum (tokens per minute limit also reported)", ReasonAgentContextOverflow},+ {"plain token limit stays overflow", "Hit the token limit for this conversation", ReasonAgentContextOverflow},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ t.Parallel()+ if got := Classify(tc.in); got != tc.want {+ t.Errorf("Classify(%q) = %q, want %q", tc.in, got, tc.want)+ }+ })+ }+}++// TestNormalizeDaemonReasonUpgradesTokenQuota covers a daemon whose rule 1+// predates the quota guard: it reports context_overflow for a TPM rejection,+// and the server relabels it. An explicit overflow keeps its label.+func TestNormalizeDaemonReasonUpgradesTokenQuota(t *testing.T) {+ t.Parallel()++ quota := "API Error: Request rejected (429) · Token usage exceeds the current model TPM (tokens per minute) limit 1000000"+ if got := NormalizeDaemonReason(string(ReasonAgentContextOverflow), quota); got != ReasonAgentProviderCapacityOrRateLimit {+ t.Errorf("NormalizeDaemonReason(context_overflow, TPM quota) = %q, want %q", got, ReasonAgentProviderCapacityOrRateLimit)+ }+ if got := NormalizeDaemonReason(string(ReasonAgentContextOverflow), "prompt is too long: tokens per minute limit reached"); got != ReasonAgentContextOverflow {+ t.Errorf("explicit overflow relabelled to %q", got)+ }+ if got := NormalizeDaemonReason(string(ReasonAgentContextOverflow), "you exceeded the token limit"); got != ReasonAgentContextOverflow {+ t.Errorf("ordinary token overflow changed to %q", got)+ }+}++func TestTokenQuotaRequestSize(t *testing.T) {+ t.Parallel()++ const oversized = "Request too large for gpt-4o on tokens per min (TPM): Limit 30000, Requested 45000. The input or output tokens must be reduced in order to run successfully."+ cases := []struct {+ name string+ in string+ want Reason+ }{+ {"Azure token rate limit without per-minute wording", "rate_limit_exceeded: Your requests to gpt-6.1-sol for gpt-6.1-sol in eastus2 have exceeded token rate limit.", ReasonAgentProviderCapacityOrRateLimit},+ {"temporary TPM exhaustion", "Rate limit reached for gpt-4o on tokens per min (TPM): Limit 30000, Used 29000, Requested 2000. Please try again in 2s.", ReasonAgentProviderCapacityOrRateLimit},+ {"single request exceeds TPM allowance", oversized, ReasonAgentContextOverflow},+ {"single request exceeds TPM allowance with HTTP wrapper", "API Error: 429 " + oversized, ReasonAgentContextOverflow},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ t.Parallel()+ if got := Classify(tc.in); got != tc.want {+ t.Errorf("Classify(%q) = %q, want %q", tc.in, got, tc.want)+ }+ if got := NormalizeDaemonReason(string(ReasonAgentContextOverflow), tc.in); got != tc.want {+ t.Errorf("NormalizeDaemonReason(context_overflow, %q) = %q, want %q", tc.in, got, tc.want)+ }+ })+ }+}+func TestNormalizeDaemonReasonDistinguishesInsufficientBalanceFromRateLimit(t *testing.T) {legacy := ReasonAgentProviderCapacityOrRateLimit.String()for _, tc := range []struct {