Skip to content

Commit 3c0ec1c

Browse files
feat: stop a hosted run before static analysis when the CodeBoarding quota is spent (#712)
* 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> * fix: log the quota check's trace, report its stop, and check full runs only - A check that gets no usable answer is logged with logger.exception, so its traceback is kept (AGENTS.md: never lose the trace). - A quota it finds is sent to PostHog via capture_error("quota_check"): mid-run quota errors reach it through track_analysis, this one stops the run before any tracked analysis starts. - Only full runs are checked up front. They spend minutes on tool installs and static analysis before the first LLM call; an incremental run may need no LLM call, so a spent quota stops it only if it reaches one. - The client is built inside the try, so any failure lets the run go on, and uses the provider's own key instead of the placeholder constant. - LLMQuotaError.is_codeboarding_quota is gone: only its own __init__ read it. - Tests use the relay's real base URL (no /v1), assert tool installs never start and the stop is reported, and share one copy of the 402 body. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test: type the recorded requests in the quota CLI tests CI runs mypy over the tests too; the two empty lists needed their type. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor: check the quota in every CLI bootstrap, without a flag Hosted credentials reach Core only through the Action, which runs the CLI, and every CLI run starts in bootstrap_environment. Checking there unconditionally covers full, incremental and partial runs, including the full run an incremental starts after an engine change, which the full_run flag missed. The check reports its own stop to PostHog, so bootstrap calls it in one line; its docstring is down to a summary and a Why. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 3d0a545 commit 3c0ec1c

4 files changed

Lines changed: 153 additions & 9 deletions

File tree

‎agents/llm_errors.py‎

Lines changed: 35 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,11 @@
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 CODEBOARDING_KEY_TAIL, LLM_PROVIDERS, current_provider_key_context
14+
from infra.monitoring.telemetry.events import capture_error
1115

1216
logger = logging.getLogger(__name__)
1317

@@ -21,7 +25,7 @@
2125
EXIT_QUOTA_EXHAUSTED = 3
2226

2327
CODEBOARDING_QUOTA_CODE = "free_credits_exhausted"
24-
# Response contract: licensing-aws/gha_proxy/handler.py.
28+
# Response contract: licensing-aws/gha_proxy (caller.py QUOTA_MESSAGE, handler.py _error's type).
2529
PROXY_ERROR_TYPE = "gha_proxy"
2630
PROXY_QUOTA_MESSAGE = "Resource exhausted: token limit reached"
2731

@@ -111,9 +115,8 @@ class LLMQuotaError(RuntimeError):
111115

112116
def __init__(self, error: BaseException):
113117
self.telemetry_properties = llm_failure_properties(error)
114-
self.is_codeboarding_quota = _is_codeboarding_quota(error)
115118
_, key_tail = current_provider_key_context()
116-
if self.is_codeboarding_quota:
119+
if _is_codeboarding_quota(error):
117120
message = (
118121
"Your CodeBoarding quota is exhausted. "
119122
"Buy a CodeBoarding license at https://codeboarding.org/pricing, "
@@ -132,6 +135,34 @@ def __init__(self, error: BaseException):
132135
super().__init__(message)
133136

134137

138+
def raise_if_codeboarding_quota_spent() -> None:
139+
"""Raise LLMQuotaError when the hosted proxy says the CodeBoarding quota is spent; any other answer passes.
140+
141+
Why: a run spends minutes on static analysis before its first LLM call, and the proxy does not meter GET /models.
142+
"""
143+
provider, key_tail = current_provider_key_context()
144+
if key_tail != CODEBOARDING_KEY_TAIL:
145+
return
146+
config = LLM_PROVIDERS[provider]
147+
try:
148+
# ChatOpenAI for its OpenAI client: Core does not depend on ``openai`` directly.
149+
client = ChatOpenAI(
150+
api_key=SecretStr(config.get_api_key() or ""),
151+
base_url=config.get_resolved_extra_args().get("base_url"),
152+
timeout=20, # seconds; on no answer the run goes ahead
153+
max_retries=0,
154+
).root_client
155+
client.models.list()
156+
except Exception as error:
157+
if not _is_codeboarding_quota(error):
158+
logger.exception("Quota check before the run got no usable answer; continuing without it")
159+
return
160+
quota = LLMQuotaError(error)
161+
# Mid-run quota errors reach PostHog through track_analysis; this stop comes before any tracked run.
162+
capture_error("quota_check", quota)
163+
raise quota from error
164+
165+
135166
def llm_failure_properties(exc: BaseException) -> dict:
136167
"""Classify a failed LLM call for exception telemetry."""
137168
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
@@ -27,12 +28,14 @@ def resolve_local_run_paths(args: argparse.Namespace) -> RunPaths:
2728

2829

2930
def bootstrap_environment(output_dir: Path, binary_location: Path | None) -> None:
31+
"""Logging, configuration, credentials and tools for one CLI run, checked before any analysis starts."""
3032
setup_logging(log_dir=output_dir)
3133
ensure_config_template()
3234
user_cfg = load_user_config()
3335
user_cfg.apply_to_env()
3436
configure_models(agent_model=user_cfg.llm.agent_model)
3537
validate_api_key_provided()
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: 61 additions & 1 deletion
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

@@ -253,7 +256,6 @@ def test_quota_error_owns_quota_guidance(hosted, status, body, codeboarding_quot
253256
with patch("agents.llm_errors.current_provider_key_context", return_value=("openrouter", key_tail)):
254257
quota_error = LLMQuotaError(error)
255258

256-
assert quota_error.is_codeboarding_quota == codeboarding_quota
257259
assert quota_error.telemetry_properties["error_message"] == str(error)
258260
assert quota_error.telemetry_properties.get("error_code") == (
259261
"free_credits_exhausted" if codeboarding_quota else None
@@ -388,3 +390,61 @@ def test_reads_retry_after_http_date(self):
388390
def test_no_retry_after_when_absent_unreadable_or_past(self, error: Exception):
389391
with patch("agents.llm_errors.time.time", return_value=1792567660.0):
390392
assert retry_after_seconds(error) is None
393+
394+
395+
# The Action points Core at its local OIDC relay, with no /v1 (configure-auth.sh).
396+
_HOSTED_ENV = {"OPENROUTER_API_KEY": OIDC_RELAY_PLACEHOLDER_KEY, "OPENROUTER_BASE_URL": "http://127.0.0.1:4000"}
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_and_reports_it(self):
419+
requests: list[httpx.Request] = []
420+
with patch("agents.llm_errors.capture_error") as capture_error, pytest.raises(LLMQuotaError) as caught:
421+
_check_quota(_HOSTED_ENV, _SPENT_QUOTA, requests)
422+
423+
capture_error.assert_called_once_with("quota_check", caught.value)
424+
assert caught.value.telemetry_properties["error_code"] == "free_credits_exhausted"
425+
assert "https://codeboarding.org/pricing" in str(caught.value)
426+
assert [(request.method, str(request.url)) for request in requests] == [("GET", "http://127.0.0.1:4000/models")]
427+
assert requests[0].headers["authorization"] == f"Bearer {OIDC_RELAY_PLACEHOLDER_KEY}"
428+
429+
@pytest.mark.parametrize(
430+
"answer",
431+
[
432+
httpx.Response(200, json={"data": []}),
433+
# A 402 that is not the proxy's own quota answer is never read as the user's quota.
434+
httpx.Response(402, json={"error": {"code": 402, "message": "Insufficient credits"}}),
435+
httpx.Response(500, json={"error": {"type": "gha_proxy", "message": "Upstream unavailable."}}),
436+
httpx.ConnectError("relay is down"),
437+
httpx.ReadTimeout("proxy is slow"),
438+
],
439+
)
440+
def test_any_other_answer_lets_the_run_go_on(self, answer: httpx.Response | Exception):
441+
requests: list[httpx.Request] = []
442+
with patch("agents.llm_errors.capture_error") as capture_error:
443+
_check_quota(_HOSTED_ENV, answer, requests)
444+
assert len(requests) == 1
445+
capture_error.assert_not_called()
446+
447+
def test_an_own_key_is_not_checked(self):
448+
requests: list[httpx.Request] = []
449+
_check_quota({"OPENROUTER_API_KEY": "sk-or-own-1234"}, _SPENT_QUOTA, requests)
450+
assert requests == []

‎tests/codeboarding_cli/test_quota_http.py‎

Lines changed: 54 additions & 4 deletions
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
@@ -25,14 +28,17 @@
2528
from static_analyzer.node import Node
2629

2730

31+
# The proxy's answer to a caller whose weekly quota is spent: the wire contract, kept literal.
32+
SPENT_QUOTA_BODY = {"error": {"type": "gha_proxy", "message": "Resource exhausted: token limit reached"}}
33+
34+
2835
@pytest.mark.parametrize("stage,remote", [("scope", False), ("planner", True)])
2936
def test_quota_logs_trace_then_guidance(tmp_path, capsys, caplog, stage, remote):
30-
error = {"type": "gha_proxy", "message": "Resource exhausted: token limit reached"}
3137
requests = []
3238

3339
def lambda_response(request):
3440
requests.append(request)
35-
return httpx.Response(402, json={"error": error})
41+
return httpx.Response(402, json=SPENT_QUOTA_BODY)
3642

3743
graph = CallGraph(language="python")
3844
graph.add_node(Node("pkg.run", NodeType.FUNCTION, "pkg.py", 1, 3))
@@ -103,7 +109,7 @@ def run(*args, **kwargs):
103109
diagnostic = (tmp_path / "quota.log").read_text()
104110
assert "Traceback (most recent call last)" in diagnostic
105111
assert "LLMQuotaError" in diagnostic
106-
assert error["message"] in diagnostic
112+
assert SPENT_QUOTA_BODY["error"]["message"] in diagnostic
107113
assert diagnostic.index("Traceback") < diagnostic.rindex("CodeBoarding: ")
108114
records = [record for record in caplog.records if record.name == "codeboarding_cli.main"]
109115
assert records[-2].exc_info is not None
@@ -113,3 +119,47 @@ def run(*args, **kwargs):
113119
assert "or wait for your weekly reset" in records[-1].getMessage()
114120
assert "CodeBoarding: CodeBoarding" not in records[-1].getMessage()
115121
assert records[-1].getMessage() == f"CodeBoarding: {exit_info.value.__cause__}"
122+
123+
124+
def _hosted_run_with_spent_quota(stack: ExitStack, requests: list[httpx.Request]) -> None:
125+
"""Hosted credentials and a proxy that says the quota is spent, with tool installs patched out."""
126+
127+
def lambda_response(request):
128+
requests.append(request)
129+
return httpx.Response(402, json=SPENT_QUOTA_BODY)
130+
131+
client = stack.enter_context(httpx.Client(transport=httpx.MockTransport(lambda_response)))
132+
hosted = {"OPENROUTER_API_KEY": OIDC_RELAY_PLACEHOLDER_KEY, "OPENROUTER_BASE_URL": "http://127.0.0.1:4000"}
133+
stack.enter_context(patch.dict(os.environ, hosted, clear=True))
134+
stack.enter_context(patch("agents.llm_errors.ChatOpenAI", partial(ChatOpenAI, http_client=client)))
135+
for name in ("setup_logging", "ensure_config_template", "load_user_config", "configure_models", "load_plugins"):
136+
stack.enter_context(patch(f"codeboarding_cli.bootstrap.{name}"))
137+
138+
139+
@pytest.mark.parametrize(
140+
"command,analysis",
141+
[
142+
(["full"], "full_analysis.run_analysis_pipeline"),
143+
# Incremental too: its engine-change recovery is a full run, started after bootstrap.
144+
(["incremental"], "incremental_analysis.run_incremental"),
145+
(["partial", "--component-id", "1"], "partial_analysis.run_analysis_pipeline"),
146+
],
147+
)
148+
def test_spent_quota_stops_every_run_before_tool_installs_and_static_analysis(tmp_path, caplog, command, analysis):
149+
requests: list[httpx.Request] = []
150+
with ExitStack() as stack:
151+
_hosted_run_with_spent_quota(stack, requests)
152+
ensure_tools = stack.enter_context(patch("codeboarding_cli.bootstrap.ensure_tools"))
153+
run_analysis = stack.enter_context(patch(f"codeboarding_cli.commands.{analysis}"))
154+
stack.enter_context(caplog.at_level(logging.ERROR, logger="codeboarding_cli.main"))
155+
exit_info = stack.enter_context(pytest.raises(SystemExit))
156+
main([command[0], "--local", str(tmp_path), *command[1:]])
157+
158+
assert exit_info.value.code == 3
159+
assert [request.url.path for request in requests] == ["/models"]
160+
ensure_tools.assert_not_called()
161+
run_analysis.assert_not_called()
162+
quota_error = exit_info.value.__cause__
163+
assert isinstance(quota_error, LLMQuotaError)
164+
assert caplog.records[-1].getMessage() == f"CodeBoarding: {quota_error}"
165+
assert "https://codeboarding.org/pricing" in caplog.records[-1].getMessage()

0 commit comments

Comments
 (0)