Repository navigation
Conversation
Reviewer's GuideGradient 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 finalizationsequenceDiagram
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
State diagram for Gradient stream lifecyclestateDiagram-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 --> [*]
File-Level Changes
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
There was a problem hiding this comment.
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
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.
|
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 thisAdd 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. |
|
@sourcery-ai review |
There was a problem hiding this comment.
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
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.
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 onlyStopIteration/StopAsyncIterationfinalized the span;close()fell through__getattr__to the wrapped stream, and a failure left the span open.close()(the async one awaitsaclose()orclose()),__del__, and an idempotent_finalize(ended_cleanly=...).incomplete; a failure getserrorplushandle_exception(span status ERROR,error.type), recorded after the accumulated partial output is written.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
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:
Enhancements:
Tests: