Skip to content

Record agent token usage per eval and tokens per minute in status - #63

Draft
kpprasa wants to merge 3 commits into
kpprasa/experiment-statusfrom
kpprasa/agent-token-usage
Draft

kpprasa wants to merge 3 commits into
kpprasa/experiment-statusfrom
kpprasa/agent-token-usage

Conversation

@kpprasa

@kpprasa kpprasa commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

Context

Stacks on #61.

Observed problem

During a multi-machine run, Forge users had to watch an external token dashboard to spot overload because results had costs but no agent token counts. Code review showed that main's Codex parser checks those counts, then drops them. The November runs used token counts and rates on the eval-runner branch; main lacks that way to track their use.

Impact

Users cannot track token use by model or see the rate of work. Adding raw native counts would overcount Codex and miss OpenCode reasoning. The run showed a need for an outside dashboard. Cost, time saved, and the rate of bad counts are unmeasured; the counting risks come from source review and fakes. A bad token count must not lose a valid turn or its text.

Changes

Changes

Save optional agent.usage for Codex, Claude Code, and OpenCode. Sum input, cached input, output, and reasoning across turns within each eval. Reports sum eval totals by model; status groups recent turn counts by model. Input includes cache use; output includes reasoning. Unknown counts stay null. Old artifacts may omit usage.

Codex totals of 100 then 180 yield turn counts of 100 then 80. A reset, bad counter, or lost baseline makes the delta unknown. A failed send clears the baseline; the next good send starts recovery. Claude Code reads the current call's usage. OpenCode adds reasoning to output.

Add agent_usage to stderr and events.jsonl, once per turn that ends with usage. This moves last_event_at and grows the log by one line per turn. Older log readers may show unavailable for the new state.

forge status adds input plus output seen in the past minute, even for runs that later fail. Missing, bad, stale, or partial data shows unavailable with a fixed reason. A recent count of zero stays zero. Long calls show bursts when they end.

Bad live counts become unknown and the turn goes on. Bad OpenCode token metrics are dropped while its text stays intact. Saved schemas stay strict. Regrade keeps source counts in its report with no extra scan of each run.

RunEvent is public at the package root via contracts/observability.ts. It was one object type. It is now a union, with a new branch that adds these fields to the shared fields:

{ type: 'agent_usage'; turn: number; usage: AgentTokenUsage }

This adds an event at run time. The two old phase event types still work. RunObserver code must handle the new one too. An exhaustive TypeScript switch gains a case. Stderr progress readers gain a new usage state too.

AgentTokenUsage is a new public type. AgentTurn.usage is a new optional field. result.json also gains optional agent.usage. Older Forge builds strictly reject that unknown field. They cannot load results that have it.

Why this is the right fix

Each agent owns its format; the engine owns saved totals and events. Pure helpers share the rules for null counts and safe sums. No raw native errors enter usage events or reports. Usage does not change plans, scores, or judge inputs.

The alternatives lose either timely counts or valid work:

  • Counting only completed evals lags by at least a whole eval, which can take many minutes.
  • A provider billing API adds delay and ties Forge to that provider; it is not portable.
  • Failing a turn on bad usage breaks the robustness principle: a bad count must not lose valid work.
  • Summing cumulative snapshots double counts past turns. Totals of 100 then 180 would become 280.

Per-turn deltas show recent work while null counts keep gaps visible. This change does not limit token use.

Validation

How to test it

The results below predate the latest rebase onto kpprasa/experiment-status; they have not been rerun or verified on this head.

Pinned upstream source (rust-v0.149.0) shows that Codex totals span resumed turns. This was not checked in a live run. Tests with fake CLI calls check the count math, including OpenCode's separate reasoning count.

Run these checks in order:

pnpm lint
pnpm typecheck
pnpm test
pnpm build
pnpm check:cases:built
pnpm check:docs:built
pnpm check:package

Lint, types, build, 75 cases, and 10 doc snippets passed before the rebase. The full test run passed 1,218 of 1,221 tests, with two known macOS base failures and one OpenCode timeout. That file passed all 10 tests alone. The macOS failure set varies by setup: the reviewer's copy passed 1,216 of 1,221 tests with five failures reported as unrelated to this change.

All 162 focused tests passed. Eight tests failed with their fixes removed. They cover bad counts, saved text, failed sends, stale rates, and regrade reads. Package lint and type checks passed; smoke stopped at a missing offline TOML tarball.

Live Docker checks were not run because Docker was unavailable. Tests use fake CLI calls. After folding, run the full live suite on a Docker host if model calls are authorized, using test credentials to check the pinned CLIs:

FORGE_LIVE=1 pnpm test:live

Rollout/revert plan

This build starts saving counts in results and reports, plus events in the log. Resume needs the same Forge build. A revert leaves saved files in place. Older strict readers may reject new fields or mark new log states unavailable. Keep this build to read its saved files.

cc @codeowners-ai-quality

kpprasa added a commit that referenced this pull request Oct 29, 2026
…eriment-events-log #57) content diff

Committed-By-Agent: claude
@kpprasa
kpprasa force-pushed the kpprasa/experiment-status branch from 0f594fb to a4722a5 Compare October 30, 2026 00:13
@kpprasa
kpprasa force-pushed the kpprasa/agent-token-usage branch from 4d98aca to 9a21685 Compare October 30, 2026 00:14
kpprasa added a commit that referenced this pull request Oct 31, 2026
Adds the nullable agent cost estimate and pricing version on top of #63's
usage recording. The estimate is observational and never fails an eval.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

Committed-By-Agent: claude
@kpprasa
kpprasa force-pushed the kpprasa/experiment-status branch from a4722a5 to 5eb37ce Compare October 31, 2026 19:46
@kpprasa
kpprasa force-pushed the kpprasa/agent-token-usage branch from 9a21685 to 3c94dc9 Compare October 31, 2026 19:46
Retain nullable token counters from Codex, Claude Code, and OpenCode in
completed eval results, then aggregate verified usage by model in reports.
Keep older results and reports readable when usage is absent.

Emit usage after completed agent turns and show a bounded trailing-minute
rate in status. Preserve host compositions and isolate observation failures
so recording does not change evaluation outcomes. Document the reporting
limits and cover parsing, totals, resume, regrade, and status with fakes.

Committed-By-Agent: codex
Subtract each Codex thread snapshot from its prior native counters so resumed
turns contribute only new usage. Leave resets and unknown baselines unknown,
then use the latest snapshot as the baseline for later turns.

Include OpenCode reasoning in normalized output tokens without guessing missing
counts or overflowing safe integers. Exercise all three adapters through saved
results, report totals and recent status rates, and document their counter scope.

Committed-By-Agent: codex
Token accounting is observational, so malformed native or third-party counters
must not discard a completed turn or its transcript. Normalize invalid counters
to unknown, preserve OpenCode evidence without invalid metrics, and invalidate
Codex's cumulative baseline after a failed send to avoid misattributing spend.

Show stale rates as unavailable, share observation policy limits, and reuse
worker-verified source data when building regrade reports. Document per-turn
progress events and preserve strict saved schemas and transcript validation.
Add regressions for each failure boundary and verify them with the fixes removed.

Committed-By-Agent: codex
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant