Retry the worker and the judge through one counter, in retry.py #129

Merged
lilleman merged 5 commits from one-failure-counter into rebuild 2026-09-29 11:12:56 +02:00
11 changed files with 42 additions and 58 deletions
+1 -1
View File
@@ -21,6 +21,6 @@ Decisions live in `docs/decisions.md`:
- loop-claude: the judge is retried alone, on its own counter
- loop-claude: the judge loads `CLAUDE.md`
- loop-claude: the archive keeps the raw transcript, and a failed archive stops the loop
- loop-claude: the rebuild keeps main's `--reloaded` state
- loop-claude: a loop running main's script stops once at the cut-over
- rebuild: a chunk into `rebuild` takes no comprehension scoring run
- loop-claude: a `claude` that cannot start is a failed worker run, retried
+1
View File
@@ -9,6 +9,7 @@
- `loop-claude` skips a transcript line it cannot parse, exits 1 naming a transcript it cannot read, and counts a `claude` it cannot start as a failed worker run.
- `loop-claude`'s judge quotes the transcript for every verdict, and a verdict quoting nothing or interrupting without a question, or a `claude` the judge cannot start, is a failed judge run; a `claude` that cannot start for an interrupt exits 1.
- `loop-claude`'s exit-2 message says what the human is needed for.
- `loop-claude` retries a failed worker within its cycle.
- `loop-claude` counts an interrupt reply starting with `<` as typed.
- `loop-claude`'s judge sees a reply the human types while claude works, and an interrupt counts one as typed.
- `loop-claude`'s archive holds the raw `.jsonl` transcript, one copy per distinct transcript, named by its SHA-256, with the verdict beside it in `<sha256>.verdict.md`; a transcript it cannot archive exits 1.
+7 -14
View File
@@ -1,12 +1,11 @@
import dataclasses
import itertools
import json
import subprocess
import typing
from loop_claude.claude_code.formats import structured_output
from loop_claude.outcome import Failure
from loop_claude.retry import stop_or_sleep_a_minute
from loop_claude.retry import retried
JUDGE_RULES = (
"Decide whether the human must now be interrupted. interrupt=true when any of these appear:\n"
@@ -57,26 +56,20 @@ def judge(root, task, premises, transcript, model):
"--tools", "",
]
prompt = judge_prompt(task, premises, transcript)
for failures in itertools.count(1):
verdict = run_judge(root, args, prompt)
if isinstance(verdict, Failure):
reason = verdict.reason
elif not grounded(verdict, transcript):
reason = f"the judge quoted {verdict.evidence!r}, nothing in the transcript" + (f", for the question: {verdict.question}" if verdict.interrupt else "")
else:
return verdict
if stop := stop_or_sleep_a_minute("judge", failures, reason):
return stop
return retried("judge", lambda: run_judge(root, args, prompt, transcript))
def run_judge(root, args, prompt):
def run_judge(root, args, prompt, transcript):
try:
proc = subprocess.run(["claude", *args], capture_output=True, cwd=root, input=prompt, text=True)
except OSError as failure:
return Failure(f"could not start claude: {failure.strerror}")
if proc.returncode != 0:
return Failure(proc.stderr.strip() or f"the judge exited {proc.returncode}")
return verdict_from(structured_output(proc.stdout))
verdict = verdict_from(structured_output(proc.stdout))
if isinstance(verdict, Verdict) and not grounded(verdict, transcript):
return Failure(f"the judge quoted {verdict.evidence!r}, nothing in the transcript" + (f", for the question: {verdict.question}" if verdict.interrupt else ""))
return verdict
def judge_prompt(task, premises, transcript):
+4 -5
View File
@@ -4,14 +4,14 @@ from loop_claude.claude_code.transcript import read, render
from loop_claude.claude_runs.interrupt import interrupt
from loop_claude.claude_runs.judge import judge
from loop_claude.claude_runs.worker import run_worker, worker_args
from loop_claude.outcome import Continue, Failure, Stop
from loop_claude.outcome import Failure, Stop
from loop_claude.retry import retried
def run_cycle(root, project, task, premises, models, paths):
session = session_for(project, paths)
resuming = bool(transcript_file(session))
if failure := run_worker(root, worker_args(task, session, models.worker, resuming)):
return failure
if stop := retried("worker", lambda: run_worker(root, worker_args(task, session, models.worker, bool(transcript_file(session))))):
return stop
path = transcript_file(session)
if not path:
return Stop(1, f"claude left no transcript for session {session.id}")
@@ -22,7 +22,6 @@ def run_cycle(root, project, task, premises, models, paths):
if failure := archive(project, path, f"Task: {task}\n\nVerdict: finished", paths):
return Stop(1, failure.reason)
delete_session(session)
return Continue()
def judge_through_interrupts(root, project, task, premises, models, session, path, paths):
+8 -17
View File
@@ -12,10 +12,10 @@ Cycles continue until an exit below or Ctrl-C. Words: ~/.claude/CLAUDE.md → "V
Exit 1: no task, not inside a checkout, no premises, a models file it cannot read or write, claude
leaves no transcript or one it cannot read or archive, claude cannot start for an interrupt, a
reload with unreadable state, or the worker or the judge fails three times running. 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 verdict misses or mistypes a field, interrupts without a
question, or quotes nothing in the transcript.
reload with unreadable state, or 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 verdict misses or
mistypes a field, interrupts without a question, or quotes nothing in the transcript.
Exit 2: the human is needed, to pick the model or answer an interrupt, and stdin or stdout is not a
terminal, the input ends, or the interrupt ended with nothing typed. Rerunning resumes any
open session.
@@ -37,18 +37,16 @@ import dataclasses
import sys
from loop_claude.cycle import run_cycle
from loop_claude.outcome import Continue, Failure, Stop
from loop_claude.outcome import Stop
from loop_claude.project.checkout import checkout_root, project_name
from loop_claude.project.models import project_models
from loop_claude.project.premises import read_premises
from loop_claude.reload import RELOAD_FLAG, decode_state, exec_if_edited, fingerprint
from loop_claude.retry import stop_or_sleep_a_minute
@dataclasses.dataclass(frozen=True)
class LoopState:
cycle_number: int
failures: int
root: str
task: str
@@ -79,15 +77,8 @@ def run_loop(argv, env, paths, launcher, cwd):
if isinstance(models, Stop):
return models
print(f"\n=== cycle {state.cycle_number} ===", flush=True)
match run_cycle(state.root, project, state.task, premises, models, paths):
case Stop() as stop:
return stop
case Failure(reason):
state = dataclasses.replace(state, failures=state.failures + 1)
if stop := stop_or_sleep_a_minute("worker", state.failures, reason):
return stop
case Continue():
state = dataclasses.replace(state, failures=0)
if stop := run_cycle(state.root, project, state.task, premises, models, paths):
return stop
def loop_state(argv, cwd):
@@ -96,7 +87,7 @@ def loop_state(argv, cwd):
if task in ("", "-h", "--help"):
return Stop(0 if task else 1, __doc__.strip())
root = checkout_root(cwd)
return root if isinstance(root, Stop) else LoopState(0, 0, root, task)
return root if isinstance(root, Stop) else LoopState(0, root, task)
state = decode_state(argv[1], LoopState) if len(argv) == 2 else None
if not (state and state.root and state.task):
return Stop(1, f"the reload cannot read the loop's state from {argv[1:]}; rerun loop-claude <task>")
+1 -6
View File
@@ -1,14 +1,9 @@
import dataclasses
@dataclasses.dataclass(frozen=True)
class Continue:
"""The cycle ended; the loop starts the next."""
@dataclasses.dataclass(frozen=True)
class Failure:
"""A step failed and its caller decides: a worker or judge run is retried until it fails three times running; anything else becomes a Stop or a warning."""
"""A step failed and its caller decides: `retried` reruns a worker or judge run until it fails three times running; anything else becomes a Stop or a warning."""
reason: str
+11 -6
View File
@@ -1,11 +1,16 @@
import itertools
import sys
import time
from loop_claude.outcome import Stop
from loop_claude.outcome import Failure, Stop
def stop_or_sleep_a_minute(who, failures, reason):
if failures == 3:
return Stop(1, f"the {who} failed three times running: {reason}")
print(f"retrying the {who} in a minute: {reason}", file=sys.stderr)
time.sleep(60)
def retried(who, attempt):
for failures in itertools.count(1):
result = attempt()
if not isinstance(result, Failure):
return result
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)
time.sleep(60)
+1 -1
View File
@@ -116,7 +116,7 @@ class Verdict(unittest.TestCase):
class LoopState(unittest.TestCase):
def test_stops_naming_the_reload_when_it_hands_over_anything_but_the_state_with_a_task(self):
for handed in (["3", "2", "/r", "do it"], ["3"], ["[1]"], [json.dumps({"cycle_number": 3, "failures": 0, "root": "/r"})], [json.dumps({"cycle_number": 3, "failures": 0, "root": "/r", "task": ""})], [json.dumps({"cycle_number": "3", "failures": 0, "root": "/r", "task": "do it"})], [json.dumps({"cycle_number": 3, "failures": 0, "root": "", "task": "do it"})], [json.dumps({"cycle_number": 3, "failures": 0, "root": "/r", "task": "do it", "turns": 1})]):
for handed in (["3", "2", "/r", "do it"], ["3"], ["[1]"], [json.dumps({"cycle_number": 3, "root": "/r"})], [json.dumps({"cycle_number": 3, "root": "/r", "task": ""})], [json.dumps({"cycle_number": "3", "root": "/r", "task": "do it"})], [json.dumps({"cycle_number": 3, "root": "", "task": "do it"})], [json.dumps({"cycle_number": 3, "root": "/r", "task": "do it", "turns": 1})], [json.dumps({"cycle_number": 3, "failures": 0, "root": "/r", "task": "do it"})]):
with self.subTest(handed=handed):
self.assertEqual(main.loop_state([main.RELOAD_FLAG, *handed], CWD), Stop(1, f"the reload cannot read the loop's state from {handed}; rerun loop-claude <task>"))
+6 -5
View File
@@ -366,6 +366,8 @@ class Cycles(unittest.TestCase):
self.assertIn("retrying the worker in a minute: claude exited 1", run.stderr)
self.assertIn("claude exited 0 without a result event", run.stderr)
self.assertEqual(run.stderr.strip().splitlines()[-1], "the worker failed three times running: claude killed by signal 9")
self.assertNotIn("=== cycle 2 ===", run.stdout)
self.assertEqual(argument(run.calls[1], "--resume"), argument(run.calls[0], "--session-id"))
run = checkout.run([worker(exit=1), worker(exit=1), worker(), judge(), worker(exit=1), worker(exit=1)])
self.assertEqual(run.code, 130)
@@ -646,17 +648,16 @@ class Reload(unittest.TestCase):
self.assertEqual(run.roles(), ["worker", "judge"] * 4)
self.assertIn("keeping the running script", run.stderr)
reloads = [json.loads(argv[1]) for argv in run.starts if argv[:1] == ["--reloaded"]]
self.assertEqual(reloads, [{"cycle_number": cycle, "failures": 0, "root": str(checkout.root), "task": TASK} for cycle in (2, 3)])
self.assertEqual(reloads, [{"cycle_number": cycle, "root": str(checkout.root), "task": TASK} for cycle in (2, 3)])
self.assertIn("=== cycle 4 ===", run.stdout)
outside = checkout.temp / "outside"
outside.mkdir()
state = {"cycle_number": 3, "failures": 2, "root": str(checkout.root), "task": TASK}
run = checkout.run([worker(exit=1)], argv=["--reloaded", json.dumps(state)], cwd=outside)
self.assertEqual((run.code, run.sleeps), (1, []))
state = {"cycle_number": 3, "root": str(checkout.root), "task": TASK}
run = checkout.run([worker()], argv=["--reloaded", json.dumps(state)], cwd=outside)
self.assertEqual((run.code, run.roles()), (130, ["worker", "judge"]))
self.assertEqual(run.calls[0]["cwd"], str(checkout.root))
self.assertIn("=== cycle 4 ===", run.stdout)
self.assertEqual(run.stderr.strip().splitlines()[-1], "the worker failed three times running: claude exited 1")
run = checkout.run([], argv=["--reloaded", "{}"])
self.assertEqual((run.code, run.calls), (1, []))
+2 -2
View File
@@ -68,9 +68,9 @@
2026-09-28, lilleman, for the rebuild. Serves goals 2 and 4: saving each transcript locally is the first step of backing it up, and it shows afterwards what an unattended run did. A copy of the `.jsonl`, deduplicated by content hash, with the verdict beside it; a rendering drops tool results, and a second-resolution stamp names two states within one second as one file. A failed archive exits 1, since a loop that loses its record silently fails the backup goal. Valid while transcripts stay small enough to copy whole.
## loop-claude: the rebuild keeps main's `--reloaded` state
## loop-claude: a loop running main's script stops once at the cut-over
2026-09-28, lilleman, for the rebuild. Serves goal 4. A loop running main's script reloads into the rebuilt one at its next cycle boundary and carries on; `decode_state` accepts only JSON whose keys and value types match `LoopState` exactly, so renaming, adding, dropping or retyping a field breaks that reload, and no code exists only for the cut-over. Valid until the rebuild merges.
2026-09-29, lilleman. Serves goal 4. The rebuild's `LoopState` lacks main's failure count, so a loop running main's script exits 1 at its first reload into the rebuild, telling the human to rerun `loop-claude <task>`. No code exists only for the cut-over: one rerun costs a one-human audience less. Valid until the rebuild merges.
## rebuild: a chunk into `rebuild` takes no comprehension scoring run
-1
View File
@@ -8,7 +8,6 @@ The rebuild lifts every dimension, one chunk per item, until the last item opens
The places the panel on `rebuild` at 2f9ab2f named (`docs/decisions.md`), capping dimension first:
- **Count the worker's and the judge's failures in one place, under one name.** All four seats traced `LoopState.failures` in `run_loop` and `judge`'s local counter to learn which run each counts.
- **Declare `LoopState` beside `decode_state`, as the state a reload carries.** All four seats held `run_loop`, `loop_state` and `exec_if_edited` open together; one found a field change ends a running loop with nothing at the dataclass saying so.
- **Hand `run_cycle` and `judge_through_interrupts` one cycle context.** Two seats: eight positional arguments.
- **Build `premises.sections` without filling `found` through an alias.** Two seats traced `current` by hand.