Skip to content

fix(diagnostics-otel): keep model usage spans inside the turn trace - #235

Merged
insomnius merged 3 commits into
boonfrom
fix/otel-usage-span-trace
Sep 22, 2026
Merged

insomnius merged 3 commits into
boonfrom
fix/otel-usage-span-trace

Conversation

@insomnius

@insomnius insomnius commented Sep 22, 2026 •

Copy link
Copy Markdown

What Problem This Solves

openclaw.model.usage (token counts, cost) often landed in a brand-new trace instead of the turn it belongs to. In the local E2E for #227 the usage span appeared as a separate root with its own trace id while openclaw.run / openclaw.model.call shared the turn trace. Drilling into a slow turn in Tempo therefore showed timings but no usage.

Why This Change Was Made

model.usage is emitted by agent-runner after the run settles, as a child of runResult.diagnosticTrace. By then the parent span is usually no longer tracked or retained by the exporter, and recordModelUsage resolved its parent with activeTrustedParentContext, which returns undefined when the parent is not tracked, so tracer.startSpan created a new root trace. recordMessageDelivery already uses activeInternalOrTrustedContext, which falls back to the event's own trace context as a remote parent; the usage span now does the same.

User Impact

Tokens and cost are attached to the same trace as the run, model calls, tools, and delivery. No config or protocol change; spans keep their names and attributes.

Evidence

  • New test: "keeps model usage in the turn trace when its parent span is not tracked" — red before the change (parent context undefined), green after.
  • The two retained-context cleanup tests now assert the late usage span links through a remote parent (isRemote: true, parent = the run span id) instead of asserting no linkage at all, which preserves their intent (retained contexts released) without forcing a detached trace.
  • pnpm test extensions/diagnostics-otel/src/service.test.ts 96/96; pnpm tsgo:extensions clean; oxlint clean; git diff --check clean.

Summary by cubic

Keeps openclaw.model.usage spans (token counts and cost) in the same trace as the rest of the turn instead of starting a detached trace.

The usage span is emitted after the run settles, so its parent span is often no longer tracked by the exporter; activeTrustedParentContext then returned undefined and the span started a brand-new root trace. Resolving the parent now uses activeInternalOrTrustedContext, which falls back to the event's own trace context as a remote parent — the same approach recordMessageDelivery already uses. Spans keep their names and attributes, and no config or protocol change is required.

Tests

  • A positive-control test asserts the late usage span resolves the retained (non-remote) run context while it's still held; the two retained-context cleanup tests now assert the late span links through a remote parent, preserving their intent without forcing a detached trace.

Written for commit 0b7c88d. Summary will update on new commits.

Review in cubic

model.usage is emitted after the run settles, so its parent span is often no
longer tracked or retained by the exporter. Resolving the parent through the
trusted-only lookup then failed and the span started a brand-new trace,
detaching token counts and cost from the turn they belong to. Fall back to the
event's own trace context (remote parent) the way message delivery spans
already do. The retained-context cleanup tests now assert the late span links
through a remote parent rather than a retained one.
@insomnius
insomnius requested a review from a team September 22, 2026 08:45
@claude

claude Bot commented Sep 22, 2026 •

Copy link
Copy Markdown

Claude encountered an error —— View job


I'll analyze this and get back to you.

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

All reported issues were addressed across 2 files

Reply with feedback, questions, or to request a fix.

Fix all with cubic | Re-trigger cubic

…e control

The late model.usage event cannot carry a runId (DiagnosticUsageEvent has no
such field), so it resolves retained run contexts through the plain
traceId:spanId key. Emit one usage event while the run context is still
retained and assert it resolves the retained (non-remote) span context, so the
post-cleanup isRemote assertion fails if drain or stop cleanup regresses. Also
drop the invalid runId from the new fallback test (CI test-types).

@augusteo augusteo left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Review (sweep pickup from #pr-review-request)

Read the change and the helpers at head b6c7b6cf:

  • activeInternalOrTrustedContext (service.ts:2113) falls back exactly as described: active trusted span → retained span context → internalOrTrustedParentContext, which builds a remote span context from the event's own trace context (parentSpanId). The updated tests assert isRemote: true with the event's traceId/CHILD_SPAN_ID, which matches that path.
  • This makes openclaw.model.usage consistent with the delivery spans (lines 2607/2626), which already use the same helper. Consistency argument holds.
  • Security: no new data exposure — the span attributes were already recorded before this change; only the parenting changes, so token/cost data lands in the turn trace instead of a detached one.
  • Tests were updated, not deleted: the two old assertions (setSpanContext not called, no parent) were inverted into positive assertions of the new fallback, plus a new dedicated test for the untracked-parent case.

Could not execute the jest suite locally (review runner disk-full), so the claimed 96/96 exporter suite is taken from CI/author. The change is one call-site line plus tests and reads correctly. No blocking issues.

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

All reported issues were addressed across 1 file (changes from recent commits).

Reply with feedback, questions, or to request a fix.

Fix all with cubic | Re-trigger cubic

@augusteo augusteo left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Re-reviewed at head 0b7c88d (supersedes my earlier approval on b6c7b6c).

Production change is a one-call-site fix: recordModelUsage now resolves its parent with activeInternalOrTrustedContext instead of activeTrustedParentContext. Verified the helper at head: it tries (1) the event's own spanId in active/aliased trusted spans, (2) retained span contexts, (3) falls back to the event's own remote parent context — exactly what delivery spans already do. Since model.usage is emitted after the run settles, the old code returned undefined and startSpan created a detached root trace; the fallback keeps tokens/cost in the turn trace.

The two commits since the prior approval are test-only: a positive control asserting the retained (non-remote) context wins while the run context is still retained, and a flush-before-read determinism fix. Tests updated, not deleted; no production behavior change since the last pass.

No new data exposure — span attributes are unchanged; only parenting changes.

@augusteo

Copy link
Copy Markdown

Independent verification at b6c7b6cf (production code identical at the current head 0b7c88d6; the two commits since are test-only). Adding evidence beyond the existing approval rather than stacking a second one:

  • RED-GREEN proven locally: with service.ts swapped to the origin/boon base, the new test fails with AssertionError: expected undefined to be '4bf92f3577b34da6a3ce929d0e0e4736' — the old activeTrustedParentContext returns undefined when the parent is untracked, so startSpan roots openclaw.model.usage in its own trace. Restored to the PR head: passes.
  • Suite green locally: vitest run extensions/diagnostics-otel → 96/96 (the file holds exactly 96 test( blocks); tsgo:extensions exit 0; oxlint clean on both changed files (full lint:extensions sweep was SIGKILLed by host memory pressure, so the scoped run is the evidence).
  • cubic's P2 (retained-context cleanup no longer pinned) is refuted on mechanism: completeTrackedLifecycleSpan retains the run span's context under BOTH the ownerless key (traceId:spanId) and the owner-keyed alias. The runId-less late model.usage lookup hits the ownerless TRACE_ID:CHILD_SPAN_ID entry, and because that entry carries no owner, the retained.owner guard passes — a surviving retained context is the run span's LOCAL context (isRemote: false), which would fail the isRemote === true assertion. The 174bfe31 positive-control commit (retained non-remote context wins while retained) now pins this directly. Note cubic's suggested fix (adding runId: "run-1") would have made the test vacuous: owner-keyed entries exist only under SPAN_ID, not CHILD_SPAN_ID, so the retained lookup would miss even with cleanup regressed.

@augusteo augusteo left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Review: approved

Re-reviewed the exact current head 0b7c88d6. The production change correctly uses activeInternalOrTrustedContext so late model.usage events retain the turn trace through an active/retained context when available, then fall back to the event trace context instead of creating a detached root.

Verified:

  • the new untracked-parent regression test asserts the same trace and parent span;
  • the cleanup tests now include a positive retained-context control and explicit event flushing before assertions;
  • both review threads are resolved at this head;
  • exact-head targeted checks are green, including OpenGrep, Workflow Sanity, Security Sensitive Guard, Dependency Guard, CodeQL, Periphery, check-test-types, check-lint, and check-additional-extension-bundled.

The large matrix CI workflow is still running with no failures observed. This approval is for the code; no merge or deployment was performed.

@insomnius
insomnius merged commit f0e3a1f into boon Sep 22, 2026
140 of 141 checks passed
@insomnius
insomnius deleted the fix/otel-usage-span-trace branch September 22, 2026 09:54
insomnius added a commit that referenced this pull request Sep 22, 2026
…238)

Root version, 135 plugin manifests synced via scripts/sync-plugin-versions.ts, changed npm-shrinkwrap.json files regenerated, CHANGELOG section for boon.46.

Shipping: #237 (diagnostics-otel owns its tracer and meter providers instead of the global ones, so it stops handing spans to a co-running SDK), #235 (model.usage stays inside the turn trace), #233 (a plugin's scheduled turn is no longer rolled back by an unrelated registry becoming active), #229 (browser-handoff recheck scheduling failure is logged), #212 (dev-only vitest bump in ui).

Base = 2026.6.11-boon.45. Gateway plus @openclaw/slack, @openclaw/msteams and @openclaw/diagnostics-prometheus bumped in lockstep; no separately published plugin source changed in this train, so a gateway roll delivers all of it.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants