Multi-tier framework for evaluating AI agent skills and plugins with quality gates, security scanning, harness compatibility checks, semantic overlap detection, synthetic evaluation dataset generation, and live agent evaluation that measures how skills affect agent behavior. Ships reusable CI templates that bring every check to any repository.
Python agent-evaluationagent-pluginsagent-securityagent-skillsagentic-aibenchmarkci-templatesclaude-codecodexevaluateevaluationharnesspluginplugin-evaluationsecurity-scannerskill-evalskill-evaluationskill-evaluatorskill-gap-analysisskills
fix(tier3): retain scores after verified timeout recovery (#222)
Christopher Kevinfad61ed740e6
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 2c2b1b7c..d3f173a3 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -172,6 +172,13 @@ All notable changes to SkillEvaluator are documented in this file.- Harbor's standalone verifier now runs on Python 3.9 task images after sharingdeterministic checks with the host evaluator. Packaged verifier checks executeon a real Python 3.9 interpreter in CI to retain this compatibility.+- With `--stop-on-pass`, a retained Harbor agent timeout followed by a matching+ completed attempt no longer invalidates the scored result. Timeout rewards+ remain excluded, failure history is retained, and the JSON summaries+ distinguish scored, recovered, and intentionally skipped attempts. Recovered+ timeouts are reported under `recovered_trial_failures` and+ `historical_job_failures` instead of as active failures. Other execution failures and+ incomplete comparisons still fail validation.- Plain removal of recognized regenerable caches no longer receives the Tier 3destructive-command penalty. Dynamic commands, mixed targets and otherdestructive operations retain their existing classification in both verifiers.diff --git a/src/skillevaluator/tier3/harbor/collector.py b/src/skillevaluator/tier3/harbor/collector.pyindex 4a20bf05..d1efd1d9 100644--- a/src/skillevaluator/tier3/harbor/collector.py+++ b/src/skillevaluator/tier3/harbor/collector.py@@ -4910,6 +4910,7 @@ def _pass_summary(stop_on_pass: bool = False,expected_cases: int | None,expected_case_ids: list[str] | None = None,+ recovered_attempts: list[dict[str, Any]] | None = None,scorer: Callable[[dict[str, Any]], float | None] | None = None,) -> dict[str, Any]:"""Summarize pass@k using SkillEvaluator continuous reward scores.@@ -4948,6 +4949,7 @@ def _pass_summary(best_score: float | None = Nonefirst_pass_attempt: int | None = Nonefor idx, (reward, overall) in enumerate(sorted(attempts, key=lambda item: _attempt_sort_key(item[0])), start=1):+ idx = _attempt_ordinal(reward) or idxscore = round(overall, 4)passed = score >= pass_thresholdattempt_passes.append({"passed": passed})@@ -4975,7 +4977,8 @@ def _pass_summary(passed_cases += 1if is_expected_case:attempts_used += len(attempts)- unscored = max(0, n_attempts - len(attempts))+ recovered_count = sum(item["case_id"] == entry_id for item in (recovered_attempts or []))+ unscored = max(0, n_attempts - len(attempts) - recovered_count)skipped = unscored if stop_on_pass and case_passed else 0missing = 0 if skipped else unscored@@ -4990,6 +4993,7 @@ def _pass_summary("passed": case_passed,"first_pass_attempt": first_pass_attempt,"attempts_used": len(attempts),+ "attempts_recovered": recovered_count,"attempts_skipped": skipped,"attempts_missing": missing,"best_score": round(best_score, 4) if best_score is not None else None,@@ -6366,6 +6370,208 @@ def _summarize_trajectory(data: dict[str, Any]) -> dict[str, Any]:}+def _timeout_recovered_by(failed: dict[str, Any], successful: dict[str, Any]) -> bool:+ """Recognize only Harbor's agent-phase deadline followed by a fresh completion.++ This is evidence classification, not command replay. Setup, transport, verifier,+ multi-step, missing, and ambiguous failures remain errors. The original result+ is never rewritten, and an unscored timeout never contributes a zero reward.+ """+ try:+ from harbor.models.trial.result import TrialResult++ before = TrialResult.model_validate(failed)+ after = TrialResult.model_validate(successful)+ except (ImportError, ValueError, TypeError):+ return False+ error = before.exception_info+ if (+ error is None+ or error.exception_type != "AgentTimeoutError"+ or not re.fullmatch(r"Agent execution timed out after [0-9.]+ seconds", error.exception_message)+ or "_run_agent_phase" not in error.exception_traceback+ or "AgentTimeoutError" not in error.exception_traceback+ or before.step_results+ or after.step_results+ or after.exception_info is not None+ or after.verifier_result is None+ or not after.verifier_result.rewards+ or before.id == after.id+ or not before.task_checksum+ or before.task_checksum != after.task_checksum+ or before.task_id != after.task_id+ or before.agent_info != after.agent_info+ or before.agent_execution is None+ or before.agent_execution.finished_at is None+ or before.finished_at is None+ or after.agent_execution is None+ or after.agent_execution.finished_at is None+ or after.finished_at is None+ ):+ return False+ # Job/physical-trial identity changes on a fresh attempt; execution inputs must not.+ excluded = {"trial_name", "trials_dir", "job_id"}+ if before.config.model_dump(exclude=excluded) != after.config.model_dump(exclude=excluded):+ return False+ try:+ return (+ before.started_at+ <= before.agent_execution.started_at+ <= before.agent_execution.finished_at+ <= error.occurred_at+ <= before.finished_at+ <= after.started_at+ <= after.agent_execution.started_at+ <= after.agent_execution.finished_at+ <= after.finished_at+ )+ except TypeError: # Mixed timezone/invalid timestamps cannot prove ordering.+ return False+++def _trial_derived_job_stats(stats: Any) -> dict[str, Any]:+ """Return the job counters Harbor derives from trials, independent of order.++ Harbor fills job-level ``metrics`` and ``pass_at_k`` after aggregating+ trials, and token or cost totals depend on summation order, so neither is+ compared.+ """+ return {+ "counts": (+ stats.n_completed_trials,+ stats.n_errored_trials,+ stats.n_running_trials,+ stats.n_pending_trials,+ stats.n_cancelled_trials,+ stats.n_retries,+ ),+ "evals": {+ key: (+ value.n_trials,+ value.n_errors,+ {+ name: {reward: sorted(trials) for reward, trials in rewards.items()}+ for name, rewards in value.reward_stats.items()+ },+ {name: sorted(trials) for name, trials in value.exception_stats.items()},+ )+ for key, value in stats.evals.items()+ },+ }+++def _split_recovered_failures(+ failures: list[dict[str, str]], recovered: list[dict[str, Any]]+) -> tuple[list[dict[str, str]], list[dict[str, str]]]:+ """Separate active trial failures from timeouts a later attempt recovered."""+ recovered_trials = {item["trial"] for item in recovered}+ active = [item for item in failures if item["trial"] not in recovered_trials]+ return active, [item for item in failures if item["trial"] in recovered_trials]+++def _job_stats_match_trials(job_dir: Path) -> bool:+ """Require a terminal native job whose counters agree with every physical trial."""+ try:+ from harbor.models.job.result import JobResult, JobStats+ from harbor.models.trial.result import TrialResult++ if _inspect_trial_directory(job_dir)[0] != "directory":+ return False+ job = JobResult.model_validate(_read_json(job_dir / "result.json"))+ trials = []+ for directory in job_dir.iterdir():+ kind, _ = _inspect_trial_directory(directory)+ if kind == "link":+ return False+ if kind == "directory":+ trials.append(TrialResult.model_validate(_read_json(directory / "result.json")))+ if not job.finished_at or len(trials) != job.n_total_trials or any(t.finished_at is None for t in trials):+ return False+ if len({t.id for t in trials}) != len(trials):+ return False+ expected = JobStats.from_trial_results(trials, n_total_trials=len(trials), n_retries=job.stats.n_retries)+ return _trial_derived_job_stats(expected) == _trial_derived_job_stats(job.stats)+ except (ImportError, ValueError, TypeError, OSError):+ return False+++def harbor_timeout_job_recovered(failed_job: Path, completed_job: Path) -> bool:+ """Check one failed single-trial launch against its successful fresh attempt."""+ failures = _extract_trial_failures(failed_job)+ if (+ len(failures) != 1+ or not _can_preserve_partial_rewards(failed_job, failures)+ or not _job_stats_match_trials(failed_job)+ ):+ return False+ failed_trials = [d for d in failed_job.iterdir() if _inspect_trial_directory(d)[0] == "directory"]+ successful_trials = [d for d in completed_job.iterdir() if _inspect_trial_directory(d)[0] == "directory"]+ if len(failed_trials) != 1 or len(successful_trials) != 1:+ return False+ valid, _ = validate_harbor_job_result(completed_job / "result.json", expected_trials=1)+ if not valid or _trial_failure_reason(successful_trials[0]):+ return False+ failed = _read_json(failed_trials[0] / "result.json")+ successful = _read_json(successful_trials[0] / "result.json")+ return isinstance(failed, dict) and isinstance(successful, dict) and _timeout_recovered_by(failed, successful)+++def _recovered_timeout_attempts(+ job_dir: Path, rewards: list[dict[str, Any]], *, n_attempts: int+) -> list[dict[str, Any]]:+ """Bind retained failures to later scoreable trials of the same task and agent."""+ completed = []+ for reward in _logical_attempt_rewards(rewards):+ root = str(reward.get("_trial_root_name") or "")+ if not root or Path(root).name != root or _overall_score(reward) is None:+ continue+ directory = job_dir / root+ if _inspect_trial_directory(directory)[0] != "directory" or _trial_failure_reason(directory):+ continue+ payload = _read_json(directory / "result.json")+ if isinstance(payload, dict):+ completed.append((reward, payload))+ recovered = []+ for directory in sorted(job_dir.iterdir()):+ if _inspect_trial_directory(directory)[0] != "directory":+ continue+ failed = _read_json(directory / "result.json")+ if not isinstance(failed, dict):+ continue+ for reward, successful in completed:+ selector = str(reward.get("_trusted_task_selector") or _entry_id(reward))+ ordinal = _structural_attempt_ordinal(directory.name, selector)+ later = _attempt_ordinal(reward)+ if ordinal is None or later is None or not 0 < ordinal < later <= n_attempts:+ continue+ if _timeout_recovered_by(failed, successful):+ recovered.append(+ {+ "trial": _published_trial_label(directory.name),+ "case_id": _entry_id(reward),+ "attempt": ordinal,+ "recovered_by": _published_trial_label(reward["_trial_root_name"]),+ "recovered_by_attempt": later,+ }+ )+ break+ return recovered+++def _recovered_job_failure(job_dir: Path, failures: list[dict[str, str]], recovered: list[dict[str, Any]]) -> bool:+ """Only dismiss aggregate error counts fully explained by retained timeouts."""+ if not recovered or not _can_preserve_partial_rewards(job_dir, failures) or not _job_stats_match_trials(job_dir):+ return False+ payload = _read_json(job_dir / "result.json")+ stats = payload.get("stats", {})+ errors = stats.get("n_errored_trials", stats.get("n_errors"))+ return (+ errors == len(recovered) == len(failures)+ and {item["trial"] for item in failures} == {item["trial"] for item in recovered}+ and payload.get("finished_at") is not None+ )++def _condition_execution_summary(rewards: list[dict[str, Any]],*,@@ -6375,6 +6581,7 @@ def _condition_execution_summary(job_failure: str,runtime_failures: list[dict[str, str]] | None = None,reward_failures: list[dict[str, str]] | None = None,+ recovered_attempts: list[dict[str, Any]] | None = None,skipped: bool = False,stop_on_pass: bool = False,pass_threshold: float = 0.50,@@ -6401,6 +6608,14 @@ def _condition_execution_summary(**_failure_list_metadata("reward_failure_details", reward_failures),}+ recovered_attempts = recovered_attempts or []+ recovered_names = {item["trial"] for item in recovered_attempts}+ runtime_failures = [+ item+ for item in (runtime_failures or [])+ if item["trial"] not in recovered_names or not item.get("reason", "").startswith("AgentTimeoutError:")+ ]+ reward_failures = [item for item in (reward_failures or []) if item["trial"] not in recovered_names]errors: list[str] = [job_failure] if job_failure else []public_runtime_failures = _public_failure_list(runtime_failures)public_reward_failures = _public_failure_list(reward_failures)@@ -6474,11 +6689,12 @@ def _condition_execution_summary(attempts.sort(key=lambda item: _attempt_sort_key(item["reward"]))def _case_attempt_coverage(case_id: str, attempts: list[dict[str, Any]]) -> tuple[int, bool, bool]:+ recovered_ordinals = [item["attempt"] for item in recovered_attempts if item["case_id"] == case_id]explicit = [item["attempt_ordinal"] for item in attempts if item["attempt_ordinal"] is not None]all_explicit = len(explicit) == len(attempts) and bool(attempts)if explicit and len(explicit) != len(attempts):errors.append(f"Scored case {case_id!r} mixes explicit and implicit attempt labels")- if len(explicit) != len(set(explicit)):+ if len(explicit + recovered_ordinals) != len(set(explicit + recovered_ordinals)):errors.append(f"Scored case {case_id!r} has duplicate attempt ordinals")required = n_attempts@@ -6495,7 +6711,7 @@ def _condition_execution_summary(if all_explicit:expected_ordinals = set(range(1, required + 1))- actual_ordinals = set(explicit)+ actual_ordinals = set(explicit + recovered_ordinals)return required, bool(expected_ordinals - actual_ordinals), bool(actual_ordinals - expected_ordinals)return required, len(attempts) < required, len(attempts) > required@@ -6528,6 +6744,8 @@ def _condition_execution_summary(errors.append(_sampled_case_id_diagnostic("Excess scored attempts for cases", sorted(excess)))scored_attempts = len(roots)+ physical_expected_attempts = expected_attempts+ expected_attempts -= len(recovered_attempts)if scored_attempts != expected_attempts:errors.append(f"Scored attempt coverage is {scored_attempts}/{expected_attempts}")all_errors = list(@@ -6544,6 +6762,15 @@ def _condition_execution_summary("execution_error_details_truncated": len(errors) < len(all_errors),"expected_attempts": expected_attempts,"scored_attempts": scored_attempts,+ **(+ {+ "physical_expected_attempts": physical_expected_attempts,+ "recovered_attempts": recovered_attempts[:PUBLISHED_FAILURE_DETAILS_MAX],+ "recovered_attempts_total": len(recovered_attempts),+ }+ if recovered_attempts+ else {}+ ),**_failure_list_metadata("runtime_failure_details", runtime_failures),**_failure_list_metadata("reward_failure_details", reward_failures),}@@ -6685,6 +6912,8 @@ def collect_harbor_results(with_runtime_failures: list[dict[str, str]] = []with_trial_failures: list[dict[str, str]] = []with_job_failure = ""+ with_recovered: list[dict[str, Any]] = []+ with_job_recovered = Falsewith_execution: dict[str, Any] = {}with_overall_score: float | None = Nonewith_policy = DEFAULT_SCORE_POLICY@@ -6721,6 +6950,10 @@ def collect_harbor_results(else [])with_rewards, invalid_score_failures = _partition_scoreable_rewards(with_collected_rewards)+ with_recovered = (+ _recovered_timeout_attempts(with_job_dir, with_rewards, n_attempts=n_attempts) if stop_on_pass else []+ )+ with_job_recovered = _recovered_job_failure(with_job_dir, with_trial_failures, with_recovered)with_logical_rewards = _logical_attempt_rewards(with_rewards)with_mixed_metric_contracts = rewards_have_mixed_metric_contracts(with_rewards)with_trial_failures.extend(invalid_score_failures)@@ -6740,13 +6973,15 @@ def collect_harbor_results(stop_on_pass=stop_on_pass,expected_cases=expected_cases,expected_case_ids=expected_case_ids,+ recovered_attempts=with_recovered,)with_execution = _condition_execution_summary(with_rewards,expected_case_ids=expected_case_ids,expected_cases=expected_cases,n_attempts=n_attempts,- job_failure=with_job_failure,+ job_failure="" if with_job_recovered else with_job_failure,+ recovered_attempts=with_recovered,runtime_failures=with_runtime_failures,reward_failures=with_trial_failures,stop_on_pass=stop_on_pass,@@ -6800,9 +7035,17 @@ def collect_harbor_results("skill_activation": summarize_skill_activation(with_rewards),"pass_at_k": _public_pass_summary(with_pass),**with_execution,- "job_failure": with_job_failure,- "trial_failures": _public_failure_list(with_trial_failures),- **_failure_list_metadata("trial_failure_details", with_trial_failures),+ "job_failure": "" if with_job_recovered else with_job_failure,+ "historical_job_failure": with_job_failure if with_job_recovered else "",+ "trial_failures": _public_failure_list(+ _split_recovered_failures(with_trial_failures, with_recovered)[0]+ ),+ "recovered_trial_failures": _public_failure_list(+ _split_recovered_failures(with_trial_failures, with_recovered)[1]+ ),+ **_failure_list_metadata(+ "trial_failure_details", _split_recovered_failures(with_trial_failures, with_recovered)[0]+ ),}_write_generated_root_json(agent_dir / "with-skill" / "summary.json", output_dir, with_summary)logger.debug(@@ -6890,6 +7133,8 @@ def collect_harbor_results(without_runtime_failures: list[dict[str, str]] = []without_trial_failures: list[dict[str, str]] = []without_job_failure = ""+ without_recovered: list[dict[str, Any]] = []+ without_job_recovered = Falsewithout_execution: dict[str, Any] = {}without_overall_score: float | None = Nonewithout_policy = DEFAULT_SCORE_POLICY@@ -6927,6 +7172,14 @@ def collect_harbor_results(else [])without_rewards, invalid_score_failures = _partition_scoreable_rewards(without_collected_rewards)+ without_recovered = (+ _recovered_timeout_attempts(without_job_dir, without_rewards, n_attempts=n_attempts)+ if stop_on_pass+ else []+ )+ without_job_recovered = _recovered_job_failure(+ without_job_dir, without_trial_failures, without_recovered+ )without_logical_rewards = _logical_attempt_rewards(without_rewards)without_mixed_metric_contracts = rewards_have_mixed_metric_contracts(without_rewards)without_trial_failures.extend(invalid_score_failures)@@ -6943,13 +7196,15 @@ def collect_harbor_results(stop_on_pass=stop_on_pass,expected_cases=expected_cases,expected_case_ids=expected_case_ids,+ recovered_attempts=without_recovered,)without_execution = _condition_execution_summary(without_rewards,expected_case_ids=expected_case_ids,expected_cases=expected_cases,n_attempts=n_attempts,- job_failure=without_job_failure,+ job_failure="" if without_job_recovered else without_job_failure,+ recovered_attempts=without_recovered,runtime_failures=without_runtime_failures,reward_failures=without_trial_failures,stop_on_pass=stop_on_pass,@@ -7005,9 +7260,18 @@ def collect_harbor_results("mixed_metric_contracts": without_mixed_metric_contracts,"pass_at_k": _public_pass_summary(without_pass),**without_execution,- "job_failure": without_job_failure,- "trial_failures": _public_failure_list(without_trial_failures),- **_failure_list_metadata("trial_failure_details", without_trial_failures),+ "job_failure": "" if without_job_recovered else without_job_failure,+ "historical_job_failure": without_job_failure if without_job_recovered else "",+ "trial_failures": _public_failure_list(+ _split_recovered_failures(without_trial_failures, without_recovered)[0]+ ),+ "recovered_trial_failures": _public_failure_list(+ _split_recovered_failures(without_trial_failures, without_recovered)[1]+ ),+ **_failure_list_metadata(+ "trial_failure_details",+ _split_recovered_failures(without_trial_failures, without_recovered)[0],+ ),}_write_generated_root_json(agent_dir / "without-skill" / "summary.json", output_dir, without_summary)logger.debug(@@ -7242,6 +7506,12 @@ def collect_harbor_results()agent_execution = _aggregate_execution([with_execution, without_execution])+ with_active_trial_failures, with_recovered_trial_failures = _split_recovered_failures(+ with_trial_failures, with_recovered+ )+ without_active_trial_failures, without_recovered_trial_failures = _split_recovered_failures(+ without_trial_failures, without_recovered+ )all_results["agents"][agent] = {"model": agent_model,"model_source": agent_model_source,@@ -7276,18 +7546,26 @@ def collect_harbor_results("without_skill": _public_failure_list(without_runtime_failures),},"trial_failures": {- "with_skill": _public_failure_list(with_trial_failures),- "without_skill": _public_failure_list(without_trial_failures),+ "with_skill": _public_failure_list(with_active_trial_failures),+ "without_skill": _public_failure_list(without_active_trial_failures),+ },+ "recovered_trial_failures": {+ "with_skill": _public_failure_list(with_recovered_trial_failures),+ "without_skill": _public_failure_list(without_recovered_trial_failures),},"failure_detail_metadata": {"with_skill_runtime": _failure_list_metadata("details", with_runtime_failures),"without_skill_runtime": _failure_list_metadata("details", without_runtime_failures),- "with_skill_trials": _failure_list_metadata("details", with_trial_failures),- "without_skill_trials": _failure_list_metadata("details", without_trial_failures),+ "with_skill_trials": _failure_list_metadata("details", with_active_trial_failures),+ "without_skill_trials": _failure_list_metadata("details", without_active_trial_failures),},"job_failures": {- "with_skill": with_job_failure,- "without_skill": without_job_failure,+ "with_skill": "" if with_job_recovered else with_job_failure,+ "without_skill": "" if without_job_recovered else without_job_failure,+ },+ "historical_job_failures": {+ "with_skill": with_job_failure if with_job_recovered else "",+ "without_skill": without_job_failure if without_job_recovered else "",},"conditions": {"with_skill": with_execution,diff --git a/src/skillevaluator/tier3/harbor/report_data.py b/src/skillevaluator/tier3/harbor/report_data.pyindex e03c2ab5..5c8be085 100644--- a/src/skillevaluator/tier3/harbor/report_data.py+++ b/src/skillevaluator/tier3/harbor/report_data.py@@ -749,6 +749,9 @@ def load_agent_data(**_execution_error_details(data, len(condition_errors)),"expected_attempts": _nonnegative_counter(data.get("expected_attempts")),"scored_attempts": _nonnegative_counter(data.get("scored_attempts")),+ "recovered_attempts_total": _nonnegative_counter(data.get("recovered_attempts_total")),+ "recovered_attempts": data.get("recovered_attempts", []),+ "recovered_trial_failures": data.get("recovered_trial_failures", []),}count_key = "num_trials" if variant == "with-skill" else "num_trials_baseline"num_trials = data.get("num_trials")diff --git a/src/skillevaluator/tier3/harbor/runner.py b/src/skillevaluator/tier3/harbor/runner.pyindex 9c22831e..3c3c3999 100644--- a/src/skillevaluator/tier3/harbor/runner.py+++ b/src/skillevaluator/tier3/harbor/runner.py@@ -103,6 +103,7 @@ from skillevaluator.tier3.harbor.collector import (_score_definition_for_policy,collect_harbor_results,harbor_job_passed,+ harbor_timeout_job_recovered,validate_harbor_job_result,)from skillevaluator.tier3.harbor.gke_environment import (@@ -4277,7 +4278,7 @@ def _run_stop_on_pass_variant(environment_kwargs: Mapping[str, Any] | None = None,) -> list[str]:"""Run each case one attempt at a time, stopping its attempts on first pass."""- errors: list[str] = []+ errors: list[tuple[Path, str]] = []attempt_job_dirs: list[Path] = []for task_name in task_names:for attempt in range(1, n_attempts + 1):@@ -4305,12 +4306,21 @@ def _run_stop_on_pass_variant(job_dir = jobs_dir / job_nameattempt_job_dirs.append(job_dir)if not ok:- errors.append(f"{agent} {variant}-skill Harbor run failed: {task_name} attempt {attempt}: {detail}")+ errors.append(+ (job_dir, f"{agent} {variant}-skill Harbor run failed: {task_name} attempt {attempt}: {detail}")+ )continue+ errors = [+ (failed_dir, detail)+ for failed_dir, detail in errors+ if not detail.endswith(": Harbor job did not complete successfully: 1 errored")+ or not failed_dir.is_dir()+ or not harbor_timeout_job_recovered(failed_dir, job_dir)+ ]if _job_passed(job_dir, pass_threshold):break_merge_attempt_jobs(attempt_job_dirs, jobs_dir / f"{skill_name}-{agent}-{variant}")- return errors+ return [detail for _, detail in errors]def _run_agent_pair(diff --git a/tests/test_harbor_timeout_recovery.py b/tests/test_harbor_timeout_recovery.pynew file mode 100644index 00000000..008596ff--- /dev/null+++ b/tests/test_harbor_timeout_recovery.py@@ -0,0 +1,353 @@+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.+# SPDX-License-Identifier: Apache-2.0+"""Timeout recovery uses native Harbor evidence, never a fabricated reward."""++from __future__ import annotations++import copy+import json+from datetime import UTC, datetime, timedelta+from pathlib import Path+from uuid import uuid4++import pytest++pytest.importorskip("harbor")++from harbor.models.job.result import JobResult, JobStats+from harbor.models.trial.result import TrialResult++from skillevaluator.tier3.harbor.collector import (+ _pass_summary,+ _shared_metric_scorer,+ _timeout_recovered_by,+ collect_harbor_results,+ harbor_timeout_job_recovered,+)+from skillevaluator.tier3.harbor.runner import _merge_attempt_jobs+++ ("shared_value", "skill_value", "threshold", "passed"),+ [(0.0, 1.0, 0.5, False), (1.0, 0.0, 0.8, True)],+)+def test_pass_summary_recovery_uses_shared_score_and_physical_ordinal(shared_value, skill_value, threshold, passed):+ shared = {"security", "accuracy", "goal_accuracy", "behavior_check"}+ reward = {+ "entry_id": "case-a",+ "_trial_name": "case-a__attempt2",+ "_attempt_ordinal": 2,+ "security": 1.0,+ "accuracy": shared_value,+ "goal_accuracy": shared_value,+ "behavior_check": shared_value,+ "skill_execution": skill_value,+ "skill_efficiency": skill_value,+ }+ summary = _pass_summary(+ [reward],+ n_attempts=3,+ pass_threshold=threshold,+ stop_on_pass=True,+ expected_cases=1,+ expected_case_ids=["case-a"],+ recovered_attempts=[{"case_id": "case-a", "attempt": 1}],+ scorer=_shared_metric_scorer({"case-a": shared}, shared, {"case-a"}),+ )+ case = summary["cases"]["case-a"]+ assert case["passed"] is passed+ assert case["first_pass_attempt"] == (2 if passed else None)+ assert case["attempts"] == [+ {"attempt": 2, "trial": "case-a__attempt2", "score": 1.0 if passed else 0.3333, "passed": passed}+ ]+ assert case["attempts_used"] == case["attempts_recovered"] == 1+ assert case["attempts_skipped"] == int(passed)+ assert case["attempts_missing"] == int(not passed)+++def native_attempt(root: Path, attempt: int, *, timeout: bool = False, reward: float = 1.0) -> Path:+ job = root / f"demo-opencode-with-case-a-attempt{attempt:03d}"+ trial = job / f"case-a__{attempt:07d}"+ trial.mkdir(parents=True)+ start = datetime(2026, 1, 1, tzinfo=UTC) + timedelta(minutes=attempt)+ finish = start + timedelta(seconds=5)+ result = TrialResult.model_validate(+ {+ "id": uuid4(),+ "task_name": "case-a",+ "trial_name": trial.name,+ "trial_uri": trial.as_uri(),+ "task_id": {"path": str(root / "task" / "case-a")},+ "task_checksum": "public-timeout-example",+ "config": {+ "task": {"path": str(root / "task" / "case-a")},+ "trial_name": trial.name,+ "trials_dir": str(job),+ },+ "agent_info": {"name": "opencode", "version": "test", "model_info": {"name": "test-model"}},+ "agent_result": {},+ "started_at": start,+ "finished_at": finish,+ "agent_execution": {"started_at": start, "finished_at": finish},+ "exception_info": {+ "exception_type": "AgentTimeoutError",+ "exception_message": "Agent execution timed out after 5.0 seconds",+ "exception_traceback": "in _run_agent_phase\nraise AgentTimeoutError(...)",+ "occurred_at": finish,+ }+ if timeout+ else None,+ "verifier_result": None if timeout else {"rewards": {"reward": reward}},+ }+ )+ (trial / "result.json").write_text(result.model_dump_json(indent=2))+ job_result = JobResult(+ id=uuid4(),+ started_at=start,+ updated_at=finish,+ finished_at=finish,+ n_total_trials=1,+ stats=JobStats.from_trial_results([result], n_total_trials=1),+ trial_results=[result],+ )+ (job / "result.json").write_text(job_result.model_dump_json(indent=2))+ return job+++def collect(root: Path, failed: Path, successful: Path, *, stop_on_pass: bool = True):+ _merge_attempt_jobs([failed, successful], root / "jobs" / "demo-opencode-with")+ return collect_harbor_results(+ skill_name="demo",+ agents=["opencode"],+ output_dir=root / "results",+ jobs_dir=root / "jobs",+ skip_baseline=True,+ n_attempts=3,+ expected_cases=1,+ expected_case_ids=["case-a"],+ case_id_by_task_selector={"case-a": "case-a"},+ stop_on_pass=stop_on_pass,+ )+++def test_fresh_scored_retry_preserves_timeout_history(tmp_path):+ failed = native_attempt(tmp_path / "attempts", 1, timeout=True)+ passed = native_attempt(tmp_path / "attempts", 2)+ original = next(failed.glob("*/result.json")).read_bytes()+ assert harbor_timeout_job_recovered(failed, passed)+ result = collect(tmp_path, failed, passed)+ agent = result["agents"]["opencode"]+ assert result["execution_status"] == "succeeded", result.get("execution_errors")+ assert agent["overall_with_skill"] == 1.0+ condition = agent["conditions"]["with_skill"]+ assert condition["scored_attempts"] == condition["expected_attempts"] == 1+ assert condition["physical_expected_attempts"] == 2+ assert condition["recovered_attempts_total"] == 1+ assert agent["trial_failures"]["with_skill"] == []+ assert agent["recovered_trial_failures"]["with_skill"]+ assert agent["job_failures"]["with_skill"] == ""+ assert agent["historical_job_failures"]["with_skill"]+ assert agent["failure_detail_metadata"]["with_skill_trials"]["details_total"] == 0+ from skillevaluator.tier3.result_display import render_result++ rendered = render_result(result)+ assert "AgentTimeoutError" not in rendered+ assert "errored" not in rendered+ case = agent["pass_at_k"]["with_skill"]["cases"]["case-a"]+ assert case["first_pass_attempt"] == 2+ assert case["attempts_used"] == 1+ assert case["attempts_recovered"] == 1+ assert case["attempts_skipped"] == 1+ assert case["attempts_missing"] == 0+ assert next(failed.glob("*/result.json")).read_bytes() == original+ from skillevaluator.tier3.harbor.report_data import load_agent_data++ loaded = load_agent_data(tmp_path / "results")["opencode"]+ assert loaded["execution_status"] == "succeeded"+ assert loaded["execution_errors"] == []+ assert loaded["conditions"]["with_skill"]["recovered_trial_failures"]+++ "mutation",+ [+ "type",+ "origin",+ "timing",+ "checksum",+ "model",+ "config",+ "identity",+ "verifier",+ "multistep",+ ],+)+def test_recovery_rejects_ambiguous_or_different_execution(tmp_path, mutation):+ failed_job = native_attempt(tmp_path, 1, timeout=True)+ passed_job = native_attempt(tmp_path, 2)+ failed = json.loads(next(failed_job.glob("*/result.json")).read_text())+ passed = json.loads(next(passed_job.glob("*/result.json")).read_text())+ assert _timeout_recovered_by(failed, passed)+ if mutation == "type":+ failed["exception_info"]["exception_type"] = "VerifierTimeoutError"+ elif mutation == "origin":+ failed["exception_info"]["exception_traceback"] = "AgentTimeoutError in setup"+ elif mutation == "timing":+ passed["started_at"] = failed["started_at"]+ elif mutation == "checksum":+ passed["task_checksum"] = "different"+ elif mutation == "model":+ passed["agent_info"]["model_info"]["name"] = "different"+ elif mutation == "config":+ passed["config"]["timeout_multiplier"] = 2.0+ elif mutation == "identity":+ passed["id"] = failed["id"]+ elif mutation == "verifier":+ passed["exception_info"] = copy.deepcopy(failed["exception_info"])+ elif mutation == "multistep":+ failed["step_results"] = [{"step_name": "step"}]+ assert not _timeout_recovered_by(failed, passed)+++def test_fixed_attempt_budget_does_not_silently_discard_timeouts(tmp_path):+ failed = native_attempt(tmp_path / "attempts", 1, timeout=True)+ passed = native_attempt(tmp_path / "attempts", 2)+ result = collect(tmp_path, failed, passed, stop_on_pass=False)+ assert result["execution_status"] == "failed"+++def test_unscored_retry_cannot_recover_timeout(tmp_path):+ failed = native_attempt(tmp_path / "attempts", 1, timeout=True)+ failed_again = native_attempt(tmp_path / "attempts", 2, timeout=True)+ assert not harbor_timeout_job_recovered(failed, failed_again)+ assert collect(tmp_path, failed, failed_again)["execution_status"] == "failed"+++def test_post_timeout_verifier_reward_does_not_become_a_score(tmp_path):+ failed = native_attempt(tmp_path / "attempts", 1, timeout=True)+ passed = native_attempt(tmp_path / "attempts", 2)+ # Harbor may run the verifier after the deadline. Its reward is not a completed attempt.+ path = next(failed.glob("*/result.json"))+ payload = json.loads(path.read_text())+ payload["verifier_result"] = {"rewards": {"reward": 0.0}}+ path.write_text(json.dumps(payload))+ # Build canonical job statistics from the unchanged exception-bearing trial.+ result = TrialResult.model_validate(payload)+ job_path = failed / "result.json"+ job = JobResult.model_validate_json(job_path.read_text())+ job.stats = JobStats.from_trial_results([result], n_total_trials=1)+ job_path.write_text(job.model_dump_json())+ data = collect(tmp_path, failed, passed)+ assert data["execution_status"] == "succeeded"+ assert data["agents"]["opencode"]["overall_with_skill"] == 1.0+ assert data["scored_attempts"] == 1+++def test_runner_keeps_unrelated_launch_errors(tmp_path, monkeypatch):+ from skillevaluator.tier3.harbor import runner++ jobs = tmp_path / "jobs"+ native_attempt(jobs, 1, timeout=True)+ native_attempt(jobs, 2)+ calls = []++ def launch(**kwargs):+ calls.append(kwargs)+ return (False, "output exceeded safety limit") if len(calls) == 1 else (True, "")++ monkeypatch.setattr(runner, "_run_harbor", launch)+ errors = runner._run_stop_on_pass_variant(+ skill_name="demo",+ agent="opencode",+ variant="with",+ dataset=tmp_path,+ task_names=["case-a"],+ env_mode="docker",+ model="test-model",+ jobs_dir=jobs,+ run_env={},+ n_attempts=3,+ pass_threshold=0.5,+ timeout_multiplier=1,+ override_cpus=None,+ override_memory_mb=None,+ override_storage_mb=None,+ )+ assert len(calls) == 2+ assert len(errors) == 1 and "safety limit" in errors[0]+++def test_runner_does_not_retain_recovered_deadline_as_launch_failure(tmp_path, monkeypatch):+ from skillevaluator.tier3.harbor import runner++ jobs = tmp_path / "jobs"+ native_attempt(jobs, 1, timeout=True)+ native_attempt(jobs, 2)+ calls = []++ def launch(**kwargs):+ calls.append(kwargs)+ return (False, "Harbor job did not complete successfully: 1 errored") if len(calls) == 1 else (True, "")++ monkeypatch.setattr(runner, "_run_harbor", launch)+ errors = runner._run_stop_on_pass_variant(+ skill_name="demo",+ agent="opencode",+ variant="with",+ dataset=tmp_path,+ task_names=["case-a"],+ env_mode="docker",+ model="test-model",+ jobs_dir=jobs,+ run_env={},+ n_attempts=3,+ pass_threshold=0.5,+ timeout_multiplier=1,+ override_cpus=None,+ override_memory_mb=None,+ override_storage_mb=None,+ )+ assert len(calls) == 2+ assert errors == []+++def test_recovery_ignores_harbor_job_metrics(tmp_path):+ failed = native_attempt(tmp_path / "attempts", 1, timeout=True)+ passed = native_attempt(tmp_path / "attempts", 2)+ for job in (failed, passed):+ path = job / "result.json"+ payload = json.loads(path.read_text())+ for stats in payload["stats"]["evals"].values():+ stats["metrics"] = [{"mean": 0.0}]+ stats["pass_at_k"] = {"1": 0.0}+ path.write_text(json.dumps(payload))+ assert harbor_timeout_job_recovered(failed, passed)+ assert collect(tmp_path, failed, passed)["execution_status"] == "succeeded"+++def test_recovery_does_not_depend_on_directory_order(tmp_path, monkeypatch):+ attempts = [+ native_attempt(tmp_path / "attempts", 1, timeout=True),+ native_attempt(tmp_path / "attempts", 2, timeout=True),+ native_attempt(tmp_path / "attempts", 3),+ ]+ _merge_attempt_jobs(attempts, tmp_path / "jobs" / "demo-opencode-with")+ original_iterdir = Path.iterdir+ monkeypatch.setattr(Path, "iterdir", lambda self: iter(sorted(original_iterdir(self), reverse=True)))+ result = collect_harbor_results(+ skill_name="demo",+ agents=["opencode"],+ output_dir=tmp_path / "results",+ jobs_dir=tmp_path / "jobs",+ skip_baseline=True,+ n_attempts=3,+ expected_cases=1,+ expected_case_ids=["case-a"],+ case_id_by_task_selector={"case-a": "case-a"},+ stop_on_pass=True,+ )+ assert result["execution_status"] == "succeeded", result.get("execution_errors")+ agent = result["agents"]["opencode"]+ assert agent["overall_with_skill"] == 1.0+ assert len(agent["recovered_trial_failures"]["with_skill"]) == 2+ assert agent["trial_failures"]["with_skill"] == []diff --git a/tests/test_harbor_timeout_recovery_docker.py b/tests/test_harbor_timeout_recovery_docker.pynew file mode 100644index 00000000..4aef12a3--- /dev/null+++ b/tests/test_harbor_timeout_recovery_docker.py@@ -0,0 +1,132 @@+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.+# SPDX-License-Identifier: Apache-2.0+"""Real Docker/Harbor recovery check; run explicitly with pytest -m integration.++Uses a deterministic agent, not an LLM provider. Requires Docker and access to+python:3.12-slim. No service credentials, private images, or datasets are used.+"""++from __future__ import annotations++import asyncio+import json+from pathlib import Path+from uuid import uuid4++import pytest++pytest.importorskip("harbor")+from harbor.agents.base import BaseAgent+from harbor.models.job.result import JobResult, JobStats+from harbor.models.trial.config import TrialConfig+from harbor.trial.trial import Trial++from skillevaluator.evaluation.tier3_report import render_agent_eval_html_report+from skillevaluator.tier3.harbor.collector import collect_harbor_results+from skillevaluator.tier3.harbor.report_data import load_agent_data+from skillevaluator.tier3.harbor.runner import _merge_attempt_jobs+++class RecoveryExampleAgent(BaseAgent):+ @staticmethod+ def name():+ return "recovery-example"++ def version(self):+ return "1"++ async def setup(self, environment):+ pass++ async def run(self, instruction, environment, context):+ del instruction, context+ if "-with-task-attempt001" in str(self.logs_dir):+ await environment.exec("sleep 30", timeout_sec=40)+ elif "-with-" in str(self.logs_dir):+ await environment.exec("printf recovered > /app/answer.txt")+ else:+ await environment.exec("printf wrong > /app/answer.txt")+++def test_docker_timeout_retry_and_scored_wrong_baseline(tmp_path: Path):+ asyncio.run(_docker_timeout_retry_and_scored_wrong_baseline(tmp_path))+++async def _docker_timeout_retry_and_scored_wrong_baseline(tmp_path: Path):+ task = tmp_path / "task"+ (task / "environment").mkdir(parents=True)+ (task / "tests").mkdir()+ (task / "environment/Dockerfile").write_text("FROM python:3.12-slim\nWORKDIR /app\n")+ (task / "instruction.md").write_text("Write recovered to /app/answer.txt.\n")+ (task / "task.toml").write_text(+ "[agent]\ntimeout_sec = 3\n[verifier]\ntimeout_sec = 30\n[environment]\ncpus = 1\nmemory_mb = 512\n"+ )+ (task / "tests/test.sh").write_text("""#!/bin/bash+mkdir -p /logs/verifier+python - <<'CHECK'+import json+from pathlib import Path+answer = Path('/app/answer.txt')+score = float(answer.exists() and answer.read_text() == 'recovered')+metrics = ('security', 'skill_execution', 'skill_efficiency', 'accuracy', 'goal_accuracy', 'behavior_check')+Path('/logs/verifier/reward.json').write_text(json.dumps(dict.fromkeys(metrics, score)))+CHECK+""")+ failed_snapshot = None+ failed_file = None+ for arm, attempts in (("with", (1, 2)), ("without", (1, 2, 3))):+ jobs = []+ for attempt in attempts:+ job = tmp_path / "jobs" / f"demo-opencode-{arm}-task-attempt{attempt:03d}"+ config = TrialConfig(+ task={"path": task},+ trial_name=f"task__attempt{attempt:03d}",+ trials_dir=job,+ agent={"import_path": f"{__name__}:RecoveryExampleAgent"},+ environment={"type": "docker"},+ )+ trial = await Trial.create(config)+ result = await trial.run()+ native = JobResult(+ id=uuid4(),+ started_at=result.started_at,+ updated_at=result.finished_at,+ finished_at=result.finished_at,+ n_total_trials=1,+ stats=JobStats.from_trial_results([result], n_total_trials=1),+ trial_results=[result],+ )+ (job / "result.json").write_text(native.model_dump_json(indent=2))+ if arm == "with" and attempt == 1:+ assert result.exception_info.exception_type == "AgentTimeoutError"+ failed_file = job / config.trial_name / "result.json"+ failed_snapshot = failed_file.read_bytes()+ else:+ assert result.exception_info is None+ jobs.append(job)+ _merge_attempt_jobs(jobs, tmp_path / "jobs" / f"demo-opencode-{arm}")+ results = collect_harbor_results(+ skill_name="demo",+ agents=["opencode"],+ output_dir=tmp_path / "results",+ jobs_dir=tmp_path / "jobs",+ n_attempts=3,+ stop_on_pass=True,+ expected_cases=1,+ expected_case_ids=["task"],+ case_id_by_task_selector={"task": "task"},+ )+ assert results["execution_status"] == "succeeded", results.get("execution_errors")+ agent = results["agents"]["opencode"]+ assert agent["overall_with_skill"] == 1.0+ assert agent["overall_without_skill"] == 0.0+ assert agent["conditions"]["with_skill"]["recovered_attempts_total"] == 1+ assert results["scored_attempts"] == 4+ assert failed_file.read_bytes() == failed_snapshot+ assert load_agent_data(tmp_path / "results")["opencode"]["execution_errors"] == []+ skill = tmp_path / "demo"+ skill.mkdir()+ report = render_agent_eval_html_report(skill, tmp_path / "results", use_llm_judge=False)+ assert report.is_file()+ assert json.loads((tmp_path / "results/opencode/with-skill/summary.json").read_text())["overall_score"] == 1.0