diff --git a/coderd/x/chatd/ARCHITECTURE.md b/coderd/x/chatd/ARCHITECTURE.md index 51f9b74aeff..5add2cece28 100644 --- a/coderd/x/chatd/ARCHITECTURE.md +++ b/coderd/x/chatd/ARCHITECTURE.md @@ -1062,7 +1062,7 @@ Live stages wrap a section of code and end when it returns: - `stream`: the provider stream, from opening the request to consuming the last part. - `time_to_first_token`: nested in `stream`, from opening the request to the first streamed output part, including block start markers such as `text_start`; warnings and finish parts do not close it. The span is emitted for every attempt, but only a window closed by an output part is observed on the histograms. A failed attempt, including one whose first part is an error part, ends the span with the error and records no observation, as does a stream released before any output part arrives. A silence timeout before the first part is recorded as the span's error. - `retry_backoff`: the wait before retrying a failed LLM API call. -- `tool_call`: one per local tool call that runs, started in `chatloop` just before the tool runs and carrying `tool_name`. Calls that never run record no stage: calls to an inactive or unknown tool, calls rejected by the exclusive-tool policy, and calls denied by a pre-tool-use hook. The tool runs on the stage's context, so its own spans nest under it. The span ends in error only when the tool fails to execute (a `Run` error or panic), not when it returns an error result to the model. The `advisor` tool's nested model call runs inside its `tool_call` and is not instrumented as `stream` or `time_to_first_token`; the tool call is its only stage. +- `tool_call`: one per local tool call that runs, started in `chatloop` just before the tool runs and carrying `tool_name`. Calls that never run record no stage: calls to an inactive or unknown tool, calls rejected by the exclusive-tool policy, and calls denied by a pre-tool-use hook. The tool runs on the stage's context, so its own spans nest under it. The span ends in error when the tool fails to execute (a `Run` error or panic) or returns an error result to the model. The `advisor` tool's nested model call runs through `GenerateAssistant` with `ModelCallStage` inside its `tool_call`, so it records a `model_call` stage, not `stream` or `time_to_first_token`. - `commit`: the `CommitStep` transaction. - `compaction`: a compaction pass. @@ -1071,6 +1071,19 @@ Reconstructed stages are recorded after the fact from timestamps captured elsewh - `acquisition` and `queue_wait`: described above. - `thinking`: one per reasoning part, from the part's start to its completion timestamp in the persisted step. +#### GenAI semantic conventions + +Three stages are also GenAI operations, and their spans follow the OpenTelemetry GenAI semantic conventions (semconv v1.41.0, the last core release that ships them) so tracing backends can attribute model usage without custom mapping. `genai.go` in `chatloop` owns the mapping. + +- `chat_turn` is named `invoke_agent coder` and carries `gen_ai.operation.name=invoke_agent` and `gen_ai.agent.name=coder`. It starts before the turn resolves a model, so `gen_ai.provider.name` is added through `runnerTurnSpan.SetProvider` as soon as `prepare` resolves the turn model, before later preparation steps that can fail. +- `stream` is named `chat {model}`, has span kind `CLIENT`, and carries `gen_ai.request.stream=true`. It is started with `StartWithModel`, so the name, `gen_ai.provider.name`, and `gen_ai.request.model` are set at creation, where head samplers see them. Before the stream opens it records the request's output token limit and temperature. After the stream is consumed, it records the response ID, the finish reason the provider reported (omitted when it sent none or an unclassified one, and kept when the loop rejects the response, since the span status and `error.type` describe the failure), and token usage. `gen_ai.usage.input_tokens` adds cache reads and cache writes to fantasy's `InputTokens`, which excludes them, because the conventions count them as input. `gen_ai.provider.name` maps the configured provider type to the conventions' well-known values, reports `aws.bedrock` for an anthropic provider with Bedrock settings, and passes other types through. The cache breakdown is recorded only when nonzero, because the OpenAI-compatible client never reports cache writes. For Anthropic, fantasy reports the first internal iteration's input counts (context occupancy), so responses that ran provider tools undercount billed input; the docs page states this. +- `tool_call` is named `execute_tool {tool}` and carries the tool name, call ID, and `gen_ai.tool.type`: `function` for built-in tools and `extension` for every other tool. It is started with `StartTool`, so the name and these attributes are set at creation. A tool that returns an error result instead of a `Run` error, as MCP clients do for an unreachable server, ends its span with `error.type=tool_error`; the result text is not recorded. +- `model_call` covers model calls outside the assistant stream and is also named `chat {model}`. `StageTracer.TraceModelCalls` wraps every model from `resolveModelCall`, innermost, so each non-streaming `Generate` or `GenerateObject` attempt (titles, status labels, chat summaries) records one span, including the usage of an object that fails to parse. It reads the response ID from OpenAI Responses metadata and sets `gen_ai.output.type=json` on `GenerateObject` only for the native OpenAI client, the one client whose default object mode sends a JSON schema rather than forcing a tool call. Compaction records one per summary stream through `GenerateCompactionOptions.Stages`. It has no histogram, so the `stream` histogram still measures assistant streams only. The advisor's `GenerateAssistant` call sets `ModelCallStage`, so it records a `model_call` span under the advisor tool span instead of `stream`. + +The span name follows the operation, so every stage span carries a `stage` attribute with its stage name, the same value as the histogram's `stage` label. Read the stage from that attribute, not from the span name. The pre-existing attributes (`chat_id`, `provider`, `model`, `tool_name`, ...) stay on the spans. + +`withStageIdentity` also puts a `chatloop.ChatIdentity` on the context, built from the chat row: the chat, owner, organization, workspace, parent chat, and root chat IDs. The three GenAI spans record it as `gen_ai.conversation.id`, `user.id`, and `coder.*` attributes, so each model call can be attributed to a user without joining other data. A turn takes the identity when it opens, so a workspace the turn creates appears on spans from the next turn. A failed stage span also records `error.type`, the classified error kind. + ### Event shape Every event that the runner loop processes has the following shape: diff --git a/coderd/x/chatd/chatadvisor/runner.go b/coderd/x/chatd/chatadvisor/runner.go index 75084197787..2e52568dc4a 100644 --- a/coderd/x/chatd/chatadvisor/runner.go +++ b/coderd/x/chatd/chatadvisor/runner.go @@ -57,6 +57,9 @@ func (rt *Runtime) RunAdvisor( Messages: BuildAdvisorMessages(question, conversationSnapshot), CallTemplate: nestedCall, StreamSilenceTimeout: rt.cfg.StreamSilenceTimeout, + Stages: rt.cfg.Stages, + StageModel: rt.cfg.StageModel, + ModelCallStage: true, } if opts != nil && (opts.OnAdviceDelta != nil || opts.OnReasoningDelta != nil) { assistantOpts.PublishMessagePart = func(role codersdk.ChatMessageRole, part codersdk.ChatMessagePart) { diff --git a/coderd/x/chatd/chatadvisor/runner_test.go b/coderd/x/chatd/chatadvisor/runner_test.go index 1ce98856912..88b5bc62cd3 100644 --- a/coderd/x/chatd/chatadvisor/runner_test.go +++ b/coderd/x/chatd/chatadvisor/runner_test.go @@ -11,9 +11,13 @@ import ( "charm.land/fantasy" fantasyopenai "charm.land/fantasy/providers/openai" "github.com/stretchr/testify/require" + "go.opentelemetry.io/otel/attribute" + sdktrace "go.opentelemetry.io/otel/sdk/trace" + "go.opentelemetry.io/otel/sdk/trace/tracetest" "golang.org/x/xerrors" "github.com/coder/coder/v2/coderd/x/chatd/chatadvisor" + "github.com/coder/coder/v2/coderd/x/chatd/chatloop" "github.com/coder/coder/v2/coderd/x/chatd/chattest" ) @@ -64,6 +68,52 @@ func TestAdvisorRunAdvice(t *testing.T) { require.Equal(t, question, singleText(t, capturedCall.Prompt[len(capturedCall.Prompt)-1])) } +func TestAdvisorRunRecordsChatSpan(t *testing.T) { + t.Parallel() + + recorder := tracetest.NewSpanRecorder() + provider := sdktrace.NewTracerProvider(sdktrace.WithSpanProcessor(recorder)) + t.Cleanup(func() { require.NoError(t, provider.Shutdown(context.Background())) }) + runtime, err := chatadvisor.NewRuntime(chatadvisor.RuntimeConfig{ + Model: &chattest.FakeModel{ + ProviderName: "anthropic", + ModelName: "claude", + StreamFn: func(context.Context, fantasy.Call) (fantasy.StreamResponse, error) { + return streamFromParts([]fantasy.StreamPart{ + {Type: fantasy.StreamPartTypeTextStart, ID: "text-1"}, + {Type: fantasy.StreamPartTypeTextDelta, ID: "text-1", Delta: "advice"}, + {Type: fantasy.StreamPartTypeTextEnd, ID: "text-1"}, + {Type: fantasy.StreamPartTypeFinish, FinishReason: fantasy.FinishReasonStop, Usage: fantasy.Usage{InputTokens: 7, OutputTokens: 3}}, + }), nil + }, + }, + MaxUsesPerRun: 1, + MaxOutputTokens: 100, + MaxRetries: 1, + Stages: chatloop.NewStageTracer(provider, nil), + StageModel: chatloop.StageModel{Provider: "anthropic", ProviderType: "anthropic", Model: "claude"}, + }) + require.NoError(t, err) + + _, err = runtime.RunAdvisor(t.Context(), "question", []fantasy.Message{textMessage(fantasy.MessageRoleUser, "hello")}, nil) + require.NoError(t, err) + + var chatSpans []sdktrace.ReadOnlySpan + for _, span := range recorder.Ended() { + if span.Name() == "chat claude" { + chatSpans = append(chatSpans, span) + } + } + require.Len(t, chatSpans, 1) + require.Contains(t, chatSpans[0].Attributes(), attribute.Int("gen_ai.usage.output_tokens", 3)) + // The advisor is not an assistant stream, so it stays out of the stream + // and time_to_first_token stages. + require.Contains(t, chatSpans[0].Attributes(), attribute.String(chatloop.AttrStage, string(chatloop.StageModelCall))) + for _, span := range recorder.Ended() { + require.NotEqual(t, string(chatloop.StageTimeToFirstToken), span.Name()) + } +} + func TestAdvisorRunTruncatesLongQuestion(t *testing.T) { t.Parallel() diff --git a/coderd/x/chatd/chatadvisor/runtime.go b/coderd/x/chatd/chatadvisor/runtime.go index 94dec29c004..97e5468d1bb 100644 --- a/coderd/x/chatd/chatadvisor/runtime.go +++ b/coderd/x/chatd/chatadvisor/runtime.go @@ -7,6 +7,8 @@ import ( "charm.land/fantasy" fantasyopenai "charm.land/fantasy/providers/openai" "golang.org/x/xerrors" + + "github.com/coder/coder/v2/coderd/x/chatd/chatloop" ) // RuntimeConfig configures a single advisor runtime instance. @@ -20,6 +22,10 @@ type RuntimeConfig struct { // MaxRetries is the maximum number of retries after a transient // provider error within one advisor call. It must be positive. MaxRetries int + // Stages records the advisor's model call as a chat span. Nil + // disables tracing. + Stages *chatloop.StageTracer + StageModel chatloop.StageModel // PriorUses is the number of successful advisor calls already made // in the current turn. chatd builds a new Runtime for every model // step, so the per-turn quota is seeded from history. diff --git a/coderd/x/chatd/chatd.go b/coderd/x/chatd/chatd.go index 750599d2f75..3a7ddcb2774 100644 --- a/coderd/x/chatd/chatd.go +++ b/coderd/x/chatd/chatd.go @@ -353,6 +353,8 @@ func (p *Server) newAdvisorRuntime( MaxOutputTokens: maxOutputTokens, StreamSilenceTimeout: p.streamSilenceTimeout, MaxRetries: p.chatLimits.MaxGenerationRetries, + Stages: p.stages, + StageModel: advisor.stageModel(), PriorUses: priorUses, }) if err != nil { @@ -2711,7 +2713,7 @@ func (p *Server) recordQueueWait(ctx context.Context, chat database.Chat, queued return } standalone := trace.ContextWithSpanContext(ctx, trace.SpanContext{}) - standalone = withStageIdentity(standalone, chatloop.ScopeTurn, chatKind(chat)) + standalone = withStageIdentity(standalone, chatloop.ScopeTurn, chat) p.stages.Record(standalone, chatloop.StageQueueWait, chatloop.StageModel{}, queuedAt, p.stages.Now(), nil, attribute.String(chatloop.AttrChatID, chat.ID.String()), @@ -2720,7 +2722,7 @@ func (p *Server) recordQueueWait(ctx context.Context, chat database.Chat, queued func (p *Server) inflightChatContext(reqCtx context.Context, chat database.Chat) (context.Context, func()) { ctx, stop := p.inflightContext(reqCtx) - return withStageIdentity(ctx, chatloop.ScopeBackground, chatKind(chat)), stop + return withStageIdentity(ctx, chatloop.ScopeBackground, chat), stop } func chatKind(chat database.Chat) chatloop.ChatKind { @@ -2730,8 +2732,24 @@ func chatKind(chat database.Chat) chatloop.ChatKind { return chatloop.ChatKindRoot } -func withStageIdentity(ctx context.Context, scope chatloop.Scope, kind chatloop.ChatKind) context.Context { +func chatIdentity(chat database.Chat) chatloop.ChatIdentity { + return chatloop.ChatIdentity{ + ChatID: chat.ID, + OwnerID: chat.OwnerID, + OrganizationID: chat.OrganizationID, + WorkspaceID: chat.WorkspaceID, + ParentChatID: chat.ParentChatID, + RootChatID: chat.RootChatID, + } +} + +func withStageIdentity(ctx context.Context, scope chatloop.Scope, chat database.Chat) context.Context { + return stageIdentityContext(ctx, scope, chatKind(chat), chatIdentity(chat)) +} + +func stageIdentityContext(ctx context.Context, scope chatloop.Scope, kind chatloop.ChatKind, identity chatloop.ChatIdentity) context.Context { ctx = chatloop.ContextWithScope(ctx, scope) + ctx = chatloop.ContextWithChatIdentity(ctx, identity) return chatloop.ContextWithChatKind(ctx, kind) } diff --git a/coderd/x/chatd/chatd_internal_test.go b/coderd/x/chatd/chatd_internal_test.go index 229a8fab2a0..f9d3e028d61 100644 --- a/coderd/x/chatd/chatd_internal_test.go +++ b/coderd/x/chatd/chatd_internal_test.go @@ -4134,8 +4134,16 @@ func TestWithStageIdentity(t *testing.T) { t.Parallel() tracer, recorder := newStageTestTracer(t) - ctx := withStageIdentity(t.Context(), chatloop.ScopeTurn, chatloop.ChatKindSubagent) - _, span := tracer.Start(ctx, chatloop.StageCommit) + chat := database.Chat{ + ID: uuid.New(), + OwnerID: uuid.New(), + OrganizationID: uuid.New(), + WorkspaceID: uuid.NullUUID{UUID: uuid.New(), Valid: true}, + ParentChatID: uuid.NullUUID{UUID: uuid.New(), Valid: true}, + RootChatID: uuid.NullUUID{UUID: uuid.New(), Valid: true}, + } + ctx := withStageIdentity(t.Context(), chatloop.ScopeTurn, chat) + _, span := tracer.Start(ctx, chatloop.StageStream) span.End(nil) ended := recorder.Ended() @@ -4143,5 +4151,11 @@ func TestWithStageIdentity(t *testing.T) { require.Subset(t, ended[0].Attributes(), []attribute.KeyValue{ attribute.String(chatloop.AttrScope, string(chatloop.ScopeTurn)), attribute.String(chatloop.AttrChatKind, string(chatloop.ChatKindSubagent)), + attribute.String("gen_ai.conversation.id", chat.ID.String()), + attribute.String("user.id", chat.OwnerID.String()), + attribute.String(chatloop.AttrOrganizationID, chat.OrganizationID.String()), + attribute.String(chatloop.AttrWorkspaceID, chat.WorkspaceID.UUID.String()), + attribute.String(chatloop.AttrParentChatID, chat.ParentChatID.UUID.String()), + attribute.String(chatloop.AttrRootChatID, chat.RootChatID.UUID.String()), }) } diff --git a/coderd/x/chatd/chatd_test.go b/coderd/x/chatd/chatd_test.go index 33215f8286d..8cd2b76bcda 100644 --- a/coderd/x/chatd/chatd_test.go +++ b/coderd/x/chatd/chatd_test.go @@ -14616,7 +14616,8 @@ func TestActiveServer_TracesChatTurn(t *testing.T) { testutil.Eventually(ctx, t, func(context.Context) bool { index = spanIndex{} for _, span := range recorder.Ended() { - index[span.Name()] = append(index[span.Name()], span) + stage := chatd.SpanAttr(t, span, chatloop.AttrStage) + index[stage] = append(index[stage], span) } return len(index[string(chatloop.StageChatTurn)]) >= n }, testutil.IntervalFast) @@ -14733,6 +14734,11 @@ func TestActiveServer_TracesChatTurn(t *testing.T) { require.Equal(t, string(chatloop.ChatKindRoot), chatd.SpanAttr(t, turn, chatloop.AttrChatKind)) require.Equal(t, chatID.String(), chatd.SpanAttr(t, turn, chatloop.AttrChatID)) require.False(t, turn.Parent().IsValid(), "chat_turn is a trace root") + require.Equal(t, "invoke_agent coder", turn.Name()) + require.Equal(t, "invoke_agent", chatd.SpanAttr(t, turn, "gen_ai.operation.name")) + require.Equal(t, chatID.String(), chatd.SpanAttr(t, turn, "gen_ai.conversation.id")) + require.Equal(t, h.user.ID.String(), chatd.SpanAttr(t, turn, "user.id")) + require.Equal(t, h.org.ID.String(), chatd.SpanAttr(t, turn, chatloop.AttrOrganizationID)) requireChild(t, single(t, index, chatloop.StageAcquisition), turn) steps := index[string(chatloop.StageGenerationStep)] @@ -14750,6 +14756,27 @@ func TestActiveServer_TracesChatTurn(t *testing.T) { requireChild(t, single(t, index, chatloop.StageCommit), generate) require.NotEmpty(t, chatd.SpanAttr(t, generate, chatloop.AttrProvider)) require.Equal(t, chatd.SpanAttr(t, stream, chatloop.AttrProvider), chatd.SpanAttr(t, generate, chatloop.AttrProvider)) + require.Equal(t, "chat "+h.model.Model, stream.Name()) + require.Equal(t, chatd.SpanAttr(t, stream, "gen_ai.provider.name"), chatd.SpanAttr(t, turn, "gen_ai.provider.name")) + // Title generation is a non-streaming model call that runs outside + // the turn, so it must still be attributed to the chat owner. + ctx := testutil.Context(t, testutil.WaitLong) + var modelCall sdktrace.ReadOnlySpan + testutil.Eventually(ctx, t, func(context.Context) bool { + for _, span := range h.recorder.Ended() { + if chatd.SpanAttr(t, span, chatloop.AttrStage) == string(chatloop.StageModelCall) { + modelCall = span + return true + } + } + return false + }, testutil.IntervalFast) + require.Equal(t, "chat "+h.model.Model, modelCall.Name()) + require.Equal(t, h.user.ID.String(), chatd.SpanAttr(t, modelCall, "user.id")) + require.Equal(t, chatID.String(), chatd.SpanAttr(t, modelCall, "gen_ai.conversation.id")) + require.Equal(t, chatID.String(), chatd.SpanAttr(t, stream, "gen_ai.conversation.id")) + require.Equal(t, h.user.ID.String(), chatd.SpanAttr(t, stream, "user.id")) + require.Equal(t, h.model.Model, chatd.SpanAttr(t, stream, "gen_ai.request.model")) require.Empty(t, index[string(chatloop.StageQueueWait)]) require.Empty(t, index[string(chatloop.StageRetryBackoff)]) require.Zero(t, chatd.StageAnomalyCount(t, h.registry, chatloop.StageAnomalyStaleAnchor)) @@ -14870,7 +14897,7 @@ func TestActiveServer_TracesChatTurn(t *testing.T) { testutil.Eventually(ctx, t, func(context.Context) bool { turns = nil for _, span := range h.recorder.Ended() { - if span.Name() == string(chatloop.StageChatTurn) { + if chatd.SpanAttr(t, span, chatloop.AttrStage) == string(chatloop.StageChatTurn) { turns = append(turns, span) } } diff --git a/coderd/x/chatd/chatloop/chatloop.go b/coderd/x/chatd/chatloop/chatloop.go index 5e4a5bc6127..0899ead49a3 100644 --- a/coderd/x/chatd/chatloop/chatloop.go +++ b/coderd/x/chatd/chatloop/chatloop.go @@ -136,6 +136,11 @@ type GenerateAssistantOptions struct { Stages *StageTracer // StageModel should match the model identity on provider_attempt stages. StageModel StageModel + // ModelCallStage records the call as a model_call stage, without the + // stream and time_to_first_token stages, so a nested call such as the + // advisor is traced without counting toward the assistant stream + // histograms. + ModelCallStage bool } // AssistantOutcome is the durable assistant-side result from one model call. @@ -237,6 +242,10 @@ type GenerateCompactionOptions struct { ResolvedProvider string ResolvedModel string ModelConfigID uuid.UUID + // Stages records each summary request as a chat span under the + // caller's compaction stage. Nil disables tracing. + Stages *StageTracer + StageModel StageModel // SummaryContextLimit is the summary model's window. When positive, it // bounds the summary cap instead of the trigger's limit. SummaryContextLimit int64 @@ -367,8 +376,16 @@ func GenerateAssistant(ctx context.Context, opts GenerateAssistantOptions) (_ As opts.OnModelStreamStart() } stepCtx := chatdebug.ReuseStep(ctx) - streamCtx, streamSpan := opts.Stages.Start(stepCtx, StageStream) - streamSpan.SetModel(opts.StageModel) + var streamCtx context.Context + var streamSpan *StageSpan + ttftStages := opts.Stages + if opts.ModelCallStage { + streamCtx, streamSpan = opts.Stages.StartModelCall(stepCtx, opts.StageModel, true) + ttftStages = nil + } else { + streamCtx, streamSpan = opts.Stages.StartWithModel(stepCtx, StageStream, opts.StageModel) + } + streamSpan.SetInferenceRequest(call) attempt, streamErr := guardedStream( streamCtx, provider, @@ -379,7 +396,7 @@ func GenerateAssistant(ctx context.Context, opts GenerateAssistantOptions) (_ As return opts.Model.Stream(attemptCtx, call) }, opts.Metrics, - opts.Stages, + ttftStages, opts.StageModel, ) if streamErr != nil { @@ -393,12 +410,18 @@ func GenerateAssistant(ctx context.Context, opts GenerateAssistantOptions) (_ As } // release closes the time_to_first_token window, so it must run // before the stream stage ends. + var inference InferenceResponse defer func() { attempt.release() - streamSpan.End(retErr) + endModelCall(streamSpan, inference, retErr) }() result, processErr := processStepStream(attempt.stream, opts.Clock, publishMessagePart) + inference = InferenceResponse{ + ResponseID: result.providerResponseID, + FinishReason: result.finishReason, + Usage: result.usage, + } // Observe before error handling so failed or rejected responses are still counted. opts.Metrics.ResponseSizeBytes.WithLabelValues(provider, modelName).Observe(float64(result.responseBytes)) if err := attempt.finish(processErr); err != nil { @@ -1184,8 +1207,14 @@ func providerResponseID(part fantasy.StreamPart) string { if part.ID != "" { return part.ID } - for _, metadata := range part.ProviderMetadata { - if responses, ok := metadata.(*fantasyopenai.ResponsesProviderMetadata); ok && responses != nil { + return metadataResponseID(part.ProviderMetadata) +} + +// metadataResponseID returns the OpenAI Responses API response ID, the +// only provider that reports it in metadata rather than a part ID. +func metadataResponseID(metadata fantasy.ProviderMetadata) string { + for _, m := range metadata { + if responses, ok := m.(*fantasyopenai.ResponsesProviderMetadata); ok && responses != nil { return responses.ResponseID } } @@ -1255,10 +1284,10 @@ func (b *toolBatch) run(ctx context.Context, localToolCalls []fantasy.ToolCallCo var toolSpan *StageSpan startRun := func(ctx context.Context) context.Context { var toolCtx context.Context - toolCtx, toolSpan = b.opts.Stages.Start(ctx, StageToolCall, + toolCtx, toolSpan = b.opts.Stages.StartTool(ctx, b.opts.StageModel, tc, + genAIToolType(b.opts.BuiltinToolNames, tc.ToolName), attribute.String(AttrToolName, tc.ToolName), ) - toolSpan.SetModel(b.opts.StageModel) return toolCtx } var execErr error @@ -1281,7 +1310,7 @@ func (b *toolBatch) run(ctx context.Context, localToolCalls []fantasy.ToolCallCo if recorder != nil { recorder.RecordComplete(i, completedAt) } - toolSpan.End(execErr) + toolSpan.End(toolSpanError(execErr, executions[i].content)) }() callCtx := ctx if b.opts.ToolCallContext != nil { diff --git a/coderd/x/chatd/chatloop/compaction.go b/coderd/x/chatd/chatloop/compaction.go index 17a6e4a89ee..1447b4790c4 100644 --- a/coderd/x/chatd/chatloop/compaction.go +++ b/coderd/x/chatd/chatloop/compaction.go @@ -205,8 +205,8 @@ func GenerateCompaction(ctx context.Context, opts GenerateCompactionOptions) (Co } summaryRuntime := opts.Clock.Since(summaryStart) if summary == "" { - publishCompactionError(config, "compaction produced an empty summary") - return CompactionResult{}, xerrors.New("compaction produced an empty summary") + publishCompactionError(config, errEmptyCompactionSummary.Error()) + return CompactionResult{}, errEmptyCompactionSummary } result := CompactionResult{ @@ -413,6 +413,8 @@ func startCompactionDebugRun( // without tool definitions for its size. var summaryToolResultCaps = []int{32 << 10, 4 << 10} +var errEmptyCompactionSummary = xerrors.New("compaction produced an empty summary") + // generateCompactionSummary asks the model to summarize the // conversation so far. The provided messages should contain the // complete history (system prompt, user/assistant turns, tool @@ -475,9 +477,21 @@ func generateCompactionSummary( } // TTFT is an assistant-generation measurement, so the summary stream // records neither its histogram nor its stage. - streamSummaryText := func(call fantasy.Call) (string, error) { + streamSummaryText := func(call fantasy.Call) (text string, retErr error) { + spanCtx, span := options.Stages.StartModelCall(summaryCtx, options.StageModel, true) + span.SetInferenceRequest(call) + var inference InferenceResponse + defer func() { + // GenerateCompaction rejects an empty summary, so the span + // reports the call as failed too. + spanErr := retErr + if spanErr == nil && text == "" { + spanErr = errEmptyCompactionSummary + } + endModelCall(span, inference, spanErr) + }() attempt, err := guardedStream( - summaryCtx, + spanCtx, options.ResolvedProvider, options.ResolvedModel, clock, @@ -526,6 +540,7 @@ func generateCompactionSummary( finishSeen = true finishReason = part.FinishReason responseID = providerResponseID(part) + inference = InferenceResponse{ResponseID: responseID, FinishReason: finishReason, Usage: part.Usage} case fantasy.StreamPartTypeError: streamErr = part.Error if streamErr == nil { diff --git a/coderd/x/chatd/chatloop/genai.go b/coderd/x/chatd/chatloop/genai.go new file mode 100644 index 00000000000..d0296720cba --- /dev/null +++ b/coderd/x/chatd/chatloop/genai.go @@ -0,0 +1,325 @@ +package chatloop + +import ( + "context" + "errors" + + "charm.land/fantasy" + "github.com/google/uuid" + "go.opentelemetry.io/otel/attribute" + semconv "go.opentelemetry.io/otel/semconv/v1.41.0" + "go.opentelemetry.io/otel/trace" + "golang.org/x/xerrors" + + "github.com/coder/coder/v2/coderd/database" + "github.com/coder/coder/v2/coderd/x/chatd/chaterror" +) + +// The OpenTelemetry GenAI semantic conventions are still in development. +// Span names and gen_ai.* attributes follow semconv v1.41.0, the last +// release that shipped them in the core registry. + +// GenAIAgentName is the gen_ai.agent.name of Coder Agents. +const GenAIAgentName = "coder" + +// Coder-specific span attribute keys that accompany the GenAI attributes. +const ( + // AttrStage carries the lifecycle stage on every stage span, since + // GenAI spans are named after the operation instead of the stage. + AttrStage = "stage" + AttrOrganizationID = "coder.organization.id" + AttrWorkspaceID = "coder.workspace.id" + AttrParentChatID = "coder.chat.parent_id" + AttrRootChatID = "coder.chat.root_id" +) + +// ChatIdentity attributes GenAI spans to a chat and its owner. +type ChatIdentity struct { + ChatID uuid.UUID + OwnerID uuid.UUID + OrganizationID uuid.UUID + WorkspaceID uuid.NullUUID + ParentChatID uuid.NullUUID + RootChatID uuid.NullUUID +} + +type chatIdentityKey struct{} + +// ContextWithChatIdentity returns ctx carrying the chat identity that +// GenAI spans started on it record. +func ContextWithChatIdentity(ctx context.Context, identity ChatIdentity) context.Context { + return context.WithValue(ctx, chatIdentityKey{}, identity) +} + +func chatIdentityFromContext(ctx context.Context) (ChatIdentity, bool) { + identity, ok := ctx.Value(chatIdentityKey{}).(ChatIdentity) + return identity, ok && identity.ChatID != uuid.Nil +} + +func (c ChatIdentity) attributes() []attribute.KeyValue { + attrs := []attribute.KeyValue{semconv.GenAIConversationID(c.ChatID.String())} + if c.OwnerID != uuid.Nil { + attrs = append(attrs, semconv.UserID(c.OwnerID.String())) + } + if c.OrganizationID != uuid.Nil { + attrs = append(attrs, attribute.String(AttrOrganizationID, c.OrganizationID.String())) + } + if c.WorkspaceID.Valid { + attrs = append(attrs, attribute.String(AttrWorkspaceID, c.WorkspaceID.UUID.String())) + } + if c.ParentChatID.Valid { + attrs = append(attrs, attribute.String(AttrParentChatID, c.ParentChatID.UUID.String())) + } + if c.RootChatID.Valid { + attrs = append(attrs, attribute.String(AttrRootChatID, c.RootChatID.UUID.String())) + } + return attrs +} + +// genAIOperation returns the GenAI operation a stage represents, if any. +func genAIOperation(stage Stage) (attribute.KeyValue, bool) { + switch stage { + case StageChatTurn: + return semconv.GenAIOperationNameInvokeAgent, true + case StageStream, StageModelCall: + return semconv.GenAIOperationNameChat, true + case StageToolCall: + return semconv.GenAIOperationNameExecuteTool, true + default: + return attribute.KeyValue{}, false + } +} + +// stageSpanStart returns the span name and start options for a stage. +// Sampling-relevant GenAI attributes and the span kind must be set at +// creation, since head samplers do not see later changes. +func stageSpanStart(ctx context.Context, stage Stage, model StageModel, toolName string) (string, []trace.SpanStartOption) { + attrs := []attribute.KeyValue{attribute.String(AttrStage, string(stage))} + operation, ok := genAIOperation(stage) + if !ok { + return string(stage), []trace.SpanStartOption{trace.WithAttributes(attrs...)} + } + attrs = append(attrs, operation) + if identity, ok := chatIdentityFromContext(ctx); ok { + attrs = append(attrs, identity.attributes()...) + } + name := operation.Value.AsString() + opts := []trace.SpanStartOption{} + switch stage { + case StageChatTurn: + name += " " + GenAIAgentName + attrs = append(attrs, semconv.GenAIAgentName(GenAIAgentName)) + case StageStream, StageModelCall: + // Models are called over HTTP, so inference spans are clients. + opts = append(opts, trace.WithSpanKind(trace.SpanKindClient)) + if model.Model != "" { + name += " " + model.Model + } + if stage == StageStream { + attrs = append(attrs, semconv.GenAIRequestStream(true)) + } + attrs = append(attrs, genAIModelAttributes(model)...) + case StageToolCall: + if toolName != "" { + name += " " + toolName + } + } + return name, append(opts, trace.WithAttributes(attrs...)) +} + +// genAIProviderName maps a configured provider type, or the wire protocol +// when the type is unknown, to gen_ai.provider.name. Types without a +// well-known value in the conventions pass through as their own name. +// TestGenAIProviderNameCoversEveryProviderType fails when a provider type +// is added, so this mapping is revisited. +func genAIProviderName(model StageModel) string { + if model.Bedrock { + return semconv.GenAIProviderNameAWSBedrock.Value.AsString() + } + switch database.AIProviderType(model.ProviderType) { + case database.AIProviderTypeOpenai: + return semconv.GenAIProviderNameOpenAI.Value.AsString() + case database.AIProviderTypeAnthropic: + return semconv.GenAIProviderNameAnthropic.Value.AsString() + case database.AIProviderTypeAzure: + return semconv.GenAIProviderNameAzureAIOpenAI.Value.AsString() + case database.AIProviderTypeBedrock: + return semconv.GenAIProviderNameAWSBedrock.Value.AsString() + case database.AIProviderTypeGoogle: + return semconv.GenAIProviderNameGCPGemini.Value.AsString() + case "": + return model.Provider + default: + return model.ProviderType + } +} + +func genAIModelAttributes(model StageModel) []attribute.KeyValue { + attrs := make([]attribute.KeyValue, 0, 2) + if provider := genAIProviderName(model); provider != "" { + attrs = append(attrs, semconv.GenAIProviderNameKey.String(provider)) + } + if model.Model != "" { + attrs = append(attrs, semconv.GenAIRequestModel(model.Model)) + } + return attrs +} + +// SetGenAIProvider records gen_ai.provider.name. invoke_agent spans +// require it but start before the turn resolves its model. +func (s *StageSpan) SetGenAIProvider(model StageModel) { + if s == nil || s.ended { + return + } + if provider := genAIProviderName(model); provider != "" { + s.span.SetAttributes(semconv.GenAIProviderNameKey.String(provider)) + } +} + +// errToolResult marks a tool call that returned an error result, such as +// an unreachable MCP server. The result text is not recorded because it +// can contain tool output. +var errToolResult = xerrors.New("tool returned an error result") + +// toolSpanError is the error an execute_tool span ends with: the run +// error, or errToolResult when the tool reported a failure as its result. +func toolSpanError(execErr error, result fantasy.ToolResultContent) error { + if execErr != nil { + return execErr + } + if _, ok := result.Result.(fantasy.ToolResultOutputContentError); ok { + return errToolResult + } + return nil +} + +// errorType returns error.type for a failed stage. +func errorType(err error) string { + if errors.Is(err, errToolResult) { + return "tool_error" + } + // A transport reset wraps context.Canceled but is a provider failure. + if errors.Is(err, context.Canceled) && !errors.Is(err, chaterror.ErrProviderTransportReset) { + return "canceled" + } + if kind := chaterror.Classify(err).Kind; kind != "" { + return string(kind) + } + return "_OTHER" +} + +// genAIToolType returns gen_ai.tool.type: "function" for tools Coder +// Agents implements and "extension" for tools served by MCP servers or +// callers. +func genAIToolType(builtinToolNames map[string]bool, name string) string { + if builtinToolNames[name] { + return "function" + } + return "extension" +} + +func genAIToolAttributes(call fantasy.ToolCallContent, toolType string) []attribute.KeyValue { + attrs := []attribute.KeyValue{semconv.GenAIToolName(call.ToolName)} + if call.ToolCallID != "" { + attrs = append(attrs, semconv.GenAIToolCallID(call.ToolCallID)) + } + if toolType != "" { + attrs = append(attrs, semconv.GenAIToolType(toolType)) + } + return attrs +} + +// SetInferenceRequest records request attributes of a chat span. +func (s *StageSpan) SetInferenceRequest(call fantasy.Call) { + s.setRequestParams(call.MaxOutputTokens, call.Temperature) +} + +func (s *StageSpan) setRequestParams(maxOutputTokens *int64, temperature *float64) { + if s == nil || s.ended { + return + } + if maxOutputTokens != nil { + s.span.SetAttributes(semconv.GenAIRequestMaxTokens(int(*maxOutputTokens))) + } + if temperature != nil { + s.span.SetAttributes(semconv.GenAIRequestTemperature(*temperature)) + } +} + +// InferenceResponse is the outcome of one chat span. +type InferenceResponse struct { + ResponseID string + FinishReason fantasy.FinishReason + Usage fantasy.Usage +} + +// SetInferenceResponse records response attributes of a chat span. +func (s *StageSpan) SetInferenceResponse(resp InferenceResponse) { + if s == nil || s.ended { + return + } + attrs := make([]attribute.KeyValue, 0, 8) + if resp.ResponseID != "" { + attrs = append(attrs, semconv.GenAIResponseID(resp.ResponseID)) + } + if reason, ok := genAIFinishReason(resp.FinishReason); ok { + attrs = append(attrs, semconv.GenAIResponseFinishReasons(reason)) + } + attrs = append(attrs, usageAttributes(resp.Usage)...) + s.span.SetAttributes(attrs...) +} + +// genAIFinishReason maps the finish reason the provider reported to its +// gen_ai.response.finish_reasons value. It reports false when the +// provider sent no reason or an unclassified one, so the span does not +// claim a reason the model never gave. A failed call is described by the +// span status and error.type, not by its finish reason. +func genAIFinishReason(reason fantasy.FinishReason) (string, bool) { + switch reason { + case fantasy.FinishReasonStop: + return "stop", true + case fantasy.FinishReasonLength: + return "length", true + case fantasy.FinishReasonToolCalls: + return "tool_call", true + case fantasy.FinishReasonContentFilter: + return "content_filter", true + case fantasy.FinishReasonError: + return "error", true + default: + return "", false + } +} + +// usageAttributes reports input tokens including cache reads and writes, +// as the conventions require. Every client chatd builds reports them +// apart from InputTokens: Google providers use the OpenAI-compatible +// client, which subtracts cached tokens from the prompt count. +// +// The cache breakdown is recorded only when nonzero: the OpenAI-compatible +// client never reports cache writes, so a zero can mean "not reported". +// +// For Anthropic, fantasy keeps the input counts of the first internal +// iteration, which measure context occupancy, and drops the cumulative +// counts Anthropic reports, so a response that ran provider tools such as +// web search undercounts its billed input. +func usageAttributes(usage fantasy.Usage) []attribute.KeyValue { + if usage == (fantasy.Usage{}) { + return nil + } + input := usage.InputTokens + usage.CacheReadTokens + usage.CacheCreationTokens + attrs := []attribute.KeyValue{ + semconv.GenAIUsageInputTokens(int(input)), + semconv.GenAIUsageOutputTokens(int(usage.OutputTokens)), + } + if usage.CacheReadTokens != 0 { + attrs = append(attrs, semconv.GenAIUsageCacheReadInputTokens(int(usage.CacheReadTokens))) + } + if usage.CacheCreationTokens != 0 { + attrs = append(attrs, semconv.GenAIUsageCacheCreationInputTokens(int(usage.CacheCreationTokens))) + } + if usage.ReasoningTokens != 0 { + attrs = append(attrs, semconv.GenAIUsageReasoningOutputTokens(int(usage.ReasoningTokens))) + } + return attrs +} diff --git a/coderd/x/chatd/chatloop/genai_internal_test.go b/coderd/x/chatd/chatloop/genai_internal_test.go new file mode 100644 index 00000000000..5703f5b262e --- /dev/null +++ b/coderd/x/chatd/chatloop/genai_internal_test.go @@ -0,0 +1,45 @@ +package chatloop + +import ( + "context" + "errors" + "maps" + "slices" + "testing" + + "github.com/stretchr/testify/require" + + "github.com/coder/coder/v2/coderd/database" + "github.com/coder/coder/v2/coderd/x/chatd/chaterror" +) + +func TestGenAIProviderNameCoversEveryProviderType(t *testing.T) { + t.Parallel() + + // Adding a provider type fails this test until the type is mapped to + // a well-known gen_ai.provider.name or listed as a pass-through. + want := map[database.AIProviderType]string{ + database.AIProviderTypeOpenai: "openai", + database.AIProviderTypeAnthropic: "anthropic", + database.AIProviderTypeAzure: "azure.ai.openai", + database.AIProviderTypeBedrock: "aws.bedrock", + database.AIProviderTypeGoogle: "gcp.gemini", + database.AIProviderTypeOpenaiCompat: "openai-compat", + database.AIProviderTypeOpenrouter: "openrouter", + database.AIProviderTypeVercel: "vercel", + database.AIProviderTypeCopilot: "copilot", + } + require.ElementsMatch(t, database.AllAIProviderTypeValues(), slices.Collect(maps.Keys(want))) + for providerType, name := range want { + require.Equal(t, name, genAIProviderName(StageModel{ProviderType: string(providerType)}), providerType) + } +} + +func TestErrorTypeKeepsTransportResetClassification(t *testing.T) { + t.Parallel() + + require.Equal(t, "canceled", errorType(context.Canceled)) + reset := errors.Join(chaterror.ErrProviderTransportReset, context.Canceled) + require.Equal(t, string(chaterror.Classify(reset).Kind), errorType(reset)) + require.NotEqual(t, "canceled", errorType(reset)) +} diff --git a/coderd/x/chatd/chatloop/stage.go b/coderd/x/chatd/chatloop/stage.go index e8b8a75c40e..a27869e822f 100644 --- a/coderd/x/chatd/chatloop/stage.go +++ b/coderd/x/chatd/chatloop/stage.go @@ -4,8 +4,10 @@ import ( "context" "time" + "charm.land/fantasy" "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/codes" + semconv "go.opentelemetry.io/otel/semconv/v1.41.0" "go.opentelemetry.io/otel/trace" "go.opentelemetry.io/otel/trace/noop" @@ -18,14 +20,17 @@ type Stage string // Stage values. const ( - StageChatTurn Stage = "chat_turn" - StageQueueWait Stage = "queue_wait" - StageAcquisition Stage = "acquisition" - StageGenerationStep Stage = "generation_step" - StagePrepare Stage = "prepare" - StageMCPConnect Stage = "mcp_connect" - StageProviderAttempt Stage = "provider_attempt" - StageStream Stage = "stream" + StageChatTurn Stage = "chat_turn" + StageQueueWait Stage = "queue_wait" + StageAcquisition Stage = "acquisition" + StageGenerationStep Stage = "generation_step" + StagePrepare Stage = "prepare" + StageMCPConnect Stage = "mcp_connect" + StageProviderAttempt Stage = "provider_attempt" + StageStream Stage = "stream" + // StageModelCall is a model call outside the assistant stream, such + // as title generation or a compaction summary. It has no histogram. + StageModelCall Stage = "model_call" StageTimeToFirstToken Stage = "time_to_first_token" StageThinking Stage = "thinking" StageToolCall Stage = "tool_call" @@ -146,6 +151,9 @@ type StageModel struct { ProviderType string Model string Effort string + // Bedrock reports that the provider serves the model through AWS + // Bedrock, which an anthropic provider type can do. + Bedrock bool } func (m StageModel) attributes() []attribute.KeyValue { @@ -213,7 +221,40 @@ func (t *StageTracer) Start( stage Stage, attrs ...attribute.KeyValue, ) (context.Context, *StageSpan) { - return t.startSpan(ctx, stage, scopeFromContext(ctx), time.Time{}, + return t.startSpan(ctx, stage, scopeFromContext(ctx), time.Time{}, StageModel{}, "", + []trace.SpanStartOption{trace.WithAttributes(attrs...)}) +} + +// StartWithModel begins a stage span that runs on model. The model is set +// at creation, so samplers see it. +func (t *StageTracer) StartWithModel( + ctx context.Context, + stage Stage, + model StageModel, + attrs ...attribute.KeyValue, +) (context.Context, *StageSpan) { + return t.startSpan(ctx, stage, scopeFromContext(ctx), time.Time{}, model, "", + []trace.SpanStartOption{trace.WithAttributes(attrs...)}) +} + +// StartModelCall begins a chat span for a model call outside the +// assistant stream. The model is set at creation, so samplers see it. +func (t *StageTracer) StartModelCall(ctx context.Context, model StageModel, stream bool) (context.Context, *StageSpan) { + return t.startSpan(ctx, StageModelCall, scopeFromContext(ctx), time.Time{}, model, "", + []trace.SpanStartOption{trace.WithAttributes(semconv.GenAIRequestStream(stream))}) +} + +// StartTool begins an execute_tool span for call. The tool metadata is +// set at creation, so samplers see it. +func (t *StageTracer) StartTool( + ctx context.Context, + model StageModel, + call fantasy.ToolCallContent, + toolType string, + attrs ...attribute.KeyValue, +) (context.Context, *StageSpan) { + attrs = append(attrs, genAIToolAttributes(call, toolType)...) + return t.startSpan(ctx, StageToolCall, scopeFromContext(ctx), time.Time{}, model, call.ToolName, []trace.SpanStartOption{trace.WithAttributes(attrs...)}) } @@ -226,7 +267,7 @@ func (t *StageTracer) StartRootAt( start time.Time, attrs ...attribute.KeyValue, ) (context.Context, *StageSpan) { - return t.startSpan(ctx, stage, ScopeTurn, start, []trace.SpanStartOption{ + return t.startSpan(ctx, stage, ScopeTurn, start, StageModel{}, "", []trace.SpanStartOption{ trace.WithNewRoot(), trace.WithAttributes(attrs...), }) @@ -237,6 +278,8 @@ func (t *StageTracer) startSpan( stage Stage, scope Scope, start time.Time, + model StageModel, + toolName string, opts []trace.SpanStartOption, ) (context.Context, *StageSpan) { if t == nil { @@ -253,13 +296,19 @@ func (t *StageTracer) startSpan( } opts = append(opts, trace.WithTimestamp(start)) chatKind := chatKindFromContext(ctx) - opts = append(opts, trace.WithAttributes(stageIdentityAttributes(scope, chatKind)...)) - ctx, span := t.otelTracer().Start(ContextWithScope(ctx, scope), string(stage), opts...) + name, genAIOpts := stageSpanStart(ctx, stage, model, toolName) + opts = append(opts, + trace.WithAttributes(model.attributes()...), + trace.WithAttributes(stageIdentityAttributes(scope, chatKind)...), + ) + opts = append(opts, genAIOpts...) + ctx, span := t.otelTracer().Start(ContextWithScope(ctx, scope), name, opts...) return ctx, &StageSpan{ tracer: t, stage: stage, scope: scope, chatKind: chatKind, + model: model, span: span, start: start, } @@ -340,6 +389,9 @@ func (s *StageSpan) closeSpanAt(err error, end time.Time) time.Duration { if err != nil { s.span.RecordError(err) s.span.SetStatus(codes.Error, err.Error()) + if s.span.IsRecording() { + s.span.SetAttributes(semconv.ErrorTypeKey.String(errorType(err))) + } } s.span.End(trace.WithTimestamp(end)) return end.Sub(s.start) @@ -365,15 +417,19 @@ func (t *StageTracer) Record( } scope := scopeFromContext(ctx) chatKind := chatKindFromContext(ctx) - _, span := t.otelTracer().Start(ctx, string(stage), + name, genAIOpts := stageSpanStart(ctx, stage, model, "") + _, span := t.otelTracer().Start(ctx, name, append([]trace.SpanStartOption{ trace.WithTimestamp(start), trace.WithAttributes(attrs...), trace.WithAttributes(model.attributes()...), trace.WithAttributes(stageIdentityAttributes(scope, chatKind)...), - ) + }, genAIOpts...)...) if err != nil { span.RecordError(err) span.SetStatus(codes.Error, err.Error()) + if span.IsRecording() { + span.SetAttributes(semconv.ErrorTypeKey.String(errorType(err))) + } } span.End(trace.WithTimestamp(end)) t.observe(stage, scope, chatKind, model, end.Sub(start)) diff --git a/coderd/x/chatd/chatloop/stage_internal_test.go b/coderd/x/chatd/chatloop/stage_internal_test.go index 7f13e49ff5c..b435871051f 100644 --- a/coderd/x/chatd/chatloop/stage_internal_test.go +++ b/coderd/x/chatd/chatloop/stage_internal_test.go @@ -2,10 +2,14 @@ package chatloop import ( "context" + "slices" + "sync" "testing" "time" "charm.land/fantasy" + fantasyopenai "charm.land/fantasy/providers/openai" + "github.com/google/uuid" "github.com/prometheus/client_golang/prometheus" dto "github.com/prometheus/client_model/go" "github.com/stretchr/testify/require" @@ -63,6 +67,10 @@ func histogramTotals(t *testing.T, registry *prometheus.Registry, name string) ( return count, sum } +func spanStage(span sdktrace.ReadOnlySpan) Stage { + return Stage(chattest.SpanStage(span)) +} + func metricLabel(metric *dto.Metric, name string) string { for _, label := range metric.GetLabel() { if label.GetName() == name { @@ -76,7 +84,7 @@ func endedSpan(t *testing.T, spans *tracetest.SpanRecorder, stage Stage) sdktrac t.Helper() var found sdktrace.ReadOnlySpan for _, span := range spans.Ended() { - if span.Name() != string(stage) { + if spanStage(span) != stage { continue } require.Nil(t, found, "more than one %s span was recorded", stage) @@ -92,8 +100,8 @@ func requireEndedBefore(t *testing.T, spans *tracetest.SpanRecorder, first, seco t.Helper() var names []string for _, span := range spans.Ended() { - if span.Name() == string(first) || span.Name() == string(second) { - names = append(names, span.Name()) + if stage := spanStage(span); stage == first || stage == second { + names = append(names, string(stage)) } } require.Equal(t, []string{string(first), string(second)}, names) @@ -115,6 +123,51 @@ func recordedErrorMessage(t *testing.T, span sdktrace.ReadOnlySpan) string { return "" } +func requireNoAttribute(t *testing.T, span sdktrace.ReadOnlySpan, key string) { + t.Helper() + for _, attr := range span.Attributes() { + require.NotEqual(t, key, string(attr.Key), "span %s has %s", span.Name(), key) + } +} + +func spanAttribute(t *testing.T, span sdktrace.ReadOnlySpan, key string) string { + t.Helper() + for _, attr := range span.Attributes() { + if string(attr.Key) == key { + return attr.Value.AsString() + } + } + t.Fatalf("span %s has no %s attribute", span.Name(), key) + return "" +} + +// recordingSampler records what the sampler sees when each span starts. +type recordingSampler struct { + mu sync.Mutex + params []sdktrace.SamplingParameters +} + +func (s *recordingSampler) ShouldSample(p sdktrace.SamplingParameters) sdktrace.SamplingResult { + s.mu.Lock() + defer s.mu.Unlock() + p.Attributes = slices.Clone(p.Attributes) + s.params = append(s.params, p) + return sdktrace.SamplingResult{Decision: sdktrace.RecordAndSample} +} + +func (*recordingSampler) Description() string { return "recording" } + +func (s *recordingSampler) find(name string) (sdktrace.SamplingParameters, bool) { + s.mu.Lock() + defer s.mu.Unlock() + for _, p := range s.params { + if p.Name == name { + return p, true + } + } + return sdktrace.SamplingParameters{}, false +} + type stageMetricsFixture struct { tracer *StageTracer spans *tracetest.SpanRecorder @@ -416,11 +469,30 @@ func TestGenerateAssistantStreamStage(t *testing.T) { err := generate(t, fixture, []fantasy.StreamPart{ {Type: fantasy.StreamPartTypeTextDelta, Delta: "hi"}, - {Type: fantasy.StreamPartTypeFinish, FinishReason: fantasy.FinishReasonStop}, + { + Type: fantasy.StreamPartTypeFinish, + ID: "msg_1", + FinishReason: fantasy.FinishReasonStop, + Usage: fantasy.Usage{InputTokens: 10, OutputTokens: 5, CacheReadTokens: 3, CacheCreationTokens: 2}, + }, }) require.NoError(t, err) stream := endedSpan(t, fixture.spans, StageStream) + require.Equal(t, "chat claude", stream.Name()) + require.Equal(t, trace.SpanKindClient, stream.SpanKind()) + require.Subset(t, stream.Attributes(), []attribute.KeyValue{ + attribute.String("gen_ai.operation.name", "chat"), + attribute.String("gen_ai.provider.name", "aws.bedrock"), + attribute.String("gen_ai.request.model", "claude"), + attribute.Bool("gen_ai.request.stream", true), + attribute.String("gen_ai.response.id", "msg_1"), + attribute.StringSlice("gen_ai.response.finish_reasons", []string{"stop"}), + attribute.Int("gen_ai.usage.input_tokens", 15), + attribute.Int("gen_ai.usage.output_tokens", 5), + attribute.Int("gen_ai.usage.cache_read.input_tokens", 3), + attribute.Int("gen_ai.usage.cache_creation.input_tokens", 2), + }) ttft := endedSpan(t, fixture.spans, StageTimeToFirstToken) require.Equal(t, codes.Unset, stream.Status().Code) require.Equal(t, codes.Unset, ttft.Status().Code) @@ -435,6 +507,49 @@ func TestGenerateAssistantStreamStage(t *testing.T) { requireStreamObserved(t, fixture) }) + t.Run("SamplerSeesModelAtCreation", func(t *testing.T) { + t.Parallel() + sampler := &recordingSampler{} + provider := sdktrace.NewTracerProvider(sdktrace.WithSampler(sampler)) + t.Cleanup(func() { + require.NoError(t, provider.Shutdown(context.Background())) + }) + fixture := newStageMetricsFixture(t) + fixture.tracer = NewStageTracer(provider, fixture.metrics, WithClock(fixture.clock)) + + err := generate(t, fixture, []fantasy.StreamPart{ + {Type: fantasy.StreamPartTypeTextDelta, Delta: "hi"}, + {Type: fantasy.StreamPartTypeFinish, FinishReason: fantasy.FinishReasonStop}, + }) + require.NoError(t, err) + + params, ok := sampler.find("chat claude") + require.True(t, ok, "no chat span was sampled under its final name") + require.Equal(t, trace.SpanKindClient, params.Kind) + require.Subset(t, params.Attributes, []attribute.KeyValue{ + attribute.String("gen_ai.operation.name", "chat"), + attribute.String("gen_ai.provider.name", "aws.bedrock"), + attribute.String("gen_ai.request.model", "claude"), + }) + }) + + t.Run("CleanCloseWithoutFinishRecordsNoReason", func(t *testing.T) { + t.Parallel() + fixture := newStageMetricsFixture(t) + + err := generate(t, fixture, []fantasy.StreamPart{ + {Type: fantasy.StreamPartTypeTextStart, ID: "t"}, + {Type: fantasy.StreamPartTypeTextDelta, ID: "t", Delta: "done"}, + {Type: fantasy.StreamPartTypeTextEnd, ID: "t"}, + }) + require.NoError(t, err) + + stream := endedSpan(t, fixture.spans, StageStream) + require.Equal(t, codes.Unset, stream.Status().Code) + // The provider gave no reason, so none is claimed. + requireNoAttribute(t, stream, "gen_ai.response.finish_reasons") + }) + t.Run("OpenFailureEndsStreamWithError", func(t *testing.T) { t.Parallel() fixture := newStageMetricsFixture(t) @@ -481,6 +596,8 @@ func TestGenerateAssistantStreamStage(t *testing.T) { stream := endedSpan(t, fixture.spans, StageStream) require.Equal(t, codes.Error, stream.Status().Code) require.Equal(t, err.Error(), recordedErrorMessage(t, stream)) + requireNoAttribute(t, stream, "gen_ai.response.finish_reasons") + require.NotEmpty(t, spanAttribute(t, stream, "error.type")) requireStreamObserved(t, fixture) }) @@ -520,24 +637,29 @@ func TestExecuteLocalToolsToolCallStage(t *testing.T) { t.Parallel() stageModel := StageModel{Provider: "openai", ProviderType: "openai", Model: "gpt-test", Effort: "high"} - execute := func(t *testing.T, fixture stageMetricsFixture, tool fantasy.AgentTool) PersistedStep { + executeWithBuiltins := func(t *testing.T, fixture stageMetricsFixture, tool fantasy.AgentTool, builtins map[string]bool) PersistedStep { t.Helper() ctx := ContextWithScope(t.Context(), ScopeTurn) ctx, step := fixture.tracer.Start(ctx, StageGenerationStep) defer step.End(nil) result, err := ExecuteLocalTools(ctx, ExecuteLocalToolsOptions{ - Tools: []fantasy.AgentTool{tool}, - ActiveTools: []string{tool.Info().Name}, - ToolCalls: []fantasy.ToolCallContent{{ToolCallID: "call-1", ToolName: tool.Info().Name, Input: "{}"}}, - ModelProvider: "openai", - ModelName: "gpt-test", - Stages: fixture.tracer, - StageModel: stageModel, - Clock: fixture.clock, + Tools: []fantasy.AgentTool{tool}, + ActiveTools: []string{tool.Info().Name}, + ToolCalls: []fantasy.ToolCallContent{{ToolCallID: "call-1", ToolName: tool.Info().Name, Input: "{}"}}, + BuiltinToolNames: builtins, + ModelProvider: "openai", + ModelName: "gpt-test", + Stages: fixture.tracer, + StageModel: stageModel, + Clock: fixture.clock, }) require.NoError(t, err) return result } + execute := func(t *testing.T, fixture stageMetricsFixture, tool fantasy.AgentTool) PersistedStep { + t.Helper() + return executeWithBuiltins(t, fixture, tool, nil) + } t.Run("RunsToolOnStageContext", func(t *testing.T) { t.Parallel() @@ -560,12 +682,45 @@ func TestExecuteLocalToolsToolCallStage(t *testing.T) { require.Contains(t, toolCall.Attributes(), attribute.String(AttrProvider, "openai")) require.Contains(t, toolCall.Attributes(), attribute.String(AttrModel, "gpt-test")) require.Contains(t, toolCall.Attributes(), attribute.String(AttrScope, string(ScopeTurn))) + require.Equal(t, "execute_tool read_file", toolCall.Name()) + require.Subset(t, toolCall.Attributes(), []attribute.KeyValue{ + attribute.String("gen_ai.operation.name", "execute_tool"), + attribute.String("gen_ai.tool.name", "read_file"), + attribute.String("gen_ai.tool.call.id", "call-1"), + attribute.String("gen_ai.tool.type", "extension"), + }) count, ok := stageSampleCount(t, fixture.registry, StageToolCall) require.True(t, ok) require.Equal(t, uint64(1), count) }) - t.Run("ErrorResultEndsWithoutError", func(t *testing.T) { + t.Run("SamplerSeesToolAtCreation", func(t *testing.T) { + t.Parallel() + sampler := &recordingSampler{} + provider := sdktrace.NewTracerProvider(sdktrace.WithSampler(sampler)) + t.Cleanup(func() { + require.NoError(t, provider.Shutdown(context.Background())) + }) + fixture := newStageMetricsFixture(t) + fixture.tracer = NewStageTracer(provider, fixture.metrics, WithClock(fixture.clock)) + tool := fantasy.NewAgentTool("read_file", "reads a file", + func(context.Context, struct{}, fantasy.ToolCall) (fantasy.ToolResponse, error) { + return fantasy.NewTextResponse("ok"), nil + }) + + executeWithBuiltins(t, fixture, tool, map[string]bool{"read_file": true}) + + params, ok := sampler.find("execute_tool read_file") + require.True(t, ok, "no tool span was sampled under its final name") + require.Subset(t, params.Attributes, []attribute.KeyValue{ + attribute.String("gen_ai.operation.name", "execute_tool"), + attribute.String("gen_ai.tool.name", "read_file"), + attribute.String("gen_ai.tool.call.id", "call-1"), + attribute.String("gen_ai.tool.type", "function"), + }) + }) + + t.Run("ErrorResultEndsWithToolError", func(t *testing.T) { t.Parallel() fixture := newStageMetricsFixture(t) tool := fantasy.NewAgentTool("read_file", "reads a file", @@ -579,7 +734,12 @@ func TestExecuteLocalToolsToolCallStage(t *testing.T) { toolResult, ok := result.Content[0].(fantasy.ToolResultContent) require.True(t, ok) require.IsType(t, fantasy.ToolResultOutputContentError{}, toolResult.Result) - require.Equal(t, codes.Unset, endedSpan(t, fixture.spans, StageToolCall).Status().Code) + // Tools such as MCP clients report failures, including an + // unreachable server, as error results rather than Run errors. + toolCall := endedSpan(t, fixture.spans, StageToolCall) + require.Equal(t, codes.Error, toolCall.Status().Code) + require.Equal(t, "tool_error", spanAttribute(t, toolCall, "error.type")) + require.NotContains(t, toolCall.Status().Description, "file not found") }) t.Run("ExecutionFailureEndsWithError", func(t *testing.T) { @@ -596,6 +756,7 @@ func TestExecuteLocalToolsToolCallStage(t *testing.T) { toolCall := endedSpan(t, fixture.spans, StageToolCall) require.Equal(t, codes.Error, toolCall.Status().Code) require.Equal(t, runErr.Error(), recordedErrorMessage(t, toolCall)) + require.NotEmpty(t, spanAttribute(t, toolCall, "error.type")) }) t.Run("PanicEndsWithError", func(t *testing.T) { @@ -644,9 +805,146 @@ func TestExecuteLocalToolsToolCallStage(t *testing.T) { require.IsType(t, fantasy.ToolResultOutputContentError{}, toolResult.Result) } for _, span := range fixture.spans.Ended() { - require.NotEqual(t, string(StageToolCall), span.Name()) + require.NotEqual(t, StageToolCall, spanStage(span)) } _, ok := stageSampleCount(t, fixture.registry, StageToolCall) require.False(t, ok) }) } + +func TestModelCallStage(t *testing.T) { + t.Parallel() + + stageModel := StageModel{Provider: "anthropic", ProviderType: "anthropic", Model: "claude"} + usage := fantasy.Usage{InputTokens: 10, OutputTokens: 5} + requireModelCallSpan := func(t *testing.T, span sdktrace.ReadOnlySpan, stream bool) { + t.Helper() + require.Equal(t, "chat claude", span.Name()) + require.Equal(t, trace.SpanKindClient, span.SpanKind()) + require.Subset(t, span.Attributes(), []attribute.KeyValue{ + attribute.String("gen_ai.operation.name", "chat"), + attribute.String("gen_ai.provider.name", "anthropic"), + attribute.Bool("gen_ai.request.stream", stream), + attribute.Int("gen_ai.usage.input_tokens", 10), + attribute.Int("gen_ai.usage.output_tokens", 5), + }) + } + + t.Run("GenerateObjectRecordsUsage", func(t *testing.T) { + t.Parallel() + fixture := newStageMetricsFixture(t) + // The context has no identity, as for manual title proposals, so + // the wrapper's identity attributes the call. + chatID := uuid.New() + model := fixture.tracer.TraceModelCalls(&chattest.FakeModel{ + ProviderName: "anthropic", + ModelName: "claude", + GenerateObjectFn: func(context.Context, fantasy.ObjectCall) (*fantasy.ObjectResponse, error) { + return &fantasy.ObjectResponse{ + FinishReason: fantasy.FinishReasonStop, + Usage: usage, + ProviderMetadata: fantasy.ProviderMetadata{ + fantasyopenai.Name: &fantasyopenai.ResponsesProviderMetadata{ResponseID: "resp_1"}, + }, + }, nil + }, + }, TracedModelOptions{StageModel: stageModel, Identity: ChatIdentity{ChatID: chatID}, JSONObjects: true}) + + _, err := model.GenerateObject(t.Context(), fantasy.ObjectCall{}) + require.NoError(t, err) + + span := endedSpan(t, fixture.spans, StageModelCall) + requireModelCallSpan(t, span, false) + require.Contains(t, span.Attributes(), attribute.String("gen_ai.conversation.id", chatID.String())) + require.Contains(t, span.Attributes(), attribute.StringSlice("gen_ai.response.finish_reasons", []string{"stop"})) + require.Contains(t, span.Attributes(), attribute.String("gen_ai.response.id", "resp_1")) + require.Contains(t, span.Attributes(), attribute.String("gen_ai.output.type", "json")) + // The usage reports no cache breakdown, so none is claimed. + requireNoAttribute(t, span, "gen_ai.usage.cache_creation.input_tokens") + _, observed := stageSampleCount(t, fixture.registry, StageModelCall) + require.False(t, observed, "model calls have no stage histogram") + }) + + t.Run("UnparsedObjectRecordsUsageAndError", func(t *testing.T) { + t.Parallel() + fixture := newStageMetricsFixture(t) + model := fixture.tracer.TraceModelCalls(&chattest.FakeModel{ + ProviderName: "anthropic", + ModelName: "claude", + GenerateObjectFn: func(context.Context, fantasy.ObjectCall) (*fantasy.ObjectResponse, error) { + return nil, &fantasy.NoObjectGeneratedError{Usage: usage, FinishReason: fantasy.FinishReasonLength} + }, + }, TracedModelOptions{StageModel: stageModel}) + + _, err := model.GenerateObject(t.Context(), fantasy.ObjectCall{}) + require.Error(t, err) + + span := endedSpan(t, fixture.spans, StageModelCall) + requireModelCallSpan(t, span, false) + require.Equal(t, codes.Error, span.Status().Code) + // The model's own reason survives the parse failure. + require.Contains(t, span.Attributes(), attribute.StringSlice("gen_ai.response.finish_reasons", []string{"length"})) + // A client that forces a tool call does not request JSON output. + requireNoAttribute(t, span, "gen_ai.output.type") + }) + + t.Run("EmptyCompactionSummaryEndsWithError", func(t *testing.T) { + t.Parallel() + fixture := newStageMetricsFixture(t) + model := &chattest.FakeModel{ + ProviderName: "anthropic", + ModelName: "claude", + StreamFn: func(context.Context, fantasy.Call) (fantasy.StreamResponse, error) { + return streamFromParts([]fantasy.StreamPart{ + {Type: fantasy.StreamPartTypeFinish, FinishReason: fantasy.FinishReasonStop, Usage: usage}, + }), nil + }, + } + + summary, _, err := generateCompactionSummary(t.Context(), model, + []fantasy.Message{{Role: fantasy.MessageRoleUser, Content: []fantasy.MessagePart{fantasy.TextPart{Text: "hello"}}}}, + GenerateCompactionOptions{SummaryPrompt: "summarize", Clock: fixture.clock, Stages: fixture.tracer, StageModel: stageModel}, + ) + require.NoError(t, err) + require.Empty(t, summary) + + span := endedSpan(t, fixture.spans, StageModelCall) + require.Equal(t, codes.Error, span.Status().Code) + require.Contains(t, span.Attributes(), attribute.Int("gen_ai.usage.output_tokens", 5)) + }) + + t.Run("CompactionSummaryRecordsChatSpan", func(t *testing.T) { + t.Parallel() + fixture := newStageMetricsFixture(t) + model := &chattest.FakeModel{ + ProviderName: "anthropic", + ModelName: "claude", + StreamFn: func(context.Context, fantasy.Call) (fantasy.StreamResponse, error) { + return streamFromParts([]fantasy.StreamPart{ + {Type: fantasy.StreamPartTypeTextStart, ID: "text"}, + {Type: fantasy.StreamPartTypeTextDelta, ID: "text", Delta: "summary"}, + {Type: fantasy.StreamPartTypeTextEnd, ID: "text"}, + {Type: fantasy.StreamPartTypeFinish, ID: "msg_summary", FinishReason: fantasy.FinishReasonStop, Usage: usage}, + }), nil + }, + } + + ctx, compaction := fixture.tracer.Start(t.Context(), StageCompaction) + _, _, err := generateCompactionSummary(ctx, model, + []fantasy.Message{{Role: fantasy.MessageRoleUser, Content: []fantasy.MessagePart{fantasy.TextPart{Text: "hello"}}}}, + GenerateCompactionOptions{ + SummaryPrompt: "summarize", + Clock: fixture.clock, + Stages: fixture.tracer, + StageModel: stageModel, + }, + ) + compaction.End(err) + require.NoError(t, err) + + span := endedSpan(t, fixture.spans, StageModelCall) + requireModelCallSpan(t, span, true) + require.Equal(t, endedSpan(t, fixture.spans, StageCompaction).SpanContext().SpanID(), span.Parent().SpanID()) + require.Contains(t, span.Attributes(), attribute.String("gen_ai.response.id", "msg_summary")) + }) +} diff --git a/coderd/x/chatd/chatloop/stage_test.go b/coderd/x/chatd/chatloop/stage_test.go index 1db150b0ec4..05ccb699df4 100644 --- a/coderd/x/chatd/chatloop/stage_test.go +++ b/coderd/x/chatd/chatloop/stage_test.go @@ -17,9 +17,14 @@ import ( "golang.org/x/xerrors" "github.com/coder/coder/v2/coderd/x/chatd/chatloop" + "github.com/coder/coder/v2/coderd/x/chatd/chattest" "github.com/coder/quartz" ) +func spanStage(span sdktrace.ReadOnlySpan) chatloop.Stage { + return chatloop.Stage(chattest.SpanStage(span)) +} + type stageFixture struct { tracer *chatloop.StageTracer clock *quartz.Mock @@ -114,7 +119,7 @@ func (f stageFixture) spanDuration(t *testing.T, stage chatloop.Stage) time.Dura t.Helper() var found []sdktrace.ReadOnlySpan for _, span := range f.spans.Ended() { - if span.Name() == string(stage) { + if spanStage(span) == stage { found = append(found, span) } } @@ -249,7 +254,8 @@ func TestStageTracerStartRootAtIgnoresParent(t *testing.T) { ended := fixture.spans.Ended() require.Len(t, ended, 2) turn, step := ended[0], ended[1] - require.Equal(t, string(chatloop.StageChatTurn), turn.Name()) + require.Equal(t, chatloop.StageChatTurn, spanStage(turn)) + require.Equal(t, "invoke_agent coder", turn.Name()) require.False(t, turn.Parent().IsValid()) require.NotEqual(t, step.SpanContext().TraceID(), turn.SpanContext().TraceID()) require.Equal(t, time.Second, fixture.spanDuration(t, chatloop.StageChatTurn)) @@ -266,7 +272,7 @@ func TestStageTracerStartRootAt(t *testing.T) { var chatTurn, acquisition sdktrace.ReadOnlySpan for _, span := range fixture.spans.Ended() { - switch chatloop.Stage(span.Name()) { + switch spanStage(span) { case chatloop.StageChatTurn: chatTurn = span case chatloop.StageAcquisition: diff --git a/coderd/x/chatd/chatloop/tracedmodel.go b/coderd/x/chatd/chatloop/tracedmodel.go new file mode 100644 index 00000000000..57137493918 --- /dev/null +++ b/coderd/x/chatd/chatloop/tracedmodel.go @@ -0,0 +1,92 @@ +package chatloop + +import ( + "context" + "errors" + + "charm.land/fantasy" + semconv "go.opentelemetry.io/otel/semconv/v1.41.0" +) + +// TracedModelOptions describes the model calls TraceModelCalls records. +type TracedModelOptions struct { + StageModel StageModel + // Identity attributes calls whose context carries none, since some + // callers run outside any chat context. + Identity ChatIdentity + // JSONObjects reports that the client requests GenerateObject output + // in the provider's native JSON format. Clients that generate objects + // through a forced tool call or text parsing do not. + JSONObjects bool +} + +// TraceModelCalls wraps model so each non-streaming Generate and +// GenerateObject call records a chat span. Streaming calls pass through: +// GenerateAssistant and compaction trace their own streams. +func (t *StageTracer) TraceModelCalls(model fantasy.LanguageModel, opts TracedModelOptions) fantasy.LanguageModel { + if t == nil || model == nil { + return model + } + return &tracedModel{LanguageModel: model, tracer: t, opts: opts} +} + +type tracedModel struct { + fantasy.LanguageModel + tracer *StageTracer + opts TracedModelOptions +} + +func (m *tracedModel) start(ctx context.Context) (context.Context, *StageSpan) { + if _, ok := chatIdentityFromContext(ctx); !ok { + ctx = ContextWithChatIdentity(ctx, m.opts.Identity) + } + return m.tracer.StartModelCall(ctx, m.opts.StageModel, false) +} + +func (m *tracedModel) Generate(ctx context.Context, call fantasy.Call) (resp *fantasy.Response, err error) { + ctx, span := m.start(ctx) + span.setRequestParams(call.MaxOutputTokens, call.Temperature) + defer func() { + inference := InferenceResponse{} + if resp != nil { + inference.ResponseID = metadataResponseID(resp.ProviderMetadata) + inference.FinishReason = resp.FinishReason + inference.Usage = resp.Usage + } + endModelCall(span, inference, err) + }() + return m.LanguageModel.Generate(ctx, call) +} + +func (m *tracedModel) GenerateObject(ctx context.Context, call fantasy.ObjectCall) (resp *fantasy.ObjectResponse, err error) { + ctx, span := m.start(ctx) + span.setRequestParams(call.MaxOutputTokens, call.Temperature) + if m.opts.JSONObjects { + span.SetAttributes(semconv.GenAIOutputTypeJSON) + } + defer func() { + inference := InferenceResponse{} + var noObject *fantasy.NoObjectGeneratedError + switch { + case resp != nil: + inference.ResponseID = metadataResponseID(resp.ProviderMetadata) + inference.FinishReason = resp.FinishReason + inference.Usage = resp.Usage + case errors.As(err, &noObject): + // The model responded and billed tokens, but the output did + // not parse. + inference.FinishReason = noObject.FinishReason + inference.Usage = noObject.Usage + } + endModelCall(span, inference, err) + }() + return m.LanguageModel.GenerateObject(ctx, call) +} + +// endModelCall records the response of a model call span and ends it. +// The finish reason stays the one the model reported, even when the caller +// rejects the response; err sets the span status and error.type. +func endModelCall(span *StageSpan, inference InferenceResponse, err error) { + span.SetInferenceResponse(inference) + span.End(err) +} diff --git a/coderd/x/chatd/chattest/spans.go b/coderd/x/chatd/chattest/spans.go new file mode 100644 index 00000000000..50be430368c --- /dev/null +++ b/coderd/x/chatd/chattest/spans.go @@ -0,0 +1,18 @@ +package chattest + +import ( + sdktrace "go.opentelemetry.io/otel/sdk/trace" +) + +// SpanStage returns the chat lifecycle stage a span records, or "" when it +// has none. GenAI spans are named after their operation, so tests identify +// stages by this attribute. The key matches chatloop.AttrStage, which this +// package cannot import because chatloop's internal tests import it. +func SpanStage(span sdktrace.ReadOnlySpan) string { + for _, attr := range span.Attributes() { + if attr.Key == "stage" { + return attr.Value.AsString() + } + } + return "" +} diff --git a/coderd/x/chatd/generation.go b/coderd/x/chatd/generation.go index 9361dbb3332..679f0821e4b 100644 --- a/coderd/x/chatd/generation.go +++ b/coderd/x/chatd/generation.go @@ -50,6 +50,9 @@ type generationPrepareInput struct { debug *generationDebug, summaries []mcpclient.ConnectSummary, ) + // RecordStageModel receives the turn model as soon as it resolves, + // so a preparation that fails later still attributes its turn span. + RecordStageModel func(chatloop.StageModel) } // generationCompaction contains compaction inputs prepared for generation. @@ -636,6 +639,9 @@ func (s *taskStarter) runGenerationStep( Chat: chat, Messages: messages, RecordMCPConnectSummaries: input.DebugTurn.RecordMCPConnectSummaries, + RecordStageModel: func(model chatloop.StageModel) { + input.TurnSpan.SetProvider(input.TurnToken, model) + }, } prepareCtx, prepareSpan := s.server.stages.Start(ctx, chatloop.StagePrepare) prepared, err := retryGenerationPhase(prepareCtx, s, "prepare", func() (turnEnvironment, error) { @@ -1319,6 +1325,8 @@ func (s *taskStarter) generateCompaction( attribute.String(chatloop.AttrCompactionSource, string(source)), ) compactionSpan.SetModel(compactionModel) + compactionOpts.Stages = s.server.stages + compactionOpts.StageModel = compactionModel outcome, err := chatloop.GenerateCompaction(compactionCtx, compactionOpts) compactionSpan.End(err) if err != nil { diff --git a/coderd/x/chatd/modelcall.go b/coderd/x/chatd/modelcall.go index 89458ffaf7b..35bccef0230 100644 --- a/coderd/x/chatd/modelcall.go +++ b/coderd/x/chatd/modelcall.go @@ -10,6 +10,7 @@ import ( "cdr.dev/slog/v3" "github.com/coder/coder/v2/coderd/database" + "github.com/coder/coder/v2/coderd/database/db2sdk" "github.com/coder/coder/v2/coderd/database/dbauthz" "github.com/coder/coder/v2/coderd/util/ptr" "github.com/coder/coder/v2/coderd/x/chatd/chatdebug" @@ -86,6 +87,10 @@ func (r resolvedModelCall) stageModel() chatloop.StageModel { if r.model.Valid() { stageModel.Provider = r.model.Provider() } + // Settings were validated when the provider was configured. + if settings, err := db2sdk.AIProviderSettings(r.route.Provider.Settings); err == nil { + stageModel.Bedrock = settings.Bedrock != nil + } return stageModel } @@ -178,6 +183,17 @@ func (p *Server) resolveModelCall(ctx context.Context, spec modelCallSpec) (reso if err != nil { return resolvedModelCall{}, xerrors.Errorf("create model: %w", err) } + // Innermost, so each provider attempt of a fallback records its own span. + tracedModel := buildOpts.StageModel + tracedModel.Provider = model.Provider() + model = model.WithLanguageModel(p.stages.TraceModelCalls(model.LanguageModel(), chatloop.TracedModelOptions{ + StageModel: tracedModel, + Identity: chatIdentity(spec.chat), + // chatd builds every client with its default object mode, and only + // the native OpenAI client's default sends a JSON schema; the + // others force a tool call. + JSONObjects: model.Provider() == fantasyopenai.Name, + })) model = p.withThinkingDropBlock(model, out.route.Provider.ID, clientCallConfig, spec.chat.ID) model = p.withQuickgenParamFallback(model, out.route.Provider.ID) out.reasoningRejected = &atomic.Bool{} diff --git a/coderd/x/chatd/modelcall_internal_test.go b/coderd/x/chatd/modelcall_internal_test.go index c217c933f55..659ca157ebb 100644 --- a/coderd/x/chatd/modelcall_internal_test.go +++ b/coderd/x/chatd/modelcall_internal_test.go @@ -1,6 +1,7 @@ package chatd import ( + "database/sql" "encoding/json" "io" "net/http" @@ -98,6 +99,23 @@ func TestResolveModelCallDerivesProviderOptions(t *testing.T) { requireOpenAIUserOption(t, summaryObjectCall(resolved).ProviderOptions, "summary-options-sentinel") } +func TestResolvedModelCallStageModelMarksBedrockSettings(t *testing.T) { + t.Parallel() + settings, err := json.Marshal(codersdk.AIProviderSettings{ + Bedrock: &codersdk.AIProviderBedrockSettings{Region: "us-east-1"}, + }) + require.NoError(t, err) + resolved := resolvedModelCall{ + route: aiGatewayModelRoute{Provider: database.AIProvider{ + Type: database.AIProviderTypeAnthropic, + Settings: sql.NullString{String: string(settings), Valid: true}, + }}, + resolvedModel: "claude", + } + + require.True(t, resolved.stageModel().Bedrock) +} + func TestResolveModelCallStageModel(t *testing.T) { t.Parallel() @@ -185,13 +203,18 @@ func TestResolveModelCallStageModel(t *testing.T) { }}}) require.Error(t, err) ended := recorder.Ended() - require.Len(t, ended, 1) - require.Equal(t, string(chatloop.StageProviderAttempt), ended[0].Name()) - require.Contains(t, ended[0].Attributes(), attribute.String(chatloop.AttrProvider, wantStageModel.Provider)) - require.Contains(t, ended[0].Attributes(), attribute.String(chatloop.AttrProviderType, wantStageModel.ProviderType)) - require.Contains(t, ended[0].Attributes(), attribute.String(chatloop.AttrModel, wantStageModel.Model)) + require.Len(t, ended, 2) + // The provider attempt ends inside the model call's chat span. + attemptSpan, modelCall := ended[0], ended[1] + require.Equal(t, chatloop.StageModelCall, spanStage(modelCall)) + require.Equal(t, modelCall.SpanContext().SpanID(), attemptSpan.Parent().SpanID()) + require.Contains(t, modelCall.Attributes(), attribute.String(chatloop.AttrProvider, wantStageModel.Provider)) + require.Equal(t, string(chatloop.StageProviderAttempt), attemptSpan.Name()) + require.Contains(t, attemptSpan.Attributes(), attribute.String(chatloop.AttrProvider, wantStageModel.Provider)) + require.Contains(t, attemptSpan.Attributes(), attribute.String(chatloop.AttrProviderType, wantStageModel.ProviderType)) + require.Contains(t, attemptSpan.Attributes(), attribute.String(chatloop.AttrModel, wantStageModel.Model)) if wantStageModel.Effort != "" { - require.Contains(t, ended[0].Attributes(), attribute.String(chatloop.AttrReasoningEffort, wantStageModel.Effort)) + require.Contains(t, attemptSpan.Attributes(), attribute.String(chatloop.AttrReasoningEffort, wantStageModel.Effort)) } }) } diff --git a/coderd/x/chatd/turn_environment.go b/coderd/x/chatd/turn_environment.go index b24669da5d7..8c7758523ac 100644 --- a/coderd/x/chatd/turn_environment.go +++ b/coderd/x/chatd/turn_environment.go @@ -220,6 +220,9 @@ func (p *Server) buildTurnEnvironment( if err != nil { return turnEnvironment{}, err } + if input.RecordStageModel != nil { + input.RecordStageModel(resolved.stageModel()) + } modelConfig := resolved.dbConfig var computerUseProvider codersdk.ChatComputerUseProvider diff --git a/coderd/x/chatd/turn_trace.go b/coderd/x/chatd/turn_trace.go index d721dea8e57..47af9de0324 100644 --- a/coderd/x/chatd/turn_trace.go +++ b/coderd/x/chatd/turn_trace.go @@ -48,6 +48,7 @@ type turnState struct { span *chatloop.StageSpan spanCtx trace.SpanContext chatKind chatloop.ChatKind + identity chatloop.ChatIdentity // triggerAt is unadjusted, unlike the span's anchor. triggerAt time.Time finished bool @@ -115,6 +116,7 @@ func (t *runnerTurnSpan) startLocked(ctx context.Context, chat database.Chat, tr turn := &turnState{ token: t.lastToken, chatKind: chatKind(chat), + identity: chatIdentity(chat), triggerAt: triggerAt, holders: map[uuid.UUID]struct{}{}, } @@ -141,7 +143,7 @@ func (turn *turnState) hold(taskID uuid.UUID) { func (turn *turnState) context(ctx context.Context) context.Context { // Stage identity is needed even when tracing is not recording. - ctx = withStageIdentity(ctx, chatloop.ScopeTurn, turn.chatKind) + ctx = stageIdentityContext(ctx, chatloop.ScopeTurn, turn.chatKind, turn.identity) if !turn.spanCtx.IsValid() { return ctx } @@ -205,6 +207,18 @@ func (t *runnerTurnSpan) Release(taskID uuid.UUID) { } } +// SetProvider records the model provider on the turn's invoke_agent span. +func (t *runnerTurnSpan) SetProvider(token turnToken, model chatloop.StageModel) { + if t == nil { + return + } + t.mu.Lock() + defer t.mu.Unlock() + if turn := t.turns[token]; turn != nil { + turn.span.SetGenAIProvider(model) + } +} + // OpenToken returns the zero token when ctx is done. func (t *runnerTurnSpan) OpenToken(ctx context.Context) turnToken { if t == nil { diff --git a/coderd/x/chatd/turn_trace_internal_test.go b/coderd/x/chatd/turn_trace_internal_test.go index 38d565464da..4d41856b440 100644 --- a/coderd/x/chatd/turn_trace_internal_test.go +++ b/coderd/x/chatd/turn_trace_internal_test.go @@ -25,6 +25,7 @@ import ( "github.com/coder/coder/v2/coderd/x/chatd/chatloop" "github.com/coder/coder/v2/coderd/x/chatd/chatprompt" "github.com/coder/coder/v2/coderd/x/chatd/chatstate" + "github.com/coder/coder/v2/coderd/x/chatd/chattest" "github.com/coder/coder/v2/codersdk" "github.com/coder/coder/v2/testutil" "github.com/coder/quartz" @@ -35,11 +36,15 @@ func turnSpansByStart(t *testing.T, recorder *tracetest.SpanRecorder) []sdktrace return stageSpansByStart(t, recorder, chatloop.StageChatTurn) } +func spanStage(span sdktrace.ReadOnlySpan) chatloop.Stage { + return chatloop.Stage(chattest.SpanStage(span)) +} + func stageSpansByStart(t *testing.T, recorder *tracetest.SpanRecorder, stage chatloop.Stage) []sdktrace.ReadOnlySpan { t.Helper() var spans []sdktrace.ReadOnlySpan for _, span := range recorder.Ended() { - if chatloop.Stage(span.Name()) == stage { + if spanStage(span) == stage { spans = append(spans, span) } } @@ -63,7 +68,7 @@ func TestRunnerTurnSpanStartsAtTriggerMessage(t *testing.T) { require.Len(t, ended, 2) acquisition, chatTurn := ended[0], ended[1] require.Equal(t, string(chatloop.StageAcquisition), acquisition.Name()) - require.Equal(t, string(chatloop.StageChatTurn), chatTurn.Name()) + require.Equal(t, "invoke_agent coder", chatTurn.Name()) require.Equal(t, triggerAt.UTC(), chatTurn.StartTime().UTC()) require.Equal(t, triggerAt.UTC(), acquisition.StartTime().UTC()) require.False(t, acquisition.StartTime().Before(chatTurn.StartTime())) @@ -96,6 +101,20 @@ func TestRunnerTurnSpanCarriesChatIdentity(t *testing.T) { } } +func TestRunnerTurnSpanRecordsProvider(t *testing.T) { + t.Parallel() + tracer, recorder := newStageTestTracer(t) + turn := newRunnerTurnSpan(tracer, false) + + _, token := turn.Ensure(t.Context(), uuid.Nil, database.Chat{ID: uuid.New()}, time.Time{}) + turn.SetProvider(token, chatloop.StageModel{ProviderType: "anthropic", Bedrock: true}) + turn.End(nil) + + turns := turnSpansByStart(t, recorder) + require.Len(t, turns, 1) + require.Contains(t, turns[0].Attributes(), attribute.String("gen_ai.provider.name", "aws.bedrock")) +} + func TestRunnerTurnSpanEnsureReusesTurnForSameTrigger(t *testing.T) { t.Parallel() tracer, recorder := newStageTestTracer(t) diff --git a/docs/coder-agents/platform-controls/opentelemetry-tracing.md b/docs/coder-agents/platform-controls/opentelemetry-tracing.md new file mode 100644 index 00000000000..eaa9c7e01d2 --- /dev/null +++ b/docs/coder-agents/platform-controls/opentelemetry-tracing.md @@ -0,0 +1,99 @@ +--- +title: OpenTelemetry tracing +--- + +Coder Agents exports OpenTelemetry traces that follow the [OpenTelemetry GenAI semantic conventions](https://opentelemetry.io/docs/specs/semconv/gen-ai/). +Observability backends that understand these conventions can attribute model usage, token spend, and tool activity to each user without custom mapping. + +The GenAI conventions are still in development. +Coder Agents follows the span names and `gen_ai.*` attributes in semantic conventions v1.41.0, and they might change as the conventions stabilize. + +## Enable tracing + +Start the Coder server with [`--trace`](../../reference/cli/server/index.md#--trace) (`CODER_TRACE_ENABLE=true`). +Coder Agents spans are exported with the rest of the server's traces. + +The server exports traces with OTLP over gRPC. +Set the collector address with `OTEL_EXPORTER_OTLP_ENDPOINT` or `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT`, and add headers with `OTEL_EXPORTER_OTLP_HEADERS`. +`OTEL_EXPORTER_OTLP_PROTOCOL` has no effect, so OTLP over HTTP is not supported. + +The connection is unencrypted by default, even for an `https://` endpoint or with `OTEL_EXPORTER_OTLP_INSECURE=false`. +To use TLS, set `OTEL_EXPORTER_OTLP_CERTIFICATE` to the collector's CA certificate, and set `OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE` and `OTEL_EXPORTER_OTLP_CLIENT_KEY` for mutual TLS. + +## Spans + +Each chat turn is a separate trace. +The root span covers the turn, and the model calls and tool calls of the turn are its descendants, including advisor and compaction calls. +Model calls that run after a turn, such as title, status label, and chat summary generation, are traces of their own. +They carry the same chat and user attributes, so you can attribute their tokens to the same user. + +| Span name | `gen_ai.operation.name` | Covers | +|-----------------------------------|-------------------------|---------------------------------------------| +| `invoke_agent coder` | `invoke_agent` | One chat turn, from the prompt to the reply | +| `chat {gen_ai.request.model}` | `chat` | One model call, with span kind `CLIENT` | +| `execute_tool {gen_ai.tool.name}` | `execute_tool` | One tool call that Coder Agents runs | + +The turn also contains spans for other lifecycle stages, such as `generation_step`, `prepare`, `commit`, and `compaction`. +Every span carries a `stage` attribute with its lifecycle stage name, such as `chat_turn`, `stream`, or `tool_call`. +Model calls outside the assistant stream, such as compaction and title generation, have the stage `model_call`. +The `stage` attribute matches the `stage` label of the `coderd_chatd_stage_duration_seconds` Prometheus metric. + +## Attributes + +All three GenAI spans carry attributes that identify the chat and its owner: + +| Attribute | Value | +|--------------------------|-----------------------------------------------| +| `gen_ai.conversation.id` | The chat ID | +| `user.id` | The ID of the user who owns the chat | +| `coder.organization.id` | The ID of the chat's organization | +| `coder.workspace.id` | The ID of the chat's workspace, if it has one | +| `coder.chat.parent_id` | The ID of the parent chat, for subagent chats | +| `coder.chat.root_id` | The ID of the root chat, for subagent chats | + +The `invoke_agent coder` span also carries `gen_ai.agent.name` (`coder`) and, once the turn selects a model, `gen_ai.provider.name`. + +The `chat` span carries the model call's details: + +| Attribute | Value | +|--------------------------------------------|---------------------------------------------------------------| +| `gen_ai.provider.name` | The provider, such as `openai`, `anthropic`, or `aws.bedrock` | +| `gen_ai.request.model` | The model name | +| `gen_ai.request.max_tokens` | The output token limit Coder Agents requested, if one is set | +| `gen_ai.request.temperature` | The temperature Coder Agents requested, if one is set | +| `gen_ai.request.stream` | Whether the response was streamed | +| `gen_ai.response.id` | The response ID the provider reported, if any | +| `gen_ai.response.finish_reasons` | Why the model stopped, if the provider reported it | +| `gen_ai.usage.input_tokens` | Input tokens, including cache reads and cache writes | +| `gen_ai.usage.output_tokens` | Output tokens, including reasoning tokens | +| `gen_ai.usage.cache_read.input_tokens` | Input tokens read from the provider's prompt cache, if any | +| `gen_ai.usage.cache_creation.input_tokens` | Input tokens written to the provider's prompt cache, if any | +| `gen_ai.usage.reasoning.output_tokens` | Reasoning tokens, if the provider reports them | +| `gen_ai.output.type` | `json`, for structured output requested in OpenAI's JSON mode | + +The request attributes describe the limits Coder Agents asks for, not always the request sent to the provider. +For example, a model configuration can set an OpenAI-specific output token limit that replaces the general limit, and some providers ignore temperature for reasoning models. + +### Token usage limits + +Token counts come from the model client Coder Agents uses, which drops some of what the provider reports: + +- **Anthropic:** when a response runs server-side tools such as web search, the model works in several internal iterations. + Anthropic reports the input of all iterations, but the client keeps only the first iteration's input. + `gen_ai.usage.input_tokens` and the cache attributes therefore undercount the billed input. + Output tokens cover the whole response. +- **OpenAI-compatible providers, such as OpenRouter:** the client does not read the cache writes these providers report, so `gen_ai.usage.cache_creation.input_tokens` is absent. + The input token total still includes them. + +[AI Governance cost control](../../ai-governance/ai-gateway/cost-controls.md) has the same Anthropic gap, so its spend for those responses is also low. + +The `execute_tool` span carries `gen_ai.tool.name`, `gen_ai.tool.call.id`, and `gen_ai.tool.type`. +The tool type is `function` for built-in Coder Agents tools and `extension` for other tools, such as tools from MCP servers. + +On `chat` and `execute_tool` spans, the operation name, provider, model, and tool attributes are set when the span starts, so samplers can use them. +The `invoke_agent coder` span starts before the turn selects a model, so samplers see its operation name and chat attributes but not `gen_ai.provider.name`. +A failed span has an error status and an `error.type` attribute. +A tool call that returns an error result, such as an MCP server that cannot be reached, ends with `error.type` set to `tool_error`. + +The `gen_ai.*` attributes contain metadata only: prompts, model responses, and tool arguments and results are not recorded in them. +Other spans and span events in the same trace, such as AI Gateway spans and server log events, can contain parts of that content. diff --git a/docs/manifest.json b/docs/manifest.json index ceaed03fe28..3b3d4a57559 100644 --- a/docs/manifest.json +++ b/docs/manifest.json @@ -845,6 +845,11 @@ "title": "Chat debug logging", "description": "Record detailed traces of each Coder Agents chat turn to troubleshoot agent behavior.", "path": "./coder-agents/platform-controls/chat-debug-logging.md" + }, + { + "title": "OpenTelemetry tracing", + "description": "Export Coder Agents traces that follow the OpenTelemetry GenAI semantic conventions.", + "path": "./coder-agents/platform-controls/opentelemetry-tracing.md" } ] }, diff --git a/docs/manifest/coder-agents/platform-controls.yml b/docs/manifest/coder-agents/platform-controls.yml index 52716768525..d38ffc7290b 100644 --- a/docs/manifest/coder-agents/platform-controls.yml +++ b/docs/manifest/coder-agents/platform-controls.yml @@ -42,3 +42,6 @@ children: - title: Chat debug logging description: Record detailed traces of each Coder Agents chat turn to troubleshoot agent behavior. path: ./coder-agents/platform-controls/chat-debug-logging.md + - title: OpenTelemetry tracing + description: Export Coder Agents traces that follow the OpenTelemetry GenAI semantic conventions. + path: ./coder-agents/platform-controls/opentelemetry-tracing.md