Skip to content

fix(grpc): support generator responses in streaming client wrapper - #20780

Open
caiotheodoro wants to merge 8 commits into
DataDog:mainfrom
caiotheodoro:fix/grpc-generator-response
Open

caiotheodoro wants to merge 8 commits into
DataDog:mainfrom
caiotheodoro:fix/grpc-generator-response

Conversation

@caiotheodoro

Copy link
Copy Markdown

Description

Fixes #20729.

_WrappedResponseCallFuture is a wrapt.ObjectProxy and stored its span with self._span = span. wrapt forwards that write to the wrapped object, which fails when the response is a plain generator (e.g. ReadRows in google-cloud-bigtable 2.46.0):

AttributeError: 'generator' object has no attribute '_span' and no __dict__ for setting new attributes

Repro (from the issue):

from ddtrace.trace import tracer
from ddtrace.contrib.internal.grpc.client_interceptor import _WrappedResponseCallFuture

def responses():
    yield object()

span = tracer.start_span("grpc.generator.repro")
list(_WrappedResponseCallFuture(responses(), span))

Changes:

  • Store the span as _self_span so it stays on the proxy.
  • Streaming spans are finished by a done callback on the rendezvous. Generators don't have add_done_callback, so finish the span on StopIteration in that case. The rendezvous path is unchanged.

Testing

Added two tests to tests/contrib/grpc/test_grpc.py:

  • a wrapped generator yields its items and the span is finished once it's exhausted (fails on main with the error above)
  • a future-like iterator with add_done_callback still gets the callback registered, and the wrapper doesn't finish the span itself

Risks

Low. A generator that the caller abandons before exhausting it leaves its span open, same as a rendezvous whose RPC never completes.

Additional Notes

Span.finish() is idempotent, so a double finish is harmless.

Store the span on the wrapt proxy as _self_span so wrapping a plain generator no longer raises AttributeError, and finish the span on StopIteration when the wrapped iterator has no done callback.

Fixes DataDog#20729

Signed-off-by: Caio Theodoro <48462974+caiotheodoro@users.noreply.github.com>
@caiotheodoro
caiotheodoro requested review from a team as code owners October 4, 2026 01:07
@caiotheodoro
caiotheodoro requested review from a team, sabrenner and wconti27 and removed request for a team October 4, 2026 01:07
@caiotheodoro

Copy link
Copy Markdown
Author

@wconti27 thanks for the approval. devflow/mergegate is still failing and I can't queue the merge from a fork. Could you add this to the merge queue when you get a chance? Happy to merge main in first if that helps, it's about 100 commits behind.

@caiotheodoro

Copy link
Copy Markdown
Author

@wconti27 the fork workflows on this never ran, they sat unapproved and got failed on 11-03 with no jobs, and mergegate's still red. want me to merge main so you can approve a fresh run?

@caiotheodoro
caiotheodoro requested a review from a team as a code owner November 21, 2026 22:38
@caiotheodoro

Copy link
Copy Markdown
Author

@wconti27 merged main in so the branch is current. the fork workflows are all sitting at "approval required", could you approve the run? once it's green this should be ready for the merge queue.

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

Bits Code Review: PASS

More details

Plain generator responses avoid the proxy attribute error and finish their spans on exhaustion. Future-like responses retain callback-owned span completion, with no reportable regression identified.

Was this helpful? React 👍 or 👎

Open Bits AI session

🤖 Bits Code Review · Commit 8730a06

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

Thanks a lot for your patience, I'll monitor more closely this PR so we make sure this is merged ASAP.

Comment thread tests/contrib/grpc/test_grpc.py Resolved
@dubloom

dubloom commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Once the comments are addressed, I'll run CI for you !

… status

A plain iterator response has no done callback to finish its span: register a weakref finalizer so a dropped generator still finishes the span, record errors and status when iteration raises, and tag grpc.status.code OK on StopIteration. Replace fake-iterator unit tests with tests through a real intercepted SayHelloTwice stream.
@caiotheodoro

Copy link
Copy Markdown
Author

@dubloom the three comments are in cb7a064. drop finishes through weakref, StopIteration sets StatusCode.OK, and the tests go through a real SayHelloTwice with a generator interceptor. those three passed locally. ready for CI when you are.

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

Bits Code Review: FAIL

The PR fixes generator-backed gRPC responses and adds span completion on exhaustion, errors, and wrapper collection. Two issues remain: collection-time finishing can deadlock on telemetry’s non-reentrant lock, and advancing an errored generator again can overwrite its failure status with OK.

Open Bits AI session

🤖 Bits Code Review · Commit cb7a064

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

Your last commit is unsigned which is the last remaining blocker.

A generator that already raised is closed, so the next pull is StopIteration. That path was writing StatusCode.OK over the failure status.

Co-authored-by: Cursor <cursoragent@cursor.com>
@caiotheodoro

Copy link
Copy Markdown
Author

@dubloom signed the tip. 694d559fe replaces the unsigned 2cf728056, same change, SSH signature with the key that signed cb7a06422.

@caiotheodoro
caiotheodoro force-pushed the fix/grpc-generator-response branch from 2cf7280 to 694d559 Compare November 23, 2026 18:06

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

Bits Code Review: FAIL

Cleanup for abandoned generator responses can deadlock the collecting thread when cyclic garbage collection runs during telemetry-recorder allocation.

Open Bits AI session

🤖 Bits Code Review · Commit 694d559

Cyclic collection can run the finalizer while telemetry's _recorder_lock is held. A refcount drop still finishes inline; during GC the span is queued onto a daemon thread.

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

Bits Code Review: FAIL

Generator-backed gRPC responses now work, and deferred GC cleanup fixes the earlier telemetry-lock deadlock. Remaining issues are a GC deadlock in the handoff queue, lost cleanup after fork because the worker is not restarted, and a scheduling race in the new test.

Open Bits AI session

🤖 Bits Code Review · Commit f74378c

Comment thread tests/contrib/grpc/test_grpc.py Resolved
Queue.get allocates while holding its mutex, so a finalizer put on that thread deadlocks the worker. Hand spans through threads.SimpleQueue, and replace the queue and worker flag after fork because the daemon thread does not survive it.

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

Bits Code Review: FAIL

The PR supports generator-backed gRPC responses and addresses the telemetry and queue deadlocks, fork recovery, and original completion-assertion race. One test race remains: replacing the shared queue before the worker enters get() can kill the worker and fail the test.

Open Bits AI session

🤖 Bits Code Review · Commit 0851f69

Comment thread tests/contrib/grpc/test_grpc.py Resolved
Thread.start() can return before the worker enters get(). If the capture object is installed in that window, a missing get() kills the worker and the span is never finished.

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

Bits Code Review: PASS

More details

Generator-backed gRPC responses now retain span state on the proxy and finish spans on exhaustion, errors, or abandonment. All reported deadlocks, post-fork cleanup failures, and test races are resolved; the final change preserves the capture queue’s consumer interface when the worker starts late.

Was this helpful? React 👍 or 👎

Open Bits AI session

🤖 Bits Code Review · Commit 596af65

Match the google_adk and openai realtime precedent: the finalizer calls
span.finish directly instead of deferring to a worker thread, which kept a
daemon thread, a module-level gc callback, and lazy thread startup out of
contrib code. Remove the tests that only exercised that machinery.
@caiotheodoro

Copy link
Copy Markdown
Author

@dubloom all three comments are in cf90f02. also finished the generator path on RpcError (bare RpcError from a user generator has no done callback either) — CI ready whenever you want to run it.

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

Bits Code Review: FAIL

The PR fixes generator-backed gRPC responses, including span completion and error status handling. The latest commit restores direct span completion during garbage collection, reopening the original telemetry-lock deadlock; the worker-related issues and test races remain resolved because their code has been removed.

Open Bits AI session

🤖 Bits Code Review · Commit cf90f02

_handle_response(self._self_span, self.__wrapped__)
if not hasattr(wrapped, "add_done_callback"):
# A plain iterator has no done callback: finish the span if the caller drops it before the end.
weakref.finalize(self, span.finish).atexit = False

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.

P1 Keep span completion out of the GC finalizer

Restoring this synchronous callback reintroduces the original deadlock. If cyclic GC collects an abandoned response during MetricRecorder allocation while _recorder_lock is held, span.finish() reaches SpanAggregator.on_span_finish() and get_metric_recorder(). Before the gRPC completion recorder exists, this reacquires the same non-reentrant lock and permanently blocks the collecting thread. Ordinary reference-counted drops and .atexit=False do not prevent this cyclic-GC path. Preserve abandoned-response cleanup through a GC-safe completion mechanism or make its reachable locking path reentrant.

React: 👍 useful · 👎 wrong · 😕 unclear · 👀 right, but not acting on it

What each reaction means
  • 👍 Useful: correct, and you're fixing it or will.
  • 👎 Wrong: the finding is incorrect, for example the bug can't happen or the code was misread.
  • 😕 Unclear: you can't tell what it means or why it matters.
  • 👀 Right, not acting: correct, but intended, out of scope for this PR, a known risk, or too minor.

🤖 Bits Code Review · Open Bits AI session

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]: gRPC response wrapper raises AttributeError for generators, affecting Bigtable reads after upgrading to 2.46.0

3 participants