"""The rung search judge-replay and review-replay share: replay archived cases on a reference rung, then hold each candidate rung to what the reference reproduced.""" import concurrent.futures import dataclasses import sys import typing from failure import Failure from loop_claude.cycle.retry import FAILURES_RUNNING from claude_code.reply import Limited from model_routing.ladder import Rung # Cases replayed at once. AT_ONCE = 4 Case = typing.TypeVar("Case") # What of an archived case a reply reproduces, such as a verdict's kind or a finding's index. Aim = typing.TypeVar("Aim") Answer = typing.TypeVar("Answer") T = typing.TypeVar("T") @dataclasses.dataclass(frozen=True) class Miss(typing.Generic[Case, Aim, Answer]): """An item of case that the reference reproduced and a rung's reply missed.""" case: Case item: Aim reply: Answer @dataclasses.dataclass(frozen=True) class Tried(typing.Generic[Case, Aim, Answer]): rung: Rung missed: list[Miss[Case, Aim, Answer]] @dataclasses.dataclass(frozen=True) class Replay(typing.Generic[Case, Aim, Answer]): """on_reference holds the reference's reply on each case; tried, each candidate tried, highest first; lowest, the lowest rung that, like each candidate above it, missed nothing, or None; climbed, each climb tried, in the order given.""" on_reference: list[Answer] tried: list[Tried[Case, Aim, Answer]] lowest: Rung | None climbed: list[Tried[Case, Aim, Answer]] = dataclasses.field(default_factory=list) def replayed( cases: list[Case], reference: Rung, candidates: list[Rung], replay_one: typing.Callable[[Case, Rung], Answer | Limited], reproduced: typing.Callable[[Case, Answer], list[Aim]], what: str, climbs: typing.Sequence[Rung] = (), ) -> Replay[Case, Aim, Answer] | Limited: """Replays the cases on the reference rung, then each climb, then each candidate, highest first, on the cases where the reference reproduced anything, until a candidate misses an item it reproduced. Going down, every rung at or above the one named was tried and missed nothing, so the result needs no assumption that a higher rung does at least as well; and a miss high up spares the cheaper rungs their replays. A climb is a rung above the candidates that a route can still pick, so each is tried whatever another misses. """ on_reference = replayed_on(cases, reference, replay_one, what) if isinstance(on_reference, Limited): return on_reference held = [(case, aim) for case, reply in zip(cases, on_reference) if (aim := reproduced(case, reply))] # With nothing to hold a rung to, every rung would miss nothing. if not held: return Replay(on_reference, [], None, []) climbed: list[Tried[Case, Aim, Answer]] = [] for rung in climbs: climb = tried_on(held, rung, replay_one, reproduced, what) if isinstance(climb, Limited): return climb climbed.append(climb) tried: list[Tried[Case, Aim, Answer]] = [] lowest = None for rung in candidates: candidate = tried_on(held, rung, replay_one, reproduced, what) if isinstance(candidate, Limited): return candidate tried.append(candidate) if candidate.missed: break lowest = rung return Replay(on_reference, tried, lowest, climbed) def tried_on( held: list[tuple[Case, list[Aim]]], rung: Rung, replay_one: typing.Callable[[Case, Rung], Answer | Limited], reproduced: typing.Callable[[Case, Answer], list[Aim]], what: str, ) -> Tried[Case, Aim, Answer] | Limited: """rung's replies on the held cases, with each item the reference reproduced that a reply missed.""" replies = replayed_on([case for case, _ in held], rung, replay_one, what) if isinstance(replies, Limited): return replies misses: list[Miss[Case, Aim, Answer]] = [] for (case, aim), reply in zip(held, replies): got = reproduced(case, reply) misses += [Miss(case, item, reply) for item in aim if item not in got] return Tried(rung, misses) def replayed_on(cases: list[Case], rung: Rung, replay_one: typing.Callable[[Case, Rung], Answer | Limited], what: str) -> list[Answer] | Limited: """Each case's reply on rung, AT_ONCE at a time; a usage limit cancels the rest.""" print(f"replaying {len(cases)} {what} on {rung}", file=sys.stderr, flush=True) with concurrent.futures.ThreadPoolExecutor(AT_ONCE) as pool: running = [pool.submit(replay_one, case, rung) for case in cases] replies: list[Answer] = [] for future in running: reply = future.result() if isinstance(reply, Limited): pool.shutdown(cancel_futures=True) return reply replies.append(reply) return replies def first_reply(attempt: typing.Callable[[], T | Failure | Limited]) -> T | Failure | Limited: """The first reply that is no Failure, or the last of FAILURES_RUNNING failures. It counts failures as loop-claude's retried does, but neither waits between attempts nor waits out a usage limit, which ends a replay. """ for _ in range(FAILURES_RUNNING - 1): if not isinstance(reply := attempt(), Failure): return reply return attempt()