Skip to content

fix: reuse stream scanner buffer in channel handlers - #5225

Merged
seefs001 merged 1 commit into
QuantumNous:mainfrom
xujiantop-crypto:codex/fix-stream-scanner-buffer-5213
Jun 5, 2026
Merged

fix: reuse stream scanner buffer in channel handlers#5225
seefs001 merged 1 commit into
QuantumNous:mainfrom
xujiantop-crypto:codex/fix-stream-scanner-buffer-5213

Conversation

@xujiantop-crypto

@xujiantop-crypto xujiantop-crypto commented Jun 1, 2026

Copy link
Copy Markdown
Contributor

Summary

  • add a shared helper.NewStreamScanner that applies the existing stream scanner buffer limit
  • update channel-specific stream scanners to use the shared buffered scanner
  • log scanner errors in zhipu/cohere paths instead of silently ending on scanner failures

Fixes #5213

Tests

  • go test ./relay/helper -run TestNewStreamScanner_AllowsLargeStreamLine -count=1
  • go test ./relay/channel/cohere ./relay/channel/zhipu ./relay/channel/cloudflare ./relay/channel/coze ./relay/channel/ollama ./relay/channel/tencent

Note: full go test ./relay/helper still fails on existing TestStreamScannerHandler_StreamStatus_PreInitialized; the focused new scanner test passes.

Summary by CodeRabbit

  • Refactor

    • Unified stream scanning across channels with centralized buffer configuration for more reliable, consistent streaming.
    • Stream scanner initialization standardized to prevent truncated/failed reads.
  • Bug Fixes

    • Improved detection and logging of stream read errors in streaming handlers.
  • Tests

    • Added test validating the scanner handles very large streaming lines without failing.

@coderabbitai

coderabbitai Bot commented Jun 1, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 99cbe733-4dae-42dd-95c0-8c48dbedcf62

📥 Commits

Reviewing files that changed from the base of the PR and between 25871fe and b9a8b42.

📒 Files selected for processing (9)
  • relay/channel/cloudflare/relay_cloudflare.go
  • relay/channel/cohere/relay-cohere.go
  • relay/channel/coze/relay-coze.go
  • relay/channel/ollama/relay-ollama.go
  • relay/channel/ollama/stream.go
  • relay/channel/tencent/relay-tencent.go
  • relay/channel/zhipu/relay-zhipu.go
  • relay/helper/stream_scanner.go
  • relay/helper/stream_scanner_test.go
✅ Files skipped from review due to trivial changes (1)
  • relay/channel/ollama/stream.go
🚧 Files skipped from review as they are similar to previous changes (8)
  • relay/channel/coze/relay-coze.go
  • relay/channel/zhipu/relay-zhipu.go
  • relay/channel/tencent/relay-tencent.go
  • relay/channel/ollama/relay-ollama.go
  • relay/helper/stream_scanner.go
  • relay/channel/cloudflare/relay_cloudflare.go
  • relay/helper/stream_scanner_test.go
  • relay/channel/cohere/relay-cohere.go

Walkthrough

Adds a NewStreamScanner factory that centralizes bufio.Scanner buffer sizing and migrates channel stream handlers to use it; several handlers also add scanner error checks and remove now-unnecessary bufio imports.

Changes

Stream Scanner Consolidation

Layer / File(s) Summary
Stream scanner helper factory and tests
relay/helper/stream_scanner.go, relay/helper/stream_scanner_test.go
Adds NewStreamScanner(reader io.Reader) that wraps bufio.NewScanner and applies configurable buffer sizing; refactors StreamScannerHandler to use it and adds TestNewStreamScanner_AllowsLargeStreamLine.
Simple channel scanner migrations
relay/channel/cloudflare/relay_cloudflare.go, relay/channel/coze/relay-coze.go, relay/channel/tencent/relay-tencent.go
Cloudflare, Coze, and Tencent stream handlers now call helper.NewStreamScanner(resp.Body) instead of bufio.NewScanner(resp.Body).
Ollama scanner migrations and import updates
relay/channel/ollama/relay-ollama.go, relay/channel/ollama/stream.go
Ollama relay files migrate to helper.NewStreamScanner(resp.Body) and remove bufio imports; both model-pull and main stream handlers updated.
Advanced migrations with error handling
relay/channel/cohere/relay-cohere.go, relay/channel/zhipu/relay-zhipu.go
Cohere and Zhipu adopt helper.NewStreamScanner and add post-scan scanner.Err() checks; Cohere also removes the bufio import.

Possibly related PRs

  • QuantumNous/new-api#2335: Introduced constant.StreamScannerMaxBufferMB that this PR leverages for scanner buffer sizing.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰
Streams once trimmed by a tiny line cap,
Now buffered wide — no more sudden gap.
NewScanner hums, each long line it will meet,
Carrots and bytes flow steady and sweet.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 13.33% 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
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'fix: reuse stream scanner buffer in channel handlers' accurately summarizes the main change: refactoring multiple channel handlers to use a centralized stream scanner helper.
Linked Issues check ✅ Passed All coding objectives from issue #5213 are met: channel handlers now use the shared helper.NewStreamScanner, scanner errors are logged in zhipu and cohere paths, and buffer limits are consistently applied across all affected channels.
Out of Scope Changes check ✅ Passed All changes are directly scoped to addressing issue #5213: creating the helper function, updating channel handlers to use it, and adding error checking.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

@xujiantop-crypto
xujiantop-crypto force-pushed the codex/fix-stream-scanner-buffer-5213 branch from 25871fe to b9a8b42 Compare June 4, 2026 02:25
@seefs001
seefs001 merged commit 3280584 into QuantumNous:main Jun 5, 2026
1 check passed
Soein added a commit to Soein/new-api that referenced this pull request Jun 6, 2026
… id 等)

主要变更(QuantumNous/new-api → adc390c):
- feat: 渠道被禁用后可配置是否清空渠道粘性 (QuantumNous#5306)
- feat(web): profile 页显示 user id (QuantumNous#5317)
- fix: 复用 channel handler 的 stream scanner buffer (QuantumNous#5225)
- fix: 收窄 OpenAI o 系列模型适配范围 (QuantumNous#5293)
- fix(relay): GLM Anthropic 兼容避免 chunked encoding (QuantumNous#5307)
- fix: 新增 relay idle 连接超时配置 (QuantumNous#5309)
- fix: 限制匿名请求体大小 (QuantumNous#5244)
- fix(distributor): 修复 video generations task_id 模型解析 (QuantumNous#5133)
- fix(dify): 远程图片字段赋值前初始化 file pointer (QuantumNous#5134)
- fix(i18n): 优化 thinking adapter 文案 (QuantumNous#5242)

去合规一致性:上游未触及任何合规文件,合并完整保留本地去合规状态
(payment_setting.go / payment-settings-section.tsx / recharge-form-card.tsx /
risk-acknowledgement-dialog.tsx 均未被改动)。

i18n:web/default 6 语言(en/zh/fr/ja/ru/vi)key 并集三路合并 + i18n:sync
规范化,4584 keys/语言,missing/extras/untranslated 全为 0。

验证:go build ./... ✅ + bun run typecheck ✅
Ember-Moth pushed a commit to Ember-Moth/new-api that referenced this pull request Jun 7, 2026
szxufan pushed a commit to szxufan/new-api that referenced this pull request Jun 9, 2026
52assert added a commit to 52assert/new-api that referenced this pull request Jun 10, 2026
…codes

* origin/main: (45 commits)
  fix(openai): support streaming image relay and image edit for images API  (QuantumNous#4608)
  perf(web): improve dialog sizing and footer layout
  feat(web): add shared dialog wrapper
  perf(web): simplify public page hero copy
  perf(model-pricing): move pricing tabs into page title
  feat(json-editor): add reusable JSON code editor
  perf(model-pricing): improve JSON pricing editor layout
  perf(model-pricing): reduce duplicate model name display
  fix: support six-decimal steps in model pricing editor
  fix: respect theme for multiselect combobox popover
  fix: reuse stream scanner buffer in channel handlers (QuantumNous#5225)
  fix: 收窄 OpenAI o 系列模型适配范围 (QuantumNous#5293)
  fix(i18n): clarify thinking adapter copy (QuantumNous#5242)
  fix: limit anonymous request body (QuantumNous#5244)
  fix(relay): fix Anthropic-compatible compatibility for GLM (avoid chunked encoding) (QuantumNous#5307)
  feat: 支持配置渠道被禁用后是否清空渠道粘性 (QuantumNous#5306)
  fix: add relay idle connection timeout config (QuantumNous#5309)
  feat(web): show user id on profile page
  perf(model-pricing): refine visual editor actions
  refactor(model-pricing): split visual pricing editor modules
  ...

# Conflicts:
#	router/api-router.go
#	web/default/src/features/usage-logs/components/usage-logs-mobile-card.tsx
endercat-alu pushed a commit to endercat-alu/new-api that referenced this pull request Jun 10, 2026
OuYang-HX pushed a commit to OuYang-HX/new-api that referenced this pull request Jun 13, 2026
ruanhangjian pushed a commit to ruanhangjian/new-api that referenced this pull request Jul 11, 2026
zhaodechao2008 pushed a commit to zhaodechao2008/new-api that referenced this pull request Jul 27, 2026
330079598 pushed a commit to 330079598/new-api that referenced this pull request Aug 19, 2026
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.

[Bug] 部分 channel 自建 bufio.Scanner 未设置 buffer,长流式响应可能 token too long 或静默结束

2 participants