LangfuseSpanNotClosedError
langfuse.exceptions.LangfuseSpanNotClosedError
Stack trace
langfuse.exceptions.LangfuseSpanNotClosedError: Span was not closed properly before exiting context or program termination
File "/app/main.py", line 42, in <module>
with lf_client.start_span("my-operation") as span:
File "/usr/local/lib/python3.9/site-packages/langfuse/client.py", line 128, in __exit__
raise LangfuseSpanNotClosedError("Span was not closed properly") Why it happens
Langfuse tracing requires every span to be explicitly closed to ensure accurate telemetry. If a span context is exited without calling the close method or the span is left hanging due to an exception or missing code, this error is raised. It ensures developers do not lose trace data or cause inconsistent trace states.
Detection
Monitor your application logs for LangfuseSpanNotClosedError exceptions and add instrumentation to verify that every span's close method is called or the context manager exits cleanly.
Causes & fixes
Span context manager exited without calling span.close() due to missing or incorrect usage
Always use the span as a context manager with 'with' syntax or explicitly call span.close() in all code paths including exception handlers.
An exception occurred inside the span context and the span was not closed in the exception handling block
Wrap span usage in try/finally or use 'with' context manager to guarantee span closure even on exceptions.
Manual span creation without matching close call
Ensure every manually started span has a corresponding close() call before the program or request ends.
Code: broken vs fixed
from langfuse import LangfuseClient
lf_client = LangfuseClient(api_key=os.environ['LANGFUSE_API_KEY'])
span = lf_client.start_span("my-operation")
# Missing span.close() call here, causes error
print("Doing work") import os
from langfuse import LangfuseClient
lf_client = LangfuseClient(api_key=os.environ['LANGFUSE_API_KEY'])
# Fixed: use context manager to auto-close span
with lf_client.start_span("my-operation") as span:
print("Doing work")
# This ensures span is properly closed even if exceptions occur Workaround
Wrap your span usage in try/finally blocks and call span.close() in the finally clause to ensure closure even if you cannot use context managers.
Prevention
Adopt consistent use of context managers for all Langfuse spans and add automated tests or linters to detect spans that are not properly closed.