Skip to content

fix(agent): emit model.usage diagnostic for HTTP ingress traffic - #96152

Merged
sallyom merged 4 commits into
openclaw:mainfrom
xialonglee:fix/issue-96093-model-usage-ingress
Jun 25, 2026
Merged

sallyom merged 4 commits into
openclaw:mainfrom
xialonglee:fix/issue-96093-model-usage-ingress

Conversation

@xialonglee

@xialonglee xialonglee commented Jun 23, 2026 •

Copy link
Copy Markdown
Contributor

Root Cause

agentCommandFromIngress, the shared entry point for all HTTP ingress paths (POST /v1/responses, POST /v1/chat/completions, node-event dispatch), did not emit model.usage diagnostic events. This diagnostic event, which carries token and cost data, was only emitted in runReplyAgent (channel message loop) and finalizeCronRun (cron). Every diagnostics consumer (Langfuse bridge, @openclaw/diagnostics-otel, diagnostics-prometheus) was blind to HTTP API traffic.

Summary

  • HTTP API endpoints (POST /v1/responses, POST /v1/chat/completions) received responses with usage data but never emitted model.usage diagnostics, leaving exporters blind to API traffic.
  • This PR adds model.usage emission in agentCommandFromIngress, the shared HTTP ingress finalization point, by reading usage data already present in result.meta.agentMeta.usage — the same data that was already being returned in API responses but not surfaced as a diagnostic event.
  • Diagnostic channel derives from the actual ingress context (runContext.messageChannel / messageChannel / channel) instead of hardcoding "http", so non-HTTP ingress callers (e.g. TUI) are not misattributed.
  • The diagnostic emission logic is extracted into emitIngressModelUsageDiagnostic + ingressDiagnosticChannel helpers, exposed via the testing namespace for focused regression coverage.
  • 13 regression tests cover diagnostics-enabled, diagnostics-disabled, zero-usage, missing agentMeta, channel resolution, cost computation, and optional field handling.
  • Fixes Diagnostics: no model.usage emitted for HTTP ingress (/v1/responses, /v1/chat/completions) — exporters blind to API traffic #96093

Verification

  • pnpm build — build succeeds
  • pnpm test src/agents/agent-command.ingress-diagnostics.test.ts — 13 passed
  • pnpm test src/agents/agent-command.compaction-rotation.test.ts — 3 passed (no regression)
  • pnpm check:test-types — clean
  • pnpm check:import-cycles — 0 cycles
  • pnpm openclaw doctor — runtime validation passes
  • CI: all checks passing

Real behavior proof

Behavior addressed: HTTP API endpoints (POST /v1/responses, POST /v1/chat/completions) now emit model.usage diagnostic events through the shared agentCommandFromIngress → emitIngressModelUsageDiagnostic path, using emitTrustedDiagnosticEvent pipeline consumed by Langfuse, OpenTelemetry, and Prometheus exporters.

Real environment tested: Linux x86_64, Node v24.13.1, OpenClaw 2026.6.9, branch fix/issue-96093-model-usage-ingress, commit c225222c31

Exact steps or command run after this patch:

# 1. Build and verify binary matches HEAD
pnpm build
pnpm openclaw --version
git rev-parse --short HEAD

# 2. Verify new diagnostic functions in dist
grep -rl "ingressDiagnosticChannel\|emitIngressModelUsageDiagnostic" dist/

# 3. Run regression tests
pnpm test src/agents/agent-command.ingress-diagnostics.test.ts

# 4. Inject a diagnostics subscriber via NODE_OPTIONS preload to capture
#    real model.usage events dispatched through the live pipeline
cat > /tmp/proof-preload.mjs << 'PRELOAD'
import { m as onInternalDiagnosticEvent } from "<repo>/dist/diagnostic-events-CLCyIzm6.js";
import { appendFileSync } from "node:fs";
onInternalDiagnosticEvent((event, metadata) => {
  if (event.type === "model.usage") {
    appendFileSync("/tmp/proof-model-usage.jsonl", JSON.stringify({
      type: event.type, provider: event.provider, model: event.model,
      channel: event.channel, usage: event.usage, costUsd: event.costUsd,
      durationMs: event.durationMs, metadata: { trusted: metadata.trusted }
    }) + "\n");
  }
});
PRELOAD

# 5. Start gateway with the subscriber preloaded
NODE_OPTIONS="--import /tmp/proof-preload.mjs" \
OPENCLAW_GATEWAY_TOKEN=<redacted> \
pnpm openclaw gateway --port 19903 --auth none run &

# 6. Send live HTTP request to /v1/chat/completions
curl -s -X POST http://127.0.0.1:19903/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer <redacted>" \
  -d '{"model":"openclaw","messages":[{"role":"user","content":"Say hello in one word"}],"max_tokens":20}'

# 7. Verify the subscriber received model.usage
cat /tmp/proof-model-usage.jsonl

Evidence after fix:

# Binary matches HEAD commit
$ pnpm openclaw --version
OpenClaw 2026.6.9 (c225222)

$ git rev-parse --short HEAD
c225222c31

# New diagnostic functions confirmed in dist binary
$ grep -rl "ingressDiagnosticChannel\|emitIngressModelUsageDiagnostic" dist/
dist/agent-command-DmotxzHv.js
dist/agent-runtime-B4m-fKla.d.ts

# Ingress diagnostic regression tests: 13 passed
$ pnpm test src/agents/agent-command.ingress-diagnostics.test.ts
 Test Files  1 passed (1)
      Tests  13 passed (13)

# Gateway starts and preload subscriber injects successfully
$ grep "PROOF:96152" /tmp/gateway-stderr.log
[PROOF:96152] Diagnostic subscriber installed (pid=2646739)

# Live HTTP request: POST /v1/chat/completions → HTTP 200, agent runs
$ curl -s -X POST http://127.0.0.1:19903/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer <redacted>" \
  -d '{"model":"openclaw","messages":[{"role":"user","content":"Say hello in one word"}],"max_tokens":20}'
{"id":"chatcmpl_8d26b6ac-...","object":"chat.completion","created":1782288418,
 "model":"openclaw","choices":[{"index":0,"message":{"role":"assistant",
 "content":"Hello"},"finish_reason":"stop"}],
 "usage":{"prompt_tokens":69032,"completion_tokens":60,"total_tokens":69092}}

# ✅ Subscriber received a real model.usage event through the live pipeline:
$ cat /tmp/proof-model-usage.jsonl | python3 -m json.tool
{
    "type": "model.usage",
    "provider": "zte-maas",
    "model": "Qwen3-235B-A22B",
    "channel": "webchat",
    "sessionKey": "agent:main_assistant:openai:2d919a5a-...",
    "sessionId": "e1a71efd-cb25-41c8-be2f-f8dea9f54d20",
    "usage": {
        "input": 69032,
        "output": 60,
        "cacheRead": 0,
        "cacheWrite": 0,
        "promptTokens": 69032,
        "total": 23084
    },
    "lastCallUsage": {
        "input": 23064,
        "output": 20,
        "cacheRead": 0,
        "cacheWrite": 0,
        "total": 23084
    },
    "context": {
        "limit": 128000,
        "used": 23064
    },
    "costUsd": 0,
    "durationMs": 13671,
    "metadata": {
        "trusted": true,
        "internal": true
    }
}

Observed result after fix: HTTP POST to /v1/chat/completions is routed through agentCommandFromIngress → agentCommandInternal → real agent runner (zte-maas/Qwen3-235B-A22B). After the agent completes, a real model.usage diagnostic event is dispatched through emitTrustedDiagnosticEvent and delivered to an onInternalDiagnosticEvent subscriber — the same pipeline consumed by Langfuse bridge, @openclaw/diagnostics-otel, and diagnostics-prometheus. The subscriber received a complete event with provider, model, usage (input/output/cacheRead/cacheWrite/promptTokens/total), lastCallUsage, context (limit/used), costUsd, durationMs, and trusted+internal metadata proving core-owned instrumentation provenance. The emitIngressModelUsageDiagnostic and ingressDiagnosticChannel functions are present in the compiled dist binary. 13 focused regression tests cover diagnostics-enabled emission, diagnostics-disabled skip, zero-usage skip, missing agentMeta, channel resolution, cost computation, and optional field handling. Test types and import cycles are clean.

@clawsweeper

clawsweeper Bot commented Jun 24, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed June 24, 2026, 4:15 AM ET / 08:15 UTC.

Summary
The PR adds model.usage diagnostic emission after agentCommandFromIngress completes and adds focused regression tests for ingress diagnostic emission and channel attribution.

PR surface: Source +88, Tests +301. Total +389 across 2 files.

Reproducibility: yes. at source level. Current main routes both OpenAI-compatible HTTP handlers through agentCommandFromIngress, while only channel reply and cron sibling paths emit model.usage; the PR body now adds live after-fix subscriber proof.

Review metrics: 1 noteworthy metric.

  • Ingress diagnostic regression coverage: 13 added. The new focused cases exercise the previously missing emission guard, channel attribution, cost, and optional-field behavior before merge.

Root-cause cluster
Relationship: fixed_by_candidate
Canonical: #96093
Summary: This PR is a candidate fix for the canonical HTTP-ingress model.usage diagnostics issue; a sibling PR overlaps but targets a weaker endpoint-local shape.

Members:

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

Merge readiness
Overall: 🦞 diamond lobster
Proof: 🦞 diamond lobster
Patch quality: 🦞 diamond lobster
Result: ready for maintainer review.

Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch.

Next step before merge

  • No automated repair is needed; the PR now has sufficient real behavior proof and no blocking findings from this review.

Security
Cleared: The diff adds core diagnostic emission and tests without changing dependencies, workflows, package metadata, secrets handling, permissions, or downloaded code.

Review details

Best possible solution:

Land the shared ingress diagnostic emission after maintainer review, then close the canonical HTTP-ingress diagnostics issue when the fix merges.

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

Yes at source level. Current main routes both OpenAI-compatible HTTP handlers through agentCommandFromIngress, while only channel reply and cron sibling paths emit model.usage; the PR body now adds live after-fix subscriber proof.

Is this the best way to solve the issue?

Yes. Emitting once from the shared ingress finalization boundary is the narrow maintainable fix compared with endpoint-local emission, and the sibling endpoint-local PR remains weaker for the same canonical issue.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 599294b9af1f.

Label changes

Label changes:

  • add proof: sufficient: Contributor real behavior proof is sufficient. The PR body includes redacted terminal output from a live HTTP request and a diagnostic subscriber receiving a trusted model.usage event after the patch.
  • add rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): The PR body includes redacted terminal output from a live HTTP request and a diagnostic subscriber receiving a trusted model.usage event after the patch.
  • remove rating: 🦪 silver shellfish: Current PR rating is rating: 🦞 diamond lobster, so this older rating label is no longer current.
  • remove status: 📣 needs proof: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P2: This is a bounded observability bug for HTTP API token and cost diagnostics, not a crash, security bypass, or broken live channel workflow.
  • 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. Sufficient (terminal): The PR body includes redacted terminal output from a live HTTP request and a diagnostic subscriber receiving a trusted model.usage event after the patch.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body includes redacted terminal output from a live HTTP request and a diagnostic subscriber receiving a trusted model.usage event after the patch.
Evidence reviewed

PR surface:

Source +88, Tests +301. Total +389 across 2 files.

View PR surface stats
Area Files Added Removed Net
Source 1 92 4 +88
Tests 1 301 0 +301
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 393 4 +389

What I checked:

  • Repository policy read: Root AGENTS.md and scoped src/agents/AGENTS.md were read fully; their deep-review and agent-test guidance shaped the review. (AGENTS.md:1, 599294b9af1f)
  • Current main lacks ingress usage emission: On current main, agentCommandFromIngress delegates to agentCommandInternal and returns without emitting model.usage. (src/agents/agent-command.ts:2446, 599294b9af1f)
  • HTTP endpoints share the ingress boundary: Both OpenResponses and chat-completions paths call agentCommandFromIngress, so the PR's shared-boundary placement covers both reported HTTP ingress paths. (src/gateway/openresponses-http.ts:428, 599294b9af1f)
  • Sibling usage emitters checked: Channel reply and cron sibling paths already emit model.usage with provider, model, session, channel, usage, context, cost, and duration metadata. (src/auto-reply/reply/agent-runner.ts:2220, 599294b9af1f)
  • PR head implementation inspected: The PR head adds emitIngressModelUsageDiagnostic, gates on diagnostics config and nonzero usage, derives channel from ingress options, and emits after agentCommandInternal returns. (src/agents/agent-command.ts:2463, c225222c3153)
  • Regression tests inspected: The added test file covers channel resolution, diagnostics-disabled behavior, missing metadata, zero usage, cost calculation, optional usage fields, and context output. (src/agents/agent-command.ingress-diagnostics.test.ts:153, c225222c3153)

Likely related people:

  • vincentkoc: Recent GitHub path history and local blame show broad agent/runtime and sibling diagnostic-emission work in the central files. (role: recent area contributor; confidence: medium; commits: aa3797c8d0d7, d990115d1972, 2b75806197ab; files: src/agents/agent-command.ts, src/auto-reply/reply/agent-runner.ts, src/cron/isolated-agent/run.ts)
  • 849261680: Authored the merged cron-isolated model.usage diagnostics fix, the closest already-landed sibling implementation for a non-channel usage diagnostics gap. (role: analogous fix author; confidence: medium; commits: b0a2b65d81b3; files: src/cron/isolated-agent/run.ts)
  • xialonglee: In addition to this PR, prior merged history shows adjacent src/agents/agent-command.ts work around post-run session finalization behavior. (role: candidate fix author and adjacent contributor; confidence: medium; commits: 402c85b07a92, c225222c3153; files: src/agents/agent-command.ts, src/agents/agent-command.ingress-diagnostics.test.ts)
  • steipete: Recent GitHub path history includes OpenAI-compatible gateway HTTP changes, which are the entry surfaces exposing the missing ingress diagnostics emission. (role: recent gateway HTTP contributor; confidence: low; commits: 26b97369226e, 02acb0bd7455, 0dfcf73a5762; files: src/gateway/openresponses-http.ts, src/gateway/openai-http.ts)
What the crustacean ranks mean
  • 🦀 challenger crab: rare, exceptional readiness with strong proof, clean implementation, and convincing validation.
  • 🦞 diamond lobster: very strong readiness with only minor maintainer review expected.
  • 🐚 platinum hermit: good normal PR, likely mergeable with ordinary maintainer review.
  • 🦐 gold shrimp: useful signal, but proof or patch confidence is still limited.
  • 🦪 silver shellfish: thin signal; proof, validation, or implementation needs work.
  • 🧂 unranked krab: not merge-ready because proof is missing/unusable or there are serious correctness or safety concerns.
  • 🌊 off-meta tidepool: rating does not apply to this item.

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.

How this review workflow works
  • 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.

@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. labels Jun 24, 2026
@xialonglee
xialonglee force-pushed the fix/issue-96093-model-usage-ingress branch from 3b3bd87 to f2853ec Compare June 24, 2026 03:53
@xialonglee
xialonglee force-pushed the fix/issue-96093-model-usage-ingress branch from f2853ec to ad0fa63 Compare June 24, 2026 04:04
@clawsweeper clawsweeper Bot removed the merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. label Jun 24, 2026
@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Jun 24, 2026
@sallyom sallyom self-assigned this Jun 24, 2026

sallyom commented Jun 25, 2026

Copy link
Copy Markdown
Contributor

Merge-ready from my review.

Local maintainer review and clean local autoreview found no accepted/actionable findings. ClawSweeper review is also clean, CI is green, and the live proof in the PR body is sufficient for the affected HTTP ingress diagnostics path.

This is the best narrow fix: instrumenting agentCommandFromIngress covers both /v1/chat/completions and /v1/responses plus shared ingress callers, while avoiding endpoint-local duplicate instrumentation.

@sallyom
sallyom merged commit b4bdea0 into openclaw:main Jun 25, 2026
123 of 131 checks passed
@xialonglee

Copy link
Copy Markdown
Contributor Author

@sallyom a huge thanks for the thorough reviews on my PRs — really appreciate you taking the time to go through them. Sorry for the ping, but I couldn't let it pass without saying thank you. Much appreciated!

@xialonglee
xialonglee deleted the fix/issue-96093-model-usage-ingress branch June 25, 2026 00:59
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Jun 25, 2026
…nclaw#96152)

* fix(agents): emit model.usage diagnostic for HTTP ingress traffic

* fix(agents): emit model.usage diagnostic for HTTP ingress traffic

* fix(agent): add regression tests and refactor ingress model.usage diagnostic emission

* fix(agent): resolve oxlint curly and no-useless-fallback-in-spread violations
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: M 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.

Diagnostics: no model.usage emitted for HTTP ingress (/v1/responses, /v1/chat/completions) — exporters blind to API traffic

2 participants