Skip to content

fix(agents): emit model.usage for isolated completions - #167960

Closed
ruel225 wants to merge 2 commits into
openclaw:mainfrom
ruel225:fix/isolated-completion-usage-diagnostics
Closed

ruel225 wants to merge 2 commits into
openclaw:mainfrom
ruel225:fix/isolated-completion-usage-diagnostics

Conversation

@ruel225

@ruel225 ruel225 commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Closes #167913

What Problem This Solves

runIsolatedCompletion returns the runtime's usage but never emits a model.usage diagnostic event. Its five core callers (conversation-label-generator.ts, progress-narrator-model.ts, session-observer-model.ts via session activity summaries and observer completions, summary-model.ts) read only the returned .text, so every background utility completion — session titles, activity recaps, session-observer runs, progress narration, transcript summaries — is invisible to openclaw_model_tokens_total and openclaw_model_cost_usd_total. Operators on a Claude CLI-backed gateway with the default utility model lose the entire Haiku series: the reporter measured 778 billed calls ($8.03, ~3.9M tokens) with no matching Prometheus series.

Sibling paths already count these calls: plugin runtime.llm.complete completions emit model.usage through finalizePluginLlmCompletion (#107937), and cron isolated agent runs emit through recordCronRunUsage.

Fix

Emit one trusted model.usage event centrally in runIsolatedCompletion, after a completed call, with token buckets normalized via normalizeUsage and cost estimated through estimateAggregateUsageCost against the model cost config — the same estimator the plugin path uses for isolated runtimes. Two boundaries:

  • Plugin completions are skipped (purpose === "plugin-completion"): their two callers pass usage to finalizePluginLlmCompletion, which emits there. Emitting centrally too would double-count them.
  • Emission keeps the existing gates: diagnostics enabled on the run's admission config, and positive finite usage only (CLI runtimes may report no usage; absence is not projected as zero).

Evidence

Pre-fix reproduction (test 1 below fails on main): with the CLI harness stubbed to return {input: 10, output: 462, cacheRead: 0, cacheWrite: 4111, total: 4583}, runIsolatedCompletion returns the usage but the diagnostic bus records zero model.usage events:

❯ src/agents/isolated-completion.usage-diagnostics.test.ts:51:23
 FAIL  … > emits one model.usage event when a CLI isolated completion reports usage
      Tests  2 failed | 3 passed (5)

(Without the fix, both emission tests fail — the CLI-path test and the harness-path test — while the skip/gating tests pass. This matches the reporter's observation that diagnostic events observed: [] on main at 476ce032f4f0.)

Post-fix, all five cases pass:

✓ emits one model.usage event when a CLI isolated completion reports usage
✓ emits one model.usage event from the harness path
✓ skips the central emission for plugin completions that finalize their own usage
✓ emits nothing when diagnostics are disabled
✓ emits nothing when the CLI runtime reports no usage
 Test Files  1 passed (1)
      Tests  5 passed (5)

The event carries the labels metrics consumers already read — agentId, provider, model — plus usage: {input: 10, output: 462, cacheRead: 0, cacheWrite: 4111, promptTokens: 4121, total: 4583}.

No behavior change for callers: the returned result is unchanged; only the diagnostic stream gains the event. The existing isolated-completion.test.ts suite (and the plugin-scope/resources/operator-model-policy suites) pass unchanged.

Gateway/exporter proof and review repair

Verified candidate: ac6fdcc98f98c5a221ebf451701354fa904f05ec (preserves @ruel225's original commit). Thanks @etzelm for the report and @ruel225 for the fix.

Addressed the pricing review finding: the central usage finalizer now carries lease.snapshot.agentDir into estimateAggregateUsageCost. A regression uses an admitted non-default agent's local models.json rate of $20/million input tokens: it fails on the original contributor head (cost missing), then passes with the repair. No config, SDK, or stored-state contract changes.

Real operator before/after

Built current main 427f926e7c2d763e362f59678c6486b6f2f4aec4 and the candidate independently in a secretless Node 24.16.0 Linux container. Each Gateway used its own state/home/profile, a non-default loopback port, diagnostics enabled, and the bundled diagnostics-prometheus exporter. A local OpenAI-compatible HTTP provider returned 101 input + 17 output = 118 tokens per request; configured prices were $2/million input and $3/million output ($0.000253/call). No internal completion functions or diagnostic emitters were substituted.

The operator action was the shipped CLI calling sessions.title.prepare, with distinct primary proof/proof-model and utility proof/proof-utility models. Both revisions returned {"title":"Metrics proof title"}. Scraped the documented protected metrics endpoint /api/diagnostics/prometheus (the exporter does not expose a literal /metrics route).

Observed action / model series Main Candidate
Initial token/cost series absent absent
One title completion / proof-utility, channel="unknown" absent input 101, output 17, prompt 101, total 118; cost 0.000253
One plugin runtime.llm.complete isolated completion / 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

The plugin control was a fixture plugin registered through the public plugin API and invoked through its Gateway RPC. The normal-turn control used the shipped agent CLI against the running Gateway. Provider request logs corroborated one request for each control, with no double counting. Normal-turn lifecycle also made two real Activity recap requests on each revision: main still exported no utility series; candidate's utility series increased to input 303, output 51, prompt 303, total 354, cost 0.000759—exactly three utility calls including the title, not a duplicate normal turn.

Candidate scrape immediately after the title:

openclaw_model_cost_usd_total{agent="main",channel="unknown",model="proof-utility",provider="proof"} 0.000253
openclaw_model_tokens_total{agent="main",channel="unknown",model="proof-utility",provider="proof",token_type="input"} 101
openclaw_model_tokens_total{agent="main",channel="unknown",model="proof-utility",provider="proof",token_type="output"} 17
openclaw_model_tokens_total{agent="main",channel="unknown",model="proof-utility",provider="proof",token_type="prompt"} 101
openclaw_model_tokens_total{agent="main",channel="unknown",model="proof-utility",provider="proof",token_type="total"} 118

Checks

  • pnpm build: passed for main and candidate.
  • Focused pnpm test with --maxWorkers=1: 122 tests passed across 5 files, 78.22 seconds wall time: isolated-completion owner + usage diagnostics, plugin LLM diagnostics + isolated runtime, and Prometheus service.
  • The added admitted-agent pricing regression failed on the original PR head and passed on the repaired candidate (7 ms test time).
  • Targeted Oxfmt check and Oxlint: passed; git diff --check: passed.
  • Hosted CI and ClawSweeper remain independent exact-head gates; local checks do not claim hosted CI success.

Maintainer intent: checked Sarah's #159246 change in the touched owner; it only documents the existing Agents API restricted-session exception. This change preserves that execution contract. No overlapping Pash change was found.

Merge danger: two-way door; reverting removes diagnostic accounting only. Blast radius is token/cost consumers for core utility completions; plugin accounting and normal agent-turn accounting remain on their existing owners.

runIsolatedCompletion returned token usage but never emitted the
model.usage diagnostic event, so background utility completions
(session titles, activity recaps, session observer, progress
narration, transcript summaries) were missing from token and cost
series. Emit one trusted model.usage event per completed call,
estimated against the model cost config like the plugin and cron
paths. Plugin completions are skipped: their callers finalize usage
through finalizePluginLlmCompletion, which already emits.
@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.

@ruel225
ruel225 marked this pull request as ready for review October 9, 2026 20:42
@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

Thanks for the context here. I swept through the related work, and this is now duplicate or superseded.

This PR is useful and now has convincing Gateway proof, but a proof-positive, cleanly mergeable replacement covers the same repair and additionally preserves terminal CLI usage totals.

Root-cause cluster
Relationship: superseded
Canonical: #167986
Summary: The replacement repairs the same missing background usage event and additionally preserves terminal CLI accounting.

Members:

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

Canonical path: Follow the replacement PR and preserve this contribution’s admitted-agent pricing regression and contributor credit.

So I’m closing this here because the remaining work is already tracked in the canonical issue.

Review details

Best possible solution:

Follow the replacement PR and preserve this contribution’s admitted-agent pricing regression and contributor credit.

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

Yes. Current-main source lacks the usage event, and supplied Gateway before/after output demonstrates a successful title completion with absent counters before the repair.

Is this the best way to solve the issue?

The shared completion boundary is appropriate, but the replacement is more complete because it also carries terminal CLI totals while retaining agent-specific pricing.

Security review:

Security review cleared: The diff adds usage instrumentation without changing credentials, permissions, dependencies, or execution authority.

AGENTS.md: found and applied where relevant.

What I checked:

  • Current main still needs accounting: The fetched main completion owner returns validated results without emitting model.usage; its source is unchanged from the introduction base. This is supersession by an open replacement, not an implemented-on-main close. (src/agents/isolated-completion.ts:664, fcbeec3103ba)
  • Previous pricing finding resolved: The repaired helper passes lease.snapshot.agentDir to cost estimation, and the added regression checks a non-default admitted agent’s $20-per-million input price. (src/agents/isolated-completion.ts:298, ac6fdcc98f98)
  • After-fix Gateway proof: The complete supplied PR body identifies the reviewed candidate and reports independent secretless Linux Gateways driven through sessions.title.prepare and the protected Prometheus endpoint. The candidate exports 118 tokens and $0.000253 for one title request; plugin and normal-turn controls remain counted once, and two additional recap requests produce exactly three utility calls. Captured body source identity: a500a74c0ec35d0ffaaa6a037db1eb4f7a4619a88399a1eb1bbe10150916ed6d. No target code was executed during this review. (ac6fdcc98f98)
  • Proof-positive replacement: fix: background utility completions are missing from token and cost metrics #167986 is open, non-draft, and cleanly mergeable. Its inspected diff implements the same shared accounting and plugin exclusion, preserves admitted-agent pricing, and prefers terminal CLI diagnostic usage. Its body shows a real Gateway title request changing from absent metrics to 120 input, 7 output, 127 total tokens, and $0.000134; its published review reports no findings. (src/agents/isolated-completion.ts, a252cd19864d)
  • Terminal CLI accounting contract: The existing captured-Claude regression distinguishes the assistant snapshot’s 5 output tokens from the terminal total’s 534 output tokens. CLI settlement carries both fields, but this PR forwards only usage; the replacement forwards diagnosticUsage as well. (src/agents/cli-output-jsonl.test.ts:513, ac6fdcc98f98)
  • Existing plugin ownership preserved: fix: include plugin LLM calls in usage diagnostics #107937 established exactly-once host-owned plugin accounting. Its recorded maintainer decision preserves exporter labels and keeps plugin attribution private; both proposals retain the existing plugin finalizer. (src/plugins/runtime/runtime-llm.runtime.ts:259, 2ea567972c5f)

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

@obviyus

obviyus commented Oct 9, 2026

Copy link
Copy Markdown
Collaborator

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. and removed status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Oct 9, 2026
@ruel225

ruel225 commented Oct 10, 2026

Copy link
Copy Markdown
Contributor Author

Superseded by #167986, which covers the same repair surface — central model.usage emission in runIsolatedCompletion with the plugin-completion exclusion, and cost estimation scoped via lease.snapshot.agentDir (so the admitted-agent pricing fix pushed here in ac6fdcc is already reflected in the canonical) — and additionally propagates terminal CLI diagnosticUsage for accounting. Closing in favor of the canonical; nothing from this branch is lost.

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: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: M

Projects

None yet

2 participants