feat(observability): log end-to-end TTFB on both ends of chat stream
To diagnose where latency lives between "user hits send" and "first token appears" we need a single number that can be matched across the browser console and the server log. Add correlated TTFB markers keyed by X-Request-ID: Frontend (streame.ts) * Generate the X-Request-ID once and reuse it for logging. * Log request:start when fetchEventSource is invoked, response:headers when onopen fires, and response:first_answer the first time an SSE payload with response_type === 'answer' arrives. Filtering by event type avoids treating session_title / references / tool_call as the "first token". Backend (session handler) * parseQARequest records the wall-clock entry time and logs TTFB:start with the same X-Request-ID. * qaRequestContext carries receivedAt through to the stream handler. * AgentStreamHandler emits a one-shot TTFB:first_answer_chunk log the first time it observes an AgentFinalAnswerData chunk, so the delta against TTFB:start is the server's request-in → first-token-out budget. The frontend delta minus the backend delta is then attributable to network + gin middleware, which were previously invisible.
This commit is contained in:
@@ -71,11 +71,21 @@ export function useStream() {
|
|||||||
// Removed validation - allow empty knowledge_base_ids array
|
// Removed validation - allow empty knowledge_base_ids array
|
||||||
// The backend should handle this case appropriately
|
// The backend should handle this case appropriately
|
||||||
|
|
||||||
|
// TTFB instrumentation: record the moment we kick off the request so
|
||||||
|
// we can compare it with the first answer chunk we receive from the
|
||||||
|
// server. This makes it possible to correlate the frontend-observed
|
||||||
|
// latency with the backend "TTFB:first_answer_chunk" log line by
|
||||||
|
// matching on X-Request-ID.
|
||||||
|
const sentAt = performance.now();
|
||||||
|
const requestID = generateRandomString(12);
|
||||||
|
let firstAnswerLogged = false;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
let url =
|
let url =
|
||||||
params.method == "POST"
|
params.method == "POST"
|
||||||
? `${apiUrl}${params.url}/${params.session_id}`
|
? `${apiUrl}${params.url}/${params.session_id}`
|
||||||
: `${apiUrl}${params.url}/${params.session_id}?message_id=${params.query}`;
|
: `${apiUrl}${params.url}/${params.session_id}?message_id=${params.query}`;
|
||||||
|
console.log(`[TTFB] request:start request_id=${requestID} url=${url} sent_at=${Date.now()}`);
|
||||||
|
|
||||||
// Prepare POST body with required fields for agent-chat
|
// Prepare POST body with required fields for agent-chat
|
||||||
// knowledge_base_ids array and agent_enabled can update Session's SessionAgentConfig
|
// knowledge_base_ids array and agent_enabled can update Session's SessionAgentConfig
|
||||||
@@ -131,7 +141,7 @@ export function useStream() {
|
|||||||
"Content-Type": "application/json",
|
"Content-Type": "application/json",
|
||||||
"Authorization": `Bearer ${token}`,
|
"Authorization": `Bearer ${token}`,
|
||||||
"Accept-Language": i18n.global.locale?.value || localStorage.getItem('locale') || 'zh-CN',
|
"Accept-Language": i18n.global.locale?.value || localStorage.getItem('locale') || 'zh-CN',
|
||||||
"X-Request-ID": `${generateRandomString(12)}`,
|
"X-Request-ID": requestID,
|
||||||
...(tenantIdHeader ? { "X-Tenant-ID": tenantIdHeader } : {}),
|
...(tenantIdHeader ? { "X-Tenant-ID": tenantIdHeader } : {}),
|
||||||
},
|
},
|
||||||
body:
|
body:
|
||||||
@@ -143,14 +153,23 @@ export function useStream() {
|
|||||||
|
|
||||||
onopen: async (res) => {
|
onopen: async (res) => {
|
||||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||||
|
console.log(`[TTFB] response:headers request_id=${requestID} elapsed_ms=${(performance.now() - sentAt).toFixed(1)}`);
|
||||||
isLoading.value = false;
|
isLoading.value = false;
|
||||||
},
|
},
|
||||||
|
|
||||||
onmessage: (ev) => {
|
onmessage: (ev) => {
|
||||||
buffer.push(JSON.parse(ev.data)); // 数据存入缓冲
|
const parsed = JSON.parse(ev.data);
|
||||||
|
// Log first answer chunk for end-to-end TTFB measurement.
|
||||||
|
// Filter by event type so non-answer events (references, tool
|
||||||
|
// calls, etc.) don't count as the "first token" arrival.
|
||||||
|
if (!firstAnswerLogged && (parsed?.response_type === 'answer' || parsed?.type === 'answer')) {
|
||||||
|
firstAnswerLogged = true;
|
||||||
|
console.log(`[TTFB] response:first_answer request_id=${requestID} elapsed_ms=${(performance.now() - sentAt).toFixed(1)}`);
|
||||||
|
}
|
||||||
|
buffer.push(parsed); // 数据存入缓冲
|
||||||
// 执行自定义处理
|
// 执行自定义处理
|
||||||
if (chunkHandler) {
|
if (chunkHandler) {
|
||||||
chunkHandler(JSON.parse(ev.data));
|
chunkHandler(parsed);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
|
|||||||
@@ -21,6 +21,8 @@ type AgentStreamHandler struct {
|
|||||||
sessionID string
|
sessionID string
|
||||||
assistantMessageID string
|
assistantMessageID string
|
||||||
requestID string
|
requestID string
|
||||||
|
receivedAt time.Time // Handler entry timestamp, used for TTFB logging
|
||||||
|
ttfbLogged bool // Guards one-shot TTFB log on first answer chunk
|
||||||
assistantMessage *types.Message
|
assistantMessage *types.Message
|
||||||
streamManager interfaces.StreamManager
|
streamManager interfaces.StreamManager
|
||||||
|
|
||||||
@@ -37,6 +39,7 @@ type AgentStreamHandler struct {
|
|||||||
func NewAgentStreamHandler(
|
func NewAgentStreamHandler(
|
||||||
ctx context.Context,
|
ctx context.Context,
|
||||||
sessionID, assistantMessageID, requestID string,
|
sessionID, assistantMessageID, requestID string,
|
||||||
|
receivedAt time.Time,
|
||||||
assistantMessage *types.Message,
|
assistantMessage *types.Message,
|
||||||
streamManager interfaces.StreamManager,
|
streamManager interfaces.StreamManager,
|
||||||
eventBus *event.EventBus,
|
eventBus *event.EventBus,
|
||||||
@@ -46,6 +49,7 @@ func NewAgentStreamHandler(
|
|||||||
sessionID: sessionID,
|
sessionID: sessionID,
|
||||||
assistantMessageID: assistantMessageID,
|
assistantMessageID: assistantMessageID,
|
||||||
requestID: requestID,
|
requestID: requestID,
|
||||||
|
receivedAt: receivedAt,
|
||||||
assistantMessage: assistantMessage,
|
assistantMessage: assistantMessage,
|
||||||
streamManager: streamManager,
|
streamManager: streamManager,
|
||||||
eventBus: eventBus,
|
eventBus: eventBus,
|
||||||
@@ -347,6 +351,17 @@ func (h *AgentStreamHandler) handleFinalAnswer(ctx context.Context, evt event.Ev
|
|||||||
h.eventStartTimes[evt.ID] = time.Now()
|
h.eventStartTimes[evt.ID] = time.Now()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Emit a one-shot TTFB log the first time *any* answer chunk reaches
|
||||||
|
// the stream handler. This lets us compare the backend's "request in →
|
||||||
|
// first token out" timing against the frontend-observed TTFB and pin
|
||||||
|
// down where latency lives (network vs server vs LLM).
|
||||||
|
if !h.ttfbLogged && !h.receivedAt.IsZero() {
|
||||||
|
h.ttfbLogged = true
|
||||||
|
ttfb := time.Since(h.receivedAt)
|
||||||
|
logger.GetLogger(h.ctx).Infof("TTFB:first_answer_chunk request_id=%s, session_id=%s, ttfb_ms=%d",
|
||||||
|
h.requestID, h.sessionID, ttfb.Milliseconds())
|
||||||
|
}
|
||||||
|
|
||||||
// Accumulate final answer locally for assistant message (database)
|
// Accumulate final answer locally for assistant message (database)
|
||||||
h.finalAnswer += data.Content
|
h.finalAnswer += data.Content
|
||||||
if data.IsFallback {
|
if data.IsFallback {
|
||||||
|
|||||||
@@ -191,11 +191,12 @@ func (h *Handler) createAssistantMessage(ctx context.Context, assistantMessage *
|
|||||||
func (h *Handler) setupStreamHandler(
|
func (h *Handler) setupStreamHandler(
|
||||||
ctx context.Context,
|
ctx context.Context,
|
||||||
sessionID, assistantMessageID, requestID string,
|
sessionID, assistantMessageID, requestID string,
|
||||||
|
receivedAt time.Time,
|
||||||
assistantMessage *types.Message,
|
assistantMessage *types.Message,
|
||||||
eventBus *event.EventBus,
|
eventBus *event.EventBus,
|
||||||
) *AgentStreamHandler {
|
) *AgentStreamHandler {
|
||||||
streamHandler := NewAgentStreamHandler(
|
streamHandler := NewAgentStreamHandler(
|
||||||
ctx, sessionID, assistantMessageID, requestID,
|
ctx, sessionID, assistantMessageID, requestID, receivedAt,
|
||||||
assistantMessage, h.streamManager, eventBus,
|
assistantMessage, h.streamManager, eventBus,
|
||||||
)
|
)
|
||||||
streamHandler.Subscribe()
|
streamHandler.Subscribe()
|
||||||
|
|||||||
@@ -24,6 +24,7 @@ type qaRequestContext struct {
|
|||||||
c *gin.Context
|
c *gin.Context
|
||||||
sessionID string
|
sessionID string
|
||||||
requestID string
|
requestID string
|
||||||
|
receivedAt time.Time // Wall-clock time the handler started processing the request
|
||||||
query string
|
query string
|
||||||
session *types.Session
|
session *types.Session
|
||||||
customAgent *types.CustomAgent
|
customAgent *types.CustomAgent
|
||||||
@@ -63,8 +64,11 @@ func (rc *qaRequestContext) buildQARequest() *types.QARequest {
|
|||||||
|
|
||||||
// parseQARequest parses and validates a QA request, returns the request context
|
// parseQARequest parses and validates a QA request, returns the request context
|
||||||
func (h *Handler) parseQARequest(c *gin.Context, logPrefix string) (*qaRequestContext, *CreateKnowledgeQARequest, error) {
|
func (h *Handler) parseQARequest(c *gin.Context, logPrefix string) (*qaRequestContext, *CreateKnowledgeQARequest, error) {
|
||||||
|
receivedAt := time.Now()
|
||||||
ctx := logger.CloneContext(c.Request.Context())
|
ctx := logger.CloneContext(c.Request.Context())
|
||||||
logger.Infof(ctx, "[%s] Start processing request", logPrefix)
|
requestID := secutils.SanitizeForLog(c.GetString(types.RequestIDContextKey.String()))
|
||||||
|
logger.Infof(ctx, "[%s] TTFB:start request_id=%s received_at=%d",
|
||||||
|
logPrefix, requestID, receivedAt.UnixMilli())
|
||||||
|
|
||||||
// Get session ID from URL parameter
|
// Get session ID from URL parameter
|
||||||
sessionID := secutils.SanitizeForLog(c.Param("session_id"))
|
sessionID := secutils.SanitizeForLog(c.Param("session_id"))
|
||||||
@@ -204,7 +208,8 @@ func (h *Handler) parseQARequest(c *gin.Context, logPrefix string) (*qaRequestCo
|
|||||||
ctx: ctx,
|
ctx: ctx,
|
||||||
c: c,
|
c: c,
|
||||||
sessionID: sessionID,
|
sessionID: sessionID,
|
||||||
requestID: secutils.SanitizeForLog(c.GetString(types.RequestIDContextKey.String())),
|
requestID: requestID,
|
||||||
|
receivedAt: receivedAt,
|
||||||
query: secutils.SanitizeForLog(request.Query),
|
query: secutils.SanitizeForLog(request.Query),
|
||||||
session: session,
|
session: session,
|
||||||
customAgent: customAgent,
|
customAgent: customAgent,
|
||||||
@@ -355,7 +360,7 @@ func (h *Handler) setupSSEStream(reqCtx *qaRequestContext, generateTitle bool) *
|
|||||||
|
|
||||||
// Setup stream handler
|
// Setup stream handler
|
||||||
h.setupStreamHandler(asyncCtx, reqCtx.sessionID, reqCtx.assistantMessage.ID,
|
h.setupStreamHandler(asyncCtx, reqCtx.sessionID, reqCtx.assistantMessage.ID,
|
||||||
reqCtx.requestID, reqCtx.assistantMessage, eventBus)
|
reqCtx.requestID, reqCtx.receivedAt, reqCtx.assistantMessage, eventBus)
|
||||||
|
|
||||||
// Generate title if needed
|
// Generate title if needed
|
||||||
if generateTitle && reqCtx.session.Title == "" {
|
if generateTitle && reqCtx.session.Title == "" {
|
||||||
|
|||||||
Reference in New Issue
Block a user