diff --git a/CHANGELOG.md b/CHANGELOG.md index ce9658ba1..4ebe4a6a6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -287,6 +287,20 @@ All notable changes to SkillEvaluator are documented in this file. case names receive the same Markdown escaping, publication-label masking and terminal secret redaction as visible rows, before their displayed length is bounded. +- Tier 3 token usage per case, per agent and over all agents now counts each + attempt in the case it belongs to. An unscored attempt of a native task whose + `[metadata] entry_id` differs from its directory joins that case's row + instead of a row of its own; the collector records the case in the attempt's + `failure.json`. A scored attempt whose trajectory recorded an invalid cache + counter is no longer counted with 0 cached tokens: it adds no tokens, and + the trial names the counter in `invalid_token_counters`. A case that a run + budget cut short expects only the attempts the budget admitted, so its row + is no longer partial with missing attempts. `tier3 evaluate` prints the + agent token sums for a run whose arms all failed, and once the report + payload left the case rows out, the terminal tables say that no report has + them instead of naming the report files. `tier3 evaluate` names only the + reports the run wrote, so a NeMo Gym run no longer points at a + `tier3-benchmark.md` it never writes. - The Tier 3 security scan no longer scores an agent clearing its own output directory as a destructive command. One literal, recursive and forced `rm` of a path inside `/workspace/output` or an output directory established by the diff --git a/docs/reports.mdx b/docs/reports.mdx index 4d1eb158a..7c5f5d693 100644 --- a/docs/reports.mdx +++ b/docs/reports.mdx @@ -1103,22 +1103,29 @@ or gate. - Attempts that failed before scoring, such as an attempt that hit the agent timeout, still used tokens and are counted. So are the scored attempts of an arm that failed. `coverage.unscored_attempts` counts the attempts without a - score. Such an attempt belongs to the case whose task directory its Harbor - `result.json` or `config.json` names, or else to the case its trial name - starts with. `resources` keeps its own totals, which need every attempt of an - arm scored and measured. + score. Such an attempt belongs to the case that its `failure.json` names in + `entry_id`, which the collector records from the task the attempt ran with + either backend, so a native task whose `[metadata] entry_id` differs from + its directory keeps its case. A run without that record gives the case whose + task directory its Harbor `result.json` or `config.json` names, or else the + case its trial name starts with. `resources` keeps its own totals, which + need every attempt of an arm scored and measured. - Nothing is estimated. An attempt with a missing or invalid counter adds no - tokens. Its arm's `coverage.status` is then `partial` (other attempts were - measured) or `unavailable` (none were), and the totals cover only the measured - attempts. An arm that did not run is `not_run`, and its `totals` are `null`: - a skipped arm, or an arm without attempts that the agent has no record of or - that the payload `mode` leaves out (`with_skill_only` or `baseline_only`). - The score tables show such a baseline as not run. A sum above - 9,007,199,254,740,991 (`2^53 - 1`), the largest integer JSON keeps exact, is - `unavailable` with `total_out_of_range` and `null` totals. + tokens. A report trial whose trajectory recorded an invalid counter names + it, never its value, in `invalid_token_counters`, and its `tokens` leave + that counter out. Its arm's `coverage.status` is then `partial` (other + attempts were measured) or `unavailable` (none were), and the totals cover + only the measured attempts. An arm that did not run is `not_run`, and its + `totals` are `null`: a skipped arm, or an arm without attempts that the agent + has no record of or that the payload `mode` leaves out (`with_skill_only` or + `baseline_only`). The score tables show such a baseline as not run. A sum + above 9,007,199,254,740,991 (`2^53 - 1`), the largest integer JSON keeps + exact, is `unavailable` with `total_out_of_range` and `null` totals. - `coverage` also gives `expected_attempts`, `observed_attempts`, `measured_attempts`, and `reason_codes` such as `missing_token_counters`, - `invalid_token_counters`, and `missing_attempts`. + `invalid_token_counters`, and `missing_attempts`. A case expects the + attempts its pass@k record planned: attempts skipped after a pass and + attempts a run budget did not admit are not expected. - `delta.total_tokens` is with skill minus baseline, and `delta.total_tokens_change_percent` divides it by the baseline. A change needs complete counts in both arms for the same cases and attempts, and both arms @@ -1173,8 +1180,12 @@ its bounded preview. Each table says how many more case rows are in the JSON payload. The full terminal report (`validate --verbose` or `-r cli`) and `tier3 evaluate --verbose` print the agent rows only and name the files that hold the case rows: the HTML, Markdown and JSON reports for `validate`, and -`report.html` and `tier3-benchmark.md` in the run directory for -`tier3 evaluate`. +for `tier3 evaluate` the reports the run wrote in its run directory: +`report.html` and `tier3-benchmark.md` for a Harbor run, `report.html` alone +for a NeMo Gym run, and none when the report step failed. When the payload +left the case rows out, they say instead that no report has them. +`tier3 evaluate` also prints the agent rows for a run whose arms all failed, +after the panel that says the evaluation did not complete. ### Failure reasons and per-trial rows diff --git a/src/skillevaluator/evaluation/tier3_report.py b/src/skillevaluator/evaluation/tier3_report.py index 4a0477f63..b28719d5d 100644 --- a/src/skillevaluator/evaluation/tier3_report.py +++ b/src/skillevaluator/evaluation/tier3_report.py @@ -3474,7 +3474,7 @@ def _normalize_trials( metric_value, overall_score, ) - from skillevaluator.tier3.harbor.report_data import logical_trial_reward_groups + from skillevaluator.tier3.harbor.report_data import _token_counter_names, logical_trial_reward_groups from skillevaluator.tier3.harbor.resource_usage import normalized_trial_timing out: list[dict[str, Any]] = [] @@ -3541,6 +3541,9 @@ def _normalize_trials( } if cached_tokens is not None: trial["tokens"]["cached"] = cached_tokens + if invalid_counters := _token_counter_names(reward.get("_invalid_token_counters")): + # Names only: token usage counts the attempt as unmeasured, not as a zero cache. + trial["invalid_token_counters"] = invalid_counters timing = normalized_trial_timing(traj.get("timing")) if timing is not None: trial["timing"] = timing diff --git a/src/skillevaluator/reporting/tier3_token_usage.py b/src/skillevaluator/reporting/tier3_token_usage.py index 3496c66ec..31daa962e 100644 --- a/src/skillevaluator/reporting/tier3_token_usage.py +++ b/src/skillevaluator/reporting/tier3_token_usage.py @@ -40,8 +40,10 @@ ) #: Where ``validate``'s terminal report, which prints agent rows only, sends readers for case rows. VALIDATE_CASE_POINTER = "Token usage per case is in the HTML, Markdown and JSON reports (-r html, markdown or json)." -#: Where ``tier3 evaluate``'s terminal summary sends readers for case rows. +#: Where ``tier3 evaluate``'s terminal summary sends readers for case rows when the run wrote both reports. EVALUATE_CASE_POINTER = "Token usage per case is in report.html and tier3-benchmark.md in the run directory." +#: The same pointer for a run that wrote ``report.html`` only, such as a NeMo Gym run. +EVALUATE_REPORT_CASE_POINTER = "Token usage per case is in report.html in the run directory." #: Case rows per agent in the HTML table; the JSON payload keeps the rest. HTML_CASE_ROWS_PER_AGENT = 64 #: Marks a case row whose ID is not one of the evaluation dataset's case IDs. @@ -194,6 +196,21 @@ def dropped_case_rows_note(usage: object) -> str | None: ) +def dropped_case_rows_pointer(usage: object) -> str | None: + """For a terminal summary: say that no report has the case rows the payload dropped, if it dropped any. + + The payload that every report reads drops the case rows of every agent, so + a pointer to the reports would send readers to rows that are not there. + """ + count = _count(_mapping(usage).get("case_rows_omitted")) + if not count: + return None + return ( + f"{count:,} case row(s) were left out of every report to keep the reports within their size limits, " + "so no report has token usage per case; the agent sums cover every attempt." + ) + + def token_usage_rows( usage: object, *, @@ -291,8 +308,10 @@ def render_token_usage_table( """Print one row per agent and the all-agent row, then the notes; return whether anything printed. ``case_pointer`` names the files of the calling command that hold the - case rows. ``text`` makes agent names and notes safe for the console, for - example by redacting secrets. Cells are plain text, never console markup. + case rows, and is empty when the command wrote none; when the payload left + the case rows out, the table says that no report has them instead. ``text`` makes agent names and notes safe for the + console, for example by redacting secrets. Cells are plain text, never + console markup. """ rows, _omitted = token_usage_rows(usage, include_cases=False) if not rows: @@ -319,8 +338,7 @@ def render_token_usage_table( pointer = " ".join( part for part in ( - case_pointer, - dropped_case_rows_note(usage), + dropped_case_rows_pointer(usage) or case_pointer, unverified_case_ids_note(usage, rows, case_label=text), ) if part diff --git a/src/skillevaluator/tier3/harbor/collector.py b/src/skillevaluator/tier3/harbor/collector.py index 9c7c15205..9dd76f88c 100644 --- a/src/skillevaluator/tier3/harbor/collector.py +++ b/src/skillevaluator/tier3/harbor/collector.py @@ -1482,6 +1482,40 @@ def _looks_like_trial_dir(path: Path) -> bool: return any((path / name).exists() for name in TRIAL_DIAGNOSTIC_ARTIFACTS) or (path / "agent").exists() +def _unscored_trial_case_id( + trial_src: Path, + case_id_by_task_selector: dict[str, str] | None, + *, + arm_suffix: str = "", + task_entry_id_map: Mapping[str, str] | None = None, +) -> str: + """Return the case of a Harbor trial without a scored reward, from the task it ran. + + The task comes from the trial's ``result.json``, or from its ``config.json`` + when the trial stopped before Harbor wrote a result. Without the trusted + selector mapping, the case counts only when it is authoritative: the + ``[metadata] entry_id`` of the task path or of the arm's staged task, as + for a scored trial. Otherwise the reader keeps its own fallback. + """ + for name in ("result.json", "config.json"): + data = _read_json(trial_src / name) + if not isinstance(data, dict): + continue + result = data if name == "result.json" else {"config": data} + if case_id_by_task_selector is not None: + case_id = _entry_id_from_harbor_result(result, case_id_by_task_selector) + else: + case_id, is_authoritative = _resolve_harbor_result_entry_id( + result, + arm_suffix=arm_suffix, + task_entry_id_map=task_entry_id_map, + ) + case_id = case_id if is_authoritative else "" + if case_id: + return case_id + return "" + + def _save_unscored_trials( rewards: list[dict[str, Any]], trials_dir: Path, @@ -1492,7 +1526,19 @@ def _save_unscored_trials( agent_model: str | None = None, agent_model_source: str | None = None, persisted_names: dict[str, str] | None = None, + case_id_by_task_selector: dict[str, str] | None = None, + arm_suffix: str = "", + task_entry_id_map: Mapping[str, str] | None = None, ) -> None: + """Persist each Harbor trial without a scored reward with a ``failure.json`` record. + + The record names the attempt's case in ``entry_id``, from the trusted + ``case_id_by_task_selector`` mapping, or without it from the arm's + ``arm_suffix`` and staged ``task_entry_id_map`` when they resolve the case + as for a scored trial. Harbor names a trial after its task directory, + which for a native task with its own ``[metadata] entry_id`` is not the + case ID, so readers cannot derive the case from the name. + """ if job_dir is None or not job_dir.exists(): return agent = _bounded_reward_metadata_text(agent) or "unknown" @@ -1578,6 +1624,13 @@ def _save_unscored_trials( if agent_model: error_summary.pop("model", None) failure.update(error_summary) + if case_id := _unscored_trial_case_id( + trial_src, + case_id_by_task_selector, + arm_suffix=arm_suffix, + task_entry_id_map=task_entry_id_map, + ): + failure["entry_id"] = case_id failure_file = trial_out / "failure.json" try: _write_bounded_failure_artifact(failure_file, failure) @@ -6376,6 +6429,9 @@ def _save_trials( agent_model: str | None = None, agent_model_source: str | None = None, expected_case_ids: list[str] | set[str] | None = None, + case_id_by_task_selector: dict[str, str] | None = None, + arm_suffix: str = "", + task_entry_id_map: Mapping[str, str] | None = None, ) -> None: """Save per-trial reward.json and trajectory.json into the results directory.""" agent = _bounded_reward_metadata_text(agent) or "unknown" @@ -6499,6 +6555,9 @@ def _save_trials( agent_model=agent_model, agent_model_source=agent_model_source, persisted_names=unscored_names, + case_id_by_task_selector=case_id_by_task_selector, + arm_suffix=arm_suffix, + task_entry_id_map=task_entry_id_map, ) @@ -7660,6 +7719,9 @@ def budget_expectations( agent_model=agent_model, agent_model_source=agent_model_source, expected_case_ids=expected_case_ids, + case_id_by_task_selector=case_id_by_task_selector, + arm_suffix=with_arm_suffix, + task_entry_id_map=with_task_entry_ids, ) with_summary = { "agent": agent, @@ -7918,6 +7980,9 @@ def budget_expectations( agent_model=agent_model, agent_model_source=agent_model_source, expected_case_ids=expected_case_ids, + case_id_by_task_selector=case_id_by_task_selector, + arm_suffix=without_arm_suffix, + task_entry_id_map=without_task_entry_ids, ) without_summary = { "reused": reused_baseline_dir is not None, @@ -8162,6 +8227,9 @@ def budget_expectations( agent_model=agent_model, agent_model_source=agent_model_source, expected_case_ids=expected_case_ids, + case_id_by_task_selector=case_id_by_task_selector, + arm_suffix=with_arm_suffix, + task_entry_id_map=with_task_entry_ids, ) agent_execution = _aggregate_execution([with_execution, without_execution]) diff --git a/src/skillevaluator/tier3/harbor/report_data.py b/src/skillevaluator/tier3/harbor/report_data.py index bdf38352d..06e5b5628 100644 --- a/src/skillevaluator/tier3/harbor/report_data.py +++ b/src/skillevaluator/tier3/harbor/report_data.py @@ -694,6 +694,30 @@ def _condition_status(agent_info: dict[str, Any], condition: str) -> str: return str(data.get("execution_status") or "unknown") if isinstance(data, dict) else "unknown" +def _invalid_token_counters(final_metrics: dict[str, Any]) -> list[str]: + """Name the token counters a trajectory recorded with a value that is not a count. + + ``_trajectory_token_counter`` reads such a value as ``None``, as it reads a + counter Harbor left out. Harbor leaves out only a zero cache counter, so + token usage needs these names to keep an invalid cache counter from + counting as 0. Only names are kept, never values. + """ + return [ + name + for name in _USAGE_COUNTERS + if (value := final_metrics.get(f"total_{name}")) is not None and _trajectory_token_counter(value) is None + ] + + +def _token_counter_names(value: object) -> list[str]: + """Return the token counter names that ``value`` lists, in ``_USAGE_COUNTERS`` order. + + Anything that is not such a name is dropped, so a report trial and a + usage-only attempt name the same counters in the same order. + """ + return [name for name in _USAGE_COUNTERS if isinstance(value, list) and name in value] + + def _usage_tokens(counters: dict[str, Any]) -> dict[str, int] | None: """Return a report trial's ``tokens`` object, or ``None`` without prompt and completion counts.""" prompt = _trajectory_token_counter(counters.get("prompt_tokens")) @@ -701,16 +725,28 @@ def _usage_tokens(counters: dict[str, Any]) -> dict[str, int] | None: if prompt is None or completion is None: return None tokens = {"prompt": prompt, "completion": completion} - raw_cached = counters.get("cached_tokens") - cached = _trajectory_token_counter(raw_cached) - if raw_cached is not None and cached is None: - # An invalid recorded counter is not Harbor's omitted zero cache. - return None + cached = _trajectory_token_counter(counters.get("cached_tokens")) if cached is not None: tokens["cached"] = cached return tokens +def _attempt_usage(counters: dict[str, Any], invalid_counters: object) -> dict[str, Any]: + """Return an attempt's token fields as a report trial carries them. + + ``tokens`` holds the valid counters, and ``invalid_token_counters`` names + the counters the trajectory recorded with an invalid value. Token usage + leaves such an attempt unmeasured. + """ + usage: dict[str, Any] = {} + tokens = _usage_tokens(counters) + if tokens is not None: + usage["tokens"] = tokens + if names := _token_counter_names(invalid_counters): + usage["invalid_token_counters"] = names + return usage + + def _harbor_task_directory(trial_dir: Path) -> str | None: """Return the task directory a Harbor trial ran, from its copied ``result.json`` or ``config.json``. @@ -734,18 +770,35 @@ def _harbor_task_directory(trial_dir: Path) -> str | None: return None +def _recorded_case_id(trial_dir: Path) -> str | None: + """Return the case ID the collector recorded in an unscored attempt's ``failure.json``. + + Older runs have no such record. The file is optional, so an unreadable or + oversized one only gives ``None``. + """ + path = trial_dir / "failure.json" + failure = _load_bounded_json(path, [], artifact="failure") if path.is_file() else None + entry_id = failure.get("entry_id") if isinstance(failure, dict) else None + return entry_id if isinstance(entry_id, str) and entry_id.strip() else None + + def _unscored_attempt_usage(trial_dir: Path) -> dict[str, Any]: """Read the token counters of an attempt that has no usable reward. - The attempt is not scored, but it ran and used tokens. Its case is the task - directory its Harbor result or config names. Without one, it is the trial - name before Harbor's ``__`` suffix, which never contains ``__`` while a - case ID may. Its trajectory is optional telemetry, so an unreadable or - oversized file only leaves the counters out and does not mark score - evidence truncated. + The attempt is not scored, but it ran and used tokens. Its case is the one + the collector recorded in its ``failure.json``, which also holds for a + native task whose ``entry_id`` differs from its directory. A run without + that record gives the task directory its Harbor result or config names, or + else the trial name before Harbor's ``__`` suffix, which never contains + ``__`` while a case ID may. Its trajectory is optional telemetry, so an + unreadable or oversized file only leaves the counters out and does not + mark score evidence truncated. """ attempt: dict[str, Any] = { - "entry_id": _harbor_task_directory(trial_dir) or trial_dir.name.rsplit("__", 1)[0] or "unknown", + "entry_id": _recorded_case_id(trial_dir) + or _harbor_task_directory(trial_dir) + or trial_dir.name.rsplit("__", 1)[0] + or "unknown", "trial_id": trial_dir.name, "scored": False, } @@ -753,9 +806,8 @@ def _unscored_attempt_usage(trial_dir: Path) -> dict[str, Any]: trajectory = _load_bounded_json(trajectory_file, [], artifact="trajectory") if trajectory_file.exists() else None final_metrics = trajectory.get("final_metrics") if isinstance(trajectory, dict) else None if isinstance(final_metrics, dict): - tokens = _usage_tokens({name: final_metrics.get(f"total_{name}") for name in _USAGE_COUNTERS}) - if tokens is not None: - attempt["tokens"] = tokens + counters = {name: final_metrics.get(f"total_{name}") for name in _USAGE_COUNTERS} + attempt.update(_attempt_usage(counters, _invalid_token_counters(final_metrics))) return attempt @@ -770,9 +822,8 @@ def _withheld_attempt_usage(rewards: list[dict[str, Any]]) -> list[dict[str, Any reward = group[0] row: dict[str, Any] = {"entry_id": reward.get("entry_id"), "trial_id": reward.get("trial_id"), "scored": True} counters = reward.get("_traj") - tokens = _usage_tokens(counters) if len(group) == 1 and isinstance(counters, dict) else None - if tokens is not None: - row["tokens"] = tokens + if len(group) == 1 and isinstance(counters, dict): + row.update(_attempt_usage(counters, reward.get("_invalid_token_counters"))) rows.append(row) return rows @@ -998,6 +1049,8 @@ def load_agent_data( rewards_complete = False unscored_attempts.append(_unscored_attempt_usage(trial_dir)) continue + # Only the trajectory read below names invalid token counters, never the reward file. + reward.pop("_invalid_token_counters", None) # Derive links from the bounded, admitted on-disk layout rather # than accepting verifier-authored paths as provenance. reward["_activation_artifacts"] = {"reward": reward_file.relative_to(results_dir).as_posix()} @@ -1035,6 +1088,9 @@ def load_agent_data( ), "cached_tokens": _trajectory_token_counter(final_metrics.get("total_cached_tokens")), } + if invalid_counters := _invalid_token_counters(final_metrics): + # ``_traj`` reads them as absent; token usage must not read a bad cache as 0. + reward["_invalid_token_counters"] = invalid_counters timing = trajectory_timing(trajectory) if timing is not None: reward["_traj"]["timing"] = timing diff --git a/src/skillevaluator/tier3/result_display.py b/src/skillevaluator/tier3/result_display.py index 4f0615baf..ed51fa107 100644 --- a/src/skillevaluator/tier3/result_display.py +++ b/src/skillevaluator/tier3/result_display.py @@ -1041,6 +1041,30 @@ def _case_first_summary(result: Mapping[str, Any], *, console: Console, skill_pa return shown +def _render_token_usage(console: Console, result: Mapping[str, Any], safe: Any) -> None: + """Print the per-agent token sums that the report step recorded: measured, not scored. + + The pointer to the case rows names only the reports the run recorded + writing: a Harbor run records ``tier3-benchmark.md`` in ``benchmark_path`` + only when the file exists, a NeMo Gym run writes ``report.html`` alone, and + a run whose report step failed records neither. + """ + from skillevaluator.reporting.tier3_token_usage import ( + EVALUATE_CASE_POINTER, + EVALUATE_REPORT_CASE_POINTER, + render_token_usage_table, + ) + + pointer = ( + EVALUATE_CASE_POINTER + if result.get("benchmark_path") + else EVALUATE_REPORT_CASE_POINTER + if result.get("report_path") + else "" + ) + render_token_usage_table(console, result.get("token_usage"), case_pointer=pointer, text=safe) + + def render_evaluation_result( result: Mapping[str, Any], *, @@ -1212,10 +1236,7 @@ def safe(value: object) -> str: _render_dimensions(console=console, agents=agents, safe=safe) - from skillevaluator.reporting.tier3_token_usage import EVALUATE_CASE_POINTER, render_token_usage_table - - # Measured, not scored: per-agent token sums the report step recorded. - render_token_usage_table(console, result.get("token_usage"), case_pointer=EVALUATE_CASE_POINTER, text=safe) + _render_token_usage(console, result, safe) # The per-evaluator findings report — evaluator reasonings, evidence # pointers, and next-step suggestions — is the feedback surface that @@ -1239,6 +1260,9 @@ def safe(value: object) -> str: ) except Exception: # advisory panel: never break the run summary logging.getLogger(__name__).debug("Findings report skipped", exc_info=True) + elif incomplete and detailed: + # A run whose arms all failed has no scores to show, but its attempts still used tokens. + _render_token_usage(console, result, safe) # A recovered timeout is neither a failure nor a score; say so instead of staying silent. for line in _recovered_timeout_lines(agents) if isinstance(agents, Mapping) else []: diff --git a/src/skillevaluator/tier3/token_usage.py b/src/skillevaluator/tier3/token_usage.py index 9a3288de4..e85459bdd 100644 --- a/src/skillevaluator/tier3/token_usage.py +++ b/src/skillevaluator/tier3/token_usage.py @@ -81,29 +81,39 @@ } +# Each counter's payload name and its short name in a report trial's ``tokens``. +_COUNTERS = {"prompt_tokens": "prompt", "completion_tokens": "completion", "cached_tokens": "cached"} + + def _count(value: object) -> int | None: """Return a non-negative whole token count; bools, strings, fractions and NaN are not counts.""" return int(value) if _is_measurement(value) and float(value).is_integer() else None -def normalize_token_counts(raw: object) -> dict[str, Any] | None: +def normalize_token_counts(raw: object, *, invalid_counters: object = ()) -> dict[str, Any] | None: """Normalize one attempt's token counters, or return ``None`` when it recorded none. ``raw`` is a report trial's ``tokens`` object (``prompt``, ``completion``, ``cached``) or ATIF-style counters (``prompt_tokens`` and so on). Harbor omits a zero cache counter, so a missing cached count is 0 once the prompt - count is present. ``complete`` is ``False`` when a counter is missing or - invalid, or when cached exceeds prompt; ``invalid_counters`` names the - rejected fields, never their values. + count is present. ``invalid_counters`` is the trial's + ``invalid_token_counters``: counters its trajectory recorded with an + invalid value, which ``tokens`` leaves out. ``complete`` is ``False`` when + a counter is missing or invalid, or when cached exceeds prompt; the + result's ``invalid_counters`` names the rejected fields, never their values. """ + names = invalid_counters if isinstance(invalid_counters, list | tuple) else () + rejected = {name for name in names if isinstance(name, str) and name in _COUNTERS} if not isinstance(raw, Mapping): - return None + if not rejected: + return None + raw = {} counts: dict[str, int | None] = {} invalid: list[str] = [] - for field, short in (("prompt_tokens", "prompt"), ("completion_tokens", "completion"), ("cached_tokens", "cached")): + for field, short in _COUNTERS.items(): value = raw.get(short, raw.get(field)) - counts[field] = _count(value) - if value is not None and counts[field] is None: + counts[field] = None if field in rejected else _count(value) + if field in rejected or (value is not None and counts[field] is None): invalid.append(field) if all(count is None for count in counts.values()) and not invalid: return None @@ -183,6 +193,11 @@ def _matching_case(label: str, trial_id: str, known_cases: set[str]) -> str: return label +def _attempt_tokens(row: Mapping[str, Any]) -> dict[str, Any] | None: + """Normalize a report trial's or usage-only attempt's ``tokens`` and its ``invalid_token_counters``.""" + return normalize_token_counts(row.get("tokens"), invalid_counters=row.get("invalid_token_counters", ())) + + def _pass_at_k_branch(agent: Mapping[str, Any], condition: str) -> Mapping[str, Any]: return _mapping(_mapping(agent.get("pass_at_k")).get(condition)) @@ -213,7 +228,7 @@ def _agent_attempts(agent: Mapping[str, Any], known_cases: set[str]) -> dict[str attempts[arm].append( _Attempt( _matching_case(_case_label(trial), trial_id if isinstance(trial_id, str) else "", known_cases), - normalize_token_counts(trial.get("tokens")), + _attempt_tokens(trial), True, ) ) @@ -227,7 +242,7 @@ def _agent_attempts(agent: Mapping[str, Any], known_cases: set[str]) -> dict[str attempts[arm].append( _Attempt( _matching_case(_case_label(row), trial_id if isinstance(trial_id, str) else "", known_cases), - normalize_token_counts(row.get("tokens")), + _attempt_tokens(row), scored, ) ) @@ -299,9 +314,18 @@ def _case_expected( observed: int, pass_at_k_cases: Mapping[str, Mapping[str, Any]], ) -> int: - """Return the attempts a case should have run, from pass@k: ``k`` minus attempts skipped after a pass.""" + """Return the attempts a case should have run, from its pass@k record. + + The collector counts the case's scored, recovered and missing attempts, + which leave out attempts skipped after a pass and attempts a run budget + refused. A record without those counts gives ``k`` minus the attempts + skipped after a pass. + """ branch = _pass_at_k_branch(agent, condition) record = _mapping(pass_at_k_cases.get(case)) + used, missing = _count(record.get("attempts_used")), _count(record.get("attempts_missing")) + if used is not None and missing is not None: + return max(observed, used + (_count(record.get("attempts_recovered")) or 0) + missing) k = _count(branch.get("k")) if not record or k is None: return observed diff --git a/tests/reporting/test_tier3_token_usage_reports.py b/tests/reporting/test_tier3_token_usage_reports.py index 5646cf04a..f3203e7da 100644 --- a/tests/reporting/test_tier3_token_usage_reports.py +++ b/tests/reporting/test_tier3_token_usage_reports.py @@ -41,6 +41,7 @@ from skillevaluator.reporting.dashboard_data import comparison_rows, parse_dashboard_report from skillevaluator.reporting.tier3_token_usage import ( EVALUATE_CASE_POINTER, + EVALUATE_REPORT_CASE_POINTER, REUSED_BASELINE_NOTE, UNVERIFIED_CASE_MARK, UNVERIFIED_CASE_NOTE, @@ -51,9 +52,10 @@ unverified_case_ids_note, ) from skillevaluator.tier3 import token_usage as token_usage_module +from skillevaluator.tier3.harbor.collector import collect_harbor_results from skillevaluator.tier3.harbor.metrics import DEFAULT_METRICS from skillevaluator.tier3.harbor.report_data import load_agent_data -from skillevaluator.tier3.result_display import render_result +from skillevaluator.tier3.result_display import render_evaluation_result, render_result from skillevaluator.tier3.token_usage import drop_token_usage_cases, per_agent_token_usage REPO_ROOT = Path(__file__).resolve().parents[2] @@ -241,9 +243,120 @@ def test_unscored_attempt_with_invalid_cached_tokens_is_not_measured(tmp_path: P baseline = result.metadata["agent_eval"]["token_usage"]["agents"]["claude-code"]["baseline"] assert baseline["coverage"]["status"] == "partial" assert baseline["coverage"]["measured_attempts"] == 1 + assert baseline["coverage"]["reason_codes"] == ["invalid_token_counters"] assert baseline["totals"]["total_tokens"] == 1650 +def _set_cached_tokens(run: Path, trial: str, cached: object) -> None: + trajectory_path = run / trial / "trajectory.json" + trajectory = json.loads(trajectory_path.read_text(encoding="utf-8")) + trajectory["final_metrics"]["total_cached_tokens"] = cached + trajectory_path.write_text(json.dumps(trajectory), encoding="utf-8") + + +@pytest.mark.parametrize("cached", [-5, True, "400", 1.5, 2**60]) +def test_a_scored_attempt_whose_arm_failed_with_invalid_cached_tokens_is_not_measured( + tmp_path: Path, cached: object +) -> None: + run = _run(tmp_path) + # Claude Code's baseline failed, so the loader keeps this scored attempt for usage only. + _set_cached_tokens(run, "claude-code/without-skill/trials/case-1__a", cached) + + assert load_agent_data(run)["claude-code"]["usage_only_attempts_baseline"][0] == { + "entry_id": "case-1", + "trial_id": "case-1__a", + "scored": True, + "tokens": {"prompt": 1500, "completion": 150}, + "invalid_token_counters": ["cached_tokens"], + } + result = agent_eval_result_from_directory(tmp_path, run, use_llm_judge=False) + + assert result is not None + baseline = result.metadata["agent_eval"]["token_usage"]["agents"]["claude-code"]["baseline"] + assert (baseline["coverage"]["status"], baseline["coverage"]["measured_attempts"]) == ("partial", 1) + assert baseline["coverage"]["reason_codes"] == ["invalid_token_counters"] + # Only the timed-out attempt is measured. + assert baseline["totals"]["total_tokens"] == 48422 + + +@pytest.mark.parametrize("cached", [-5, True, "400", 1.5, 2**60]) +def test_a_scored_attempt_with_invalid_cached_tokens_is_not_measured_and_resources_keep_it( + tmp_path: Path, cached: object +) -> None: + run = _run(tmp_path) + _set_cached_tokens(run, "codex/with-skill/trials/case-1__a", cached) + + result = agent_eval_result_from_directory(tmp_path, run, use_llm_judge=False) + + assert result is not None + payload = result.metadata["agent_eval"] + codex = payload["token_usage"]["agents"]["codex"] + assert (codex["with_skill"]["coverage"]["status"], codex["with_skill"]["coverage"]["measured_attempts"]) == ( + "partial", + 1, + ) + assert codex["with_skill"]["coverage"]["reason_codes"] == ["invalid_token_counters"] + assert codex["with_skill"]["totals"]["total_tokens"] == 660 + assert codex["delta"]["reason_codes"] == ["with_skill_tokens_incomplete"] + trial = next(trial for trial in payload["agents"]["codex"]["trials"] if trial["entry_id"] == "case-1") + assert (trial["tokens"], trial["invalid_token_counters"]) == ({"prompt": 500, "completion": 50}, ["cached_tokens"]) + # ``resources`` totals prompt plus completion, which stay valid. + assert payload["agents"]["codex"]["resources"]["tokens"]["with_skill"]["total"] == 1210 + + +@pytest.mark.parametrize("cached", [0, -5], ids=["valid-cache", "invalid-cache"]) +@pytest.mark.parametrize( + "names", [[1, "a"], ["cached_tokens"], ["x" * 50]], ids=["mixed-types", "a-counter", "not-a-counter"] +) +def test_only_the_trajectory_names_the_invalid_token_counters_of_a_scored_attempt( + tmp_path: Path, names: list[Any], cached: int +) -> None: + run = _run(tmp_path) + # A scored attempt of Claude Code's failed baseline, kept for usage only, and one of a succeeded arm. + for trial in ("claude-code/without-skill/trials/case-1__a", "codex/with-skill/trials/case-1__a"): + # The collector writes no ``_`` keys to reward.json, but an edited results directory can hold them. + reward_file = run / trial / "reward.json" + reward = json.loads(reward_file.read_text(encoding="utf-8")) + reward_file.write_text(json.dumps({**reward, "_invalid_token_counters": names}), encoding="utf-8") + _set_cached_tokens(run, trial, cached) + invalid = ["cached_tokens"] if cached < 0 else [] + + usage_row = load_agent_data(run)["claude-code"]["usage_only_attempts_baseline"][0] + assert (usage_row["trial_id"], usage_row.get("invalid_token_counters", [])) == ("case-1__a", invalid) + result = agent_eval_result_from_directory(tmp_path, run, use_llm_judge=False) + + assert result is not None + payload = result.metadata["agent_eval"] + trial = next(trial for trial in payload["agents"]["codex"]["trials"] if trial["entry_id"] == "case-1") + assert trial.get("invalid_token_counters", []) == invalid + usage = payload["token_usage"]["agents"] + coverage = [usage["claude-code"]["baseline"]["coverage"], usage["codex"]["with_skill"]["coverage"]] + expected = ("partial", ["invalid_token_counters"]) if invalid else ("complete", []) + assert [(arm["status"], arm["reason_codes"]) for arm in coverage] == [expected, expected] + + +def test_report_trials_and_usage_only_attempts_name_only_token_counters_in_one_order(tmp_path: Path) -> None: + run = _run(tmp_path) + for trial in ("claude-code/without-skill/trials/case-1__a", "codex/with-skill/trials/case-1__a"): + trajectory_path = run / trial / "trajectory.json" + trajectory = json.loads(trajectory_path.read_text(encoding="utf-8")) + trajectory["final_metrics"].update(total_prompt_tokens="1500", total_cached_tokens=-5) + trajectory_path.write_text(json.dumps(trajectory), encoding="utf-8") + agents = load_agent_data(run) + usage_row = agents["claude-code"]["usage_only_attempts_baseline"][0] + assert usage_row["invalid_token_counters"] == ["prompt_tokens", "cached_tokens"] + reward = next(reward for reward in agents["codex"]["rewards"] if reward["entry_id"] == "case-1") + assert reward["_invalid_token_counters"] == ["prompt_tokens", "cached_tokens"] + # Agent data that the loader did not build can hold any list. + reward["_invalid_token_counters"] = [1, "x" * 50, "cached_tokens", "prompt_tokens"] + + payload = build_agent_eval_payload("demo", agents, use_llm_judge=False) + + assert payload is not None + trial = next(trial for trial in payload["agents"]["codex"]["trials"] if trial["entry_id"] == "case-1") + assert trial["invalid_token_counters"] == ["prompt_tokens", "cached_tokens"] + + def test_an_unscored_attempt_of_a_case_id_with_double_underscores_keeps_its_case(tmp_path: Path) -> None: run = tmp_path / "run" _arm(run, "codex", "with-skill", [("auth__login__a1b2c3d", (100, 10, 0), True)]) @@ -288,6 +401,84 @@ def test_a_stop_on_pass_unscored_attempt_takes_its_case_from_its_harbor_files(tm assert codex["delta"]["total_tokens"] == 0 +@pytest.mark.parametrize("harbor_file", ["result.json", "config.json"]) +def test_the_collector_records_the_case_of_an_unscored_native_task_attempt(tmp_path: Path, harbor_file: str) -> None: + # A native task's directory (``login-task``) differs from its ``[metadata] entry_id`` (``auth-login``). + jobs = tmp_path / "jobs" + trial = jobs / "demo-opencode-with" / "login-task__a1b2c3d" + (trial / "agent").mkdir(parents=True) + task = {"path": "/runs/x/_harbor-tasks/opencode/with/login-task"} + timeout = {"exception_type": "AgentTimeoutError", "exception_message": "Agent timed out after 600 seconds"} + # A trial that stopped before Harbor wrote its result has only its config. + harbor_record = ( + {"task_id": task, "config": {"task": task}, "exception_info": timeout} + if harbor_file == "result.json" + else {"task": task} + ) + (trial / harbor_file).write_text(json.dumps(harbor_record), encoding="utf-8") + trajectory = { + "schema_version": "ATIF-v1.4", + "session_id": "session-1", + "agent": {"name": "opencode", "version": "1"}, + "steps": [{"step_id": 1, "source": "user", "message": "Fix the login."}], + "final_metrics": {"total_prompt_tokens": 14000, "total_completion_tokens": 100}, + } + (trial / "agent" / "trajectory.json").write_text(json.dumps(trajectory), encoding="utf-8") + + for name, mapping in (("native", {"login-task": "auth-login"}), ("legacy", None)): + results = tmp_path / name + collect_harbor_results( + skill_name="demo", + agents=["opencode"], + output_dir=results, + jobs_dir=jobs, + skip_baseline=True, + expected_cases=1, + expected_case_ids=["auth-login"] if mapping else ["login-task"], + case_id_by_task_selector=mapping, + ) + failure_file = results / "opencode" / "with-skill" / "trials" / trial.name / "failure.json" + failure = json.loads(failure_file.read_text(encoding="utf-8")) + [attempt] = load_agent_data(results)["opencode"]["usage_only_attempts"] + if mapping: + assert (failure["entry_id"], attempt["entry_id"]) == ("auth-login", "auth-login") + else: + # Without the mapping nothing is recorded, and the loader keeps the task directory. + assert ("entry_id" not in failure, attempt["entry_id"]) == (True, "login-task") + assert attempt["tokens"] == {"prompt": 14000, "completion": 100} + + +def test_an_unscored_attempt_takes_the_case_its_failure_record_names(tmp_path: Path) -> None: + # Native tasks: ``fix-login-bug`` has entry_id ``auth-001`` and ``add-logout`` has ``auth-002``. + run = tmp_path / "run" + _arm( + run, "codex", "with-skill", [("fix-login-bug__a", (1000, 100, 0), True), ("add-logout__a", (900, 90, 0), True)] + ) + _arm( + run, + "codex", + "without-skill", + [("fix-login-bug__b", (1200, 120, 0), True), ("add-logout__b", (40000, 900, 0), False)], + status="failed", + ) + for variant, trial in (("with-skill", "fix-login-bug__a"), ("without-skill", "fix-login-bug__b")): + _set_reward_case(run, "codex", variant, trial, "auth-001") + _set_reward_case(run, "codex", "with-skill", "add-logout__a", "auth-002") + timed_out = run / "codex" / "without-skill" / "trials" / "add-logout__b" + failure = json.loads((timed_out / "failure.json").read_text(encoding="utf-8")) + (timed_out / "failure.json").write_text(json.dumps({**failure, "entry_id": "auth-002"}), encoding="utf-8") + task = {"path": "/runs/x/_harbor-tasks/codex/without/add-logout"} + (timed_out / "result.json").write_text(json.dumps({"task_id": task}), encoding="utf-8") + + usage = build_agent_eval_payload("demo", load_agent_data(run), use_llm_judge=False)["token_usage"] + + codex = usage["agents"]["codex"] + assert [case["entry_id"] for case in codex["cases"]] == ["auth-001", "auth-002"] + auth_002 = codex["cases"][1]["baseline"] + assert (auth_002["totals"]["total_tokens"], auth_002["coverage"]["unscored_attempts"]) == (40900, 1) + assert codex["delta"]["reason_codes"] == ["baseline_failed"] + + def test_payload_counts_the_failed_attempt_and_keeps_resources_complete_only(run_result: tuple[Path, Any]) -> None: _run_dir, result = run_result payload = result.metadata["agent_eval"] @@ -655,6 +846,9 @@ def test_tier3_evaluate_terminal_prints_the_agent_sums_the_report_step_recorded( "execution_status": "succeeded", "agents": {"codex": {"execution_status": "succeeded"}}, "token_usage": recorded, + # As the Harbor runner records the reports it wrote. + "report_path": str(run / "report.html"), + "benchmark_path": str(run / "tier3-benchmark.md"), } output = render_result(display) assert "Token Usage (measured, not scored)" in output @@ -662,6 +856,119 @@ def test_tier3_evaluate_terminal_prints_the_agent_sums_the_report_step_recorded( assert EVALUATE_CASE_POINTER in " ".join(output.split()) +def test_tier3_evaluate_terminal_prints_the_token_usage_of_a_run_whose_arms_all_failed(tmp_path: Path) -> None: + skill = tmp_path / "demo" + skill.mkdir() + run = tmp_path / "run" + attempts = { + "with-skill": [("case-1__a", (1000, 100, 400), False), ("case-2__a", (2000, 200, 0), False)], + "without-skill": [("case-1__b", (1500, 150, 0), False), ("case-2__b", (900, 47522, 0), False)], + } + for variant, trials in attempts.items(): + _arm(run, "codex", variant, trials, status="failed") + conditions = {"with_skill": {"execution_status": "failed"}, "without_skill": {"execution_status": "failed"}} + engine_result: dict[str, Any] = { + "execution_status": "failed", + "run_dir": str(run), + "agents": {"codex": {"execution_status": "failed", "conditions": conditions}}, + } + + report = render_agent_eval_html_report(skill, run, engine_result=engine_result, use_llm_judge=False) + # Without ``include_benchmark`` only report.html is written, as in a NeMo Gym run. + engine_result["report_path"] = str(report) + + assert "Token usage by case" in report.read_text(encoding="utf-8") + assert not report.with_name("tier3-benchmark.md").exists() + for verbose in (False, True): + stream = io.StringIO() + render_evaluation_result( + engine_result, console=Console(file=stream, width=220, color_system=None), verbose=verbose + ) + output = stream.getvalue() + assert "Evaluation did not complete" in output + assert "Token Usage (measured, not scored)" in output + assert re.search(r"codex\s+│\s+3,300\s+│\s+50,072\s+│\s+N/A", output) + text = " ".join(output.split()) + assert EVALUATE_REPORT_CASE_POINTER in text + assert EVALUATE_CASE_POINTER not in text + + +@pytest.mark.parametrize("written", ["both", "report.html", "none"]) +def test_tier3_evaluate_terminal_names_only_the_reports_the_run_wrote(tmp_path: Path, written: str) -> None: + skill = tmp_path / "demo" + skill.mkdir() + run = _run(tmp_path) + engine_result: dict[str, Any] = { + "execution_status": "succeeded", + "run_dir": str(run), + "agents": {"codex": {"execution_status": "succeeded"}}, + } + # The Harbor runner renders the benchmark too; the NeMo Gym runner renders report.html only. + report = render_agent_eval_html_report( + skill, run, engine_result=engine_result, use_llm_judge=False, include_benchmark=written == "both" + ) + benchmark = report.with_name("tier3-benchmark.md") + assert benchmark.is_file() is (written == "both") + # The runners record a path only for a report they wrote; a failed report step records none. + if written != "none": + engine_result["report_path"] = str(report) + if benchmark.is_file(): + engine_result["benchmark_path"] = str(benchmark) + + text = " ".join(render_result(engine_result).split()) + + assert "Token Usage (measured, not scored)" in text + named = [pointer for pointer in (EVALUATE_CASE_POINTER, EVALUATE_REPORT_CASE_POINTER) if pointer in text] + expected = {"both": [EVALUATE_CASE_POINTER], "report.html": [EVALUATE_REPORT_CASE_POINTER], "none": []} + assert named == expected[written] + assert ("Token usage per case is in" in text) is (written != "none") + + +def test_terminals_say_no_report_has_the_case_rows_the_payload_left_out( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + skill = tmp_path / "demo" + skill.mkdir() + run = _cases_run(tmp_path, agents=2, cases=6) + full = agent_eval_result_from_directory( + skill, run, engine_result=_failed_case_findings("agent-1", 3), use_llm_judge=False + ) + assert full is not None + # The case findings that the report step adds leave no room for the token case rows. + monkeypatch.setattr(reporting_base, "AGENT_EVAL_REPORT_MAX_NODES", _nodes(full.metadata["agent_eval"]) + 1) + engine_result = _failed_case_findings("agent-1", 3) + report = render_agent_eval_html_report( + skill, run, output_path=tmp_path / "report.html", engine_result=engine_result, use_llm_judge=False + ) + assert "Token usage by case" in report.read_text(encoding="utf-8") + recorded = engine_result["token_usage"] + assert recorded["case_rows_omitted"] == 12 + # ``validate`` fits the payload the same way after its applicability fields. + payload = copy.deepcopy(full.metadata["agent_eval"]) + assert drop_token_usage_cases(payload["token_usage"]) == 12 + + outputs = { + "validate": _cli_output(_validation_result_from_payload(payload)), + "tier3 evaluate": render_result( + { + "execution_status": "succeeded", + "agents": {"codex": {"execution_status": "succeeded"}}, + "token_usage": recorded, + "report_path": str(report), + "benchmark_path": str(report.with_name("tier3-benchmark.md")), + } + ), + } + + for name, output in outputs.items(): + text = " ".join(output.split()) + assert "Token Usage (measured, not scored)" in text, name + assert VALIDATE_CASE_POINTER not in text and EVALUATE_CASE_POINTER not in text, name + assert EVALUATE_REPORT_CASE_POINTER not in text, name + assert "12 case row(s) were left out of every report" in text, name + assert "left out of this report" not in text, name + + def test_terminal_tables_print_agent_names_as_text_not_markup() -> None: usage = { "agents": { @@ -840,6 +1147,7 @@ def test_docs_and_changelog_describe_the_token_usage_contract() -> None: "left out without a record", ): assert field in section, field + assert [line for line in section.splitlines() if len(line) > 80] == [] changelog = (REPO_ROOT / "CHANGELOG.md").read_text(encoding="utf-8") added_sections = [ section.split("### Added\n", 1)[1].split("\n### ", 1)[0] @@ -847,6 +1155,18 @@ def test_docs_and_changelog_describe_the_token_usage_contract() -> None: if "### Added\n" in section ] assert any("token usage per case" in section for section in added_sections) + # The Fixed entry is found in any release section, so a release heading above it can change. + fixed_entries = [ + " ".join(entry.split()).removeprefix("- ") + for section in changelog.split("\n## ")[1:] + if "### Fixed\n" in section + for entry in section.split("### Fixed\n", 1)[1].split("\n### ", 1)[0].split("\n- ") + ] + (entry,) = [entry for entry in fixed_entries if entry.startswith("Tier 3 token usage per case")] + assert "now counts each attempt in the case it belongs to." in entry + # The table needs no --verbose: a run whose arms all failed never shows a case summary. + assert "`tier3 evaluate` prints the agent token sums for a run whose arms all failed" in entry + assert "--verbose" not in entry def test_an_unverified_case_id_is_marked_in_every_table_and_explained() -> None: diff --git a/tests/test_nemo_gym_backend.py b/tests/test_nemo_gym_backend.py index 9d3f8cbf1..45dc095ef 100644 --- a/tests/test_nemo_gym_backend.py +++ b/tests/test_nemo_gym_backend.py @@ -159,6 +159,58 @@ def test_normalized_gym_jobs_are_read_by_shared_collector(tmp_path: Path) -> Non assert agent["scored_attempts"] +def test_an_unscored_gym_attempt_of_a_native_task_counts_its_tokens_in_its_case(tmp_path: Path) -> None: + from skillevaluator.evaluation.tier3_report import build_agent_eval_payload + from skillevaluator.tier3.harbor.report_data import load_agent_data + + # The native task ``login-task`` sets its own ``[metadata] entry_id``. + out, jobs = tmp_path / "out", tmp_path / "jobs" + for arm in ("with", "without"): + 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", + ) + rows = [_rollout(tmp_path / arm, "login-task", 1, 0.8), _rollout(tmp_path / arm, "login-task", 2, None)] + for row, (prompt, completion) in zip(rows, ((1000, 100), (14000, 100)), strict=True): + trajectory = { + "schema_version": "ATIF-v1.4", + "session_id": "session-1", + "agent": {"name": "codex", "version": "1"}, + "steps": [{"step_id": 1, "source": "user", "message": "Fix the login."}], + "final_metrics": {"total_prompt_tokens": prompt, "total_completion_tokens": completion}, + } + (Path(row["verifier_logs_dir"]) / "trajectory.json").write_text(json.dumps(trajectory), encoding="utf-8") + write_job_from_rollouts( + rows, + jobs / f"demo-codex-{arm}", + eval_name="codex__m", + task_case_ids={"login-task": "auth-login"}, + n_attempts=2, + ) + + collect_harbor_results( + "demo", + ["codex"], + out, + jobs, + n_attempts=2, + expected_cases=1, + expected_case_ids=["auth-login"], + expected_trials=2, + ) + + for variant in ("with-skill", "without-skill"): + failure_file = out / "codex" / variant / "trials" / "login-task__gym002" / "failure.json" + assert json.loads(failure_file.read_text(encoding="utf-8"))["entry_id"] == "auth-login" + usage = build_agent_eval_payload("demo", load_agent_data(out), use_llm_judge=False)["token_usage"] + [case] = usage["agents"]["codex"]["cases"] + assert case["entry_id"] == "auth-login" + for arm in ("with_skill", "baseline"): + assert (case[arm]["totals"]["total_tokens"], case[arm]["coverage"]["unscored_attempts"]) == (15200, 1) + + def _evaluate(monkeypatch: pytest.MonkeyPatch, tmp_path: Path, **overrides): from skillevaluator.provider_config import ProviderConfig from skillevaluator.tier3 import commands as tier3_commands diff --git a/tests/tier3/test_token_usage.py b/tests/tier3/test_token_usage.py index d5c382cf0..900fe6a30 100644 --- a/tests/tier3/test_token_usage.py +++ b/tests/tier3/test_token_usage.py @@ -5,11 +5,14 @@ from __future__ import annotations +import copy import json from typing import Any import pytest +from skillevaluator.tier3.harbor.collector import _pass_summary +from skillevaluator.tier3.harbor.metrics import DEFAULT_METRICS from skillevaluator.tier3.token_usage import build_token_usage, normalize_token_counts @@ -52,6 +55,24 @@ def _agent( } +def _collector_pass_at_k(scored: dict[str, int], *, k: int, planned: dict[str, int] | None = None) -> dict[str, Any]: + """One arm's pass@k as the collector records it: ``scored`` attempts per case, ``planned`` under a run budget.""" + scores = dict.fromkeys(DEFAULT_METRICS, 0.9) + rewards = [ + {"entry_id": case, "_trial_name": f"{case}__{index}", **scores} + for case, count in scored.items() + for index in range(count) + ] + return _pass_summary( + rewards, + n_attempts=k, + pass_threshold=0.5, + expected_cases=len(scored), + expected_case_ids=list(scored), + expected_attempts_by_case=planned, + ) + + def _scopes(usage: dict[str, Any], agent: str = "codex") -> list[dict[str, Any]]: return [usage["dataset"], usage["agents"][agent], *usage["agents"][agent]["cases"]] @@ -91,6 +112,33 @@ def test_invalid_counters_are_rejected_and_named_without_their_values(field: str assert "100" not in json.dumps(normalized["invalid_counters"]) +def test_a_counter_the_trajectory_recorded_invalid_is_rejected_although_tokens_leave_it_out() -> None: + # A report trial's ``tokens`` leave out an invalid counter; ``invalid_token_counters`` names it. + normalized = normalize_token_counts({"prompt": 100, "completion": 20}, invalid_counters=["cached_tokens"]) + assert normalized is not None + assert (normalized["complete"], normalized["cached_tokens"], normalized["invalid_counters"]) == ( + False, + None, + ["cached_tokens"], + ) + without_tokens = normalize_token_counts(None, invalid_counters=["prompt_tokens"]) + assert without_tokens is not None + assert (without_tokens["complete"], without_tokens["invalid_counters"]) == (False, ["prompt_tokens"]) + # Anything but known counter names is ignored. + assert normalize_token_counts(None, invalid_counters=["steps", {"x": 1}]) is None + + trial = {**_trial("case-1", 100, 20), "invalid_token_counters": ["cached_tokens"]} + usage = build_token_usage({"codex": _agent([trial, _trial("case-2", 50, 5)], [_trial("case-1", 90, 10)])}) + + assert usage is not None + with_skill = usage["agents"]["codex"]["with_skill"] + assert (with_skill["coverage"]["measured_attempts"], with_skill["coverage"]["reason_codes"]) == ( + 1, + ["invalid_token_counters"], + ) + assert with_skill["totals"]["total_tokens"] == 55 + + def test_cached_above_prompt_is_invalid() -> None: normalized = normalize_token_counts({"prompt": 10, "completion": 5, "cached": 11}) assert normalized is not None @@ -226,10 +274,19 @@ def test_partial_coverage_sums_only_measured_attempts_and_never_estimates() -> N assert cases["case-2"]["with_skill"]["coverage"]["status"] == "unavailable" -def test_an_attempt_that_never_ran_leaves_the_arm_partial() -> None: +@pytest.mark.parametrize( + "pass_at_k", + [ + _collector_pass_at_k({"case-1": 1}, k=2), + # A result file from before the collector counted each case's attempts. + {"k": 2, "cases": {"case-1": {"attempts_skipped": 0}}}, + ], + ids=["collector", "k-only"], +) +def test_an_attempt_that_never_ran_leaves_the_arm_partial(pass_at_k: dict[str, Any]) -> None: agent = _agent([_trial("case-1", 100, 20)], [_trial("case-1", 90, 10)]) agent["conditions"]["with_skill"]["expected_attempts"] = 2 - agent["pass_at_k"] = {"with_skill": {"k": 2, "cases": {"case-1": {"attempts_skipped": 0}}}} + agent["pass_at_k"] = {"with_skill": pass_at_k} usage = build_token_usage({"codex": agent}) @@ -282,6 +339,28 @@ def test_attempts_skipped_after_a_pass_are_not_missing() -> None: assert case["delta"]["total_tokens"] == 20 +def test_a_case_that_a_run_budget_cut_short_expects_only_the_attempts_it_admitted() -> None: + # The budget admitted all 3 attempts of case-1 but only 1 of case-2, in both arms. + trials = [ + {**_trial(case, 100, 10), "trial_id": f"{case}__{index}"} + for case, count in (("case-1", 3), ("case-2", 1)) + for index in range(count) + ] + agent = _agent(trials, copy.deepcopy(trials)) + pass_at_k = _collector_pass_at_k({"case-1": 3, "case-2": 1}, k=3, planned={"case-1": 3, "case-2": 1}) + agent["pass_at_k"] = {"with_skill": pass_at_k, "without_skill": copy.deepcopy(pass_at_k)} + + usage = build_token_usage({"codex": agent}) + + assert usage is not None + cases = {row["entry_id"]: row for row in usage["agents"]["codex"]["cases"]} + for arm in ("with_skill", "baseline"): + coverage = cases["case-2"][arm]["coverage"] + assert (coverage["status"], coverage["expected_attempts"], coverage["reason_codes"]) == ("complete", 1, []) + assert cases["case-2"]["delta"]["total_tokens"] == 0 + assert usage["agents"]["codex"]["delta"]["status"] == "available" + + def test_a_recovered_timeout_attempt_is_expected_usage() -> None: history = {"entry_id": "case-1", "trial_id": "case-1__x", "tokens": {"prompt": 10, "completion": 1}} agent = _agent([_trial("case-1", 100, 20)], [_trial("case-1", 90, 10)]) @@ -705,4 +784,3 @@ def test_two_pass_at_k_keys_for_one_case_merge_the_same_way_in_either_order(cut_ [row] = usage["agents"]["codex"]["cases"] assert row["entry_id"] == _LONG_CASE assert row["with_skill"]["coverage"]["expected_attempts"] == 3 -