Skip to content

fix(relay): end the stream on a bare [DONE] line in StreamScannerHandler - #8036

Closed
AiFLYF wants to merge 1 commit into
QuantumNous:mainfrom
AiFLYF:fix/stream-scanner-bare-done
Closed

AiFLYF wants to merge 1 commit into
QuantumNous:mainfrom
AiFLYF:fix/stream-scanner-bare-done

Conversation

@AiFLYF

@AiFLYF AiFLYF commented Oct 26, 2026 •

Copy link
Copy Markdown

一句话:StreamScannerHandler 对每个被接受的 SSE 行无条件执行 data = data[5:],裸 [DONE] 行被切成 ] 并当作数据帧转发,扫描也不在结束符处停止;本 PR 把这一步改成只去掉可选的 data: 前缀(1 行),裸 [DONE] 与 data: [DONE] 行为一致。

是不是重复:main 上该缺陷仍在(relay/helper/stream_scanner.go);同题的 #7932 已被维护者关闭、#6798 属于另一个 issue 且停更 2 个月,详见「Research → Duplicate / prior art」。


Agent

  • Tool: Qoder
  • Tool version: 0.4.11
  • Model (full id): MiniMax-M3.1-Flash
  • Host (CLI / IDE / GitHub coding agent / other): Qoder Desktop (IDE)
  • Date (UTC): 2026-10-26

Links

User request

Quote the request the user made to the agent as faithfully as possible.
Keep the original language and line breaks. Do not rewrite, summarize,
translate, or turn it into a PR description.

  • Verbatim:
# 角色
你是一名经验丰富的开源贡献者助手,帮我为一个开源项目寻找"值得提、会被合并"的 PR 机会。
目标是高质量、小而准的贡献,而不是数量。

# 项目信息
- 目标仓库:QuantumNous/new-api
- 我的 fork 已克隆在当前目录,远程名:origin(我的 fork)、upstream(官方仓库)

# 硬性规则
1. 阶段一到阶段三是【只读】:不修改任何文件、不创建分支、不提交、不评论、不 push。
2. 在我明确回复"做第 N 个"之前,不得进入阶段五。
3. 不得在 issue 或 PR 下替我发评论,所有对外动作必须由我确认包括提交等操作!!!。
4. 遇到不确定的地方,写进报告让我决定,不要猜。
5. 不编造信息:每个结论必须附上来源(文件路径+行号,或 issue/PR 链接)。

# 阶段五:实现(仅在我选定后)
1. 从 upstream 最新主分支创建分支:{类型}/{简短描述}
2. 改动最小化:只改与该问题直接相关的内容,不顺手重构、不改无关格式。
3. 严格遵循项目现有代码风格,不引入新依赖。
4. 必须补充或更新测试;修 bug 要先写能复现 bug 的失败测试。
5. 运行测试、lint、格式化,结果与阶段一基线对比,确保没有新增失败。
6. commit message 遵循项目规范。
7. 生成 PR 草稿(标题+正文,按项目模板),正文包含:
   - 关联 issue(Fixes #123)
   - 改了什么、为什么
   - 如何测试
   - 如项目要求或鼓励,如实说明本 PR 有 AI 辅助
8. 先把 diff 和 PR 草稿给我审阅,【不要自己执行 git push 或 gh pr create】。
  • Later constraints or corrections from the user (quote, or none):
允许安装依赖,你可以先在本地测试验证看看有没有错误问题是否真实存在,怎么修复修复成功了验证它,确认检查然后再统一汇报给我,允许子代理并行
可以的,分为多个pr提交,先确认验证在我自己仓库里面跑验证测试先但没有我的确认不允许提交pr:https://github.com/AiFLYF/new-api
可提,需说明重叠是什么意思,另外优先提是确认可行吗,确认成功问题问题属实!

Out of scope — refuse

If the change matches any item below, tell the user this repository does not
accept it and do not open a PR.

  • Matched: no
  • If yes, what was told the user (stop here; do not open a PR): 不适用

Open gate — do not open unless all are satisfied

If any item fails, tell the user and stop. Do not open the PR.

  • Out of scope (including pass-through-only forwarding): no
  • Usage / configuration / integration (answered instead of opening): no
  • Required issue facts present without invention: yes
  • Verification is actual commands or steps and observed results, not only go build or tests passed: yes
  • Body is short and factual; no unfiltered AI-generated text: yes
  • Open: yes
  • If no, what was told the user (stop here): 不适用

Kind

  • Bug fix
  • New feature
  • Performance / refactor
  • Docs
  • Other:

Issue facts

Take these from the linked issue. If a needed item is empty, ask the user that question.

  • Actual behavior: relay/helper/stream_scanner.go 的 StreamScannerHandler 对每个被接受的 SSE 行无条件执行 data = data[5:]。裸 [DONE] 行(无 data: 前缀)会被切成 "]" 并作为一帧转发给客户端,扫描循环也不在 [DONE] 处结束。
  • Impact: 流在 [DONE] 后继续扫描;客户端在正常数据帧之外多收到一个内容为 "]" 的帧。
  • Frequency: 每当上游以裸 [DONE] 行(SSE 允许的形式)结束流时触发。
  • Evidence that the problem is in new-api rather than the client or upstream: 切片逻辑位于 new-api 的 stream_scanner.go,不依赖客户端或某个具体上游;用本地 StreamScannerHandler 单测即可复现。
  • Applicable types and their fields (relay / billing / frontend / deployment; write "not applicable" otherwise): relay(relay/helper/stream_scanner.go,各 chat/completions 流式端点的公共路径,任意流式模型,SSE,透传未开启);billing、frontend、deployment 不适用。

Change

relay/helper/stream_scanner.go 的扫描循环里,先用 data[:5] != "data:" && data[:6] != "[DONE]" 过滤出可接受的行(relay/helper/stream_scanner.go:304),然后无条件执行 data = data[5:](原第 307 行)。

SSE 允许省略字段名,因此 [DONE] 可以裸写:

  • data: [DONE] → 去掉 data: 后为 [DONE],被 strings.HasPrefix(data, "[DONE]") 识别为结束符(relay/helper/stream_scanner.go:312),扫描终止。
  • [DONE](裸行)→ 被切成 ],HasPrefix("[DONE]") 不成立,于是 ] 被当成一帧数据 dataChan <- data 转发给客户端,扫描循环也不会在结束符处返回。

本 PR 把 data = data[5:] 换成 data = strings.TrimPrefix(data, "data:"):

  • 带 data: 前缀的行:TrimPrefix 只去掉字段名,剩下的载荷与原来 data[5:] 的结果完全一致(包括 data: 后面带空格的情况,后面紧跟 strings.TrimSpace)。
  • 裸 [DONE] 行:没有 data: 前缀可去,TrimPrefix 原样返回 [DONE],于是能被第 312 行的结束符判断识别,扫描在正确的地方终止,] 不会再被转发。

其余逻辑(长度守卫 len(data) < 6、空行跳过、ReceivedResponseCount 统计、结束原因 StreamEndReasonDone)保持不变。改动只涉及 1 行有效代码。

Research

Duplicate / prior art

Docs and code

Open them. Do not write "already checked" without sources.

  • https://docs.newapi.ai/ :
    • 站点导航为 Installation / Administration / API Reference / AI Applications / Skills / Help,没有 SSE 或流式转发的页面。
    • https://docs.newapi.ai/en/docs/api/ai-model/chat/openai/createchatcompletion、https://docs.newapi.ai/en/docs/api/ai-model/chat/createmessage(及中文版):未提及 data: 帧格式或 [DONE]。
    • https://docs.newapi.ai/llms.txt(全站页面索引):全站没有 SSE/streaming 说明页。
  • https://deepwiki.com/QuantumNous/new-api : 不可访问,6 次尝试均返回 HTTP 429,未取到任何内容。
  • README / repo docs:
    • README.md:138:「Use OpenAI Chat Completions, Responses, Anthropic Messages, and Gemini APIs; stream responses and use tools…」;:157 提到 RelayKit「provides request, response, and streaming conversion」——README 只说明支持流式,不规定帧格式。
    • docs/plugin-api/v1.md:558「### Optional SSE response reader」与 :624「### Optional host-managed SSE accumulation」讲的是宿主 → 插件的提交流,不是上游 → 客户端的转发路径。
    • docs/openapi/relay.json:未定义 SSE 帧格式。
  • Code paths and what they imply for this change:
    • relay/helper/stream_scanner.go:301:if len(data) < 6 { continue }——所以 data[:6] 不会越界panic,本 issue 不是安全问题。
    • relay/helper/stream_scanner.go:304:先按 data[:5] != "data:" && data[:6] != "[DONE]" 放行,说明代码本身已经认为裸 [DONE] 是合法输入;问题出在紧接着的无条件切片。
    • relay/helper/stream_scanner.go:312:strings.HasPrefix(data, "[DONE]") 才是真正的终止符判断,说明下游本来就按「去掉前缀后的内容」来识别终止符,与本 PR 的改法一致。
    • 仓库内既有惯例也把裸 [DONE] 当终止符:relay/channel/openai/chat_via_responses.go:79(if data == "" || data == "[DONE]")、relay/channel/cloudflare/relay_cloudflare.go:50(if data == "[DONE]")、controller/channel-test.go:626,649(bytes.Equal(payload, []byte("[DONE]"))。本 PR 的改法与这些位置的行为对齐。

Alternatives considered

  • Option A: 先判断是不是裸 [DONE],是则直接走终止符分支,否则照旧切 5 字节(把判断上移到 :304)。
  • Option B: 把无条件切片换成 strings.TrimPrefix(data, "data:")(本次采用)。
  • Why this approach: Option A 需要新增一个分支并让 data[:6] != "[DONE]" 的判断结果参与后续流程,代码更长;Option B 一行即可,且 TrimPrefix 的语义恰好是「有 data: 前缀才去掉」,与 SSE 里字段名可省略的规则一致。两种写法对 data: [DONE] 与普通 data: {...} 行的行为完全相同,Option B 的额外风险为零。

Files

Path Why
relay/helper/stream_scanner.go 把无条件切 5 字节换成只去掉可选的 data: 字段名,1 行
relay/helper/stream_scanner_test.go 新增 TestStreamScannerHandler_BareDoneStopsStream(裸 [DONE] 与 data: [DONE] 两种形式)与 TestStreamScannerHandler_PayloadPreservedVerbatim(载荷不被改写)

Behavior

  • Before: 上游以裸 [DONE] 行结束时,客户端会额外收到一帧内容为 ] 的数据;扫描器不在结束符处停止,继续读上游剩余内容。
  • After: 裸 [DONE] 与 data: [DONE] 行为一致,都在结束符处终止扫描并置结束原因为 StreamEndReasonDone,客户端只收到真实数据帧。
  • Explicit non-goals / leftover work: 不改写客户端侧下发的帧格式,不动其它 SSE 解析路径,不改 data: 前缀的转发形式。

Verification

Only what was actually run. Do not state only that go build or tests passed.
Each item needs the command or steps and the observed result.

  • Commands and results:
    • go vet ./...(根模块)→ 退出码 0,无输出。
    • go build ./...(根模块)→ 退出码 0。(main.go:44 的 //go:embed web/dist 需要 web/dist/index.html,本地按 CI 的做法先建占位文件;web/dist 被 .gitignore 忽略,不在提交里。)
    • go test ./relay/helper -count=1 → ok github.com/QuantumNous/new-api/relay/helper 5.891s(含新增的两个测试)。
    • go test ./... -count=1(根模块全量)→ 除 controller 外全部 ok;controller 的失败见「Not verified」。
    • relaykit 模块:GOWORK=off go vet ./... → 0;GOWORK=off go build ./... → 0;GOWORK=off go test ./... -count=1 → 0。
    • tokenkit 模块:GOWORK=off go vet ./... → 0;GOWORK=off go build ./... → 0;GOWORK=off go test ./... -count=1 → 0。
    • gofmt -l relay/helper/stream_scanner.go relay/helper/stream_scanner_test.go → 无输出。
  • Manual steps and observed result:
    • 新增测试 TestStreamScannerHandler_BareDoneStopsStream 用响应体 data: {"x":1}\n\n[DONE]\n\ndata: should_not_appear\n\n 走 StreamScannerHandler,断言只收到 ["{\"x\":1}"]、结束原因为 done、ReceivedResponseCount == 1;子测试分别覆盖裸 [DONE] 与 data: [DONE] 两种写法。
    • 复现确认:把 relay/helper/stream_scanner.go 换回 main 版本、保留新测试后重跑 → FAIL,实际收到 ["{\"x\":1}", "]", "should_not_appear"]——正是 issue 流式转发:裸 [DONE] 行未按结束处理,被切成 "]" 作为数据帧下发 #7929 描述的「多收到一帧 ]」且「[DONE] 之后继续扫描」。改回本 PR 的版本后 → PASS。
    • 另外用 TestStreamScannerHandler_PayloadPreservedVerbatim 确认带 data: 前缀的载荷在改动后逐字节不变(TrimPrefix 不会动到载荷内容)。
    • 顺带在 main 上叠加 PR fix(relay): forward bare-JSON stream frames without "data:" prefix #6798 的改动跑同一条测试命令 → 两个子测试同样 PASS(说明 fix(relay): forward bare-JSON stream frames without "data:" prefix #6798 也覆盖本 bug,见「Research」中的重复性说明),go test ./relay/helper -count=1 也全部通过。
  • UI: screenshot or recording (or why none): 无 UI 改动,不适用。
  • Tests added or updated, or why none: 新增两个测试,原有测试未改动。
  • Databases / providers / platforms exercised: 无数据库、不连上游——测试用 httptest 构造响应体直接驱动扫描器。
  • Not verified:
    • 未做真实上游 SSE 端到端抓包(需要能发出裸 [DONE] 的上游);测试在 handler 层用构造的响应体覆盖。
    • 根模块全量 go test ./... -count=1 在 Windows 上只有 controller 包失败(52 个测试),报错为 TempDir RemoveAll cleanup: unlinkat ...\audit.db: The process cannot access the file because it is being used by another process——sqlite 文件锁在临时目录清理阶段的 Windows 专有问题。在未修改的 main 上单独跑 go test ./controller/... -count=1 得到同一批失败(同一批测试名、同一原因),本 PR 未触碰 controller 涉及的任何代码。
    • 本次全量跑里 relay/channel 包整体 ok;同批测试在另两次并行跑中出现过 TestUpstreamGetBody_HTTP2* 失败(Windows socket 报错 An established connection was aborted by the software in your host machine),单独跑 go test ./relay/channel -run 'TestUpstreamGetBody' -count=1 → 4 个测试全部 PASS,属并行负载下的抖动,与本改动无关。

Risks

Scope check

  • Single focused change: yes
  • Secrets included: no
  • Out of scope (Coding Plan / reverse-engineered channel / third-party wrapper / Codex / pass-through-only forwarding): no

StreamScannerHandler accepted a line starting with "[DONE]" but then sliced
five bytes off every accepted line, turning a bare "[DONE]" into "]" that was
forwarded as a data frame while the scanner kept reading past the end of the
stream. Trim only the optional "data:" field name so both forms reach the
terminator check.
@coderabbitai

coderabbitai Bot commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

No actionable comments were generated in the recent review.

Recent review info
Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 552b5030-f381-486d-9cb9-55cff180d6d0
Commits

Reviewing files that changed from the base of the PR and between 34003e9 and 9ab2f9f.

Files selected for processing: 2
  • relay/helper/stream_scanner.go
  • relay/helper/stream_scanner_test.go

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.

Walkthrough

The stream scanner now removes the data: prefix only when present. Bare [DONE] lines reach the existing terminator check. Tests cover both terminator forms and verify that payload contents and whitespace remain unchanged.

Changes

Stream terminator handling

Layer / File(s) Summary
Scanner handling and tests
relay/helper/stream_scanner.go, relay/helper/stream_scanner_test.go
The scanner removes only an optional data: prefix. Tests verify that bare and prefixed [DONE] lines stop the stream after the preceding payload, and that payload whitespace is preserved.

Priority: Normal

Estimated code review effort: 2 (Simple) | ~10 minutes

Change: Bug fix · Severity of issue fixed: Medium

Suggested reviewers: calcium-ion

Merge Risk: Minimal · up to 9ab2f

The change appears ready to merge after normal checks; no outstanding issue is identified.

Pre-merge checks: Passed 4 · Failed 1

Failed 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%. Docstring coverage is scoped to functions touched by this diff. Analyzed 5 functions across 2 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title names the main change: the stream scanner now ends the stream when it reads a bare [DONE] line in StreamScannerHandler. It also names the affected area, relay. The raw summary and objectives…
Linked Issues check Passed Issue #7929 requires that a bare [DONE] line end the scan and not be forwarded as a ] data frame. At the base, StreamScannerHandler (relay/helper/stream_scanner.go, around line 304-307) accepts …
Out of Scope Changes check Passed The whole-PR diff against the merge base touches two files. relay/helper/stream_scanner.go changes one statement, data = data[5:] to strings.TrimPrefix(data, "data:"), and adds a 3-line comment th…
Full details: Title check

Explanation

The title names the main change: the stream scanner now ends the stream when it reads a bare [DONE] line in StreamScannerHandler. It also names the affected area, relay. The raw summary and objectives both describe the stream terminator fix in relay/helper/stream_scanner.go as the core change, with tests added for bare and prefixed [DONE] lines. The title is specific, concise, and free of noise. The fix: prefix removal is now optional, so bare [DONE] lines reach the existing terminator check.

Full details: Linked Issues check

Explanation

Issue #7929 requires that a bare [DONE] line end the scan and not be forwarded as a ] data frame. At the base, StreamScannerHandler (relay/helper/stream_scanner.go, around line 304-307) accepts a bare [DONE] line, because data[:6] == "[DONE]" passes the gate. It then runs data = data[5:] unconditionally, which yields ]. That value is not [DONE]-prefixed, so it is sent to dataChan. At head the line is data = strings.TrimPrefix(data, "data:"). A bare [DONE] stays intact and reaches the strings.HasPrefix(data, "[DONE]") check, which sets StreamEndReasonDone and returns. For data:-prefixed lines, TrimPrefix removes the same 5 bytes that data[5:] removed, so payload handling is unchanged. The len(data) &lt; 6 guard and the empty-line skip are unchanged. The issue's reproduction body (data: {"id":1}, [DONE], data: {"id":2}) now forwards only {"id":1} and stops. Tests in relay/helper/stream_scanner_test.go cover this: TestStreamScannerHandler_BareDoneStopsStream (bare and data: [DONE] forms, asserting one delivered frame, StreamEndReasonDone, and ReceivedResponseCount == 1) and TestStreamScannerHandler_PayloadPreservedVerbatim. The test results in the PR description were not re-run in this review. The conclusion rests on source reading of the diff and the loop logic.

Full details: Out of Scope Changes check

Explanation

The whole-PR diff against the merge base touches two files. relay/helper/stream_scanner.go changes one statement, data = data[5:] to strings.TrimPrefix(data, "data:"), and adds a 3-line comment that explains the change. relay/helper/stream_scanner_test.go adds two tests for the same bare [DONE] termination and payload preservation for data: lines. Both changes connect directly to #7929. The tests support the fix and are not unrelated work. The diff does not change the accepted-line gate, client frame formatting, pass-through paths, or other SSE parsing. The PR description refers to related PRs (#8023, #7777, #6798), but the reviewed code does not include their changes. Their presence or absence does not affect this assessment.

Finishing Touches
🧪 Generate unit tests (beta)
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Warning

⚠️ This pull request shows signs of AI-generated slop (ai_padded_prose). It has been flagged by CodeRabbit slop detection and should be reviewed carefully.

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

A rabbit watched the data flow,
Then saw the bare [DONE] line glow.
The stream stops where the marker lies,
No stray bracket hops outside.
Payload spaces stay as they go.

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

流式转发:裸 [DONE] 行未按结束处理,被切成 "]" 作为数据帧下发

2 participants