Skip to content

fix(go-sdk): record the error on a failed stream before ending its span - #1989

Open
basil-k-aji-dev wants to merge 1 commit into
openlit:mainfrom
basil-k-aji-dev:fix/go-stream-error-order
Open

basil-k-aji-dev wants to merge 1 commit into
openlit:mainfrom
basil-k-aji-dev:fix/go-stream-error-order

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 #1982

Change description:

When a streaming request fails before any chunk is read, the OpenAI and Anthropic Go clients ended the span first and recorded the error afterwards:

span.End()
helpers.RecordError(span, err)

The OpenTelemetry SDK ignores RecordError and SetStatus on an ended span, so the span of a failed streaming call finished with status Unset and no exception event. I checked that on its own with a small standalone program against the SDK (end-then-record gives status=Unset events=0, record-then-end gives status=Error events=1), so it is not an artefact of the tests. The vllm client in the same SDK already uses the right order.

This swaps the two calls on all eight failure paths (marshal error, request creation error, transport error and non-200 response, in openai/streaming.go and anthropic/streaming.go). Error text, returns and the body close are unchanged; on the non-200 path the order is now read body, close, build the error, record, end.

Left out on purpose:

  • Recording gen_ai.client.operation.duration with error.type when a stream fails to start. The streaming setup functions have no meter, start time or named-return failure block, so that would be new plumbing rather than a reorder. I narrowed the issue to the span status and exception event.
  • Mid-stream error payloads. Anthropic sends event: error and the stream switch only handles the message and delta events; an OpenAI {"error": ...} data chunk decodes without error. In both cases the span ends Ok. That is a separate change.

How was this tested

New subtests in the existing TestChatCompletion_Streaming_Error_SpanStatus (openai) and TestCreateMessage_Streaming_Error_SpanStatus (anthropic), one per failure path: non-200 (401), transport error (closed server), marshal error (Temperature: math.NaN(), which json.Marshal rejects) and request creation error (a base URL with a control character). Each asserts span status Error and an exception event.

Red on the unmodified streaming.go:

want span status Error, got Unset
want an exception event on the span, got 0 events

All pass with the change. I also swapped the order back at each of the eight sites on its own, and each swap fails a test (8 of 8 caught). go vet ./... and go test ./... pass in sdk/go. -race could not run on the machine I used.

gofmt -l lists four files already unformatted on main (helpers/config.go, helpers/pricing.go, anthropic/types.go, openai/types.go); this PR does not touch them.

My other Go SDK PRs (#1986, #1987, #1988) touch the same test files and add similar span-recorder helpers (setupSpanRecorder is declared identically in three of them), so whichever merges second needs a small rebase, and a duplicate helper has to be dropped. 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

Record streaming request failures before ending OpenTelemetry spans in the OpenAI and Anthropic Go clients.

Bug Fixes:

  • Ensure failed OpenAI and Anthropic streaming requests record span errors before ending their OpenTelemetry spans, preserving Error status and exception events.

Tests:

  • Add coverage for span status and exception recording across streaming setup failures, including non-200 responses, transport errors, request marshaling errors, and invalid URLs.

@sourcery-ai

sourcery-ai Bot commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Reviewer's Guide

Implementation

Record errors before ending the stream span on each setup failure path so the ended span retains its error status and exception event.

  • sdk/go/instrumentation/anthropic/streaming.go L37-65 (5 small edits)
  • sdk/go/instrumentation/openai/streaming.go L40-67 (5 small edits)

Tests

Add failure-path tests for both streaming clients that verify failed spans end with Error status and an exception event.

  • sdk/go/instrumentation/anthropic/anthropic_test.go L8, L18, L527-625
  • sdk/go/instrumentation/openai/openai_test.go L8, L15-18, L516-622

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

fix(go-sdk): record streaming setup errors before ending spans

🐞 Bug fix 🧪 Tests 🕐 10-20 Minutes

Grey Divider

AI Description

• Record OpenAI and Anthropic stream-start failures before ending their spans, preserving error
 status and exception events.
• Add regression tests for marshal, request creation, transport, and non-200 response failures in
 both clients.
Merge Risk 🟢 Low

Blast radius 🟢 Low 💥 0 capabilities

  • Fault-specific containment limits risk to the originating changed behavior.
Behavioral complexity 🟢 Low 🧩 Straightforward

  • Before, each existing error branch ended the span before calling the established RecordError helper, so the helper's status and exception recording could be lost.
  • After, the same helper is called first and the span is then ended.
  • The new correctness condition is the ordering rule that error recording must precede span termination; there are no new states, branches, algorithms, concurrency protocols, or coordinated writes.
Potential damage 🟢 Low 🩹 Cosmetic

  • Conservative damage bound for the originating changed behavior; downstream capabilities remain contained.
  • The affected capability is diagnostic telemetry.
  • A missing or incorrect error status/event reduces observability but does not alter the Anthropic response, caller error handling, persistent state, or external provider effect.
  • Reverting code restores the prior instrumentation behavior; already-emitted spans cannot be repaired, but future spans are corrected immediately.
  • Reversible for future telemetry by code rollback or redeployment; historical spans missing the event/status cannot be retroactively repaired.
  • No persistent-state repair or external compensation is required.
Assessed commit b6a3f4a
Diagram

sequenceDiagram
    actor Caller
    participant Client as Streaming client
    participant API as HTTP API
    participant Helper as RecordError
    participant Span as OTel span
    Caller->>Client: Start stream
    Client->>Span: Start
    alt Setup failure
        Client->>Client: Build error
    else Transport or non-200 failure
        Client->>API: Send request
        API-->>Client: Failure
        Client->>Client: Close body if present
    end
    Client->>Helper: Record error
    Helper->>Span: Exception and Error status
    Client->>Span: End
    Client-->>Caller: Return error
Loading
High-Level Assessment

The local reorder is the best fit for this scoped fix: it corrects all eight failure paths without changing error returns or stream ownership. A broader span-finalization abstraction would add plumbing for a problem resolved by recording the error before End.

Files changed (4) +221 / -8

Bug fix (2) +8 / -8
streaming.goRecord Anthropic stream errors before ending spans +4/-4

Record Anthropic stream errors before ending spans

• Reorders error recording and span termination for marshal, request creation, transport, and non-200 response failures. Existing error returns and response-body closure remain unchanged.

sdk/go/instrumentation/anthropic/streaming.go

streaming.goRecord OpenAI stream errors before ending spans +4/-4

Record OpenAI stream errors before ending spans

• Reorders error recording and span termination for marshal, request creation, transport, and non-200 response failures. Existing error returns and response-body closure remain unchanged.

sdk/go/instrumentation/openai/streaming.go

Tests (2) +213 / -0
anthropic_test.goTest Anthropic stream-start failure spans +101/-0

Test Anthropic stream-start failure spans

• Adds four failure-path subtests and an assertion that each call ends one span with Error status and an exception event.

sdk/go/instrumentation/anthropic/anthropic_test.go

openai_test.goTest OpenAI stream-start failure spans +112/-0

Test OpenAI stream-start failure spans

• Adds a span recorder and four failure-path subtests. Each verifies that the ended span has Error status and an exception event.

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 b6a3f4a

#1982 Bug: Go SDK OpenAI and Anthropic streaming failures end the span before recording the error · 1 of 1 met

# Requirement Status Notes
1 Record errors before ending spans for marshal, request-creation, transport, and non-200 failures in both OpenAI and Anthropic streaming clients, so failed spans have Error status and an exception event. ✅ Met Both streaming setup functions now call helpers.RecordError before span.End() on all four failure paths, and the new tests check the status and exception event.

@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 reviewed your changes and they look great!

Sourcery assessment

Approved.


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

This branch was previously deployed

1 inactive deployment
release-notes — b6a3f4a2 Deployed Nov 22, 2026 by basil-k-aji-dev via Normalize / Conventional title #881
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 and Anthropic streaming failures end the span before recording the error

1 participant