Skip to content

[AI-2910] Count a rate limit that arrives mid-stream after a 200 - #2527

Merged
kanat merged 8 commits into
mainfrom
kanat/ai-2910-midstream-rate-limits
Nov 26, 2026
Merged

kanat merged 8 commits into
mainfrom
kanat/ai-2910-midstream-rate-limits

Conversation

@kanat

@kanat kanat commented Nov 26, 2026

Copy link
Copy Markdown
Collaborator

Stacked on #2526: review only git diff 6d21e607b..16e8eef3e until #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 sends rate_limit_exceeded or slow_down in an error or response.failed event, and OpenAI-compatible providers send a 429 code or rate_limit_exceeded in the event body. The key pool counted only refusals that came back before the stream began, so these rate limits were missing from router_vendor_rate_limited_total and router_keypool_refused_attempts_total.

How it works

request ctx ── keypool.Sending(ctx) ──> sentOn (one per request)
                                          │
pool sendTimes, each attempt ─────────────┘ stores the ring and the key
                                          │
provider error event inside a 200 stream  │
  ├─ anthropic rate_limit_error ──────────┤
  ├─ openai rate_limit_exceeded, slow_down┤
  └─ openaicompat 429 or rate_limit ──────┘
                                          v
                          RateLimitedInStream(ctx)
                            ├─ router's own key: vendor_rate_limited_total++
                            └─ refused_attempts{status="429"}++
                            (rests no key; once per attempt;
                             a request no pool sent counts nothing)

Changes

  • keypool: Sending(ctx) marks a request; sendTimes records 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 with Sending, and the stream's rate-limit error events call RateLimitedInStream.
  • Classification is unchanged. A rate limit inside a stream is still transient; the rate-limit codes only move into their own case.
  • keypool/metrics.go: the help text of keypool_refused_attempts_total and vendor_rate_limited_total names 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, and gofmt -l were run on 16e8eef by the author.

Test Defect it catches
VendorRateLimitSuite/TestARateLimitInTheStreamIsCountedOnTheKeyItWasSentOn the in-stream 429 is counted on the wrong key or not at all
VendorRateLimitSuite/TestARateLimitInTheStreamOfNoPooledKeyCountsNothing a request no pool sent is counted under a blank key
VendorRateLimitSuite/TestARateLimitInTheStreamOfACustomersKeyIsTheirs a customer's key is counted as one of the router's own
AnthropicSuite/TestARateLimitMidStreamIsCountedOnTheKeyItWasSentOn Anthropic's mid-stream rate_limit_error is not counted
OpenAISuite/TestARateLimitInTheStreamIsCountedOnceOnTheKeyItWasSentOn a rate limit OpenAI sends in two events is counted twice
OpenAICompatSuite/TestARateLimitSentMidStreamIsCountedOnTheKeyItWasSentOn a compat provider's mid-stream 429 is not counted

Mutation 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 counts server_error) by OpenAISuite/TestARateLimitInTheStreamIsCountedOnceOnTheKeyItWasSentOn.

🤖 Generated with Claude Code

@kanat kanat left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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) RateLimitedInStream counting under context.Background() survives. The refusal then loses the product and the model that the key_refused alert names (keypool.go:415).
  • b) settle() calling failure without p.ctx survives. The only case with a response.failed rate limit also has an error event (openai_test.go:366).
  • c) OpenAI counting server_is_overloaded or vector_store_timeout as a rate limit survives (openai_test.go:366).
  • d) Anthropic counting api_error or timeout_error survives (anthropic_test.go:688).
  • e) Removing transient = true from the rate_limit_error case 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: Create returns upstream.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.
  • -race is 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))

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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},

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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}: kills settle() passing context.Background() to failure. Today the only response.failed rate limit comes after an error event, which counts first.
  • {[]string{`{"type":"error","code":"server_is_overloaded","message":"busy","param":null,"sequence_number":1}`}, 0}: kills counting serverOverloaded or VectorStoreTimeout as a rate limit.

Both rows pass on head.

counted float64
}{
{"rate_limit_error", 1},
{"overloaded_error", 0},

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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},

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

kanat and others added 2 commits November 26, 2026 01:44
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SWVEMob5wtaNHdUCC1msgG

@kanat kanat left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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
kanat marked this pull request as ready for review November 26, 2026 06:49

@kanat kanat left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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, the refusedAttempts Help line in keypool/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 28fed66c8 touches exactly the 10 PR files (253 insertions, 22 deletions). Its hunks match git diff 8a5323a9a 38c48d2b5 on 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 ./... and go vet -tags integration ./... pass; go test -race -count=1 ./internal/keypool/... ./internal/llm/... and go 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.

@kanat
kanat merged commit 9d8d3bb into main Nov 26, 2026
13 checks passed
@kanat
kanat deleted the kanat/ai-2910-midstream-rate-limits branch November 26, 2026 23:27
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant