Skip to content

fix: SSE write timeout - #15852

Merged
yingfeng merged 12 commits into
infiniflow:mainfrom
bitloi:fix/15840-go-sse-write-timeout
Jun 12, 2026
Merged

yingfeng merged 12 commits into
infiniflow:mainfrom
bitloi:fix/15840-go-sse-write-timeout

Conversation

@bitloi

@bitloi bitloi commented Jun 9, 2026 •

Copy link
Copy Markdown
Contributor

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:

  • 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

  • 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

@dosubot dosubot Bot added size:M This PR changes 30-99 lines, ignoring generated files. 🐞 bug Something isn't working, pull request that fix bug. labels Jun 9, 2026
@coderabbitai

coderabbitai Bot commented Jun 9, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Adds 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.

Changes

SSE Write Deadline Management

Layer / File(s) Summary
SSE write deadline helper and integration test
internal/handler/streaming.go, internal/handler/streaming_test.go
disableWriteDeadlineForSSE clears the HTTP response write deadline via http.NewResponseController(c.Writer).SetWriteDeadline(time.Time{}). Integration test streams two flushed SSE chunks with a short server WriteTimeout and verifies both arrive.
Streaming endpoint integrations
internal/handler/chat_session.go, internal/handler/providers.go, internal/handler/searchbot.go
Inserted disableWriteDeadlineForSSE(c) at the start of SSE streaming branches (before setting Content-Type: text/event-stream and writing the status) in ChatSessionHandler.Completion, ChatToModel, TranscribeAudio, AudioSpeech, and SearchBotHandler.Ask.
Searchbot test updates and test double
internal/handler/searchbot_test.go
Expanded imports, added delay to fakeStreamingLLM, changed ChatStream to optionally emit delayed chunks, added a tenant-DB test helper, and added an integration test TestAskHandler_DisablesWriteDeadlineForSSE.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • infiniflow/ragflow#15739: Modifies the ChatSessionHandler.Completion streaming path; related to streaming behavior and header/write-deadline handling.

Suggested reviewers

  • Haruko386

Poem

🐇 I nudge the stream to stretch and play,
Deadlines loosen, then slip away.
Two flushed lines drift past the gate,
The tiny packets do not wait.
The long-lived SSE hums — hooray!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 20.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'fix: SSE write timeout' clearly and concisely summarizes the main change: fixing SSE (Server-Sent Events) write timeout issues in the codebase.
Linked Issues check ✅ Passed The PR successfully addresses all coding requirements from issue #15840: adds disableWriteDeadlineForSSE helper to clear response write deadlines in SSE-streaming branches, applies it to all affected handlers (chat completion, chat stream, transcription, speech), and includes comprehensive tests.
Out of Scope Changes check ✅ Passed All changes directly support the primary objective of fixing SSE write timeout issues. New files (streaming.go, streaming_test.go, searchbot_test.go updates) and modifications to existing handlers remain within scope and address issue #15840.
Description check ✅ Passed The PR description provides a clear problem statement, identifies the affected endpoints, explains the solution, and specifies the type of change and test plan.

✏️ 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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (2)
internal/handler/streaming.go (2)

26-28: 💤 Low value

Consider logging errors from SetWriteDeadline.

While SetWriteDeadline rarely 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 win

Add 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

📥 Commits

Reviewing files that changed from the base of the PR and between f0efa63 and c86c5e0.

📒 Files selected for processing (4)
  • internal/handler/chat_session.go
  • internal/handler/providers.go
  • internal/handler/streaming.go
  • internal/handler/streaming_test.go

@bitloi

bitloi commented Jun 9, 2026

Copy link
Copy Markdown
Contributor Author

Hi @xugangqiang Ready for review!

@bitloi bitloi changed the title Fix SSE write timeout fix: SSE write timeout Jun 9, 2026
@xugangqiang

Copy link
Copy Markdown
Contributor

@bitloi May I know how to verify the fix? How to make sure there will be no regression issues?

@bitloi

bitloi commented Jun 9, 2026

Copy link
Copy Markdown
Contributor Author

@bitloi May I know how to verify the fix? How to make sure there will be no regression issues?

The fix is verified by TestDisableWriteDeadlineForSSEAllowsLongLivedStream.

That test starts a real httptest.Server with WriteTimeout = 30ms, sends one SSE chunk, sleeps for 120ms, then verifies the client still receives a second SSE chunk. Without clearing the response write deadline, that second write/read path would be cut off by the server write timeout.

For regression safety:

  • the global WriteTimeout in cmd/server_main.go is unchanged;
  • the helper is called only inside existing stream branches, before SSE headers/body are written;
  • non-streaming requests keep the existing timeout behavior;
  • I also ran the full handler package test: /root/go/bin/go test ./internal/handler -count=1.

So the change is limited to long-lived SSE responses and is covered by a focused server-level regression test.

@xugangqiang

Copy link
Copy Markdown
Contributor

@bitloi May I know how to verify the fix? How to make sure there will be no regression issues?

The fix is verified by TestDisableWriteDeadlineForSSEAllowsLongLivedStream.

That test starts a real httptest.Server with WriteTimeout = 30ms, sends one SSE chunk, sleeps for 120ms, then verifies the client still receives a second SSE chunk. Without clearing the response write deadline, that second write/read path would be cut off by the server write timeout.

For regression safety:

  • the global WriteTimeout in cmd/server_main.go is unchanged;
  • the helper is called only inside existing stream branches, before SSE headers/body are written;
  • non-streaming requests keep the existing timeout behavior;
  • I also ran the full handler package test: /root/go/bin/go test ./internal/handler -count=1.

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.

@bitloi

bitloi commented Jun 10, 2026

Copy link
Copy Markdown
Contributor Author

You're right. The current test uses a real httptest.Server, but it only verifies the helper behavior on a synthetic route.

I also noticed that /api/v1/searchbots/ask, which is explicitly mentioned in #15840, is not covered by the PR yet. I’ll update the PR to wire disableWriteDeadlineForSSE(c) into that handler and add an endpoint-level regression test with a short WriteTimeout, so the test exercises a real Ragflow SSE route rather than only the helper.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
internal/handler/searchbot.go (1)

518-519: Unused helper functions in internal/handler/searchbot.go

intPtr (lines 518-519) and floatPtr (lines 518-519) have no call sites (outside *_test.go), so they’re dead/unnecessary. Also, floatPtr duplicates ptrFloat64 at line 516 and can be removed in favor of ptrFloat64.

🤖 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

📥 Commits

Reviewing files that changed from the base of the PR and between 74f8b72 and ab476ec.

📒 Files selected for processing (2)
  • internal/handler/searchbot.go
  • internal/handler/searchbot_test.go

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 in internal/handler/searchbot.go

intPtr (lines 518-519) and floatPtr (lines 518-519) have no call sites (outside *_test.go), so they’re dead/unnecessary. Also, floatPtr duplicates ptrFloat64 at line 516 and can be removed in favor of ptrFloat64.

🤖 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

📥 Commits

Reviewing files that changed from the base of the PR and between 74f8b72 and ab476ec.

📒 Files selected for processing (2)
  • internal/handler/searchbot.go
  • internal/handler/searchbot_test.go
🛑 Comments failed to post (1)
internal/handler/searchbot.go (1)

372-380: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

SSE error written before Content-Type header is set.

At line 373, when modelID is empty, the handler writes an SSE-formatted error via h.sseWriter.Write(), but the Content-Type: text/event-stream header 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.

@bitloi

bitloi commented Jun 10, 2026

Copy link
Copy Markdown
Contributor Author

Updated in ab476ecab.

I added the missing disableWriteDeadlineForSSE(c) call to /api/v1/searchbots/ask, which is the endpoint explicitly mentioned in #15840.

I also added TestAskHandler_DisablesWriteDeadlineForSSE, which exercises the real /api/v1/searchbots/ask handler through a real httptest.Server with WriteTimeout = 30ms. The fake Ask stream sends one chunk, waits 120ms, then sends a second chunk, so this verifies the endpoint-level SSE path can continue beyond the server write timeout.

I ran:

/root/go/bin/go test ./internal/handler -run 'TestAskHandler_DisablesWriteDeadlineForSSE|TestDisableWriteDeadlineForSSEAllowsLongLivedStream' -count=1

and

/root/go/bin/go test ./internal/handler -count=1

@xugangqiang xugangqiang added the ci Continue Integration label Jun 12, 2026
@xugangqiang
xugangqiang marked this pull request as draft June 12, 2026 07:42
@xugangqiang
xugangqiang marked this pull request as ready for review June 12, 2026 07:56
@codecov

codecov Bot commented Jun 12, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (49ef959) to head (b920647).
⚠️ Report is 26 commits behind head on main.

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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@xugangqiang
xugangqiang requested a review from yingfeng June 12, 2026 12:47
@xugangqiang
xugangqiang requested a review from JinHai-CN June 12, 2026 12:47
@xugangqiang

Copy link
Copy Markdown
Contributor

@JinHai-CN @yingfeng LGTM

@yingfeng
yingfeng merged commit cafa0f2 into infiniflow:main Jun 12, 2026
2 checks passed
SailedApple1991 pushed a commit to SailedApple1991/greenlaw-ragflow that referenced this pull request Jun 14, 2026
### 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)
SailedApple1991 added a commit to SailedApple1991/greenlaw-ragflow that referenced this pull request Jun 14, 2026
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.
1BugKiller added a commit to 1BugKiller/ragflow that referenced this pull request Oct 29, 2026
…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
1BugKiller added a commit to 1BugKiller/ragflow that referenced this pull request Oct 29, 2026
…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
1BugKiller added a commit to 1BugKiller/ragflow that referenced this pull request Oct 30, 2026
…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
1BugKiller added a commit to 1BugKiller/ragflow that referenced this pull request Oct 30, 2026
…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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐞 bug Something isn't working, pull request that fix bug. ci Continue Integration size:M This PR changes 30-99 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Go: SSE streaming endpoints can be terminated by WriteTimeout (120s)

3 participants