Python
core: include task inputs in the reuse identity of a rollout (#76)
zhouh0a40ff88e5c1
diff --git a/harness2/benchmarks/jobbench.py b/harness2/benchmarks/jobbench.pyindex cf3f37d..5647a36 100644--- a/harness2/benchmarks/jobbench.py+++ b/harness2/benchmarks/jobbench.py@@ -726,11 +726,13 @@ class JobBenchAdapter:label = run_id.replace("/", "__")out = self._out_dir(task_id, label)mark = self._traj_dir(task_id, label)- if RM.is_complete(mark, harness_dir=harness_dir) and self.artifacts_intact(out):+ inputs = RM.inputs_fingerprint(self.task_prompt(task_id), self.task_files(task_id))+ reusable = RM.is_complete(mark, harness_dir=harness_dir, inputs=inputs)+ if reusable and self.artifacts_intact(out):out.mkdir(parents=True, exist_ok=True)return outif out.is_dir() or mark.is_dir():- reason = RM.why_not(mark, harness_dir=harness_dir)+ reason = RM.why_not(mark, harness_dir=harness_dir, inputs=inputs)if reason == "reusable":reason = "output fingerprint missing or changed"print(@@ -757,6 +759,7 @@ class JobBenchAdapter:mark,run_id=run_id,harness_dir=harness_dir,+ inputs=inputs,extra={"output_fingerprint": self._output_fingerprint(out)},)return dirs[0]diff --git a/harness2/benchmarks/lab.py b/harness2/benchmarks/lab.pyindex 7ff40a1..86099e9 100644--- a/harness2/benchmarks/lab.py+++ b/harness2/benchmarks/lab.py@@ -606,11 +606,13 @@ class LabAdapter:self, task_id: str, harness_dir: Path | None, run_id: str, *, timeout: int | None = None) -> Path:out = self._run_dir(run_id)- if RM.is_complete(out, harness_dir=harness_dir) and self.artifacts_intact(out):+ inputs = RM.inputs_fingerprint(self.task_prompt(task_id), self.task_files(task_id))+ reusable = RM.is_complete(out, harness_dir=harness_dir, inputs=inputs)+ if reusable and self.artifacts_intact(out):self._check_tool_gate(out)return outif out.is_dir() and any(out.iterdir()):- reason = RM.why_not(out, harness_dir=harness_dir)+ reason = RM.why_not(out, harness_dir=harness_dir, inputs=inputs)if reason == "reusable":reason = "output fingerprint missing or changed"print(@@ -636,6 +638,7 @@ class LabAdapter:out,run_id=run_id,harness_dir=harness_dir,+ inputs=inputs,extra={"output_fingerprint": self._output_fingerprint(out)},)return outdiff --git a/harness2/core/runmark.py b/harness2/core/runmark.pyindex 1de5794..afa1287 100644--- a/harness2/core/runmark.py+++ b/harness2/core/runmark.py@@ -15,8 +15,9 @@"""Trial identity: was this rollout finished, and by this configuration?Completion is recorded explicitly by the code that observed the run return; presence of output-is not enough. The marker also fingerprints the harness that produced the rollout, so a rollout-from a different configuration is never reused.+is not enough. The marker also fingerprints the harness that produced the rollout, and optionally+the task inputs the rollout answered, so a rollout from a different configuration -- or one+answering a task that has since been corrected -- is never reused."""from __future__ import annotations@@ -61,10 +62,48 @@ def fingerprint(harness_dir: Path | None) -> str:return h.hexdigest()[:16]+def inputs_fingerprint(task_prompt: str, files_dir: Path | None) -> str:+ """A stable digest of what the agent was asked and what it was given.++ `task_prompt` is the model-visible task text (adapters already strip the answer key and the+ grading criteria from it, so those never enter the digest); `files_dir` is the source+ material from `BenchmarkAdapter.task_files`, walked in sorted order and hashed by relative+ path plus bytes. An adapter that exposes neither still digests to a stable value, so callers+ need no special case.+ """+ h = hashlib.sha1()+ h.update(b"prompt\0")+ h.update(str(task_prompt).encode())+ h.update(b"\0")+ root = Path(files_dir) if files_dir is not None else None+ if root is not None and root.is_dir():+ for p in sorted(root.rglob("*")):+ if not p.is_file() or _ignored(p):+ continue+ h.update(str(p.relative_to(root)).encode())+ h.update(b"\0")+ try:+ h.update(p.read_bytes())+ except OSError:+ h.update(b"<unreadable>")+ h.update(b"\0")+ return h.hexdigest()[:16]++def mark_complete(- where: Path, *, run_id: str, harness_dir: Path | None = None, extra: dict | None = None+ where: Path,+ *,+ run_id: str,+ harness_dir: Path | None = None,+ inputs: str | None = None,+ extra: dict | None = None,) -> Path:- """Record that `run_id` finished. Call only after the runner returned normally."""+ """Record that `run_id` finished. Call only after the runner returned normally.++ `inputs` is `inputs_fingerprint` for the task this rollout answered, or `None` when the+ adapter does not expose task inputs; it is omitted from the marker rather than written as+ null so markers keep their previous shape for such adapters.+ """d = Path(where)d.mkdir(parents=True, exist_ok=True)payload = {@@ -74,6 +113,8 @@ def mark_complete("harness": fingerprint(harness_dir),**(extra or {}),}+ if inputs is not None:+ payload["inputs"] = inputstmp = d / f"{MARK}.{os.getpid()}.tmp"tmp.write_text(json.dumps(payload, indent=2, sort_keys=True))final = d / MARK@@ -89,26 +130,47 @@ def read_mark(where: Path) -> dict | None:def is_complete(- where: Path, *, harness_dir: Path | None = None, match_harness: bool = True+ where: Path,+ *,+ harness_dir: Path | None = None,+ match_harness: bool = True,+ inputs: str | None = None,) -> bool:"""Whether the artifacts at `where` may be reused: a current marker naming the same- harness, unless `match_harness` is off.+ harness and the same task inputs, unless either comparison is off.++ `inputs=None` keeps the previous behaviour of not comparing task inputs, and a marker+ written before input identity existed (no `inputs` key) stays reusable: rewriting identity+ for every in-flight run is a bigger decision than this check is worth."""m = read_mark(where)if not m or m.get("version") != VERSION:return False+ if inputs is not None and not _inputs_match(m, inputs):+ return Falseif not match_harness:return Truereturn m.get("harness") == fingerprint(harness_dir)-def why_not(where: Path, *, harness_dir: Path | None = None) -> str:+def _inputs_match(m: dict, inputs: str | None) -> bool:+ """Legacy markers carry no input identity and are not invalidated by its arrival."""+ recorded = m.get("inputs")+ return recorded is None or inputs is None or recorded == inputs+++def why_not(where: Path, *, harness_dir: Path | None = None, inputs: str | None = None) -> str:"""A sentence for a log line explaining why `where` is or is not reusable."""m = read_mark(where)if not m:return f"no {MARK} -- never finished, or finished before completion was recorded"if m.get("version") != VERSION:return f"marker version {m.get('version')} != {VERSION}"+ if not _inputs_match(m, inputs):+ return (+ f"task inputs {m.get('inputs')} != {inputs} -- the task prompt or its source "+ f"files changed since this rollout finished"+ )want, got = fingerprint(harness_dir), m.get("harness")if want != got:return f"harness fingerprint {got} != {want} -- produced by a different configuration"diff --git a/harness2/core/schedule.py b/harness2/core/schedule.pyindex 176f6e8..7183c0e 100644--- a/harness2/core/schedule.py+++ b/harness2/core/schedule.py@@ -243,6 +243,7 @@ class TaskResult:k: intseed: int | None = Nonestatus: str = "running"+ inputs: str | None = Nonemodes: dict = field(default_factory=dict)selections: dict = field(default_factory=dict)base: list[str] = field(default_factory=list)@@ -255,6 +256,7 @@ class TaskResult:"k": self.k,"seed": self.seed,"status": self.status,+ "inputs": self.inputs,"base": self.base,"modes": self.modes,"selections": self.selections,@@ -262,6 +264,21 @@ class TaskResult:}+def _task_inputs(adapter: BenchmarkAdapter, task_id: str) -> str | None:+ """The task's own identity: its model-visible prompt plus its source material.++ `None` when the adapter cannot supply them, which keeps the summary check off rather than+ turning a missing task into a spurious invalidation.+ """+ try:+ prompt = adapter.task_prompt(task_id)+ files = getattr(adapter, "task_files", None)+ files_dir = files(task_id) if callable(files) else None+ except (OSError, RuntimeError, ValueError):+ return None+ return runmark.inputs_fingerprint(prompt, files_dir)++def _merged_status(merged: dict) -> str:"""ok iff every mode record on the merged summary succeeded and no error is recorded."""modes = merged.get("modes") or {}@@ -300,27 +317,40 @@ def _write_summary(summary_path: Path, res: TaskResult) -> None:merged = res.to_dict()if summary_path.is_file():old = _load_old(summary_path)- for key in ("modes", "selections"):- prev = _modes_of(old) if key == "modes" else dict(old.get(key) or {})- prev.update(merged.get(key) or {})- merged[key] = prev-- merged["errors"] = list(merged.get("errors") or [])- seen = {json.dumps(e, sort_keys=True, default=str) for e in merged["errors"]}- for e in old.get("errors") or []:- if e == "no base rollout produced anything" and res.status in ("ok", "partial"):- continue- mode = str(e).partition(":")[0]- if (- (res.modes.get(mode) or {}).get("ok")- and (res.selections.get(mode) or {}).get("ok")- and (res.selections.get(mode) or {}).get("chosen_label")- ):- continue- if json.dumps(e, sort_keys=True, default=str) not in seen:- merged["errors"].append(e)- if merged.get("status") in ("ok", "partial"):- merged["status"] = _merged_status(merged)+ inputs_changed = (+ res.inputs is not None+ and old.get("inputs") is not None+ and old.get("inputs") != res.inputs+ )+ if not inputs_changed:+ for key in ("modes", "selections"):+ prev = _modes_of(old) if key == "modes" else dict(old.get(key) or {})+ prev.update(merged.get(key) or {})+ merged[key] = prev++ merged["errors"] = list(merged.get("errors") or [])+ seen = {json.dumps(e, sort_keys=True, default=str) for e in merged["errors"]}+ for e in old.get("errors") or []:+ if e == "no base rollout produced anything" and res.status in (+ "ok",+ "partial",+ ):+ continue+ mode = str(e).partition(":")[0]+ if (+ (res.modes.get(mode) or {}).get("ok")+ and (res.selections.get(mode) or {}).get("ok")+ and (res.selections.get(mode) or {}).get("chosen_label")+ ):+ continue+ if json.dumps(e, sort_keys=True, default=str) not in seen:+ merged["errors"].append(e)+ if merged.get("status") in ("ok", "partial"):+ merged["status"] = _merged_status(merged)+ # else: the previous summary answered a different question. Its mode+ # records and selections were derived from the old inputs and must not+ # be re-used under the new digest, otherwise a later run would skip+ # recomputation for results that are already stale.tmp = summary_path.with_suffix(".json.tmp")tmp.write_text(json.dumps(merged, indent=2, default=str))os.replace(tmp, summary_path)@@ -359,7 +389,12 @@ def _resume(mode_libs: dict[str, library_store.Library],res: TaskResult,) -> bool:- """Fill `res` from a cached summary covering every requested mode; True if it did."""+ """Fill `res` from a cached summary covering every requested mode; True if it did.++ The summary only stands for this task while the task itself is unchanged: a corrected+ instruction or a refreshed data room under the same task id makes the cached selections+ answers to a different question, so they are re-derived rather than reported as complete.+ """try:got = json.loads(summary_path.read_text())except (OSError, json.JSONDecodeError) as exc:@@ -370,6 +405,14 @@ def _resume(return Falseif got.get("status") not in ("ok", "partial"):return False+ recorded_inputs = got.get("inputs")+ if recorded_inputs is not None and res.inputs is not None and recorded_inputs != res.inputs:+ print(+ f" [{task_id}] task inputs {recorded_inputs} != {res.inputs} -- the task prompt "+ f"or its source files changed since this summary was written; re-running",+ flush=True,+ )+ return Falsecached_modes = _modes_of(got)cached_sels = got.get("selections") or {}missing = sorted(@@ -612,6 +655,7 @@ def run_task(work = base_ns.task_dir(runs_root, task_id)work.mkdir(parents=True, exist_ok=True)summary_path = work / "summary.json"+ res.inputs = _task_inputs(adapter, task_id)if summary_path.is_file() and _resume(summary_path, task_id, k, adapter, runs_root, modes, seed, tag, mode_libs, resdiff --git a/tests/test_task_input_identity.py b/tests/test_task_input_identity.pynew file mode 100644index 0000000..a1c1d07--- /dev/null+++ b/tests/test_task_input_identity.py@@ -0,0 +1,298 @@+# Copyright 2026 Google LLC+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# https://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.++"""Task inputs are part of a rollout's identity, at both cache layers.++A rollout answers the task it was given. When the instruction or the source material changes+under the same task id, the saved answer is no longer an answer to the current question, so+neither the task summary nor the rollout marker may be reused.+"""++import io+import json+import tempfile+import unittest+from contextlib import redirect_stdout+from pathlib import Path+from unittest.mock import patch++from harness2 import config+from harness2.benchmarks.lab import LabAdapter+from harness2.core import runmark, schedule+++class _FakeAdapter:+ """The two adapter methods the task-input identity reads, and nothing else."""++ def __init__(self, prompt: str, files: Path | None):+ self._prompt = prompt+ self._files = files++ def task_prompt(self, task_id: str) -> str:+ return self._prompt++ def task_files(self, task_id: str) -> Path | None:+ return self._files+++class InputsFingerprintTests(unittest.TestCase):+ def setUp(self):+ temporary = tempfile.TemporaryDirectory()+ self.addCleanup(temporary.cleanup)+ self.root = Path(temporary.name)+ self.files = self.root / "documents"+ self.files.mkdir()+ (self.files / "source.txt").write_text("version-one")++ def test_digest_is_stable_for_unchanged_inputs(self):+ first = runmark.inputs_fingerprint("Use version one.", self.files)+ second = runmark.inputs_fingerprint("Use version one.", self.files)+ self.assertEqual(first, second)++ def test_digest_follows_the_prompt(self):+ before = runmark.inputs_fingerprint("Use version one.", self.files)+ after = runmark.inputs_fingerprint("Use version two.", self.files)+ self.assertNotEqual(before, after)++ def test_digest_follows_file_contents_and_membership(self):+ before = runmark.inputs_fingerprint("Use version one.", self.files)+ (self.files / "source.txt").write_text("version-two")+ changed = runmark.inputs_fingerprint("Use version one.", self.files)+ self.assertNotEqual(before, changed)+ (self.files / "extra.txt").write_text("more")+ added = runmark.inputs_fingerprint("Use version one.", self.files)+ self.assertNotEqual(changed, added)++ def test_digest_ignores_byproducts_and_missing_material(self):+ before = runmark.inputs_fingerprint("Use version one.", self.files)+ (self.files / "__pycache__").mkdir()+ (self.files / "__pycache__" / "stale.pyc").write_bytes(b"\x00")+ self.assertEqual(before, runmark.inputs_fingerprint("Use version one.", self.files))+ self.assertEqual(+ runmark.inputs_fingerprint("Use version one.", None),+ runmark.inputs_fingerprint("Use version one.", self.root / "absent"),+ )+++class MarkerInputTests(unittest.TestCase):+ def setUp(self):+ temporary = tempfile.TemporaryDirectory()+ self.addCleanup(temporary.cleanup)+ self.run_dir = Path(temporary.name) / "run"++ def test_marker_refuses_reuse_under_changed_inputs(self):+ runmark.mark_complete(self.run_dir, run_id="r1", inputs="aaaa")+ self.assertTrue(runmark.is_complete(self.run_dir, inputs="aaaa"))+ self.assertFalse(runmark.is_complete(self.run_dir, inputs="bbbb"))+ self.assertEqual(runmark.why_not(self.run_dir, inputs="aaaa"), "reusable")+ self.assertIn("task inputs aaaa != bbbb", runmark.why_not(self.run_dir, inputs="bbbb"))++ def test_marker_without_inputs_stays_reusable(self):+ """Markers written before input identity existed must not invalidate on upgrade."""+ runmark.mark_complete(self.run_dir, run_id="r1")+ marker = json.loads((self.run_dir / runmark.MARK).read_text())+ self.assertNotIn("inputs", marker)+ self.assertTrue(runmark.is_complete(self.run_dir, inputs="aaaa"))+ self.assertEqual(runmark.why_not(self.run_dir, inputs="aaaa"), "reusable")++ def test_caller_without_inputs_keeps_previous_behaviour(self):+ runmark.mark_complete(self.run_dir, run_id="r1", inputs="aaaa")+ self.assertTrue(runmark.is_complete(self.run_dir))+ self.assertEqual(runmark.why_not(self.run_dir), "reusable")+++class SummaryInputTests(unittest.TestCase):+ def setUp(self):+ temporary = tempfile.TemporaryDirectory()+ self.addCleanup(temporary.cleanup)+ self.root = Path(temporary.name)+ self.files = self.root / "documents"+ self.files.mkdir()+ (self.files / "ledger.csv").write_text("amount\n1.00\n")+ self.summary = self.root / "summary.json"+ self.res = schedule.TaskResult(task_id="task-1", domain="d", k=1)++ def _write_summary(self, adapter):+ self.summary.write_text(+ json.dumps(+ {+ "task_id": "task-1",+ "domain": "d",+ "k": 1,+ "status": "ok",+ "inputs": schedule._task_inputs(adapter, "task-1"),+ "modes": {"agg": {"ok": True}},+ "selections": {"agg": {"ok": True, "chosen_label": "c1"}},+ }+ )+ )++ def _resume(self, adapter):+ self.res.inputs = schedule._task_inputs(adapter, "task-1")+ out = io.StringIO()+ with redirect_stdout(out):+ resumed = schedule._resume(+ self.summary,+ "task-1",+ 1,+ adapter,+ self.root,+ ("agg",),+ None,+ "",+ {},+ self.res,+ )+ return resumed, out.getvalue()++ def test_changed_source_files_are_not_resumed(self):+ adapter = _FakeAdapter("Sum ledger.csv.", self.files)+ self._write_summary(adapter)+ (self.files / "ledger.csv").write_text("amount\n1.00\n2.00\n")+ resumed, printed = self._resume(adapter)+ self.assertFalse(resumed)+ self.assertIn("changed since this summary was written", printed)++ def test_changed_prompt_is_not_resumed(self):+ adapter = _FakeAdapter("Sum ledger.csv.", self.files)+ self._write_summary(adapter)+ resumed, printed = self._resume(_FakeAdapter("Sum ledger.csv twice.", self.files))+ self.assertFalse(resumed)+ self.assertIn("task inputs", printed)++ def test_summary_without_inputs_is_not_invalidated(self):+ """A summary written before input identity existed keeps its previous meaning."""+ adapter = _FakeAdapter("Sum ledger.csv.", self.files)+ self.summary.write_text(json.dumps({"status": "ok"}))+ resumed, printed = self._resume(adapter)+ self.assertFalse(resumed)+ self.assertNotIn("task inputs", printed)++ def test_write_summary_drops_modes_from_an_older_input_identity(self):+ """Modes recorded under a previous input digest must not survive a re-run.++ `_write_summary` merges per-mode records across processes, but a mode computed+ from the old inputs is an answer to a different question. Carrying it over under+ the new digest would let a later run skip recomputation for a stale result.+ """+ adapter = _FakeAdapter("Sum ledger.csv.", self.files)+ self.summary.write_text(+ json.dumps(+ {+ "task_id": "task-1",+ "domain": "d",+ "k": 1,+ "status": "ok",+ "inputs": schedule._task_inputs(adapter, "task-1"),+ "modes": {"agg": {"ok": True}, "seq": {"ok": True}},+ "selections": {+ "agg": {"ok": True, "chosen_label": "c1"},+ "seq": {"ok": True, "chosen_label": "c1"},+ },+ }+ )+ )++ # The task changes; only `agg` is re-run and written back.+ (self.files / "ledger.csv").write_text("amount\n1.00\n2.00\n")+ res = schedule.TaskResult(task_id="task-1", domain="d", k=1)+ res.inputs = schedule._task_inputs(adapter, "task-1")+ res.status = "ok"+ res.modes["agg"] = {"ok": True}+ res.selections["agg"] = {"ok": True, "chosen_label": "c2"}+ schedule._write_summary(self.summary, res)++ merged = json.loads(self.summary.read_text())+ self.assertEqual(merged["inputs"], res.inputs)+ self.assertIn("agg", merged["modes"])+ self.assertNotIn("seq", merged["modes"])+ self.assertNotIn("seq", merged["selections"])+++class RolloutReuseTests(unittest.TestCase):+ """The reported symptom, end to end through `LabAdapter.execute`.++ The executor is replaced by a deterministic function that writes the current document into+ the run directory: no model call, no downloaded benchmark, no shell.+ """++ task_id = "example/task-1"+ run_id = "lab-cx-agg1/example__task-1/base1"++ def setUp(self):+ temporary = tempfile.TemporaryDirectory()+ self.addCleanup(temporary.cleanup)+ self.root = Path(temporary.name)+ self.lab = self.root / "lab"+ self.task = self.lab / "tasks" / self.task_id+ (self.task / "documents").mkdir(parents=True)+ self.task_json = self.task / "task.json"+ self.document = self.task / "documents" / "source.txt"+ self.task_json.write_text(json.dumps({"instructions": "Use version one."}))+ self.document.write_text("version-one")++ def _adapter(self):+ runs = patch.object(config, "RUNS", self.root / "runs")+ lab_repo = patch.object(config, "lab_repo", return_value=self.lab)+ runs.start()+ lab_repo.start()+ self.addCleanup(runs.stop)+ self.addCleanup(lab_repo.stop)+ return LabAdapter(substrate="cx")++ def _runner(self, adapter):+ def runner(task_id, install, run_ids, timeout):+ out = adapter._run_dir(run_ids[0])+ (out / "output").mkdir(parents=True, exist_ok=True)+ (out / "output" / "answer.txt").write_text(self.document.read_text())+ (out / "metrics.json").write_text("{}")+ return [out]++ return runner++ def _answer(self, run_dir):+ return (Path(run_dir) / "output" / "answer.txt").read_text()++ def test_unchanged_inputs_reuse_the_rollout(self):+ adapter = self._adapter()+ with patch.object(adapter.substrate, "execute", side_effect=self._runner(adapter)) as execs:+ first = adapter.execute(self.task_id, None, self.run_id)+ second = adapter.execute(self.task_id, None, self.run_id)+ self.assertEqual(execs.call_count, 1)+ self.assertEqual(self._answer(first), "version-one")+ self.assertEqual(Path(second), Path(first))++ def test_changed_source_files_re_roll_the_rollout(self):+ adapter = self._adapter()+ with patch.object(adapter.substrate, "execute", side_effect=self._runner(adapter)) as execs:+ adapter.execute(self.task_id, None, self.run_id)+ self.document.write_text("version-two")+ out = adapter.execute(self.task_id, None, self.run_id)+ self.assertEqual(execs.call_count, 2)+ self.assertEqual(self._answer(out), "version-two")++ def test_changed_instructions_re_roll_the_rollout(self):+ adapter = self._adapter()+ with patch.object(adapter.substrate, "execute", side_effect=self._runner(adapter)) as execs:+ adapter.execute(self.task_id, None, self.run_id)+ self.task_json.write_text(json.dumps({"instructions": "Use version two."}))+ out = adapter.execute(self.task_id, None, self.run_id)+ self.assertEqual(execs.call_count, 2)+ self.assertIn("version two", adapter.task_prompt(self.task_id))+ # The source material is unchanged, so the fresh answer still matches it.+ self.assertEqual(self._answer(out), "version-one")+++if __name__ == "__main__":+ unittest.main()