Skip to content

fix(gateway): aggregate usage.cost across agents - #42063

Closed
stablegenius49 wants to merge 1 commit into
openclaw:mainfrom
stablegenius49:pr-factory/issue-41986-usage-all-agents
Closed

stablegenius49 wants to merge 1 commit into
openclaw:mainfrom
stablegenius49:pr-factory/issue-41986-usage-all-agents

Conversation

@stablegenius49

@stablegenius49 stablegenius49 commented Mar 10, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • aggregate usage.cost across all configured gateway agents instead of only the main agent
  • merge per-agent daily/totals data before caching so the Usage header and daily cost chart use the same scope
  • add a gateway unit test covering multi-agent aggregation

Testing

  • ./node_modules/.bin/vitest run src/gateway/server-methods/usage.test.ts src/gateway/server-methods/usage.sessions-usage.test.ts --config vitest.gateway.config.ts
  • ./node_modules/.bin/oxfmt --check src/gateway/server-methods/usage.ts src/gateway/server-methods/usage.test.ts
  • node --import tsx - <<'TS' ... __test.loadCostUsageSummaryCached(...) ... TS (local smoke check against configured agents)

Fixes #41986.

@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime size: M labels Mar 10, 2026
@greptile-apps

greptile-apps Bot commented Mar 10, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes the usage.cost gateway endpoint to aggregate cost data across all configured gateway agents instead of only the main agent. It introduces three new helper functions (createEmptyCostUsageTotals, mergeCostUsageTotals, mergeCostUsageSummaries) to fan-out one loadCostUsageSummary call per agent and merge the results, and updates the cache key to include the sorted list of agent IDs so different agent configurations produce separate cache entries. A new unit test covers the multi-agent aggregation scenario.

Key changes and observations:

  • mergeCostUsageSummaries correctly accumulates both totals and per-date daily entries via a date-keyed map, then sorts by date. Logic is sound.
  • The effectiveAgentIds fallback to ["main"] preserves backward-compatible behaviour when no agents are explicitly configured.
  • The existing "loadCostUsageSummaryCached caches within TTL" test now invokes listAgentsForGateway (via the reworked loadCostUsageSummaryCached) with a bare {} as OpenClawConfig. If resolveDefaultAgentId or normalizeAgentId cannot handle an empty config, that pre-existing test will start failing after this change.
  • The new test hardcodes the floating-point precision artifact cacheWriteCost: 1.2000000000000002 (0.4 + 0.8 in IEEE 754). Using expect.closeTo() would make the intent clearer and avoid encoding platform-dependent precision into the test expectations.

Confidence Score: 4/5

  • Safe to merge; the aggregation logic is correct and the new test validates the key scenario, with two minor non-blocking concerns.
  • The core fan-out and merge logic is well-implemented and correctly cache-keyed. The main uncertainty is whether the existing TTL cache test (which now implicitly calls listAgentsForGateway with an empty config object) will remain green — this is a straightforward test-compatibility question rather than a production bug. The floating-point hardcoding in the test is a style concern only.
  • src/gateway/server-methods/usage.ts — verify that listAgentsForGateway({}) handles an empty config without throwing, to keep the pre-existing TTL cache test valid.

Last reviewed commit: da3d7d3

Comment on lines +254 to +282
expect(summary.totals).toEqual({
input: 6,
output: 8,
cacheRead: 10,
cacheWrite: 12,
totalTokens: 40,
totalCost: 4,
inputCost: 0.7,
outputCost: 1,
cacheReadCost: 1.1,
cacheWriteCost: 1.2000000000000002,
missingCostEntries: 1,
});
expect(summary.daily).toEqual([
{
date: "2026-02-05",
input: 6,
output: 8,
cacheRead: 10,
cacheWrite: 12,
totalTokens: 40,
totalCost: 4,
inputCost: 0.7,
outputCost: 1,
cacheReadCost: 1.1,
cacheWriteCost: 1.2000000000000002,
missingCostEntries: 1,
},
]);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hardcoded floating-point precision artifact

The test explicitly encodes the floating-point precision artefact cacheWriteCost: 1.2000000000000002 (i.e., 0.4 + 0.8 in IEEE 754). While this documents current behaviour, it means the same imprecise value will surface in the UI (e.g., cost charts or the Usage header). For floating-point fields, prefer expect.closeTo() so that the assertion is intent-driven rather than platform-dependent:

Suggested change
expect(summary.totals).toEqual({
input: 6,
output: 8,
cacheRead: 10,
cacheWrite: 12,
totalTokens: 40,
totalCost: 4,
inputCost: 0.7,
outputCost: 1,
cacheReadCost: 1.1,
cacheWriteCost: 1.2000000000000002,
missingCostEntries: 1,
});
expect(summary.daily).toEqual([
{
date: "2026-02-05",
input: 6,
output: 8,
cacheRead: 10,
cacheWrite: 12,
totalTokens: 40,
totalCost: 4,
inputCost: 0.7,
outputCost: 1,
cacheReadCost: 1.1,
cacheWriteCost: 1.2000000000000002,
missingCostEntries: 1,
},
]);
expect(summary.totals).toEqual(
expect.objectContaining({
input: 6,
output: 8,
cacheRead: 10,
cacheWrite: 12,
totalTokens: 40,
totalCost: 4,
inputCost: expect.closeTo(0.7),
outputCost: expect.closeTo(1.0),
cacheReadCost: expect.closeTo(1.1),
cacheWriteCost: expect.closeTo(1.2),
missingCostEntries: 1,
}),
);

The same applies to the summary.daily assertion at line 267–282. Using expect.closeTo also makes it clear this is intentional rounding—not a bug to preserve.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/gateway/server-methods/usage.test.ts
Line: 254-282

Comment:
**Hardcoded floating-point precision artifact**

The test explicitly encodes the floating-point precision artefact `cacheWriteCost: 1.2000000000000002` (i.e., `0.4 + 0.8` in IEEE 754). While this documents current behaviour, it means the same imprecise value will surface in the UI (e.g., cost charts or the Usage header). For floating-point fields, prefer `expect.closeTo()` so that the assertion is intent-driven rather than platform-dependent:

```suggestion
    expect(summary.totals).toEqual(
      expect.objectContaining({
        input: 6,
        output: 8,
        cacheRead: 10,
        cacheWrite: 12,
        totalTokens: 40,
        totalCost: 4,
        inputCost: expect.closeTo(0.7),
        outputCost: expect.closeTo(1.0),
        cacheReadCost: expect.closeTo(1.1),
        cacheWriteCost: expect.closeTo(1.2),
        missingCostEntries: 1,
      }),
    );
```

The same applies to the `summary.daily` assertion at line 267–282. Using `expect.closeTo` also makes it clear this is intentional rounding—not a bug to preserve.

How can I resolve this? If you propose a fix, please make it concise.

Comment on lines +353 to +356
const agentIds = listAgentsForGateway(params.config)
.agents.map((agent) => agent.id)
.toSorted();
const effectiveAgentIds = agentIds.length ? agentIds : ["main"];

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pre-existing TTL test may now fail with empty config

The "loadCostUsageSummaryCached caches within TTL" test passes config = {} as OpenClawConfig. Before this change, loadCostUsageSummaryCached never called listAgentsForGateway; now it does on every invocation. If listAgentsForGateway({}) throws (e.g., if resolveDefaultAgentId or normalizeAgentId cannot handle an empty config), that test will start failing. Consider also mocking listAgentsForGateway in that existing test, or ensuring the TTL test is still exercised with a minimal valid config stub.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/gateway/server-methods/usage.ts
Line: 353-356

Comment:
**Pre-existing TTL test may now fail with empty config**

The `"loadCostUsageSummaryCached caches within TTL"` test passes `config = {} as OpenClawConfig`. Before this change, `loadCostUsageSummaryCached` never called `listAgentsForGateway`; now it does on every invocation. If `listAgentsForGateway({})` throws (e.g., if `resolveDefaultAgentId` or `normalizeAgentId` cannot handle an empty config), that test will start failing. Consider also mocking `listAgentsForGateway` in that existing test, or ensuring the TTL test is still exercised with a minimal valid config stub.

How can I resolve this? If you propose a fix, please make it concise.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: da3d7d3eb7

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

endMs: params.endMs,
config: params.config,
})
const inFlight = Promise.all(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Isolate per-agent load failures in usage.cost aggregation

Using Promise.all here makes the entire usage.cost response fail when any single agent summary read rejects (for example, one agent has an unreadable/corrupt transcript file), even though other agents could still produce valid totals. Before this change only the main-agent read could fail; now one broken secondary agent can take down the aggregate endpoint for everyone querying it. Consider handling per-agent errors (e.g., settling each load and merging successful summaries) so partial data is still returned.

Useful? React with 👍 / 👎.

@prtags

prtags Bot commented Apr 23, 2026

Copy link
Copy Markdown

Related work from PRtags group known-caiman-exhw

Title: usage.cost should aggregate across configured agents

Number Title
#42063* fix(gateway): aggregate usage.cost across agents
#70205 fix(gateway): aggregate usage cost across agents

* This PR

@prtags prtags Bot mentioned this pull request Apr 23, 2026
11 of 25 tasks
@clawsweeper

clawsweeper Bot commented Apr 26, 2026

Copy link
Copy Markdown
Contributor

Closing this as duplicate or superseded after Codex automated review.

PR #42063 is a focused fix for aggregating usage.cost across configured gateway agents, but current main has not shipped that behavior and the same remaining work is now tracked by the newer, broader PR #70205. PR #70205 is in the PRtags group for the same title, is still open, and covers the same core gateway aggregation problem with additional cache-scope, explicit-agent, UI date-label, and verification coverage. Closing #42063 as superseded keeps review focused on the canonical successor rather than losing the bug fix.

Best possible solution:

Close #42063 as superseded and keep the remaining usage.cost aggregation work centralized on PR #70205 or its maintainer-chosen successor, preserving #41986 as the bug context until a complete fix lands.

What I checked:

So I’m closing this here and keeping the remaining discussion on the canonical linked item.

Codex Review notes: model gpt-5.5, reasoning high; reviewed against a57d681db9b2.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

gateway Gateway runtime size: M

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Usage dashboard shows total cost as millions of dollars while daily chart sums to ~$10-15

1 participant