Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 52 additions & 5 deletions codd/ai_invoke.py
Original file line number Diff line number Diff line change
Expand Up @@ -421,7 +421,7 @@ def invoke_file_writing_agent(
_record_retry_stderr(result.stderr)
detail = (result.stderr.strip() or result.stdout.strip()
or f"exit code {result.returncode}")
raise ValueError(f"AI command failed: {detail}")
raise ValueError(f"AI command failed: {_with_usage_headline(detail)}")

# Keep UTF-8 names literal in both listings and make diff paths relative to cwd.
# Set the options in the subprocess environments to preserve the Git argv.
Expand Down Expand Up @@ -599,7 +599,7 @@ def _invoke_subprocess(
stderr = result.stderr.strip()
exit_code = f"exit code {result.returncode}"
detail = stderr or result.stdout.strip() or exit_code
error = ValueError(f"AI command failed: {detail}")
error = ValueError(f"AI command failed: {_with_usage_headline(detail)}")
# Keep the existing exception contract and provide feedback without stdout.
error.__dict__["retry_diagnostic"] = stderr or exit_code
raise error
Expand All @@ -614,6 +614,8 @@ def _invoke_subprocess(
def _is_transient_failure(exc: ValueError) -> bool:
"""Transient = nonzero exit or empty output. Missing binary is permanent."""
message = str(exc)
if message.startswith("AI command failed") and _usage_exhausted_line(message):
return False # an exhausted usage limit does not clear on retry
return message.startswith("AI command failed") or message == "AI command returned empty output"


Expand Down Expand Up @@ -712,6 +714,46 @@ def _transport_error_text(detail: str, stderr: str | None, prompt: str) -> str:
return "".join(parts).strip() or detail


#: A CLI's own error line ("ERROR: ...", "error: ...", "fatal: ..."), also when
#: it follows the "AI command failed: " prefix on the message's first line.
_ERROR_LINE = re.compile(r"^\s*(?:AI command failed:\s*)?(?:error|fatal)\s*[:!]", re.IGNORECASE)

# An exhausted usage limit or credit balance: permanent for the rest of the
# run (the CLI usually says when it resets). Deliberately narrow: per-minute
# quotas and rate limits ("429", "quota exceeded for ... per minute") stay
# transient and keep their retry.
_USAGE_EXHAUSTED = re.compile(
r"\busage limit\b|\bpurchase more credits\b|\bout of credits\b|\binsufficient credits?\b",
re.IGNORECASE,
)


def _usage_exhausted_line(text: str) -> str | None:
"""The CLI's last own error line, when it says the usage limit or credits
are exhausted. Only the last error line counts: earlier "ERROR:" lines can
be log output the agent printed while working."""
last = None
for line in (text or "").splitlines():
if _ERROR_LINE.match(line):
last = line
if last is None or not _USAGE_EXHAUSTED.search(last):
return None
return re.sub(r"^\s*AI command failed:\s*", "", last).strip()


def _with_usage_headline(detail: str) -> str:
"""Put an exhausted-usage error line first, so the one-line summary of the
failure names it instead of a leading warning. Any other failure keeps its
detail unchanged."""
line = _usage_exhausted_line(detail)
if line is None:
return detail
first = detail.strip().splitlines()[0].strip() if detail.strip() else ""
if first == line:
return detail
return f"{line}\n{detail}"


def _is_transient_error(stderr: str) -> bool:
"""True when *stderr* clearly describes a transient/recoverable transport
failure (socket/connection drop, timeout, 429/5xx gateway, overload).
Expand Down Expand Up @@ -812,9 +854,14 @@ def _invoke_with_recovery(
os.environ[OUTPUT_TOKENS_ENV] = prior
else:
return attempt(prompt, raised_env)
# Transient transport: bounded auto-retry with backoff.
if transient_attempts < TRANSIENT_AUTO_RETRIES and _is_transient_error(
_transport_error_text(detail, _retry_stderr.get(), prompt)
# Transient transport: bounded auto-retry with backoff. An exhausted
# usage limit or quota is never transient, whatever else the
# transcript mentions: re-issuing the call cannot succeed.
transport_text = _transport_error_text(detail, _retry_stderr.get(), prompt)
if (
transient_attempts < TRANSIENT_AUTO_RETRIES
and not _usage_exhausted_line(detail)
and _is_transient_error(transport_text)
):
transient_attempts += 1
print(
Expand Down
101 changes: 101 additions & 0 deletions tests/test_ai_failure_headline.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
"""An AI command failure names the CLI's own error line first, and an exhausted
usage limit is not retried as a transient transport error.

Live symptom: an agent CLI printed a benign configuration warning on its first
stderr line and "ERROR: You've hit your usage limit ... try again at <time>"
near the end. The stage error showed only the warning, and the call was retried
as "transient" because the long transcript happened to contain transport words.
"""
from __future__ import annotations

import subprocess

import pytest

import codd.ai_invoke as ai_invoke
from codd.ai_invoke import invoke_ai

_WARNING = "warning: Untrusted project-local configuration is disabled."
_TRANSCRIPT = "exec\n$ pytest -q\nrequest timed out while waiting\n" * 3
_LIMIT = "ERROR: You've hit your usage limit. Try again at Dec 4th, 9:50 AM."


def _completed(command, returncode=0, stdout="ai output", stderr=""):
return subprocess.CompletedProcess(command, returncode, stdout=stdout, stderr=stderr)


def _always_fail(monkeypatch, stderr, attempts):
def fake_run(command, **kwargs):
attempts.append(command)
return _completed(command, returncode=1, stderr=stderr)
monkeypatch.setattr(ai_invoke.subprocess, "run", fake_run)


def _fail_once(monkeypatch, stderr, attempts):
def fake_run(command, **kwargs):
attempts.append(command)
if len(attempts) == 1:
return _completed(command, returncode=1, stderr=stderr)
return _completed(command, stdout="recovered")
monkeypatch.setattr(ai_invoke.subprocess, "run", fake_run)


def test_exhausted_usage_line_comes_first_and_is_not_retried(monkeypatch):
monkeypatch.setattr(ai_invoke.time, "sleep", lambda _s: None)
attempts: list = []
_always_fail(monkeypatch, f"{_WARNING}\n{_TRANSCRIPT}{_LIMIT}\n{_LIMIT}\n", attempts)

with pytest.raises(ValueError) as excinfo:
invoke_ai("mock-ai", "prompt")
message = str(excinfo.value)
assert message.splitlines()[0] == f"AI command failed: {_LIMIT}"
assert _WARNING in message # the full detail still follows
assert len(attempts) == 1 # main retried this as "transient"


def test_exhausted_usage_is_not_retried_by_the_caller_retries_either(monkeypatch):
monkeypatch.setattr(ai_invoke.time, "sleep", lambda _s: None)
attempts: list = []
_always_fail(monkeypatch, f"{_LIMIT}\n", attempts)
with pytest.raises(ValueError):
invoke_ai("mock-ai", "prompt", retries=2)
assert len(attempts) == 1


def test_exhausted_usage_on_the_first_line_is_not_retried(monkeypatch):
monkeypatch.setattr(ai_invoke.time, "sleep", lambda _s: None)
attempts: list = []
_always_fail(monkeypatch, f"{_LIMIT}\nrequest timed out\n", attempts)
with pytest.raises(ValueError) as excinfo:
invoke_ai("mock-ai", "prompt")
assert str(excinfo.value).splitlines()[0] == f"AI command failed: {_LIMIT}"
assert len(attempts) == 1


def test_per_minute_quota_is_still_transient(monkeypatch):
monkeypatch.setattr(ai_invoke.time, "sleep", lambda _s: None)
attempts: list = []
_fail_once(monkeypatch, "ERROR: 429 Quota exceeded for quota metric 'requests per minute'\n", attempts)
assert invoke_ai("mock-ai", "prompt") == "recovered"
assert len(attempts) == 2


def test_earlier_log_error_lines_do_not_block_a_transient_retry(monkeypatch):
monkeypatch.setattr(ai_invoke.time, "sleep", lambda _s: None)
attempts: list = []
_fail_once(monkeypatch,
"ERROR:app.billing:usage limit reached for tenant acme\n"
"ERROR: stream disconnected before completion: connection reset by peer\n",
attempts)
assert invoke_ai("mock-ai", "prompt") == "recovered"
assert len(attempts) == 2


def test_other_failures_keep_their_message_unchanged(monkeypatch):
monkeypatch.setattr(ai_invoke.time, "sleep", lambda _s: None)
attempts: list = []
stderr = f"{_WARNING}\nError: input exceeds the context window\n"
_always_fail(monkeypatch, stderr, attempts)
with pytest.raises(ValueError) as excinfo:
invoke_ai("mock-ai", "prompt")
assert str(excinfo.value) == "AI command failed: " + stderr.strip()
Loading