Skip to content

Commit 602992c

Browse files
committed
fix: distinguish agent-turn telemetry
1 parent 6286b01 commit 602992c

7 files changed

Lines changed: 134 additions & 24 deletions

File tree

‎docs/gateway/opentelemetry.md‎

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -216,16 +216,20 @@ Every `openclaw.model.call` span identifies what its lifecycle measures through
216216
calls use this unit.
217217

218218
Both units remain model-call spans so trace backends can render model input,
219-
output, usage, and hierarchy. OpenClaw records both in its
220-
`openclaw.model_call.*` metrics, which include the observation unit. Only
221-
`request` events contribute to `gen_ai.client.operation.duration`; excluding
222-
`turn` events prevents request-latency charts from mixing in full-turn latency.
219+
output, usage, and hierarchy. Request spans use the API-derived GenAI operation
220+
(`chat`, `generate_content`, or `text_completion`), while turn spans use
221+
`gen_ai.operation.name = invoke_agent`. Both contribute to
222+
`gen_ai.client.operation.duration`, where the operation name keeps direct
223+
request latency separate from full-turn latency. OpenClaw's OTEL model-call
224+
metrics also include `openclaw.model_call.observation_unit`; the Prometheus
225+
model-call metrics expose the equivalent `observation_unit` label.
223226

224227
### Claude Code CLI model-call fidelity
225228

226229
Claude Code CLI turns emit one synthetic, turn-level `openclaw.model.call`
227230
span. These are not Anthropic HTTP request spans. They use `openclaw.api =
228231
claude-code`, `openclaw.model_call.observation_unit = turn`, and identify
232+
the operation as `gen_ai.operation.name = invoke_agent`. They identify
229233
OpenClaw's CLI boundary through
230234
`openclaw.transport`:
231235

@@ -291,7 +295,7 @@ bounds; content remains off by default.
291295
- `openclaw.run.duration_ms` (histogram, attrs: `openclaw.channel`, `openclaw.provider`, `openclaw.model`)
292296
- `openclaw.context.tokens` (histogram, attrs: `openclaw.context`, `openclaw.channel`, `openclaw.provider`, `openclaw.model`)
293297
- `gen_ai.client.token.usage` (histogram, GenAI semantic-conventions metric, attrs: `gen_ai.token.type` = `input`/`output`, `gen_ai.provider.name`, `gen_ai.operation.name`, `gen_ai.request.model`)
294-
- `gen_ai.client.operation.duration` (histogram, seconds, GenAI semantic-conventions metric for request-scoped model calls only; attrs: `gen_ai.provider.name`, `gen_ai.operation.name`, `gen_ai.request.model`, optional `error.type`)
298+
- `gen_ai.client.operation.duration` (histogram, seconds, GenAI semantic-conventions metric for model requests and synthetic agent turns; attrs: `gen_ai.provider.name`, `gen_ai.operation.name`, `gen_ai.request.model`, optional `error.type`; turn observations use `gen_ai.operation.name = invoke_agent`)
295299
- `openclaw.model_call.duration_ms` (histogram, attrs: `openclaw.provider`, `openclaw.model`, `openclaw.api`, `openclaw.transport`, `openclaw.model_call.observation_unit`, plus `openclaw.errorCategory` and `openclaw.failureKind` on classified errors)
296300
- `openclaw.model_call.request_bytes` (histogram, UTF-8 byte size of the final model request payload; for Claude Code CLI, the observable prompt input/envelope described above; no raw payload content)
297301
- `openclaw.model_call.response_bytes` (histogram, UTF-8 byte size of streamed response chunk payloads; high-frequency text, thinking, and tool-call deltas count only incremental `delta` bytes; for Claude Code CLI, observed stdout bytes; no raw response content)
@@ -423,7 +427,7 @@ Liveness warnings also emit:
423427
- `openclaw.model_call.prompt.input_messages_count`, `openclaw.model_call.prompt.input_messages_chars`, `openclaw.model_call.prompt.system_prompt_chars`, `openclaw.model_call.prompt.tool_definitions_count`, `openclaw.model_call.prompt.tool_definitions_chars`, `openclaw.model_call.prompt.total_chars` (safe component sizes only, no prompt text)
424428
- `openclaw.model_call.usage.*` and `gen_ai.usage.*` when the result carries usage for that request or aggregate turn
425429
- Span event `openclaw.provider.request` with attribute `openclaw.upstreamRequestIdHash` (bounded, hash-based) when the upstream provider result exposes a request id; raw ids are never exported
426-
- With `OTEL_SEMCONV_STABILITY_OPT_IN=gen_ai_latest_experimental`, model-call spans use the latest GenAI inference span name `{gen_ai.operation.name} {gen_ai.request.model}` and `CLIENT` span kind instead of `openclaw.model.call`.
430+
- With `OTEL_SEMCONV_STABILITY_OPT_IN=gen_ai_latest_experimental`, request spans use the latest GenAI inference span name `{gen_ai.operation.name} {gen_ai.request.model}`. Turn spans use `invoke_agent` because OpenClaw does not claim a native agent name from the opaque CLI boundary. Both use `CLIENT` span kind instead of `openclaw.model.call`.
427431
- `openclaw.harness.run`
428432
- `openclaw.harness.id`, `openclaw.harness.plugin`, `openclaw.outcome`, `openclaw.provider`, `openclaw.model`, `openclaw.channel`
429433
- On completion: `openclaw.harness.result_classification`, `openclaw.harness.yield_detected`, `openclaw.harness.items.started`, `openclaw.harness.items.completed`, `openclaw.harness.items.active`

‎docs/gateway/prometheus.md‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -95,8 +95,8 @@ For traces, logs, OTLP push, and OpenTelemetry GenAI semantic attributes, see [O
9595
| ------------------------------------------------ | --------- | ----------------------------------------------------------------------------------------- |
9696
| `openclaw_run_completed_total` | counter | `channel`, `model`, `outcome`, `provider`, `trigger` |
9797
| `openclaw_run_duration_seconds` | histogram | `channel`, `model`, `outcome`, `provider`, `trigger` |
98-
| `openclaw_model_call_total` | counter | `api`, `error_category`, `model`, `outcome`, `provider`, `transport` |
99-
| `openclaw_model_call_duration_seconds` | histogram | `api`, `error_category`, `model`, `outcome`, `provider`, `transport` |
98+
| `openclaw_model_call_total` | counter | `api`, `error_category`, `model`, `observation_unit`, `outcome`, `provider`, `transport` |
99+
| `openclaw_model_call_duration_seconds` | histogram | `api`, `error_category`, `model`, `observation_unit`, `outcome`, `provider`, `transport` |
100100
| `openclaw_model_failover_total` | counter | `from_model`, `from_provider`, `lane`, `reason`, `suspended`, `to_model`, `to_provider` |
101101
| `openclaw_model_tokens_total` | counter | `agent`, `channel`, `model`, `provider`, `token_type` |
102102
| `openclaw_gen_ai_client_token_usage` | histogram | `model`, `provider`, `token_type` |
@@ -148,6 +148,11 @@ For traces, logs, OTLP push, and OpenTelemetry GenAI semantic attributes, see [O
148148
| `openclaw_diagnostic_async_queue_dropped_total` | counter | `drop_class` |
149149
| `openclaw_diagnostic_async_queue_length` | gauge | none |
150150

151+
For model-call metrics, `observation_unit="request"` measures one observable
152+
provider request. `observation_unit="turn"` measures a synthetic Claude Code
153+
or Codex CLI agent turn that can contain multiple hidden provider requests.
154+
Keep those series separate when comparing latency.
155+
151156
## Label policy
152157

153158
<AccordionGroup>

‎extensions/diagnostics-otel/src/service-genai-attributes.ts‎

Lines changed: 24 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { SpanKind } from "@opentelemetry/api";
2+
import { GEN_AI_OPERATION_NAME_VALUE_INVOKE_AGENT } from "@opentelemetry/semantic-conventions/incubating";
23
import type { DiagnosticEventPayload } from "../api.js";
34
import { redactSensitiveText } from "../api.js";
45
import { lowCardinalityAttr } from "./service-attributes.js";
@@ -26,7 +27,13 @@ function emitLatestGenAiSemconv(): boolean {
2627

2728
export function genAiOperationName(
2829
api: string | undefined,
29-
): "chat" | "generate_content" | "text_completion" {
30+
observationUnit?: "request" | "turn",
31+
): "chat" | "generate_content" | "invoke_agent" | "text_completion" {
32+
// CLI/app-server diagnostics bracket an opaque agent turn, not one inference request.
33+
// Label that boundary as agent invocation so its latency stays distinct from request latency.
34+
if (observationUnit === "turn") {
35+
return GEN_AI_OPERATION_NAME_VALUE_INVOKE_AGENT;
36+
}
3037
const normalized = api?.trim().toLowerCase();
3138
if (!normalized) {
3239
return "chat";
@@ -146,7 +153,12 @@ export function assignModelCallUsageAttrs(
146153

147154
export function assignGenAiSpanIdentityAttrs(
148155
attrs: Record<string, string | number | boolean>,
149-
input: { api?: string; model?: string; provider?: string },
156+
input: {
157+
api?: string;
158+
model?: string;
159+
observationUnit?: "request" | "turn";
160+
provider?: string;
161+
},
150162
): void {
151163
if (emitLatestGenAiSemconv()) {
152164
attrs["gen_ai.provider.name"] = lowCardinalityAttr(input.provider);
@@ -161,7 +173,7 @@ export function assignGenAiSpanIdentityAttrs(
161173
// reads gen_ai.request.model). Keep the redacted raw model on the span.
162174
attrs["gen_ai.request.model"] = redactSensitiveText(input.model.trim());
163175
}
164-
attrs["gen_ai.operation.name"] = genAiOperationName(input.api);
176+
attrs["gen_ai.operation.name"] = genAiOperationName(input.api, input.observationUnit);
165177
}
166178

167179
export function assignGenAiModelCallAttrs(
@@ -183,11 +195,18 @@ export function modelCallObservationUnit(evt: {
183195
return evt.observationUnit ?? "request";
184196
}
185197

186-
export function modelCallSpanName(evt: { api?: string; model?: string }): string {
198+
export function modelCallSpanName(evt: {
199+
api?: string;
200+
model?: string;
201+
observationUnit?: "request" | "turn";
202+
}): string {
187203
if (!emitLatestGenAiSemconv()) {
188204
return "openclaw.model.call";
189205
}
190-
return `${genAiOperationName(evt.api)} ${lowCardinalityAttr(evt.model)}`;
206+
const operationName = genAiOperationName(evt.api, evt.observationUnit);
207+
return operationName === GEN_AI_OPERATION_NAME_VALUE_INVOKE_AGENT
208+
? operationName
209+
: `${operationName} ${lowCardinalityAttr(evt.model)}`;
191210
}
192211

193212
export function modelCallSpanKind(): SpanKind | undefined {

‎extensions/diagnostics-otel/src/service-recorders-model.ts‎

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ export function createModelRecorders(runtime: DiagnosticsRecorderRuntime) {
4646
evt: ModelCallLifecycleDiagnosticEvent,
4747
errorType?: string,
4848
) => ({
49-
"gen_ai.operation.name": genAiOperationName(evt.api),
49+
"gen_ai.operation.name": genAiOperationName(evt.api, evt.observationUnit),
5050
"gen_ai.provider.name": lowCardinalityAttr(evt.provider),
5151
"gen_ai.request.model": lowCardinalityAttr(evt.model),
5252
...(errorType ? { "error.type": errorType } : {}),
@@ -55,11 +55,6 @@ export function createModelRecorders(runtime: DiagnosticsRecorderRuntime) {
5555
evt: ModelCallLifecycleDiagnosticEvent,
5656
errorType?: string,
5757
) => {
58-
// The standard GenAI series stays request-scoped so opaque CLI-turn latency
59-
// cannot be averaged with direct provider-request latency.
60-
if (modelCallObservationUnit(evt) !== "request") {
61-
return;
62-
}
6358
genAiOperationDurationHistogram.record(
6459
evt.durationMs / 1000,
6560
genAiModelCallMetricAttrs(evt, errorType),

‎extensions/diagnostics-otel/src/service.test.ts‎

Lines changed: 46 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2548,7 +2548,7 @@ describe("diagnostics-otel service", () => {
25482548
await service.stop?.(ctx);
25492549
});
25502550

2551-
test("exports GenAI client duration only for request-scoped model calls", async () => {
2551+
test("separates request and turn GenAI client duration by operation", async () => {
25522552
const service = createDiagnosticsOtelService();
25532553
const ctx = createOtelContext(OTEL_TEST_ENDPOINT, { traces: true, metrics: true });
25542554
await service.start(ctx);
@@ -2609,7 +2609,7 @@ describe("diagnostics-otel service", () => {
26092609
const genAiOperationDuration = telemetryState.histograms.get(
26102610
"gen_ai.client.operation.duration",
26112611
);
2612-
expect(genAiOperationDuration?.record).toHaveBeenCalledTimes(2);
2612+
expect(genAiOperationDuration?.record).toHaveBeenCalledTimes(4);
26132613
expect(genAiOperationDuration?.record).toHaveBeenCalledWith(0.25, {
26142614
"gen_ai.operation.name": "text_completion",
26152615
"gen_ai.provider.name": "anthropic",
@@ -2621,6 +2621,17 @@ describe("diagnostics-otel service", () => {
26212621
"gen_ai.request.model": "gemini-2.5-flash",
26222622
"error.type": "TimeoutError",
26232623
});
2624+
expect(genAiOperationDuration?.record).toHaveBeenCalledWith(2.5, {
2625+
"gen_ai.operation.name": "invoke_agent",
2626+
"gen_ai.provider.name": "anthropic",
2627+
"gen_ai.request.model": "claude-opus-4-7",
2628+
});
2629+
expect(genAiOperationDuration?.record).toHaveBeenCalledWith(3, {
2630+
"gen_ai.operation.name": "invoke_agent",
2631+
"gen_ai.provider.name": "openai",
2632+
"gen_ai.request.model": "gpt-5.4",
2633+
"error.type": "TurnError",
2634+
});
26242635
const openClawModelCallDuration = telemetryState.histograms.get(
26252636
"openclaw.model_call.duration_ms",
26262637
);
@@ -2639,6 +2650,20 @@ describe("diagnostics-otel service", () => {
26392650
],
26402651
);
26412652
expect(spanObservationUnits).toEqual(["request", "request", "turn", "turn"]);
2653+
const spanOperations = telemetryState.tracer.startSpan.mock.calls
2654+
.filter((call) => call[0] === "openclaw.model.call")
2655+
.map(
2656+
(call) =>
2657+
(call[1] as { attributes?: Record<string, unknown> }).attributes?.[
2658+
"gen_ai.operation.name"
2659+
],
2660+
);
2661+
expect(spanOperations).toEqual([
2662+
"text_completion",
2663+
"generate_content",
2664+
"invoke_agent",
2665+
"invoke_agent",
2666+
]);
26422667
expect(JSON.stringify(genAiOperationDuration?.record.mock.calls)).not.toContain("session-key");
26432668
expect(JSON.stringify(genAiOperationDuration?.record.mock.calls)).not.toContain("run-1");
26442669
await service.stop?.(ctx);
@@ -3067,7 +3092,7 @@ describe("diagnostics-otel service", () => {
30673092
await service.stop?.(ctx);
30683093
});
30693094

3070-
test("uses latest GenAI inference span shape only when semconv opt-in is set", async () => {
3095+
test("uses latest GenAI request and agent span shapes only when semconv opt-in is set", async () => {
30713096
process.env.OTEL_SEMCONV_STABILITY_OPT_IN = "http,gen_ai_latest_experimental";
30723097

30733098
const service = createDiagnosticsOtelService();
@@ -3083,6 +3108,17 @@ describe("diagnostics-otel service", () => {
30833108
api: "openai-completions",
30843109
durationMs: 80,
30853110
});
3111+
emitDiagnosticEvent({
3112+
type: "model.call.completed",
3113+
runId: "run-1",
3114+
callId: "call-2",
3115+
provider: "anthropic",
3116+
model: "claude-opus-4-7",
3117+
api: "claude-code",
3118+
transport: "stdio-live",
3119+
observationUnit: "turn",
3120+
durationMs: 90,
3121+
});
30863122
emitDiagnosticEvent({
30873123
type: "model.usage",
30883124
provider: "openai",
@@ -3100,6 +3136,13 @@ describe("diagnostics-otel service", () => {
31003136
expect(Object.hasOwn(modelCallOptions?.attributes ?? {}, "gen_ai.system")).toBe(false);
31013137
expect(modelCallOptions?.startTime).toBeTypeOf("number");
31023138
expect(modelCallOptions?.kind).toBe(2);
3139+
const agentTurnOptions = startedSpanOptions("invoke_agent");
3140+
expect(agentTurnOptions?.attributes?.["gen_ai.provider.name"]).toBe("anthropic");
3141+
expect(agentTurnOptions?.attributes?.["gen_ai.request.model"]).toBe("claude-opus-4-7");
3142+
expect(agentTurnOptions?.attributes?.["gen_ai.operation.name"]).toBe("invoke_agent");
3143+
expect(agentTurnOptions?.attributes?.["openclaw.model_call.observation_unit"]).toBe("turn");
3144+
expect(agentTurnOptions?.startTime).toBeTypeOf("number");
3145+
expect(agentTurnOptions?.kind).toBe(2);
31033146
const modelUsageOptions = startedSpanOptions("openclaw.model.usage");
31043147
expect(modelUsageOptions?.attributes?.["gen_ai.provider.name"]).toBe("openai");
31053148
expect(modelUsageOptions?.attributes?.["gen_ai.request.model"]).toBe("gpt-5.4");

‎extensions/diagnostics-prometheus/src/service.test.ts‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,48 @@ describe("diagnostics-prometheus service", () => {
131131
expect(metrics.render()).toBe("");
132132
});
133133

134+
it("separates request and turn model-call metrics by observation unit", () => {
135+
const metrics = createMetricsHarness();
136+
137+
metrics.record(
138+
{
139+
...baseEvent(),
140+
type: "model.call.completed",
141+
runId: "run-1",
142+
callId: "call-1",
143+
provider: "openai",
144+
model: "gpt-5.4",
145+
api: "openai-responses",
146+
transport: "http",
147+
durationMs: 250,
148+
},
149+
trusted,
150+
);
151+
metrics.record(
152+
{
153+
...baseEvent(),
154+
type: "model.call.completed",
155+
runId: "run-1",
156+
callId: "call-2",
157+
provider: "anthropic",
158+
model: "claude-opus-4-7",
159+
api: "claude-code",
160+
transport: "stdio-live",
161+
observationUnit: "turn",
162+
durationMs: 2500,
163+
},
164+
trusted,
165+
);
166+
167+
const rendered = metrics.render();
168+
expect(rendered).toContain(
169+
'openclaw_model_call_total{api="openai-responses",error_category="none",model="gpt-5.4",observation_unit="request",outcome="completed",provider="openai",transport="http"} 1',
170+
);
171+
expect(rendered).toContain(
172+
'openclaw_model_call_duration_seconds_sum{api="claude-code",error_category="none",model="claude-opus-4-7",observation_unit="turn",outcome="completed",provider="anthropic",transport="stdio-live"} 2.5',
173+
);
174+
});
175+
134176
it("drops untrusted plugin-emitted diagnostic events that spoof gateway stability signals", () => {
135177
const metrics = createMetricsHarness();
136178

‎extensions/diagnostics-prometheus/src/service.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -323,6 +323,7 @@ function modelCallLabels(evt: {
323323
api?: string;
324324
errorCategory?: string;
325325
model?: string;
326+
observationUnit?: "request" | "turn";
326327
provider?: string;
327328
transport?: string;
328329
type: string;
@@ -332,6 +333,7 @@ function modelCallLabels(evt: {
332333
error_category:
333334
evt.type === "model.call.error" ? lowCardinalityLabel(evt.errorCategory, "other") : "none",
334335
model: lowCardinalityLabel(evt.model),
336+
observation_unit: evt.observationUnit === "turn" ? "turn" : "request",
335337
outcome: evt.type === "model.call.error" ? "error" : "completed",
336338
provider: lowCardinalityLabel(evt.provider),
337339
transport: lowCardinalityLabel(evt.transport),
@@ -584,13 +586,13 @@ function recordDiagnosticEvent(
584586
case "model.call.error":
585587
store.histogram(
586588
"openclaw_model_call_duration_seconds",
587-
"Provider model call duration in seconds.",
589+
"Model request or synthetic agent-turn duration in seconds.",
588590
modelCallLabels(evt),
589591
seconds(evt.durationMs),
590592
);
591593
store.counter(
592594
"openclaw_model_call_total",
593-
"Provider model calls completed by outcome.",
595+
"Model requests or synthetic agent turns completed by outcome.",
594596
modelCallLabels(evt),
595597
);
596598
return;

0 commit comments

Comments
 (0)