From 2948e04e53e1ac46af508d65b26a7cc764b0f601 Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Fri, 20 Nov 2026 22:17:45 -0800 Subject: [PATCH 01/10] fix(nemo-gym): score multi-step episodes and keep step evidence A NeMo Gym run of a native multi-step task reported every attempt as "SkillEvaluator verifier did not run in the NeMo Gym sandbox", even when each step's verifier ran and wrote its rewards. Gym reports each step on `turns` and leaves the top-level verifier fields unset, and the adapter only read the top level. The adapter now copies each step's verifier files and trajectory to steps//, lists the steps in order as step_results, and rolls up the attempt's reward with the task's strategy: the last step's rewards for final, or each key's mean over the steps that ran for mean, with a key a step did not report counted as 0. The shared collector then scores the attempt once and merges the step trajectories, as it does for Harbor. An attempt stays unscored, with its step evidence kept, when a step was masked, failed or has no verifier result, when Gym marked the episode failed, or when the turns, strategy or stop point are malformed. Gym's mean would count an ungraded step as 0 and Harbor's would leave it out, so neither result is presented as a score. An episode that stopped early because a step missed its min_reward is scored over the steps that ran, as on Harbor. Single-step rollouts keep their current layout. Refs #846 Signed-off-by: Deepak Jain --- CHANGELOG.md | 5 + docs/nemo-gym.mdx | 14 + src/skillevaluator/tier3/nemo_gym/results.py | 154 +++++++-- tests/tier3/test_gym_multi_step_results.py | 337 +++++++++++++++++++ 4 files changed, 491 insertions(+), 19 deletions(-) create mode 100644 tests/tier3/test_gym_multi_step_results.py diff --git a/CHANGELOG.md b/CHANGELOG.md index f3a2e9ee0..ae9f0cddd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -199,6 +199,11 @@ notes below describe the new policy and backend configuration behavior. ### Fixed +- NeMo Gym runs of native multi-step tasks are scored instead of failing with + "SkillEvaluator verifier did not run in the NeMo Gym sandbox". Each step's + rewards, verifier files and trajectory are kept in order, and the attempt is + scored once by the task's `mean` or `final` strategy. An attempt with a masked, + failed or ungraded step stays unscored and names that step. - Bound declarative output-pattern checks with isolated Python regex workers and a shared matching budget, preserving Python regex semantics and later checks. Interpreter startup and JSON transfer have a separate startup allowance and do not consume diff --git a/docs/nemo-gym.mdx b/docs/nemo-gym.mdx index 2178e8290..5e549faa9 100644 --- a/docs/nemo-gym.mdx +++ b/docs/nemo-gym.mdx @@ -239,6 +239,20 @@ Its help must describe a standalone positional `TARGET`, `tasks`, `task_dir`, be collected. The Gym implementation must execute inside Docker and resolve task environment templates; a host-only agent harness does not meet this contract. +A native multi-step task reports its steps in order in `turns`, each with its own +`verifier_return_code` and `verifier_logs_dir`; Gym leaves the top-level pair unset. +SkillEvaluator keeps each step's rewards, verifier files and trajectory under the step's +name, as for a Harbor multi-step trial, and scores the attempt once by the task's +`multi_step_reward_strategy` as Gym reports it in `turn_reward_strategy`: `final` takes +the last step's rewards, and `mean` averages each reward key over the steps that ran, +counting a key a step did not report as 0. The attempt is unscored when a step was masked, +failed, or produced no verifier result, when Gym marked the episode failed, or when the +strategy is missing or unsupported. For a step with no verifier result, Gym's own `mean` +counts it as 0 and Harbor leaves it out; SkillEvaluator does neither, so a step the +verifier never graded is never part of a score. An episode Gym stopped after a step +missed its `min_reward` is scored over the steps that ran, as on Harbor. Tests cover this +with source-shaped Gym rollouts; a live multi-step Gym run has not been recorded yet. + diff --git a/src/skillevaluator/tier3/nemo_gym/results.py b/src/skillevaluator/tier3/nemo_gym/results.py index 3225f1e9a..8b61be68f 100644 --- a/src/skillevaluator/tier3/nemo_gym/results.py +++ b/src/skillevaluator/tier3/nemo_gym/results.py @@ -6,6 +6,11 @@ becomes one trial holding the verifier files Gym downloaded from ``/logs/verifier`` and the ATIF trajectory Gym wrote for the verifier, so scoring, lift, pass@k and reports stay backend-neutral. + +A multi-step episode reports each step on its ordered ``turns`` and leaves the +top-level verifier fields unset. It becomes Harbor's multi-step trial layout: +``step_results`` with one ``steps//`` folder per step, and a root reward +rolled up from the step reward files by Gym's ``turn_reward_strategy``. """ from __future__ import annotations @@ -15,12 +20,15 @@ import math import re import shutil +import unicodedata from collections import defaultdict from pathlib import Path from typing import Any _UNSAFE = re.compile(r"[^A-Za-z0-9._-]+") _VERIFIER_FILES = ("reward.json", "reward.txt", "skill_evaluator_reward.json", "custom_reward.json", "test-stdout.txt") +_TURN_REWARD_STRATEGIES = ("mean", "final") +_TURN_METADATA = ("turn_sessions", "turn_reward_strategy", "stopped_after_turn", "turns_without_verifier_result") def _safe(value: str) -> str: @@ -112,6 +120,13 @@ def rollout_failure_text(row: dict[str, Any]) -> str: def _failure_text(row: dict[str, Any]) -> str: + failure = _reported_failure_text(row) + if not failure and row.get("verifier_return_code") is None: + return "SkillEvaluator verifier did not run in the NeMo Gym sandbox" + return failure + + +def _reported_failure_text(row: dict[str, Any]) -> str: failure = row.get("failure") or row.get("failure_reason") or row.get("failure_kind") if isinstance(failure, dict): return str(failure.get("message") or failure.get("failure_kind") or "NeMo Gym episode failed") @@ -119,11 +134,118 @@ def _failure_text(row: dict[str, Any]) -> str: return str(failure) if row.get("mask_sample"): return "NeMo Gym masked the sample (Gym-side failure)" - if row.get("verifier_return_code") is None: - return "SkillEvaluator verifier did not run in the NeMo Gym sandbox" return "" +def _verified_rewards(verifier_dir: Path, case_id: str) -> tuple[dict[str, Any] | None, str]: + """Return the verifier's rewards stamped with ``case_id``, or why they cannot be scored.""" + loaded = read_verifier_rewards(verifier_dir) + if loaded is None: + return None, "the task verifier wrote no reward.json or numeric reward.txt" + loaded_entry_id = loaded.get("entry_id") + if loaded_entry_id is not None and str(loaded_entry_id) != str(case_id): + return None, f"the task verifier reported case {str(loaded_entry_id)!r} for staged case {str(case_id)!r}" + rewards = {**loaded, "entry_id": case_id} + reward_path = verifier_dir / "reward.json" + if reward_path.is_file(): + reward_path.write_text(json.dumps(rewards, indent=2), encoding="utf-8") + return rewards, "" + + +def _turn_names(turns: Any) -> list[str] | None: + """Return the turns' step names when each can be its own ``steps//`` folder, else ``None``.""" + from skillevaluator.tier3.harbor.collector import _safe_trial_path_component + + if not isinstance(turns, list) or not turns: + return None + names: list[str] = [] + keys: set[str] = set() + for turn in turns: + name = turn.get("name") if isinstance(turn, dict) else None + if not isinstance(name, str) or _safe_trial_path_component(name) != name: + return None + # Case-insensitive file systems would otherwise merge two steps' evidence into one folder. + key = unicodedata.normalize("NFC", name).casefold() + if key in keys: + return None + names.append(name) + keys.add(key) + return names + + +def _reward_number(value: Any) -> float | None: + return float(value) if isinstance(value, int | float) and not isinstance(value, bool) else None + + +def _rolled_up_rewards(step_rewards: list[dict[str, Any]], strategy: str, case_id: str) -> dict[str, Any]: + """Roll up the steps that ran as Harbor does: the last step's rewards, or each key's mean, a missing key as 0.""" + if strategy == "final": + return dict(step_rewards[-1]) + keys = sorted( + {key for rewards in step_rewards for key, value in rewards.items() if _reward_number(value) is not None} + ) + means = { + key: sum(_reward_number(rewards.get(key)) or 0.0 for rewards in step_rewards) / len(step_rewards) + for key in keys + } + return {**means, "entry_id": case_id} + + +def _multi_step_outcome( + row: dict[str, Any], trial_dir: Path, case_id: str +) -> tuple[dict[str, Any] | None, str, dict[str, Any]]: + """Write a multi-step episode's steps and return its rewards, why it is unscored, and its result fields. + + Every step must have run its verifier and written rewards for the episode to be scored. A masked or + failed step, a step without a verifier result, or an episode Gym marked failed leaves the attempt + unscored, keeping each step's evidence. Gym's ``mean`` counts a step without a verifier result as 0 and + Harbor's leaves it out; the adapter applies neither, so an ungraded step never becomes a score. An + episode that stopped after a step missed its ``min_reward`` is scored over the steps that ran, as on Harbor. + """ + turns = row.get("turns") + fields: dict[str, Any] = {"nemo_gym": {key: row.get(key) for key in _TURN_METADATA}} + names = _turn_names(turns) + if names is None: + return None, "NeMo Gym returned malformed multi-step turns", fields + fields["config"] = {"agent": {"resume_trajectory": row.get("turn_sessions") == "continue"}} + step_results: list[dict[str, Any]] = [] + step_rewards: list[dict[str, Any]] = [] + failure = "" + for name, turn in zip(names, turns, strict=True): + step_dir = trial_dir / "steps" / name + logs_dir = turn.get("verifier_logs_dir") + if isinstance(logs_dir, str) and Path(logs_dir).is_dir(): + _copy_verifier_logs(Path(logs_dir), step_dir) + rewards = None + step_failure = _failure_text(turn) + if not step_failure: + rewards, step_failure = _verified_rewards(step_dir / "verifier", case_id) + step_results.append( + { + "step_name": name, + "verifier_result": {"rewards": rewards} if rewards else None, + "exception_info": {"exception_type": "NeMoGymStepFailure", "exception_message": step_failure} + if step_failure + else None, + } + ) + if rewards is not None: + step_rewards.append(rewards) + elif not failure: + failure = f"step {name!r}: {step_failure}" + fields["step_results"] = step_results + strategy = row.get("turn_reward_strategy") + stopped_after = row.get("stopped_after_turn") + failure = failure or _reported_failure_text(row) + if not failure and strategy not in _TURN_REWARD_STRATEGIES: + failure = f"NeMo Gym reported an unsupported turn_reward_strategy {strategy!r}" + if not failure and stopped_after is not None and stopped_after != names[-1]: + failure = f"NeMo Gym stopped after turn {stopped_after!r}, which is not its last turn" + if failure: + return None, failure, fields + return _rolled_up_rewards(step_rewards, strategy, case_id), "", fields + + def _copy_verifier_logs(logs_dir: Path, trial_dir: Path) -> None: verifier_dir = trial_dir / "verifier" verifier_dir.mkdir(parents=True, exist_ok=True) @@ -183,25 +305,18 @@ def write_job_from_rollouts( trial_name = f"{_safe(task_name)}__gym{attempt:03d}" trial_dir = job_dir / trial_name trial_dir.mkdir(parents=True, exist_ok=True) - logs_dir = row.get("verifier_logs_dir") - if isinstance(logs_dir, str) and Path(logs_dir).is_dir(): - _copy_verifier_logs(Path(logs_dir), trial_dir) - reward_path = trial_dir / "verifier" / "reward.json" - failure = _failure_text(row) rewards: dict[str, Any] | None = None - loaded = None if failure else read_verifier_rewards(trial_dir / "verifier") - if loaded is not None: - loaded_entry_id = loaded.get("entry_id") - if loaded_entry_id is not None and str(loaded_entry_id) != str(case_id): - failure = ( - f"the task verifier reported case {str(loaded_entry_id)!r} for staged case {str(case_id)!r}" - ) - else: - rewards = {**loaded, "entry_id": case_id} - if reward_path.is_file(): - reward_path.write_text(json.dumps(rewards, indent=2), encoding="utf-8") + step_fields: dict[str, Any] = {} + if row.get("turns") is not None: + rewards, failure, step_fields = _multi_step_outcome(row, trial_dir, case_id) + else: + logs_dir = row.get("verifier_logs_dir") + if isinstance(logs_dir, str) and Path(logs_dir).is_dir(): + _copy_verifier_logs(Path(logs_dir), trial_dir) + failure = _failure_text(row) + if not failure: + rewards, failure = _verified_rewards(trial_dir / "verifier", case_id) if rewards is None: - failure = failure or "the task verifier wrote no reward.json or numeric reward.txt" n_errors += 1 if not row.get(_MISSING_ROLLOUT): errors.append(f"case {case_id} attempt {attempt}: {failure}") @@ -220,6 +335,7 @@ def write_job_from_rollouts( "exception_info": None if rewards else {"exception_type": "NeMoGymEpisodeFailure", "exception_message": failure}, + **step_fields, }, indent=2, ), diff --git a/tests/tier3/test_gym_multi_step_results.py b/tests/tier3/test_gym_multi_step_results.py new file mode 100644 index 000000000..a161c28ce --- /dev/null +++ b/tests/tier3/test_gym_multi_step_results.py @@ -0,0 +1,337 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""A multi-step NeMo Gym episode keeps its ordered steps and is scored by its declared strategy. + +Gym records each step's verifier code, logs and rewards on ``turns[]`` and leaves the +top-level verifier fields unset, so the adapter writes Harbor's multi-step trial layout +(``step_results`` plus ``steps//``) for the shared collector instead. +""" + +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any + +import pytest + +from skillevaluator.tier3.harbor.collector import collect_harbor_results +from skillevaluator.tier3.nemo_gym.results import write_job_from_rollouts + +CASES = {"case-1": "case-1"} + + +def _trajectory(name: str) -> dict[str, Any]: + return { + "schema_version": "ATIF-v1.7", + "session_id": f"session-{name}", + "trajectory_id": f"trajectory-{name}", + "agent": {"name": "codex", "version": "1"}, + "steps": [{"step_id": 1, "source": "agent", "message": name}], + "final_metrics": {"total_prompt_tokens": 10, "total_completion_tokens": 2}, + } + + +def _turn(base: Path, name: str, score: float | None, **fields: Any) -> dict[str, Any]: + logs = base / "gym-logs" / name + logs.mkdir(parents=True) + rewards = None if score is None else {"overall": score, "correctness": score} + if rewards is not None: + (logs / "reward.json").write_text(json.dumps(rewards), encoding="utf-8") + (logs / "skill_evaluator_reward.json").write_text(json.dumps(rewards), encoding="utf-8") + (logs / "trajectory.json").write_text(json.dumps(_trajectory(name)), encoding="utf-8") + turn = { + "name": name, + "reward": score or 0.0, + "mask_sample": False, + "verifier_rewards": rewards, + "verifier_return_code": None if score is None else 0, + "verifier_logs_dir": str(logs), + } + return turn | fields + + +def _episode(turns: list[dict[str, Any]], *, task: str = "case-1", **fields: Any) -> dict[str, Any]: + row = { + "_ng_task_id": {"taskset": "t", "task_id": task}, + "episode_id": {"rollout_id": "r1", "attempt": 0}, + "reward": 99.0, + "mask_sample": False, + "verifier_return_code": None, + "verifier_logs_dir": None, + "turns": turns, + "turn_sessions": "fresh", + "turn_reward_strategy": "mean", + "turns_without_verifier_result": sum(1 for turn in turns if turn.get("verifier_rewards") is None), + "stopped_after_turn": None, + } + return row | fields + + +def _write(rows: list[dict[str, Any]], job_dir: Path, cases: dict[str, str] = CASES) -> list[str]: + return write_job_from_rollouts(rows, job_dir, eval_name="codex__m", task_case_ids=cases, n_attempts=1) + + +@pytest.mark.parametrize(("strategy", "expected"), [("mean", 0.625), ("final", 1.0)]) +def test_successful_turns_become_ordered_step_results(tmp_path: Path, strategy: str, expected: float) -> None: + job_dir = tmp_path / "job" + row = _episode([_turn(tmp_path, "first", 0.25), _turn(tmp_path, "second", 1.0)], turn_reward_strategy=strategy) + + assert _write([row], job_dir) == [] + + trial = job_dir / "case-1__gym001" + result = json.loads((trial / "result.json").read_text(encoding="utf-8")) + assert result["exception_info"] is None + assert result["verifier_result"]["rewards"] == {"overall": expected, "correctness": expected, "entry_id": "case-1"} + assert [step["step_name"] for step in result["step_results"]] == ["first", "second"] + assert [step["verifier_result"]["rewards"]["overall"] for step in result["step_results"]] == [0.25, 1.0] + assert all(step["exception_info"] is None for step in result["step_results"]) + assert result["config"] == {"agent": {"resume_trajectory": False}} + assert result["nemo_gym"] == { + "turn_sessions": "fresh", + "turn_reward_strategy": strategy, + "stopped_after_turn": None, + "turns_without_verifier_result": 0, + } + for name, score in (("first", 0.25), ("second", 1.0)): + step = trial / "steps" / name + assert json.loads((step / "verifier" / "reward.json").read_text(encoding="utf-8"))["overall"] == score + assert (step / "verifier" / "skill_evaluator_reward.json").is_file() + assert ( + json.loads((step / "agent" / "trajectory.json").read_text(encoding="utf-8"))["steps"][0]["message"] == name + ) + # The last step's evidence never stands in for the episode's. + assert not (trial / "verifier").exists() + assert not (trial / "agent").exists() + job = json.loads((job_dir / "result.json").read_text(encoding="utf-8")) + assert job["stats"]["n_errors"] == 0 + assert job["stats"]["evals"]["codex__m"]["reward_stats"]["reward"] == {str(expected): ["case-1__gym001"]} + + +def test_issue_reproduction_with_reward_only_files_is_scored(tmp_path: Path) -> None: + turns = [] + for name, score in (("first", 0.25), ("second", 1.0)): + logs = tmp_path / name + logs.mkdir() + (logs / "reward.json").write_text(json.dumps({"reward": score}), encoding="utf-8") + turns.append( + { + "name": name, + "reward": score, + "mask_sample": False, + "verifier_rewards": {"reward": score}, + "verifier_return_code": 0, + "verifier_logs_dir": str(logs), + } + ) + row = _episode(turns, task_id={"task_id": "case-1"}, reward=0.625, verifier_rewards={"reward": 0.625}) + del row["_ng_task_id"] + + assert _write([row], tmp_path / "job") == [] + + result = json.loads((tmp_path / "job" / "case-1__gym001" / "result.json").read_text(encoding="utf-8")) + assert result["verifier_result"]["rewards"] == {"reward": 0.625, "entry_id": "case-1"} + assert len(result["step_results"]) == 2 + + +def test_continued_sessions_merge_step_trajectories_as_resumed(tmp_path: Path) -> None: + row = _episode([_turn(tmp_path, "first", 1.0), _turn(tmp_path, "second", 1.0)], turn_sessions="continue") + + assert _write([row], tmp_path / "job") == [] + + result = json.loads((tmp_path / "job" / "case-1__gym001" / "result.json").read_text(encoding="utf-8")) + assert result["config"] == {"agent": {"resume_trajectory": True}} + assert result["nemo_gym"]["turn_sessions"] == "continue" + + +def test_a_missed_min_reward_is_scored_over_the_steps_that_ran(tmp_path: Path) -> None: + row = _episode([_turn(tmp_path, "first", 0.2)], stopped_after_turn="first") + + assert _write([row], tmp_path / "job") == [] + + result = json.loads((tmp_path / "job" / "case-1__gym001" / "result.json").read_text(encoding="utf-8")) + assert result["verifier_result"]["rewards"]["overall"] == 0.2 + assert [step["step_name"] for step in result["step_results"]] == ["first"] + assert result["nemo_gym"]["stopped_after_turn"] == "first" + + +def test_mean_counts_a_metric_a_step_did_not_report_as_zero(tmp_path: Path) -> None: + first = _turn(tmp_path, "first", 1.0) + Path(first["verifier_logs_dir"], "reward.json").write_text(json.dumps({"overall": 1.0}), encoding="utf-8") + row = _episode([first, _turn(tmp_path, "second", 0.5)]) + + assert _write([row], tmp_path / "job") == [] + + result = json.loads((tmp_path / "job" / "case-1__gym001" / "result.json").read_text(encoding="utf-8")) + assert result["verifier_result"]["rewards"] == {"overall": 0.75, "correctness": 0.25, "entry_id": "case-1"} + + +def _second_turn_failure(base: Path, kind: str) -> tuple[dict[str, Any], str]: + if kind == "masked": + turn = _turn(base, "second", 1.0, mask_sample=True, failure_kind="harbor:trajectory_export_failed") + return turn, "harbor:trajectory_export_failed" + if kind == "no-verifier-result": + turn = _turn(base, "second", None, failure_kind="harbor:no_turn_result", failure_reason="test.sh timed out") + return turn, "test.sh timed out" + if kind == "setup-failed": + turn = { + "name": "second", + "reward": 0.0, + "failure_kind": "harbor:step_setup", + "failure_reason": "setup.sh exit 1", + } + return turn, "setup.sh exit 1" + if kind == "missing-reward-file": + turn = _turn(base, "second", 1.0) + Path(turn["verifier_logs_dir"], "reward.json").unlink() + return turn, "the task verifier wrote no reward.json or numeric reward.txt" + turn = _turn(base, "second", 1.0) + Path(turn["verifier_logs_dir"], "reward.json").write_text(json.dumps({"entry_id": "other", "overall": 1.0})) + return turn, "the task verifier reported case 'other' for staged case 'case-1'" + + +@pytest.mark.parametrize( + "kind", ["masked", "no-verifier-result", "setup-failed", "missing-reward-file", "case-mismatch"] +) +def test_a_failed_step_leaves_the_episode_unscored_with_its_step_evidence(tmp_path: Path, kind: str) -> None: + second, reason = _second_turn_failure(tmp_path, kind) + row = _episode([_turn(tmp_path, "first", 1.0), second]) + + errors = _write([row], tmp_path / "job") + + assert errors == [f"case case-1 attempt 1: step 'second': {reason}"] + trial = tmp_path / "job" / "case-1__gym001" + result = json.loads((trial / "result.json").read_text(encoding="utf-8")) + assert result["verifier_result"] is None + assert result["exception_info"] == { + "exception_type": "NeMoGymEpisodeFailure", + "exception_message": f"step 'second': {reason}", + } + first, failed = result["step_results"] + assert first["verifier_result"]["rewards"]["overall"] == 1.0 and first["exception_info"] is None + assert failed["verifier_result"] is None + assert failed["exception_info"] == {"exception_type": "NeMoGymStepFailure", "exception_message": reason} + assert (trial / "steps" / "first" / "verifier" / "reward.json").is_file() + job = json.loads((tmp_path / "job" / "result.json").read_text(encoding="utf-8")) + assert job["stats"]["n_errors"] == 1 + assert job["stats"]["evals"]["codex__m"]["reward_stats"]["reward"] == {} + + +@pytest.mark.parametrize( + ("fields", "reason"), + [ + ({"turns": []}, "NeMo Gym returned malformed multi-step turns"), + ({"turns": "first"}, "NeMo Gym returned malformed multi-step turns"), + ({"turn_reward_strategy": None}, "NeMo Gym reported an unsupported turn_reward_strategy None"), + ({"turn_reward_strategy": "sum"}, "NeMo Gym reported an unsupported turn_reward_strategy 'sum'"), + ({"stopped_after_turn": "first"}, "NeMo Gym stopped after turn 'first', which is not its last turn"), + ({"mask_sample": True}, "NeMo Gym masked the sample (Gym-side failure)"), + ], +) +def test_an_inconsistent_episode_is_not_scored(tmp_path: Path, fields: dict[str, Any], reason: str) -> None: + row = _episode([_turn(tmp_path, "first", 1.0), _turn(tmp_path, "second", 1.0)]) | fields + + assert _write([row], tmp_path / "job") == [f"case case-1 attempt 1: {reason}"] + + result = json.loads((tmp_path / "job" / "case-1__gym001" / "result.json").read_text(encoding="utf-8")) + assert result["verifier_result"] is None + assert result["exception_info"]["exception_message"] == reason + + +@pytest.mark.parametrize("names", [("same", "same"), ("Step", "step"), ("ok", "../escape"), ("ok", "trailing.")]) +def test_step_names_that_cannot_be_distinct_directories_are_rejected(tmp_path: Path, names: tuple[str, str]) -> None: + turns = [_turn(tmp_path / str(index), name.replace("/", "_"), 1.0) for index, name in enumerate(names)] + for turn, name in zip(turns, names, strict=True): + turn["name"] = name + job_dir = tmp_path / "job" + + errors = _write([_episode(turns)], job_dir) + + assert errors == ["case case-1 attempt 1: NeMo Gym returned malformed multi-step turns"] + assert not (job_dir / "case-1__gym001" / "steps").exists() + assert not (job_dir / "escape").exists() + + +def test_a_single_step_row_with_null_turns_keeps_the_single_step_layout(tmp_path: Path) -> None: + logs = tmp_path / "logs" + logs.mkdir() + (logs / "reward.json").write_text(json.dumps({"overall": 0.5}), encoding="utf-8") + row = {"task_id": "case-1", "turns": None, "verifier_return_code": 0, "verifier_logs_dir": str(logs)} + + assert _write([row], tmp_path / "job") == [] + + trial = tmp_path / "job" / "case-1__gym001" + result = json.loads((trial / "result.json").read_text(encoding="utf-8")) + assert "step_results" not in result + assert result["verifier_result"]["rewards"] == {"overall": 0.5, "entry_id": "case-1"} + assert (trial / "verifier" / "reward.json").is_file() + + +def _stage_native_task(out: Path, arm: str) -> None: + task = out / "_harbor-tasks" / "codex" / arm / "login-task" + task.mkdir(parents=True) + (task / "task.toml").write_text( + f'[task]\nname = "nvidia/login-task-{arm}-skill"\n\n[metadata]\nentry_id = "auth-login"\n', + encoding="utf-8", + ) + + +@pytest.mark.parametrize(("strategy", "expected"), [("mean", 0.625), ("final", 1.0)]) +def test_shared_collector_scores_the_episode_once_with_merged_step_evidence( + tmp_path: Path, strategy: str, expected: float +) -> None: + out, jobs = tmp_path / "out", tmp_path / "jobs" + for arm in ("with", "without"): + _stage_native_task(out, arm) + turns = [_turn(tmp_path / arm, "first", 0.25), _turn(tmp_path / arm, "second", 1.0)] + row = _episode(turns, task="login-task", turn_reward_strategy=strategy) + assert _write([row], jobs / f"demo-codex-{arm}", {"login-task": "auth-login"}) == [] + + results = collect_harbor_results( + "demo", ["codex"], out, jobs, expected_cases=1, expected_case_ids=["auth-login"], expected_trials=1 + ) + + agent = results["agents"]["codex"] + assert agent["overall_with_skill"] == pytest.approx(expected) + assert agent["overall_without_skill"] == pytest.approx(expected) + assert agent["num_trials_with"] == 1 + trial = out / "codex" / "with-skill" / "trials" / "login-task__gym001" + reward = json.loads((trial / "reward.json").read_text(encoding="utf-8")) + assert reward["entry_id"] == "auth-login" + assert reward["overall"] == pytest.approx(expected) + assert reward.get("evaluation_status") != "failed" + persisted = json.loads((trial / "result.json").read_text(encoding="utf-8")) + assert [step["step_name"] for step in persisted["step_results"]] == ["first", "second"] + trajectory = json.loads((trial / "trajectory.json").read_text(encoding="utf-8")) + assert [step["message"] for step in trajectory["steps"]] == ["first", "second"] + assert [step["extra"]["harbor_step_name"] for step in trajectory["steps"]] == ["first", "second"] + + +def test_shared_collector_records_a_failed_step_as_an_unscored_attempt(tmp_path: Path) -> None: + out, jobs = tmp_path / "out", tmp_path / "jobs" + _stage_native_task(out, "with") + second, reason = _second_turn_failure(tmp_path, "no-verifier-result") + row = _episode([_turn(tmp_path, "first", 1.0), second], task="login-task") + _write([row], jobs / "demo-codex-with", {"login-task": "auth-login"}) + + results = collect_harbor_results( + "demo", + ["codex"], + out, + jobs, + skip_baseline=True, + expected_cases=1, + expected_case_ids=["auth-login"], + expected_trials=1, + ) + + agent = results["agents"]["codex"] + assert agent["scored_attempts"] == 0 + assert agent["overall_with_skill"] is None + trial = out / "codex" / "with-skill" / "trials" / "login-task__gym001" + failure = json.loads((trial / "failure.json").read_text(encoding="utf-8")) + assert failure["entry_id"] == "auth-login" + assert failure["error"]["message"] == f"step 'second': {reason}" + persisted = json.loads((trial / "result.json").read_text(encoding="utf-8")) + assert [step["step_name"] for step in persisted["step_results"]] == ["first", "second"] From 6a10e1a9e20bacc4fc3edb33fdb612287bda49d0 Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Fri, 20 Nov 2026 23:39:28 -0800 Subject: [PATCH 02/10] test(cli): build help contexts with the CLI's context settings Three tests built a click.Context for the root CLI or the Tier 3 workflow by hand, without the command's context_settings. Click 8.2 and later create a command's help option once, from the first context that asks for it, and keep it on the command. When one of these tests was the first to render help on a pytest-xdist worker, the cached option only knew --help, and every later `skillevaluator -h` on that worker exited 2 with "No such option". Which test a worker runs first depends on the total test count, so the failure came and went as PRs added tests. With 43,803 tests the fourth worker starts at test_nested_help_does_not_show_banner, and the -h case of test_noninteractive_invocations_preserve_streams_and_exit_codes fails on Python 3.12, 3.13 and 3.14. The tests now build these contexts with cli.make_context, or as children of such a context, which is how Click builds them for a real invocation. Signed-off-by: Deepak Jain --- tests/cli/test_tier_workflows.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/tests/cli/test_tier_workflows.py b/tests/cli/test_tier_workflows.py index 3655c3321..a0e594400 100644 --- a/tests/cli/test_tier_workflows.py +++ b/tests/cli/test_tier_workflows.py @@ -422,7 +422,10 @@ def test_tier3_help_keeps_option_descriptions_visible(width): import click command = cli.commands["tier3"] - output = render_help(command.workflow, click.Context(command.workflow), width=width) + # A parentless context lacks -h, and Click would cache that help option for `tier3 PATH -h`. + with cli.make_context("skillevaluator", [], resilient_parsing=True) as parent: + ctx = click.Context(command.workflow, info_name="tier3", parent=parent) + output = render_help(command.workflow, ctx, width=width) normalized = " ".join(output.split()) assert "Run an extra agent-only execution of" in normalized assert "first staged task before the full" in normalized From 7923f9b48b2f35115e47f4565c3cf52f61e72616 Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Sat, 21 Nov 2026 00:18:23 -0800 Subject: [PATCH 03/10] fix(nemo-gym): carry step evidence and Gym's strategy through collection Review of the multi-step change found four places where a Gym episode lost what the adapter had recorded. Judge attribution read the reward strategy only from a staged task.toml, which Gym trials do not reference. When every step had the same score, the collector could not tell final from mean and credited the judges of every step. It now uses the strategy Gym reported, so a final attempt names only the last step's judges. The shared collector published a trial's top-level diagnostics and its merged trajectory but not its steps// folders, and a Gym run removes its job folders after collection. A partial attempt has no merged trajectory, so the steps that ran left nothing behind. Published multi-step trials, scored or not, now keep each named step's redacted trajectory and test-stdout.txt under steps//. Harbor multi-step trials get the same folders. The live case status read only the top-level verifier logs, which Gym leaves unset for a multi-step episode, so every such attempt showed as an error while the run was in progress. The episode rules now live in one function that the result writer and the live status both use; the live status reads the step rewards where Gym wrote them. For turn_sessions "continue" the adapter set Harbor's resume flag, which tells the collector that each step's trajectory repeats the earlier steps. Gym exports each turn's own input and new output under the episode's single session id, so a turn that opened with the same steps as the one before it lost them in the merged trajectory: two turns of two and three steps merged to three. The adapter no longer sets the flag, and the merged trajectory keeps all five. Refs #846 Signed-off-by: Deepak Jain --- CHANGELOG.md | 6 +- docs/nemo-gym.mdx | 11 +- docs/reports.mdx | 4 +- src/skillevaluator/tier3/case_summary.py | 14 +- src/skillevaluator/tier3/harbor/collector.py | 48 +++++- src/skillevaluator/tier3/nemo_gym/results.py | 119 +++++++++----- tests/tier3/test_gym_multi_step_results.py | 160 ++++++++++++++++++- 7 files changed, 295 insertions(+), 67 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ae9f0cddd..1c2c21992 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -203,7 +203,11 @@ notes below describe the new policy and backend configuration behavior. "SkillEvaluator verifier did not run in the NeMo Gym sandbox". Each step's rewards, verifier files and trajectory are kept in order, and the attempt is scored once by the task's `mean` or `final` strategy. An attempt with a masked, - failed or ungraded step stays unscored and names that step. + failed or ungraded step stays unscored and names that step. The live case + status uses the same score, and a `final` attempt credits only the last + step's judges. Published multi-step trials, from Gym or Harbor, keep each + step's redacted trajectory and verifier output under `steps//`, so the + evidence survives job cleanup and a partial attempt keeps the steps that ran. - Bound declarative output-pattern checks with isolated Python regex workers and a shared matching budget, preserving Python regex semantics and later checks. Interpreter startup and JSON transfer have a separate startup allowance and do not consume diff --git a/docs/nemo-gym.mdx b/docs/nemo-gym.mdx index 5e549faa9..905219ef6 100644 --- a/docs/nemo-gym.mdx +++ b/docs/nemo-gym.mdx @@ -250,8 +250,15 @@ failed, or produced no verifier result, when Gym marked the episode failed, or w strategy is missing or unsupported. For a step with no verifier result, Gym's own `mean` counts it as 0 and Harbor leaves it out; SkillEvaluator does neither, so a step the verifier never graded is never part of a score. An episode Gym stopped after a step -missed its `min_reward` is scored over the steps that ran, as on Harbor. Tests cover this -with source-shaped Gym rollouts; a live multi-step Gym run has not been recorded yet. +missed its `min_reward` is scored over the steps that ran, as on Harbor. Gym exports +each turn's own input and new output even when `turn_sessions` is `continue`, so the +merged trajectory keeps every turn's steps in order and never treats a turn that opens +like the previous one as a repeat. The live case status shown during the run applies +the same rules. Judge attribution follows +`turn_reward_strategy` too, so a `final` attempt names only the last step's judges. The +published trial keeps each step's redacted trajectory and verifier output under +`steps//` after the run's job folder is removed. Tests cover this with +source-shaped Gym rollouts; a live multi-step Gym run has not been recorded yet. diff --git a/docs/reports.mdx b/docs/reports.mdx index e28aa9cbc..040edde2f 100644 --- a/docs/reports.mdx +++ b/docs/reports.mdx @@ -833,7 +833,9 @@ completed run directly: per-trial artifacts: the trial's `reward.json`, Harbor's `trajectory.json` when available, and redacted, size-capped diagnostic copies such as `trial.log`, `exception.txt`, and agent logs (`codex.txt`, `opencode.txt`). - With standard grading, `reward.json` records `trajectory_source` (the + A multi-step trial also keeps each named step's redacted `trajectory.json` + and `test-stdout.txt` under `steps//`, so an attempt that stopped + partway still shows the steps that ran. With standard grading, `reward.json` records `trajectory_source` (the trajectory or agent log that was graded) and, under each LLM judge's `details`, an `omitted` record showing whether its evidence was truncated to fit the [evidence budget](/skills/skillevaluator/tier3-grading#evidence-budgets) or, for diff --git a/src/skillevaluator/tier3/case_summary.py b/src/skillevaluator/tier3/case_summary.py index 482f2556a..b678f188c 100644 --- a/src/skillevaluator/tier3/case_summary.py +++ b/src/skillevaluator/tier3/case_summary.py @@ -1624,12 +1624,7 @@ def _add_gym_live_marks( Each attempt is scored from its verifier logs with the same rules the Gym result normalizer uses. """ - from skillevaluator.tier3.nemo_gym.results import ( - read_rollouts, - read_verifier_rewards, - rollout_failure_text, - rollout_task_name, - ) + from skillevaluator.tier3.nemo_gym.results import read_rollouts, rollout_rewards, rollout_task_name gym_root = run_dir / "_nemo-gym" if not gym_root.is_dir() or gym_root.is_symlink(): @@ -1644,12 +1639,7 @@ def _add_gym_live_marks( case_id = rollout_task_name(row) if case_id is None or not _SAFE_TRIAL.match(case_id): continue - logs_dir = row.get("verifier_logs_dir") - rewards = ( - read_verifier_rewards(Path(logs_dir)) - if not rollout_failure_text(row) and isinstance(logs_dir, str) and logs_dir - else None - ) + rewards = rollout_rewards(row) score = rewards.get("overall", rewards.get("reward")) if rewards else None if not isinstance(score, int | float) or isinstance(score, bool): mark = ERROR diff --git a/src/skillevaluator/tier3/harbor/collector.py b/src/skillevaluator/tier3/harbor/collector.py index 37669adbc..07f8380ba 100644 --- a/src/skillevaluator/tier3/harbor/collector.py +++ b/src/skillevaluator/tier3/harbor/collector.py @@ -124,6 +124,7 @@ "_trusted_case_identity_unresolved", ) TRIAL_DIAGNOSTIC_ARTIFACTS = ("result.json", "config.json", "exception.txt", "trial.log") +STEP_VERIFIER_ARTIFACTS = ("test-stdout.txt",) AGENT_LOG_ARTIFACTS = ( "trajectory.json", "cursor-cli.txt", @@ -1415,6 +1416,44 @@ def _copy_trial_artifacts( return copied +def _copy_step_artifacts(trial_dir: Path, trial_out: Path) -> list[str]: + """Publish each named step's redacted trajectory and verifier output under ``steps//``. + + A partial episode keeps the steps that ran even when its merged trajectory is incomplete. + """ + names = _expected_step_trajectory_names(trial_dir) + if names is None: + return [] + trajectories = {path.parent.parent.name: path for path in _ordered_step_trajectory_paths(trial_dir)} + copied: list[str] = [] + for name in names: + if _safe_trial_path_component(name) != name: + continue + step_out = trial_out / "steps" / name + trajectory_path = trajectories.get(name) + trajectory: dict[str, Any] | None = None + if trajectory_path is not None: + try: + trajectory, _reference_key = _materialize_trajectory_file(trajectory_path.parent, trajectory_path.name) + except (OSError, SecurePathError, _TrajectoryMergeError, RecursionError): + trajectory = None + safe_trajectory = _redacted_trajectory_data(trajectory) if trajectory is not None else None + if safe_trajectory is not None: + step_out.mkdir(parents=True, exist_ok=True) + (step_out / "trajectory.json").write_text( + json.dumps(safe_trajectory, separators=(",", ":"), ensure_ascii=True, allow_nan=False), + encoding="utf-8", + ) + copied.append(f"steps/{name}/trajectory.json") + for artifact_name in STEP_VERIFIER_ARTIFACTS: + src = trial_dir / "steps" / name / "verifier" / artifact_name + if src.exists() or src.is_symlink(): + ok, _record = _write_redacted_text_copy(src, step_out / artifact_name, source_root=trial_dir) + if ok: + copied.append(f"steps/{name}/{artifact_name}") + return copied + + def _record_skipped_trajectory(trial_out: Path, reason: str) -> None: """Persist a value-free explanation when canonical trajectory output is omitted.""" manifest_path = trial_out / "artifact_manifest.json" @@ -1613,6 +1652,7 @@ def _save_unscored_trials( trial_out = trials_dir / persisted_names.get(trial_src.name, "unknown") trial_out.mkdir(parents=True, exist_ok=True) copied = _copy_trial_artifacts(trial_src, trial_out, include_root_trajectory=False) + copied.extend(_copy_step_artifacts(trial_src, trial_out)) materialized_trajectory, trajectory_reason = _materialized_trial_trajectory(trial_src, None) safe_trajectory = ( _redacted_trajectory_data(materialized_trajectory) if materialized_trajectory is not None else None @@ -5482,7 +5522,11 @@ def _shared_metric_pass_lift( def _harbor_multi_step_reward_strategy(result: dict[str, Any]) -> str | None: - """Read the task's strategy when its staged configuration is still available.""" + """Read the strategy NeMo Gym reported, else the task's when its staged configuration is still available.""" + gym = result.get("nemo_gym") + if result.get("execution_backend") == "nemo-gym" and isinstance(gym, dict): + strategy = gym.get("turn_reward_strategy") + return strategy if isinstance(strategy, str) and strategy in {"final", "mean"} else None config = result.get("config") task = config.get("task") if isinstance(config, dict) else None paths = { @@ -6668,6 +6712,8 @@ def _save_trials( if trial_src: _copy_trial_artifacts(trial_src, trial_out, include_root_trajectory=False) + if not reward.get("_step_name"): + _copy_step_artifacts(trial_src, trial_out) if safe_materialized_traj: (trial_out / "trajectory.json").write_text( json.dumps( diff --git a/src/skillevaluator/tier3/nemo_gym/results.py b/src/skillevaluator/tier3/nemo_gym/results.py index 8b61be68f..a50eb0e53 100644 --- a/src/skillevaluator/tier3/nemo_gym/results.py +++ b/src/skillevaluator/tier3/nemo_gym/results.py @@ -29,6 +29,7 @@ _VERIFIER_FILES = ("reward.json", "reward.txt", "skill_evaluator_reward.json", "custom_reward.json", "test-stdout.txt") _TURN_REWARD_STRATEGIES = ("mean", "final") _TURN_METADATA = ("turn_sessions", "turn_reward_strategy", "stopped_after_turn", "turns_without_verifier_result") +_NO_REWARDS = "the task verifier wrote no reward.json or numeric reward.txt" def _safe(value: str) -> str: @@ -114,9 +115,29 @@ def read_verifier_rewards(verifier_dir: Path) -> dict[str, Any] | None: return None -def rollout_failure_text(row: dict[str, Any]) -> str: - """Return why a Gym rollout failed, or an empty string when its verifier ran.""" - return _failure_text(row) +def rollout_rewards(row: dict[str, Any]) -> dict[str, Any] | None: + """Return a Gym rollout's rewards read in place from its verifier logs, or ``None`` when it is unscored. + + A multi-step episode is rolled up from its turns with the rules the result normalizer applies. + """ + turns = row.get("turns") + if turns is None: + return _logged_rewards(row)[0] + names = _turn_names(turns) + if names is None: + return None + return _episode_rewards(row, names, [_logged_rewards(turn) for turn in turns])[0] + + +def _logged_rewards(row: dict[str, Any]) -> tuple[dict[str, Any] | None, str]: + failure = _failure_text(row) + if failure: + return None, failure + logs_dir = row.get("verifier_logs_dir") + rewards = read_verifier_rewards(Path(logs_dir)) if isinstance(logs_dir, str) and logs_dir else None + if rewards is None: + return None, _NO_REWARDS + return rewards, "" def _failure_text(row: dict[str, Any]) -> str: @@ -141,7 +162,7 @@ def _verified_rewards(verifier_dir: Path, case_id: str) -> tuple[dict[str, Any] """Return the verifier's rewards stamped with ``case_id``, or why they cannot be scored.""" loaded = read_verifier_rewards(verifier_dir) if loaded is None: - return None, "the task verifier wrote no reward.json or numeric reward.txt" + return None, _NO_REWARDS loaded_entry_id = loaded.get("entry_id") if loaded_entry_id is not None and str(loaded_entry_id) != str(case_id): return None, f"the task verifier reported case {str(loaded_entry_id)!r} for staged case {str(case_id)!r}" @@ -177,18 +198,48 @@ def _reward_number(value: Any) -> float | None: return float(value) if isinstance(value, int | float) and not isinstance(value, bool) else None -def _rolled_up_rewards(step_rewards: list[dict[str, Any]], strategy: str, case_id: str) -> dict[str, Any]: +def _rolled_up_rewards(step_rewards: list[dict[str, Any]], strategy: str) -> dict[str, Any]: """Roll up the steps that ran as Harbor does: the last step's rewards, or each key's mean, a missing key as 0.""" if strategy == "final": return dict(step_rewards[-1]) keys = sorted( {key for rewards in step_rewards for key, value in rewards.items() if _reward_number(value) is not None} ) - means = { + return { key: sum(_reward_number(rewards.get(key)) or 0.0 for rewards in step_rewards) / len(step_rewards) for key in keys } - return {**means, "entry_id": case_id} + + +def _episode_rewards( + row: dict[str, Any], names: list[str], steps: list[tuple[dict[str, Any] | None, str]] +) -> tuple[dict[str, Any] | None, str]: + """Return a multi-step episode's rolled-up rewards from each step's ``(rewards, failure)``, or why it is unscored. + + Every step must have run its verifier and written rewards for the episode to be scored. A masked or + failed step, a step without a verifier result, or an episode Gym marked failed leaves the attempt + unscored. Gym's ``mean`` counts a step without a verifier result as 0 and Harbor's leaves it out; the + adapter applies neither, so an ungraded step never becomes a score. An episode that stopped after a + step missed its ``min_reward`` is scored over the steps that ran, as on Harbor. + """ + failure = next( + ( + f"step {name!r}: {step_failure}" + for name, (rewards, step_failure) in zip(names, steps, strict=True) + if rewards is None + ), + "", + ) + strategy = row.get("turn_reward_strategy") + stopped_after = row.get("stopped_after_turn") + failure = failure or _reported_failure_text(row) + if not failure and strategy not in _TURN_REWARD_STRATEGIES: + failure = f"NeMo Gym reported an unsupported turn_reward_strategy {strategy!r}" + if not failure and stopped_after is not None and stopped_after != names[-1]: + failure = f"NeMo Gym stopped after turn {stopped_after!r}, which is not its last turn" + if failure: + return None, failure + return _rolled_up_rewards([rewards for rewards, _failure in steps if rewards is not None], strategy), "" def _multi_step_outcome( @@ -196,54 +247,36 @@ def _multi_step_outcome( ) -> tuple[dict[str, Any] | None, str, dict[str, Any]]: """Write a multi-step episode's steps and return its rewards, why it is unscored, and its result fields. - Every step must have run its verifier and written rewards for the episode to be scored. A masked or - failed step, a step without a verifier result, or an episode Gym marked failed leaves the attempt - unscored, keeping each step's evidence. Gym's ``mean`` counts a step without a verifier result as 0 and - Harbor's leaves it out; the adapter applies neither, so an ungraded step never becomes a score. An - episode that stopped after a step missed its ``min_reward`` is scored over the steps that ran, as on Harbor. + An unscored episode keeps each step's evidence. """ turns = row.get("turns") fields: dict[str, Any] = {"nemo_gym": {key: row.get(key) for key in _TURN_METADATA}} names = _turn_names(turns) if names is None: return None, "NeMo Gym returned malformed multi-step turns", fields - fields["config"] = {"agent": {"resume_trajectory": row.get("turn_sessions") == "continue"}} - step_results: list[dict[str, Any]] = [] - step_rewards: list[dict[str, Any]] = [] - failure = "" + # Gym exports each turn's own input and new output under the episode's one session id, even under + # turn_sessions "continue", so no turn holds an earlier one's steps for Harbor's resume merge to strip. + fields["config"] = {"agent": {"resume_trajectory": False}} + steps: list[tuple[dict[str, Any] | None, str]] = [] for name, turn in zip(names, turns, strict=True): step_dir = trial_dir / "steps" / name logs_dir = turn.get("verifier_logs_dir") if isinstance(logs_dir, str) and Path(logs_dir).is_dir(): _copy_verifier_logs(Path(logs_dir), step_dir) - rewards = None step_failure = _failure_text(turn) - if not step_failure: - rewards, step_failure = _verified_rewards(step_dir / "verifier", case_id) - step_results.append( - { - "step_name": name, - "verifier_result": {"rewards": rewards} if rewards else None, - "exception_info": {"exception_type": "NeMoGymStepFailure", "exception_message": step_failure} - if step_failure - else None, - } - ) - if rewards is not None: - step_rewards.append(rewards) - elif not failure: - failure = f"step {name!r}: {step_failure}" - fields["step_results"] = step_results - strategy = row.get("turn_reward_strategy") - stopped_after = row.get("stopped_after_turn") - failure = failure or _reported_failure_text(row) - if not failure and strategy not in _TURN_REWARD_STRATEGIES: - failure = f"NeMo Gym reported an unsupported turn_reward_strategy {strategy!r}" - if not failure and stopped_after is not None and stopped_after != names[-1]: - failure = f"NeMo Gym stopped after turn {stopped_after!r}, which is not its last turn" - if failure: - return None, failure, fields - return _rolled_up_rewards(step_rewards, strategy, case_id), "", fields + steps.append(_verified_rewards(step_dir / "verifier", case_id) if not step_failure else (None, step_failure)) + fields["step_results"] = [ + { + "step_name": name, + "verifier_result": {"rewards": rewards} if rewards else None, + "exception_info": {"exception_type": "NeMoGymStepFailure", "exception_message": step_failure} + if step_failure + else None, + } + for name, (rewards, step_failure) in zip(names, steps, strict=True) + ] + rewards, failure = _episode_rewards(row, names, steps) + return ({**rewards, "entry_id": case_id} if rewards is not None else None), failure, fields def _copy_verifier_logs(logs_dir: Path, trial_dir: Path) -> None: diff --git a/tests/tier3/test_gym_multi_step_results.py b/tests/tier3/test_gym_multi_step_results.py index a161c28ce..d3c7c3dd7 100644 --- a/tests/tier3/test_gym_multi_step_results.py +++ b/tests/tier3/test_gym_multi_step_results.py @@ -11,12 +11,15 @@ from __future__ import annotations import json +import shutil from pathlib import Path from typing import Any import pytest +from skillevaluator.tier3.case_summary import ERROR, FAIL, PASS, live_case_marks from skillevaluator.tier3.harbor.collector import collect_harbor_results +from skillevaluator.tier3.harbor.metrics import DEFAULT_METRICS from skillevaluator.tier3.nemo_gym.results import write_job_from_rollouts CASES = {"case-1": "case-1"} @@ -41,6 +44,7 @@ def _turn(base: Path, name: str, score: float | None, **fields: Any) -> dict[str (logs / "reward.json").write_text(json.dumps(rewards), encoding="utf-8") (logs / "skill_evaluator_reward.json").write_text(json.dumps(rewards), encoding="utf-8") (logs / "trajectory.json").write_text(json.dumps(_trajectory(name)), encoding="utf-8") + (logs / "test-stdout.txt").write_text(f"{name} verifier output\n", encoding="utf-8") turn = { "name": name, "reward": score or 0.0, @@ -135,14 +139,33 @@ def test_issue_reproduction_with_reward_only_files_is_scored(tmp_path: Path) -> assert len(result["step_results"]) == 2 -def test_continued_sessions_merge_step_trajectories_as_resumed(tmp_path: Path) -> None: - row = _episode([_turn(tmp_path, "first", 1.0), _turn(tmp_path, "second", 1.0)], turn_sessions="continue") - - assert _write([row], tmp_path / "job") == [] +def test_continued_sessions_keep_each_turns_own_transcript(tmp_path: Path) -> None: + out, jobs = tmp_path / "out", tmp_path / "jobs" + _stage_native_task(out, "with") + first, second = _turn(tmp_path, "first", 1.0), _turn(tmp_path, "second", 1.0) + # Gym exports each turn's own input and new output under the episode's one session id, even when the + # harness continues its session, so a turn that opens like the one before it is still new work. + opening = [ + {"step_id": 1, "source": "agent", "message": "listed the repository"}, + {"step_id": 2, "source": "agent", "message": "read login.py"}, + ] + later = [*opening, {"step_id": 3, "source": "agent", "message": "fixed the login check"}] + for turn, steps in ((first, opening), (second, later)): + trajectory = {**_trajectory("episode"), "steps": steps} + Path(turn["verifier_logs_dir"], "trajectory.json").write_text(json.dumps(trajectory), encoding="utf-8") + row = _episode([first, second], task="login-task", turn_sessions="continue") + assert _write([row], jobs / "demo-codex-with", {"login-task": "auth-login"}) == [] + + collect_harbor_results( + "demo", ["codex"], out, jobs, skip_baseline=True, expected_cases=1, expected_case_ids=["auth-login"] + ) - result = json.loads((tmp_path / "job" / "case-1__gym001" / "result.json").read_text(encoding="utf-8")) - assert result["config"] == {"agent": {"resume_trajectory": True}} - assert result["nemo_gym"]["turn_sessions"] == "continue" + trial = out / "codex" / "with-skill" / "trials" / "login-task__gym001" + trajectory = json.loads((trial / "trajectory.json").read_text(encoding="utf-8")) + assert [step["extra"]["harbor_step_name"] for step in trajectory["steps"]] == ["first"] * 2 + ["second"] * 3 + persisted = json.loads((trial / "result.json").read_text(encoding="utf-8")) + assert persisted["config"] == {"agent": {"resume_trajectory": False}} + assert persisted["nemo_gym"]["turn_sessions"] == "continue" def test_a_missed_min_reward_is_scored_over_the_steps_that_ran(tmp_path: Path) -> None: @@ -335,3 +358,126 @@ def test_shared_collector_records_a_failed_step_as_an_unscored_attempt(tmp_path: assert failure["error"]["message"] == f"step 'second': {reason}" persisted = json.loads((trial / "result.json").read_text(encoding="utf-8")) assert [step["step_name"] for step in persisted["step_results"]] == ["first", "second"] + + +def _judged_turn(base: Path, name: str, accuracy: float, judge: str) -> dict[str, Any]: + logs = base / "gym-logs" / name + logs.mkdir(parents=True) + scores = {**dict.fromkeys(DEFAULT_METRICS, 0.5), "accuracy": accuracy} + (logs / "reward.json").write_text(json.dumps(scores), encoding="utf-8") + sidecar = {**scores, "details": {"accuracy": {"judge_model_used": judge}}} + (logs / "skill_evaluator_reward.json").write_text(json.dumps(sidecar), encoding="utf-8") + (logs / "trajectory.json").write_text(json.dumps(_trajectory(name)), encoding="utf-8") + return { + "name": name, + "reward": accuracy, + "mask_sample": False, + "verifier_return_code": 0, + "verifier_logs_dir": str(logs), + } + + +@pytest.mark.parametrize(("strategy", "final_only"), [("final", True), ("mean", False)]) +def test_shared_collector_attributes_judges_by_gyms_declared_strategy( + tmp_path: Path, strategy: str, final_only: bool +) -> None: + out, jobs = tmp_path / "out", tmp_path / "jobs" + for arm in ("with", "without"): + _stage_native_task(out, arm) + accuracy = 1.0 if arm == "with" else 0.6 + # Equal step scores leave the strategy impossible to infer from the rewards alone. + turns = [ + _judged_turn(tmp_path / arm, "prepare", accuracy, "fallback" if arm == "with" else "primary"), + _judged_turn(tmp_path / arm, "finish", accuracy, "primary"), + ] + row = _episode(turns, task="login-task", turn_reward_strategy=strategy) + assert _write([row], jobs / f"demo-codex-{arm}", {"login-task": "auth-login"}) == [] + + results = collect_harbor_results( + "demo", ["codex"], out, jobs, expected_cases=1, expected_case_ids=["auth-login"], expected_trials=1 + ) + + reward_path = out / "codex" / "with-skill" / "trials" / "login-task__gym001" / "reward.json" + reward = json.loads(reward_path.read_text(encoding="utf-8")) + lift = results["agents"]["codex"]["lift"] + if final_only: + assert reward["details"]["accuracy"]["judge_models"] == ["primary"] + assert lift["accuracy"]["delta"] == pytest.approx(0.4) + assert "judge_mixed_cases" not in lift + else: + assert reward["details"]["accuracy"]["judge_models"] == ["fallback", "primary"] + assert lift["judge_mixed_cases"] == {"accuracy": 1} + assert "accuracy" not in lift + + +@pytest.mark.parametrize("outcome", ["scored", "second-step-setup-failed"]) +def test_named_step_evidence_survives_collection_and_job_cleanup(tmp_path: Path, outcome: str) -> None: + out, jobs = tmp_path / "out", tmp_path / "jobs" + _stage_native_task(out, "with") + if outcome == "scored": + second = _turn(tmp_path, "second", 1.0) + else: + second, _reason = _second_turn_failure(tmp_path, "setup-failed") + row = _episode([_turn(tmp_path, "first", 0.25), second], task="login-task") + _write([row], jobs / "demo-codex-with", {"login-task": "auth-login"}) + + collect_harbor_results( + "demo", ["codex"], out, jobs, skip_baseline=True, expected_cases=1, expected_case_ids=["auth-login"] + ) + shutil.rmtree(jobs) + + steps = out / "codex" / "with-skill" / "trials" / "login-task__gym001" / "steps" + first = steps / "first" + assert json.loads((first / "trajectory.json").read_text(encoding="utf-8"))["steps"][0]["message"] == "first" + assert (first / "test-stdout.txt").read_text(encoding="utf-8") == "first verifier output\n" + if outcome == "scored": + assert json.loads((steps / "second" / "trajectory.json").read_text(encoding="utf-8"))["session_id"] == ( + "session-second" + ) + assert (steps / "second" / "test-stdout.txt").is_file() + else: + # The step whose setup failed left no evidence to keep. + assert not (steps / "second").exists() + + +def test_step_evidence_publication_refuses_linked_files(tmp_path: Path) -> None: + out, jobs = tmp_path / "out", tmp_path / "jobs" + _stage_native_task(out, "with") + row = _episode([_turn(tmp_path, "first", 0.25), _turn(tmp_path, "second", 1.0)], task="login-task") + _write([row], jobs / "demo-codex-with", {"login-task": "auth-login"}) + secret = tmp_path / "secret.txt" + secret.write_text("outside the trial\n", encoding="utf-8") + linked = jobs / "demo-codex-with" / "login-task__gym001" / "steps" / "first" / "verifier" / "test-stdout.txt" + linked.unlink() + linked.symlink_to(secret) + + collect_harbor_results( + "demo", ["codex"], out, jobs, skip_baseline=True, expected_cases=1, expected_case_ids=["auth-login"] + ) + + steps = out / "codex" / "with-skill" / "trials" / "login-task__gym001" / "steps" + assert not (steps / "first" / "test-stdout.txt").exists() + assert (steps / "first" / "trajectory.json").is_file() + assert (steps / "second" / "test-stdout.txt").is_file() + + +def test_live_marks_score_multi_step_episodes_as_the_final_result_does(tmp_path: Path) -> None: + run_dir = tmp_path / "run" + (run_dir / "_harbor-tasks" / "codex" / "with" / "case-1").mkdir(parents=True) + arm = run_dir / "_nemo-gym" / "codex-with" + arm.mkdir(parents=True) + failed_second, _reason = _second_turn_failure(tmp_path / "failed", "no-verifier-result") + rows = [ + _episode([_turn(tmp_path / "pass", "first", 0.25), _turn(tmp_path / "pass", "second", 1.0)]), + # Gym stopped after a step missed its min_reward: scored over the steps that ran, below the threshold. + _episode([_turn(tmp_path / "stop", "first", 0.2)], stopped_after_turn="first"), + _episode([_turn(tmp_path / "failed", "first", 1.0), failed_second]), + ] + (arm / "rollouts.jsonl").write_text("".join(json.dumps(row) + "\n" for row in rows), encoding="utf-8") + + marks, running = live_case_marks(run_dir, ["codex"], pass_threshold=0.5) + + assert marks == {"codex": {"with_skill": {"case-1": [PASS, FAIL, ERROR]}}} + assert running == set() + final = write_job_from_rollouts(rows, tmp_path / "job", eval_name="codex__m", task_case_ids=CASES, n_attempts=3) + assert final == ["case case-1 attempt 3: step 'second': test.sh timed out"] From 8a9cbcc0467e4fda7c3cd71b6fa881b6fb7ecb2f Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Sat, 21 Nov 2026 04:53:14 -0800 Subject: [PATCH 04/10] fix(nemo-gym): give the live case status the finished run's verdict The live case grid for a Gym run still passed any attempt whose overall score cleared the threshold. The finished run also applies standard grading's goal check and checks that the verifier scored the staged case. So an attempt with overall 0.95 and Goal Accuracy 0.5 showed as a pass while the run was active and as a failure once it finished, and a verifier reward that named a different case passed live but was left unscored at collection. The live poller now marks each Gym attempt, single-step or multi-step, with the attempt verdict the finished grid uses. It reads the rewards through the normalizer's case check against the staged task's [metadata].entry_id. A single-step rollout's reward sidecars are merged in as the collector merges them, so a goal the verifier recorded as not applicable is not read as 0. Once the run has removed its staged tasks the case can no longer be looked up, so the live view skips that one check rather than turning a correctly scored attempt into an error. Signed-off-by: Deepak Jain --- CHANGELOG.md | 11 +- docs/nemo-gym.mdx | 4 +- src/skillevaluator/tier3/case_summary.py | 33 ++++-- src/skillevaluator/tier3/nemo_gym/results.py | 45 +++++--- tests/tier3/test_gym_multi_step_results.py | 107 ++++++++++++++++++- 5 files changed, 173 insertions(+), 27 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1c2c21992..410e6d1ad 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -204,10 +204,13 @@ notes below describe the new policy and backend configuration behavior. rewards, verifier files and trajectory are kept in order, and the attempt is scored once by the task's `mean` or `final` strategy. An attempt with a masked, failed or ungraded step stays unscored and names that step. The live case - status uses the same score, and a `final` attempt credits only the last - step's judges. Published multi-step trials, from Gym or Harbor, keep each - step's redacted trajectory and verifier output under `steps//`, so the - evidence survives job cleanup and a partial attempt keeps the steps that ran. + status uses the same score and, for every Gym attempt, the finished run's + pass verdict, so a goal missed under standard grading or a verifier that + names another case no longer shows as a pass while the run is active. A + `final` attempt credits only the last step's judges. Published multi-step + trials, from Gym or Harbor, keep each step's redacted trajectory and verifier + output under `steps//`, so the evidence survives job cleanup and a + partial attempt keeps the steps that ran. - Bound declarative output-pattern checks with isolated Python regex workers and a shared matching budget, preserving Python regex semantics and later checks. Interpreter startup and JSON transfer have a separate startup allowance and do not consume diff --git a/docs/nemo-gym.mdx b/docs/nemo-gym.mdx index 905219ef6..b8534776c 100644 --- a/docs/nemo-gym.mdx +++ b/docs/nemo-gym.mdx @@ -254,7 +254,9 @@ missed its `min_reward` is scored over the steps that ran, as on Harbor. Gym exp each turn's own input and new output even when `turn_sessions` is `continue`, so the merged trajectory keeps every turn's steps in order and never treats a turn that opens like the previous one as a repeat. The live case status shown during the run applies -the same rules. Judge attribution follows +the same rules and, for every Gym attempt, the finished run's pass verdict: an attempt +that misses its goal under standard grading shows as failed, and one whose verifier +names a different case than the staged task shows as an error. Judge attribution follows `turn_reward_strategy` too, so a `final` attempt names only the last step's judges. The published trial keeps each step's redacted trajectory and verifier output under `steps//` after the run's job folder is removed. Tests cover this with diff --git a/src/skillevaluator/tier3/case_summary.py b/src/skillevaluator/tier3/case_summary.py index b678f188c..f61f04b29 100644 --- a/src/skillevaluator/tier3/case_summary.py +++ b/src/skillevaluator/tier3/case_summary.py @@ -10,6 +10,7 @@ import os import re import tempfile +import tomllib from collections import Counter from collections.abc import Callable, Mapping from contextvars import ContextVar @@ -1617,12 +1618,28 @@ def _live_mark(trial: Path, run_dir: Path, pass_threshold: float) -> str | None: return ERROR +def _gym_staged_case_id(staged: Path, task: str, run_dir: Path) -> str | None: + """The case the Gym runner staged ``task`` as, or ``None`` once the run has removed its staged task. + + As in the runner, a task without a ``[metadata].entry_id`` is staged as its folder name. + """ + try: + with SecureRoot(run_dir) as reader: + raw, _ = reader.read_bytes((staged / task / "task.toml").relative_to(run_dir), _MAX_TRIAL_JSON_BYTES) + metadata = tomllib.loads(raw.decode("utf-8")).get("metadata") + except (OSError, ValueError, SecurePathError): + return None + entry_id = metadata.get("entry_id") if isinstance(metadata, dict) else None + return entry_id if isinstance(entry_id, str) and entry_id else task + + def _add_gym_live_marks( run_dir: Path, agents: list[str], marks: dict[str, dict[str, dict[str, list[str]]]], pass_threshold: float ) -> bool: """Add the attempts a running NeMo Gym arm has appended to its ``rollouts.jsonl``; False for a non-Gym run. - Each attempt is scored from its verifier logs with the same rules the Gym result normalizer uses. + Each attempt is scored from its verifier logs with the same rules the Gym result normalizer uses, + including the staged case its verifier must name, and marked by the final attempt verdict. """ from skillevaluator.tier3.nemo_gym.results import read_rollouts, rollout_rewards, rollout_task_name @@ -1635,17 +1652,21 @@ def _add_gym_live_marks( rollouts = arm / "rollouts.jsonl" if arm.is_symlink() or rollouts.is_symlink() or not rollouts.is_file(): continue + staged = run_dir / "_harbor-tasks" / agent / variant + case_ids: dict[str, str | None] = {} for row in read_rollouts(rollouts): - case_id = rollout_task_name(row) - if case_id is None or not _SAFE_TRIAL.match(case_id): + task = rollout_task_name(row) + if task is None or not _SAFE_TRIAL.match(task): continue - rewards = rollout_rewards(row) + if task not in case_ids: + case_ids[task] = _gym_staged_case_id(staged, task, run_dir) + rewards = rollout_rewards(row, case_ids[task]) score = rewards.get("overall", rewards.get("reward")) if rewards else None if not isinstance(score, int | float) or isinstance(score, bool): mark = ERROR else: - mark = PASS if score >= pass_threshold else FAIL - marks.setdefault(agent, {}).setdefault(key, {}).setdefault(case_id, []).append(mark) + mark = PASS if attempt_verdict(score, pass_threshold, reward=rewards).passed else FAIL + marks.setdefault(agent, {}).setdefault(key, {}).setdefault(task, []).append(mark) return True diff --git a/src/skillevaluator/tier3/nemo_gym/results.py b/src/skillevaluator/tier3/nemo_gym/results.py index a50eb0e53..a5dd2a33c 100644 --- a/src/skillevaluator/tier3/nemo_gym/results.py +++ b/src/skillevaluator/tier3/nemo_gym/results.py @@ -115,29 +115,35 @@ def read_verifier_rewards(verifier_dir: Path) -> dict[str, Any] | None: return None -def rollout_rewards(row: dict[str, Any]) -> dict[str, Any] | None: - """Return a Gym rollout's rewards read in place from its verifier logs, or ``None`` when it is unscored. +def rollout_rewards(row: dict[str, Any], case_id: str | None) -> dict[str, Any] | None: + """Return the rewards the collector scores for a Gym rollout, read in place, or ``None`` when it is unscored. - A multi-step episode is rolled up from its turns with the rules the result normalizer applies. + The rollout passes the result normalizer's checks, including that its verifier scored the staged + ``case_id`` when that is known. A multi-step episode is rolled up from its turns; a single-step + rollout's reward sidecars are merged in as the collector merges them. """ turns = row.get("turns") if turns is None: - return _logged_rewards(row)[0] + rewards = _logged_rewards(row, case_id)[0] + if rewards is not None: + from skillevaluator.tier3.harbor.collector import _merge_reward_sidecars + + _merge_reward_sidecars(rewards, Path(row["verifier_logs_dir"])) + return rewards names = _turn_names(turns) if names is None: return None - return _episode_rewards(row, names, [_logged_rewards(turn) for turn in turns])[0] + return _episode_rewards(row, names, [_logged_rewards(turn, case_id) for turn in turns])[0] -def _logged_rewards(row: dict[str, Any]) -> tuple[dict[str, Any] | None, str]: +def _logged_rewards(row: dict[str, Any], case_id: str | None) -> tuple[dict[str, Any] | None, str]: failure = _failure_text(row) if failure: return None, failure logs_dir = row.get("verifier_logs_dir") - rewards = read_verifier_rewards(Path(logs_dir)) if isinstance(logs_dir, str) and logs_dir else None - if rewards is None: + if not isinstance(logs_dir, str) or not logs_dir: return None, _NO_REWARDS - return rewards, "" + return _case_rewards(read_verifier_rewards(Path(logs_dir)), case_id) def _failure_text(row: dict[str, Any]) -> str: @@ -158,19 +164,28 @@ def _reported_failure_text(row: dict[str, Any]) -> str: return "" -def _verified_rewards(verifier_dir: Path, case_id: str) -> tuple[dict[str, Any] | None, str]: - """Return the verifier's rewards stamped with ``case_id``, or why they cannot be scored.""" - loaded = read_verifier_rewards(verifier_dir) +def _case_rewards(loaded: dict[str, Any] | None, case_id: str | None) -> tuple[dict[str, Any] | None, str]: + """Return the verifier's rewards stamped with ``case_id``, or why they cannot be scored. + + An unknown ``case_id`` leaves the rewards as the verifier wrote them. + """ if loaded is None: return None, _NO_REWARDS + if case_id is None: + return dict(loaded), "" loaded_entry_id = loaded.get("entry_id") if loaded_entry_id is not None and str(loaded_entry_id) != str(case_id): return None, f"the task verifier reported case {str(loaded_entry_id)!r} for staged case {str(case_id)!r}" - rewards = {**loaded, "entry_id": case_id} + return {**loaded, "entry_id": case_id}, "" + + +def _verified_rewards(verifier_dir: Path, case_id: str) -> tuple[dict[str, Any] | None, str]: + """Return the trial verifier's rewards stamped with ``case_id`` and write them back, or why they are unscored.""" + rewards, failure = _case_rewards(read_verifier_rewards(verifier_dir), case_id) reward_path = verifier_dir / "reward.json" - if reward_path.is_file(): + if rewards is not None and reward_path.is_file(): reward_path.write_text(json.dumps(rewards, indent=2), encoding="utf-8") - return rewards, "" + return rewards, failure def _turn_names(turns: Any) -> list[str] | None: diff --git a/tests/tier3/test_gym_multi_step_results.py b/tests/tier3/test_gym_multi_step_results.py index d3c7c3dd7..c4ad46398 100644 --- a/tests/tier3/test_gym_multi_step_results.py +++ b/tests/tier3/test_gym_multi_step_results.py @@ -17,7 +17,7 @@ import pytest -from skillevaluator.tier3.case_summary import ERROR, FAIL, PASS, live_case_marks +from skillevaluator.tier3.case_summary import ERROR, FAIL, PASS, case_marks, live_case_marks from skillevaluator.tier3.harbor.collector import collect_harbor_results from skillevaluator.tier3.harbor.metrics import DEFAULT_METRICS from skillevaluator.tier3.nemo_gym.results import write_job_from_rollouts @@ -481,3 +481,108 @@ def test_live_marks_score_multi_step_episodes_as_the_final_result_does(tmp_path: assert running == set() final = write_job_from_rollouts(rows, tmp_path / "job", eval_name="codex__m", task_case_ids=CASES, n_attempts=3) assert final == ["case case-1 attempt 3: step 'second': test.sh timed out"] + + +def _graded(logs: Path, goal_accuracy: float, *, entry_id: str | None = None, **sidecar: Any) -> None: + rewards: dict[str, Any] = {**dict.fromkeys(DEFAULT_METRICS, 1.0), "goal_accuracy": goal_accuracy, "overall": 0.95} + if entry_id is not None: + rewards["entry_id"] = entry_id + (logs / "reward.json").write_text(json.dumps(rewards), encoding="utf-8") + (logs / "skill_evaluator_reward.json").write_text(json.dumps(rewards | sidecar), encoding="utf-8") + + +def _graded_turn(base: Path, name: str, goal_accuracy: float, entry_id: str | None = None) -> dict[str, Any]: + turn = _turn(base, name, 0.95) + _graded(Path(turn["verifier_logs_dir"]), goal_accuracy, entry_id=entry_id) + return turn + + +def _live_and_final_marks(out: Path, jobs: Path, rows: list[dict[str, Any]]) -> tuple[list[str], list[str]]: + arm = out / "_nemo-gym" / "codex-with" + arm.mkdir(parents=True) + (arm / "rollouts.jsonl").write_text("".join(json.dumps(row) + "\n" for row in rows), encoding="utf-8") + live, running = live_case_marks(out, ["codex"], pass_threshold=0.5) + assert running == set() + write_job_from_rollouts( + rows, + jobs / "demo-codex-with", + eval_name="codex__m", + task_case_ids={"login-task": "auth-login"}, + n_attempts=len(rows), + ) + results = collect_harbor_results( + "demo", + ["codex"], + out, + jobs, + skip_baseline=True, + expected_cases=1, + expected_case_ids=["auth-login"], + expected_trials=len(rows), + ) + return live["codex"]["with_skill"]["login-task"], case_marks(results)["codex"]["with_skill"]["auth-login"] + + +@pytest.mark.parametrize("strategy", ["mean", "final"]) +def test_live_marks_apply_the_final_verdict_and_staged_case_to_episodes(tmp_path: Path, strategy: str) -> None: + out, jobs = tmp_path / "out", tmp_path / "jobs" + _stage_native_task(out, "with") + + def episode(label: str, goal_accuracy: float, second_entry_id: str | None = None) -> dict[str, Any]: + turns = [ + _graded_turn(tmp_path / label, "first", goal_accuracy), + _graded_turn(tmp_path / label, "second", goal_accuracy, second_entry_id), + ] + return _episode(turns, task="login-task", turn_reward_strategy=strategy) + + rows = [ + episode("goal-met", 1.0), + # Overall clears the threshold, but standard grading requires the goal. + episode("goal-missed", 0.5), + episode("other-case", 1.0, second_entry_id="other-case"), + episode("staged-case", 1.0, second_entry_id="auth-login"), + ] + + live, final = _live_and_final_marks(out, jobs, rows) + + assert live == [PASS, FAIL, ERROR, PASS] + assert sorted(live) == sorted(final) + + +def test_live_marks_keep_a_verified_case_after_its_staged_task_is_removed(tmp_path: Path) -> None: + out = tmp_path / "out" + _stage_native_task(out, "with") + turns = [_graded_turn(tmp_path, name, 1.0, "auth-login") for name in ("first", "second")] + arm = out / "_nemo-gym" / "codex-with" + arm.mkdir(parents=True) + (arm / "rollouts.jsonl").write_text(json.dumps(_episode(turns, task="login-task")) + "\n", encoding="utf-8") + # The run removes its staged tasks before the live view stops polling. + shutil.rmtree(out / "_harbor-tasks") + + marks, _running = live_case_marks(out, ["codex"], pass_threshold=0.5) + + assert marks == {"codex": {"with_skill": {"login-task": [PASS]}}} + + +def test_live_marks_apply_the_final_verdict_and_staged_case_to_single_steps(tmp_path: Path) -> None: + out, jobs = tmp_path / "out", tmp_path / "jobs" + _stage_native_task(out, "with") + + def rollout(label: str, goal_accuracy: float, **reward: Any) -> dict[str, Any]: + logs = tmp_path / label + logs.mkdir() + _graded(logs, goal_accuracy, **reward) + return {"task_id": "login-task", "verifier_return_code": 0, "verifier_logs_dir": str(logs)} + + not_applicable = {"details": {"goal_accuracy": {"status": "not_applicable"}}} + rows = [ + rollout("goal-missed", 0.5), + rollout("other-case", 1.0, entry_id="other-case"), + # The collector reads the sidecar's N/A goal back into the reward, so only Overall decides. + rollout("goal-not-applicable", 0.0, **not_applicable), + ] + + live, final = _live_and_final_marks(out, jobs, rows) + + assert live == [FAIL, ERROR, PASS] + assert sorted(live) == sorted(final) From 7221d9975d18c090cab05a78d5dd3d12d1808a4f Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Sat, 21 Nov 2026 05:57:16 -0800 Subject: [PATCH 05/10] fix(nemo-gym): judge live Gym attempts with the collector's own checks Two cases still made the live case grid of a Gym run disagree with the finished run. Once the run removed its staged tasks, the live view could no longer look up the case each task was staged as, so an attempt whose verifier named another case showed as a pass and then finished unscored. The live view also applied only part of the collector's checks. When a required judge fails, the built-in verifier still writes its other scores and an overall of 0, so a mean episode could reach the threshold live and a single-step rollout showed as failed, while collection leaves both unscored. The runner now writes each arm's task to case map to _nemo-gym/-/task_case_ids.json when it stages the arm. That folder is kept after the staged tasks are removed, and the live view takes its case ids from it. Each live attempt is judged by the collector itself: the rollout is written to a scratch job the way the runner writes it, read with the collector's reward extraction and scoreability checks, and marked with the attempt verdict, as harbor_job_passed reads a job. Gym never rewrites a rollout line, so each is judged once and its scratch job is removed. Signed-off-by: Deepak Jain --- CHANGELOG.md | 7 +- docs/nemo-gym.mdx | 18 +++-- src/skillevaluator/tier3/case_summary.py | 51 ++++++------ src/skillevaluator/tier3/nemo_gym/results.py | 76 +++++++++-------- src/skillevaluator/tier3/nemo_gym/runner.py | 8 +- tests/test_nemo_gym_backend.py | 37 ++++++++- tests/tier3/test_gym_multi_step_results.py | 85 ++++++++++++++++---- 7 files changed, 185 insertions(+), 97 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 410e6d1ad..8fa234f3b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -204,9 +204,10 @@ notes below describe the new policy and backend configuration behavior. rewards, verifier files and trajectory are kept in order, and the attempt is scored once by the task's `mean` or `final` strategy. An attempt with a masked, failed or ungraded step stays unscored and names that step. The live case - status uses the same score and, for every Gym attempt, the finished run's - pass verdict, so a goal missed under standard grading or a verifier that - names another case no longer shows as a pass while the run is active. A + status judges every Gym attempt as the finished run does, so a goal missed + under standard grading shows as failed, and a required judge that failed or a + verifier that names another case shows as an error, also after the staged + tasks are removed. A `final` attempt credits only the last step's judges. Published multi-step trials, from Gym or Harbor, keep each step's redacted trajectory and verifier output under `steps//`, so the evidence survives job cleanup and a diff --git a/docs/nemo-gym.mdx b/docs/nemo-gym.mdx index b8534776c..c146bda20 100644 --- a/docs/nemo-gym.mdx +++ b/docs/nemo-gym.mdx @@ -253,13 +253,14 @@ verifier never graded is never part of a score. An episode Gym stopped after a s missed its `min_reward` is scored over the steps that ran, as on Harbor. Gym exports each turn's own input and new output even when `turn_sessions` is `continue`, so the merged trajectory keeps every turn's steps in order and never treats a turn that opens -like the previous one as a repeat. The live case status shown during the run applies -the same rules and, for every Gym attempt, the finished run's pass verdict: an attempt -that misses its goal under standard grading shows as failed, and one whose verifier -names a different case than the staged task shows as an error. Judge attribution follows -`turn_reward_strategy` too, so a `final` attempt names only the last step's judges. The -published trial keeps each step's redacted trajectory and verifier output under -`steps//` after the run's job folder is removed. Tests cover this with +like the previous one as a repeat. The live case status shown during the run judges +every Gym attempt as the finished run does: an attempt that misses its goal under +standard grading shows as failed, and one the finished run leaves unscored, such as +one whose required judge failed or whose verifier names a different case than the +staged task, shows as an error, also after the staged tasks are removed. Judge +attribution follows `turn_reward_strategy` too, so a `final` attempt names only the last +step's judges. The published trial keeps each step's redacted trajectory and verifier +output under `steps//` after the run's job folder is removed. Tests cover this with source-shaped Gym rollouts; a live multi-step Gym run has not been recorded yet. @@ -319,7 +320,8 @@ Docker sandboxes before you run again. A finished run updates `latest` and recor the same dataset snapshot and publication target as a Harbor run. As on Harbor without `--harbor-keep-jobs`, the staged tasks and per-trial files are removed at the end; Gym's own redacted `gym.log` and its `rollouts.jsonl` stay under -`_nemo-gym/` in the run folder, and the rollouts hold the raw agent responses. +`_nemo-gym/` in the run folder with each arm's `task_case_ids.json`, the case each +staged task ran as, and the rollouts hold the raw agent responses. diff --git a/src/skillevaluator/tier3/case_summary.py b/src/skillevaluator/tier3/case_summary.py index f61f04b29..8bcbd2513 100644 --- a/src/skillevaluator/tier3/case_summary.py +++ b/src/skillevaluator/tier3/case_summary.py @@ -5,12 +5,12 @@ from __future__ import annotations +import hashlib import json import logging import os import re import tempfile -import tomllib from collections import Counter from collections.abc import Callable, Mapping from contextvars import ContextVar @@ -1591,6 +1591,8 @@ def load_case_marks(run_dir: Path) -> dict[str, dict[str, dict[str, list[str]]]] _LIVE_VARIANTS = {"with": "with_skill", "without": "without_skill"} +_GYM_LIVE_MARKS: dict[str, str] = {} +_MAX_GYM_LIVE_MARKS = 65536 def _harbor_job_owner(job_name: str, agents: list[str]) -> tuple[str, str] | None: @@ -1618,19 +1620,19 @@ def _live_mark(trial: Path, run_dir: Path, pass_threshold: float) -> str | None: return ERROR -def _gym_staged_case_id(staged: Path, task: str, run_dir: Path) -> str | None: - """The case the Gym runner staged ``task`` as, or ``None`` once the run has removed its staged task. +def _gym_live_mark(row: dict[str, Any], task: str, case_id: str, gym_root: Path, pass_threshold: float) -> str: + from skillevaluator.tier3.nemo_gym.results import rollout_verdict - As in the runner, a task without a ``[metadata].entry_id`` is staged as its folder name. - """ - try: - with SecureRoot(run_dir) as reader: - raw, _ = reader.read_bytes((staged / task / "task.toml").relative_to(run_dir), _MAX_TRIAL_JSON_BYTES) - metadata = tomllib.loads(raw.decode("utf-8")).get("metadata") - except (OSError, ValueError, SecurePathError): - return None - entry_id = metadata.get("entry_id") if isinstance(metadata, dict) else None - return entry_id if isinstance(entry_id, str) and entry_id else task + # Gym appends a rollout only once its verifier logs are written, so each line is judged once. + key = hashlib.sha256(json.dumps([row, task, case_id, pass_threshold], sort_keys=True).encode()).hexdigest() + mark = _GYM_LIVE_MARKS.get(key) + if mark is None: + passed = rollout_verdict(row, task, case_id, pass_threshold, gym_root) + mark = ERROR if passed is None else PASS if passed else FAIL + if len(_GYM_LIVE_MARKS) >= _MAX_GYM_LIVE_MARKS: + _GYM_LIVE_MARKS.clear() + _GYM_LIVE_MARKS[key] = mark + return mark def _add_gym_live_marks( @@ -1638,10 +1640,10 @@ def _add_gym_live_marks( ) -> bool: """Add the attempts a running NeMo Gym arm has appended to its ``rollouts.jsonl``; False for a non-Gym run. - Each attempt is scored from its verifier logs with the same rules the Gym result normalizer uses, - including the staged case its verifier must name, and marked by the final attempt verdict. + Each attempt is judged as the finished run judges it, for the case the runner staged its task as. + A task the runner recorded no case for is its own case. """ - from skillevaluator.tier3.nemo_gym.results import read_rollouts, rollout_rewards, rollout_task_name + from skillevaluator.tier3.nemo_gym.results import TASK_CASE_IDS_FILE, read_rollouts, rollout_task_name gym_root = run_dir / "_nemo-gym" if not gym_root.is_dir() or gym_root.is_symlink(): @@ -1652,20 +1654,17 @@ def _add_gym_live_marks( rollouts = arm / "rollouts.jsonl" if arm.is_symlink() or rollouts.is_symlink() or not rollouts.is_file(): continue - staged = run_dir / "_harbor-tasks" / agent / variant - case_ids: dict[str, str | None] = {} + case_ids = _load_json(arm / TASK_CASE_IDS_FILE, root=run_dir) + if not isinstance(case_ids, dict): + case_ids = {} for row in read_rollouts(rollouts): task = rollout_task_name(row) if task is None or not _SAFE_TRIAL.match(task): continue - if task not in case_ids: - case_ids[task] = _gym_staged_case_id(staged, task, run_dir) - rewards = rollout_rewards(row, case_ids[task]) - score = rewards.get("overall", rewards.get("reward")) if rewards else None - if not isinstance(score, int | float) or isinstance(score, bool): - mark = ERROR - else: - mark = PASS if attempt_verdict(score, pass_threshold, reward=rewards).passed else FAIL + case_id = case_ids.get(task) + if not isinstance(case_id, str) or not case_id: + case_id = task + mark = _gym_live_mark(row, task, case_id, gym_root, pass_threshold) marks.setdefault(agent, {}).setdefault(key, {}).setdefault(task, []).append(mark) return True diff --git a/src/skillevaluator/tier3/nemo_gym/results.py b/src/skillevaluator/tier3/nemo_gym/results.py index a5dd2a33c..9ea2a6e6e 100644 --- a/src/skillevaluator/tier3/nemo_gym/results.py +++ b/src/skillevaluator/tier3/nemo_gym/results.py @@ -20,16 +20,20 @@ import math import re import shutil +import tempfile import unicodedata from collections import defaultdict from pathlib import Path from typing import Any +from skillevaluator.tier3.attempt_verdict import attempt_verdict + _UNSAFE = re.compile(r"[^A-Za-z0-9._-]+") _VERIFIER_FILES = ("reward.json", "reward.txt", "skill_evaluator_reward.json", "custom_reward.json", "test-stdout.txt") _TURN_REWARD_STRATEGIES = ("mean", "final") _TURN_METADATA = ("turn_sessions", "turn_reward_strategy", "stopped_after_turn", "turns_without_verifier_result") _NO_REWARDS = "the task verifier wrote no reward.json or numeric reward.txt" +TASK_CASE_IDS_FILE = "task_case_ids.json" def _safe(value: str) -> str: @@ -115,35 +119,36 @@ def read_verifier_rewards(verifier_dir: Path) -> dict[str, Any] | None: return None -def rollout_rewards(row: dict[str, Any], case_id: str | None) -> dict[str, Any] | None: - """Return the rewards the collector scores for a Gym rollout, read in place, or ``None`` when it is unscored. +def write_task_case_ids(gym_arm_dir: Path, task_case_ids: dict[str, str]) -> None: + """Record an arm's staged task to case map beside its rollouts, which the run keeps after removing its tasks.""" + gym_arm_dir.mkdir(parents=True, exist_ok=True) + (gym_arm_dir / TASK_CASE_IDS_FILE).write_text(json.dumps(task_case_ids, indent=2), encoding="utf-8") - The rollout passes the result normalizer's checks, including that its verifier scored the staged - ``case_id`` when that is known. A multi-step episode is rolled up from its turns; a single-step - rollout's reward sidecars are merged in as the collector merges them. - """ - turns = row.get("turns") - if turns is None: - rewards = _logged_rewards(row, case_id)[0] - if rewards is not None: - from skillevaluator.tier3.harbor.collector import _merge_reward_sidecars - _merge_reward_sidecars(rewards, Path(row["verifier_logs_dir"])) - return rewards - names = _turn_names(turns) - if names is None: - return None - return _episode_rewards(row, names, [_logged_rewards(turn, case_id) for turn in turns])[0] +def rollout_verdict( + row: dict[str, Any], task_name: str, case_id: str, pass_threshold: float, scratch_parent: Path +) -> bool | None: + """Return whether a Gym rollout passes as the finished run judges it, or ``None`` when it is unscored. + The rollout is written to a scratch job under ``scratch_parent`` as the runner writes it, then read with + the collector's reward extraction, scoreability checks and attempt verdict, as ``harbor_job_passed`` is. + """ + from skillevaluator.tier3.harbor.collector import ( + _extract_rewards, + _logical_attempt_rewards, + _overall_score, + _partition_scoreable_rewards, + ) -def _logged_rewards(row: dict[str, Any], case_id: str | None) -> tuple[dict[str, Any] | None, str]: - failure = _failure_text(row) - if failure: - return None, failure - logs_dir = row.get("verifier_logs_dir") - if not isinstance(logs_dir, str) or not logs_dir: - return None, _NO_REWARDS - return _case_rewards(read_verifier_rewards(Path(logs_dir)), case_id) + task_case_ids = {task_name: case_id} + with tempfile.TemporaryDirectory(prefix=".live-", dir=scratch_parent) as scratch: + job_dir = Path(scratch) / "job" + write_job_from_rollouts([row], job_dir, eval_name="live", task_case_ids=task_case_ids, n_attempts=1) + rewards, _failures = _partition_scoreable_rewards(_extract_rewards(job_dir, task_entry_id_map=task_case_ids)) + attempts = _logical_attempt_rewards(rewards) + if not attempts: + return None + return attempt_verdict(_overall_score(attempts[0]), pass_threshold, reward=attempts[0]).passed def _failure_text(row: dict[str, Any]) -> str: @@ -164,28 +169,19 @@ def _reported_failure_text(row: dict[str, Any]) -> str: return "" -def _case_rewards(loaded: dict[str, Any] | None, case_id: str | None) -> tuple[dict[str, Any] | None, str]: - """Return the verifier's rewards stamped with ``case_id``, or why they cannot be scored. - - An unknown ``case_id`` leaves the rewards as the verifier wrote them. - """ +def _verified_rewards(verifier_dir: Path, case_id: str) -> tuple[dict[str, Any] | None, str]: + """Return the verifier's rewards stamped with ``case_id``, or why they cannot be scored.""" + loaded = read_verifier_rewards(verifier_dir) if loaded is None: return None, _NO_REWARDS - if case_id is None: - return dict(loaded), "" loaded_entry_id = loaded.get("entry_id") if loaded_entry_id is not None and str(loaded_entry_id) != str(case_id): return None, f"the task verifier reported case {str(loaded_entry_id)!r} for staged case {str(case_id)!r}" - return {**loaded, "entry_id": case_id}, "" - - -def _verified_rewards(verifier_dir: Path, case_id: str) -> tuple[dict[str, Any] | None, str]: - """Return the trial verifier's rewards stamped with ``case_id`` and write them back, or why they are unscored.""" - rewards, failure = _case_rewards(read_verifier_rewards(verifier_dir), case_id) + rewards = {**loaded, "entry_id": case_id} reward_path = verifier_dir / "reward.json" - if rewards is not None and reward_path.is_file(): + if reward_path.is_file(): reward_path.write_text(json.dumps(rewards, indent=2), encoding="utf-8") - return rewards, failure + return rewards, "" def _turn_names(turns: Any) -> list[str] | None: diff --git a/src/skillevaluator/tier3/nemo_gym/runner.py b/src/skillevaluator/tier3/nemo_gym/runner.py index 10ef8609c..0478f2c33 100644 --- a/src/skillevaluator/tier3/nemo_gym/runner.py +++ b/src/skillevaluator/tier3/nemo_gym/runner.py @@ -54,7 +54,12 @@ nemo_gym_version, uses_native_harbor_tasks, ) -from skillevaluator.tier3.nemo_gym.results import read_rollout_failures, read_rollouts, write_job_from_rollouts +from skillevaluator.tier3.nemo_gym.results import ( + read_rollout_failures, + read_rollouts, + write_job_from_rollouts, + write_task_case_ids, +) __all__ = ["MODEL_API_KEY_ENV", "MODEL_URL_ENV", "RUN_TIMEOUT_ENV"] @@ -1181,6 +1186,7 @@ def _config_failure(detail: str) -> dict[str, Any]: }, ) task_case_ids = _task_case_ids(arm_dir) + write_task_case_ids(gym_root / f"{agent}-{arm}", task_case_ids) case_ids = case_ids or sorted(set(task_case_ids.values())) staged_task_paths += [task for task in task_paths if task.is_dir()] planned.append((agent, arm, arm_dir, task_case_ids)) diff --git a/tests/test_nemo_gym_backend.py b/tests/test_nemo_gym_backend.py index 5726a97e4..9a4fafe2a 100644 --- a/tests/test_nemo_gym_backend.py +++ b/tests/test_nemo_gym_backend.py @@ -14,6 +14,7 @@ import pytest from skillevaluator.evaluation.options import EvaluationOptions +from skillevaluator.tier3.case_summary import ERROR, PASS, live_case_marks from skillevaluator.tier3.harbor.collector import collect_harbor_results from skillevaluator.tier3.nemo_gym.backend import ( DEFAULT_EXECUTION_BACKEND, @@ -615,8 +616,11 @@ def test_nemo_gym_rejects_agent_runtime_preflight(monkeypatch: pytest.MonkeyPatc if os.environ.get("FAKE_GYM_REWARD_TXT"): (logs / "reward.txt").write_text("1\\n") else: - (logs / "reward.json").write_text(json.dumps({{"overall": 0.75}})) - (logs / "skill_evaluator_reward.json").write_text(json.dumps({{"overall": 0.75}})) + rewards = {{"overall": 0.75}} + if os.environ.get("FAKE_GYM_ENTRY_ID"): + rewards["entry_id"] = os.environ["FAKE_GYM_ENTRY_ID"] + (logs / "reward.json").write_text(json.dumps(rewards)) + (logs / "skill_evaluator_reward.json").write_text(json.dumps(rewards)) row = {{"_ng_task_id": {{"taskset": tasks.name, "task_id": task.name}}, "verifier_return_code": 0, "verifier_logs_dir": str(logs), "episode_id": {{"rollout_id": f"r{{attempt}}", "attempt": 0}}}} if os.environ.get("FAKE_GYM_FAILURE"): @@ -672,7 +676,13 @@ def _fake_gym_skill(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, config: str gym_runner, "_GYM_HOST_ENV_VARS", gym_runner._GYM_HOST_ENV_VARS - | {"FAKE_GYM_ENV_LOG", "FAKE_GYM_REWARD_TXT", "FAKE_GYM_FAILURE", "FAKE_GYM_EXTRA_ROLLOUT"}, + | { + "FAKE_GYM_ENV_LOG", + "FAKE_GYM_REWARD_TXT", + "FAKE_GYM_FAILURE", + "FAKE_GYM_EXTRA_ROLLOUT", + "FAKE_GYM_ENTRY_ID", + }, ) monkeypatch.setenv("GITHUB_TOKEN", "host-only-token") monkeypatch.setenv("ANTHROPIC_API_KEY", "host-only-key") @@ -2289,6 +2299,27 @@ def test_gym_run_starts_the_reporter_with_its_run_dir(tmp_path: Path, monkeypatc assert plan.output_dir == result["run_dir"] and plan.case_count == 2 and plan.matrix_trials == 4 +@pytest.mark.parametrize(("verified_case", "expected", "scored"), [("auth-login", PASS, 1), ("other-case", ERROR, 0)]) +def test_live_marks_keep_the_runners_case_map_after_it_removes_the_staged_tasks( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, verified_case: str, expected: str, scored: int +) -> None: + config = "schema_version: 1\nharbor:\n task_source: native_harbor\ngrading:\n mode: custom_only\n" + skill, _env_log = _fake_gym_skill(tmp_path, monkeypatch, config=config) + task_toml = _native_task(skill) / "task.toml" + task_toml.write_text(task_toml.read_text().replace('entry_id = "case-001"', 'entry_id = "auth-login"')) + monkeypatch.setenv("FAKE_GYM_ENTRY_ID", verified_case) + + result = _run_fake_gym(skill, tmp_path, skip_baseline=True) + + run_dir = Path(result["run_dir"]) + assert not (run_dir / "_harbor-tasks").exists() + arm = run_dir / "_nemo-gym" / "codex-with" + assert json.loads((arm / "task_case_ids.json").read_text()) == {"case-001": "auth-login"} + marks, _running = live_case_marks(run_dir, ["codex"], pass_threshold=0.5) + assert marks == {"codex": {"with_skill": {"case-001": [expected]}}} + assert result["agents"]["codex"]["num_trials_with"] == scored + + def test_live_marks_score_reward_logs_and_skip_normalized_gym_jobs(tmp_path: Path) -> None: from skillevaluator.tier3.case_summary import live_case_marks diff --git a/tests/tier3/test_gym_multi_step_results.py b/tests/tier3/test_gym_multi_step_results.py index c4ad46398..3171d7160 100644 --- a/tests/tier3/test_gym_multi_step_results.py +++ b/tests/tier3/test_gym_multi_step_results.py @@ -20,7 +20,7 @@ from skillevaluator.tier3.case_summary import ERROR, FAIL, PASS, case_marks, live_case_marks from skillevaluator.tier3.harbor.collector import collect_harbor_results from skillevaluator.tier3.harbor.metrics import DEFAULT_METRICS -from skillevaluator.tier3.nemo_gym.results import write_job_from_rollouts +from skillevaluator.tier3.nemo_gym.results import write_job_from_rollouts, write_task_case_ids CASES = {"case-1": "case-1"} @@ -483,24 +483,50 @@ def test_live_marks_score_multi_step_episodes_as_the_final_result_does(tmp_path: assert final == ["case case-1 attempt 3: step 'second': test.sh timed out"] -def _graded(logs: Path, goal_accuracy: float, *, entry_id: str | None = None, **sidecar: Any) -> None: - rewards: dict[str, Any] = {**dict.fromkeys(DEFAULT_METRICS, 1.0), "goal_accuracy": goal_accuracy, "overall": 0.95} +def _graded( + logs: Path, goal_accuracy: float, *, entry_id: str | None = None, overall: float = 0.95, **sidecar: Any +) -> None: + rewards: dict[str, Any] = { + **dict.fromkeys(DEFAULT_METRICS, 1.0), + "goal_accuracy": goal_accuracy, + "overall": overall, + } if entry_id is not None: rewards["entry_id"] = entry_id (logs / "reward.json").write_text(json.dumps(rewards), encoding="utf-8") (logs / "skill_evaluator_reward.json").write_text(json.dumps(rewards | sidecar), encoding="utf-8") -def _graded_turn(base: Path, name: str, goal_accuracy: float, entry_id: str | None = None) -> dict[str, Any]: - turn = _turn(base, name, 0.95) - _graded(Path(turn["verifier_logs_dir"]), goal_accuracy, entry_id=entry_id) +def _graded_turn( + base: Path, name: str, goal_accuracy: float, entry_id: str | None = None, overall: float = 0.95 +) -> dict[str, Any]: + turn = _turn(base, name, overall) + _graded(Path(turn["verifier_logs_dir"]), goal_accuracy, entry_id=entry_id, overall=overall) return turn -def _live_and_final_marks(out: Path, jobs: Path, rows: list[dict[str, Any]]) -> tuple[list[str], list[str]]: +def _judge_failed(logs: Path) -> dict[str, Any]: + """Write what the built-in verifier writes when a required judge fails, and return how Gym records its exit.""" + scores: dict[str, Any] = {**dict.fromkeys(DEFAULT_METRICS, 1.0), "accuracy": None} + rewards = {metric: score for metric, score in scores.items() if score is not None} | {"overall": 0.0} + (logs / "reward.json").write_text(json.dumps(rewards), encoding="utf-8") + sidecar = scores | { + "details": {"accuracy": {"score": None, "status": "error", "reason": "judge request timed out"}}, + "evaluation_status": "failed", + "evaluation_errors": {"accuracy": "judge request timed out"}, + } + (logs / "skill_evaluator_reward.json").write_text(json.dumps(sidecar), encoding="utf-8") + return {"reward": 0.0, "verifier_rewards": rewards, "verifier_return_code": 1, "verifier_logs_dir": str(logs)} + + +def _live_arm(out: Path, rows: list[dict[str, Any]]) -> None: arm = out / "_nemo-gym" / "codex-with" - arm.mkdir(parents=True) + write_task_case_ids(arm, {"login-task": "auth-login"}) (arm / "rollouts.jsonl").write_text("".join(json.dumps(row) + "\n" for row in rows), encoding="utf-8") + + +def _live_and_final_marks(out: Path, jobs: Path, rows: list[dict[str, Any]]) -> tuple[list[str], list[str]]: + _live_arm(out, rows) live, running = live_case_marks(out, ["codex"], pass_threshold=0.5) assert running == set() write_job_from_rollouts( @@ -535,33 +561,57 @@ def episode(label: str, goal_accuracy: float, second_entry_id: str | None = None ] return _episode(turns, task="login-task", turn_reward_strategy=strategy) + judged = _graded_turn(tmp_path / "judge-failed", "first", 1.0, overall=1.0) + failed_judge = _turn(tmp_path / "judge-failed", "second", 1.0) + failed_judge |= _judge_failed(Path(failed_judge["verifier_logs_dir"])) rows = [ episode("goal-met", 1.0), # Overall clears the threshold, but standard grading requires the goal. episode("goal-missed", 0.5), episode("other-case", 1.0, second_entry_id="other-case"), episode("staged-case", 1.0, second_entry_id="auth-login"), + # Under mean the two steps still reach the threshold, but a step's required judge failed. + _episode([judged, failed_judge], task="login-task", turn_reward_strategy=strategy), ] live, final = _live_and_final_marks(out, jobs, rows) - assert live == [PASS, FAIL, ERROR, PASS] + assert live == [PASS, FAIL, ERROR, PASS, ERROR] assert sorted(live) == sorted(final) -def test_live_marks_keep_a_verified_case_after_its_staged_task_is_removed(tmp_path: Path) -> None: +def test_live_marks_keep_the_staged_case_after_the_staged_tasks_are_removed(tmp_path: Path) -> None: out = tmp_path / "out" _stage_native_task(out, "with") - turns = [_graded_turn(tmp_path, name, 1.0, "auth-login") for name in ("first", "second")] - arm = out / "_nemo-gym" / "codex-with" - arm.mkdir(parents=True) - (arm / "rollouts.jsonl").write_text(json.dumps(_episode(turns, task="login-task")) + "\n", encoding="utf-8") + rows = [ + _episode([_graded_turn(tmp_path / case, name, 1.0, case) for name in ("first", "second")], task="login-task") + for case in ("auth-login", "other-case") + ] + _live_arm(out, rows) # The run removes its staged tasks before the live view stops polling. shutil.rmtree(out / "_harbor-tasks") marks, _running = live_case_marks(out, ["codex"], pass_threshold=0.5) - assert marks == {"codex": {"with_skill": {"login-task": [PASS]}}} + assert marks == {"codex": {"with_skill": {"login-task": [PASS, ERROR]}}} + + +def test_live_marks_judge_each_rollout_once_and_leave_no_scratch( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + from skillevaluator.tier3.nemo_gym import results + + out = tmp_path / "out" + _live_arm(out, [_episode([_graded_turn(tmp_path, name, 1.0) for name in ("first", "second")], task="login-task")]) + judged: list[str] = [] + verdict = results.rollout_verdict + monkeypatch.setattr(results, "rollout_verdict", lambda row, *args: judged.append(args[0]) or verdict(row, *args)) + + polls = [live_case_marks(out, ["codex"], pass_threshold=0.5)[0] for _ in range(2)] + + assert polls == [{"codex": {"with_skill": {"login-task": [PASS]}}}] * 2 + assert judged == ["login-task"] + assert [path.name for path in (out / "_nemo-gym").iterdir()] == ["codex-with"] def test_live_marks_apply_the_final_verdict_and_staged_case_to_single_steps(tmp_path: Path) -> None: @@ -575,14 +625,17 @@ def rollout(label: str, goal_accuracy: float, **reward: Any) -> dict[str, Any]: return {"task_id": "login-task", "verifier_return_code": 0, "verifier_logs_dir": str(logs)} not_applicable = {"details": {"goal_accuracy": {"status": "not_applicable"}}} + judge_failed = tmp_path / "judge-failed" + judge_failed.mkdir() rows = [ rollout("goal-missed", 0.5), rollout("other-case", 1.0, entry_id="other-case"), # The collector reads the sidecar's N/A goal back into the reward, so only Overall decides. rollout("goal-not-applicable", 0.0, **not_applicable), + {"task_id": "login-task", **_judge_failed(judge_failed)}, ] live, final = _live_and_final_marks(out, jobs, rows) - assert live == [FAIL, ERROR, PASS] + assert live == [FAIL, ERROR, PASS, ERROR] assert sorted(live) == sorted(final) From 5e94c77cee4f8443488550f3bac7b15dfb626436 Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Sat, 21 Nov 2026 15:02:21 -0800 Subject: [PATCH 06/10] fix(nemo-gym): judge live Gym attempts without writing to the run folder The live case grid judged each Gym attempt in a scratch job that it created under _nemo-gym in the run folder, and it filled that job with everything the runner publishes, including every step's trajectory and verifier stdout. When the poll could not write to _nemo-gym, it showed no case rows. When it could, its first poll of each rollout copied trajectories and logs that the verdict never reads. The scratch job now lives in the system temporary folder, so the live view only reads the run folder. It holds only the files the attempt verdict reads: the reward files, and a single-step trajectory small enough for the collector to read, which it checks for an agent that never started. Step trajectories and verifier stdout are left out. The verdict still comes from the collector's own checks, so the live grid and the finished grid still agree. Signed-off-by: Deepak Jain --- src/skillevaluator/tier3/case_summary.py | 6 +- src/skillevaluator/tier3/nemo_gym/results.py | 50 +++++++---- tests/tier3/test_gym_multi_step_results.py | 90 +++++++++++++++++++- 3 files changed, 124 insertions(+), 22 deletions(-) diff --git a/src/skillevaluator/tier3/case_summary.py b/src/skillevaluator/tier3/case_summary.py index 8bcbd2513..454bbce30 100644 --- a/src/skillevaluator/tier3/case_summary.py +++ b/src/skillevaluator/tier3/case_summary.py @@ -1620,14 +1620,14 @@ def _live_mark(trial: Path, run_dir: Path, pass_threshold: float) -> str | None: return ERROR -def _gym_live_mark(row: dict[str, Any], task: str, case_id: str, gym_root: Path, pass_threshold: float) -> str: +def _gym_live_mark(row: dict[str, Any], task: str, case_id: str, pass_threshold: float) -> str: from skillevaluator.tier3.nemo_gym.results import rollout_verdict # Gym appends a rollout only once its verifier logs are written, so each line is judged once. key = hashlib.sha256(json.dumps([row, task, case_id, pass_threshold], sort_keys=True).encode()).hexdigest() mark = _GYM_LIVE_MARKS.get(key) if mark is None: - passed = rollout_verdict(row, task, case_id, pass_threshold, gym_root) + passed = rollout_verdict(row, task, case_id, pass_threshold) mark = ERROR if passed is None else PASS if passed else FAIL if len(_GYM_LIVE_MARKS) >= _MAX_GYM_LIVE_MARKS: _GYM_LIVE_MARKS.clear() @@ -1664,7 +1664,7 @@ def _add_gym_live_marks( case_id = case_ids.get(task) if not isinstance(case_id, str) or not case_id: case_id = task - mark = _gym_live_mark(row, task, case_id, gym_root, pass_threshold) + mark = _gym_live_mark(row, task, case_id, pass_threshold) marks.setdefault(agent, {}).setdefault(key, {}).setdefault(task, []).append(mark) return True diff --git a/src/skillevaluator/tier3/nemo_gym/results.py b/src/skillevaluator/tier3/nemo_gym/results.py index 9ea2a6e6e..6e7addd2a 100644 --- a/src/skillevaluator/tier3/nemo_gym/results.py +++ b/src/skillevaluator/tier3/nemo_gym/results.py @@ -29,7 +29,8 @@ from skillevaluator.tier3.attempt_verdict import attempt_verdict _UNSAFE = re.compile(r"[^A-Za-z0-9._-]+") -_VERIFIER_FILES = ("reward.json", "reward.txt", "skill_evaluator_reward.json", "custom_reward.json", "test-stdout.txt") +_REWARD_FILES = ("reward.json", "reward.txt", "skill_evaluator_reward.json", "custom_reward.json") +_VERIFIER_FILES = (*_REWARD_FILES, "test-stdout.txt") _TURN_REWARD_STRATEGIES = ("mean", "final") _TURN_METADATA = ("turn_sessions", "turn_reward_strategy", "stopped_after_turn", "turns_without_verifier_result") _NO_REWARDS = "the task verifier wrote no reward.json or numeric reward.txt" @@ -125,13 +126,12 @@ def write_task_case_ids(gym_arm_dir: Path, task_case_ids: dict[str, str]) -> Non (gym_arm_dir / TASK_CASE_IDS_FILE).write_text(json.dumps(task_case_ids, indent=2), encoding="utf-8") -def rollout_verdict( - row: dict[str, Any], task_name: str, case_id: str, pass_threshold: float, scratch_parent: Path -) -> bool | None: +def rollout_verdict(row: dict[str, Any], task_name: str, case_id: str, pass_threshold: float) -> bool | None: """Return whether a Gym rollout passes as the finished run judges it, or ``None`` when it is unscored. - The rollout is written to a scratch job under ``scratch_parent`` as the runner writes it, then read with - the collector's reward extraction, scoreability checks and attempt verdict, as ``harbor_job_passed`` is. + The rollout is written as the runner writes it, with only the files the verdict reads, to a scratch job + in the system temporary folder, so the run folder is only read. The job is then read with the + collector's reward extraction, scoreability checks and attempt verdict, as ``harbor_job_passed`` is. """ from skillevaluator.tier3.harbor.collector import ( _extract_rewards, @@ -141,9 +141,11 @@ def rollout_verdict( ) task_case_ids = {task_name: case_id} - with tempfile.TemporaryDirectory(prefix=".live-", dir=scratch_parent) as scratch: + with tempfile.TemporaryDirectory(prefix="skillevaluator-gym-live-") as scratch: job_dir = Path(scratch) / "job" - write_job_from_rollouts([row], job_dir, eval_name="live", task_case_ids=task_case_ids, n_attempts=1) + write_job_from_rollouts( + [row], job_dir, eval_name="live", task_case_ids=task_case_ids, n_attempts=1, verdict_only=True + ) rewards, _failures = _partition_scoreable_rewards(_extract_rewards(job_dir, task_entry_id_map=task_case_ids)) attempts = _logical_attempt_rewards(rewards) if not attempts: @@ -254,7 +256,7 @@ def _episode_rewards( def _multi_step_outcome( - row: dict[str, Any], trial_dir: Path, case_id: str + row: dict[str, Any], trial_dir: Path, case_id: str, *, verdict_only: bool = False ) -> tuple[dict[str, Any] | None, str, dict[str, Any]]: """Write a multi-step episode's steps and return its rewards, why it is unscored, and its result fields. @@ -273,7 +275,7 @@ def _multi_step_outcome( step_dir = trial_dir / "steps" / name logs_dir = turn.get("verifier_logs_dir") if isinstance(logs_dir, str) and Path(logs_dir).is_dir(): - _copy_verifier_logs(Path(logs_dir), step_dir) + _copy_verifier_logs(Path(logs_dir), step_dir, verdict_only=verdict_only, step=True) step_failure = _failure_text(turn) steps.append(_verified_rewards(step_dir / "verifier", case_id) if not step_failure else (None, step_failure)) fields["step_results"] = [ @@ -290,17 +292,27 @@ def _multi_step_outcome( return ({**rewards, "entry_id": case_id} if rewards is not None else None), failure, fields -def _copy_verifier_logs(logs_dir: Path, trial_dir: Path) -> None: +def _copy_verifier_logs(logs_dir: Path, trial_dir: Path, *, verdict_only: bool = False, step: bool = False) -> None: + """Copy a Gym verifier's files and trajectory into a trial or into one of its step folders. + + With ``verdict_only``, copy only what the attempt verdict reads: the reward files, and a trial's own + trajectory when it is small enough for the collector to read and check for an agent that never started. + """ + from skillevaluator.tier3.harbor.collector import DEFAULT_DIAGNOSTIC_ARTIFACT_MAX_BYTES + verifier_dir = trial_dir / "verifier" verifier_dir.mkdir(parents=True, exist_ok=True) - for name in _VERIFIER_FILES: + for name in _REWARD_FILES if verdict_only else _VERIFIER_FILES: source = logs_dir / name if source.is_file() and not source.is_symlink(): shutil.copyfile(source, verifier_dir / name) trajectory = logs_dir / "trajectory.json" - if trajectory.is_file() and not trajectory.is_symlink(): - (trial_dir / "agent").mkdir(parents=True, exist_ok=True) - shutil.copyfile(trajectory, trial_dir / "agent" / "trajectory.json") + if not trajectory.is_file() or trajectory.is_symlink(): + return + if verdict_only and (step or trajectory.stat().st_size > DEFAULT_DIAGNOSTIC_ARTIFACT_MAX_BYTES): + return + (trial_dir / "agent").mkdir(parents=True, exist_ok=True) + shutil.copyfile(trajectory, trial_dir / "agent" / "trajectory.json") def write_job_from_rollouts( @@ -311,10 +323,12 @@ def write_job_from_rollouts( task_case_ids: dict[str, str], n_attempts: int, failures: dict[str, list[str]] | None = None, + verdict_only: bool = False, ) -> list[str]: """Write one collector job directory from Gym rollouts and return the run errors. - ``task_case_ids`` maps each staged task folder name to its evals.json case id. + ``task_case_ids`` maps each staged task folder name to its evals.json case id. With ``verdict_only``, + a trial gets only the verifier files its attempt verdict reads, not the evidence a report publishes. """ job_dir.mkdir(parents=True, exist_ok=True) errors: list[str] = [] @@ -352,11 +366,11 @@ def write_job_from_rollouts( rewards: dict[str, Any] | None = None step_fields: dict[str, Any] = {} if row.get("turns") is not None: - rewards, failure, step_fields = _multi_step_outcome(row, trial_dir, case_id) + rewards, failure, step_fields = _multi_step_outcome(row, trial_dir, case_id, verdict_only=verdict_only) else: logs_dir = row.get("verifier_logs_dir") if isinstance(logs_dir, str) and Path(logs_dir).is_dir(): - _copy_verifier_logs(Path(logs_dir), trial_dir) + _copy_verifier_logs(Path(logs_dir), trial_dir, verdict_only=verdict_only) failure = _failure_text(row) if not failure: rewards, failure = _verified_rewards(trial_dir / "verifier", case_id) diff --git a/tests/tier3/test_gym_multi_step_results.py b/tests/tier3/test_gym_multi_step_results.py index 3171d7160..9a7ec66d9 100644 --- a/tests/tier3/test_gym_multi_step_results.py +++ b/tests/tier3/test_gym_multi_step_results.py @@ -11,14 +11,16 @@ from __future__ import annotations import json +import os import shutil +import tempfile from pathlib import Path from typing import Any import pytest from skillevaluator.tier3.case_summary import ERROR, FAIL, PASS, case_marks, live_case_marks -from skillevaluator.tier3.harbor.collector import collect_harbor_results +from skillevaluator.tier3.harbor.collector import DEFAULT_DIAGNOSTIC_ARTIFACT_MAX_BYTES, collect_harbor_results from skillevaluator.tier3.harbor.metrics import DEFAULT_METRICS from skillevaluator.tier3.nemo_gym.results import write_job_from_rollouts, write_task_case_ids @@ -614,6 +616,70 @@ def test_live_marks_judge_each_rollout_once_and_leave_no_scratch( assert [path.name for path in (out / "_nemo-gym").iterdir()] == ["codex-with"] +def _graded_rollout(logs: Path, trajectory_bytes: int = 0) -> dict[str, Any]: + logs.mkdir() + _graded(logs, 1.0) + trajectory = json.dumps(_trajectory(logs.name)).ljust(trajectory_bytes) + (logs / "trajectory.json").write_text(trajectory, encoding="utf-8") + (logs / "test-stdout.txt").write_text("verifier output\n", encoding="utf-8") + return {"task_id": "login-task", "verifier_return_code": 0, "verifier_logs_dir": str(logs)} + + +def test_live_marks_need_no_write_access_to_the_run_folder(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + out, scratch = tmp_path / "out", tmp_path / "scratch" + scratch.mkdir() + monkeypatch.setattr(tempfile, "tempdir", str(scratch)) + episode = _episode([_graded_turn(tmp_path, name, 1.0) for name in ("first", "second")], task="login-task") + _live_arm(out, [episode, _graded_rollout(tmp_path / "single")]) + gym_root = out / "_nemo-gym" + for folder in (gym_root / "codex-with", gym_root): + folder.chmod(0o555) + try: + if os.access(gym_root, os.W_OK): + pytest.skip("this account can write to a read-only folder") + marks, _running = live_case_marks(out, ["codex"], pass_threshold=0.5) + finally: + for folder in (gym_root, gym_root / "codex-with"): + folder.chmod(0o755) + + assert marks == {"codex": {"with_skill": {"login-task": [PASS, PASS]}}} + assert list(scratch.iterdir()) == [] + + +def test_live_marks_copy_only_what_the_verdict_reads(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + out = tmp_path / "out" + episode = _episode( + [_graded_turn(tmp_path / "episode", name, 1.0) for name in ("first", "second")], task="login-task" + ) + rows = [ + episode, + _graded_rollout(tmp_path / "small"), + # The collector reads no more of a trajectory than this, so a larger one cannot change the verdict. + _graded_rollout(tmp_path / "large", DEFAULT_DIAGNOSTIC_ARTIFACT_MAX_BYTES + 1), + ] + _live_arm(out, rows) + copied: list[str] = [] + copyfile = shutil.copyfile + + def record(source: Path, target: Path) -> Any: + copied.append(Path(source).relative_to(tmp_path).as_posix()) + return copyfile(source, target) + + monkeypatch.setattr(shutil, "copyfile", record) + + marks, _running = live_case_marks(out, ["codex"], pass_threshold=0.5) + + assert marks == {"codex": {"with_skill": {"login-task": [PASS, PASS, PASS]}}} + rewards = ("reward.json", "skill_evaluator_reward.json") + assert sorted(copied) == sorted( + [ + *(f"episode/gym-logs/{step}/{name}" for step in ("first", "second") for name in rewards), + *(f"{label}/{name}" for label in ("small", "large") for name in rewards), + "small/trajectory.json", + ] + ) + + def test_live_marks_apply_the_final_verdict_and_staged_case_to_single_steps(tmp_path: Path) -> None: out, jobs = tmp_path / "out", tmp_path / "jobs" _stage_native_task(out, "with") @@ -639,3 +705,25 @@ def rollout(label: str, goal_accuracy: float, **reward: Any) -> dict[str, Any]: assert live == [FAIL, ERROR, PASS, ERROR] assert sorted(live) == sorted(final) + + +def test_live_marks_still_read_the_trajectory_of_an_agent_that_never_started(tmp_path: Path) -> None: + out, jobs = tmp_path / "out", tmp_path / "jobs" + _stage_native_task(out, "with") + row = _graded_rollout(tmp_path / "never-started") + # A tokenless trajectory that names an auth failure is an agent that never started, which stays unscored. + tokenless = _trajectory("never-started") | {"final_metrics": {}} + tokenless["steps"][0]["message"] = "API Error: 401 Unauthorized" + Path(row["verifier_logs_dir"], "trajectory.json").write_text(json.dumps(tokenless), encoding="utf-8") + _live_arm(out, [row]) + + marks, _running = live_case_marks(out, ["codex"], pass_threshold=0.5) + + assert marks == {"codex": {"with_skill": {"login-task": [ERROR]}}} + write_job_from_rollouts( + [row], jobs / "demo-codex-with", eval_name="codex__m", task_case_ids={"login-task": "auth-login"}, n_attempts=1 + ) + results = collect_harbor_results( + "demo", ["codex"], out, jobs, skip_baseline=True, expected_cases=1, expected_case_ids=["auth-login"] + ) + assert results["agents"]["codex"]["scored_attempts"] == 0 From ec5fc221027c16da6b22bf03acc42ee318a369d4 Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Sat, 21 Nov 2026 20:18:31 -0800 Subject: [PATCH 07/10] fix(nemo-gym): keep the polled run's live verdicts past the cache cap The live case grid kept every Gym verdict in one cache and cleared all of it once it reached 65,536 entries. Each poll walks every rollout in order, so a run with more rollouts than that refilled the cache from the start on every refresh and built a scratch job again for rollouts it had already judged. The cache now holds each run's verdicts for the rollouts its last poll read, so a poll judges only the rollouts Gym appended since the one before, however many the run holds. Once the kept verdicts pass the cap, the runs polled longest ago are dropped. The run being polled is never dropped, and it keeps one verdict per rollout it holds. Signed-off-by: Deepak Jain --- src/skillevaluator/tier3/case_summary.py | 38 ++++++++++++++++++---- tests/tier3/test_gym_multi_step_results.py | 31 ++++++++++++++++++ 2 files changed, 62 insertions(+), 7 deletions(-) diff --git a/src/skillevaluator/tier3/case_summary.py b/src/skillevaluator/tier3/case_summary.py index 454bbce30..727871fbc 100644 --- a/src/skillevaluator/tier3/case_summary.py +++ b/src/skillevaluator/tier3/case_summary.py @@ -1591,7 +1591,8 @@ def load_case_marks(run_dir: Path) -> dict[str, dict[str, dict[str, list[str]]]] _LIVE_VARIANTS = {"with": "with_skill", "without": "without_skill"} -_GYM_LIVE_MARKS: dict[str, str] = {} +# Gym run folder -> mark of each rollout its last poll read, the least recently polled run first. +_GYM_LIVE_MARKS: dict[str, dict[str, str]] = {} _MAX_GYM_LIVE_MARKS = 65536 @@ -1620,21 +1621,41 @@ def _live_mark(trial: Path, run_dir: Path, pass_threshold: float) -> str | None: return ERROR -def _gym_live_mark(row: dict[str, Any], task: str, case_id: str, pass_threshold: float) -> str: +def _gym_live_mark( + row: dict[str, Any], + task: str, + case_id: str, + pass_threshold: float, + judged: Mapping[str, str], + seen: dict[str, str], +) -> str: from skillevaluator.tier3.nemo_gym.results import rollout_verdict # Gym appends a rollout only once its verifier logs are written, so each line is judged once. key = hashlib.sha256(json.dumps([row, task, case_id, pass_threshold], sort_keys=True).encode()).hexdigest() - mark = _GYM_LIVE_MARKS.get(key) + mark = seen.get(key) or judged.get(key) if mark is None: passed = rollout_verdict(row, task, case_id, pass_threshold) mark = ERROR if passed is None else PASS if passed else FAIL - if len(_GYM_LIVE_MARKS) >= _MAX_GYM_LIVE_MARKS: - _GYM_LIVE_MARKS.clear() - _GYM_LIVE_MARKS[key] = mark + seen[key] = mark return mark +def _keep_gym_live_marks(run: str, seen: dict[str, str]) -> None: + """Keep the verdicts of the rollouts a Gym run holds now for its next poll. + + Past ``_MAX_GYM_LIVE_MARKS`` verdicts, the runs polled longest ago are dropped; the run just polled + keeps all of its verdicts, so a poll judges only the rollouts appended since the last one. + """ + _GYM_LIVE_MARKS.pop(run, None) + _GYM_LIVE_MARKS[run] = seen + kept = sum(len(marks) for marks in list(_GYM_LIVE_MARKS.values())) + for other in [other for other in list(_GYM_LIVE_MARKS) if other != run]: + if kept <= _MAX_GYM_LIVE_MARKS: + break + kept -= len(_GYM_LIVE_MARKS.pop(other, {})) + + def _add_gym_live_marks( run_dir: Path, agents: list[str], marks: dict[str, dict[str, dict[str, list[str]]]], pass_threshold: float ) -> bool: @@ -1648,6 +1669,8 @@ def _add_gym_live_marks( gym_root = run_dir / "_nemo-gym" if not gym_root.is_dir() or gym_root.is_symlink(): return False + judged = _GYM_LIVE_MARKS.get(str(gym_root), {}) + seen: dict[str, str] = {} for agent in agents: for variant, key in _LIVE_VARIANTS.items(): arm = gym_root / f"{agent}-{variant}" @@ -1664,8 +1687,9 @@ def _add_gym_live_marks( case_id = case_ids.get(task) if not isinstance(case_id, str) or not case_id: case_id = task - mark = _gym_live_mark(row, task, case_id, pass_threshold) + mark = _gym_live_mark(row, task, case_id, pass_threshold, judged, seen) marks.setdefault(agent, {}).setdefault(key, {}).setdefault(task, []).append(mark) + _keep_gym_live_marks(str(gym_root), seen) return True diff --git a/tests/tier3/test_gym_multi_step_results.py b/tests/tier3/test_gym_multi_step_results.py index 9a7ec66d9..a03fdd92b 100644 --- a/tests/tier3/test_gym_multi_step_results.py +++ b/tests/tier3/test_gym_multi_step_results.py @@ -616,6 +616,37 @@ def test_live_marks_judge_each_rollout_once_and_leave_no_scratch( assert [path.name for path in (out / "_nemo-gym").iterdir()] == ["codex-with"] +def test_live_marks_keep_the_polled_runs_verdicts_past_the_cache_cap( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + from skillevaluator.tier3 import case_summary + from skillevaluator.tier3.nemo_gym import results + + monkeypatch.setattr(case_summary, "_GYM_LIVE_MARKS", {}) + monkeypatch.setattr(case_summary, "_MAX_GYM_LIVE_MARKS", 2) + judged: list[str] = [] + verdict = results.rollout_verdict + monkeypatch.setattr(results, "rollout_verdict", lambda row, *args: judged.append(args[0]) or verdict(row, *args)) + out = tmp_path / "out" + rows = [_graded_rollout(tmp_path / f"rollout-{index}") for index in range(3)] + + judged_per_poll = [] + for count in (2, 2, 3, 3, 3): + _live_arm(out, rows[:count]) + before = len(judged) + marks, _running = live_case_marks(out, ["codex"], pass_threshold=0.5) + judged_per_poll.append(len(judged) - before) + assert marks == {"codex": {"with_skill": {"login-task": [PASS] * count}}} + + # The run being polled keeps every verdict, even with more rollouts than the cap. + assert judged_per_poll == [2, 0, 1, 0, 0] + # Past the cap, a run that is no longer polled gives up its verdicts. + other = tmp_path / "other" + _live_arm(other, [_graded_rollout(tmp_path / "other-rollout")]) + live_case_marks(other, ["codex"], pass_threshold=0.5) + assert list(case_summary._GYM_LIVE_MARKS) == [str(other / "_nemo-gym")] + + def _graded_rollout(logs: Path, trajectory_bytes: int = 0) -> dict[str, Any]: logs.mkdir() _graded(logs, 1.0) From eb63db92e089cfa243b6674c85020f56c05bb307 Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Sun, 22 Nov 2026 22:59:51 -0800 Subject: [PATCH 08/10] fix(nemo-gym): redact credentials from turn diagnostics MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A verifier that wrote no reward could leave a configured credential in the run summary and published trial even though the launch error masked it. Apply the arm’s credential redaction when building failure records and copying verifier stdout. Keep the diagnostic text and line breaks so the failed step can still be investigated. Signed-off-by: Deepak Jain --- .gitleaksignore | 2 + CHANGELOG.md | 3 +- src/skillevaluator/tier3/harbor/collector.py | 5 ++ src/skillevaluator/tier3/nemo_gym/results.py | 36 +++++++++++--- src/skillevaluator/tier3/nemo_gym/runner.py | 18 +------ tests/test_nemo_gym_backend.py | 51 +++++++++++++++++++- 6 files changed, 89 insertions(+), 26 deletions(-) diff --git a/.gitleaksignore b/.gitleaksignore index 82f53173a..e8a22c51a 100644 --- a/.gitleaksignore +++ b/.gitleaksignore @@ -1,3 +1,5 @@ 08b38a1d499d894b009a761a5db04b818ef1af70:tests/reporting/test_tier3_failure_reasons.py:curl-auth-user:581 # Synthetic escaped-quote curl fixture from the preserved author commit. ccd7363b0ea3377781bc391f788a4f614deebc9b:tests/tier3/test_security_finding_evidence.py:curl-auth-user:1274 +# Synthetic policy key in the original Gym turn-diagnostics regression test. +8ba95ad23ca2f00fa6fae270bbb7d4589dbd1b11:tests/test_nemo_gym_backend.py:generic-api-key:2063 diff --git a/CHANGELOG.md b/CHANGELOG.md index 8fa234f3b..48c3266a4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -211,7 +211,8 @@ notes below describe the new policy and backend configuration behavior. `final` attempt credits only the last step's judges. Published multi-step trials, from Gym or Harbor, keep each step's redacted trajectory and verifier output under `steps//`, so the evidence survives job cleanup and a - partial attempt keeps the steps that ran. + partial attempt keeps the steps that ran. Gym masks configured credentials in + step failure messages and published verifier output. - Bound declarative output-pattern checks with isolated Python regex workers and a shared matching budget, preserving Python regex semantics and later checks. Interpreter startup and JSON transfer have a separate startup allowance and do not consume diff --git a/src/skillevaluator/tier3/harbor/collector.py b/src/skillevaluator/tier3/harbor/collector.py index 07f8380ba..6791f60df 100644 --- a/src/skillevaluator/tier3/harbor/collector.py +++ b/src/skillevaluator/tier3/harbor/collector.py @@ -1302,6 +1302,7 @@ def _write_redacted_text_copy( dest: Path, *, source_root: Path | None = None, + secret_values: set[str] | None = None, ) -> tuple[bool, dict[str, Any] | None]: """Copy a Harbor text artifact while masking common credential shapes.""" max_bytes = _diagnostic_artifact_max_bytes() @@ -1349,6 +1350,10 @@ def _write_redacted_text_copy( except UnicodeDecodeError as e: logger.debug("Failed to read Harbor artifact %s: %s", src, e) return False, {"name": src.name, "reason": "read_failed", "size_bytes": size_bytes} + if secret_values: + from skillevaluator.tier3.harbor.stream_redaction import StreamingSecretRedactor + + text = StreamingSecretRedactor(secret_values).feed(text, final=True) redacted = _redacted_artifact_text(src, text) if redacted is None: return False, {"name": src.name, "reason": "invalid_json", "size_bytes": size_bytes} diff --git a/src/skillevaluator/tier3/nemo_gym/results.py b/src/skillevaluator/tier3/nemo_gym/results.py index 6e7addd2a..a64368ae5 100644 --- a/src/skillevaluator/tier3/nemo_gym/results.py +++ b/src/skillevaluator/tier3/nemo_gym/results.py @@ -27,6 +27,7 @@ from typing import Any from skillevaluator.tier3.attempt_verdict import attempt_verdict +from skillevaluator.tier3.harbor.progress import redact_progress_detail _UNSAFE = re.compile(r"[^A-Za-z0-9._-]+") _REWARD_FILES = ("reward.json", "reward.txt", "skill_evaluator_reward.json", "custom_reward.json") @@ -256,7 +257,7 @@ def _episode_rewards( def _multi_step_outcome( - row: dict[str, Any], trial_dir: Path, case_id: str, *, verdict_only: bool = False + row: dict[str, Any], trial_dir: Path, case_id: str, *, verdict_only: bool, secret_values: set[str] | None ) -> tuple[dict[str, Any] | None, str, dict[str, Any]]: """Write a multi-step episode's steps and return its rewards, why it is unscored, and its result fields. @@ -275,9 +276,14 @@ def _multi_step_outcome( step_dir = trial_dir / "steps" / name logs_dir = turn.get("verifier_logs_dir") if isinstance(logs_dir, str) and Path(logs_dir).is_dir(): - _copy_verifier_logs(Path(logs_dir), step_dir, verdict_only=verdict_only, step=True) + _copy_verifier_logs( + Path(logs_dir), step_dir, verdict_only=verdict_only, step=True, secret_values=secret_values + ) step_failure = _failure_text(turn) - steps.append(_verified_rewards(step_dir / "verifier", case_id) if not step_failure else (None, step_failure)) + rewards, failure = (None, step_failure) if step_failure else _verified_rewards(step_dir / "verifier", case_id) + if failure and secret_values is not None: + failure = redact_progress_detail(failure, secret_values=secret_values) + steps.append((rewards, failure)) fields["step_results"] = [ { "step_name": name, @@ -292,20 +298,27 @@ def _multi_step_outcome( return ({**rewards, "entry_id": case_id} if rewards is not None else None), failure, fields -def _copy_verifier_logs(logs_dir: Path, trial_dir: Path, *, verdict_only: bool = False, step: bool = False) -> None: +def _copy_verifier_logs( + logs_dir: Path, trial_dir: Path, *, verdict_only: bool, secret_values: set[str] | None, step: bool = False +) -> None: """Copy a Gym verifier's files and trajectory into a trial or into one of its step folders. With ``verdict_only``, copy only what the attempt verdict reads: the reward files, and a trial's own trajectory when it is small enough for the collector to read and check for an agent that never started. """ - from skillevaluator.tier3.harbor.collector import DEFAULT_DIAGNOSTIC_ARTIFACT_MAX_BYTES + from skillevaluator.tier3.harbor.collector import DEFAULT_DIAGNOSTIC_ARTIFACT_MAX_BYTES, _write_redacted_text_copy verifier_dir = trial_dir / "verifier" verifier_dir.mkdir(parents=True, exist_ok=True) for name in _REWARD_FILES if verdict_only else _VERIFIER_FILES: source = logs_dir / name if source.is_file() and not source.is_symlink(): - shutil.copyfile(source, verifier_dir / name) + if name == "test-stdout.txt" and secret_values: + _write_redacted_text_copy( + source, verifier_dir / name, source_root=logs_dir, secret_values=secret_values + ) + else: + shutil.copyfile(source, verifier_dir / name) trajectory = logs_dir / "trajectory.json" if not trajectory.is_file() or trajectory.is_symlink(): return @@ -324,6 +337,7 @@ def write_job_from_rollouts( n_attempts: int, failures: dict[str, list[str]] | None = None, verdict_only: bool = False, + secret_values: set[str] | None = None, ) -> list[str]: """Write one collector job directory from Gym rollouts and return the run errors. @@ -366,15 +380,21 @@ def write_job_from_rollouts( rewards: dict[str, Any] | None = None step_fields: dict[str, Any] = {} if row.get("turns") is not None: - rewards, failure, step_fields = _multi_step_outcome(row, trial_dir, case_id, verdict_only=verdict_only) + rewards, failure, step_fields = _multi_step_outcome( + row, trial_dir, case_id, verdict_only=verdict_only, secret_values=secret_values + ) else: logs_dir = row.get("verifier_logs_dir") if isinstance(logs_dir, str) and Path(logs_dir).is_dir(): - _copy_verifier_logs(Path(logs_dir), trial_dir, verdict_only=verdict_only) + _copy_verifier_logs( + Path(logs_dir), trial_dir, verdict_only=verdict_only, secret_values=secret_values + ) failure = _failure_text(row) if not failure: rewards, failure = _verified_rewards(trial_dir / "verifier", case_id) if rewards is None: + if secret_values is not None: + failure = redact_progress_detail(failure, secret_values=secret_values) n_errors += 1 if not row.get(_MISSING_ROLLOUT): errors.append(f"case {case_id} attempt {attempt}: {failure}") diff --git a/src/skillevaluator/tier3/nemo_gym/runner.py b/src/skillevaluator/tier3/nemo_gym/runner.py index 0478f2c33..06ee61be3 100644 --- a/src/skillevaluator/tier3/nemo_gym/runner.py +++ b/src/skillevaluator/tier3/nemo_gym/runner.py @@ -743,21 +743,6 @@ def _stop() -> None: reader.join(timeout=_GYM_LOG_DRAIN_SECONDS) -def _redacted_row(row: dict[str, Any], secrets: set[str]) -> dict[str, Any]: - """Redact the failure text a rollout row carries before it reaches trial and result files.""" - redacted = dict(row) - for name in ("failure", "failure_reason", "failure_kind"): - value = redacted.get(name) - if isinstance(value, dict): - redacted[name] = { - key: redact_progress_detail(item, secret_values=secrets) if isinstance(item, str) else item - for key, item in value.items() - } - elif isinstance(value, str): - redacted[name] = redact_progress_detail(value, secret_values=secrets) - return redacted - - def gym_launch_environment(credentials: dict[str, str]) -> dict[str, str]: """Return Gym's process environment: the host variables a Harbor backend may receive, plus its credentials. @@ -1291,7 +1276,7 @@ def _config_failure(detail: str) -> dict[str, Any]: arm_errors.append(f"gym eval run timed out after {arm_timeout:.0f}s") elif returncode != 0: arm_errors.append(f"gym eval run exited {returncode}; see {log_path}") - rows = [_redacted_row(row, secrets) for row in read_rollouts(rollouts_path, arm_errors)] + rows = read_rollouts(rollouts_path, arm_errors) failures = { task: [redact_progress_detail(reason, secret_values=secrets) for reason in reasons] for task, reasons in read_rollout_failures(rollouts_path, arm_errors).items() @@ -1303,6 +1288,7 @@ def _config_failure(detail: str) -> dict[str, Any]: task_case_ids=task_case_ids, n_attempts=attempts, failures=failures, + secret_values=secrets, ) launch_errors += [ f"{agent} {arm}-skill: {redact_progress_detail(error, secret_values=secrets)}" diff --git a/tests/test_nemo_gym_backend.py b/tests/test_nemo_gym_backend.py index 9a4fafe2a..77a3e871f 100644 --- a/tests/test_nemo_gym_backend.py +++ b/tests/test_nemo_gym_backend.py @@ -2086,9 +2086,12 @@ def test_reward_txt_is_scored_like_harbor(tmp_path: Path) -> None: assert trial["verifier_result"]["rewards"] == {"entry_id": "case-1", "reward": 1.0} +_SYNTHETIC_POLICY_KEY = "gw-policy-0a1b2c3d4e5f6789" + + def test_rollout_row_failures_are_redacted(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: skill, _env_log = _fake_gym_skill(tmp_path, monkeypatch) - secret = "gw-policy-0a1b2c3d4e5f6789" + secret = _SYNTHETIC_POLICY_KEY monkeypatch.setenv(MODEL_API_KEY_ENV, secret) monkeypatch.setenv("FAKE_GYM_FAILURE", f"AuthenticationError: 401 invalid key {secret}") result = _run_fake_gym(skill, tmp_path, skip_baseline=True, max_cases=1) @@ -2098,6 +2101,52 @@ def test_rollout_row_failures_are_redacted(tmp_path: Path, monkeypatch: pytest.M assert all(secret not in path.read_text() for path in run_dir.rglob("*.json")) +def test_published_turn_diagnostics_mask_configured_credentials( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + import subprocess + + from skillevaluator.tier3.nemo_gym import runner + + config = "schema_version: 1\nharbor:\n task_source: native_harbor\ngrading:\n mode: custom_only\n" + skill, _ = _fake_gym_skill(tmp_path, monkeypatch, config=config) + _native_task(skill) + subprocess.run(["git", "init", "--quiet", str(skill)], check=True) + secret = _SYNTHETIC_POLICY_KEY + monkeypatch.setenv(MODEL_API_KEY_ENV, secret) + + def replay(command, *, cwd, **kwargs): + task = next(path for path in Path(command[3]).iterdir() if (path / "task.toml").is_file()) + logs = cwd / "verifier" + logs.mkdir() + diagnostic = f"missing verifier reward: {secret}" + (logs / "test-stdout.txt").write_text(f"start\n{diagnostic}\nend\n", encoding="utf-8") + row = { + "task_id": task.name, + "turn_reward_strategy": "final", + "failure_reason": diagnostic, + "turns": [{"name": "verify", "verifier_logs_dir": str(logs), "failure": {"message": diagnostic}}], + } + Path(command[command.index("--output") + 1]).write_text(json.dumps(row) + "\n", encoding="utf-8") + return 0 + + monkeypatch.setattr(runner, "_run_gym", replay) + result = _run_fake_gym(skill, tmp_path, skip_baseline=True, max_cases=1, n_attempts=1) + arm = Path(result["run_dir"]) / "codex" / "with-skill" + (trial,) = (arm / "trials").iterdir() + stdout = (trial / "steps" / "verify" / "test-stdout.txt").read_text(encoding="utf-8") + diagnostics = { + "returned result": json.dumps(result), + "arm summary": (arm / "summary.json").read_text(encoding="utf-8"), + "trial result": (trial / "result.json").read_text(encoding="utf-8"), + "trial failure": (trial / "failure.json").read_text(encoding="utf-8"), + "verifier stdout": stdout, + } + assert not [name for name, text in diagnostics.items() if secret in text] + assert all("missing verifier reward" in text for text in diagnostics.values()) + assert stdout.splitlines()[::2] == ["start", "end"] + + def test_malformed_mcp_servers_toml_is_handled_as_on_harbor(tmp_path: Path, caplog: pytest.LogCaptureFixture) -> None: from skillevaluator.tier3.nemo_gym.backend import MCP_SERVERS_ERROR, nemo_gym_config_errors From 3cd61c661ef9f6fc0a20616ae1ead4ad1eee96da Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Tue, 24 Nov 2026 06:41:13 -0800 Subject: [PATCH 09/10] fix(nemo-gym): mask retained turn evidence and honor final applicability Mask configured values in decoded trajectory text and in turn failures before whitespace is collapsed. Keep ATIF schema tags and the single-step startup check intact. When the final verifier marks a metric not applicable, use that decision for the final score without discarding a failed earlier turn. Signed-off-by: Deepak Jain --- .gitleaksignore | 2 - CHANGELOG.md | 21 ++---- src/skillevaluator/tier3/harbor/collector.py | 49 +++++++++++-- src/skillevaluator/tier3/harbor/progress.py | 9 ++- src/skillevaluator/tier3/nemo_gym/results.py | 19 ++++- tests/test_nemo_gym_backend.py | 17 +++-- tests/tier3/test_gym_multi_step_results.py | 77 +++++++++++++++++++- 7 files changed, 161 insertions(+), 33 deletions(-) diff --git a/.gitleaksignore b/.gitleaksignore index e8a22c51a..82f53173a 100644 --- a/.gitleaksignore +++ b/.gitleaksignore @@ -1,5 +1,3 @@ 08b38a1d499d894b009a761a5db04b818ef1af70:tests/reporting/test_tier3_failure_reasons.py:curl-auth-user:581 # Synthetic escaped-quote curl fixture from the preserved author commit. ccd7363b0ea3377781bc391f788a4f614deebc9b:tests/tier3/test_security_finding_evidence.py:curl-auth-user:1274 -# Synthetic policy key in the original Gym turn-diagnostics regression test. -8ba95ad23ca2f00fa6fae270bbb7d4589dbd1b11:tests/test_nemo_gym_backend.py:generic-api-key:2063 diff --git a/CHANGELOG.md b/CHANGELOG.md index 48c3266a4..c4b780585 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,13 @@ All notable changes to SkillEvaluator are documented in this file. ### Fixed +- NeMo Gym now scores native multi-step tasks once using the task's `mean` or + `final` strategy. The live case grid and finished report use the same verdict. + A failed or ungraded step leaves the attempt unscored. With `final`, the last + step determines which metrics apply, even if an earlier step scored one. + Each step keeps its own verifier output and trajectory after job cleanup, + including steps completed before a failure. Gym masks configured credential + values in trajectory text, verifier output, and step failure messages. - Reject unsafe paths in SkillSpector scope exclusions and clarify incomplete supply-chain scans when work counters disagree with the ledger. @@ -199,20 +206,6 @@ notes below describe the new policy and backend configuration behavior. ### Fixed -- NeMo Gym runs of native multi-step tasks are scored instead of failing with - "SkillEvaluator verifier did not run in the NeMo Gym sandbox". Each step's - rewards, verifier files and trajectory are kept in order, and the attempt is - scored once by the task's `mean` or `final` strategy. An attempt with a masked, - failed or ungraded step stays unscored and names that step. The live case - status judges every Gym attempt as the finished run does, so a goal missed - under standard grading shows as failed, and a required judge that failed or a - verifier that names another case shows as an error, also after the staged - tasks are removed. A - `final` attempt credits only the last step's judges. Published multi-step - trials, from Gym or Harbor, keep each step's redacted trajectory and verifier - output under `steps//`, so the evidence survives job cleanup and a - partial attempt keeps the steps that ran. Gym masks configured credentials in - step failure messages and published verifier output. - Bound declarative output-pattern checks with isolated Python regex workers and a shared matching budget, preserving Python regex semantics and later checks. Interpreter startup and JSON transfer have a separate startup allowance and do not consume diff --git a/src/skillevaluator/tier3/harbor/collector.py b/src/skillevaluator/tier3/harbor/collector.py index 6791f60df..f29076c07 100644 --- a/src/skillevaluator/tier3/harbor/collector.py +++ b/src/skillevaluator/tier3/harbor/collector.py @@ -2027,7 +2027,30 @@ def _merged_atif_schema_version(*trajectories: Mapping[str, Any]) -> str: return f"ATIF-v{newest[0]}.{newest[1]}" -def _validated_trajectory_dict(data: Any) -> dict[str, Any]: +def _mask_atif_fields(value: Any, mask: Callable[[str], str]) -> Any: + """Mask free text and free-form metadata while preserving ATIF's field names and literal tags.""" + from typing import Literal, get_origin + + from pydantic import BaseModel + + if isinstance(value, BaseModel): + fields = {} + for name, field in type(value).model_fields.items(): + item = getattr(value, name) + if item is None: + continue + masked = item if get_origin(field.annotation) is Literal else _mask_atif_fields(item, mask) + if name != "timestamp" or masked == item: + fields[name] = masked + return fields + if isinstance(value, dict): + return {key: _mask_atif_fields(item, mask) for key, item in value.items() if mask(key) == key} + if isinstance(value, list): + return [_mask_atif_fields(item, mask) for item in value] + return mask(value) if isinstance(value, str) else value + + +def _validated_trajectory_dict(data: Any, *, secret_values: set[str] | None = None) -> dict[str, Any]: try: # Bound traversal before deepcopy so hostile ATIF cannot amplify work # before validation begins. @@ -2127,7 +2150,20 @@ def _validated_trajectory_dict(data: Any) -> dict[str, Any]: ) from harbor.models.trajectories import Trajectory - validated = Trajectory.model_validate(candidate).to_json_dict() + trajectory = Trajectory.model_validate(candidate) + if secret_values: + from skillevaluator.tier3.harbor.stream_redaction import collision_safe_redaction_marker + + secrets = sorted(secret_values - {""}, key=len, reverse=True) + marker = collision_safe_redaction_marker(secrets) + + def mask(text: str) -> str: + for secret in secrets: + text = text.replace(secret, marker) + return text + + trajectory = Trajectory.model_validate(_mask_atif_fields(trajectory, mask)) + validated = trajectory.to_json_dict() _validate_generated_json_value( validated, max_depth=ATIF_JSON_MAX_DEPTH, @@ -3519,7 +3555,7 @@ def _constituent_custom_metric_failure(result: dict[str, Any]) -> str: def _restore_constituent_not_applicable( data: dict[str, Any], result: dict[str, Any], trial_root: Path ) -> dict[str, Any]: - """Restore absent N/A metrics only when every declared step has bounded sidecar evidence. + """Restore absent N/A metrics from the scoring steps, after checking every sidecar. The returned validation view preserves Harbor's authoritative numeric values. Missing or unsafe sidecars cannot turn absent metrics into applicable scores. @@ -3542,10 +3578,11 @@ def _restore_constituent_not_applicable( original = root_verifier.get("rewards") if isinstance(root_verifier, dict) else None if not isinstance(original, dict): return result + scoring_steps = names[-1:] if _harbor_multi_step_reward_strategy(result) == "final" else names restored = [ metric for metric in _standard_reward_metrics(original) - if metric not in original and all(metric_is_not_applicable(by_name[name], metric) for name in names) + if metric not in original and all(metric_is_not_applicable(by_name[name], metric) for name in scoring_steps) ] if not restored: return result @@ -3558,6 +3595,8 @@ def _restore_constituent_not_applicable( return result rewards = dict(rewards) for metric in restored: + if not metric_is_not_applicable(by_name[name], metric): + continue # A conflicting numeric value remains authoritative and prevents restoration. if metric in rewards and not metric_is_not_applicable(rewards, metric): return result @@ -3565,7 +3604,7 @@ def _restore_constituent_not_applicable( mark_not_applicable(rewards, metric, recorded_not_applicable_reason(by_name[name], metric)) steps.append({**step, "verifier_result": {**verifier, "rewards": rewards}}) for metric in restored: - reason = shared_not_applicable_reason([by_name[name] for name in names], metric) + reason = shared_not_applicable_reason([by_name[name] for name in scoring_steps], metric) mark_not_applicable(root_rewards, metric, reason) if metric not in data: mark_not_applicable(data, metric, reason) diff --git a/src/skillevaluator/tier3/harbor/progress.py b/src/skillevaluator/tier3/harbor/progress.py index 814769fec..ff52979d9 100644 --- a/src/skillevaluator/tier3/harbor/progress.py +++ b/src/skillevaluator/tier3/harbor/progress.py @@ -149,10 +149,15 @@ def close(self) -> None: ... def redact_progress_detail(detail: object, *, secret_values: set[str] | None = None) -> str: """Return a single-line diagnostic safe enough for a progress surface.""" - text = " ".join(strip_terminal_controls(str(detail)).split()) + raw = str(detail) + secrets = sorted(secret_values or (), key=len, reverse=True) + for secret in secrets: + if secret and secret != " ".join(strip_terminal_controls(secret).split()): + raw = raw.replace(secret, "") + text = " ".join(strip_terminal_controls(raw).split()) if "://" in text: text = _CREDENTIAL_URI_USERINFO_RE.sub(r"\g@", text) - for secret in sorted(secret_values or (), key=len, reverse=True): + for secret in secrets: if len(secret) >= MIN_EXACT_SECRET_CHARS: text = text.replace(secret, "") elif secret: diff --git a/src/skillevaluator/tier3/nemo_gym/results.py b/src/skillevaluator/tier3/nemo_gym/results.py index a64368ae5..aecc703dc 100644 --- a/src/skillevaluator/tier3/nemo_gym/results.py +++ b/src/skillevaluator/tier3/nemo_gym/results.py @@ -306,7 +306,13 @@ def _copy_verifier_logs( With ``verdict_only``, copy only what the attempt verdict reads: the reward files, and a trial's own trajectory when it is small enough for the collector to read and check for an agent that never started. """ - from skillevaluator.tier3.harbor.collector import DEFAULT_DIAGNOSTIC_ARTIFACT_MAX_BYTES, _write_redacted_text_copy + from skillevaluator.tier3.harbor.collector import ( + DEFAULT_DIAGNOSTIC_ARTIFACT_MAX_BYTES, + _read_json, + _TrajectoryMergeError, + _validated_trajectory_dict, + _write_redacted_text_copy, + ) verifier_dir = trial_dir / "verifier" verifier_dir.mkdir(parents=True, exist_ok=True) @@ -325,7 +331,16 @@ def _copy_verifier_logs( if verdict_only and (step or trajectory.stat().st_size > DEFAULT_DIAGNOSTIC_ARTIFACT_MAX_BYTES): return (trial_dir / "agent").mkdir(parents=True, exist_ok=True) - shutil.copyfile(trajectory, trial_dir / "agent" / "trajectory.json") + destination = trial_dir / "agent" / "trajectory.json" + if not step or not secret_values: + shutil.copyfile(trajectory, destination) + return + try: + masked = _validated_trajectory_dict(_read_json(trajectory), secret_values=secret_values) + encoded = json.dumps(masked, separators=(",", ":"), allow_nan=False) + except _TrajectoryMergeError: + encoded = "null" + destination.write_text(encoded, encoding="utf-8") def write_job_from_rollouts( diff --git a/tests/test_nemo_gym_backend.py b/tests/test_nemo_gym_backend.py index 77a3e871f..cfa365972 100644 --- a/tests/test_nemo_gym_backend.py +++ b/tests/test_nemo_gym_backend.py @@ -2101,19 +2101,25 @@ def test_rollout_row_failures_are_redacted(tmp_path: Path, monkeypatch: pytest.M assert all(secret not in path.read_text() for path in run_dir.rglob("*.json")) +@pytest.mark.parametrize("multiline", [False, True]) def test_published_turn_diagnostics_mask_configured_credentials( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, multiline: bool ) -> None: import subprocess from skillevaluator.tier3.nemo_gym import runner - config = "schema_version: 1\nharbor:\n task_source: native_harbor\ngrading:\n mode: custom_only\n" + config = ( + "schema_version: 1\nharbor:\n task_source: native_harbor\n" + " runtime_env:\n SERVICE_SETTING: ${SERVICE_SETTING}\ngrading:\n mode: custom_only\n" + ) skill, _ = _fake_gym_skill(tmp_path, monkeypatch, config=config) _native_task(skill) subprocess.run(["git", "init", "--quiet", str(skill)], check=True) - secret = _SYNTHETIC_POLICY_KEY - monkeypatch.setenv(MODEL_API_KEY_ENV, secret) + secret = "opaque first\nsecond line" if multiline else _SYNTHETIC_POLICY_KEY + monkeypatch.setenv("SERVICE_SETTING", secret if multiline else "on") + if not multiline: + monkeypatch.setenv(MODEL_API_KEY_ENV, secret) def replay(command, *, cwd, **kwargs): task = next(path for path in Path(command[3]).iterdir() if (path / "task.toml").is_file()) @@ -2142,7 +2148,8 @@ def replay(command, *, cwd, **kwargs): "trial failure": (trial / "failure.json").read_text(encoding="utf-8"), "verifier stdout": stdout, } - assert not [name for name, text in diagnostics.items() if secret in text] + forms = (secret, json.dumps(secret)[1:-1], " ".join(secret.split())) + assert not [name for name, text in diagnostics.items() if any(form in text for form in forms)] assert all("missing verifier reward" in text for text in diagnostics.values()) assert stdout.splitlines()[::2] == ["start", "end"] diff --git a/tests/tier3/test_gym_multi_step_results.py b/tests/tier3/test_gym_multi_step_results.py index a03fdd92b..cbf7ba7d4 100644 --- a/tests/tier3/test_gym_multi_step_results.py +++ b/tests/tier3/test_gym_multi_step_results.py @@ -21,7 +21,7 @@ from skillevaluator.tier3.case_summary import ERROR, FAIL, PASS, case_marks, live_case_marks from skillevaluator.tier3.harbor.collector import DEFAULT_DIAGNOSTIC_ARTIFACT_MAX_BYTES, collect_harbor_results -from skillevaluator.tier3.harbor.metrics import DEFAULT_METRICS +from skillevaluator.tier3.harbor.metrics import DEFAULT_METRICS, mark_not_applicable from skillevaluator.tier3.nemo_gym.results import write_job_from_rollouts, write_task_case_ids CASES = {"case-1": "case-1"} @@ -442,6 +442,45 @@ def test_named_step_evidence_survives_collection_and_job_cleanup(tmp_path: Path, assert not (steps / "second").exists() +@pytest.mark.parametrize("partial", [False, True], ids=["scored", "partial"]) +def test_retained_trajectories_mask_arm_values(tmp_path: Path, partial: bool) -> None: + out, jobs = tmp_path / "out", tmp_path / "jobs" + _stage_native_task(out, "with") + first = _turn(tmp_path, "first", 1.0) + second = _second_turn_failure(tmp_path, "setup-failed")[0] if partial else _turn(tmp_path, "second", 1.0) + secret = 'opaque "sample"\nvalue' + trajectory = _trajectory("first") + trajectory["steps"][0].update( + message=f"before {secret} after", timestamp="2026-11-24T12:34:56.808012Z", extra={"nested": [secret, 7]} + ) + (Path(first["verifier_logs_dir"]) / "trajectory.json").write_text(json.dumps(trajectory), encoding="utf-8") + errors = write_job_from_rollouts( + [_episode([first, second], task="login-task")], + jobs / "demo-codex-with", + eval_name="codex__m", + task_case_ids={"login-task": "auth-login"}, + n_attempts=1, + secret_values={secret, "name", "agent", "8080"}, + ) + assert bool(errors) == partial + collect_harbor_results("demo", ["codex"], out, jobs, skip_baseline=True, expected_case_ids=["auth-login"]) + trial = out / "codex/with-skill/trials/login-task__gym001" + paths = [trial / "steps/first/trajectory.json"] + if not partial: + paths.append(trial / "trajectory.json") + exposed = [] + for path in paths: + document = json.loads(path.read_text(encoding="utf-8")) + assert document["agent"]["name"] == "codex" + step = document["steps"][0] + assert step["message"].startswith("before ") and step["message"].endswith(" after") + assert step["extra"]["nested"][1] == 7 + if secret in step["message"] or secret in step["extra"]["nested"][0]: + exposed.append(path.relative_to(trial)) + assert not exposed + assert "timestamp" not in json.loads(paths[0].read_text(encoding="utf-8"))["steps"][0] + + def test_step_evidence_publication_refuses_linked_files(tmp_path: Path) -> None: out, jobs = tmp_path / "out", tmp_path / "jobs" _stage_native_task(out, "with") @@ -582,6 +621,33 @@ def episode(label: str, goal_accuracy: float, second_entry_id: str | None = None assert sorted(live) == sorted(final) +@pytest.mark.parametrize("failed_prepare", [False, True], ids=["healthy", "failed-prepare"]) +def test_final_turn_determines_metric_applicability(tmp_path: Path, failed_prepare: bool) -> None: + out, jobs = tmp_path / "out", tmp_path / "jobs" + _stage_native_task(out, "with") + prepare = _graded_turn(tmp_path, "prepare", 1.0, overall=1.0) + if failed_prepare: + _judge_failed(Path(prepare["verifier_logs_dir"])) + final = _graded_turn(tmp_path, "verify", 1.0, overall=1.0) + logs = Path(final["verifier_logs_dir"]) + numeric = json.loads((logs / "reward.json").read_text()) + del numeric["behavior_check"] + (logs / "reward.json").write_text(json.dumps(numeric)) + sidecar = numeric.copy() + mark_not_applicable(sidecar, "behavior_check", "No behavior assertions") + (logs / "skill_evaluator_reward.json").write_text(json.dumps(sidecar)) + row = _episode([prepare, final], task="login-task", turn_reward_strategy="final") + + live, finished = _live_and_final_marks(out, jobs, [row]) + + expected = [ERROR] if failed_prepare else [PASS] + assert (live, finished) == (expected, expected) + if not failed_prepare: + reward = json.loads((out / "codex/with-skill/trials/login-task__gym001/reward.json").read_text()) + assert reward["overall"] == 1.0 + assert reward["details"]["behavior_check"]["reason"] == "No behavior assertions" + + def test_live_marks_keep_the_staged_case_after_the_staged_tasks_are_removed(tmp_path: Path) -> None: out = tmp_path / "out" _stage_native_task(out, "with") @@ -744,7 +810,7 @@ def test_live_marks_still_read_the_trajectory_of_an_agent_that_never_started(tmp row = _graded_rollout(tmp_path / "never-started") # A tokenless trajectory that names an auth failure is an agent that never started, which stays unscored. tokenless = _trajectory("never-started") | {"final_metrics": {}} - tokenless["steps"][0]["message"] = "API Error: 401 Unauthorized" + tokenless["steps"][0]["message"] = "AuthenticationError: provider refused request" Path(row["verifier_logs_dir"], "trajectory.json").write_text(json.dumps(tokenless), encoding="utf-8") _live_arm(out, [row]) @@ -752,7 +818,12 @@ def test_live_marks_still_read_the_trajectory_of_an_agent_that_never_started(tmp assert marks == {"codex": {"with_skill": {"login-task": [ERROR]}}} write_job_from_rollouts( - [row], jobs / "demo-codex-with", eval_name="codex__m", task_case_ids={"login-task": "auth-login"}, n_attempts=1 + [row], + jobs / "demo-codex-with", + eval_name="codex__m", + task_case_ids={"login-task": "auth-login"}, + n_attempts=1, + secret_values={"Error"}, ) results = collect_harbor_results( "demo", ["codex"], out, jobs, skip_baseline=True, expected_cases=1, expected_case_ids=["auth-login"] From a5d75121b24e865bf0aab5a692e3e97bb0d8e5f1 Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Tue, 24 Nov 2026 11:31:20 -0800 Subject: [PATCH 10/10] fix(nemo-gym): mask single-step trial trajectories Mask configured credential values before saving a single-step trajectory, whether the verifier scored the rollout or failed. Check the original message for startup failures so masking cannot change the verdict. Signed-off-by: Deepak Jain --- src/skillevaluator/tier3/harbor/collector.py | 21 ++++++++++---- src/skillevaluator/tier3/nemo_gym/results.py | 27 +++++++++++------- tests/tier3/test_gym_multi_step_results.py | 30 ++++++++++++++++++++ 3 files changed, 62 insertions(+), 16 deletions(-) diff --git a/src/skillevaluator/tier3/harbor/collector.py b/src/skillevaluator/tier3/harbor/collector.py index f29076c07..dfb0aab41 100644 --- a/src/skillevaluator/tier3/harbor/collector.py +++ b/src/skillevaluator/tier3/harbor/collector.py @@ -890,13 +890,17 @@ def _agent_log_runtime_failure_reason( trial_dir: Path, *, include_text_logs: bool = True, + trajectory_startup_failed: bool | None = None, ) -> str: """Return the most specific agent log/runtime startup failure, if present.""" - for trajectory_path in (trial_dir / "agent" / "trajectory.json", trial_dir / "trajectory.json"): - if trajectory_path.exists(): - reason = _trajectory_agent_runtime_failure_reason(_read_json(trajectory_path)) - if reason: - return reason + if trajectory_startup_failed is not False: + for trajectory_path in (trial_dir / "agent" / "trajectory.json", trial_dir / "trajectory.json"): + if trajectory_path.exists(): + reason = _trajectory_agent_runtime_failure_reason(_read_json(trajectory_path)) + if reason: + return reason + if trajectory_startup_failed: + return "NeMo Gym agent failed to start" for path in ( trial_dir / "agent" / "claude-code.txt", @@ -928,12 +932,17 @@ def _agent_log_runtime_failure_reason( def _agent_runtime_failure_reason(trial_dir: Path) -> str: """Return why a trial cannot produce a valid score.""" + result = _read_json(trial_dir / "result.json") + result = result if isinstance(result, dict) else {} + gym = result.get("nemo_gym") if result.get("execution_backend") == "nemo-gym" else None + startup_failed = gym.get("trajectory_startup_failed") if isinstance(gym, dict) else None exception_details = [ - _trial_exception_details(trial_dir), + _exception_details(result.get("exception_info")), *_trial_step_exception_details(trial_dir), ] agent_reason = _agent_log_runtime_failure_reason( trial_dir, + trajectory_startup_failed=startup_failed if isinstance(startup_failed, bool) else None, include_text_logs=any( exception_type in _AGENT_RUNTIME_EXCEPTION_TYPES or exception_type in _UNCONDITIONAL_AGENT_RUNTIME_EXCEPTION_TYPES diff --git a/src/skillevaluator/tier3/nemo_gym/results.py b/src/skillevaluator/tier3/nemo_gym/results.py index aecc703dc..8e5b4a646 100644 --- a/src/skillevaluator/tier3/nemo_gym/results.py +++ b/src/skillevaluator/tier3/nemo_gym/results.py @@ -300,15 +300,17 @@ def _multi_step_outcome( def _copy_verifier_logs( logs_dir: Path, trial_dir: Path, *, verdict_only: bool, secret_values: set[str] | None, step: bool = False -) -> None: +) -> bool | None: """Copy a Gym verifier's files and trajectory into a trial or into one of its step folders. With ``verdict_only``, copy only what the attempt verdict reads: the reward files, and a trial's own trajectory when it is small enough for the collector to read and check for an agent that never started. + When masking a trial's trajectory, return its startup verdict from the original text. """ from skillevaluator.tier3.harbor.collector import ( DEFAULT_DIAGNOSTIC_ARTIFACT_MAX_BYTES, _read_json, + _trajectory_agent_runtime_failure_reason, _TrajectoryMergeError, _validated_trajectory_dict, _write_redacted_text_copy, @@ -327,20 +329,23 @@ def _copy_verifier_logs( shutil.copyfile(source, verifier_dir / name) trajectory = logs_dir / "trajectory.json" if not trajectory.is_file() or trajectory.is_symlink(): - return + return None if verdict_only and (step or trajectory.stat().st_size > DEFAULT_DIAGNOSTIC_ARTIFACT_MAX_BYTES): - return + return None (trial_dir / "agent").mkdir(parents=True, exist_ok=True) destination = trial_dir / "agent" / "trajectory.json" - if not step or not secret_values: + if verdict_only or not secret_values: shutil.copyfile(trajectory, destination) - return + return None + original = _read_json(trajectory) + startup_failed = None if step else bool(_trajectory_agent_runtime_failure_reason(original)) try: - masked = _validated_trajectory_dict(_read_json(trajectory), secret_values=secret_values) + masked = _validated_trajectory_dict(original, secret_values=secret_values) encoded = json.dumps(masked, separators=(",", ":"), allow_nan=False) except _TrajectoryMergeError: encoded = "null" destination.write_text(encoded, encoding="utf-8") + return startup_failed def write_job_from_rollouts( @@ -393,17 +398,19 @@ def write_job_from_rollouts( trial_dir = job_dir / trial_name trial_dir.mkdir(parents=True, exist_ok=True) rewards: dict[str, Any] | None = None - step_fields: dict[str, Any] = {} + trial_fields: dict[str, Any] = {} if row.get("turns") is not None: - rewards, failure, step_fields = _multi_step_outcome( + rewards, failure, trial_fields = _multi_step_outcome( row, trial_dir, case_id, verdict_only=verdict_only, secret_values=secret_values ) else: logs_dir = row.get("verifier_logs_dir") if isinstance(logs_dir, str) and Path(logs_dir).is_dir(): - _copy_verifier_logs( + startup_failed = _copy_verifier_logs( Path(logs_dir), trial_dir, verdict_only=verdict_only, secret_values=secret_values ) + if startup_failed is not None: + trial_fields["nemo_gym"] = {"trajectory_startup_failed": startup_failed} failure = _failure_text(row) if not failure: rewards, failure = _verified_rewards(trial_dir / "verifier", case_id) @@ -428,7 +435,7 @@ def write_job_from_rollouts( "exception_info": None if rewards else {"exception_type": "NeMoGymEpisodeFailure", "exception_message": failure}, - **step_fields, + **trial_fields, }, indent=2, ), diff --git a/tests/tier3/test_gym_multi_step_results.py b/tests/tier3/test_gym_multi_step_results.py index cbf7ba7d4..d33a9cc6c 100644 --- a/tests/tier3/test_gym_multi_step_results.py +++ b/tests/tier3/test_gym_multi_step_results.py @@ -481,6 +481,36 @@ def test_retained_trajectories_mask_arm_values(tmp_path: Path, partial: bool) -> assert "timestamp" not in json.loads(paths[0].read_text(encoding="utf-8"))["steps"][0] +@pytest.mark.parametrize("failed", [False, True], ids=["scored", "failed"]) +def test_single_step_published_trajectory_masks_arm_value(tmp_path: Path, failed: bool) -> None: + out, jobs = tmp_path / "out", tmp_path / "jobs" + _stage_native_task(out, "with") + logs = tmp_path / "single" + row = _graded_rollout(logs) + if failed: + row.update(failure="verifier failed", verifier_return_code=1) + secret = 'opaque "example"\nvalue' + trajectory = _trajectory("single") | {"final_metrics": {}} + trajectory["steps"][0]["message"] = f"before {secret}401 after" + (logs / "trajectory.json").write_text(json.dumps(trajectory), encoding="utf-8") + + errors = write_job_from_rollouts( + [row], + jobs / "demo-codex-with", + eval_name="codex__m", + task_case_ids={"login-task": "auth-login"}, + n_attempts=1, + secret_values={secret}, + ) + assert bool(errors) == failed + results = collect_harbor_results("demo", ["codex"], out, jobs, skip_baseline=True, expected_case_ids=["auth-login"]) + assert results["agents"]["codex"]["scored_attempts"] == (0 if failed else 1) + published = out / "codex/with-skill/trials/login-task__gym001/trajectory.json" + message = json.loads(published.read_text(encoding="utf-8"))["steps"][0]["message"] + assert message.startswith("before ") and message.endswith(" after") + assert secret not in message + + def test_step_evidence_publication_refuses_linked_files(tmp_path: Path) -> None: out, jobs = tmp_path / "out", tmp_path / "jobs" _stage_native_task(out, "with")