Wait out a usage limit and retry, without counting it as a failed run
This commit is contained in:
@@ -2,6 +2,7 @@
|
||||
|
||||
## Unreleased
|
||||
|
||||
- `loop-claude` waits out a usage limit and retries, without counting it as a failure: 2 minutes past the reset, or every 10 minutes when claude names none. It prints when the next try is due.
|
||||
- Install the `claude-security` plugin (README → Install): larv-review's full security scan now runs once you confirm its cost; an unattended larv-review reports the scan as not run. `settings.json` silences the plugin's scan tip after `git push`.
|
||||
- systems-architect and product-owner-reviewer can no longer edit what they review; stability-reviewer keeps its shell to run tests, and loses Claude Code's file-editing tools.
|
||||
- Every project's `todo.md` takes one shape, and larv-review's gate checks it: one table of items, each scored by the formula and goal weights the file states and held to its bar, an item under the bar dropped unless its Exempt cell says why. `bin/rank_todo.py` ranks the table, and `rank_todo.py --help` shows a valid file.
|
||||
|
||||
@@ -89,6 +89,16 @@ def ends_stream(event: dict) -> bool:
|
||||
return event.get("type") == "result"
|
||||
|
||||
|
||||
# {"type": "result", "structured_output": {"evidence": "...", ...}, ...}
|
||||
def structured_output(stdout: str) -> object:
|
||||
return (parse_entry(stdout) or {}).get("structured_output")
|
||||
# {"type": "result", "api_error_status": 429, "result": "You've hit your session limit · resets 7:40pm (Europe/Stockholm)", ...}
|
||||
def hit_limit(event: dict) -> bool:
|
||||
return ends_stream(event) and event.get("api_error_status") == 429
|
||||
|
||||
|
||||
# {"type": "rate_limit_event", "rate_limit_info": {"status": "rejected", "resetsAt": 1790790000, ...}}
|
||||
def rejected_until(event: dict) -> int | None:
|
||||
"""When a usage limit that rejected the request resets, in seconds since the epoch."""
|
||||
info = event.get("rate_limit_info") if event.get("type") == "rate_limit_event" else None
|
||||
if not isinstance(info, dict) or info.get("status") != "rejected":
|
||||
return None
|
||||
resets_at = info.get("resetsAt")
|
||||
return resets_at if isinstance(resets_at, int) and not isinstance(resets_at, bool) else None
|
||||
|
||||
@@ -2,11 +2,11 @@ import dataclasses
|
||||
import json
|
||||
import typing
|
||||
|
||||
from loop_claude.claude_code.entries import structured_output
|
||||
from loop_claude.claude_code.entries import hit_limit, parse_entry
|
||||
from loop_claude.cycle.retry import retried
|
||||
from loop_claude.cycle.verdicts import Finished, Interrupt, Unfinished, Verdict
|
||||
from loop_claude.effects import Effects
|
||||
from loop_claude.failure import Failure
|
||||
from loop_claude.failure import Failure, Limited
|
||||
from loop_claude.stop import Stop
|
||||
|
||||
JUDGED_TRANSCRIPT_TAIL = 40000
|
||||
@@ -63,14 +63,18 @@ def judge(root: str, task: str, premises: str, rendered_transcript: str, model:
|
||||
return retried("judge", lambda: run_judge(root, args, prompt, rendered_transcript, effects), effects)
|
||||
|
||||
|
||||
def run_judge(root: str, args: list[str], prompt: str, rendered_transcript: str, effects: Effects) -> Verdict | Failure:
|
||||
def run_judge(root: str, args: list[str], prompt: str, rendered_transcript: str, effects: Effects) -> Verdict | Failure | Limited:
|
||||
try:
|
||||
proc = effects.claude(args, root, prompt)
|
||||
except OSError as failure:
|
||||
return Failure(f"could not start claude: {failure.strerror}")
|
||||
reply = parse_entry(proc.stdout) or {}
|
||||
# The json output names the reset only in prose, such as "resets 7:40pm (Europe/Stockholm)", so the retry polls.
|
||||
if hit_limit(reply):
|
||||
return Limited(None)
|
||||
if proc.returncode != 0:
|
||||
return Failure(proc.stderr.strip() or f"the judge exited {proc.returncode}")
|
||||
verdict = verdict_from(structured_output(proc.stdout))
|
||||
verdict = verdict_from(reply.get("structured_output"))
|
||||
if isinstance(verdict, Failure):
|
||||
return Failure(f"{verdict.reason}; it replied: {proc.stdout.strip() or 'nothing'}")
|
||||
if not grounded(verdict.evidence, rendered_transcript):
|
||||
|
||||
@@ -1,21 +1,37 @@
|
||||
import sys
|
||||
import time
|
||||
import typing
|
||||
|
||||
from loop_claude.effects import Effects
|
||||
from loop_claude.failure import Failure
|
||||
from loop_claude.failure import Failure, Limited
|
||||
from loop_claude.stop import Stop
|
||||
|
||||
T = typing.TypeVar("T")
|
||||
|
||||
PAST_RESET = 120
|
||||
UNKNOWN_RESET_POLL = 600
|
||||
|
||||
def retried(who: str, attempt: typing.Callable[[], T | Failure], effects: Effects) -> T | Stop:
|
||||
|
||||
def retried(who: str, attempt: typing.Callable[[], T | Failure | Limited], effects: Effects) -> T | Stop:
|
||||
failures = 0
|
||||
while True:
|
||||
failures += 1
|
||||
result = attempt()
|
||||
if isinstance(result, Limited):
|
||||
due = retry_due(result, effects.now())
|
||||
print(f"the {who} hit a usage limit; retrying at {time.strftime('%Y-%m-%d %H:%M', time.localtime(due))}", file=sys.stderr, flush=True)
|
||||
effects.sleep(due - effects.now())
|
||||
continue
|
||||
if not isinstance(result, Failure):
|
||||
return result
|
||||
failures += 1
|
||||
if failures == 3:
|
||||
return Stop(1, f"the {who} failed three times running: {result.reason}")
|
||||
print(f"retrying the {who} in a minute: {result.reason}", file=sys.stderr)
|
||||
effects.sleep(60)
|
||||
|
||||
|
||||
def retry_due(limited: Limited, now: float) -> float:
|
||||
# A retry before the reset fails (https://platform.claude.com/docs/en/api/rate-limits), so polling sooner only spends requests.
|
||||
if limited.resets_at is not None and limited.resets_at + PAST_RESET > now:
|
||||
return limited.resets_at + PAST_RESET
|
||||
return now + UNKNOWN_RESET_POLL
|
||||
|
||||
@@ -1,25 +1,31 @@
|
||||
from loop_claude.claude_code.entries import assistant_parts, ends_stream, parse_entry
|
||||
from loop_claude.claude_code.entries import assistant_parts, ends_stream, hit_limit, parse_entry, rejected_until
|
||||
from loop_claude.claude_code.session import Session
|
||||
from loop_claude.claude_code.transcript import part_line
|
||||
from loop_claude.effects import Effects
|
||||
from loop_claude.failure import Failure
|
||||
from loop_claude.failure import Failure, Limited
|
||||
|
||||
PRINTED_TOOL_INPUT = 160
|
||||
|
||||
|
||||
def run_worker(root: str, args: list[str], effects: Effects) -> Failure | None:
|
||||
def run_worker(root: str, args: list[str], effects: Effects) -> Failure | Limited | None:
|
||||
try:
|
||||
proc = effects.stream_claude(args, root)
|
||||
except OSError as failure:
|
||||
return Failure(f"could not start claude: {failure.strerror}")
|
||||
done = False
|
||||
done = limited = False
|
||||
resets: list[int] = []
|
||||
for raw in proc.lines():
|
||||
event = parse_entry(raw) or {}
|
||||
done = done or ends_stream(event)
|
||||
limited = limited or hit_limit(event)
|
||||
if (resets_at := rejected_until(event)) is not None:
|
||||
resets.append(resets_at)
|
||||
for part in assistant_parts(event):
|
||||
if line := part_line(part, PRINTED_TOOL_INPUT):
|
||||
print(line, flush=True)
|
||||
code = proc.wait()
|
||||
if limited:
|
||||
return Limited(max(resets, default=None))
|
||||
if code < 0:
|
||||
return Failure(f"claude killed by signal {-code}")
|
||||
if code:
|
||||
|
||||
@@ -21,6 +21,7 @@ class Effects:
|
||||
execv: typing.Callable[[str, list[str]], None]
|
||||
git: typing.Callable[[list[str], str], subprocess.CompletedProcess[str]]
|
||||
input: typing.Callable[[str], str]
|
||||
now: typing.Callable[[], float]
|
||||
on_terminal: typing.Callable[[], bool]
|
||||
python: typing.Callable[[list[str]], subprocess.CompletedProcess[str]]
|
||||
sleep: typing.Callable[[float], None]
|
||||
@@ -46,6 +47,7 @@ def system_effects() -> Effects:
|
||||
execv=os.execv,
|
||||
git=lambda args, cwd: subprocess.run(["git", *args], capture_output=True, cwd=cwd, text=True),
|
||||
input=input,
|
||||
now=time.time,
|
||||
on_terminal=lambda: sys.stdin.isatty() and sys.stdout.isatty(),
|
||||
python=lambda args: subprocess.run([sys.executable, *args], capture_output=True, text=True),
|
||||
sleep=time.sleep,
|
||||
|
||||
@@ -5,3 +5,9 @@ import dataclasses
|
||||
class Failure:
|
||||
"""A step failed, and reason says why; its caller decides what follows."""
|
||||
reason: str
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Limited:
|
||||
"""claude hit a usage limit, which resets at resets_at in seconds since the epoch, or at a time it did not say."""
|
||||
resets_at: int | None
|
||||
|
||||
@@ -45,7 +45,9 @@ Exit 1, saying why, when:
|
||||
- the worker or the judge fails three times running, retried a minute apart within the cycle. A
|
||||
worker fails when claude cannot start, exits non-zero, is killed, or ends without a result event;
|
||||
a judge when claude cannot start or exits non-zero, or its reply misses or mistypes a field,
|
||||
interrupts without a question, or quotes a line the transcript does not hold.
|
||||
interrupts without a question, or quotes a line the transcript does not hold. A usage limit is
|
||||
no failure: it is retried 2 minutes past its reset, or every 10 minutes while claude names no
|
||||
future reset, as the judge's reply never does; stderr says when the next try is due.
|
||||
|
||||
Exit 2, when the human is needed and cannot answer:
|
||||
- stdin or stdout is not a terminal, when a model must be picked or an interrupt answered
|
||||
|
||||
+32
-3
@@ -19,12 +19,13 @@ from loop_claude.claude_code import entries, session, transcript, trust
|
||||
from loop_claude.cycle import archive, interrupt, judge, retry, run, states, worker
|
||||
from loop_claude.cycle.verdicts import Finished, Interrupt, Unfinished
|
||||
from loop_claude.effects import Effects
|
||||
from loop_claude.failure import Failure
|
||||
from loop_claude.failure import Failure, Limited
|
||||
from loop_claude.loop import main, reload
|
||||
from loop_claude.project import checkout, model_choice, premises
|
||||
from loop_claude.stop import Stop
|
||||
|
||||
CWD = pathlib.Path("/c")
|
||||
NOW = 1790000000
|
||||
|
||||
|
||||
def assistant(*parts):
|
||||
@@ -54,6 +55,7 @@ class FakeEffects:
|
||||
execv=self.execv,
|
||||
git=lambda args, cwd: self.answer("git", args),
|
||||
input=lambda prompt: self.answer("input", prompt),
|
||||
now=lambda: NOW,
|
||||
on_terminal=lambda: self.terminal,
|
||||
python=lambda args: self.answer("python", args),
|
||||
sleep=lambda seconds: self.calls.append(("sleep", seconds)),
|
||||
@@ -108,11 +110,12 @@ class Worker:
|
||||
|
||||
|
||||
class Streamed:
|
||||
def __init__(self, code):
|
||||
def __init__(self, code, *events):
|
||||
self.code = code
|
||||
self.events = events or ({"type": "result"},)
|
||||
|
||||
def lines(self):
|
||||
return [json.dumps({"type": "result"}) + "\n"]
|
||||
return [json.dumps(event) + "\n" for event in self.events]
|
||||
|
||||
def wait(self):
|
||||
return self.code
|
||||
@@ -255,6 +258,32 @@ class Retried(unittest.TestCase):
|
||||
self.assertEqual(retry.retried("judge", lambda: Failure("no"), fake.effects()), Stop(1, "the judge failed three times running: no"))
|
||||
self.assertEqual(fake.calls, [("sleep", 60), ("sleep", 60)])
|
||||
|
||||
def test_waits_out_a_usage_limit_without_counting_a_failure(self):
|
||||
fake = FakeEffects()
|
||||
results = [Failure("one"), Limited(NOW + 3600), Failure("two"), Limited(None), Limited(NOW - 600), Failure("three")]
|
||||
self.assertEqual(retry.retried("worker", lambda: results.pop(0), fake.effects()), Stop(1, "the worker failed three times running: three"))
|
||||
self.assertEqual(fake.calls, [("sleep", 60), ("sleep", 3720), ("sleep", 60), ("sleep", 600), ("sleep", 600)])
|
||||
|
||||
|
||||
class Limits(unittest.TestCase):
|
||||
def test_the_worker_reports_the_latest_reset_its_stream_names(self):
|
||||
rejected = [{"type": "rate_limit_event", "rate_limit_info": {"status": "rejected", "resetsAt": resets_at}} for resets_at in (NOW + 60, NOW + 600)]
|
||||
allowed = {"type": "rate_limit_event", "rate_limit_info": {"status": "allowed", "resetsAt": NOW + 9000}}
|
||||
limited = {"type": "result", "api_error_status": 429}
|
||||
fake = FakeEffects(streams=[Streamed(1, rejected[1], allowed, rejected[0], limited), Streamed(1, limited), Streamed(0, rejected[0], {"type": "result"})])
|
||||
self.assertEqual(worker.run_worker("/r", [], fake.effects()), Limited(NOW + 600))
|
||||
self.assertEqual(worker.run_worker("/r", [], fake.effects()), Limited(None))
|
||||
self.assertIsNone(worker.run_worker("/r", [], fake.effects()))
|
||||
|
||||
def test_the_judge_reports_a_limit_whatever_its_exit_code(self):
|
||||
reply = json.dumps({"type": "result", "api_error_status": 429, "is_error": True, "result": "You've hit your session limit · resets 7:40pm (Europe/Stockholm)"})
|
||||
fake = FakeEffects(claude=[ran(reply, code=1, stderr="limited")])
|
||||
self.assertEqual(judge.run_judge("/r", [], "", "", fake.effects()), Limited(None))
|
||||
|
||||
def test_reads_only_a_rejecting_events_whole_seconds(self):
|
||||
for info, want in [({"status": "rejected", "resetsAt": NOW}, NOW), ({"status": "allowed", "resetsAt": NOW}, None), ({"status": "rejected", "resetsAt": True}, None), ({"status": "rejected"}, None), ("rejected", None)]:
|
||||
self.assertEqual(entries.rejected_until({"type": "rate_limit_event", "rate_limit_info": info}), want, info)
|
||||
|
||||
|
||||
class Interrupts(unittest.TestCase):
|
||||
def test_stops_off_a_terminal_before_starting_claude(self):
|
||||
|
||||
@@ -390,6 +390,18 @@ class Cycles(unittest.TestCase):
|
||||
self.assertIn("retrying the judge in a minute: the judge returned no reply; it replied: nothing\n", run.stderr)
|
||||
self.assertEqual(run.stderr.strip().splitlines()[-1], 'the judge failed three times running: the judge\'s reply has no evidence of type string; it replied: {"structured_output": {"interrupt": false}}')
|
||||
|
||||
def test_waits_out_a_usage_limit_and_retries_without_counting_a_failure(self):
|
||||
checkout = Checkout(self)
|
||||
resets_at = int(time.time()) + 3600
|
||||
rejected = json.dumps({"type": "rate_limit_event", "rate_limit_info": {"status": "rejected", "resetsAt": resets_at}})
|
||||
limited = json.dumps({"type": "result", "api_error_status": 429, "is_error": True, "result": "You've hit your session limit"})
|
||||
run = checkout.run([worker(exit=1), worker(stream=f"{rejected}\n{limited}\n", result=False, exit=1), worker(exit=1), worker(), judge(stdout=limited, exit=1), judge()])
|
||||
self.assertEqual(run.code, 130)
|
||||
self.assertEqual(run.roles(), ["worker"] * 4 + ["judge"] * 2 + ["worker"])
|
||||
self.assertEqual([round(seconds, -1) for seconds in run.sleeps], [60, 3720, 60, 600])
|
||||
self.assertIn(f"the worker hit a usage limit; retrying at {time.strftime('%Y-%m-%d %H:%M', time.localtime(resets_at + 120))}\n", run.stderr)
|
||||
self.assertIn("the judge hit a usage limit; retrying at ", run.stderr)
|
||||
|
||||
def test_retries_the_judge_alone_when_its_verdict_quotes_nothing_in_the_transcript(self):
|
||||
checkout = Checkout(self)
|
||||
run = checkout.run([
|
||||
|
||||
@@ -25,7 +25,6 @@
|
||||
| ID | Release | Exempt | Item | R | S | A | G | Goals | Score |
|
||||
|---|---|---|---|---|---|---|---|---|---|
|
||||
| 1 | 0.1.0 | question | **Say in README → Install how the transcript archive is backed up, once bender-infra backs up ai-sandbox's data volume.** | 3 | 5 | 8 | 9 | 2, 3 | 27.8 |
|
||||
| 3 | 0.1.0 | | **Wait out a usage limit and retry however long it lasts, without counting it as a failed run.** | 4 | 5 | 9 | 8 | 4 | 23.5 |
|
||||
| 7 | 0.1.0 | decision | **Give the judge the project's recorded decisions, and ask it whether anything the project records settles a choice.** | 3 | 4 | 8 | 8 | 4.2 | 19.0 |
|
||||
| 8 | 0.1.0 | | **Judge a cycle on more than the transcript's last 40,000 characters.** | 4 | 5 | 7 | 8 | 4.2 | 15.8 |
|
||||
| 13 | 0.1.0 | decision | **Make larv-review §3 applicable on its own, cite its rules by name, and say where a pass's round count is recorded.** | 3 | 5 | 6 | 7 | 4.1 | 15.6 |
|
||||
@@ -48,10 +47,6 @@ It lives under `~/.claude`, which `.gitignore` keeps from the remote, so a lost
|
||||
|
||||
2026-10-02, the human: ai-sandbox is the VM `loop-claude` will run on, hosted on the server bender. bender-infra, the infrastructure-as-code project that manages bender, will back up ai-sandbox's data volume once ai-sandbox is rebuilt. The item waits for the human to say the rebuild has landed. Before writing the README line, check that `~/.claude` lives on that volume and that the backup is private and encrypted at rest.
|
||||
|
||||
### 3. Wait out a usage limit and retry however long it lasts, without counting it as a failed run.
|
||||
|
||||
Today a worker or judge that hits a usage limit fails three times a minute apart, and the loop exits 1, so an unattended loop dies at every limit. The transcript line Claude Code writes for it, marked `"error":"rate_limit"`, holds the reset time: `You've hit your session limit · resets 7:40pm (Europe/Stockholm)`. Sleep until 2 minutes past it. The judge runs without a transcript, so find what its JSON reply carries on a limit. Where no reset time can be read, retry every 10 minutes: a retry before the reset fails (https://platform.claude.com/docs/en/api/rate-limits), so polling sooner only spends requests. Print when the next try is due, and update `--help`'s exit 1.
|
||||
|
||||
### 7. Give the judge the project's recorded decisions, and ask it whether anything the project records settles a choice.
|
||||
|
||||
Today it reads only the README's Goals and Audience (`premises.py`) and cannot see an answer recorded in `docs/decisions.md` or `AGENTS.md`, so it can interrupt the human again for a question already answered. Revise the decision "loop-claude: a judge decides each interrupt from the transcript and the README's premises; the worker's own account of which goal settles a choice decides nothing" to match.
|
||||
|
||||
Reference in New Issue
Block a user