mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-11-24 19:52:53 +08:00
fix(gemini): apply the request rate limit to Cloud Code and countTokens (#4862)
## Description
`handle_google_cloudcode_stream` (Cloud Code Assist / Antigravity
`:streamGenerateContent`) and `handle_gemini_count_tokens`
(`:countTokens`) never called the request rate limiter
(`TokenBucketRateLimiter.check_request`) that
`handle_gemini_generate_content` uses. With a per-minute request limit
configured, requests on those two routes were never counted or refused.
The check is now one helper, `_enforce_request_rate_limit`, called by
all three routes. It uses the same identity rule
(`rate_limit_identity`), the same 429 detail and the same
`record_rate_limited` metric. It runs after the internal `x-headroom-*`
headers are stripped, the same point where generateContent already ran
it.
Fix adapted from a proposal by HetCreep.
## Type of Change
- [x] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [ ] Performance improvement
- [ ] Code refactoring (no functional changes)
## Changes Made
- `headroom/proxy/handlers/gemini.py`: new
`_enforce_request_rate_limit`. generateContent now calls it in place of
its inline block, and the Cloud Code stream and countTokens handlers
call it too. The token check in generateContent now computes its
identity inline, since the local `rate_key` moved into the helper.
- `tests/test_gemini_rate_limit_routes.py`: at 1 request/minute, four
calls to each route return `[200, 429, 429, 429]` and only the first
reaches upstream.
## Testing
- [x] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check .`)
- [x] Type checking passes (`mypy headroom`)
- [x] New tests added for new functionality
- [ ] Manual testing performed
### Test Output
New test on `origin/main` code:
```text
E assert [200, 200, 200, 200] == [200, 429, 429, 429]
E assert [200, 200, 200, 200] == [200, 429, 429, 429]
============================== 2 failed in 1.42s ===============================
```
With the fix:
```text
$ pytest -q tests/test_gemini_rate_limit_routes.py
============================== 2 passed in 5.21s ===============================
$ pytest -q tests/*gemini* tests/*cloudcode* tests/*rate_limit* tests/*antigravity* (20 files)
======================= 147 passed, 27 skipped in 26.52s =======================
$ ruff check / ruff format --check (0.17.3): All checks passed
$ mypy headroom/proxy/handlers/gemini.py --ignore-missing-imports
Success: no issues found in 1 source file
```
## Real Behavior Proof
- Environment: macOS (Apple silicon), Python 3.12 venv. The real
`headroom proxy` runs from this branch and from `origin/main`, with
`--rpm 1 --no-optimize` and `--gemini-api-url` / `--cloudcode-api-url`
pointed at a local stand-in upstream (`http.server` that returns
`{"totalTokens": 3}` or one SSE chunk).
- Exact command / steps:
```text
headroom proxy --port 18912 --rpm 1 --no-optimize --gemini-api-url
http://127.0.0.1:18911 --cloudcode-api-url http://127.0.0.1:18911
4x curl -X POST
http://127.0.0.1:18912/v1beta/models/gemini-2.0-flash:countTokens -H
'x-goog-api-key: test' -d '{"contents":[...]}'
4x curl -X POST
'http://127.0.0.1:18912/v1internal:streamGenerateContent?alt=sse' -H
'authorization: Bearer test' -d
'{"model":"gemini-2.0-flash","project":"p","request":{"contents":[...]}}'
```
- Observed result:
```text
this branch: countTokens 200 429 429 429 cloudcode stream 200 429 429
429
origin/main: countTokens 200 200 200 200 cloudcode stream 200 200 200
200
```
The unit tests also drive the handlers with a real Starlette `Request`
whose JSON body arrives in two ASGI chunks.
- Not tested: real Google upstreams (the change happens before the
upstream call).
## Runtime Rollout Safety
- Rollout-managed feature(s): none
- Minimum rollout channel: n/a
- Stable/default behavior changed: only when a request rate limit is
configured. Cloud Code stream and countTokens requests now count toward
it and get 429 when over, like generateContent. Clients that call
countTokens before every generation (Gemini CLI) now use two requests
from the bucket per turn.
- Kill switch / disable path: existing rate-limit settings (raise or
disable the request limit)
- Unsafe override required: no
- Qualification impact: none
- Rollback path: revert this PR
## Review Readiness
- [x] I have performed a self-review
- [x] This PR is ready for human review
## Checklist
- [x] My code follows the project's style guidelines
- [x] I have performed a self-review of my code
- [x] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation — n/a
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] New and existing unit tests pass locally with my changes
- [x] I did **not** edit `CHANGELOG.md` — it is generated by
release-please from my Conventional Commit PR title (a CI guard enforces
this)
## Additional Notes
Other routes that do not consult the request limiter today (Bedrock
invoke, batch endpoints, the Responses WebSocket) are left out of this
PR.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
JerrettDavis
parent
5503383bef
commit
c2292ed0c6
@@ -396,6 +396,28 @@ class GeminiHandlerMixin:
|
||||
|
||||
return contents, system_instruction
|
||||
|
||||
async def _enforce_request_rate_limit(
|
||||
self, request: Request, headers: dict[str, str], provider_name: str
|
||||
) -> None:
|
||||
"""Raise HTTP 429 when the caller is over the request rate limit.
|
||||
|
||||
One identity rule for every provider
|
||||
(headroom/proxy/rate_limit_identity.py).
|
||||
"""
|
||||
if not self.rate_limiter:
|
||||
return
|
||||
from fastapi import HTTPException
|
||||
|
||||
allowed, wait_seconds = await self.rate_limiter.check_request(
|
||||
rate_limit_identity(request, headers)
|
||||
)
|
||||
if not allowed:
|
||||
await self.metrics.record_rate_limited(provider=provider_name, source="headroom")
|
||||
raise HTTPException(
|
||||
status_code=429,
|
||||
detail=f"Rate limited. Retry after {wait_seconds:.1f}s",
|
||||
)
|
||||
|
||||
async def handle_gemini_generate_content(
|
||||
self,
|
||||
request: Request,
|
||||
@@ -492,17 +514,7 @@ class GeminiHandlerMixin:
|
||||
stripped_count=_pre_strip_count_gem,
|
||||
request_id=request_id,
|
||||
)
|
||||
# Rate limiting: one identity rule for every provider
|
||||
# (headroom/proxy/rate_limit_identity.py).
|
||||
if self.rate_limiter:
|
||||
rate_key = rate_limit_identity(request, headers)
|
||||
allowed, wait_seconds = await self.rate_limiter.check_request(rate_key)
|
||||
if not allowed:
|
||||
await self.metrics.record_rate_limited(provider=provider_name, source="headroom")
|
||||
raise HTTPException(
|
||||
status_code=429,
|
||||
detail=f"Rate limited. Retry after {wait_seconds:.1f}s",
|
||||
)
|
||||
await self._enforce_request_rate_limit(request, headers, provider_name)
|
||||
|
||||
# Budget check
|
||||
cost_tracker = self.cost_tracker
|
||||
@@ -722,7 +734,9 @@ class GeminiHandlerMixin:
|
||||
tokenizer, original_tokens = await self._count_tokens_offloaded(model, messages)
|
||||
|
||||
if self.rate_limiter:
|
||||
allowed, wait_seconds = await self.rate_limiter.check_tokens(rate_key, original_tokens)
|
||||
allowed, wait_seconds = await self.rate_limiter.check_tokens(
|
||||
rate_limit_identity(request, headers), original_tokens
|
||||
)
|
||||
if not allowed:
|
||||
await self.metrics.record_rate_limited(provider=provider_name)
|
||||
raise HTTPException(
|
||||
@@ -1319,6 +1333,8 @@ class GeminiHandlerMixin:
|
||||
request_id=request_id,
|
||||
)
|
||||
|
||||
await self._enforce_request_rate_limit(request, headers, "gemini")
|
||||
|
||||
# Budget check
|
||||
cost_tracker = self.cost_tracker
|
||||
if cost_tracker:
|
||||
@@ -1528,6 +1544,8 @@ class GeminiHandlerMixin:
|
||||
request_id=request_id,
|
||||
)
|
||||
|
||||
await self._enforce_request_rate_limit(request, headers, provider_name)
|
||||
|
||||
# Convert Gemini format to messages for optimization
|
||||
system_instruction = body.get("systemInstruction")
|
||||
messages, preserved_indices = self._gemini_contents_to_messages(
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
"""The Cloud Code stream and :countTokens Gemini routes honour the request rate limiter."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from starlette.requests import Request
|
||||
|
||||
from headroom.proxy.handlers.gemini import GeminiHandlerMixin
|
||||
from headroom.proxy.rate_limiter import TokenBucketRateLimiter
|
||||
|
||||
|
||||
def _request(path: str, payload: dict) -> Request:
|
||||
"""Real Starlette Request whose JSON body arrives in two ASGI chunks."""
|
||||
body = json.dumps(payload).encode()
|
||||
chunks = [body[: len(body) // 2], body[len(body) // 2 :]]
|
||||
scope = {
|
||||
"type": "http",
|
||||
"method": "POST",
|
||||
"path": path,
|
||||
"raw_path": path.encode(),
|
||||
"query_string": b"",
|
||||
"headers": [(b"content-type", b"application/json")],
|
||||
"client": ("127.0.0.1", 50000),
|
||||
}
|
||||
|
||||
async def receive() -> dict:
|
||||
if chunks:
|
||||
chunk = chunks.pop(0)
|
||||
return {"type": "http.request", "body": chunk, "more_body": bool(chunks)}
|
||||
return {"type": "http.disconnect"}
|
||||
|
||||
return Request(scope, receive)
|
||||
|
||||
|
||||
class _Response:
|
||||
status_code = 200
|
||||
content = b'{"totalTokens": 1}'
|
||||
headers = {"content-type": "application/json"}
|
||||
|
||||
def json(self) -> object:
|
||||
return {"totalTokens": 1}
|
||||
|
||||
|
||||
class _FakeMetrics:
|
||||
def __init__(self) -> None:
|
||||
self.rate_limited: list[str] = []
|
||||
|
||||
async def record_rate_limited(self, *, provider: str, **_: object) -> None:
|
||||
self.rate_limited.append(provider)
|
||||
|
||||
async def record_failed(self, *, provider: str, model: str = "") -> None:
|
||||
pass
|
||||
|
||||
|
||||
class _Handler(GeminiHandlerMixin):
|
||||
GEMINI_API_URL = "https://gemini.example"
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.memory_handler = None
|
||||
self.usage_reporter = None
|
||||
self.rate_limiter = TokenBucketRateLimiter(requests_per_minute=1)
|
||||
self.metrics = _FakeMetrics()
|
||||
from headroom.cache.prefix_tracker import SessionTrackerStore
|
||||
|
||||
self.session_tracker_store = SessionTrackerStore()
|
||||
self.config = SimpleNamespace(optimize=False)
|
||||
self.upstream_calls = 0
|
||||
self.streamed = 0
|
||||
|
||||
async def _next_request_id(self) -> str:
|
||||
return "req-1"
|
||||
|
||||
async def _retry_request(self, method, url, headers, body): # noqa: ANN001, ANN201
|
||||
self.upstream_calls += 1
|
||||
return _Response()
|
||||
|
||||
async def _stream_response(self, *args, **kwargs): # noqa: ANN002, ANN003, ANN201
|
||||
self.streamed += 1
|
||||
return SimpleNamespace(status_code=200)
|
||||
|
||||
|
||||
async def _statuses(call, n: int) -> list[int]: # noqa: ANN001
|
||||
from fastapi import HTTPException
|
||||
|
||||
out: list[int] = []
|
||||
for _ in range(n):
|
||||
try:
|
||||
out.append((await call()).status_code)
|
||||
except HTTPException as exc:
|
||||
out.append(exc.status_code)
|
||||
return out
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_count_tokens_is_rate_limited() -> None:
|
||||
# inlineData-only body takes the early forward path (no tokenizer needed).
|
||||
payload = {"contents": [{"role": "user", "parts": [{"inlineData": {"data": "x"}}]}]}
|
||||
handler = _Handler()
|
||||
|
||||
statuses = await _statuses(
|
||||
lambda: handler.handle_gemini_count_tokens(
|
||||
_request("/v1beta/models/gemini-pro:countTokens", payload), "gemini-pro"
|
||||
),
|
||||
4,
|
||||
)
|
||||
|
||||
assert statuses == [200, 429, 429, 429]
|
||||
assert handler.upstream_calls == 1
|
||||
assert handler.metrics.rate_limited == ["gemini"] * 3
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_cloudcode_stream_is_rate_limited() -> None:
|
||||
payload = {
|
||||
"model": "gemini-pro",
|
||||
"request": {"contents": [{"role": "user", "parts": [{"text": "hi"}]}]},
|
||||
}
|
||||
handler = _Handler()
|
||||
|
||||
statuses = await _statuses(
|
||||
lambda: handler.handle_google_cloudcode_stream(
|
||||
_request("/v1internal:streamGenerateContent", payload)
|
||||
),
|
||||
4,
|
||||
)
|
||||
|
||||
assert statuses == [200, 429, 429, 429]
|
||||
assert handler.streamed == 1
|
||||
assert handler.metrics.rate_limited == ["gemini"] * 3
|
||||
Reference in New Issue
Block a user