Skip to content

fix: background utility completions are missing from token and cost metrics - #167986

Merged
obviyus merged 1 commit into
openclaw:mainfrom
ericcurtin:fix/isolated-completion-model-usage
Oct 10, 2026
Merged

obviyus merged 1 commit into
openclaw:mainfrom
ericcurtin:fix/isolated-completion-model-usage

Conversation

@ericcurtin

@ericcurtin ericcurtin commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Closes #167913

What Problem This Solves

Fixes: session titles, recaps and other background utility completions are missing from token and cost metrics.

User Impact

openclaw_model_tokens_total and openclaw_model_cost_usd_total now count these calls.

Why This Change Was Made

runIsolatedCompletion now emits model.usage once. Plugin completions are skipped, since they already emit it. CLI calls use the terminal turn usage, like other emitters.

Evidence

  • New isolated-completion.usage.test.ts (CLI, harness, terminal usage, no usage, plugin skip): the emit cases fail before the fix and pass after. pnpm test src/agents/isolated-completion.usage.test.ts --maxWorkers=1, about 40 to 55s.
  • pnpm test src/agents/isolated-completion and the plugin runtime and Prometheus tests pass.
  • pnpm tsgo:core and the agents, gateway and plugin tsgo:core:test shards pass.
  • Live isolated gateway, diagnostics-prometheus on, mock OpenAI-compatible provider (120 input, 7 output tokens), one sessions.title.prepare call, then GET /api/diagnostics/prometheus:
before (d0fc39e8729): title "Trip Planning", 1 provider request, no openclaw_model_* series
after  (a252cd19864): title "Trip Planning", 1 provider request, then
openclaw_model_tokens_total{agent="main",model="m1",provider="mock",token_type="input"} 120
openclaw_model_tokens_total{agent="main",model="m1",provider="mock",token_type="output"} 7
openclaw_model_tokens_total{agent="main",model="m1",provider="mock",token_type="total"} 127
openclaw_model_cost_usd_total{agent="main",model="m1",provider="mock"} 0.000134

@clawsweeper

clawsweeper Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: S labels Oct 9, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Oct 9, 2026
@clawsweeper

clawsweeper Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR includes background utility completions in token and cost metrics while preserving plugin completion accounting.

Example: Generate a session title using 101 input tokens and 17 output tokens at a cost of $0.000253.

  • Before: The title succeeds, but its token and cost series are absent.
  • After: Prometheus records 118 total tokens and $0.000253 exactly once.

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) A focused, correct repair with shipped-entry-point accounting proof, useful regressions, and no unresolved finding.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): Supplied exact-head output exercises built Gateway title and Activity recap flows through the shipped Prometheus endpoint in secretless Linux isolation, with synthetic HTTP and CLI transports, unchanged plugin and normal-turn controls, and terminal CLI totals of 118 rather than 106 tokens exactly once.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Operators cannot see background utility model tokens and costs in their existing diagnostic metrics.
Reason: The patch repairs a demonstrated accounting omission across core callers without changing completion behavior or adding product surface.

Merge readiness

✅ Ready for maintainer review

Keep open: this PR fixes a current accounting bug, has relevant shipped-entry-point proof, and introduces no actionable defects.

Priority: P2
Reviewed head: a252cd19864dfc1ac967a5f05a5afde6ece2d1b7

Before merge

None.

Findings

None.

Agent review details

How this fits together

Core title, recap, observer, narration, and transcript callers send prompts through the isolated completion owner; its validated runtime results now feed the existing diagnostic event bus and metrics exporters.

flowchart LR
  A[Background utility callers] --> B[Isolated completion owner]
  B --> C[Selected CLI or harness]
  C --> B
  B --> D[Trusted usage diagnostics]
  D --> E[Metrics exporters]
  B --> F[Completion text]
Loading

Technical review

Best possible solution:

Land this focused accounting fix through the normal maintainer workflow.

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

Current-main source establishes the missing event path, and supplied before/after Gateway output demonstrates the accounting failure; this read-only review ran no target code.

Is this the best way to solve the issue?

The shared completion owner is the appropriate boundary: it handles all core callers, reuses existing normalization and pricing, and excludes plugin calls already finalized elsewhere.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against d12658c4c9dd.

Provenance checked

  • CLI usage propagation and plugin accounting keeps the original intent (2ea5679: The merged plugin diagnostics repair propagated isolated usage to one host-owned plugin finalizer with private exporter attribution.)
  • Isolated completion lifecycle and output validation keeps the original intent (ce67ffb: The isolated-completion feature created a fresh runtime-owned inference boundary; subsequent output and admission repairs retain validation before returning results.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 4da5d44 adds src/agents/isolated-completion.ts:401 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 4da5d447f695; files: src/agents/isolated-completion.ts)

PR surface

Source +49, Tests +97. Total +146 across 2 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 1 51 2 +49
Tests 1 97 0 +97
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 148 2 +146

Review metrics

Metric Value Why it matters
Production versus regression coverage Production +51/-2; tests +97/-0 The production growth adds one shared accounting boundary and terminal usage propagation; five focused cases reuse the existing fixture without adding production test seams.

Root-cause cluster

Relationship: same_root_cause
Canonical: #167913
Summary: This PR implements the canonical report and replaces the prior closed, unmerged repair.

Members:

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

Labels

Label changes:

  • add rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • remove rating: 🐚 platinum hermit: Current PR rating is rating: 🦞 diamond lobster, so this older rating label is no longer current.

Label justifications:

  • P2: Background model spend is systematically undercounted, but completion and delivery workflows remain functional.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only; repair and merge need explicit maintainer commands such as @clawsweeper autofix or @clawsweeper automerge.

History

Review history (2 earlier review cycles)
  • reviewed 2026-10-09T22:15:43.654Z sha a252cd1 :: needs real behavior proof before merge. :: none
  • reviewed 2026-10-09T22:45:31.379Z sha a252cd1 :: needs maintainer review before merge. :: none

Reviewed October 9, 2026, 9:40 PM ET / October 10, 2026, 01:40 UTC (Revision 3).

@ericcurtin

Copy link
Copy Markdown
Contributor Author

Added live gateway before/after proof to the description. @clawsweeper re-review

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Oct 9, 2026
@obviyus

obviyus commented Oct 10, 2026

Copy link
Copy Markdown
Collaborator

Independently verified a252cd1 as-is through built Gateways in a secretless Node 24.16.0 Linux container. No source changes or push were needed. Thanks @ruel225 for the earlier #167960 contribution and the admitted-agent pricing correction, and @ericcurtin for carrying the terminal CLI usage distinction here. #167960 was closed by its author; this is the selected canonical repair.

Real caller → exporter proof

Each Gateway had isolated home/state/profile paths and a non-default loopback port, with diagnostics-prometheus enabled. Scraped the shipped endpoint /api/diagnostics/prometheus.

HTTP utility/title and sibling controls: a local OpenAI-compatible provider returned 101 input + 17 output = 118 tokens per request, priced at $0.000253. Both main 427f926e7c2d763e362f59678c6486b6f2f4aec4 and this head returned {"title":"Metrics proof title"} from sessions.title.prepare.

Real action / scrape series Main This exact head
One title, proof-utility, channel="unknown" token/cost series absent input 101, output 17, prompt 101, total 118; cost 0.000253
One plugin runtime.llm.complete, isolated mode, proof-model, channel="unknown" total 118; cost 0.000253 total 118; cost 0.000253
One normal Gateway agent turn, proof-model, channel="http" total 118; cost 0.000253 total 118; cost 0.000253
Title plus two real Activity recap calls, proof-utility token/cost series absent input 303, output 51, prompt 303, total 354; cost 0.000759

The plugin control registers through the public API and is called over Gateway RPC; the normal-turn control uses the shipped agent CLI. Provider logs confirm exactly one title, one plugin request, one normal-turn request, and two Activity recap requests. No double counting.

Terminal CLI regression: the same real sessions.title.prepare path used the bundled anthropic/claude-cli backend with a synthetic subprocess transport. Its Claude-compatible JSONL reports assistant snapshot usage 101 input / 5 output, then a successful terminal result 101 input / 17 output. The actual backend performed isolated launch, JSONL parsing and completion accounting; no internal callbacks or diagnostic emitters were substituted.

The earlier ac6fdcc98f98 build without terminal propagation and this head both returned {"title":"Terminal usage proof"}. The scrape changes from 106 total / 5 output to 118 total / 17 output, exactly once:

openclaw_model_tokens_total{agent="main",channel="unknown",model="terminal-model",provider="anthropic",token_type="input"} 101
openclaw_model_tokens_total{agent="main",channel="unknown",model="terminal-model",provider="anthropic",token_type="output"} 17
openclaw_model_tokens_total{agent="main",channel="unknown",model="terminal-model",provider="anthropic",token_type="prompt"} 101
openclaw_model_tokens_total{agent="main",channel="unknown",model="terminal-model",provider="anthropic",token_type="total"} 118

Full build passed. Focused tests passed: 121 tests across 5 files, 241.03 seconds wall time (isolated-completion.usage, isolated-completion owner, plugin LLM diagnostics and isolated runtime, Prometheus service; --maxWorkers=1). Proof Gateways are stopped; isolated artifacts are retained for maintainer handoff. These are synthetic provider/CLI transport fixtures driving real shipped entry points, not a claim of paid-provider live testing.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. labels Oct 10, 2026
@obviyus
obviyus merged commit 2c1ecd3 into openclaw:main Oct 10, 2026
145 of 146 checks passed
@obviyus

obviyus commented Oct 10, 2026

Copy link
Copy Markdown
Collaborator

Landed in 2c1ecd3. Thanks @ericcurtin for the fix, @ruel225 for the earlier PR and the pricing catch, and @etzelm for the report: background completions now show up in token and cost metrics.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 10, 2026
…etrics (openclaw#167986)

runIsolatedCompletion returned usage but never emitted a model.usage diagnostic event, so background utility completions (session titles, activity recaps) were missing from openclaw_model_tokens_total and openclaw_model_cost_usd_total. Isolated completions now emit model.usage once from the terminal usage, with cost estimated for the admitted agent; plugin runtime.llm.complete keeps its existing accounting. Verified through a built Gateway: a claude-cli title counted 118 tokens once, recaps counted, and normal and plugin turns were unchanged. Fixes openclaw#167913.

Co-authored-by: Ayaan Zaidi <[email protected]>
@ericcurtin
ericcurtin deleted the fix/isolated-completion-model-usage branch October 12, 2026 18:02
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. size: S status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

2 participants