Skip to content

Commit 4cd5e22

Browse files
fix(api): classify a usage limit reported after startup
Startup verification gives Claude 1.5 seconds to fail. A subscription limit is often reported later than that, so the run was accepted as successful and the terminal error text was returned to the caller as assistant content with HTTP 200 instead of the 429. Expose the error Claude reported on stdout and classify it once the run has finished, using the same helper as the start-time path so the two cannot drift.
1 parent 874211c commit 4cd5e22

3 files changed

Lines changed: 36 additions & 4 deletions

File tree

‎claude_code_api/api/chat.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
ClaudeSessionConflictError,
1616
ClaudeUsageLimitError,
1717
create_project_directory,
18+
raise_for_usage_limit,
1819
)
1920
from claude_code_api.core.session_manager import SessionManager
2021
from claude_code_api.models.claude import get_default_model, validate_claude_model
@@ -159,6 +160,7 @@ async def _collect_non_streaming_response(
159160
project_id: str,
160161
) -> Dict[str, Any]:
161162
messages, parser = await _gather_claude_messages(claude_process)
163+
raise_for_usage_limit(getattr(claude_process, "terminal_error", None))
162164
_log_message_summary(messages)
163165

164166
usage_summary = OpenAIConverter.calculate_usage(parser)

‎claude_code_api/core/claude_manager.py‎

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -210,6 +210,11 @@ async def _read_error(self):
210210
except Exception as e:
211211
logger.error("Error reading stderr", error=str(e))
212212

213+
@property
214+
def terminal_error(self) -> Optional[str]:
215+
"""Error Claude reported on stdout, if the run ended in one."""
216+
return self._result_error
217+
213218
async def _drain_readers(self) -> None:
214219
"""Let buffered stdout and stderr be consumed before reporting an error."""
215220
for task in (self._output_task, self._error_task):
@@ -367,6 +372,14 @@ def __init__(self, message: str, reset_at: Optional[datetime] = None):
367372
self.reset_at = reset_at
368373

369374

375+
def raise_for_usage_limit(error_message: Optional[str]) -> None:
376+
"""Raise when Claude reported an exhausted subscription."""
377+
if error_message and _is_usage_limit_error(error_message):
378+
raise ClaudeUsageLimitError(
379+
error_message, reset_at=_extract_usage_limit_reset(error_message)
380+
)
381+
382+
370383
def _is_model_rejection_error(error_message: str) -> bool:
371384
lowered = (error_message or "").lower()
372385
patterns = (
@@ -549,10 +562,7 @@ async def _start_with_fallback_models(
549562
return process
550563

551564
last_error = process.last_error or last_error
552-
if _is_usage_limit_error(last_error):
553-
raise ClaudeUsageLimitError(
554-
last_error, reset_at=_extract_usage_limit_reset(last_error)
555-
)
565+
raise_for_usage_limit(last_error)
556566
if not _is_model_rejection_error(last_error):
557567
raise ClaudeProcessStartError(last_error)
558568

‎tests/test_usage_limit.py‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -167,3 +167,23 @@ async def late_reader():
167167

168168
assert await process._verify_startup() is False
169169
assert "Usage limit reached" in process.last_error
170+
171+
172+
@pytest.mark.asyncio
173+
async def test_late_usage_limit_is_raised_not_returned_as_content(monkeypatch):
174+
"""A limit reported after startup must not surface as a successful reply."""
175+
from claude_code_api.api import chat as chat_api
176+
from claude_code_api.utils.parser import ClaudeOutputParser
177+
178+
class _Process:
179+
terminal_error = "Usage limit reached resets_at=1774000000"
180+
181+
async def fake_gather(_process):
182+
return [], ClaudeOutputParser()
183+
184+
monkeypatch.setattr(chat_api, "_gather_claude_messages", fake_gather)
185+
186+
with pytest.raises(cm.ClaudeUsageLimitError):
187+
await chat_api._collect_non_streaming_response(
188+
_Process(), None, "sess", "claude-haiku-4-5-20251001", "proj"
189+
)

0 commit comments

Comments
 (0)