Answer the architect: a pure worker_outcome, Limited beside the retry, a limit ends a run of failures

This commit is contained in:
2026-10-02 22:59:21 +02:00
parent b37b2e91f7
commit 7bf437e75b
8 changed files with 47 additions and 36 deletions
+1 -1
View File
@@ -2,7 +2,7 @@
## Unreleased ## 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 the reset time is unknown. It prints what claude said about the limit and when the next try is due. - `loop-claude` waits out a usage limit and retries, without counting it as a failure, and a limit ends a run of failures: 2 minutes past the reset, or every 10 minutes when the reset time is unknown. It prints what claude said about the limit and 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`. - 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. - 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. - 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.
+2 -2
View File
@@ -3,10 +3,10 @@ import json
import typing import typing
from loop_claude.claude_code.entries import hit_limit, limit_said, parse_entry from loop_claude.claude_code.entries import hit_limit, limit_said, parse_entry
from loop_claude.cycle.retry import retried from loop_claude.cycle.retry import Limited, retried
from loop_claude.cycle.verdicts import Finished, Interrupt, Unfinished, Verdict from loop_claude.cycle.verdicts import Finished, Interrupt, Unfinished, Verdict
from loop_claude.effects import Effects from loop_claude.effects import Effects
from loop_claude.failure import Failure, Limited from loop_claude.failure import Failure
from loop_claude.stop import Stop from loop_claude.stop import Stop
JUDGED_TRANSCRIPT_TAIL = 40000 JUDGED_TRANSCRIPT_TAIL = 40000
+11 -1
View File
@@ -1,9 +1,10 @@
import dataclasses
import sys import sys
import time import time
import typing import typing
from loop_claude.effects import Effects from loop_claude.effects import Effects
from loop_claude.failure import Failure, Limited from loop_claude.failure import Failure
from loop_claude.stop import Stop from loop_claude.stop import Stop
T = typing.TypeVar("T") T = typing.TypeVar("T")
@@ -12,11 +13,20 @@ PAST_RESET = 120
UNKNOWN_RESET_POLL = 600 UNKNOWN_RESET_POLL = 600
@dataclasses.dataclass(frozen=True)
class Limited:
"""claude hit a usage limit; said is claude's message about it, and resets_at is when the limit resets, in seconds since the epoch, or None when unknown."""
resets_at: int | None
said: str
def retried(who: str, attempt: typing.Callable[[], T | Failure | Limited], effects: Effects) -> T | Stop: def retried(who: str, attempt: typing.Callable[[], T | Failure | Limited], effects: Effects) -> T | Stop:
failures = 0 failures = 0
while True: while True:
result = attempt() result = attempt()
if isinstance(result, Limited): if isinstance(result, Limited):
# Hitting the limit proves claude started and reached the API, so the failures before it no longer run on.
failures = 0
now = effects.now() now = effects.now()
wait = limit_wait(result, now) wait = limit_wait(result, now)
print(f"the {who} hit a usage limit ({result.said}); retrying at {time.strftime('%Y-%m-%d %H:%M %Z', time.localtime(now + wait))}", file=sys.stderr, flush=True) print(f"the {who} hit a usage limit ({result.said}); retrying at {time.strftime('%Y-%m-%d %H:%M %Z', time.localtime(now + wait))}", file=sys.stderr, flush=True)
+12 -10
View File
@@ -1,8 +1,9 @@
from loop_claude.claude_code.entries import assistant_parts, ends_stream, hit_limit, limit_said, parse_entry, rejected_until from loop_claude.claude_code.entries import assistant_parts, ends_stream, hit_limit, limit_said, parse_entry, rejected_until
from loop_claude.claude_code.session import Session from loop_claude.claude_code.session import Session
from loop_claude.claude_code.transcript import part_line from loop_claude.claude_code.transcript import part_line
from loop_claude.cycle.retry import Limited
from loop_claude.effects import Effects from loop_claude.effects import Effects
from loop_claude.failure import Failure, Limited from loop_claude.failure import Failure
PRINTED_TOOL_INPUT = 160 PRINTED_TOOL_INPUT = 160
@@ -12,27 +13,28 @@ def run_worker(root: str, args: list[str], effects: Effects) -> Failure | Limite
proc = effects.stream_claude(args, root) proc = effects.stream_claude(args, root)
except OSError as failure: except OSError as failure:
return Failure(f"could not start claude: {failure.strerror}") return Failure(f"could not start claude: {failure.strerror}")
done = False result: dict | None = None
limit: str | None = None
resets: list[int] = [] resets: list[int] = []
for raw in proc.lines(): for raw in proc.lines():
event = parse_entry(raw) or {} event = parse_entry(raw) or {}
done = done or ends_stream(event) if ends_stream(event):
if hit_limit(event): result = event
limit = limit_said(event)
if (resets_at := rejected_until(event)) is not None: if (resets_at := rejected_until(event)) is not None:
resets.append(resets_at) resets.append(resets_at)
for part in assistant_parts(event): for part in assistant_parts(event):
if line := part_line(part, PRINTED_TOOL_INPUT): if line := part_line(part, PRINTED_TOOL_INPUT):
print(line, flush=True) print(line, flush=True)
code = proc.wait() return worker_outcome(proc.wait(), result, resets)
if limit is not None:
return Limited(max(resets, default=None), limit)
def worker_outcome(code: int, result: dict | None, resets: list[int]) -> Failure | Limited | None:
if result is not None and hit_limit(result):
return Limited(max(resets, default=None), limit_said(result))
if code < 0: if code < 0:
return Failure(f"claude killed by signal {-code}") return Failure(f"claude killed by signal {-code}")
if code: if code:
return Failure(f"claude exited {code}") return Failure(f"claude exited {code}")
return None if done else Failure("claude exited 0 without a result event") return None if result is not None else Failure("claude exited 0 without a result event")
def worker_args(task: str, session: Session, model: str, resuming: bool) -> list[str]: def worker_args(task: str, session: Session, model: str, resuming: bool) -> list[str]:
-7
View File
@@ -5,10 +5,3 @@ import dataclasses
class Failure: class Failure:
"""A step failed, and reason says why; its caller decides what follows.""" """A step failed, and reason says why; its caller decides what follows."""
reason: str reason: str
@dataclasses.dataclass(frozen=True)
class Limited:
"""claude hit a usage limit; said is claude's message about it, and resets_at is when the limit resets, in seconds since the epoch, or None when unknown."""
resets_at: int | None
said: str
+1 -1
View File
@@ -46,7 +46,7 @@ Exit 1, saying why, when:
worker fails when claude cannot start, exits non-zero, is killed, or ends without a result event; 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, 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. A usage limit is interrupts without a question, or quotes a line the transcript does not hold. A usage limit is
not a failure: the worker or the judge is retried 2 minutes after the limit resets, or every 10 not a failure, and ends a run of them: the worker or the judge is retried 2 minutes after the limit resets, or every 10
minutes when the reset time is unknown or past. The judge's reply gives its reset time only as minutes when the reset time is unknown or past. The judge's reply gives its reset time only as
text, so the judge is always retried every 10 minutes. stderr says when the next try is due. text, so the judge is always retried every 10 minutes. stderr says when the next try is due.
+16 -10
View File
@@ -19,7 +19,8 @@ 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 import archive, interrupt, judge, retry, run, states, worker
from loop_claude.cycle.verdicts import Finished, Interrupt, Unfinished from loop_claude.cycle.verdicts import Finished, Interrupt, Unfinished
from loop_claude.effects import Effects from loop_claude.effects import Effects
from loop_claude.failure import Failure, Limited from loop_claude.cycle.retry import Limited
from loop_claude.failure import Failure
from loop_claude.loop import main, reload from loop_claude.loop import main, reload
from loop_claude.project import checkout, model_choice, premises from loop_claude.project import checkout, model_choice, premises
from loop_claude.stop import Stop from loop_claude.stop import Stop
@@ -258,11 +259,11 @@ 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(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)]) self.assertEqual(fake.calls, [("sleep", 60), ("sleep", 60)])
def test_waits_out_a_usage_limit_without_counting_a_failure(self): def test_waits_out_a_usage_limit_which_ends_a_run_of_failures(self):
fake = FakeEffects() fake = FakeEffects()
results = [Failure("one"), Limited(NOW + 3600, "limit"), Failure("two"), Limited(None, "limit"), Limited(NOW - 600, "limit"), Failure("three")] results = [Failure("one"), Failure("two"), Limited(NOW + 3600, "limit"), Failure("three"), Limited(None, "limit"), Limited(NOW - 600, "limit"), Failure("four"), Failure("five"), Failure("six")]
self.assertEqual(retry.retried("worker", lambda: results.pop(0), fake.effects()), Stop(1, "the worker failed three times running: three")) self.assertEqual(retry.retried("worker", lambda: results.pop(0), fake.effects()), Stop(1, "the worker failed three times running: six"))
self.assertEqual(fake.calls, [("sleep", 60), ("sleep", 3720), ("sleep", 60), ("sleep", 600), ("sleep", 600)]) self.assertEqual(fake.calls, [("sleep", 60), ("sleep", 60), ("sleep", 3720), ("sleep", 60), ("sleep", 600), ("sleep", 600), ("sleep", 60), ("sleep", 60)])
class Limits(unittest.TestCase): class Limits(unittest.TestCase):
@@ -270,12 +271,17 @@ class Limits(unittest.TestCase):
rejected = [{"type": "rate_limit_event", "rate_limit_info": {"status": "rejected", "resetsAt": resets_at}} for resets_at in (NOW + 60, NOW + 600)] 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}} allowed = {"type": "rate_limit_event", "rate_limit_info": {"status": "allowed", "resetsAt": NOW + 9000}}
limited = {"type": "result", "api_error_status": 429, "result": "You've hit your session limit"} limited = {"type": "result", "api_error_status": 429, "result": "You've hit your session limit"}
fake = FakeEffects(streams=[Streamed(1, rejected[1], allowed, rejected[0], limited), Streamed(1, {"type": "result", "api_error_status": 429}), Streamed(1, {"type": "result", "api_error_status": 429, "result": " \n"}), Streamed(1, {"type": "result", "api_error_status": 429, "result": "limit\n resets 7pm"}), Streamed(0, rejected[0], {"type": "result"})]) fake = FakeEffects(streams=[Streamed(1, rejected[1], allowed, rejected[0], limited)])
self.assertEqual(worker.run_worker("/r", [], fake.effects()), Limited(NOW + 600, "You've hit your session limit")) self.assertEqual(worker.run_worker("/r", [], fake.effects()), Limited(NOW + 600, "You've hit your session limit"))
self.assertEqual(worker.run_worker("/r", [], fake.effects()), Limited(None, "claude gave no message"))
self.assertEqual(worker.run_worker("/r", [], fake.effects()), Limited(None, "claude gave no message")) def test_a_limit_outranks_the_exit_code_and_its_message_fits_one_line(self):
self.assertEqual(worker.run_worker("/r", [], fake.effects()), Limited(None, "limit resets 7pm")) def limited(**said):
self.assertIsNone(worker.run_worker("/r", [], fake.effects())) return {"type": "result", "api_error_status": 429, **said}
self.assertEqual(worker.worker_outcome(-9, limited(result="limit\n resets 7pm"), []), Limited(None, "limit resets 7pm"))
self.assertEqual(worker.worker_outcome(1, limited(result=" \n"), [NOW]), Limited(NOW, "claude gave no message"))
self.assertEqual(worker.worker_outcome(0, limited(), []), Limited(None, "claude gave no message"))
self.assertEqual(worker.worker_outcome(0, None, [NOW]), Failure("claude exited 0 without a result event"))
self.assertIsNone(worker.worker_outcome(0, {"type": "result"}, [NOW]))
def test_the_judge_reports_a_limit_whatever_its_exit_code(self): 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)"}) reply = json.dumps({"type": "result", "api_error_status": 429, "is_error": True, "result": "You've hit your session limit · resets 7:40pm (Europe/Stockholm)"})
+4 -4
View File
@@ -390,15 +390,15 @@ class Cycles(unittest.TestCase):
self.assertIn("retrying the judge in a minute: the judge returned no reply; it replied: nothing\n", run.stderr) 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}}') 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): def test_waits_out_a_usage_limit_which_ends_a_run_of_failures(self):
checkout = Checkout(self) checkout = Checkout(self)
resets_at = int(time.time()) + 3600 resets_at = int(time.time()) + 3600
rejected = json.dumps({"type": "rate_limit_event", "rate_limit_info": {"status": "rejected", "resetsAt": resets_at}}) 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"}) 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()]) run = checkout.run([worker(exit=1), 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.code, 130)
self.assertEqual(run.roles(), ["worker"] * 4 + ["judge"] * 2 + ["worker"]) self.assertEqual(run.roles(), ["worker"] * 5 + ["judge"] * 2 + ["worker"])
self.assertEqual([round(seconds, -1) for seconds in run.sleeps], [60, 3720, 60, 600]) self.assertEqual([round(seconds, -1) for seconds in run.sleeps], [60, 60, 3720, 60, 600])
self.assertIn(f"the worker hit a usage limit (You've hit your session limit); retrying at {time.strftime('%Y-%m-%d %H:%M %Z', time.localtime(resets_at + 120))}\n", run.stderr) self.assertIn(f"the worker hit a usage limit (You've hit your session limit); retrying at {time.strftime('%Y-%m-%d %H:%M %Z', time.localtime(resets_at + 120))}\n", run.stderr)
self.assertIn("the judge hit a usage limit (You've hit your session limit); retrying at ", run.stderr) self.assertIn("the judge hit a usage limit (You've hit your session limit); retrying at ", run.stderr)