Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions dokimi/changelog.d/20261202_210000_arms-resume.md
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.
27 changes: 23 additions & 4 deletions dokimi/docs/evaluating-treatments.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 `<out stem>.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/<cell>.partial.json`.
and reports require a finished artifact. `arms matrix-run` keeps one checkpoint
per cell, `cells/<cell>.partial.json`.

To resume an interrupted single-turn or local-tool `arms run`, rerun the command with
`--resume-from <out stem>.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`

Expand Down
1 change: 1 addition & 0 deletions dokimi/docs/reference/cli-interface.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"},
Expand Down
5 changes: 5 additions & 0 deletions dokimi/dokimi/cli_flags.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
26 changes: 21 additions & 5 deletions dokimi/dokimi/commands/arms.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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)
Expand All @@ -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:
Expand Down Expand Up @@ -434,9 +446,13 @@ def register(sub, positive_int) -> None:
"<out stem>.rep<k>.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")

Copy link
Copy Markdown
Contributor

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-from help 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
--- a/dokimi/changelog.d/20261202_210000_arms-resume.md
+++ b/dokimi/changelog.d/20261202_210000_arms-resume.md
@@ -1,6 +1,6 @@
 ### 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.
+- **Resume interrupted arms runs** — `arms run --resume-from` checks the ordered inputs and settings, then restores completed questions and their judge material from the checkpoint.
 
 ### Changed
 
--- a/dokimi/dokimi/commands/arms.py
+++ b/dokimi/dokimi/commands/arms.py
@@ -452,7 +452,7 @@
                             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")
+                  help="Reuse complete questions from an interrupted arms checkpoint JSON file")
     add_preflight_flag(arms_run_p)
     arms_run_p.set_defaults(func=cmd_arms_run)
 
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 list baseline and profile: 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.

add_preflight_flag(arms_run_p)
arms_run_p.set_defaults(func=cmd_arms_run)

Expand Down
7 changes: 4 additions & 3 deletions dokimi/dokimi/eval/arm_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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
Expand Down Expand Up @@ -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()

Expand Down
174 changes: 174 additions & 0 deletions dokimi/dokimi/eval/arms_checkpoint.py
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={})

Check warning on line 39 in dokimi/dokimi/eval/arms_checkpoint.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: flip-bool `True` -> `False`
Comment thread
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)]

Check warning on line 72 in dokimi/dokimi/eval/arms_checkpoint.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: return-none `[treatment.plugin_set, _treatment_identity(treatment.inner)]` -> `None`
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

Check warning on line 77 in dokimi/dokimi/eval/arms_checkpoint.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: return-none `identity` -> `None`
if isinstance(treatment, AgentProfileTreatment):
return [*identity, treatment.max_chars, treatment.profile.system_prompt]

Check warning on line 79 in dokimi/dokimi/eval/arms_checkpoint.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: return-none `[*identity, treatment.max_chars, treatment.profile.system_prompt]` -> `None`

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The 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 None from line 79 leaves the tests passing.
Input: a profile: arm, with the profile file edited between the interrupted run and --resume-from.
Got: Line 79 puts the system prompt and max_chars into the fingerprint, so the edit should be refused with InputError.

Suggestion: Add a test that edits the profile file between attempts and expects --resume-from to raise InputError, as the resource-treatment contents case does for skills.

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:
Details

If I change line 79 to return None, the two changed test files still pass (59 tests), so no test expects that refusal.

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")

Check warning on line 84 in dokimi/dokimi/eval/arms_checkpoint.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: delete-statement `raise ValueError(f"arm {treatment.name!r} depends on input that cannot be fingerprinted")` -> `pass`


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")

Check warning on line 90 in dokimi/dokimi/eval/arms_checkpoint.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: delete-statement `raise ValueError("session checkpoints do not carry judge context")` -> `pass`
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"])

Check warning on line 93 in dokimi/dokimi/eval/arms_checkpoint.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: delete-statement `settings["answer_route"] = resolve_model(settings["model"], settings["provider"])` -> `pass`

Copy link
Copy Markdown
Contributor

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 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 InputError.

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."""
 
Details

Input: a resume with the same --model and --provider names, where the names now resolve to a different litellm route, for example after a package upgrade. Line 93 stores that route in the fingerprint, and settings holds only the name and provider. Without line 93 the resume is accepted, and no test expects a refusal.

return digest_text(json.dumps(
["arms-resume.v1", __version__, settings, identities, questions], sort_keys=True,

Check warning on line 95 in dokimi/dokimi/eval/arms_checkpoint.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: flip-bool `True` -> `False`
))


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

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: drop-clause `not isinstance(data, dict) or data.get("schema_version") != "arms.v1" or "partial" not in data` -> `(data.get('schema_version') != 'arms.v1' or 'partial' not in data)`

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Must fix (blocking): A JSON list given to --resume-from is not tested: removing the not isinstance(data, dict) check on line 101 leaves the tests passing.
Input: --resume-from on a file holding [], such as a questions file in the old bare-list format.
Got: The latest commit refuses it with InputError at line 101 and names the flag.

Suggestion: Add a case that writes [] to the checkpoint path and expects InputError in the refusal tests.

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)
Details

Without the isinstance check, data.get raises AttributeError and the run ends in a traceback, and no changed test passes a list, so nothing fails.

raise InputError(f"--resume-from {path}: expected an arms.v1 checkpoint")
try:
validate_artifact("arms", data)

Check warning on line 104 in dokimi/dokimi/eval/arms_checkpoint.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: delete-statement `validate_artifact("arms", data)` -> `pass`
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):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The 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 is_empty_reply check on line 121 leaves the tests passing.
Input: an interrupted run that saved an arm answer whose text is empty and has no error.
Got: The latest commit counts it as incomplete, so the question is answered again.

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}}
Details

Without 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)
Loading
Loading