Repository navigation
fix(go/openai): record finish reasons on streams that end with a usage chunk - #1986
Conversation
Reviewer's GuideImplementationCollect non-empty finish reasons by choice index while reading chunks, then emit them in index order at stream completion so a final usage-only chunk does not discard them.
TestsAdd span-recorder helpers and streaming tests covering finish reasons before a usage-only chunk, including multiple choices that finish out of index order.
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
PR Summary by QodoRecord finish reasons when OpenAI streams end with a usage chunk
AI Description
Merge Risk
|
Code Review by Qodo🐞 Bugs (0) 📘 Rule violations (0) 📎 Requirement gaps (0)
Great, no issues found!Qodo reviewed your code and found no material issues that require reviewTip of the day💡 Did you know, you can route each severity your way: inline, summary, both, or drop |
Linked issuesChecked at commit f9b15c7 #1983 Bug: Go SDK OpenAI streaming drops gen_ai.response.finish_reasons · 1 of 1 met
|
There was a problem hiding this comment.
Hey - I've found 3 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="sdk/go/instrumentation/openai/streaming.go" line_range="156" />
<code_context>
+ for _, choice := range chunk.Choices {
+ if choice.FinishReason != "" {
+ finishReasonByIndex[choice.Index] = choice.FinishReason
+ }
+ }
</code_context>
<issue_to_address>
**Untrusted streams exhaust memory**
When a malicious or compromised OpenAI-compatible endpoint sends an unbounded stream of chunks with nonempty finish reasons and distinct choice indices, `readStream` retains each distinct response choice index in `finishReasonByIndex` until the stream ends, so the process runs out of memory before completion.
Bound the number of choice indices collected (for example, against the requested choice count) before adding entries.
</issue_to_address>
### Comment 2
<location path="sdk/go/instrumentation/openai/streaming.go" line_range="156" />
<code_context>
+ for _, choice := range chunk.Choices {
+ if choice.FinishReason != "" {
+ finishReasonByIndex[choice.Index] = choice.FinishReason
+ }
+ }
</code_context>
<issue_to_address>
**Aborted streams lose finish reasons**
When a stream is canceled or encounters a parse/read error after a choice has emitted its finish reason, `readStream` returns before the normal-end block writes `finishReasonByIndex` to the span, so finish reasons already received are omitted.
Write the collected finish reasons to the span on every exit path after they have been received.
Also at `sdk/go/instrumentation/openai/streaming.go:212-223`.
</issue_to_address>
### Comment 3
<location path="sdk/go/instrumentation/openai/openai_test.go" line_range="678" />
<code_context>
+ otel.SetTracerProvider(tp)
+ t.Cleanup(func() {
+ _ = tp.Shutdown(context.Background())
+ otel.SetTracerProvider(sdktrace.NewTracerProvider())
+ })
+ return sr
</code_context>
<issue_to_address>
**Second test cannot record spans**
When both new tests run in the same package test process, the cleanup shuts down the first test's provider, then attempts to install a fresh global provider. OpenTelemetry does not replace an already-installed global provider, so the second test's recorder is never used and `waitForEndedSpan` fails.
Use a provider setup that can be reset between tests, or share one recorder/provider across both tests.
</issue_to_address>Sourcery assessment
Needs a human reviewer. 3 findings to address first, and if the accumulation or ordering is wrong, exported spans may contain incorrect finish-reason labels; reverting stops future spans from being affected, but cannot retract telemetry already collected. This does not change completion behavior or persist application data.
Blocking findings: sdk/go/instrumentation/openai/streaming.go:156, sdk/go/instrumentation/openai/streaming.go:156, sdk/go/instrumentation/openai/openai_test.go:678
|
|
||
| for _, choice := range chunk.Choices { | ||
| if choice.FinishReason != "" { | ||
| finishReasonByIndex[choice.Index] = choice.FinishReason |
There was a problem hiding this comment.
🟡 Medium · Untrusted streams exhaust memory
When a malicious or compromised OpenAI-compatible endpoint sends an unbounded stream of chunks with nonempty finish reasons and distinct choice indices, readStream retains each distinct response choice index in finishReasonByIndex until the stream ends, so the process runs out of memory before completion.
Bound the number of choice indices collected (for example, against the requested choice count) before adding entries.
Prompt for AI agents
In `sdk/go/instrumentation/openai/streaming.go` at line 156:
**Untrusted streams exhaust memory**
When a malicious or compromised OpenAI-compatible endpoint sends an unbounded stream of chunks with nonempty finish reasons and distinct choice indices, `readStream` retains each distinct response choice index in `finishReasonByIndex` until the stream ends, so the process runs out of memory before completion.
Bound the number of choice indices collected (for example, against the requested choice count) before adding entries.|
|
||
| for _, choice := range chunk.Choices { | ||
| if choice.FinishReason != "" { | ||
| finishReasonByIndex[choice.Index] = choice.FinishReason |
There was a problem hiding this comment.
🟡 Medium · Aborted streams lose finish reasons
When a stream is canceled or encounters a parse/read error after a choice has emitted its finish reason, readStream returns before the normal-end block writes finishReasonByIndex to the span, so finish reasons already received are omitted.
Write the collected finish reasons to the span on every exit path after they have been received.
Also at sdk/go/instrumentation/openai/streaming.go:212-223.
Prompt for AI agents
In `sdk/go/instrumentation/openai/streaming.go` at line 156:
**Aborted streams lose finish reasons**
When a stream is canceled or encounters a parse/read error after a choice has emitted its finish reason, `readStream` returns before the normal-end block writes `finishReasonByIndex` to the span, so finish reasons already received are omitted.
Write the collected finish reasons to the span on every exit path after they have been received.
Also at `sdk/go/instrumentation/openai/streaming.go:212-223`.| otel.SetTracerProvider(tp) | ||
| t.Cleanup(func() { | ||
| _ = tp.Shutdown(context.Background()) | ||
| otel.SetTracerProvider(sdktrace.NewTracerProvider()) |
There was a problem hiding this comment.
🔴 Critical · Second test cannot record spans
When both new tests run in the same package test process, the cleanup shuts down the first test's provider, then attempts to install a fresh global provider. OpenTelemetry does not replace an already-installed global provider, so the second test's recorder is never used and waitForEndedSpan fails.
Use a provider setup that can be reset between tests, or share one recorder/provider across both tests.
Prompt for AI agents
In `sdk/go/instrumentation/openai/openai_test.go` at line 678:
**Second test cannot record spans**
When both new tests run in the same package test process, the cleanup shuts down the first test's provider, then attempts to install a fresh global provider. OpenTelemetry does not replace an already-installed global provider, so the second test's recorder is never used and `waitForEndedSpan` fails.
Use a provider setup that can be reset between tests, or share one recorder/provider across both tests.
Merged PR summary
Generated from the merged PR description and bounded, component-scoped file evidence. Release preparation reuses this validated summary. |
Issue number: Fixes #1983
Change description:
The OpenAI streaming client in the Go SDK forces
stream_options.include_usage = true. With that option the API sends a final chunk that carriesusageand an emptychoicesarray.readStreamkept only the last chunk and read the finish reasons from its choices, sogen_ai.response.finish_reasonswas never set on a streaming span.The fix collects the finish reason of every choice as the chunks arrive, keyed by choice index, and sets the attribute once at the end, in index order. A choice that never receives a finish reason (a cut stream) is left out; if none does, the attribute is absent, as before. This matches how the non-streaming path already lists every choice.
lastChunkis still used for usage.For one choice the result is the same as Python's (
["stop"]). Forn > 1Python records one value (whichever arrived last atchoices[0]), while Go now records every choice. I kept the non-streaming behaviour rather than copy that.How was this tested
The existing
TestChatCompletion_Streamingputsfinish_reasonandusagein the same chunk, which the API does not do, so it could not catch this. Two new tests inopenai_test.gouse the real shape.Red on the unmodified
streaming.go, on the missing attribute:Both pass with the fix, as do
go vet ./...andgo test ./...insdk/go. The multi-choice test uses four choices that finish out of index order, so removing the sort fails it on every run (40 of 40 runs).Not covered: keeping the first finish reason seen for a choice instead of the latest is not tested, since the API sends one per choice.
-racecould not run on the machine I used (the race detector rejects its address-space size).gofmt -llists four files (helpers/config.go,helpers/pricing.go,anthropic/types.go,openai/types.go) that are already unformatted onmain. This PR does not touch them.Related PRs of mine for the Go SDK (#1982, #1984, #1985) touch the same test files and add similar span-recorder helpers, so whichever merges second will need a small rebase. I will do that.
Checklist
If your change doesn't seem to apply, please leave them unchecked.
Acknowledgment
By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of the project license.
Summary by Sourcery
Fix Go OpenAI streaming spans so finish-reason attributes remain available when usage is delivered in a separate final chunk.
Bug Fixes:
Tests: