diff --git a/dokimi/changelog.d/20261202_210000_arms-resume.md b/dokimi/changelog.d/20261202_210000_arms-resume.md new file mode 100644 index 000000000..cdfd58a46 --- /dev/null +++ b/dokimi/changelog.d/20261202_210000_arms-resume.md @@ -0,0 +1,7 @@ +### Added + +- **Resume interrupted local-skill arms runs** — `arms run --resume-from` checks the ordered inputs and settings, then restores completed questions and their judge material from the checkpoint. + +### Changed + +- With a single `arms run`, keep `--out` and `--out-md` outside the skill directories so outputs do not change the inputs. diff --git a/dokimi/docs/evaluating-treatments.md b/dokimi/docs/evaluating-treatments.md index da8d099f1..d393ee992 100644 --- a/dokimi/docs/evaluating-treatments.md +++ b/dokimi/docs/evaluating-treatments.md @@ -2,6 +2,7 @@ depends_on: - dokimi/dokimi/treatments/** - dokimi/dokimi/commands/arms.py + - dokimi/dokimi/eval/arms_checkpoint.py - dokimi/dokimi/eval/arms_run.py - dokimi/dokimi/schemas/arms.v1.json - dokimi/dokimi/skills/loader.py @@ -208,12 +209,30 @@ killed or crashed before that save leaves it behind: an `arms.v1` file with a `p (`questions_requested`, `questions_recorded`) and the answers paid for, none judged. It never replaces a file (a name that holds one, finished, left by a crashed run or taken by a run going on at the same time, is passed over for `.partial2.json`), -and the commands that read arms files refuse it. There is no resume: rerun the command. -`arms matrix-run` keeps one per cell, `cells/.partial.json`. +and reports require a finished artifact. `arms matrix-run` keeps one checkpoint +per cell, `cells/.partial.json`. + +To resume an interrupted single-turn or local-tool `arms run`, rerun the command with +`--resume-from .partial.json`. The first attempt must have written a +checkpoint with a resume fingerprint. Keep the ordered question set, arm inputs, +model and settings identical. You can change `--concurrency` and the output paths. +Supported arms include `skill-agent:`, `skill-catalog:`, `skill:`, `profile:` and +`baseline`, including combinations and runtime plugins. For a single run, keep +`--out` and `--out-md` outside all skill directories so saved outputs do not +change treatment contents. The run checks the contents of bundled skill files +and the effective model route. Pin the model to a +provider snapshot when you need protection against a provider changing an alias. + +The resumed run restores completed questions and their judge material, and answers +the remaining questions. If a saved question contains an errored or missing answer, +the resumed run answers that question again. With `--judge`, it scores all answers +after generation. The original checkpoint stays available. Resume requires a single +run (`--reps 1`). For `--session-turns`, documentation or MCP arms, and older +checkpoints, rerun the original command. + For single-turn model calls without tools, set `DOKIMI_RESPONSE_CACHE` before the first attempt and keep that directory for the rerun. The rerun can reuse -cached answers for identical requests and marks them as replays. The original -checkpoint stays available for inspection. +cached answers for identical requests and marks them as replays. ### Repetitions: `--reps N` diff --git a/dokimi/docs/reference/cli-interface.json b/dokimi/docs/reference/cli-interface.json index 7f35347ea..4dbb2c5e1 100644 --- a/dokimi/docs/reference/cli-interface.json +++ b/dokimi/docs/reference/cli-interface.json @@ -171,6 +171,7 @@ {"key": "--questions", "action": "_StoreAction", "choices": null, "const": null, "default": null, "group_key": null, "group_required": null, "hidden": false, "is_flag": false, "kind": "option", "nargs": null, "position": null, "required": true, "type": null}, {"key": "--reps", "action": "_StoreAction", "choices": null, "const": null, "default": 1, "group_key": null, "group_required": null, "hidden": false, "is_flag": false, "kind": "option", "nargs": null, "position": null, "required": false, "type": "dokimi.cli_types.positive_int#96184e0d3f3b"}, {"key": "--rerank-threshold", "action": "_StoreAction", "choices": null, "const": null, "default": 0.3, "group_key": null, "group_required": null, "hidden": false, "is_flag": false, "kind": "option", "nargs": null, "position": null, "required": false, "type": "float"}, + {"key": "--resume-from", "action": "_StoreAction", "choices": null, "const": null, "default": null, "group_key": null, "group_required": null, "hidden": false, "is_flag": false, "kind": "option", "nargs": null, "position": null, "required": false, "type": null}, {"key": "--seed", "action": "_StoreAction", "choices": null, "const": null, "default": null, "group_key": null, "group_required": null, "hidden": false, "is_flag": false, "kind": "option", "nargs": null, "position": null, "required": false, "type": "int"}, {"key": "--session-turns", "action": "_StoreAction", "choices": null, "const": null, "default": null, "group_key": null, "group_required": null, "hidden": false, "is_flag": false, "kind": "option", "nargs": null, "position": null, "required": false, "type": "dokimi.cli_types.positive_int#96184e0d3f3b"}, {"key": "--temperature", "action": "_StoreAction", "choices": null, "const": null, "default": null, "group_key": null, "group_required": null, "hidden": false, "is_flag": false, "kind": "option", "nargs": null, "position": null, "required": false, "type": "float"}, diff --git a/dokimi/dokimi/cli_flags.py b/dokimi/dokimi/cli_flags.py index 2d48d36cf..94b030d27 100644 --- a/dokimi/dokimi/cli_flags.py +++ b/dokimi/dokimi/cli_flags.py @@ -220,6 +220,11 @@ class Concept: canonical=(Flag("--dry-run", kind="flag", meaning="estimate, make no paid call"),), banned=("--estimate-only", "--work-dry-run"), ), + Concept( + name="checkpoint", + help="resume an interrupted run from a checkpoint", + canonical=(Flag("--resume-from", "FILE", "path"),), + ), Concept( name="tokens", help="token caps and token budget fractions", diff --git a/dokimi/dokimi/commands/arms.py b/dokimi/dokimi/commands/arms.py index 0aea4c1d5..3586de641 100644 --- a/dokimi/dokimi/commands/arms.py +++ b/dokimi/dokimi/commands/arms.py @@ -102,6 +102,16 @@ def _print_ask_block(output: dict) -> None: print("\n" + "\n".join(ask_summary_lines(output["summary"]["ask"], output["arms"]))) +def _arms_run_paths(args: argparse.Namespace) -> tuple[Path, Path, Path | None]: + out_json = Path(args.out_json) if args.out_json else Path(f"results/arms/{args.product}.json") + out_md = Path(args.out_md) if args.out_md else Path(f"results/arms/{args.product}.md") + source = getattr(args, "resume_from", None) + resume_from = Path(source) if source is not None else None + if resume_from is not None and any(_same_file(resume_from, path) for path in (out_json, out_md)): + raise InputError(f"--resume-from {resume_from}: choose a different path for --out and --out-md") + return out_json, out_md, resume_from + + def cmd_arms_run(args: argparse.Namespace) -> None: """Run an N-arm treatment comparison and optionally judge it.""" apply_preflight_flag(args) @@ -114,10 +124,11 @@ def cmd_arms_run(args: argparse.Namespace) -> None: config = _flags_config(args) reps = getattr(args, "reps", 1) # a caller that builds its own Namespace runs once + out_json, out_md, resume_from = _arms_run_paths(args) + if reps > 1 and resume_from is not None: + raise InputError("--resume-from requires a single run (--reps 1)") refuse_replayed_reps(reps) refuse_unjudged_reps(reps, config) - out_json = Path(args.out_json) if args.out_json else Path(f"results/arms/{args.product}.json") - out_md = Path(args.out_md) if args.out_md else Path(f"results/arms/{args.product}.md") if reps > 1: # a destination known to be invalid is refused before any provider call refuse_colliding_outputs(reps, out_json, out_md) refuse_stale_reps(out_json, out_md) @@ -126,7 +137,8 @@ def cmd_arms_run(args: argparse.Namespace) -> None: specs = _parse_arm_specs(args.arms) questions = _load_questions(args.questions) config = _with_named_cell(config, args.matrix_cells, args.matrix_cell) - prepared = prepare_arms(config, specs, questions) + prepared = prepare_arms(config, specs, questions, checkpoint=reps == 1, resume_from=resume_from, + checkpoint_outputs=(("--out", out_json), ("--out-md", out_md))) except InputError: # EmptyQuestionError is one raise # a bad input record or an unreadable file, not an arm setup error: cli.main reports it (exit 2) except ProbeError as exc: @@ -434,9 +446,13 @@ def register(sub, positive_int) -> None: ".rep.json; --out then holds the arms_reps.v1 pooled comparison: per-question " "paired deltas, the noise floor across reps and a verdict. One run gives no verdict (default 1)") cli_flags.add(arms_run_p, "output", "--out", default=None, dest="out_json", - help="Output JSON path (default: results/arms/{product}.json)") + help="Output JSON path (default: results/arms/{product}.json). " + "For a single run, choose a path outside the skill directories.") arms_run_p.add_argument("--out-md", default=None, dest="out_md", - help="Output Markdown report path (default: results/arms/{product}.md)") + help="Output Markdown report path (default: results/arms/{product}.md). " + "For a single run, choose a path outside the skill directories.") + cli_flags.add(arms_run_p, "checkpoint", "--resume-from", metavar="FILE", + help="Reuse complete questions from an interrupted local-skill arms checkpoint JSON file") add_preflight_flag(arms_run_p) arms_run_p.set_defaults(func=cmd_arms_run) diff --git a/dokimi/dokimi/eval/arm_runner.py b/dokimi/dokimi/eval/arm_runner.py index b20b281a2..87b62bfac 100644 --- a/dokimi/dokimi/eval/arm_runner.py +++ b/dokimi/dokimi/eval/arm_runner.py @@ -216,6 +216,7 @@ def run( library_id: Optional[str] = None, concurrency: int = 5, on_record: Optional[Callable[[List[Dict[str, Any]]], None]] = None, + *, completed: Optional[Dict[int, Dict[str, Any]]] = None, ) -> List[Dict[str, Any]]: """Answer every question under every arm. Returns one record per question; *on_record* gets the records so far, in question order, as each question is done.""" n = len(questions) @@ -224,8 +225,8 @@ def run( if self.session_turns is not None: # Before any answer is paid for: a question short of follow-ups fails the run. check_session_questions(questions, self.session_turns) - results: Dict[int, Dict[str, Any]] = {} - lock, done = threading.Lock(), [0] + results = dict(completed or {}) + lock, done = threading.Lock(), [len(results)] stop = threading.Event() # set by a run-wide error: questions not yet started are not asked def _keep(idx: int, rec: Dict[str, Any]) -> None: # under the lock @@ -259,7 +260,7 @@ def _process(idx: int, q: Dict[str, Any]) -> None: print(f"Running {len(self.treatments)} arms over {n} questions " f"(arms: {', '.join(self.arm_names)})", flush=True) with ThreadPoolExecutor(max_workers=concurrency) as pool: - futures = [pool.submit(_process, i, q) for i, q in enumerate(questions)] + futures = [pool.submit(_process, i, q) for i, q in enumerate(questions) if i not in results] for f in as_completed(futures): f.result() diff --git a/dokimi/dokimi/eval/arms_checkpoint.py b/dokimi/dokimi/eval/arms_checkpoint.py new file mode 100644 index 000000000..7f7b3f583 --- /dev/null +++ b/dokimi/dokimi/eval/arms_checkpoint.py @@ -0,0 +1,174 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""Compatibility checks and record recovery for interrupted local-skill arms runs.""" + +from __future__ import annotations + +import json +from collections.abc import Iterator +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +from dokimi._version import __version__ +from dokimi.artifacts import ArtifactValidationError, validate_artifact +from dokimi.caching import is_empty_reply +from dokimi.digest import digest_text, tree_digest +from dokimi.eval.judge_context import JudgeContextStore +from dokimi.eval.question_text import question_text_of +from dokimi.files import InputError, read_json_input +from dokimi.llm import resolve_model +from dokimi.plugins import PluginWrappedTreatment +from dokimi.records import Record, question_id, records as as_records +from dokimi.skills import Skill +from dokimi.treatments.arms import ( + AgentProfileTreatment, + BaselineTreatment, + CombinedTreatment, + SkillAgentTreatment, + SkillCatalogTreatment, + SkillTreatment, +) +from dokimi.treatments.base import Treatment + + +def _skill_identity(skill: Skill) -> str: + # The agent can request any Markdown under the skill root. Hash the files' + # on-disk bytes, including untracked files, as well as the loaded body. + files = tree_digest(skill.path.parent.resolve(), strict=True, tracked={}) + return digest_text(json.dumps([skill.name, skill.description, skill.body, files])) + + +def _arm_skills(treatment: Treatment) -> Iterator[Skill]: + if isinstance(treatment, PluginWrappedTreatment): + yield from _arm_skills(treatment.inner) + elif isinstance(treatment, CombinedTreatment): + for child in treatment.treatments: + yield from _arm_skills(child) + elif isinstance(treatment, SkillCatalogTreatment): + yield from treatment.skills + elif isinstance(treatment, (SkillAgentTreatment, SkillTreatment)): + yield treatment.skill + + +def _refuse_skill_outputs(treatments: list[Treatment], outputs: tuple[tuple[str, Path], ...]) -> None: + roots = {skill.path.parent.resolve() for treatment in treatments for skill in _arm_skills(treatment)} + if not roots: + return + for flag, path in outputs: + try: + parent, target = path.parent.resolve(), path.resolve() + except (OSError, RuntimeError) as exc: + raise InputError(f"{flag} {path}: cannot resolve the output path: {exc}") from exc + # A checkpoint is written beside --out, even if --out links elsewhere. + for root in sorted(roots): + if parent.is_relative_to(root) or target.is_relative_to(root): + raise InputError(f"{flag} {path}: choose a path outside the skill directory {root}") + + +def _treatment_identity(treatment: Treatment) -> list[Any]: + if isinstance(treatment, PluginWrappedTreatment): + return [treatment.plugin_set, _treatment_identity(treatment.inner)] + if isinstance(treatment, CombinedTreatment): + return [treatment.name, [_treatment_identity(child) for child in treatment.treatments]] + identity = [treatment.name, type(treatment).__name__] + if isinstance(treatment, BaselineTreatment): + return identity + if isinstance(treatment, AgentProfileTreatment): + return [*identity, treatment.max_chars, treatment.profile.system_prompt] + if isinstance(treatment, (SkillAgentTreatment, SkillTreatment)): + return [*identity, treatment.max_chars, _skill_identity(treatment.skill)] + if isinstance(treatment, SkillCatalogTreatment): + return [*identity, treatment.max_chars, [_skill_identity(skill) for skill in treatment.skills]] + raise ValueError(f"arm {treatment.name!r} depends on input that cannot be fingerprinted") + + +def fingerprint(config: dict, treatments: list[Treatment], questions: list[dict]) -> str: + """Hash the ordered inputs and settings. Worker count may change between attempts.""" + if config["session_turns"] is not None: + raise ValueError("session checkpoints do not carry judge context") + settings = {key: value for key, value in config.items() if key != "concurrency"} + identities = [_treatment_identity(treatment) for treatment in treatments] + settings["answer_route"] = resolve_model(settings["model"], settings["provider"]) + return digest_text(json.dumps( + ["arms-resume.v1", __version__, settings, identities, questions], sort_keys=True, + )) + + +def read_checkpoint(path: Path) -> dict: + data = read_json_input(path, flag="--resume-from") + if not isinstance(data, dict) or data.get("schema_version") != "arms.v1" or "partial" not in data: + raise InputError(f"--resume-from {path}: expected an arms.v1 checkpoint") + try: + validate_artifact("arms", data) + except ArtifactValidationError as exc: + raise InputError(f"--resume-from {path}: {exc}") from exc + if not data["partial"].get("resume_fingerprint"): + raise InputError(f"--resume-from {path}: this checkpoint has no resume fingerprint") + return data + + +@dataclass +class RestoredAnswers: + records: dict[int, dict] + context: JudgeContextStore + + +def _is_complete(row: Record, arms: list[str]) -> bool: + for arm in arms: + cell = row.answer(arm) + if cell is None or cell.raw.get("error") or is_empty_reply(cell.text): + return False + return set(row.answers) == set(arms) + + +def restore(data: dict, expected: str, questions: list[dict], arms: list[str], + judge_context: str, path: Path) -> RestoredAnswers: + """Seed completed questions by index, including any saved out of execution order.""" + label = f"--resume-from {path}" + partial = data["partial"] + if partial["resume_fingerprint"] != expected or data["arms"] != arms: + raise InputError(f"{label}: questions, run settings or treatment contents differ from the checkpoint") + rows = as_records(data["answers"], source=label, kind="answers") + if partial["questions_requested"] != len(questions) or partial["questions_recorded"] != len(rows): + raise InputError(f"{label}: inconsistent checkpoint question counts") + indices = {question_id(question): index for index, question in enumerate(questions)} + seen: set[int] = set() + completed: dict[int, dict] = {} + for row in rows: + index = indices.get(row.question_id) + if index is None or index in seen or row.question_text != question_text_of(questions[index]): + raise InputError(f"{label}: unexpected or repeated answer record for question {row.question_id!r}") + seen.add(index) + if _is_complete(row, arms): + completed[index] = dict(row.raw) + store = JudgeContextStore.from_artifact({ + "arms": arms, + "answers": list(completed.values()), + "judge_context": data.get("judge_context"), + "judge_materials": data.get("judge_materials"), + }) + if store.mode != judge_context or any( + store.get(question_id(questions[index]), arm) is None for index in completed for arm in arms + ): + raise InputError(f"{label}: the completed answers are missing matching judge context") + return RestoredAnswers(completed, store) + + +def checkpoint_setup(config: dict, treatments: list[Treatment], questions: list[dict], + source: Path | None, *, outputs: tuple[tuple[str, Path], ...] = (), + ) -> tuple[str | None, RestoredAnswers | None]: + if outputs: + _refuse_skill_outputs(treatments, outputs) + data = read_checkpoint(source) if source is not None else None + try: + identity = fingerprint(config, treatments, questions) + except (OSError, ValueError, RecursionError) as exc: + if source is not None: + raise InputError(f"--resume-from {source}: cannot identify the run inputs: {exc}") from exc + return None, None + if source is None or data is None: + return identity, None + arms = [treatment.name for treatment in treatments] + return identity, restore(data, identity, questions, arms, config["judge_context"], source) diff --git a/dokimi/dokimi/eval/arms_run.py b/dokimi/dokimi/eval/arms_run.py index 52e2eb0e2..56c6cfd93 100644 --- a/dokimi/dokimi/eval/arms_run.py +++ b/dokimi/dokimi/eval/arms_run.py @@ -17,7 +17,8 @@ import functools import logging from collections.abc import Callable -from dataclasses import dataclass, replace +from dataclasses import asdict, dataclass, replace +from pathlib import Path from typing import TYPE_CHECKING from dokimi.defaults import ( @@ -465,9 +466,13 @@ class PreparedArms: runner: ArmRunner judge: Judge | JudgePanel | None library_id: str | None + checkpoint_fingerprint: str | None = None + completed: dict[int, dict] | None = None -def prepare_arms(config: ArmsRunConfig, specs: list[str], questions: list[dict]) -> PreparedArms: +def prepare_arms(config: ArmsRunConfig, specs: list[str], questions: list[dict], *, + checkpoint: bool = False, resume_from: Path | None = None, + checkpoint_outputs: tuple[tuple[str, Path], ...] = ()) -> PreparedArms: """Setup and every refusal: the config, the arms, the plugins, the sampling, the judge. Nothing here answers a question. A refused input raises ``ValueError`` (a usage error, exit 2), @@ -475,6 +480,7 @@ def prepare_arms(config: ArmsRunConfig, specs: list[str], questions: list[dict]) call, raises :class:`ProbeError` (a run failure, exit 1). """ from dokimi.eval.arm_runner import ArmRunner + from dokimi.eval.arms_checkpoint import checkpoint_setup from dokimi.eval.session import check_session_questions _refuse_judged_session(config) @@ -484,6 +490,10 @@ def prepare_arms(config: ArmsRunConfig, specs: list[str], questions: list[dict]) check_session_questions(questions, config.session_turns) treatments, library_id, plugin_set = _treatments(config, specs, questions) refuse_cli_arms(config, treatments) + identity, restored = ( + checkpoint_setup(asdict(config), treatments, questions, resume_from, outputs=checkpoint_outputs) + if checkpoint or resume_from is not None else (None, None) + ) check_clis_signed_in((config.provider, config.judge_provider if config.judge else None)) config = check_sampling_support(config) judge = None @@ -509,7 +519,10 @@ def prepare_arms(config: ArmsRunConfig, specs: list[str], questions: list[dict]) turn_reminder=config.turn_reminder, judge_context_mode=config.judge_context, ) - return PreparedArms(runner=runner, judge=judge, library_id=library_id) + if restored is not None: + runner.judge_context = restored.context + print(f"Restored {len(restored.records)}/{len(questions)} completed questions from {resume_from}") + return PreparedArms(runner, judge, library_id, identity, None if restored is None else restored.records) def partial_output(runner: ArmRunner, config: ArmsRunConfig, records: list[dict]) -> dict: @@ -529,19 +542,28 @@ def run_prepared(prepared: PreparedArms, config: ArmsRunConfig, questions: list[ *on_partial* gets the :func:`partial_output` each time a question is answered, so a caller can save what is paid for before the run ends; an exception from it stops the run. """ + def save_partial(done: list[dict]) -> None: + assert on_partial is not None + output = partial_output(prepared.runner, config, done) + if prepared.checkpoint_fingerprint is not None: + output["partial"]["resume_fingerprint"] = prepared.checkpoint_fingerprint + on_partial(output) + records = prepared.runner.run( library_name=config.product, questions=questions, library_id=prepared.library_id, concurrency=config.concurrency, - on_record=None if on_partial is None else ( - lambda done: on_partial(partial_output(prepared.runner, config, done))), + on_record=None if on_partial is None else save_partial, + completed=prepared.completed, ) evaluations = None if prepared.judge is None else _judge_records(prepared.runner, prepared.judge, config, records) output = prepared.runner.build_output( config.product, records, evaluations=evaluations, baseline_arm=config.baseline_arm, judge=prepared.judge, ) + if prepared.completed is not None: + output["resumed_questions"] = len(prepared.completed) if prepared.runner.stop_error is not None: # the artifact says the run stopped, not that it completed output["terminated"] = { "reason": str(prepared.runner.stop_error), diff --git a/dokimi/dokimi/schemas/arms.v1.json b/dokimi/dokimi/schemas/arms.v1.json index 4be5ead22..4a8baa427 100644 --- a/dokimi/dokimi/schemas/arms.v1.json +++ b/dokimi/dokimi/schemas/arms.v1.json @@ -106,13 +106,19 @@ "total_questions": { "type": "integer" }, + "resumed_questions": { + "description": "Number of completed questions restored from the checkpoint named by --resume-from." + }, "partial": { "type": "object", "required": ["questions_requested", "questions_recorded"], "description": "Present only in .partial.json, the file an arms run rewrites after each answered question until it saves its output whole (and then removes): what a killed or crashed run had paid for. answers holds the questions done, none judged (no evaluations or summary). Readers of arms files refuse it (issue #228 step 4).", "properties": { "questions_requested": {"type": "integer", "minimum": 0}, - "questions_recorded": {"type": "integer", "minimum": 0} + "questions_recorded": {"type": "integer", "minimum": 0}, + "resume_fingerprint": { + "description": "sha256: digest of ordered inputs and settings for a resumable arms run." + } } }, "answers": { diff --git a/dokimi/tests/test_arm_runner_incremental.py b/dokimi/tests/test_arm_runner_incremental.py index c7a382a70..eb74a9064 100644 --- a/dokimi/tests/test_arm_runner_incremental.py +++ b/dokimi/tests/test_arm_runner_incremental.py @@ -57,9 +57,9 @@ def _questions(tmp_path: Path) -> Path: return path -def _arms_argv(tmp_path: Path, *extra: str) -> list[str]: +def _arms_argv(tmp_path: Path, *extra: str, arms: str = ARMS) -> list[str]: return ["arms", "run", "--product", "onedal", "--questions", str(_questions(tmp_path)), - "--arm", ARMS, "--concurrency", "1", + "--arm", arms, "--concurrency", "1", "--out", str(tmp_path / "arms.json"), "--out-md", str(tmp_path / "arms.md"), *extra] @@ -103,6 +103,7 @@ def test_a_killed_run_leaves_its_answered_questions_in_a_valid_partial_file(tmp_ partial = tmp_path / "arms.partial.json" data = json.loads(partial.read_text(encoding="utf-8")) validate_artifact("arms", data) + assert data["partial"].pop("resume_fingerprint").startswith("sha256:") assert data["partial"] == {"questions_requested": 4, "questions_recorded": 2} assert [a["question_id"] for a in data["answers"]] == ["q0", "q1"] assert [a["arms"]["baseline"]["answer"] for a in data["answers"]] == ["answer 1", "answer 3"] @@ -192,6 +193,7 @@ def record(library_name, q, qid, *a, **k): assert len(calls) == 8 assert not (tmp_path / "arms.json").exists() data = json.loads((tmp_path / "arms.partial.json").read_text(encoding="utf-8")) + assert data["partial"].pop("resume_fingerprint").startswith("sha256:") assert data["partial"] == {"questions_requested": 4, "questions_recorded": 3} assert [a["question_id"] for a in data["answers"]] == ["q0", "q1", "q3"] @@ -267,6 +269,169 @@ def judge(*a, **k): assert json.loads(partial.read_text(encoding="utf-8"))["partial"]["questions_recorded"] == 4 +@pytest.fixture +def local_skill(tmp_path): + skill = tmp_path / "local-skill" + skill.mkdir() + (skill / "SKILL.md").write_text( + "---\nname: local-skill\ndescription: Local answers\n---\nRead the reference.\n", encoding="utf-8", + ) + resource = skill / "reference.md" + resource.write_text("reference text\n", encoding="utf-8") + return skill + + +@pytest.mark.parametrize(("flag", "arm"), [ + ("--out", "skill-agent:{skill}"), + ("--out-md", "skill:{skill}"), + ("--out", "baseline+skill:{skill}/SKILL.md"), + ("--out", "skill-catalog:{parent}"), +]) +def test_resume_outputs_stay_outside_skill_roots(tmp_path, monkeypatch, local_skill, flag, arm): + def paid_call(config): + pytest.fail("The output must be refused before the paid sampling probe") + + monkeypatch.setattr(arms_run, "check_sampling_support", paid_call) + destination = local_skill / "results" / ("arms.json" if flag == "--out" else "arms.md") + args = _arms_argv(tmp_path, flag, str(destination), "--plugins", "caveman", + arms=arm.format(skill=local_skill, parent=tmp_path)) + with pytest.raises(InputError, match=rf"{flag} .*outside the skill directory"): + _run(args) + assert not destination.parent.exists() + + +@pytest.mark.skipif(os.name == "nt", reason="symlinks need privileges on Windows") +@pytest.mark.parametrize("link_inside_skill", [False, True]) +def test_resume_refuses_an_output_link_overlapping_a_skill( + tmp_path, monkeypatch, local_skill, link_inside_skill, +): + def paid_call(config): + pytest.fail("The output must be refused before the paid sampling probe") + + monkeypatch.setattr(arms_run, "check_sampling_support", paid_call) + inside = local_skill / "answers.json" + outside = tmp_path / "answers.json" + destination, target = (inside, outside) if link_inside_skill else (outside, inside) + destination.symlink_to(target) + args = _arms_argv(tmp_path, "--out", str(destination), arms=f"skill:{local_skill}") + with pytest.raises(InputError, match=r"--out .*outside the skill directory"): + _run(args) + assert not target.exists() + + +@pytest.fixture +def resumable_skill_run(tmp_path, monkeypatch, local_skill): + """Keep the regular CLI checkpoint from an interrupted run with read-only skill tools.""" + from dokimi.eval import agent_runner + + calls = _fake_llm(monkeypatch) + agent_calls = [] + judged = [] + + def agent(question, tools, **kwargs): + agent_calls.append(question) + return { + "answer": f"{question}\n{tools[0].call(file='reference.md')}", + "token_usage": {"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15}, + "transcript": [], + "tool_call_count": 1, + "iterations": 1, + "stopped_reason": "completed", + } + + class Judge(_FakeJudge): + def score_answer(self, library_name, question, answer, context="", ground_truth=None): + judged.append((question, answer, context)) + return super().score_answer(library_name, question, answer, context, ground_truth) + + monkeypatch.setattr(agent_runner, "run_agent_loop", agent) + monkeypatch.setattr(arms_run, "_build_judge", lambda config: Judge()) + args = _arms_argv(tmp_path, "--judge", arms=f"baseline,skill-agent:{local_skill}") + save = _Partial.save + + def interrupt(self, output): + save(self, output) + if self.recorded == 2: + raise OSError("interrupted") + + with monkeypatch.context() as patch: + patch.setattr(_Partial, "save", interrupt) + with pytest.raises(SystemExit) as error: + _run(args) + assert error.value.code == 1 + checkpoint = tmp_path / "arms.partial.json" + assert len(calls) == len(agent_calls) == 2 + calls.clear() + agent_calls.clear() + return args, checkpoint, local_skill / "reference.md", calls, agent_calls, judged + + +@pytest.mark.parametrize("complete", [True, False]) +def test_resume_uses_complete_answers_in_input_order(resumable_skill_run, tmp_path, complete): + args, checkpoint, _, calls, agent_calls, judged = resumable_skill_run + payload = json.loads(checkpoint.read_text(encoding="utf-8")) + # A different worker could have answered q1 first. Save only that row. + saved = payload["answers"][1] + payload["answers"] = [saved] + payload["partial"]["questions_recorded"] = 1 + arm = "skill_agent:local-skill" + if not complete: + saved["arms"][arm]["error"] = "agent failed" + checkpoint.write_text(json.dumps(payload), encoding="utf-8") + original_bytes = checkpoint.read_bytes() + + _run([*args, "--resume-from", str(checkpoint), "--concurrency", "3"]) + + result = load_artifact("arms", tmp_path / "arms.json") + assert result["resumed_questions"] == int(complete) + assert [row["question_id"] for row in result["answers"]] == [f"q{i}" for i in range(4)] + expected = {item["question"] for i, item in enumerate(QUESTIONS) if not complete or i != 1} + assert set(agent_calls) == expected + assert len(calls) == len(agent_calls) == len(expected) + if complete: + assert result["answers"][1] == saved + assert all(row["scores"][arm]["judge_context_source"] == "stored" for row in result["evaluations"]) + assert len(judged) == 8 + assert checkpoint.read_bytes() == original_bytes + assert not (tmp_path / "arms.partial2.json").exists() + + +@pytest.mark.parametrize("changed, message", [ + ("model", "settings"), + ("question", "questions"), + ("resource", "treatment contents"), + ("output", "different path"), + ("context", "judge context"), + ("legacy", "no resume fingerprint"), + ("reps", "requires a single run"), +]) +def test_resume_refuses_incompatible_checkpoints_before_answers(resumable_skill_run, changed, message): + args, checkpoint, resource, calls, agent_calls, _ = resumable_skill_run + if changed == "model": + args.extend(["--model", "gpt-4o"]) + if changed == "question": + questions = Path(args[args.index("--questions") + 1]) + questions.write_text(questions.read_text(encoding="utf-8").replace("thing 3", "thing X"), encoding="utf-8") + if changed == "resource": + resource.write_text("reference TEXT\n", encoding="utf-8") + if changed == "output": + args.extend(["--out-md", str(checkpoint)]) + if changed == "reps": + args.extend(["--reps", "2"]) + if changed in {"legacy", "context"}: + payload = json.loads(checkpoint.read_text(encoding="utf-8")) + if changed == "legacy": + del payload["partial"]["resume_fingerprint"] + else: + payload["judge_materials"].clear() + checkpoint.write_text(json.dumps(payload), encoding="utf-8") + before = checkpoint.read_bytes() + with pytest.raises(InputError, match=message): + _run([*args, "--resume-from", str(checkpoint)]) + assert calls == agent_calls == [] + assert checkpoint.read_bytes() == before + + def test_a_matrix_cell_keeps_its_partial_file_until_its_save(tmp_path, monkeypatch, capsys): calls = _fake_llm(monkeypatch) cells = tmp_path / "cells.json" diff --git a/dokimi/tests/test_run_wide_stop.py b/dokimi/tests/test_run_wide_stop.py index 3637811f6..c839ba900 100644 --- a/dokimi/tests/test_run_wide_stop.py +++ b/dokimi/tests/test_run_wide_stop.py @@ -100,7 +100,7 @@ def test_arms_run_exits_1_and_names_the_stop_when_the_artifact_is_terminated(mon monkeypatch.setattr(arms_cmd, "_load_questions", lambda p: []) monkeypatch.setattr(arms_cmd, "run_config_from_args", lambda a: SimpleNamespace(product="lib")) monkeypatch.setattr(arms_cmd, "_with_named_cell", lambda cfg, cells, cell: cfg) - monkeypatch.setattr(arms_run, "prepare_arms", lambda cfg, specs, questions: object()) + monkeypatch.setattr(arms_run, "prepare_arms", lambda cfg, specs, questions, **kwargs: object()) monkeypatch.setattr(arms_run, "run_prepared", lambda prepared, cfg, questions, on_partial=None: _terminated_output()) monkeypatch.setattr(arms_cmd, "_save_arms_output", lambda output, out_json, out_md, partial=None: None) args = SimpleNamespace(arms="baseline", questions="q.json", matrix_cells=None, matrix_cell=None,