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:
wizardchen
2026-05-12 21:12:03 +08:00
committed by lyingbug
parent f740e7cecf
commit 55caeefc3d
4 changed files with 47 additions and 7 deletions
@@ -21,6 +21,8 @@ type AgentStreamHandler struct {
sessionID string
assistantMessageID 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
streamManager interfaces.StreamManager
@@ -37,6 +39,7 @@ type AgentStreamHandler struct {
func NewAgentStreamHandler(
ctx context.Context,
sessionID, assistantMessageID, requestID string,
receivedAt time.Time,
assistantMessage *types.Message,
streamManager interfaces.StreamManager,
eventBus *event.EventBus,
@@ -46,6 +49,7 @@ func NewAgentStreamHandler(
sessionID: sessionID,
assistantMessageID: assistantMessageID,
requestID: requestID,
receivedAt: receivedAt,
assistantMessage: assistantMessage,
streamManager: streamManager,
eventBus: eventBus,
@@ -347,6 +351,17 @@ func (h *AgentStreamHandler) handleFinalAnswer(ctx context.Context, evt event.Ev
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)
h.finalAnswer += data.Content
if data.IsFallback {