Repository navigation
feat(arms): resume from partial checkpoints #1659
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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. |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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={}) | ||
|
napetrov marked this conversation as resolved.
Resolved
|
||
| 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] | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Must fix (blocking): Nothing checks that a profile arm's identity includes its system prompt: returning Suggestion: Add a test that edits the profile file between attempts and expects I tested this patch: it fixes the problem, and the tests still pass. Patch--- a/dokimi/tests/test_arm_runner_incremental.py
+++ b/dokimi/tests/test_arm_runner_incremental.py
@@ -196,6 +196,21 @@
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"]
+
+
+def test_a_profile_arm_fingerprint_changes_with_its_system_prompt(monkeypatch):
+ from dokimi.agent_profiles.loader import AgentProfile
+ from dokimi.eval import arms_checkpoint
+ from dokimi.treatments.arms import AgentProfileTreatment
+
+ monkeypatch.setattr(arms_checkpoint, "resolve_model", lambda model, provider: "route")
+ config = {"session_turns": None, "concurrency": 5, "model": "m", "provider": "p"}
+
+ def fingerprint_with(prompt):
+ profile = AgentProfile(id="expert", name="Expert", description="", system_prompt=prompt, path=Path("e.md"))
+ return arms_checkpoint.fingerprint(config, [AgentProfileTreatment(profile)], [])
+
+ assert fingerprint_with("Answer briefly.") != fingerprint_with("Answer at length.")
def _normalized(data: dict) -> dict:DetailsIf I change line 79 to |
||
| 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"]) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Fix before merge (blocking): The model route check is not tested: removing line 93 leaves the tests passing, though the docs say resume checks the effective model route. Suggestion: Add a test that changes the resolved route between attempts and expects I tested this patch: it fixes the problem, and the tests still pass. Patch--- a/dokimi/tests/test_arm_runner_incremental.py
+++ b/dokimi/tests/test_arm_runner_incremental.py
@@ -490,6 +490,16 @@
assert capsys.readouterr().err.count(f"Error: cannot write {tmp_path / 'arms.partial.json'}") == 1
+def test_a_resume_fingerprint_changes_with_the_model_route(monkeypatch):
+ from dokimi.eval import arms_checkpoint
+
+ config = {"session_turns": None, "concurrency": 5, "model": "m", "provider": "p"}
+ monkeypatch.setattr(arms_checkpoint, "resolve_model", lambda model, provider: "route-a")
+ before = arms_checkpoint.fingerprint(config, [], [])
+ monkeypatch.setattr(arms_checkpoint, "resolve_model", lambda model, provider: "route-b")
+ assert arms_checkpoint.fingerprint(config, [], []) != before
+
+
class _RetrievalArm(Treatment):
"""Context that differs per question, as a docs arm retrieves it."""
DetailsInput: a resume with the same |
||
| 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: | ||
|
Check warning on line 101 in dokimi/dokimi/eval/arms_checkpoint.py
|
||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Must fix (blocking): A JSON list given to Suggestion: Add a case that writes I tested this patch: it fixes the problem, and the tests still pass. Patch--- a/dokimi/tests/test_arm_runner_incremental.py
+++ b/dokimi/tests/test_arm_runner_incremental.py
@@ -949,3 +949,12 @@
partial.save(_bare_partial(1, "mine"))
assert partial.name() == tmp_path / "arms.partial2.json"
assert not (tmp_path / "arms.partial.json").exists() and not out.exists() # the link dangles again
+
+
+def test_a_checkpoint_that_is_a_json_list_is_refused_by_name(tmp_path):
+ from dokimi.eval.arms_checkpoint import read_checkpoint
+
+ path = tmp_path / "questions.json"
+ path.write_text("[]", encoding="utf-8")
+ with pytest.raises(InputError, match=r"--resume-from .*expected an arms.v1 checkpoint"):
+ read_checkpoint(path)DetailsWithout the |
||
| 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): | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Must fix (blocking): A saved answer with empty text is taken as complete on resume: dropping the Suggestion: Add a case with an empty saved answer that expects the question to be asked again. I tested this patch: it fixes the problem, and the tests still pass. Patch--- a/dokimi/tests/test_arm_runner_incremental.py
+++ b/dokimi/tests/test_arm_runner_incremental.py
@@ -772,6 +772,14 @@
assert exc.value.code == 2
+def test_an_empty_saved_answer_is_asked_again_on_resume():
+ from dokimi.eval.arms_checkpoint import _is_complete
+ from dokimi.records import Answer, Record
+
+ row = Record(question_id="q0", answers={"baseline": Answer(text="")})
+ assert not _is_complete(row, ["baseline"])
+
+
def _bare_partial(recorded: int, answer: str) -> dict:
return {"arms": ["baseline"], "answers": [{"question_id": "q0", "arms": {"baseline": {"answer": answer}}}],
"partial": {"questions_requested": 4, "questions_recorded": recorded}}DetailsWithout the check it is restored as complete and the judge scores the empty answer, and the two changed test files still pass. |
||
| 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) | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Fix before merge (blocking): The
--resume-fromhelp and the changelog heading say the flag resumes local-skill runs only, but baseline and profile runs resume too.Also at:
dokimi/changelog.d/20261202_210000_arms-resume.md:3.Suggestion: Name the arm kinds the flag accepts in the help text and the changelog heading.
I tested this patch: it fixes the problem, and the tests still pass.
Patch
Details
The help text on line 455 and the changelog heading (
dokimi/changelog.d/20261202_210000_arms-resume.md:3) say the flag reads a local-skill checkpoint. The docs listbaselineandprofile:among the supported arms, and the fingerprint covers both. I'd name the arm kinds in the help and the changelog, or say an interrupted arms run, so that they are not narrower than the code.