Skip to content

Commit 2969681

Browse files
feat: stop a hosted run before static analysis when the CodeBoarding quota is spent
A large repository's Action run spent many minutes on static analysis before its first LLM call, and only then learned the free-tier quota was spent. The hosted proxy gates every request on the caller's weekly quota before forwarding it and meters only completions, so a GET /models through the same client answers 402 at no token cost. bootstrap_environment now makes that one request on hosted credentials and raises the same LLMQuotaError the runtime path raises, so full, incremental and partial runs exit 3 with Core's message. Any other answer lets the run go on. Own provider keys are never checked. Replaces the Action-side probe removed from CodeBoarding/CodeBoarding-action#184. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 3d0a545 commit 2969681

5 files changed

Lines changed: 144 additions & 2 deletions

File tree

‎agents/llm_errors.py‎

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,15 @@
77
import re
88
import time
99

10-
from agents.llm_config import CODEBOARDING_KEY_TAIL, current_provider_key_context
10+
from langchain_openai import ChatOpenAI
11+
from pydantic import SecretStr
12+
13+
from agents.llm_config import (
14+
CODEBOARDING_KEY_TAIL,
15+
LLM_PROVIDERS,
16+
OIDC_RELAY_PLACEHOLDER_KEY,
17+
current_provider_key_context,
18+
)
1119

1220
logger = logging.getLogger(__name__)
1321

@@ -132,6 +140,31 @@ def __init__(self, error: BaseException):
132140
super().__init__(message)
133141

134142

143+
def raise_if_codeboarding_quota_spent() -> None:
144+
"""Raise LLMQuotaError before the run starts when the hosted proxy says the CodeBoarding quota is spent.
145+
146+
Why: a large repository spends minutes on static analysis before its first LLM call. The proxy checks
147+
the caller's weekly quota before forwarding any request and meters only completions, so GET /models
148+
costs nothing. Any other answer lets the run go on; a quota spent mid-run is still caught at the LLM call.
149+
"""
150+
provider, key_tail = current_provider_key_context()
151+
if key_tail != CODEBOARDING_KEY_TAIL:
152+
return
153+
config = LLM_PROVIDERS[provider]
154+
model = ChatOpenAI(
155+
api_key=SecretStr(OIDC_RELAY_PLACEHOLDER_KEY),
156+
base_url=config.get_resolved_extra_args().get("base_url"),
157+
timeout=20, # seconds; on no answer the run goes ahead
158+
max_retries=0,
159+
)
160+
try:
161+
model.root_client.models.list()
162+
except Exception as error:
163+
if _is_codeboarding_quota(error):
164+
raise LLMQuotaError(error) from error
165+
logger.info("Quota check before the run got no usable answer, continuing: %s", error)
166+
167+
135168
def llm_failure_properties(exc: BaseException) -> dict:
136169
"""Classify a failed LLM call for exception telemetry."""
137170
quota = is_quota_exhausted(exc)

‎codeboarding_cli/bootstrap.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
from pathlib import Path
44

55
from agents.llm_config import configure_models, validate_api_key_provided
6+
from agents.llm_errors import raise_if_codeboarding_quota_spent
67
from health.plugins import get_registries, load_plugins
78
from diagram_analysis.run_context import RunPaths
89
from infra.install import enable_on_demand_install, ensure_tools
@@ -33,6 +34,8 @@ def bootstrap_environment(output_dir: Path, binary_location: Path | None) -> Non
3334
user_cfg.apply_to_env()
3435
configure_models(agent_model=user_cfg.llm.agent_model)
3536
validate_api_key_provided()
37+
# Before tool installs and static analysis, which a spent hosted quota would waste.
38+
raise_if_codeboarding_quota_spent()
3639
load_plugins(get_registries())
3740
if binary_location is not None:
3841
update_config(binary_location)

‎tests/agents/test_llm_errors.py‎

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,14 @@
11
"""Tests for provider-agnostic LLM auth-error detection and typing."""
22

33
import os
4+
from functools import partial
45
from unittest.mock import patch
56

67
import botocore.exceptions
78
import httpx
89
import openai
910
import pytest
11+
from langchain_openai import ChatOpenAI
1012

1113
from agents.llm_config import CODEBOARDING_KEY_TAIL, OIDC_RELAY_PLACEHOLDER_KEY, current_provider_key_context
1214
from agents.llm_errors import (
@@ -18,6 +20,7 @@
1820
is_transient_llm_error,
1921
llm_failure_properties,
2022
raise_if_auth_error,
23+
raise_if_codeboarding_quota_spent,
2124
retry_after_seconds,
2225
)
2326

@@ -388,3 +391,59 @@ def test_reads_retry_after_http_date(self):
388391
def test_no_retry_after_when_absent_unreadable_or_past(self, error: Exception):
389392
with patch("agents.llm_errors.time.time", return_value=1792567660.0):
390393
assert retry_after_seconds(error) is None
394+
395+
396+
_HOSTED_ENV = {"OPENROUTER_API_KEY": OIDC_RELAY_PLACEHOLDER_KEY, "OPENROUTER_BASE_URL": "http://127.0.0.1:4000/v1"}
397+
_SPENT_QUOTA = httpx.Response(
398+
402, json={"error": {"type": "gha_proxy", "message": "Resource exhausted: token limit reached"}}
399+
)
400+
401+
402+
def _check_quota(env: dict[str, str], answer: httpx.Response | Exception, requests: list[httpx.Request]) -> None:
403+
def proxy(request: httpx.Request) -> httpx.Response:
404+
requests.append(request)
405+
if isinstance(answer, Exception):
406+
raise answer
407+
return answer
408+
409+
with (
410+
httpx.Client(transport=httpx.MockTransport(proxy)) as client,
411+
patch.dict(os.environ, env, clear=True),
412+
patch("agents.llm_errors.ChatOpenAI", partial(ChatOpenAI, http_client=client)),
413+
):
414+
raise_if_codeboarding_quota_spent()
415+
416+
417+
class TestQuotaCheckBeforeTheRun:
418+
def test_a_spent_quota_raises_the_runtime_error(self):
419+
requests: list[httpx.Request] = []
420+
with pytest.raises(LLMQuotaError) as caught:
421+
_check_quota(_HOSTED_ENV, _SPENT_QUOTA, requests)
422+
423+
assert caught.value.is_codeboarding_quota
424+
assert "https://codeboarding.org/pricing" in str(caught.value)
425+
assert [(request.method, str(request.url)) for request in requests] == [
426+
("GET", "http://127.0.0.1:4000/v1/models")
427+
]
428+
assert requests[0].headers["authorization"] == f"Bearer {OIDC_RELAY_PLACEHOLDER_KEY}"
429+
430+
@pytest.mark.parametrize(
431+
"answer",
432+
[
433+
httpx.Response(200, json={"data": []}),
434+
# OpenRouter itself out of credits: a CodeBoarding service issue, not the user's quota.
435+
httpx.Response(402, json={"error": {"code": 402, "message": "Insufficient credits"}}),
436+
httpx.Response(500, json={"error": {"type": "gha_proxy", "message": "Upstream unavailable."}}),
437+
httpx.ConnectError("relay is down"),
438+
httpx.ReadTimeout("proxy is slow"),
439+
],
440+
)
441+
def test_any_other_answer_lets_the_run_go_on(self, answer: httpx.Response | Exception):
442+
requests: list[httpx.Request] = []
443+
_check_quota(_HOSTED_ENV, answer, requests)
444+
assert len(requests) == 1
445+
446+
def test_an_own_key_is_not_checked(self):
447+
requests: list[httpx.Request] = []
448+
_check_quota({"OPENROUTER_API_KEY": "sk-or-own-1234"}, _SPENT_QUOTA, requests)
449+
assert requests == []

‎tests/codeboarding_cli/test_bootstrap.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ def _bootstrap(tmp_path: Path, binary_location: Path | None) -> tuple[MagicMock,
1515
"load_user_config",
1616
"configure_models",
1717
"validate_api_key_provided",
18+
"raise_if_codeboarding_quota_spent",
1819
"load_plugins",
1920
"get_registries",
2021
):

‎tests/codeboarding_cli/test_quota_http.py‎

Lines changed: 47 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
"""Exercise the deployed Lambda response through the model client, scope analysis and CLI."""
22

33
import logging
4-
from contextlib import closing
4+
import os
5+
from contextlib import ExitStack, closing
6+
from functools import partial
57
from pathlib import Path
68
from unittest.mock import patch
79

@@ -11,6 +13,7 @@
1113
from pydantic import SecretStr
1214

1315
from agents.agent_responses import AnalysisInsights, Component
16+
from agents.llm_config import OIDC_RELAY_PLACEHOLDER_KEY
1417
from agents.llm_errors import LLMQuotaError
1518
from agents.scope_analysis_agent import ScopeAnalysisAgent
1619
from agents.tree_planner_agent import BUDGET, TreePlannerAgent
@@ -113,3 +116,46 @@ def run(*args, **kwargs):
113116
assert "or wait for your weekly reset" in records[-1].getMessage()
114117
assert "CodeBoarding: CodeBoarding" not in records[-1].getMessage()
115118
assert records[-1].getMessage() == f"CodeBoarding: {exit_info.value.__cause__}"
119+
120+
121+
@pytest.mark.parametrize(
122+
"command,analysis",
123+
[
124+
("full", "codeboarding_cli.commands.full_analysis.run_analysis_pipeline"),
125+
("incremental", "codeboarding_cli.commands.incremental_analysis.run_incremental"),
126+
],
127+
)
128+
def test_spent_quota_stops_the_run_before_static_analysis(tmp_path, caplog, command, analysis):
129+
requests = []
130+
131+
def lambda_response(request):
132+
requests.append(request)
133+
return httpx.Response(
134+
402, json={"error": {"type": "gha_proxy", "message": "Resource exhausted: token limit reached"}}
135+
)
136+
137+
hosted = {"OPENROUTER_API_KEY": OIDC_RELAY_PLACEHOLDER_KEY, "OPENROUTER_BASE_URL": "http://127.0.0.1:4000/v1"}
138+
with ExitStack() as stack:
139+
client = stack.enter_context(httpx.Client(transport=httpx.MockTransport(lambda_response)))
140+
stack.enter_context(patch.dict(os.environ, hosted, clear=True))
141+
stack.enter_context(patch("agents.llm_errors.ChatOpenAI", partial(ChatOpenAI, http_client=client)))
142+
for name in (
143+
"setup_logging",
144+
"ensure_config_template",
145+
"load_user_config",
146+
"configure_models",
147+
"ensure_tools",
148+
"enable_on_demand_install",
149+
):
150+
stack.enter_context(patch(f"codeboarding_cli.bootstrap.{name}"))
151+
run_analysis = stack.enter_context(patch(analysis))
152+
stack.enter_context(caplog.at_level(logging.ERROR, logger="codeboarding_cli.main"))
153+
exit_info = stack.enter_context(pytest.raises(SystemExit))
154+
main([command, "--local", str(tmp_path)])
155+
156+
assert exit_info.value.code == 3
157+
run_analysis.assert_not_called()
158+
assert [request.url.path for request in requests] == ["/v1/models"]
159+
assert isinstance(exit_info.value.__cause__, LLMQuotaError)
160+
assert caplog.records[-1].getMessage() == f"CodeBoarding: {exit_info.value.__cause__}"
161+
assert "https://codeboarding.org/pricing" in caplog.records[-1].getMessage()

0 commit comments

Comments
 (0)