Skip to content

feat(optimization): report the run's cost by role and phase - #618

Merged
nhungbi merged 3 commits into
strands-agents:mainfrom
jjbuck:opt/cost-breakdown
Nov 25, 2026
Merged

nhungbi merged 3 commits into
strands-agents:mainfrom
jjbuck:opt/cost-breakdown

Conversation

@jjbuck

@jjbuck jjbuck commented Nov 17, 2026

Copy link
Copy Markdown
Collaborator

Description

OptimizationResult reports what a run spent in four fields, and they hide where the spend went:

  • agent_cost counts only each trial's last attempt, so an attempt that a re-run pass replaced, or that Experiment retried on throttling, is missing from the agent's cost.
  • retry_cost holds those earlier attempts, but it adds the agent's usage in them to the failed judges' usage, so neither role's total can be read off.
  • search_cost is one total over every proposer, with no per-block figure and no count of failed proposer attempts.

For example, take a one-iteration run of the smoke-test agent (a scripted model that reports tokens) where one trial's sandbox fails after the agent ran, and one judge raises after its model call. Both are retried. Over every attempt, the agent used 33,882 tokens and the judges 3,080. The result reported agent_cost 33,182 (summed over splits), judge_cost 3,040, and retry_cost 740, which is the agent's 700 and the judge's 40 added together.

This PR replaces the four fields with one cost: RunCost, by role and phase:

  • cost.agent[split] is an AgentSpend: the agent's usage on that split's trials over every attempt, the trial count, the attempts to run the agent, and how many of those failed (agent_failure or infrastructure_invalid).
  • cost.judges[split] is a Spend: the evaluators' usage on those trials, the failed judges of earlier attempts included, and the attempts with a failed evaluator.
  • cost.proposers[block] is a Spend for each block of the search: what its proposer reported spending, and its failed attempts (proposer_retry and proposer_error events).
  • cost.total sums every role.

Splits are the phases, as elsewhere in the module: train is the search, and validation and test are the end phase. usage.model_calls is each role's model call count. The optimizer doesn't record how many times it called propose, so that count isn't reported.

_finish builds RunCost from every saved trial and every event. A killed iteration's trials and proposer calls still count after a resume, as before. Because the proposer figures now come from the event log, Optimizer._search_cost and ResumeState.search_cost were a second copy of the same sum, and this PR removes them. Adding a proposer's proposer_usage event to _search_cost was also what rejected an event without a Usage before it was written. The proposer log callback now checks the type itself, so a bad event still ends the search with proposer_error instead of being saved and failing _finish later, on every resume.

summary() replaces its cost sentence with the total tokens and a table: tokens per split, model calls, the agent's attempts, and each role's failed attempts, one row per role, then the total.

Behavior changes:

  • agent_cost, search_cost, judge_cost and retry_cost are removed; read result.cost instead. They exist only on this workstream branch, since feat(optimization): the Optimizer: the loop, the end phase, resume, and the results API #535, and in no release.
  • The agent's and the judges' figures now include earlier attempts, so they are larger whenever a trial was retried.
  • The cost lines of summary() are different.
  • Spend, AgentSpend and RunCost are exported from strands_evals.optimization.
  • A result.json written before this change no longer loads with OptimizationResult.from_file. Resuming the finished run rewrites it. Run directories and event logs are unchanged, so earlier runs resume as before.

Related Issues

Part of #442. The cost fields were introduced in #535.

Documentation PR

None

Type of Change

Breaking change

Testing

New tests:

  • tests/strands_evals/optimization/test_result.py (new file, mirroring result.py):
    • test_the_agent_and_the_judges_count_every_attempt_each_in_its_own_role: hand-built trial records with a re-run pass, a throttled attempt, judge-only re-runs (one after completed, one after evaluator_invalid), an agent failure, and a trial left infrastructure_invalid. It checks each split's usage, trials, attempts and failed attempts for the agent and the judges.
    • test_each_block_gets_its_proposers_spend_and_failed_attempts: every block appears in the search's order, a block that reported nothing is zero, a block only the events name comes last, and both kinds of proposer_usage event and both failure events count.
    • test_the_summary_table_has_a_row_per_role_and_the_total.
  • tests/strands_evals/optimization/test_smoke.py::test_retried_agent_and_judge_spend_counts_in_their_own_roles: the example above on a real Optimizer run. The agent's cost equals its usage over every attempt, which is more than its last attempts' usage, with one more attempt than trials and one failed. The judges' cost is one judgment more than the trial count, with one failed attempt.
  • tests/strands_evals/optimization/test_optimizer.py::test_a_proposer_usage_event_without_a_usage_is_refused_before_it_is_written: the search stops with proposer_error, the event names the TypeError, and no proposer_usage event is written.

Updated tests: the killed-run tests that read ResumeState.search_cost and Optimizer._search_cost now read each block's proposer tokens from the run's event log, the way the result counts them. They now check per-block figures, for example {"structure": 10, "numbers": 10} where they checked a total of 20, and test_a_proposers_spend_on_no_patch_is_counted_and_survives_resume is renamed test_a_proposers_spend_on_no_patch_is_counted_under_its_block, since it no longer reads a resume state. The ResumeState.search_cost assertion in tests/strands_evals/optimization/record/test_resume.py is deleted with the field; test_result.py and the killed-run tests cover what it checked. Other tests that read the old fields now read result.cost.

On workstream/optimizer-workflow, the new cost tests fail: the result has no cost, and its old fields give the figures in the example above.

Results:

  • pytest tests/strands_evals/optimization tests/strands_evals/types/optimization: 1461 passed, 1 xfailed.

  • ruff check and ruff format --check on the changed files: clean.

  • mypy -p strands_evals: no errors in the optimization module. The 24 errors it reports in other modules are already on workstream/optimizer-workflow.

  • I ran hatch run prepare

Checklist

  • I have read the CONTRIBUTING document
  • I have reviewed and understand every line of code in this PR, including any generated by AI tools, and I can explain why it works
  • My change is focused and reasonably small; I have split unrelated work into separate PRs
  • I have added any necessary tests that prove my fix is effective or my feature works
  • I have updated the documentation accordingly
  • I have added an appropriate example to the documentation to outline the feature, or no new docs are needed
  • My changes generate no new warnings
  • Any dependent changes have been merged and published

By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.

@jjbuck
jjbuck requested a review from a team as a code owner November 17, 2026 21:42
@jjbuck
jjbuck requested a review from notowen333 November 17, 2026 21:42
@github-actions github-actions Bot added area-core Core eval framework: Case, Experiment, task handler, evaluation data stores enhancement New feature or request labels Nov 17, 2026
arielnabavian
arielnabavian previously approved these changes Nov 24, 2026
@nhungbi
nhungbi changed the base branch from workstream/optimizer-workflow to main November 24, 2026 22:16
@nhungbi
nhungbi deployed to auto-approve November 24, 2026 22:16 — with GitHub Actions Active
@nhungbi
nhungbi deployed to auto-approve November 24, 2026 22:16 — with GitHub Actions Active
@github-actions

Copy link
Copy Markdown

Assessment: Comment

The cost accounting is correct. I followed every path that writes previous_attempts (re-run passes, Experiment throttling retries, judge-only re-runs), and attempts / failed hold up on each one. The other remaining points are about how the change is presented to users: an unclear error when loading an old result.json, and a summary table that doesn't match the description (both inline).

Review Categories
  • PR description is out of date with the head commit: It says four fields are replaced, but benchmark_cost is removed too and now lives in RunCost.benchmark, which the description doesn't mention. It lists test_the_summary_table_has_a_row_per_role_and_the_total, but that test doesn't exist; the table is checked inside the existing summary tests, and test_the_rollouts_other_agents_count_per_split_in_every_attempt is new but not listed. It also describes table columns that aren't in the table. Please bring it in line so reviewers and the changelog reflect what ships.
  • API review: The PR exports three new public types (Spend, AgentSpend, RunCost) and breaks the OptimizationResult contract, but it has no api/needs-review label. The workstream is unreleased, so this matters less, but it's worth labeling so the shape gets reviewed before the release. One design point to raise there: benchmark is the only role stored as a plain Usage instead of a Spend, so code that walks every role has to treat it separately (as _tokens_table and total already do).
  • Verification: pytest tests/strands_evals/optimization tests/strands_evals/types/optimization tests/strands_evals/cli/test_agent_file.py gives 1874 passed and 2 skipped on 554576d. No references to the removed fields are left in the source, tests or docs.

Moving the proposer totals onto the event log, so they no longer need their own copy in ResumeState, is a nice simplification.

jjbuck and others added 2 commits November 24, 2026 17:57
The result's four cost fields hid where a run's spend went. agent_cost
counted only each trial's last attempt, retry_cost added the agent's
earlier attempts to the failed judges' usage, and search_cost was one
total over every proposer with no failure counts.

OptimizationResult.cost (RunCost) replaces them. The agent's and the
judges' usage is reported per split over every attempt; the agent's
cell also counts trials, attempts to run the agent, and failed attempts,
and the judges' cell counts attempts with a failed evaluator. Each block
of the search gets its proposer's reported usage and its failed attempts
(proposer_retry and proposer_error events). summary() shows the total
and a table with one row per role.

The rollouts' other agents (benchmark_usage, a simulated user) are a role of
RunCost too, per split over every attempt, replacing benchmark_cost; the
summary's tokens table shows one row per role with its failed attempts.

The cost is built in _finish from every saved trial and every event, so
a killed iteration's spend still counts after a resume. That made
Optimizer._search_cost and ResumeState.search_cost a second copy of the
proposer sum, so they are removed; the proposer log callback now checks
that a proposer_usage event carries a Usage before writing it, which
the running sum used to enforce.
… fix for an old result, and count every role in the UI's cost

- `AgentSpend.failed` counts `agent_failure` attempts only, as `CandidateScores.failures` does;
  `AgentSpend.infrastructure` counts the `infrastructure_invalid` ones (throttling, a lost sandbox).
- Each `RunCost` field documents what its `failed` counts.
- Loading a `result.json` written before `cost` raises an error that names the resume that rewrites it.
- The UI's cost figure and spend-by-iteration chart count every role and every attempt, as `cost` does.
…d attempts again

Splitting them into AgentSpend.infrastructure hid them: the summary showed no column for it. The
summary note now says plainly that infrastructure failures such as throttling count.
@liramon2
liramon2 deployed to auto-approve November 24, 2026 23:14 — with GitHub Actions Active
@liramon2
liramon2 deployed to auto-approve November 24, 2026 23:15 — with GitHub Actions Active
@github-actions

Copy link
Copy Markdown

Assessment: Comment

Re-reviewed at 6513452. 9c5a7c4 is the first commit rebased onto #608 with no changes to the cost logic, so this pass covers 9c5a7c4..6513452. The old-result.json error is fixed: it names the fields and the resume that rewrites the file, and I checked that optimize resume does reload result.json on a finished run, so the advice to move it aside is correct. Splitting agent_failure from infrastructure_invalid matches CandidateScores.failures. In the UI, counting only the last record per trial means earlier attempts aren't counted twice.

Still open
  • Summary table vs. description: The thread about the table's columns was resolved, but the table didn't change, and the new AgentSpend.infrastructure count isn't shown anywhere in summary() either. Since failed now leaves infrastructure out, a run that was throttled heavily shows 0 failed and higher tokens, with nothing in the summary to explain the difference. I'd add an infra (or attempts) column for the agent row. Otherwise, please update the description.
  • PR description is more out of date than before: It still says the agent's failed counts "agent_failure or infrastructure_invalid", that "four fields" are replaced (it's five), and that from_file can't load an old result. It also lists test_the_summary_table_has_a_row_per_role_and_the_total, which doesn't exist, and doesn't mention the UI cost change in ui-optimizer-record.js / ui-optimizer.js, which changes what the cost figure and the per-iteration chart show.
  • API review label: My earlier note still applies. The PR has new exported types and a changed OptimizationResult contract, with no api/needs-review label.

Verification:

  • pytest tests/strands_evals/optimization tests/strands_evals/types/optimization tests/strands_evals/cli: 2591 passed. The one failure, test_fetch_langfuse_writes_session_json, is because the langfuse extra isn't installed locally.
  • tests/ui/optimization.mjs: 269 passed.

@github-actions

Copy link
Copy Markdown

Assessment: Comment

Re-reviewed through 4e998ad. Two new commits since my last review:

  • 6513452 adds a clear error when loading a result.json written before cost existed, and makes the UI's cost count every role and every attempt.
  • 4e998ad undoes the brief split of AgentSpend.infrastructure, so the agent's failed again counts infrastructure failures.

Both look right. The new error message points to a fix that works: optimize resume prints the saved result.json when one exists, so moving it aside is what makes resume rewrite it. The UI only counts each trial's last record, so earlier attempts aren't counted twice. The code has nothing left that needs to change before merge.

Remaining items
  • Summary table vs. description: I resolved the earlier thread on this, but the table still shows only search / validation / test / total / failed. The description still says it has "model calls" and "the agent's attempts" columns. Your own commit message for 4e998ad names the problem: a count with no column is hidden. That's also true of AgentSpend.attempts, which is the figure that explains why the agent's tokens grow after a re-run. Please either add an attempts column (with - for the other rows), or change the description to match the table.
  • PR description is out of date: It still says "four fields", but benchmark_cost is removed too and now lives in RunCost.benchmark. It lists test_the_summary_table_has_a_row_per_role_and_the_total, which doesn't exist. Under Behavior changes it says an old result.json "no longer loads"; it now fails with an error naming the resume that rewrites it. It also doesn't mention the UI change in ui-optimizer-record.js / ui-optimizer.js.
  • API review: The PR still has no api/needs-review label, although it exports three new public types and changes the OptimizationResult contract.
  • Verification on 4e998ad: pytest tests/strands_evals/optimization tests/strands_evals/types/optimization tests/strands_evals/cli gives 2591 passed and 1 failed. The failure is test_fetch_langfuse_writes_session_json; it fails the same way on the base commit 425d46b, because the langfuse extra isn't installed, so it isn't caused by this PR. The UI suites (tests/ui, npm test) pass: all 13.

The error for an old result is a good fix: it names what changed and how to recover.

@nhungbi
nhungbi merged commit f8e9be0 into strands-agents:main Nov 25, 2026
20 checks passed
nhungbi pushed a commit to nhungbi/harness-sdk that referenced this pull request Nov 25, 2026
…d trajectory-free reports

Replace agent_cost/judge_cost/search_cost/retry_cost with result.cost by role and split
(strands-agents/evals#618), and update the quickstart's Tokens table from the same run.
Show a JsonField on a number, a boolean, or a set of values, which now reaches the factory
typed and is searched with TPE (strands-agents#599). Say that report rows name their transcript instead
of carrying the trajectory (strands-agents#610).

This branch was successfully deployed

1 active deployment
auto-approve — 4e998ade Deployed Nov 24, 2026 by liramon2 via Trigger Strands Review #966
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area-core Core eval framework: Case, Experiment, task handler, evaluation data stores enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants