Files
claude-config/bin/chunk_driver/project/test_model_choice.py
T

166 lines
7.9 KiB
Python

import contextlib
import dataclasses
import fcntl
import io
import json
import pathlib
import sys
import tempfile
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2]))
from failure import Failure
from loop_effects.doubles import FakeEffects
from chunk_driver.drivers import LOOP_CLAUDE
from chunk_driver.project import model_choice
from loop_state.paths import paths_from
from text_files.file_writes import replace_file
from agent_cycle.stop import Stop
class Overridden(unittest.TestCase):
def test_the_environment_names_the_judges_or_the_workers_model_over_the_default(self):
self.assertEqual(model_choice.overridden({}, "saved"), model_choice.Models("saved", "saved"))
self.assertEqual(model_choice.overridden({"LOOP_CLAUDE_JUDGE_MODEL": "j", "LOOP_CLAUDE_WORKER_MODEL": ""}, "saved"), model_choice.Models("j", "saved"))
self.assertEqual(model_choice.overridden({"LOOP_CLAUDE_JUDGE_MODEL": "j", "LOOP_CLAUDE_WORKER_MODEL": "w"}, "saved"), model_choice.Models("j", "w"))
class ModelsOfARun(unittest.TestCase):
def setUp(self):
temp = tempfile.TemporaryDirectory()
self.addCleanup(temp.cleanup)
self.paths = paths_from(pathlib.Path(temp.name))
self.paths.models_file.parent.mkdir()
def test_a_run_that_names_both_models_reads_no_models_file_and_asks_nothing(self):
self.paths.models_file.write_text("not json")
fake = FakeEffects()
env = {"LOOP_CLAUDE_JUDGE_MODEL": "j", "LOOP_CLAUDE_WORKER_MODEL": "w"}
self.assertEqual(model_choice.get_or_ask_models("proj", self.paths, env, LOOP_CLAUDE, fake.effects()), model_choice.Models("j", "w"))
self.assertEqual(fake.calls, [])
def test_a_run_that_names_one_model_takes_the_other_from_the_models_file(self):
self.paths.models_file.write_text(json.dumps({"proj": "saved"}))
fake = FakeEffects()
self.assertEqual(model_choice.get_or_ask_models("proj", self.paths, {"LOOP_CLAUDE_JUDGE_MODEL": "j"}, LOOP_CLAUDE, fake.effects()), model_choice.Models("j", "saved"))
self.assertEqual(model_choice.get_or_ask_models("proj", self.paths, {"LOOP_CLAUDE_WORKER_MODEL": "w"}, LOOP_CLAUDE, fake.effects()), model_choice.Models("saved", "w"))
self.assertEqual(fake.calls, [])
def test_a_run_that_names_one_model_asks_for_the_projects_where_none_is_saved_and_saves_the_pick(self):
fake, said = FakeEffects(inputs=["my-model"]), io.StringIO()
with contextlib.redirect_stderr(said):
models = model_choice.get_or_ask_models("proj", self.paths, {"LOOP_CLAUDE_JUDGE_MODEL": "j"}, LOOP_CLAUDE, fake.effects())
self.assertEqual(models, model_choice.Models("j", "my-model"))
self.assertEqual(json.loads(self.paths.models_file.read_text()), {"proj": "my-model"})
self.assertIn(" proj runs on my-model\n", said.getvalue())
def test_off_a_terminal_it_stops_naming_the_driver_to_rerun_and_the_file_to_merge_the_model_into(self):
fake = FakeEffects(on_terminal=False)
stop = model_choice.get_or_ask_models("proj", self.paths, {}, LOOP_CLAUDE, fake.effects())
assert isinstance(stop, Stop)
self.assertEqual(stop.code, 2)
self.assertIn(f"pick proj's model, or merge {{\"proj\": \"<model>\"}} into {self.paths.models_file}", stop.reason)
self.assertIn(LOOP_CLAUDE, stop.reason)
self.assertFalse(self.paths.models_file.exists())
def test_stops_with_exit_1_where_the_models_file_maps_no_projects_to_model_names(self):
for held in ("[]", '{"proj": 5}', '{"proj": ""}'):
with self.subTest(held=held):
self.paths.models_file.write_text(held)
stop = model_choice.get_or_ask_models("proj", self.paths, {}, LOOP_CLAUDE, FakeEffects().effects())
self.assertEqual(stop, Stop(1, f"could not read {self.paths.models_file}: not an object mapping projects to model names"))
class SavingAModel(unittest.TestCase):
def setUp(self):
temp = tempfile.TemporaryDirectory()
self.addCleanup(temp.cleanup)
self.paths = paths_from(pathlib.Path(temp.name))
self.lock = self.paths.home / ".local/state/loop-claude/models.lock"
def test_adds_the_projects_model_to_those_the_file_holds(self):
self.paths.models_file.parent.mkdir()
self.paths.models_file.write_text(json.dumps({"other": "model-x"}))
self.assertIsNone(model_choice.save_model("proj", "model-b", self.paths, replace_file))
self.assertEqual(json.loads(self.paths.models_file.read_text()), {"other": "model-x", "proj": "model-b"})
def test_writes_the_file_for_a_human_to_merge_into_a_project_per_tab_indented_line_in_the_order_of_their_keys(self):
self.paths.models_file.parent.mkdir()
self.paths.models_file.write_text(json.dumps({"zebra": "model-z", "other": "model-x"}))
self.assertIsNone(model_choice.save_model("proj", "model-b", self.paths, replace_file))
self.assertEqual(self.paths.models_file.read_text(), '{\n\t"other": "model-x",\n\t"proj": "model-b",\n\t"zebra": "model-z"\n}')
def lock_is_held(self) -> bool:
with open(self.lock, "a") as other:
try:
fcntl.flock(other, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
return True
return False
def test_holds_the_models_lock_from_its_read_to_its_write(self):
self.paths.models_file.parent.mkdir()
held = []
class Watched(pathlib.PosixPath):
"""The models file, which notes whether the lock is held each time it is opened."""
def __fspath__(watched) -> str:
held.append(self.lock_is_held())
return super().__fspath__()
def replace(path: pathlib.Path, data: bytes) -> None:
held.append(self.lock_is_held())
paths = dataclasses.replace(self.paths, models_file=Watched(self.paths.models_file))
self.assertIsNone(model_choice.save_model("proj", "model-b", paths, replace))
self.assertEqual(held, [True, True])
self.assertFalse(self.lock_is_held())
def test_doesnt_save_anything_where_it_cannot_take_the_lock(self):
self.paths.models_file.parent.mkdir()
self.lock.parent.parent.mkdir(parents=True)
self.lock.parent.write_text("")
saved = model_choice.save_model("proj", "model-b", self.paths, replace_file)
assert isinstance(saved, Failure)
self.assertRegex(saved.reason, f"^could not save the model in {self.paths.models_file}: cannot lock {self.lock.parent}: \\w")
self.assertFalse(self.paths.models_file.exists())
def test_a_pick_is_saved_through_save_model_alone(self):
self.paths.models_file.parent.mkdir()
fake, held = FakeEffects(inputs=["my-model"]), []
def replace(path: pathlib.Path, data: bytes) -> Failure:
held.append(self.lock_is_held())
return Failure("could not save")
fake.replace_file = replace
self.assertEqual(model_choice.get_or_ask_model("proj", self.paths, LOOP_CLAUDE, fake.effects()), Stop(1, f"could not save the model in {self.paths.models_file}: could not save"))
self.assertEqual(held, [True])
class ModelPrompt(unittest.TestCase):
OFFERED = [("claude-opus-5-5", "Opus 5.5"), ("claude-haiku-4-5", "Haiku 4.5")]
def test_reads_a_number_as_the_offered_model_and_anything_else_as_a_name(self):
self.assertEqual(model_choice.model_picked(" 2 ", self.OFFERED), "claude-haiku-4-5")
self.assertEqual(model_choice.model_picked("1", self.OFFERED), "claude-opus-5-5")
self.assertEqual(model_choice.model_picked("0", self.OFFERED), Failure("pick 1 to 2"))
self.assertEqual(model_choice.model_picked("opus", self.OFFERED), "opus")
self.assertEqual(model_choice.model_picked("3", []), "3")
self.assertEqual(model_choice.model_picked("3", self.OFFERED), Failure("pick 1 to 2"))
self.assertIsNone(model_choice.model_picked(" ", self.OFFERED))
def test_asks_again_until_an_answer_picks_a_model(self):
with tempfile.TemporaryDirectory() as empty:
fake = FakeEffects(inputs=["", "my-model"])
self.assertEqual(model_choice.ask_for_model("proj", pathlib.Path("/m.json"), pathlib.Path(empty), LOOP_CLAUDE, fake.effects()), "my-model")
self.assertEqual(len(fake.made("input")), 2)
fake = FakeEffects(inputs=[EOFError()])
self.assertEqual(model_choice.ask_for_model("proj", pathlib.Path("/m.json"), pathlib.Path(empty), LOOP_CLAUDE, fake.effects()), Stop(2, "the human is needed to pick proj's model, but the input ended"))
if __name__ == "__main__":
unittest.main()