Skip to content

fix(go/openai): record finish reasons on streams that end with a usage chunk - #1986

Merged
AmanAgarwal041 merged 1 commit into
openlit:mainfrom
basil-k-aji-dev:fix/go-openai-stream-finish-reasons
Nov 28, 2026
Merged

AmanAgarwal041 merged 1 commit into
openlit:mainfrom
basil-k-aji-dev:fix/go-openai-stream-finish-reasons

Conversation

@basil-k-aji-dev

@basil-k-aji-dev basil-k-aji-dev commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

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 carries usage and an empty choices array. readStream kept only the last chunk and read the finish reasons from its choices, so gen_ai.response.finish_reasons was 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. lastChunk is still used for usage.

For one choice the result is the same as Python's (["stop"]). For n > 1 Python records one value (whichever arrived last at choices[0]), while Go now records every choice. I kept the non-streaming behaviour rather than copy that.

How was this tested

The existing TestChatCompletion_Streaming puts finish_reason and usage in the same chunk, which the API does not do, so it could not catch this. Two new tests in openai_test.go use the real shape.

Red on the unmodified streaming.go, on the missing attribute:

--- FAIL: TestChatCompletion_Streaming_FinishReasonBeforeUsageChunk
    openai_test.go:752: missing gen_ai.response.finish_reasons attribute
--- FAIL: TestChatCompletion_Streaming_FinishReasonsMultipleChoices
    openai_test.go:783: missing gen_ai.response.finish_reasons attribute

Both pass with the fix, as do go vet ./... and go test ./... in sdk/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. -race could not run on the machine I used (the race detector rejects its address-space size).

gofmt -l lists four files (helpers/config.go, helpers/pricing.go, anthropic/types.go, openai/types.go) that are already unformatted on main. 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.

  • PR title follows Conventional Commit format.
  • I have reviewed the contributing guidelines
  • Have you checked to ensure there aren't other open Pull Requests for the same update/change?
  • I have performed a self-review of this change
  • Changes have been tested
  • Changes are documented

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:

  • Record streaming response finish reasons even when OpenAI sends a final usage-only chunk.
  • Preserve finish reasons for all completed choices in index order while omitting unfinished choices.

Tests:

  • Add streaming instrumentation tests covering usage-only terminal chunks, multiple choices, finish-reason ordering, and usage attributes.

@sourcery-ai

sourcery-ai Bot commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Reviewer's Guide

Implementation

Collect 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.

  • sdk/go/instrumentation/openai/streaming.go L154-159, L212-222 (+2 small edits)

Tests

Add span-recorder helpers and streaming tests covering finish reasons before a usage-only chunk, including multiple choices that finish out of index order.

  • sdk/go/instrumentation/openai/openai_test.go L12-18, L670-793

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Nov 22, 2026 •

Copy link
Copy Markdown

PR Summary by Qodo

Record finish reasons when OpenAI streams end with a usage chunk

🐞 Bug fix 🧪 Tests 🕐 10-20 Minutes

Grey Divider

AI Description

• Preserve streaming finish reasons when the final usage chunk has no choices.
• Record multiple choices in index order, with regression tests for both stream shapes.
Merge Risk 🟡 Medium

Blast radius 🟢 Low 💥 0 capabilities

  • Fault-specific containment limits risk to the originating changed behavior.
Behavioral complexity 🟡 Medium 🧩 Interacting branches

  • Before: the implementation inspected only the final chunk's choices when constructing finish reasons.
  • After: it accumulates non-empty finish reasons across multiple chunks, keys them by choice index, then sorts indexes before emitting the span attribute.
  • New correctness condition: terminal finish-reason observations arriving in separate chunks must be retained without collision and deterministically mapped back to the correct choice.
  • The added state and ordering interaction is limited to telemetry aggregation; it does not introduce a new application concurrency protocol or persistent-state invariant.
Sources

sdk/go/instrumentation/openai/streaming.go[212-223]

		if len(finishReasonByIndex) > 0 {
			indexes := make([]int, 0, len(finishReasonByIndex))
			for idx := range finishReasonByIndex {
				indexes = append(indexes, idx)
			}
			sort.Ints(indexes)
			finishReasons := make([]string, 0, len(indexes))
			for _, idx := range indexes {
				finishReasons = append(finishReasons, finishReasonByIndex[idx])
			}
			semconv.SetStringSliceAttribute(span, semconv.GenAIResponseFinishReasons, finishReasons)
		}
Potential damage 🟡 Medium 🩹 Recoverable

  • Conservative damage bound for the originating changed behavior; downstream capabilities remain contained.
  • The affected capability is observability of OpenAI streaming completions.
  • A wrong finish-reason attribute can mislead dashboards, traces, or telemetry-based analysis, but does not alter the streamed completion, persistent application state, or an external business action.
  • Reverting the SDK restores future telemetry; already exported incorrect spans cannot generally be rewritten, so historical telemetry may require deletion or annotation if that is supported by the telemetry backend.
  • Recoverable by deploying a corrected SDK or reverting the change for future requests.
  • Previously exported spans remain inaccurate unless the telemetry backend supports cleanup or correction; no automatic repair path is established.
Sources

sdk/go/instrumentation/openai/streaming.go[212-223]

		if len(finishReasonByIndex) > 0 {
			indexes := make([]int, 0, len(finishReasonByIndex))
			for idx := range finishReasonByIndex {
				indexes = append(indexes, idx)
			}
			sort.Ints(indexes)
			finishReasons := make([]string, 0, len(indexes))
			for _, idx := range indexes {
				finishReasons = append(finishReasons, finishReasonByIndex[idx])
			}
			semconv.SetStringSliceAttribute(span, semconv.GenAIResponseFinishReasons, finishReasons)
		}
Assessed commit f9b15c7
Diagram

graph TD
  A["OpenAI SSE"] --> B["readStream"] --> C["Finish reasons"] --> E["Span attributes"]
  B --> D["Last usage chunk"] --> E
Loading
High-Level Assessment

Collecting reasons by choice index is appropriate because the usage-only final chunk cannot supply them, and stream arrival order need not match choice order. Retaining the last chunk separately preserves existing usage handling.

Files changed (2) +146 / -8

Bug fix (1) +17 / -8
streaming.goCollect streaming finish reasons across chunks +17/-8

Collect streaming finish reasons across chunks

• Stores non-empty finish reasons by choice index as chunks arrive, then writes them to the span in index order. The last chunk remains the source of usage data, and the finish-reasons attribute remains absent when no reason is received.

sdk/go/instrumentation/openai/streaming.go

Tests (1) +129 / -0
openai_test.goTest finish reasons before final usage chunks +129/-0

Test finish reasons before final usage chunks

• Adds a span recorder and streaming test helper. Two tests verify finish reasons with a usage-only final chunk, including four choices that finish out of index order, while checking usage attributes remain present.

sdk/go/instrumentation/openai/openai_test.go

@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (0) 📘 Rule violations (0) 📎 Requirement gaps (0)

Grey Divider

Great, no issues found!

Qodo reviewed your code and found no material issues that require review

Grey Divider

Tip of the day
💡 Did you know, you can route each severity your way: inline, summary, both, or drop

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

@sourcery-ai

sourcery-ai Bot commented Nov 22, 2026

Copy link
Copy Markdown
Contributor

Linked issues

Checked at commit f9b15c7

#1983 Bug: Go SDK OpenAI streaming drops gen_ai.response.finish_reasons · 1 of 1 met

# Requirement Status Notes
1 Record the streaming finish reason, such as stop, alongside usage attributes when usage arrives in a final chunk with empty choices. ✅ Met readStream collects finish reasons as chunks arrive and sets the attribute after processing the final chunk; the new test verifies both finish reasons and usage attributes.

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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


Sourcery is free for open source - if you like our reviews please consider sharing them ✨


for _, choice := range chunk.Choices {
if choice.FinishReason != "" {
finishReasonByIndex[choice.Index] = choice.FinishReason

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 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())

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔴 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.

@AmanAgarwal041
AmanAgarwal041 merged commit 2c48318 into openlit:main Nov 28, 2026
13 checks passed
@github-actions

Copy link
Copy Markdown

Merged PR summary

  • Go SDK · Fixes — Fix Go SDK OpenAI streaming spans to record finish reasons for all completed choices when usage arrives in a separate final chunk.

Generated from the merged PR description and bounded, component-scoped file evidence. Release preparation reuses this validated summary.

This branch was successfully deployed

1 active deployment
release-notes — f9b15c7f Deployed Nov 28, 2026 by AmanAgarwal041 via Summarize / Merged pull request #338
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bug: Go SDK OpenAI streaming drops gen_ai.response.finish_reasons

2 participants