Repository navigation
fix: CLI backend runs record only their last model call's usage - #155430
chughtapan wants to merge 3 commits into
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Rebased onto main 3ff1898 (no conflicts, diff unchanged). The earlier CI failures were in files this PR does not touch ( |
2b1a3f5 to
d9da791
Compare
|
Codex review: blocked before merge. Reviewed September 22, 2026, 7:37 PM ET / 23:37 UTC (Revision 5). ClawSweeper reviewWhat this changesThe PR records cumulative CLI-run token usage for billing, stores last-call context separately, and adds persistence tests and documentation. Regression provenancePossible regression — suspected (reviewed change). No predecessor PR is attributed. Merge readiness⛔ Blocked before merge - 4 items remain The accounting repair remains necessary, but the prior compaction finding is unresolved and aggregate-only backend results gain an unjustified fresh-context marker. The overlapping PR is not yet a verified safe replacement. Priority: P2 Review scores
Verification
How this fits togetherOpenClaw’s CLI runner converts backend process output into agent results and stored conversation records. Billing reads cumulative counters, while context displays and compaction need measurements from the latest model call. flowchart TD
A[CLI backend output] --> B[Usage parser]
B --> C[Whole-run counters]
B --> D[Last-call measurements]
C --> E[Stored assistant record]
D --> E
E --> F[Billing reports]
E --> G[Context and compaction]
Before merge
Findings
Agent review detailsSecurityNone. PR surfaceSource +42, Tests +93, Docs +5. Total +140 across 9 files. View PR surface stats
Review metricsNone. Root-cause clusterRelationship: Members:
Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything. Merge-risk optionsMaintainer options:
Copy recommended automerge instructionTechnical reviewBest possible solution: Keep cumulative billing separate from verified last-call context across every reader, preserving unavailable context when a backend supplies only aggregate counters. Do we have a high-confidence way to reproduce the issue? Yes, from source: multi-call CLI output retains terminal totals separately while main persists last-call counters; the proposed rows also expose the two context-sizing failures described below. No runtime reproduction was executed during this read-only review. Is this the best way to solve the issue? The billing/context split is appropriate, but the cutover is incomplete: compaction must consume the context snapshot consistently, and a generic usage object cannot establish last-call scope. Full review comments:
Overall correctness: patch is incorrect AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 488019c3c346. LabelsLabel changes:
Label justifications:
EvidenceAcceptance criteria:
What I checked:
Likely related people:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (4 earlier review cycles)
|
A CLI backend's terminal record is cumulative for the run, and the last streamed record is one model call. Run meta and the CLI transcript row reported the last call, so a Claude Code turn of several model calls was billed as one. usage now carries the cumulative record when the backend reports one; lastCallUsage and the transcript row's totalTokens stay the last call, which sizes the context window.
d9da791 to
be5c797
Compare
The transcript row billed the run's cumulative counters but kept the last call's totalTokens, so billing readers, which prefer an explicit total, still reported the last call. All five billing fields now come from one scope, and the last call travels as contextUsage, the existing context-snapshot contract the gateway reader already honours. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
be5c797 to
ed26510
Compare
|
Addressed the review in ed26510:
Also updated the @clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
CI run 35794144850 on ed26510: the gate failed on 7 shard jobs, none in files this PR touches (
I can't rerun jobs on this repo; a maintainer rerun of the failed jobs should clear them. The PR's own tests ( |
What Problem This Solves
Fixes: a run on a CLI backend (Claude Code) records the usage of its last model call, not the run, when the turn makes tool calls. A turn that produced 164 output tokens over several calls records 3.
User Impact
User impact:
agentMeta.usageand the CLI assistant transcript row carry the run's cumulative tokens, so session usage totals and cost views match what the backend billed. Context displays are unchanged:lastCallUsagestill sizes the context window, and the transcript row now carries the last call ascontextUsage.Why This Change Was Made
cli-run-settlement.tsalready keeps the backend's cumulative terminal record asdiagnosticUsage; the settledusagetook the last streamed record. Other runners already preferdiagnosticUsage ?? usage.The transcript row follows the contract in
docs/reference/token-use.md: billing and context are separate. All five billing fields (input,output,cacheRead,cacheWrite,totalTokens) come from one scope, the run's cumulative usage when the backend reports one, else the last call. The last call travels ascontextUsage, the same shaperesolveCliTranscriptUsagealready writes on the command path; that derivation is now one sharedderiveCliContextUsageinsrc/agents/usage.ts.totalTokenscontextUsageOut of scope:
command/post-run.ts → persistCliTurnTranscriptstill billslastCallUsage, whichattempt-execution.cli.test.tspins ("marks CLI transcript context unavailable when only cumulative usage exists"). Happy to align it in this PR or a follow-up if maintainers want both writers billing the run.Evidence
src/agents/cli-runner/cli-run-transcript.test.ts, each persisting through the real SQLite transcript: explicit totals, omitted run total, no run usage, and persistence into both readers (computeUsageTokenTotalsreports 30;aggregateSessionTranscriptUsagereports context 11).pnpm test src/agents/cli-runner/cli-run-transcript.test.ts src/agents/cli-runner.context-engine.test.ts src/agents/command/attempt-execution.cli.test.ts src/infra/session-cost-usage-reporting.test.ts --maxWorkers=1: 216 passed.src/gateway/session-utils.test.ts(covers legacy CLI rows withoutcontextUsage): 258 passed, 1 failed inlistAgentsForGateway reports whether each workspace is a git checkout, which depends on the local checkout layout (a partial-clone worktree) and not on this change.pnpm test src/agents/cli-runner/cli-run-transcript.test.ts --maxWorkers=1: 12 passed; wall time 55.7 s (vitest duration 46.6 s, of which tests 6%, transform 69%), on an 8-core Linux host. In CI run 35794144850 (shardagentic-agents-support-hosted-2) all 12 passed; the six new tests took 576 ms of test time and the file about 1.3 s.pnpm tsgo:core, oxlint, oxfmt,git diff --check, and the pre-commit guard: clean.resultevents field for field over 1-turn, 3-tool-call and 20-turn sessions (20 turns: input 120, output 4,281, cacheRead 1,276,929, cacheWrite 16,920).🤖 Generated with Claude Code