Skip to content

Commit c486887

Browse files
goingforstudying-ctrlgoingforstudying-ctrl
authored andcommitted
fix(observe): add span-finalization assertion and document context-var trade-off
- Assert span.ended == 1 after TimeoutError in test_async_generator_wrapper_respects_asyncio_timeout - Expand docstring on _ContextPreservedAsyncGeneratorWrapper to note that context-var mutations across yield points are discarded between iterations
1 parent 1af6f10 commit c486887

2 files changed

Lines changed: 12 additions & 1 deletion

File tree

‎langfuse/_client/observe.py‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -632,7 +632,17 @@ def __next__(self) -> Any:
632632

633633

634634
class _ContextPreservedAsyncGeneratorWrapper:
635-
"""Async generator wrapper that ensures each iteration runs in preserved context."""
635+
"""Async generator wrapper that ensures each iteration runs in preserved context.
636+
637+
.. note::
638+
The wrapper snapshots the caller's contextvars once at construction time
639+
and re-applies those values before each ``__anext__`` call. This means
640+
mutations issued by the generator body *across* ``yield`` points are
641+
discarded between iterations. For Langfuse's own tracing this is fine
642+
because child spans are opened and closed within a single ``__anext__``
643+
call, but user generators that rely on context-var state persisting
644+
across yields will not see those changes.
645+
"""
636646

637647
def __init__(
638648
self,

‎tests/unit/test_observe.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -338,6 +338,7 @@ async def generator() -> AsyncGenerator[str, None]:
338338
# Should have yielded at least once before the timeout fired
339339
assert len(seen) >= 1
340340
assert all(v == "preserved" for v in seen)
341+
assert span.ended == 1
341342

342343

343344
@pytest.mark.asyncio

0 commit comments

Comments
 (0)