fix(proxy): clamp /transformations/feed limit to [1, 100] (#4934)

fix(proxy): clamp /transformations/feed limit to [1, 100]

## Description

`/transformations/feed` only clamped `limit > 100`. `limit=0` made the
logger slice `[-0:]` (the whole log) and a negative limit returned all
but the first `|n|` entries, so both bypassed the 100-entry cap that
protects the event loop. This clamps both ends in the handler and makes
`RequestLogger.get_recent` / `get_recent_with_messages` return `[]` for
`n <= 0`.

Closes #4933

## Type of Change

- [x] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [x] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [ ] Performance improvement
- [ ] Code refactoring (no functional changes)
- [ ] Test-only change

## Changes Made

- `headroom/proxy/server.py`: `limit = max(1, min(limit, 100))` in
`transformations_feed`.
- `headroom/proxy/request_logger.py`: `get_recent` and
`get_recent_with_messages` return `[]` when `n <= 0`.
- `tests/test_proxy/test_transformations_feed.py`: seed the log (150
entries) and assert `limit=5`, default, `limit=1000`, and `limit=0 / -1
/ -100 / 0 with include_messages=0`. The "returns messages" test now
seeds entries and checks the values, so it fails if bodies are dropped.
- `tests/test_proxy/test_request_logger.py`: `n <= 0` returns nothing
from both getters.

## Testing

- [x] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check .`)
- [ ] Type checking passes (`mypy headroom`)
- [x] New tests added for new functionality
- [x] Manual testing performed

### Test Output

```text
tests/test_proxy/test_transformations_feed.py + tests/test_proxy/test_request_logger.py
17 passed in 78.33s   (with the fix)
4 failed, 13 passed   (same files, source files restored from origin/main; the -149 case
                       was then changed to -100, which also fails on the old code by arithmetic)
ruff check / ruff format --check: clean on the 4 touched files
```

## Real Behavior Proof

- Environment: Windows 11, Python via the project venv, in-process ASGI
client (`create_app()`, `HEADROOM_REQUIRE_RUST_CORE=false`), 500 logged
entries.
- Exact command / steps: log 500 `RequestLog` entries, then `GET
/transformations/feed?limit=<q>` for each `q`.
- Observed result:

```text
before: limit=5 -> 5 | limit=1000 -> 100 | limit=0 -> 500 | limit=-1 -> 499 | limit=0&include_messages=0 -> 500
after:  limit=5 -> 5 | limit=1000 -> 100 | limit=0 -> 1   | limit=-1 -> 1   | limit=0&include_messages=0 -> 1
```

- Not tested: real-size payloads (the 44 MB figure is from the
docstring); tests that need `headroom._core`
(`tests/test_proxy_stats_recent_requests.py` fails on the missing
extension here, unrelated to this change); mypy.

## Runtime Rollout Safety

- Rollout-managed feature(s): none
- Minimum rollout channel: n/a
- Stable/default behavior changed: only for `limit<=0`, which now
returns 1 entry instead of the whole log (or all but `|n|`)
- Kill switch / disable path: n/a
- Unsafe override required: no
- Qualification impact: none
- Rollback path: revert the commit

## Review Readiness

- [x] I have performed a self-review
- [ ] 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
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective or that my
feature works
- [ ] 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

`limit=0` returns 1 entry rather than `[]` or a 422. I found no
`Query(ge=...)` convention in `server.py` to copy, and this keeps the
response 200 for any integer. A maintainer who prefers 422 for
`limit<=0` can swap the handler line for `Query(ge=1)`; the logger guard
stays useful either way. Unchecked items above: the neighbouring files
that need `_core` could not run here.

<!-- devin-review-badge-begin -->

---

<a href="https://app.devin.ai/review/headroomlabs-ai/headroom/pull/4934"
target="_blank"><picture><source media="(prefers-color-scheme: dark)"
srcset="https://static.devin.ai/assets/gh-devin-review-dark.svg?v=4"><img
src="https://static.devin.ai/assets/gh-devin-review-light.svg?v=4"
alt="Devin Review"></picture></a>
<!-- devin-review-badge-end -->
This commit is contained in:
HetCreep
2026-11-18 16:11:43 -06:00
committed by GitHub
parent f4691e8ab1
commit ec2ab21844
4 changed files with 80 additions and 20 deletions
+4
View File
@@ -172,6 +172,8 @@ class RequestLogger:
def get_recent(self, n: int = 100) -> list[dict]:
"""Get recent log entries (without request/compressed messages and response_content)."""
if n <= 0: # [-0:] would be the whole log
return []
# Convert deque to list for slicing (deque doesn't support slicing)
entries = list(self._logs)[-n:]
# Not asdict(): that deep-copies every field BEFORE the heavy ones are
@@ -197,6 +199,8 @@ class RequestLogger:
full copy of each transcript (~160 KB per Claude Code turn, ~44 MB per
``limit=100`` feed pull) on the event loop.
"""
if n <= 0:
return []
entries = list(self._logs)[-n:]
if include_messages:
return [asdict(e) for e in entries]
+2 -2
View File
@@ -6123,8 +6123,8 @@ def create_app(config: ProxyConfig | None = None) -> FastAPI:
Returns empty list if log_full_messages is disabled (messages are not stored).
"""
if limit > 100:
limit = 100
# Clamp both ends: limit<=0 would otherwise slice the whole log.
limit = max(1, min(limit, 100))
transformations = []
log_full_messages = proxy.config.log_full_messages if proxy else False
+12
View File
@@ -195,3 +195,15 @@ def test_get_recent_with_messages_can_skip_payloads_without_walking_them():
assert slim[0]["tokens_saved"] == 60
assert slim[0]["transforms_applied"] == ["kompress:user:0.4"]
assert not {"request_messages", "compressed_messages", "response_content"} & slim[0].keys()
def test_get_recent_non_positive_n_returns_nothing_not_the_whole_log():
logger = RequestLogger(log_file=None, log_full_messages=True)
for i in range(5):
logger.log(_entry(request_id=f"r{i}"))
assert len(logger.get_recent(2)) == 2
for n in (0, -1, -4):
assert logger.get_recent(n) == []
assert logger.get_recent_with_messages(n) == []
assert logger.get_recent_with_messages(n, include_messages=False) == []
+62 -18
View File
@@ -16,6 +16,42 @@ def app():
return create_app()
def _log_entry(request_id: str, **overrides) -> RequestLog:
base: dict = {
"request_id": request_id,
"timestamp": "2026-04-24T10:00:00Z",
"provider": "anthropic",
"model": "claude-sonnet-4-6",
"input_tokens_original": 100,
"input_tokens_optimized": 40,
"output_tokens": 10,
"tokens_saved": 60,
"savings_percent": 60.0,
"optimization_latency_ms": 1.0,
"total_latency_ms": 20.0,
"tags": {},
"cache_hit": False,
"transforms_applied": [],
}
base.update(overrides)
return RequestLog(**base)
def _seed(app, count: int, **overrides) -> None:
for i in range(count):
app.state.proxy.logger.log(_log_entry(f"r{i}", **overrides))
async def _feed(app, query: str = "") -> list[dict]:
async with AsyncClient(
transport=ASGITransport(app=app, client=("127.0.0.1", 12345)),
base_url="http://127.0.0.1",
) as client:
response = await client.get(f"/transformations/feed?{query}")
assert response.status_code == 200
return response.json()["transformations"]
@pytest.mark.asyncio
async def test_transformations_feed_endpoint_returns_list(app):
"""The endpoint should return a list of recent transformations."""
@@ -40,34 +76,42 @@ async def test_transformations_feed_returns_messages(app):
The pre/post pair is what makes compression legible: consumers can diff
the two to see what the pipeline stripped, replaced, or kept.
"""
async with AsyncClient(
transport=ASGITransport(app=app, client=("127.0.0.1", 12345)),
base_url="http://127.0.0.1",
) as client:
response = await client.get("/transformations/feed")
data = response.json()
transformations = data["transformations"]
_seed(
app,
3,
request_messages=[{"role": "user", "content": "pre"}],
compressed_messages=[{"role": "user", "content": "post"}],
response_content="ok",
)
transformations = await _feed(app)
assert len(transformations) == 3
for t in transformations:
assert "request_messages" in t
assert t["request_messages"] is None or isinstance(t["request_messages"], list)
assert t["request_messages"] == [{"role": "user", "content": "pre"}]
assert "compressed_messages" in t
assert t["compressed_messages"] is None or isinstance(t["compressed_messages"], list)
assert t["compressed_messages"] == [{"role": "user", "content": "post"}]
assert "response_content" in t
assert t["response_content"] is None or isinstance(t["response_content"], str)
assert t["response_content"] == "ok"
@pytest.mark.asyncio
async def test_transformations_feed_respects_limit(app):
"""The endpoint should respect a ?limit= query parameter."""
async with AsyncClient(
transport=ASGITransport(app=app, client=("127.0.0.1", 12345)),
base_url="http://127.0.0.1",
) as client:
response = await client.get("/transformations/feed?limit=5")
_seed(app, 150)
assert len(await _feed(app, "limit=5")) == 5
assert len(await _feed(app)) == 20 # default
assert len(await _feed(app, "limit=1000")) == 100 # upper clamp
data = response.json()
assert len(data["transformations"]) <= 5
@pytest.mark.asyncio
@pytest.mark.parametrize(
"query", ["limit=0", "limit=-1", "limit=-100", "limit=0&include_messages=0"]
)
async def test_transformations_feed_clamps_non_positive_limit(app, query):
"""``limit<=0`` used to slice ``[-0:]`` / ``[-n:]`` and return (nearly) the
whole log, bypassing the 100-entry cap that guards the event loop."""
_seed(app, 150)
assert len(await _feed(app, query)) == 1
@pytest.mark.asyncio