Skip to content

fix(agents): keep cumulative token totals consistent - #117930

Merged
vincentkoc merged 2 commits into
mainfrom
fix-117586-usage-basis
Aug 2, 2026
Merged

vincentkoc merged 2 commits into
mainfrom
fix-117586-usage-basis

Conversation

@vincentkoc

Copy link
Copy Markdown
Member

Closes #117586

What Problem This Solves

Fixes an issue where multi-call agent runs exposed token metadata whose input/output/cache buckets were cumulative but whose total was replaced with the latest provider-call total. Consumers of agent-exec JSON, diagnostics, cron telemetry, and billing metadata could therefore receive an internally inconsistent aggregate.

Why This Change Was Made

usage now remains the canonical cumulative run aggregate. Latest-call context stays in the existing lastCallUsage and promptTokens fields. The obsolete lastTurnTotal override and its cross-loop plumbing were removed instead of adding another reconciliation rule.

Architectural owner: embedded agent usage normalization/reporting. No config, protocol, SDK, provider, or persistence contract changes.

User Impact

Multi-call runs now report internally consistent cumulative token totals. Current-context behavior is unchanged because it already reads lastCallUsage / promptTokens.

Evidence

  • Regression reproduced before the fix: cumulative buckets expected 350, but metadata returned the latest-call total 200.
  • Post-fix local focused proof: 41/41 tests passed across helper, terminal preparation, attempt normalization, and worker payload coverage.
  • Blacksmith Testbox: full usage-reporting.test.ts passed 10/10; pnpm check:changed passed. Run: https://github.com/openclaw/openclaw/actions/runs/30739656157
  • Post-rebase formatting, git diff --check, and the 41-test focused suite passed on current origin/main.
  • Production change is net-negative: the fix deletes the override and dead propagation paths.

Codex dependency contract checked directly at openai/codex@2b5bdcf67547860f2e5c5a605009a70026796b2b:

Regression provenance: the mixed-basis reporting policy originated in a62ff19a6638 (2026-02-16, @artale; committed by @steipete), and PR #34275 propagated it into error metadata (authored by @RealKai42, merged by @jalehman on 2026-03-04).

AI assistance: Codex assisted with investigation, implementation, tests, and structured review. The maintainer directly verified the source contracts, diff, and proof above.

@vincentkoc

Copy link
Copy Markdown
Member Author

@clawsweeper review

@vincentkoc vincentkoc self-assigned this Aug 2, 2026
@clawsweeper

clawsweeper Bot commented Aug 2, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime agents Agent runtime and tooling size: S maintainer Maintainer-authored PR labels Aug 2, 2026
@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. labels Aug 2, 2026
@clawsweeper

clawsweeper Bot commented Aug 2, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed August 2, 2026, 7:49 AM ET / 11:49 UTC.

ClawSweeper review

What this changes

The PR removes lastTurnTotal propagation so embedded-agent metadata keeps usage cumulative across all model calls while retaining latest-call context in lastCallUsage and promptTokens.

Merge readiness

⚠️ Ready for maintainer review - 2 items remain

Keep this PR open for normal maintainer review. The branch is a focused, coherent repair for a source-proven mixed-basis usage object, but it changes the observable meaning of an existing metadata field and this read-only environment could not complete the repository-required direct sibling Codex source inspection because ../codex is absent and GitHub DNS resolution failed.

Priority: P2
Reviewed head: c857ac614962f75e4195b65a27d622f124af1406

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The patch is focused, net-negative in production code, and matches the current owner boundary, with merge readiness held for compatibility and dependency-contract review rather than patch-quality defects.
Proof confidence 🌊 off-meta tidepool Not applicable: This is a member-authored PR, so the external-contributor proof gate does not apply; the supplied exact-head Testbox claims remain useful supplemental evidence but could not be independently opened from this environment.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: This is a member-authored PR, so the external-contributor proof gate does not apply; the supplied exact-head Testbox claims remain useful supplemental evidence but could not be independently opened from this environment.
Evidence reviewed 5 items Current source proves the reported inconsistency: Current main creates cumulative usage from the accumulator and then overwrites only usage.total with lastTurnTotal; lastCallUsage and promptTokens are already represented separately.
Consumers distinguish aggregate and latest-call views: The gateway usage adapter prefers aggregate agentMeta.usage and falls back to lastCallUsage; cron separately derives session context from latest-call data while emitting aggregate telemetry.
Candidate repair is focused and clean: The branch deletes the override and related propagation across embedded-run lifecycle paths, updates focused accounting coverage, and passes git diff --check; no config, protocol, persistence, dependency, or workflow files are changed.
Findings None None.
Security None None.

How this fits together

Embedded agent runs combine token usage from each model call into agent metadata. That metadata feeds session-context accounting, cron telemetry, OpenAI-compatible gateway responses, and gateway worker payloads, which need aggregate billing data and latest-call context to remain distinct.

flowchart LR
  A[Model calls] --> B[Usage accumulator]
  B --> C[Agent metadata builder]
  C --> D[Latest-call context]
  C --> E[Cumulative usage metadata]
  D --> F[Session context]
  E --> G[Cron telemetry]
  E --> H[Gateway responses and workers]
Loading

Before merge

  • Resolve merge risk (P1) - Merging changes the observable meaning of agentMeta.usage.total for multi-call runs from a latest-call override to a cumulative run total; consumers that relied on the old mixed value need maintainer-confirmed compatibility acceptance.
  • Resolve merge risk (P1) - The required direct Codex protocol/source check could not be performed in this environment, so this review cannot independently confirm the PR’s dependency-contract claims.
Agent review details

Security

None.

PR surface

Source -40, Tests +45. Total +5 across 11 files.

View PR surface stats
Area Files Added Removed Net
Source 8 2 42 -40
Tests 3 90 45 +45
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 11 92 87 +5

Review metrics

None.

Stored data model

Persistent data-model change detected: durable storage schema: src/gateway/worker-environments/worker-turn-payload.ts. Confirm migration or upgrade compatibility proof before merge.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #117586
Summary: This PR is the explicit candidate repair for the linked deterministic mixed-basis usage report.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Merge-risk options

Maintainer options:

  1. Verify the cumulative metadata contract (recommended)
    Before merge, directly inspect the Codex usage contract and confirm that supported downstream consumers should treat usage.total as a cumulative aggregate.
  2. Preserve the legacy total meaning
    Pause this PR if maintainers identify a supported consumer that requires usage.total to remain the latest-call value.

Technical review

Best possible solution:

Adopt one canonical cumulative usage object and leave current-turn context in the existing lastCallUsage and promptTokens fields, after a maintainer directly verifies the Codex usage contract and accepts the compatibility change.

Do we have a high-confidence way to reproduce the issue?

Yes: current main has a deterministic source path where cumulative accumulator fields are returned with only total replaced by lastTurnTotal; the linked issue supplies a focused multi-call helper reproduction.

Is this the best way to solve the issue?

Yes in code shape: deleting the mixed-basis override is the narrowest owner-boundary repair because latest-call context already has separate fields. The merge decision remains conditional on direct Codex-contract verification and compatibility acceptance.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 096cd231ea74.

Labels

Label justifications:

  • P2: This is a bounded correctness repair for agent token metadata rather than a crash, security, or delivery failure.
  • merge-risk: 🚨 compatibility: The patch intentionally changes the established value semantics of the existing agentMeta.usage.total field.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: This is a member-authored PR, so the external-contributor proof gate does not apply; the supplied exact-head Testbox claims remain useful supplemental evidence but could not be independently opened from this environment.

Evidence

What I checked:

  • Current source proves the reported inconsistency: Current main creates cumulative usage from the accumulator and then overwrites only usage.total with lastTurnTotal; lastCallUsage and promptTokens are already represented separately. (src/agents/embedded-agent-runner/run/helpers.ts:204, 096cd231ea74)
  • Consumers distinguish aggregate and latest-call views: The gateway usage adapter prefers aggregate agentMeta.usage and falls back to lastCallUsage; cron separately derives session context from latest-call data while emitting aggregate telemetry. (src/gateway/openai-agent-run-usage.ts:14, 096cd231ea74)
  • Candidate repair is focused and clean: The branch deletes the override and related propagation across embedded-run lifecycle paths, updates focused accounting coverage, and passes git diff --check; no config, protocol, persistence, dependency, or workflow files are changed. (src/agents/embedded-agent-runner/run/helpers.ts:205, c857ac614962)
  • Historical origin: The mixed-basis behavior appears to date to the commit explicitly named fix(agent): isolate last-turn total in token usage reporting; the later merged error-metadata work is related provenance for the affected lifecycle paths. (src/agents/embedded-agent-runner/run/helpers.ts:208, a62ff19a6638)
  • Required Codex dependency check is unavailable: Repository policy requires this reviewer to inspect sibling ../codex before a Codex-contract or proof-sufficiency claim. The sibling checkout is absent; attempts to hydrate missing partial-clone objects failed because the GitHub hostname could not resolve, and this read-only review cannot clone it. (c857ac614962)

Likely related people:

  • artale: Commit a62ff19a6638 is the identifiable origin of the last-turn total reporting policy now being removed. (role: introduced historical behavior; confidence: high; commits: a62ff19a6638; files: src/agents/embedded-agent-runner/run/helpers.ts)
  • Kai: Commit 4242c5152f59c86b232b70dfcc0e869ed1487bba added related embedded-agent error metadata that this PR also updates through the same helper boundary. (role: adjacent lifecycle contributor; confidence: medium; commits: 4242c5152f59; files: src/agents/embedded-agent-runner/run/helpers.ts)
  • Peter Steinberger: Local file-history sampling shows the most commits on the current helper path from this contributor, although the partial clone prevents a complete follow-through across older revisions. (role: recent area contributor; confidence: low; commits: e348182e8123; files: src/agents/embedded-agent-runner/run/helpers.ts)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Directly inspect the sibling Codex usage protocol/source and record the compatibility conclusion before merge.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (2 earlier review cycles)
  • reviewed 2026-08-02T09:31:46.298Z sha 1c3508b :: needs maintainer review before merge. :: none
  • reviewed 2026-08-02T10:27:27.595Z sha c857ac6 :: needs maintainer review before merge. :: none

@vincentkoc

Copy link
Copy Markdown
Member Author

Owner decision: accept and land the cumulative metadata contract after normal maintainer review.

ClawSweeper rank-up moves are complete:

The reported storage-schema flag is a path heuristic false positive: worker-turn-payload.ts constructs an existing in-memory payload and this PR removes one builder argument. No persisted shape, schema, migration, or protocol field changes.

@vincentkoc

Copy link
Copy Markdown
Member Author

@clawsweeper re-review

@vincentkoc

Copy link
Copy Markdown
Member Author

Follow-up proof at c857ac614962f75e4195b65a27d622f124af1406: corrected the cloud-worker cumulative total expectation to 405 while preserving lastCallUsage.total = 270, and added explicit zero-usage-retry plus error-exit cumulative-vs-latest coverage. Blacksmith Testbox passed all affected files (63/63): https://github.com/openclaw/openclaw/actions/runs/30743430549. Fresh branch autoreview returned no findings (correctness 0.97).

@clawsweeper

clawsweeper Bot commented Aug 2, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Aug 2, 2026
@vincentkoc

Copy link
Copy Markdown
Member Author

Exact-head rank-up closeout for c857ac614962f75e4195b65a27d622f124af1406: maintainer acceptance of the cumulative usage versus latest-call lastCallUsage contract remains explicit in #117930 (comment). I also rechecked the cited sibling openai/codex@2b5bdcf67547860f2e5c5a605009a70026796b2b protocol/session/thread sources; this follow-up commit changes tests only and does not alter that dependency contract or the supported-consumer analysis. No storage schema or persisted shape changes.

@vincentkoc
vincentkoc marked this pull request as ready for review August 2, 2026 11:44
@vincentkoc
vincentkoc merged commit 4dedd5c into main Aug 2, 2026
182 of 184 checks passed
@vincentkoc
vincentkoc deleted the fix-117586-usage-basis branch August 2, 2026 11:55
@vincentkoc

Copy link
Copy Markdown
Member Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 3, 2026
* fix(agents): keep aggregate usage totals cumulative

* test(agents): cover cumulative usage reporting paths
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling gateway Gateway runtime maintainer Maintainer-authored PR merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: S status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Usage total field is overwritten with last-turn value, producing negative derived prompt tokens

1 participant