Repository navigation
fix: SSE write timeout - #15852
fix: SSE write timeout#15852
Conversation
📝 WalkthroughWalkthroughAdds a Gin helper that clears per-request HTTP write deadlines for SSE, invokes it before SSE headers in streaming branches across handlers, and includes integration tests verifying long-lived SSE streams survive short server WriteTimeouts. ChangesSSE Write Deadline Management
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related PRs
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
🧹 Nitpick comments (2)
internal/handler/streaming.go (2)
26-28: 💤 Low valueConsider logging errors from
SetWriteDeadline.While
SetWriteDeadlinerarely fails for HTTP connections, silently discarding the error could hide issues in edge cases (e.g., connection already closed, unsupported by underlying transport). Consider logging the error to aid debugging if SSE streams fail unexpectedly.📝 Proposed enhancement with error logging
func disableWriteDeadlineForSSE(c *gin.Context) { - _ = http.NewResponseController(c.Writer).SetWriteDeadline(time.Time{}) + if err := http.NewResponseController(c.Writer).SetWriteDeadline(time.Time{}); err != nil { + // Log but don't fail - if we can't clear the deadline, the stream will timeout anyway + // This helps diagnose potential issues with the underlying connection + c.Error(err) + } }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/handler/streaming.go` around lines 26 - 28, The call to http.NewResponseController(c.Writer).SetWriteDeadline currently discards any returned error; change disableWriteDeadlineForSSE to capture the error and log it for debugging (e.g., err := http.NewResponseController(c.Writer).SetWriteDeadline(time.Time{}); if err != nil { c.Error(err) or use c.Logger().Errorf(...) }) so failures in SetWriteDeadline are recorded and include a short contextual message identifying disableWriteDeadlineForSSE and that it failed to clear the write deadline.
26-28: ⚡ Quick winAdd documentation comment explaining purpose and usage.
The helper function would benefit from a doc comment explaining why it's needed and when to call it, especially since the write-deadline behavior is subtle and specific to SSE streams.
📝 Proposed documentation
+// disableWriteDeadlineForSSE clears the HTTP response write deadline for long-lived +// Server-Sent Events (SSE) connections. This prevents the server's global WriteTimeout +// from terminating SSE streams that exceed the timeout duration. +// Must be called before writing SSE headers and data. func disableWriteDeadlineForSSE(c *gin.Context) { _ = http.NewResponseController(c.Writer).SetWriteDeadline(time.Time{}) }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/handler/streaming.go` around lines 26 - 28, Add a package-level doc comment for the helper function disableWriteDeadlineForSSE explaining its purpose (to clear the HTTP write deadline for long-lived Server-Sent Events streams), why it sets an empty time.Time (to disable per-connection write deadlines), and when to call it (before starting SSE streaming to avoid premature connection timeouts). Reference the function name disableWriteDeadlineForSSE and the use of http.NewResponseController(c.Writer).SetWriteDeadline(time.Time{}) so readers know exactly which call is affecting deadline behavior and the intended usage pattern.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In `@internal/handler/streaming.go`:
- Around line 26-28: The call to
http.NewResponseController(c.Writer).SetWriteDeadline currently discards any
returned error; change disableWriteDeadlineForSSE to capture the error and log
it for debugging (e.g., err :=
http.NewResponseController(c.Writer).SetWriteDeadline(time.Time{}); if err !=
nil { c.Error(err) or use c.Logger().Errorf(...) }) so failures in
SetWriteDeadline are recorded and include a short contextual message identifying
disableWriteDeadlineForSSE and that it failed to clear the write deadline.
- Around line 26-28: Add a package-level doc comment for the helper function
disableWriteDeadlineForSSE explaining its purpose (to clear the HTTP write
deadline for long-lived Server-Sent Events streams), why it sets an empty
time.Time (to disable per-connection write deadlines), and when to call it
(before starting SSE streaming to avoid premature connection timeouts).
Reference the function name disableWriteDeadlineForSSE and the use of
http.NewResponseController(c.Writer).SetWriteDeadline(time.Time{}) so readers
know exactly which call is affecting deadline behavior and the intended usage
pattern.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: b374e042-faa2-4826-92c8-0ab229ba3c5b
📒 Files selected for processing (4)
internal/handler/chat_session.gointernal/handler/providers.gointernal/handler/streaming.gointernal/handler/streaming_test.go
|
Hi @xugangqiang Ready for review! |
|
@bitloi May I know how to verify the fix? How to make sure there will be no regression issues? |
The fix is verified by That test starts a real For regression safety:
So the change is limited to long-lived SSE responses and is covered by a focused server-level regression test. |
@bitloi Thanks for the input. Is it possible to do a real test? The above mentioned is not a "real" test and may not be good enough. |
|
You're right. The current test uses a real I also noticed that |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
internal/handler/searchbot.go (1)
518-519: Unused helper functions ininternal/handler/searchbot.go
intPtr(lines 518-519) andfloatPtr(lines 518-519) have no call sites (outside*_test.go), so they’re dead/unnecessary. Also,floatPtrduplicatesptrFloat64at line 516 and can be removed in favor ofptrFloat64.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/handler/searchbot.go` around lines 518 - 519, Remove the two unused helpers intPtr and floatPtr from internal/handler/searchbot.go; floatPtr is a duplicate of ptrFloat64 so replace any uses in *_test.go with ptrFloat64, and for any test that needs an int pointer either use an existing test-only helper or add a small int pointer helper inside the test file (do not add it back into production code). Ensure you remove the intPtr and floatPtr function definitions and update all test call sites to reference ptrFloat64 (for float64) or a test-scoped int pointer helper.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@internal/handler/searchbot.go`:
- Around line 372-380: The SSE error is written before the response headers are
set; instead of calling h.sseWriter.Write(sseError(...)) when modelID == "" you
should return a JSON error like the earlier validations to keep behavior
consistent: remove the h.sseWriter.Write call inside the modelID check and
respond with c.JSON(...) (or the same JSON error helper used at other
validations) so you don't set SSE headers for a non-SSE response; alternatively,
if you prefer SSE semantics, move disableWriteDeadlineForSSE and the
c.Header("Content-Type","text/event-stream") / Cache-Control / Connection lines
to execute before checking modelID so the sseError is sent with the proper
headers. Ensure references to h.sseWriter.Write, sseError,
disableWriteDeadlineForSSE and the c.Header calls are updated accordingly.
---
Nitpick comments:
In `@internal/handler/searchbot.go`:
- Around line 518-519: Remove the two unused helpers intPtr and floatPtr from
internal/handler/searchbot.go; floatPtr is a duplicate of ptrFloat64 so replace
any uses in *_test.go with ptrFloat64, and for any test that needs an int
pointer either use an existing test-only helper or add a small int pointer
helper inside the test file (do not add it back into production code). Ensure
you remove the intPtr and floatPtr function definitions and update all test call
sites to reference ptrFloat64 (for float64) or a test-scoped int pointer helper.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 88c00e8a-5d3a-4678-a282-62b6a420323e
📒 Files selected for processing (2)
internal/handler/searchbot.gointernal/handler/searchbot_test.go
There was a problem hiding this comment.
Caution
Inline review comments failed to post. This is likely due to GitHub's internal server error or limits when posting large numbers of comments. If you are seeing this consistently it is likely a permissions issue. Please check "Moderation" -> "Code review limits" under your organization settings.
Actionable comments posted: 1
🧹 Nitpick comments (1)
internal/handler/searchbot.go (1)
518-519: Unused helper functions ininternal/handler/searchbot.go
intPtr(lines 518-519) andfloatPtr(lines 518-519) have no call sites (outside*_test.go), so they’re dead/unnecessary. Also,floatPtrduplicatesptrFloat64at line 516 and can be removed in favor ofptrFloat64.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/handler/searchbot.go` around lines 518 - 519, Remove the two unused helpers intPtr and floatPtr from internal/handler/searchbot.go; floatPtr is a duplicate of ptrFloat64 so replace any uses in *_test.go with ptrFloat64, and for any test that needs an int pointer either use an existing test-only helper or add a small int pointer helper inside the test file (do not add it back into production code). Ensure you remove the intPtr and floatPtr function definitions and update all test call sites to reference ptrFloat64 (for float64) or a test-scoped int pointer helper.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@internal/handler/searchbot.go`:
- Around line 372-380: The SSE error is written before the response headers are
set; instead of calling h.sseWriter.Write(sseError(...)) when modelID == "" you
should return a JSON error like the earlier validations to keep behavior
consistent: remove the h.sseWriter.Write call inside the modelID check and
respond with c.JSON(...) (or the same JSON error helper used at other
validations) so you don't set SSE headers for a non-SSE response; alternatively,
if you prefer SSE semantics, move disableWriteDeadlineForSSE and the
c.Header("Content-Type","text/event-stream") / Cache-Control / Connection lines
to execute before checking modelID so the sseError is sent with the proper
headers. Ensure references to h.sseWriter.Write, sseError,
disableWriteDeadlineForSSE and the c.Header calls are updated accordingly.
---
Nitpick comments:
In `@internal/handler/searchbot.go`:
- Around line 518-519: Remove the two unused helpers intPtr and floatPtr from
internal/handler/searchbot.go; floatPtr is a duplicate of ptrFloat64 so replace
any uses in *_test.go with ptrFloat64, and for any test that needs an int
pointer either use an existing test-only helper or add a small int pointer
helper inside the test file (do not add it back into production code). Ensure
you remove the intPtr and floatPtr function definitions and update all test call
sites to reference ptrFloat64 (for float64) or a test-scoped int pointer helper.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 88c00e8a-5d3a-4678-a282-62b6a420323e
📒 Files selected for processing (2)
internal/handler/searchbot.gointernal/handler/searchbot_test.go
🛑 Comments failed to post (1)
internal/handler/searchbot.go (1)
372-380:
⚠️ Potential issue | 🟠 Major | ⚡ Quick winSSE error written before Content-Type header is set.
At line 373, when
modelIDis empty, the handler writes an SSE-formatted error viah.sseWriter.Write(), but theContent-Type: text/event-streamheader isn't set until line 378. The client may not correctly interpret this as an SSE response.For consistency with earlier validation failures (lines 338, 351) that return JSON, consider returning a JSON error here as well, or move the SSE header setup before the modelID check.
Option A: Return JSON error (consistent with other validation)
if modelID == "" { - h.sseWriter.Write(c, sseError("chat model not configured")) + c.JSON(http.StatusBadRequest, gin.H{"code": common.CodeArgumentError, "data": nil, "message": "chat model not configured"}) return }Option B: Set headers before modelID check
+ disableWriteDeadlineForSSE(c) + c.Header("Content-Type", "text/event-stream") + c.Header("Cache-Control", "no-cache") + c.Header("Connection", "keep-alive") + if modelID == "" { h.sseWriter.Write(c, sseError("chat model not configured")) return } - disableWriteDeadlineForSSE(c) - c.Header("Content-Type", "text/event-stream") - c.Header("Cache-Control", "no-cache") - c.Header("Connection", "keep-alive")📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.if modelID == "" { c.JSON(http.StatusBadRequest, gin.H{"code": common.CodeArgumentError, "data": nil, "message": "chat model not configured"}) return } disableWriteDeadlineForSSE(c) c.Header("Content-Type", "text/event-stream") c.Header("Cache-Control", "no-cache") c.Header("Connection", "keep-alive")disableWriteDeadlineForSSE(c) c.Header("Content-Type", "text/event-stream") c.Header("Cache-Control", "no-cache") c.Header("Connection", "keep-alive") if modelID == "" { h.sseWriter.Write(c, sseError("chat model not configured")) return }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/handler/searchbot.go` around lines 372 - 380, The SSE error is written before the response headers are set; instead of calling h.sseWriter.Write(sseError(...)) when modelID == "" you should return a JSON error like the earlier validations to keep behavior consistent: remove the h.sseWriter.Write call inside the modelID check and respond with c.JSON(...) (or the same JSON error helper used at other validations) so you don't set SSE headers for a non-SSE response; alternatively, if you prefer SSE semantics, move disableWriteDeadlineForSSE and the c.Header("Content-Type","text/event-stream") / Cache-Control / Connection lines to execute before checking modelID so the sseError is sent with the proper headers. Ensure references to h.sseWriter.Write, sseError, disableWriteDeadlineForSSE and the c.Header calls are updated accordingly.
|
Updated in I added the missing I also added I ran:
and
|
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #15852 +/- ##
=======================================
Coverage 93.16% 93.16%
=======================================
Files 10 10
Lines 717 717
Branches 118 118
=======================================
Hits 668 668
Misses 29 29
Partials 20 20 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
|
@JinHai-CN @yingfeng LGTM |
### What problem does this PR solve? Fixes infiniflow#15840. The Go HTTP server sets `WriteTimeout: 120s`, which also applies to long-lived SSE responses. Existing Go streaming handlers did not clear the per-response write deadline, so streams that run longer than the server timeout can be terminated mid-response. This PR adds a small handler helper that clears the response write deadline for SSE requests and calls it only in existing Go streaming branches: - conversation completion streaming - provider chat streaming - provider transcription streaming - provider speech streaming The global server `WriteTimeout` remains unchanged for non-streaming requests. ### Type of change - [x] Bug Fix (non-breaking change which fixes an issue) ### Test plan - `/root/go/bin/go test ./internal/handler -run TestDisableWriteDeadlineForSSEAllowsLongLivedStream -count=1` - `/root/go/bin/go test ./internal/handler -count=1` (cherry picked from commit cafa0f2)
The Go infiniflow#15852 fix only protects hybrid/golang mode. This deploy runs the Python/Quart backend, whose RESPONSE_TIMEOUT/BODY_TIMEOUT default to 600s. Raise them to 3600s (matching nginx proxy_read/send_timeout) so a long chat/agent SSE stream is never cut by the app before the proxy.
…ndlers http.Server carries a hard-coded WriteTimeout of 180s. In Go that is a deadline for the whole response, not an idle timeout, so an SSE stream is cut off at 180s even while data keeps flowing: long agent runs never finish and the client sees a closed connection with no final event. infiniflow#15852 added clearResponseWriteDeadline for exactly this and wired it into chat_session, providers, searchbot, search, chat_audio and openai_chat. Five SSE handlers were left without it: agent.go RunAgent agent.go AgentChatCompletions (stream branch) agent_openai.go streamOpenAICompat bot.go AgentbotCompletion bot.go ChatbotCompletion Call the helper in all five, next to the Content-Type header like the existing call sites, and give the four undocumented ones a doc comment that names the endpoint and records why the deadline is cleared. Test: sse_write_deadline_guard_test.go walks the package with go/ast and fails for any function that sets a text/event-stream Content-Type without calling the helper. On the previous revision it reports these five handlers; with the change it passes (12 SSE handlers, all covered). It is a source-level guard because reaching these streaming branches needs a chat runner, database and Redis, while the failure mode is precisely "a streaming handler forgot the call". Not verified here: the package cannot be compiled on Windows, where internal/agent/sandbox and internal/agentic_rag/decisionhead are build-gated off, and the 180s cut itself was not reproduced against a live server. The helper's behaviour is already pinned by streaming_test.go. Fixes infiniflow#21649
…ndlers http.Server carries a hard-coded WriteTimeout of 180s. In Go that is a deadline for the whole response, not an idle timeout, so an SSE stream is cut off at 180s even while data keeps flowing: long agent runs never finish and the client sees a closed connection with no final event. infiniflow#15852 added clearResponseWriteDeadline for exactly this and wired it into chat_session, providers, searchbot, search, chat_audio and openai_chat. Five SSE handlers were left without it: agent.go RunAgent agent.go AgentChatCompletions (stream branch) agent_openai.go streamOpenAICompat bot.go AgentbotCompletion bot.go ChatbotCompletion The non-stream paths of the two agent completion endpoints had the same gap from the other direction: both run a full agent turn and only write once the run completes, so WriteTimeout bounds them just as tightly. Clear the deadline there too - AgentChatCompletions before collecting the non-stream answer, handleOpenAICompat before the collection starts, mirroring chat_session.go's non-stream branch and openai_chat.go, which clears it before branching. Give the four undocumented handlers a doc comment naming the endpoint and recording why the deadline is cleared. Test: sse_write_deadline_guard_test.go walks the package with go/ast and fails for any handler that can outlive WriteTimeout without calling the helper. A handler is in scope when it sets a text/event-stream Content-Type or runs an agent turn through a chat runner - the second condition is what catches the non-stream branches, which never set the SSE header. With the change all 13 in-scope handlers are covered; a non-stream-only handler that runs an agent turn is reported. Not verified here: the package cannot be compiled on Windows, where internal/agent/sandbox and internal/agentic_rag/decisionhead are build-gated off, and the 180s cut itself was not reproduced against a live server. The helper's behaviour is already pinned by streaming_test.go. Fixes infiniflow#21649
…ndlers http.Server carries a hard-coded WriteTimeout of 180s. In Go that is a deadline for the whole response, not an idle timeout, so an SSE stream is cut off at 180s even while data keeps flowing: long agent runs never finish and the client sees a closed connection with no final event. infiniflow#15852 added clearResponseWriteDeadline for exactly this and wired it into chat_session, providers, searchbot, search, chat_audio and openai_chat. Five SSE handlers were left without it: agent.go RunAgent agent.go AgentChatCompletions (stream branch) agent_openai.go streamOpenAICompat bot.go AgentbotCompletion bot.go ChatbotCompletion The non-stream paths of the two agent completion endpoints had the same gap from the other direction: both run a full agent turn and only write once the run completes, so WriteTimeout bounds them just as tightly. Clear the deadline there too - AgentChatCompletions before collecting the non-stream answer, handleOpenAICompat before the collection starts, mirroring chat_session.go's non-stream branch and openai_chat.go, which clears it before branching. Give the four undocumented handlers a doc comment naming the endpoint and recording why the deadline is cleared. Test: sse_write_deadline_guard_test.go walks the package with go/ast and fails for any handler that can outlive WriteTimeout without calling the helper. A handler is in scope when it sets a text/event-stream Content-Type or runs an agent turn through a chat runner - the second condition is what catches the non-stream branches, which never set the SSE header. With the change all 13 in-scope handlers are covered; a non-stream-only handler that runs an agent turn is reported. The guard is structural, so it checks that a function body calls the helper somewhere rather than that every long path reaches a call: AgentChatCompletions clears on both branches, and deleting the non-stream call would still pass. The test's doc comment records that limit (and that runsAgentTurn over-approximates on purpose) so the guard is not mistaken for a per-branch proof. Not verified here: the package cannot be compiled on Windows, where internal/agent/sandbox and internal/agentic_rag/decisionhead are build-gated off, and the 180s cut itself was not reproduced against a live server. The helper's behaviour is already pinned by streaming_test.go. Fixes infiniflow#21649
…ndlers http.Server carries a hard-coded WriteTimeout of 180s. In Go that is a deadline for the whole response, not an idle timeout, so an SSE stream is cut off at 180s even while data keeps flowing: long agent runs never finish and the client sees a closed connection with no final event. infiniflow#15852 added clearResponseWriteDeadline for exactly this and wired it into chat_session, providers, searchbot, search, chat_audio and openai_chat. Five SSE handlers were left without it: agent.go RunAgent agent.go AgentChatCompletions (stream branch) agent_openai.go streamOpenAICompat bot.go AgentbotCompletion bot.go ChatbotCompletion The non-stream paths of the two agent completion endpoints had the same gap from the other direction: both run a full agent turn and only write once the run completes, so WriteTimeout bounds them just as tightly. Clear the deadline before the run starts, not after it: RunAgent waits for the session lock while a session is busy (service/agent.go polls on a 100ms ticker until the lock frees), so the wait itself can outlive the deadline, and a deadline that expired during the wait cannot be restored by clearing it later. The clear therefore sits at the handler boundary in RunAgent, handleOpenAICompat and AgentbotCompletion - which covers the stream and non-stream paths below them - and in AgentChatCompletions before each of its two response sections. streamOpenAICompat keeps its own clear: redundant at the current call site, but it honours the function's contract when called directly. Give the four undocumented handlers a doc comment naming the endpoint and recording why the deadline is cleared. Test: sse_write_deadline_guard_test.go walks the package with go/ast and fails for any handler that can outlive WriteTimeout without calling the helper. A handler is in scope when it sets a text/event-stream Content-Type or runs an agent turn through a chat runner - the second condition is what catches the non-stream branches, which never set the SSE header. With the change all 13 in-scope handlers are covered; a non-stream-only handler that runs an agent turn is reported. The guard is function-level, so it checks that a function body calls the helper somewhere rather than that every long path reaches a call, or that the call precedes the work it protects. Its doc comment records that limit (and that runsAgentTurn over-approximates on purpose) so it is not mistaken for a per-branch proof. Not verified here: the package cannot be compiled on Windows, where internal/agent/sandbox and internal/agentic_rag/decisionhead are build-gated off, and the 180s cut itself was not reproduced against a live server. The helper's behaviour is already pinned by streaming_test.go. Fixes infiniflow#21649
What problem does this PR solve?
Fixes #15840.
The Go HTTP server sets
WriteTimeout: 120s, which also applies to long-lived SSE responses. Existing Go streaming handlers did not clear the per-response write deadline, so streams that run longer than the server timeout can be terminated mid-response.This PR adds a small handler helper that clears the response write deadline for SSE requests and calls it only in existing Go streaming branches:
The global server
WriteTimeoutremains unchanged for non-streaming requests.Type of change
Test plan
/root/go/bin/go test ./internal/handler -run TestDisableWriteDeadlineForSSEAllowsLongLivedStream -count=1/root/go/bin/go test ./internal/handler -count=1