Skip to content

[Bug] for sse Server-Sent Events, opentelemetry-instrumentation-flask server span time is less than real response end #3401

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

Open
RichardoMrMu opened this issue Apr 2, 2025 · 2 comments
Labels
bug Something isn't working

Comments

@RichardoMrMu
Copy link

Describe your environment

OS: (e.g, Ubuntu)
Python version: (e.g., Python 3.8.10)
Package version: (e.g., 0.46.0)

What happened?

When I use opentelemetry-instrumentation-flask to get flask sse span, the server span end before the sse response end, that makes flask sse server span time is incorrect. Did anyone solve this problem ?

from flask import Flask, Response
import time
import os
import flask
from opentelemetry.instrumentation.flask import FlaskInstrumentor, _ENVIRON_SPAN_KEY
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import ConsoleSpanExporter, BatchSpanProcessor
from werkzeug.local import LocalProxy
from opentelemetry.trace import get_current_span
app = Flask(__name__)

# 初始化追踪提供者和导出器
provider = TracerProvider()
console_exporter = ConsoleSpanExporter()
provider.add_span_processor(BatchSpanProcessor(console_exporter))
trace.set_tracer_provider(provider)

# 初始化 FlaskInstrumentor 并应用到 Flask 应用
FlaskInstrumentor().instrument_app(app)


# 定义一个生成器,用于流数据
def event_stream():
    for i in range(1, 5):
        # 每次发送消息(遵循 SSE 数据格式)
        yield f"data: Server Time {time.ctime()}\n\n"
        time.sleep(1)  # 每秒发送一次


@app.route('/stream')
def stream():
    # 返回流式响应
    response = Response(event_stream(), content_type='text/event-stream')
    response.headers["test"] = "test"
    return response


if __name__ == '__main__':
    app.run(debug=True)

Steps to Reproduce

code

Expected Result

code

Actual Result

code

Additional context

code

Would you like to implement a fix?

None

@RichardoMrMu RichardoMrMu added the bug Something isn't working label Apr 2, 2025
@xrmx
Copy link
Contributor

xrmx commented Apr 2, 2025

Pretty sure you don't need to open 3 bugs for the same issue 😅

@rahulhacker
Copy link
Contributor

@xrmx : I want to work on the issue

Here my analysis:

The issue seems to be related to how opentelemetry-instrumentation-flask handles the lifecycle of spans for streaming responses.
The Response object for SSE streams is returned immediately, but the actual streaming continues asynchronously, which might not be accounted for in the span lifecycle

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

3 participants