diff --git a/CHANGELOG.md b/CHANGELOG.md index f3a2e9ee0..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. diff --git a/docs/nemo-gym.mdx b/docs/nemo-gym.mdx index 2178e8290..c146bda20 100644 --- a/docs/nemo-gym.mdx +++ b/docs/nemo-gym.mdx @@ -239,6 +239,30 @@ 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. 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 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. + @@ -296,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/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..727871fbc 100644 --- a/src/skillevaluator/tier3/case_summary.py +++ b/src/skillevaluator/tier3/case_summary.py @@ -5,6 +5,7 @@ from __future__ import annotations +import hashlib import json import logging import os @@ -1590,6 +1591,9 @@ def load_case_marks(run_dir: Path) -> dict[str, dict[str, dict[str, list[str]]]] _LIVE_VARIANTS = {"with": "with_skill", "without": "without_skill"} +# 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 def _harbor_job_owner(job_name: str, agents: list[str]) -> tuple[str, str] | None: @@ -1617,45 +1621,75 @@ 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, + 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 = 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 + 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: """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 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, - read_verifier_rewards, - rollout_failure_text, - 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(): 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}" rollouts = arm / "rollouts.jsonl" if arm.is_symlink() or rollouts.is_symlink() or not rollouts.is_file(): continue + 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): - 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 - 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 - ) - 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) + 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, judged, seen) + marks.setdefault(agent, {}).setdefault(key, {}).setdefault(task, []).append(mark) + _keep_gym_live_marks(str(gym_root), seen) return True diff --git a/src/skillevaluator/tier3/harbor/collector.py b/src/skillevaluator/tier3/harbor/collector.py index 37669adbc..dfb0aab41 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", @@ -889,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", @@ -927,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 @@ -1301,6 +1311,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() @@ -1348,6 +1359,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} @@ -1415,6 +1430,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 +1666,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 @@ -1982,7 +2036,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. @@ -2082,7 +2159,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, @@ -3474,7 +3564,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. @@ -3497,10 +3587,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 @@ -3513,6 +3604,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 @@ -3520,7 +3613,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) @@ -5482,7 +5575,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 +6765,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/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 3225f1e9a..8e5b4a646 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,22 @@ 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 +from skillevaluator.tier3.harbor.progress import redact_progress_detail + _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" +TASK_CASE_IDS_FILE = "task_case_ids.json" def _safe(value: str) -> str: @@ -106,12 +121,47 @@ 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 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") + + +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 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, + _logical_attempt_rewards, + _overall_score, + _partition_scoreable_rewards, + ) + + task_case_ids = {task_name: case_id} + 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, 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: + return None + return attempt_verdict(_overall_score(attempts[0]), pass_threshold, reward=attempts[0]).passed 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,22 +169,183 @@ 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 _copy_verifier_logs(logs_dir: Path, trial_dir: Path) -> None: +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 + 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) -> 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} + ) + return { + key: sum(_reward_number(rewards.get(key)) or 0.0 for rewards in step_rewards) / len(step_rewards) + for key in keys + } + + +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( + 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. + + 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 + # 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, verdict_only=verdict_only, step=True, secret_values=secret_values + ) + step_failure = _failure_text(turn) + 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, + "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, *, verdict_only: bool, secret_values: set[str] | None, step: bool = False +) -> 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, + ) + 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) + 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 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 None + if verdict_only and (step or trajectory.stat().st_size > DEFAULT_DIAGNOSTIC_ARTIFACT_MAX_BYTES): + return None + (trial_dir / "agent").mkdir(parents=True, exist_ok=True) + destination = trial_dir / "agent" / "trajectory.json" + if verdict_only or not secret_values: + shutil.copyfile(trajectory, destination) + return None + original = _read_json(trajectory) + startup_failed = None if step else bool(_trajectory_agent_runtime_failure_reason(original)) + try: + 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( @@ -145,10 +356,13 @@ 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, + secret_values: set[str] | None = None, ) -> 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] = [] @@ -183,25 +397,26 @@ 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}" + trial_fields: dict[str, Any] = {} + if row.get("turns") is not None: + 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(): + startup_failed = _copy_verifier_logs( + Path(logs_dir), trial_dir, verdict_only=verdict_only, secret_values=secret_values ) - else: - rewards = {**loaded, "entry_id": case_id} - if reward_path.is_file(): - reward_path.write_text(json.dumps(rewards, indent=2), encoding="utf-8") + 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) if rewards is None: - failure = failure or "the task verifier wrote no reward.json or numeric reward.txt" + 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}") @@ -220,6 +435,7 @@ def write_job_from_rollouts( "exception_info": None if rewards else {"exception_type": "NeMoGymEpisodeFailure", "exception_message": failure}, + **trial_fields, }, indent=2, ), diff --git a/src/skillevaluator/tier3/nemo_gym/runner.py b/src/skillevaluator/tier3/nemo_gym/runner.py index 10ef8609c..06ee61be3 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"] @@ -738,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. @@ -1181,6 +1171,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)) @@ -1285,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() @@ -1297,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/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 diff --git a/tests/test_nemo_gym_backend.py b/tests/test_nemo_gym_backend.py index 5726a97e4..cfa365972 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") @@ -2076,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) @@ -2088,6 +2101,59 @@ 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, multiline: bool +) -> None: + import subprocess + + from skillevaluator.tier3.nemo_gym import runner + + 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 = "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()) + 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, + } + 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"] + + 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 @@ -2289,6 +2355,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 new file mode 100644 index 000000000..d33a9cc6c --- /dev/null +++ b/tests/tier3/test_gym_multi_step_results.py @@ -0,0 +1,861 @@ +# 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 +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 DEFAULT_DIAGNOSTIC_ARTIFACT_MAX_BYTES, collect_harbor_results +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"} + + +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") + (logs / "test-stdout.txt").write_text(f"{name} verifier output\n", 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_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"] + ) + + 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: + 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"] + + +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() + + +@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] + + +@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") + 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"] + + +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, 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 _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" + 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( + 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) + + 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, ERROR] + 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") + 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, 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_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) + 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") + + 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"}}} + 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, 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"] = "AuthenticationError: provider refused request" + 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, + secret_values={"Error"}, + ) + 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