Skip to content

fix(python-sdk): end gradient streaming spans on close, drop, or error - #1807

Open
feiiiiii5 wants to merge 4 commits into
openlit:mainfrom
feiiiiii5:fix/gradient-stream-lifecycle
Open

feiiiiii5 wants to merge 4 commits into
openlit:mainfrom
feiiiiii5:fix/gradient-stream-lifecycle

Conversation

@feiiiiii5

@feiiiiii5 feiiiiii5 commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Issue number: #1806

Change description:

Gradient chat streams now end their span once on exhaustion, context-manager exit, explicit close() / await close(), release after a bare loop break, or a mid-stream failure. Previously only StopIteration / StopAsyncIteration finalized the span; close() fell through __getattr__ to the wrapped stream, and a failure left the span open.

  • Sync and async wrappers gain close() (the async one awaits aclose() or close()), __del__, and an idempotent _finalize(ended_cleanly=...).
  • A stream cut short gets finish reason incomplete; a failure gets error plus handle_exception (span status ERROR, error.type), recorded after the accumulated partial output is written.
  • The shared finalizer no longer writes OK when the scope carries a stream error, because the OTel SDK ignores a later status change once OK is set. Full consumption is unchanged.

Validation: 13 lifecycle tests pass on Python 3.12.8 with a real OpenTelemetry in-memory exporter. On the previous PR head, 8 fail: immediate read failure, cleanup/context-exit failure, and concurrent close/read cases. Event barriers make the concurrency cases deterministic. Changed-file Pylint passes at 10.00/10; Poetry check/build pass. Full-SDK Pylint was also run and reports the existing E1102 findings in tests/test_groq.py:21 and tests/test_together.py:19. No live gradient call was made.

Review follow-up: context exit and close record cleanup errors and finalize in finally; stream read failures export before close; finalization waits for in-flight reads so concurrent close cannot hide their error. The original exception is re-raised and a retained wrapper exports once.

Checklist

  • 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 (local regressions above)
  • Changes are documented (method docstrings)

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

Finalize Gradient sync and async streaming spans reliably across all termination paths while preserving partial output and accurate error reporting.

Bug Fixes:

  • Ensure synchronous and asynchronous Gradient streaming spans finalize exactly once when streams are exhausted, closed, abandoned, cancelled, or fail during reading or cleanup.
  • Record incomplete streams with an incomplete finish reason and preserve partial output, while recording stream failures with error status and exception metadata.

Enhancements:

  • Make stream finalization safe for concurrent reads and close operations, ensuring in-flight errors are captured before spans are exported.
  • Avoid overwriting error status with OK during shared chat finalization.

Tests:

  • Add lifecycle coverage for normal completion, early exit, explicit close, context-manager failures, entry failures, cancellation, stream errors, and concurrent close/read behavior.

@sourcery-ai

sourcery-ai Bot commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Reviewer's Guide

Gradient streaming wrappers now reliably end spans exactly once on exhaustion, early release, cleanup, cancellation, and failures, with accurate incomplete/error metadata and deterministic synchronization for concurrent reads and close operations.

Sequence diagram for Gradient stream span finalization

sequenceDiagram
    participant Caller
    participant StreamWrapper
    participant GradientStream
    participant Span

    Caller->>StreamWrapper: __next__() / __anext__()
    StreamWrapper->>GradientStream: read next chunk
    GradientStream-->>StreamWrapper: chunk
    StreamWrapper-->>Caller: chunk

    alt stream exhaustion
        GradientStream-->>StreamWrapper: StopIteration / StopAsyncIteration
        StreamWrapper->>StreamWrapper: _finalize(ended_cleanly=True)
        StreamWrapper->>Span: final_processor()
        StreamWrapper->>Span: end span with stop reason
    else early close, release, or cancellation
        Caller->>StreamWrapper: close() / __del__()
        StreamWrapper->>GradientStream: close() / aclose()
        StreamWrapper->>StreamWrapper: _finalize(ended_cleanly=False)
        StreamWrapper->>Span: final_processor()
        StreamWrapper->>Span: end span with incomplete reason
    else read or cleanup failure
        GradientStream-->>StreamWrapper: exception
        StreamWrapper->>StreamWrapper: _finalize(ended_cleanly=False)
        StreamWrapper->>Span: final_processor() with partial output
        StreamWrapper->>Span: handle_exception()
        StreamWrapper->>Span: end span with error status
    end
Loading

State diagram for Gradient stream lifecycle

stateDiagram-v2
    [*] --> Active
    Active --> Active: __next__() / __anext__()
    Active --> Finalizing: StopIteration / StopAsyncIteration
    Active --> Finalizing: close() / aclose()
    Active --> Finalizing: __exit__() / __aexit__()
    Active --> Finalizing: __del__()
    Active --> Finalizing: GeneratorExit / CancelledError
    Active --> Error: read exception
    Error --> Finalizing: _finalize(ended_cleanly=False)
    Finalizing --> Finalizing: wait for active reads
    Finalizing --> Completed: final_processor()
    Completed --> [*]
Loading

File-Level Changes

Change Details Files
Made synchronous and asynchronous Gradient stream wrappers finalize tracing spans across all lifecycle termination paths.
  • Added explicit close methods, destructor cleanup, and context-manager finalization.
  • Tracked active reads and deferred finalization to coordinate concurrent close/read operations.
  • Made finalization idempotent while distinguishing clean completion from incomplete termination.
sdk/python/src/openlit/instrumentation/gradient/gradient.py
sdk/python/src/openlit/instrumentation/gradient/async_gradient.py
Recorded incomplete streams and failures with correct span metadata while preserving successful stream behavior.
  • Marked early termination as incomplete and read or cleanup failures as error.
  • Preserved accumulated partial output and recorded exception metadata after final processing.
  • Avoided overwriting failed spans with OK status in shared chat finalization.
sdk/python/src/openlit/instrumentation/gradient/gradient.py
sdk/python/src/openlit/instrumentation/gradient/async_gradient.py
sdk/python/src/openlit/instrumentation/gradient/utils.py
Added lifecycle and concurrency regression coverage for sync and async Gradient streams.
  • Covered normal exhaustion, explicit cleanup, context exit, garbage collection, cancellation, and failure paths.
  • Verified cleanup waits for in-flight reads, exports exactly once, and retains partial output and error status.
sdk/python/tests/test_gradient_stream_span_lifecycle.py

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

@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 2 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="sdk/python/src/openlit/instrumentation/gradient/gradient.py" line_range="121" />
<code_context>
             if hasattr(self.__wrapped__, "__aexit__"):
                 await self.__wrapped__.__aexit__(exc_type, exc_value, traceback)
-            self._finalize()
+            self._finalize(ended_cleanly=False)

         def __aiter__(self):
</code_context>
<issue_to_address>
**Context exit leaves spans open**

When the wrapped stream's `__exit__` or `__aexit__` raises, the wrapped context-manager exit runs before `_finalize` and is not protected by `finally`, so its exception skips finalization and leaves the span open and unexported; the cleanup failure is also absent from the span.

Record any cleanup exception, finalize in a `finally` block, and re-raise the exception.

Also at `sdk/python/src/openlit/instrumentation/gradient/async_gradient.py:81`, `sdk/python/src/openlit/instrumentation/gradient/async_gradient.py:84`, `sdk/python/src/openlit/instrumentation/gradient/gradient.py:129`.
</issue_to_address>

### Comment 2
<location path="sdk/python/src/openlit/instrumentation/gradient/gradient.py" line_range="180" />
<code_context>
+                self._finish_reason = "error"
+                self._gen_ai_error = self._stream_error
+            elif not ended_cleanly:
+                self._finish_reason = "incomplete"
             try:
                 with trace_api.use_span(  # pylint: disable=not-context-manager
</code_context>
<issue_to_address>
**Concurrent close hides read errors**

When a caller closes a stream while another thread or task is reading it, a concurrent `close()` can set `_finalized` and export an incomplete span while `__next__` or `__anext__` is still running; if that read then raises, it stores `_stream_error` after finalization, and the guard prevents recording the error or correcting the finish reason.

Coordinate close with in-flight reads so any read error is incorporated before the span is finalized.

Also at `sdk/python/src/openlit/instrumentation/gradient/async_gradient.py:136`.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 2 findings to address first, and closing, abandoning, or failing a stream now finalizes its span and can export the partial generated output and error details to the configured telemetry backend. Those exported records survive a revert, though the exposure is limited to affected streams and can be bounded through backend retention or deletion.

Blocking findings: sdk/python/src/openlit/instrumentation/gradient/gradient.py:121, sdk/python/src/openlit/instrumentation/gradient/gradient.py:180


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

sourcery-ai[bot]
sourcery-ai Bot previously approved these changes Oct 30, 2026

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

Sourcery assessment

Approved.

CancelledError (and GeneratorExit) is a BaseException, so the async stream wrapper skipped the finalization path and the span was never exported. Finalize it as incomplete exactly once and re-raise; add a cancellation regression that asserts one exported span before the wrapper is released.
@sourcery-ai

sourcery-ai Bot commented Nov 3, 2026

Copy link
Copy Markdown
Contributor

Warning

Sourcery was unable to dismiss its earlier approval of this pull request, because the latest commits introduced blocking findings. The approval above no longer reflects the current commits.

How to resolve this

Add the Sourcery app under Restrict who can dismiss pull request reviews in this repository's branch protection rules. Sourcery only ever dismisses its own reviews. It does not dismiss reviews from anyone else.

@feiiiiii5

Copy link
Copy Markdown
Contributor Author

@sourcery-ai review

@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 1 issue

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="sdk/python/src/openlit/instrumentation/gradient/gradient.py" line_range="132" />
<code_context>
+                self._stream_error = exc
+                raise
+            finally:
+                self._finalize(ended_cleanly=False)

         def __aiter__(self):
</code_context>
<issue_to_address>
**Failed context entry leaves span open**

When the wrapped stream’s context-manager entry raises and the caller retains the traced wrapper, the wrapped stream’s `__enter__` or `__aenter__` raises before an exit hook can run, so these finalizers are skipped. A retained wrapper leaves its span open; if it is later dropped, `__del__` records only an incomplete stream, not the entry error, and the caller sees missing error telemetry.

Catch entry failures, record them as stream errors, finalize the span, and re-raise the original exception.

Also at `sdk/python/src/openlit/instrumentation/gradient/async_gradient.py:98`.
</issue_to_address>

Sourcery assessment

Approval pending. 1 finding to address first.

Blocking findings: sdk/python/src/openlit/instrumentation/gradient/gradient.py:132


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

A retained wrapper whose __enter__/__aenter__ raised skipped the finalizers entirely, because a failed entry never reaches __exit__/__aexit__. Record the entry error, finalize once, and re-raise for both the sync and async wrappers; add entry-failure regressions.

This branch was previously deployed

1 inactive (outdated) deployment
release-notes — 985b62b0 Deployed Oct 20, 2026 by feiiiiii5 via Normalize / Conventional title #616
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant