Repository navigation
[AI-2910] Count a rate limit that arrives mid-stream after a 200 - #2527
Conversation
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01SWVEMob5wtaNHdUCC1msgG
…t was sent on Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01SWVEMob5wtaNHdUCC1msgG
…ed for Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01SWVEMob5wtaNHdUCC1msgG
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01SWVEMob5wtaNHdUCC1msgG
kanat
left a comment
There was a problem hiding this comment.
VERDICT: NO-GO
Reviewed 16e8eef (only 6d21e607b..16e8eef3e, the AI-2910 commit), merged onto main cc8c7f5 (already an ancestor). Draft: CI's go and integration jobs skip until gh pr ready. Build, vet, gofmt, the touched unit suites with -race and internal/llmrouter integration all pass.
[Should fix] R1.1: six mutants of the new rules survive. Each one has a test row (inline comments). Each row fails under its mutant and passes on head (checked in a scratch copy):
- a)
RateLimitedInStreamcounting undercontext.Background()survives. The refusal then loses the product and the model that thekey_refusedalert names (keypool.go:415). - b)
settle()callingfailurewithoutp.ctxsurvives. The only case with aresponse.failedrate limit also has anerrorevent (openai_test.go:366). - c) OpenAI counting
server_is_overloadedorvector_store_timeoutas a rate limit survives (openai_test.go:366). - d) Anthropic counting
api_errorortimeout_errorsurvives (anthropic_test.go:688). - e) Removing
transient = truefrom therate_limit_errorcase that was moved out survives. The description says classification is unchanged, but no test checks it for Anthropic (anthropic_test.go:688). - f) openaicompat counting any string code (
code != "") survives (openaicompat_test.go:325).
[Question] R1.2 (author's question: should a rate limit sent mid-stream also rest the key?). Ruling: a ticket, not this PR. Resting changes which key the next request takes, which is a behaviour change. Counting without resting is still correct for both counters. The ticket should note that OpenAI's pool is a Pin (openai.go:179), so a session keeps using a key that was rate limited mid-stream.
Checked and sound:
- Each stream counts once. The second OpenAI event finds the key cleared.
- An up-front 429 is not counted a second time:
Createreturnsupstream.Err()before a puller exists. A probe that answers every request with 429 counted 3 for 3 SDK attempts. - A request that no pool sent counts nothing.
-raceis clean.- A mid-stream rate limit on one of our keys now raises
key_refused<KEY_VAR>/429(Warn, as an up-front 429 does). A customer's key raises nothing. This matches the ticket's spec.
Stack note (for the mechanic, not a code finding): git merge-tree --write-tree d02cdde6d 16e8eef3e reports a CONFLICT in acceleration/internal/keypool/metrics.go. It is the refusedAttempts Help line: #2526 and this PR each add a clause. Keep both.
Verdict: request changes, for R1.1.
| if source, index, ok := ring.own(key); ok { | ||
| rateLimited.WithLabelValues(source, index).Inc() | ||
| } | ||
| ring.countRefused(ctx, strconv.Itoa(http.StatusTooManyRequests)) |
There was a problem hiding this comment.
[Should fix] R1.1a: no test checks that the in-stream count keeps the caller's product and model. Mutant: ring.countRefused(context.Background(), ...) here, and every test still passes. Row (RefusedAttemptsSuite, or a new row in TestARefusalIsCountedUnderTheProductAndModelItWasMadeFor): s.ctx = Sending(WithCaller(context.Background(), "llm", model)); s.post(p.Pool); RateLimitedInStream(s.ctx) → keypooltest.Series(s.T(), "router_keypool_refused_attempts_total", p.keyVars[0]) == {model + "/ours/llm/429": 1}. This row fails under the mutant and passes on head.
| `{"type":"error","code":"rate_limit_exceeded","message":"slow down","param":null,"sequence_number":1}`, | ||
| `{"type":"response.failed","response":{"id":"r","status":"failed","error":{"code":"rate_limit_exceeded","message":"slow down"}}}`, | ||
| }, 1}, | ||
| {[]string{`{"type":"error","code":"slow_down","message":"busy","param":null,"sequence_number":1}`}, 1}, |
There was a problem hiding this comment.
[Should fix] R1.1b/c: two mutants survive this table. Add these rows:
{[]string{`{"type":"response.failed","response":{"id":"r","status":"failed","error":{"code":"rate_limit_exceeded","message":"slow down"}}}`}, 1}: killssettle()passingcontext.Background()tofailure. Today the onlyresponse.failedrate limit comes after anerrorevent, which counts first.{[]string{`{"type":"error","code":"server_is_overloaded","message":"busy","param":null,"sequence_number":1}`}, 0}: kills countingserverOverloadedorVectorStoreTimeoutas a rate limit.
Both rows pass on head.
| counted float64 | ||
| }{ | ||
| {"rate_limit_error", 1}, | ||
| {"overloaded_error", 0}, |
There was a problem hiding this comment.
[Should fix] R1.1d/e: add the rows {"api_error", 0} and {"timeout_error", 0}. They kill a mutant that counts those types as rate limits. Also add s.True(llm.Transient(err), tc.errorType) after ErrorContains. That kills dropping transient = true from the rate_limit_error case that was moved out, which nothing checks today. Both rows pass on head.
| }{ | ||
| {`{"error":{"code":"rate_limit_exceeded","message":"slow down"}}`, 1}, | ||
| {`{"error":{"code":429,"message":"slow down"}}`, 1}, | ||
| {`{"error":{"code":503,"message":"try later"}}`, 0}, |
There was a problem hiding this comment.
[Should fix] R1.1f: add the row {`{"error":{"code":"server_error","message":"fell over"}}`, 0}. It kills the mutant number == 429 || code != "" (any string code counted as a rate limit), which survives today. It passes on head.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01SWVEMob5wtaNHdUCC1msgG
…uarded Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01SWVEMob5wtaNHdUCC1msgG
kanat
left a comment
There was a problem hiding this comment.
VERDICT: GO
Delta review, round 2, of 38c48d2 (previous 16e8eef, NO-GO on R1.1). Base main cc8c7f5 (already contained in head; merge was "Already up to date").
Prior findings
- R1.1 a-f: fixed. Mutants R1, R2, R9, R8, R12 and R4 from the round-1 mut.py each fail on head, in the row the finding named:
- R1 (RateLimitedInStream counted with context.Background()): fails TestARefusalIsCountedUnderTheProductAndModelItWasMadeFor/rate_limit_sent_in_the_stream_after_a_200 (metrics_test.go).
- R2 (response.failed counted without p.ctx): fails TestARateLimitInTheStreamIsCountedOnceOnTheKeyItWasSentOn (openai_test.go).
- R9 (server_is_overloaded and vector_store_timeout counted): same openai test.
- R8 (api_error and timeout_error counted): TestARateLimitMidStreamIsCountedOnTheKeyItWasSentOn (anthropic_test.go).
- R12 (rate_limit_error not transient): same anthropic test, via the new llm.Transient assertion.
- R4 (any string code counts): TestARateLimitSentMidStreamIsCountedOnTheKeyItWasSentOn (openaicompat_test.go).
- R1.2: ticket, not blocking (unchanged ruling).
Merge d4ed51c (git show --remerge-diff): one conflict, the refusedAttempts Help line in keypool/metrics.go. The resolution keeps the #2526 clause "(for a customer's own key, the vendor's variable)" and this PR's ", also for a rate limit an LLM sent in the stream after answering 200". The key_var comment from #2526 is intact. Diff of d02cdde..head touches only #2527's files (10 files, no #2526 change reverted).
New findings: none. The head commit changes tests only (5 files); the only production-file change in the delta is the merge's Help line.
Runs on head (already on the current base): gofmt clean, go build ./..., go vet on keypool and llm; go test -race -count=1 ./internal/keypool/... ./internal/llm/... pass; go test -count=1 ./internal/llmrouter/ pass.
CI: at review time Analyze (actions) and GitGuardian pass, CodeQL Go/Python pending, go and integration skipping (draft).
Mutations: 6 checked, 0 survived. Worktree clean after each mutant.
Unverified: integration tag suites (CI runs them; not run here).
kanat
left a comment
There was a problem hiding this comment.
VERDICT: GO
Delta review, round 3, of 28fed66 (last GO head 38c48d2). Only main was merged since: the mechanic's merge de96832 (after #2526 became f12ab67) and GitHub's update-branch merge with #2566.
git show --remerge-diff de968326b: one conflict, therefusedAttemptsHelp line inkeypool/metrics.go. The resolution keeps main's text and adds only the AI-2910 phrase ", also for a rate limit an LLM sent in the stream after answering 200". Nothing else differs from the auto-merge.git show --remerge-diff 28fed66c8: empty, no conflict, nothing reverted.git diff origin/main 28fed66c8touches exactly the 10 PR files (253 insertions, 22 deletions). Its hunks matchgit diff 8a5323a9a 38c48d2b5on the same files: identical bodies, only 6@@line offsets differ because main moved code above them. So no change of main is reverted and nothing of the PR is lost.- On 28fed66 in a clean detached worktree: gofmt clean on keypool and llm;
go build ./...,go vet ./...andgo vet -tags integration ./...pass;go test -race -count=1 ./internal/keypool/... ./internal/llm/...andgo test -count=1 ./internal/llmrouter/pass.
Prior findings: R1.1 (six unpinned mutants) fixed, as ruled in round 2; none of its hunks changed. R1.2 stays a ticket, not blocking. New findings: none. No mutants rerun, since no production or test hunk changed since round 2.
CI when I looked: Analyze (actions), Analyze (python), labeler and GitGuardian pass; go, Analyze (go) and the integration jobs pending. Not run here: the integration-tag suites (only go vet -tags integration); CI runs them.
Stacked on #2526: review only
git diff 6d21e607b..16e8eef3euntil #2526 merges.Why
An LLM provider can refuse a request after it has already answered 200. The refusal comes as an error event inside the stream: Anthropic sends
rate_limit_error, OpenAI sendsrate_limit_exceededorslow_downin anerrororresponse.failedevent, and OpenAI-compatible providers send a 429 code orrate_limit_exceededin the event body. The key pool counted only refusals that came back before the stream began, so these rate limits were missing fromrouter_vendor_rate_limited_totalandrouter_keypool_refused_attempts_total.How it works
Changes
keypool:Sending(ctx)marks a request;sendTimesrecords the key each attempt goes out on;RateLimitedInStream(ctx)counts the rate limit on that key.llm/anthropic,llm/openai,llm/openaicompat: the request context is marked withSending, and the stream's rate-limit error events callRateLimitedInStream.keypool/metrics.go: the help text ofkeypool_refused_attempts_totalandvendor_rate_limited_totalnames the in-stream case.Validation
Unit suites (
go test ./internal/keypool/... ./internal/llm/...), integration suite (go test -tags integration -p 1 ./internal/llmrouter/),go build,go vet,go vet -tags integration, andgofmt -lwere run on 16e8eef by the author.VendorRateLimitSuite/TestARateLimitInTheStreamIsCountedOnTheKeyItWasSentOnVendorRateLimitSuite/TestARateLimitInTheStreamOfNoPooledKeyCountsNothingVendorRateLimitSuite/TestARateLimitInTheStreamOfACustomersKeyIsTheirsAnthropicSuite/TestARateLimitMidStreamIsCountedOnTheKeyItWasSentOnrate_limit_erroris not countedOpenAISuite/TestARateLimitInTheStreamIsCountedOnceOnTheKeyItWasSentOnOpenAICompatSuite/TestARateLimitSentMidStreamIsCountedOnTheKeyItWasSentOnMutation check: 20 mutants of the new rules (M10 to M30; M12 was dropped after it survived, as a redundant guard, and that guard was removed). All 20 were killed by the tests above. For example, M22 (Anthropic counts overload as a rate limit) is killed by
AnthropicSuite/TestARateLimitMidStreamIsCountedOnTheKeyItWasSentOn, and M26 (OpenAI countsserver_error) byOpenAISuite/TestARateLimitInTheStreamIsCountedOnceOnTheKeyItWasSentOn.🤖 Generated with Claude Code