173 lines
8.6 KiB
Python
173 lines
8.6 KiB
Python
import contextlib
|
|
import io
|
|
import json
|
|
import pathlib
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
import unittest
|
|
|
|
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
|
|
|
from rung_replay.archive import archiving, print_report, replay_folder
|
|
from rung_replay.command import down_from
|
|
from loop_effects.effects import Effects
|
|
from failure import Failure
|
|
from rung_replay.search import first_reply, Miss, Replay, replayed, Tried
|
|
from claude_code.reply import Limited
|
|
from model_routing.ladder_file import read_ladder, SHIPPED
|
|
from model_routing.ladder import Rung
|
|
|
|
LADDER = read_ladder(SHIPPED)
|
|
REFERENCE = Rung("claude-opus-5-5", "medium")
|
|
MIDDLE = Rung("claude-sonnet-5-5", "high")
|
|
CHEAP = Rung("claude-haiku-5-5", "max")
|
|
LOWER = Rung("claude-haiku-5-5", "xhigh")
|
|
|
|
|
|
def search(cases, candidates, replies, climbs=()):
|
|
"""replayed on cases named by strings, where replies[rung][case] is the set of items a rung reproduces in the case."""
|
|
asked = []
|
|
|
|
def replay_one(case, rung):
|
|
asked.append((case, rung))
|
|
reply = replies[rung]
|
|
return reply if isinstance(reply, Limited) else reply[case]
|
|
|
|
with contextlib.redirect_stderr(io.StringIO()):
|
|
return replayed(cases, REFERENCE, candidates, replay_one, lambda _, reply: sorted(reply), "cases", climbs), asked
|
|
|
|
|
|
class Replayed(unittest.TestCase):
|
|
def test_holds_each_candidate_highest_first_to_what_the_reference_reproduced_and_stops_at_the_first_that_misses(self):
|
|
replies = {REFERENCE: {"a": {0, 1}, "b": set()}, MIDDLE: {"a": {0, 1}}, CHEAP: {"a": {1}}}
|
|
replay, asked = search(["a", "b"], [MIDDLE, CHEAP, LOWER], replies)
|
|
self.assertEqual(replay, Replay([{0, 1}, set()], [Tried(MIDDLE, []), Tried(CHEAP, [Miss("a", 0, {1})])], MIDDLE))
|
|
self.assertEqual(sorted(asked, key=lambda pair: (pair[1] != REFERENCE, pair[0])), [("a", REFERENCE), ("b", REFERENCE), ("a", MIDDLE), ("a", CHEAP)])
|
|
|
|
def test_names_no_rung_when_the_first_misses_and_tries_none_when_the_reference_reproduced_nothing(self):
|
|
self.assertEqual(search(["a"], [MIDDLE, CHEAP], {REFERENCE: {"a": {0}}, MIDDLE: {"a": set()}})[0], Replay([{0}], [Tried(MIDDLE, [Miss("a", 0, set())])], None))
|
|
self.assertEqual(search(["a"], [MIDDLE], {REFERENCE: {"a": set()}}), (Replay([set()], [], None), [("a", REFERENCE)]))
|
|
|
|
def test_counts_a_miss_in_any_case_not_only_the_last(self):
|
|
replies = {REFERENCE: {"a": {0}, "b": {0}}, MIDDLE: {"a": set(), "b": {0}}}
|
|
self.assertEqual(search(["a", "b"], [MIDDLE], replies)[0], Replay([{0}, {0}], [Tried(MIDDLE, [Miss("a", 0, set())])], None))
|
|
|
|
def test_holds_each_climb_to_what_the_reference_reproduced_whatever_another_climb_misses(self):
|
|
high, higher = Rung("claude-fable-5-2", "low"), Rung("claude-fable-5-2", "high")
|
|
replies = {REFERENCE: {"a": {0}, "b": set()}, high: {"a": set()}, higher: {"a": {0}}, MIDDLE: {"a": {0}}}
|
|
replay, asked = search(["a", "b"], [MIDDLE], replies, [high, higher])
|
|
self.assertEqual(replay, Replay([{0}, set()], [Tried(MIDDLE, [])], MIDDLE, [Tried(high, [Miss("a", 0, set())]), Tried(higher, [])]))
|
|
self.assertNotIn(("b", high), asked)
|
|
self.assertEqual(search(["a"], [MIDDLE], {REFERENCE: {"a": set()}}, [high]), (Replay([set()], [], None, []), [("a", REFERENCE)]))
|
|
|
|
def test_stops_at_a_usage_limit(self):
|
|
limit = Limited(None, "limit")
|
|
self.assertEqual(search(["a"], [MIDDLE], {REFERENCE: {"a": {0}}, MIDDLE: {"a": {0}}, CHEAP: limit}, [CHEAP])[0], limit)
|
|
self.assertEqual(search(["a"], [MIDDLE], {REFERENCE: limit})[0], limit)
|
|
self.assertEqual(search(["a"], [MIDDLE, CHEAP], {REFERENCE: {"a": {0}}, MIDDLE: limit})[0], limit)
|
|
|
|
|
|
class FirstReply(unittest.TestCase):
|
|
def test_tries_three_times_and_returns_the_first_reply_that_is_no_failure(self):
|
|
replies = [Failure("one"), Failure("two"), "done"]
|
|
self.assertEqual(first_reply(lambda: replies.pop(0)), "done")
|
|
replies = [Failure("one"), Limited(None, "limit")]
|
|
self.assertEqual(first_reply(lambda: replies.pop(0)), Limited(None, "limit"))
|
|
replies = [Failure("one"), Failure("two"), Failure("three"), "unasked"]
|
|
self.assertEqual(first_reply(lambda: replies.pop(0)), Failure("three"))
|
|
|
|
|
|
class DownFrom(unittest.TestCase):
|
|
def test_runs_from_the_projects_rung_down_to_the_floor_highest_first(self):
|
|
self.assertEqual(down_from(LADDER, Rung("claude-fable-5-2", "low"), MIDDLE), [Rung("claude-fable-5-2", "low"), REFERENCE, MIDDLE])
|
|
self.assertEqual(down_from(LADDER, REFERENCE, MIDDLE), [REFERENCE, MIDDLE])
|
|
|
|
|
|
def effects(claude):
|
|
return Effects(claude=claude, **{name: unused for name in Effects.__dataclass_fields__ if name != "claude"})
|
|
|
|
|
|
def unused(*_):
|
|
raise AssertionError("not called")
|
|
|
|
|
|
class ArchivedRuns(unittest.TestCase):
|
|
def setUp(self):
|
|
self.folder = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory())) / "replays" / "tool-1"
|
|
|
|
def run_archived(self, replies):
|
|
return archiving(effects(lambda args, cwd, prompt: replies.pop(0)), self.folder).claude
|
|
|
|
def kept(self):
|
|
return sorted(self.folder.glob("*.jsonl"))
|
|
|
|
def test_keeps_each_run_as_the_prompt_it_read_then_the_stream_it_printed_and_returns_claudes_process_as_it_was(self):
|
|
stream = '{"type": "system"}\n{"type": "result", "result": "ok"}\n'
|
|
proc = subprocess.CompletedProcess(["claude"], 0, stream, "")
|
|
run = self.run_archived([proc, subprocess.CompletedProcess(["claude"], 0, stream, "")])
|
|
self.assertIs(run(["-p", "--agent", "prose-reviewer"], "/clone", "Review it."), proc)
|
|
run(["-p", "--agent", "prose-reviewer"], "/clone", "Review that.")
|
|
first, second = (path.read_text(encoding="utf-8").splitlines() for path in self.kept())
|
|
prompts = sorted((json.loads(lines[0]) for lines in (first, second)), key=lambda header: header["prompt"])
|
|
self.assertEqual(prompts, [
|
|
{"type": "replay_run", "args": ["-p", "--agent", "prose-reviewer"], "cwd": "/clone", "prompt": prompt, "returncode": 0, "stderr": ""} for prompt in ("Review it.", "Review that.")
|
|
])
|
|
self.assertEqual(first[1:], stream.splitlines())
|
|
|
|
def test_keeps_the_runs_private_and_the_prompt_readable(self):
|
|
self.run_archived([subprocess.CompletedProcess(["claude"], 0, "{}", "")])([], "/r", "Läs den.")
|
|
self.assertEqual(self.folder.stat().st_mode & 0o777, 0o700)
|
|
self.assertIn("Läs den.", self.kept()[0].read_text(encoding="utf-8"))
|
|
|
|
def test_keeps_a_run_that_failed_and_a_run_repeated_once(self):
|
|
failed = subprocess.CompletedProcess(["claude"], 1, "half a stream", "boom")
|
|
run = self.run_archived([failed, failed])
|
|
run([], "/r", "p")
|
|
run([], "/r", "p")
|
|
self.assertEqual(len(self.kept()), 1)
|
|
kept = self.kept()[0].read_text(encoding="utf-8").splitlines()
|
|
self.assertEqual((json.loads(kept[0])["returncode"], json.loads(kept[0])["stderr"], kept[1]), (1, "boom", "half a stream"))
|
|
|
|
def test_keeps_nothing_where_claude_did_not_start_and_says_where_it_could_not_keep_a_run(self):
|
|
def missing(args, cwd, prompt):
|
|
raise FileNotFoundError(2, "No such file or directory")
|
|
|
|
with self.assertRaises(FileNotFoundError):
|
|
archiving(effects(missing), self.folder).claude([], "/r", "p")
|
|
self.assertFalse(self.folder.exists())
|
|
# A file where the folder's parent should be.
|
|
self.folder.parent.parent.mkdir(exist_ok=True)
|
|
self.folder.parent.write_text("")
|
|
proc = subprocess.CompletedProcess(["claude"], 0, "{}", "")
|
|
err = io.StringIO()
|
|
with contextlib.redirect_stderr(err):
|
|
self.assertIs(self.run_archived([proc])([], "/r", "p"), proc)
|
|
self.assertIn(f"could not keep the run in {self.folder}: ", err.getvalue())
|
|
|
|
def test_prints_the_report_and_keeps_it_beside_the_runs(self):
|
|
out = io.StringIO()
|
|
with contextlib.redirect_stdout(out):
|
|
print_report(self.folder, "The report.")
|
|
self.assertEqual(out.getvalue(), "The report.\n")
|
|
self.assertEqual((self.folder / "result.md").read_text(encoding="utf-8"), "The report.\n")
|
|
self.assertEqual(self.folder.stat().st_mode & 0o777, 0o700)
|
|
|
|
def test_says_on_stderr_where_it_could_not_keep_the_report_and_still_prints_it(self):
|
|
self.folder.parent.parent.mkdir(exist_ok=True)
|
|
self.folder.parent.write_text("")
|
|
out, err = io.StringIO(), io.StringIO()
|
|
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
|
|
print_report(self.folder, "The report.")
|
|
self.assertEqual(out.getvalue(), "The report.\n")
|
|
self.assertIn(f"could not keep the result in {self.folder}: ", err.getvalue())
|
|
|
|
def test_names_the_folder_by_the_tool_its_arguments_and_the_second_in_utc_under_replays(self):
|
|
root = pathlib.Path("/archive")
|
|
self.assertEqual(replay_folder(root, "review-replay", ["stability", "claude-opus-5-5", "--omit-claude-md"], 1790000000.0), root / "replays" / "review-replay-stability-claude-opus-5-5-omit-claude-md-20260921T141320Z")
|
|
self.assertEqual(replay_folder(root, "judge-replay", ["a/b c"], 0.0), root / "replays" / "judge-replay-a_b_c-19700101T000000Z")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|