-
Notifications
You must be signed in to change notification settings - Fork 183
fix: Avoid mixed Langfuse traces in async envs #2207
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
Replacing #2188 |
Asking @mpangrazzi a review since he was originally involved. Let's also adjust the title. |
I checked complex agents and examples pipelines. All good. Thanks a lot for the confirmation @LastRemote 💪 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Looks good! 👍 I've left only a minor comment (note that I am not a Langfuse expert 😉)
if self._context and self._context[-1] == span: | ||
self._context.pop() | ||
# Restore previous span stack using saved token - ensures proper cleanup | ||
span_stack_var.reset(token) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Can we safely assume this line will never throw an error?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
No mention of it in pydocs anywhere. Seems like it can't happen
Fixed and released in https://pypi.org/project/langfuse-haystack/2.3.0/ |
Why:
Purpose: Fixes a race condition where spans from concurrent pipeline runs become intertwined, corrupting tracing data and making debugging unreliable in production web server environments.
LangfuseTracer
is not thread-safe, causing mixed traces in async environments #2140What:
self._context
list withContextVar
for thread-safe span stack managementLangfuseTracer.trace()
method to use context-local span storagecurrent_span()
method to read from context-local statespan_context_var
ContextVar for isolated span contexts per execution threadHow can it be used:
Nothing changes in client code except that we don't corrupt traces in concurrent async pipelines. All existing usage patterns continue to work exactly as before, but now with proper thread safety.
How did you test it: