Skip to content

fix(relay): retry on another channel when stream times out with no response - #4060

Closed
0-don wants to merge 1 commit into
QuantumNous:mainfrom
0-don:fix/stream-timeout-retry
Closed

0-don wants to merge 1 commit into
QuantumNous:mainfrom
0-don:fix/stream-timeout-retry

Conversation

@0-don

@0-don 0-don commented Apr 2, 2026 •

Copy link
Copy Markdown
Contributor

📝 变更描述 / Description

When an upstream provider accepts a streaming connection (HTTP 200) but never sends any tokens, the stream eventually times out via STREAMING_TIMEOUT. Previously this was silently treated as success (zero tokens, $0 billed) because StreamScannerHandler returned no error and shouldRetry never triggered. Users saw a hung response, no retry, and no error log.

Fix. StreamScannerHandler now returns a *types.NewAPIError when the stream ends with a retriable reason (timeout, scanner error, ping failure, or panic) and zero tokens were sent to the client (ReceivedResponseCount == 0). The error carries a channel: prefix and HTTP 502, which IsChannelError / shouldRetry recognize so the retry loop tries the next available channel automatically.

If any tokens were already streamed (ReceivedResponseCount > 0), HTTP headers and partial data are flushed and retry is impossible, so no error is returned and the request settles as-is. 502 is intentional: 504 is in AlwaysSkipRetryStatusCodes, while 502 is semantically correct for upstream-not-responding and goes through the retry path.

The fix is applied uniformly across every adaptor that uses StreamScannerHandler (OpenAI / Claude / Gemini / Baidu / Dify / xAI, plus OpenAI audio and responses paths). Tests are added in relay/helper/stream_scanner_test.go covering the new error contract.

🚀 变更类型 / Type of change

  • 🐛 Bug 修复 (Bug fix)

🔗 关联任务 / Related Issue

✅ 提交前检查项 / Checklist

  • 人工确认: 我已亲自整理并撰写此描述,没有直接粘贴未经处理的 AI 输出。
  • 非重复提交: 我已搜索现有的 Issues 与 PRs,确认不是重复提交。
  • Bug fix 说明: 若此 PR 标记为 Bug fix,我已提交或关联对应 Issue,且不会将设计取舍、预期不一致或理解偏差直接归类为 bug。
  • 变更理解: 我已理解这些更改的工作原理及可能影响。
  • 范围聚焦: 本 PR 未包含任何与当前任务无关的代码改动。
  • 本地验证: 已在本地运行并通过测试或手动验证,维护者可以据此复核结果。
  • 安全合规: 代码中无敏感凭据,且符合项目代码规范。

📸 运行证明 / Proof of Work

Backend: go build -o /dev/null . passes. relay/helper/stream_scanner_test.go passes (covers the new error contract).

Frontend: cd web/default && bun run build passes (no frontend changes in this PR).

Functional verification:

  • Configure a channel pointing at an upstream that accepts the connection but never streams tokens; send a streaming request: stream times out, retry kicks in, the next available channel serves the response.
  • Configure a partial-response channel (some tokens then hang): no retry attempted, error logged, headers already flushed.
  • Healthy streaming requests are unaffected.

@coderabbitai

coderabbitai Bot commented Apr 2, 2026 •

Copy link
Copy Markdown
Contributor

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

Walkthrough

StreamScannerHandler now returns a retriable-aware error; multiple channel stream handlers were updated to capture and propagate that scanner error (returning early on non-nil). StreamStatus gained IsRetriable to classify retriable end reasons. Tests and HTTP client timeout handling were also adjusted.

Changes

Cohort / File(s) Summary
Stream Scanner Core
relay/helper/stream_scanner.go, relay/helper/stream_scanner_test.go
StreamScannerHandler signature changed to return *types.NewAPIError. Adds post-stream logic to return a retriable channel:stream_timeout_no_response error when info.StreamStatus.IsRetriable() && info.ReceivedResponseCount == 0. Tests updated to capture the return value.
Stream Status Utility
relay/common/stream_status.go
Added (*StreamStatus) IsRetriable() bool to classify retriable end reasons (timeout, scanner_error, ping_fail, panic).
Channel Stream Handlers
relay/channel/baidu/relay-baidu.go, relay/channel/claude/relay-claude.go, relay/channel/dify/relay-dify.go, relay/channel/gemini/relay-gemini.go, relay/channel/openai/relay-openai.go, relay/channel/openai/chat_via_responses.go, relay/channel/openai/relay_responses.go, relay/channel/xai/text.go
Stream handlers now capture the error returned by StreamScannerHandler (e.g., streamErr) and, when non-nil, close the response and return the scanner error immediately, skipping post-stream finalization and usage computation.
OpenAI TTS streaming path
relay/channel/openai/audio.go
In the TTS streaming branch the scanner call result is explicitly captured/assigned (_ = ...) preserving prior behavior (no propagation).
HTTP Client Timeout Handling
service/http_client.go
Switched from per-client http.Client.Timeout to configuring http.Transport.ResponseHeaderTimeout when common.RelayTimeout > 0; unified client creation paths and removed previous per-client Timeout assignments.

Sequence Diagram(s)

sequenceDiagram
    participant Client as Client
    participant Relay as RelayHandler
    participant Upstream as Upstream
    participant Scanner as StreamScanner
    participant Service as Service

    Client->>Relay: send streaming request
    Relay->>Upstream: forward request
    Upstream-->>Relay: streaming HTTP response (resp)
    Relay->>Scanner: StreamScannerHandler(resp, info, dataHandler)
    Scanner->>Relay: invoke dataHandler per chunk
    Scanner-->>Relay: returns error or nil
    alt streamErr != nil
        Relay->>Service: CloseResponseBodyGracefully(resp)
        Relay-->>Client: return error (streamErr)
    else streamErr == nil
        Relay->>Service: extract usage / finalize
        Relay-->>Client: return success + usage
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • fix: deepseek claude response #1833: Modifies dispatch to call Claude handlers directly — related to changed Claude stream handler error propagation.
  • Revert 1385 patch 1 #1472: Changes to relay/helper/stream_scanner.go behavior/end handling — overlaps with the scanner return-value and retriable logic.

Suggested reviewers

  • seefs001
  • Calcium-Ion

Poem

🐰 I nibble codes on moonlit keys,
I watch the silent streaming seas.
When quiet upstream leaves no sound,
I hop and mark the error found.
Retry I prod with tiny paws, unbound.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 13.51% 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(relay): retry on another channel when stream times out with no response' accurately and specifically describes the main change: implementing retry logic when streaming times out without tokens.
Linked Issues check ✅ Passed The pull request fully addresses the objectives from issue #2989: it detects empty streams ending for retriable reasons (timeout, scanner error, etc.) and triggers retry logic via error propagation, preventing silent success and enabling fallback to other channels.
Out of Scope Changes check ✅ Passed All changes are in-scope: StreamStatus.IsRetriable() identifies retriable stream failures; StreamScannerHandler returns errors for timeout/no-response cases; handlers propagate errors enabling retry; http_client.go updates support timeout configuration for the retry mechanism.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

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

@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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
relay/channel/openai/audio.go (1)

38-53: ⚠️ Potential issue | 🟡 Minor

OpenaiTTSHandler should return an error like all other channel handlers.

Unlike other handlers (Claude, Gemini, STT, chat, Rerank, etc.), OpenaiTTSHandler has a signature that returns only *dto.Usage with no error. This means it cannot propagate the error from StreamScannerHandler to the caller at line 619, preventing the retry loop from triggering for transient failures.

All comparable handlers return (*dto.Usage, *types.NewAPIError) or (*types.NewAPIError, *dto.Usage) and are called with error capture (e.g., err, usage = OpenaiSTTHandler(...) at line 623). The TTS handler should follow this same pattern.

Change the function signature to func OpenaiTTSHandler(...) (*dto.Usage, *types.NewAPIError) to align with other handlers and allow proper error propagation.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@relay/channel/openai/audio.go` around lines 38 - 53, OpenaiTTSHandler
currently returns only *dto.Usage and swallows streaming errors; change its
signature to func OpenaiTTSHandler(...) (*dto.Usage, *types.NewAPIError) and
propagate any errors from helper.StreamScannerHandler back to the caller as a
*types.NewAPIError (create/convert from the sr.Error or returned error in the
StreamScannerHandler callback). Ensure the callback passed to
helper.StreamScannerHandler sets/collects the error and that OpenaiTTSHandler
returns (nil, newAPIErr) when an error occurred, otherwise return (usage, nil)
so callers that expect (err, usage) can trigger retries.
🧹 Nitpick comments (1)
relay/helper/stream_scanner_test.go (1)

533-533: Add assertions for the new return-value contract.

At Line 533 (and similarly across this file), the returned error is discarded. Please add explicit tests for:

  1. abnormal end with zero chunks ⇒ non-nil channel:* retriable error,
  2. abnormal end after at least one chunk ⇒ nil error.
    This protects the new retry behavior from regressions.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@relay/helper/stream_scanner_test.go` at line 533, Update tests that call
StreamScannerHandler (e.g., the call at the line using StreamScannerHandler(c,
resp, info, func(data string, sr *StreamResult) {})) to capture its returned
error instead of discarding it, and add two assertions: simulate an abnormal end
with zero chunks and assert the returned error is a non-nil retriable channel
error (match error type or message like "channel:*"), and simulate an abnormal
end after at least one chunk and assert the returned error is nil; use the same
StreamScannerHandler invocation and StreamResult hook to produce the
chunk/no-chunk scenarios so the new retry contract is covered across the file.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@relay/helper/stream_scanner.go`:
- Around line 304-308: The returned channel error in the
types.NewErrorWithStatusCode call currently uses http.StatusGatewayTimeout (504)
which prevents the orchestration from treating it as a retriable channel error;
update the status code to http.StatusBadGateway (502) in the
types.NewErrorWithStatusCode invocation (the one that wraps fmt.Errorf("stream
failed without response: %s", info.StreamStatus.Summary())) in stream_scanner.go
so the error emits a 502 and matches the existing retry/fallback contract.

---

Outside diff comments:
In `@relay/channel/openai/audio.go`:
- Around line 38-53: OpenaiTTSHandler currently returns only *dto.Usage and
swallows streaming errors; change its signature to func OpenaiTTSHandler(...)
(*dto.Usage, *types.NewAPIError) and propagate any errors from
helper.StreamScannerHandler back to the caller as a *types.NewAPIError
(create/convert from the sr.Error or returned error in the StreamScannerHandler
callback). Ensure the callback passed to helper.StreamScannerHandler
sets/collects the error and that OpenaiTTSHandler returns (nil, newAPIErr) when
an error occurred, otherwise return (usage, nil) so callers that expect (err,
usage) can trigger retries.

---

Nitpick comments:
In `@relay/helper/stream_scanner_test.go`:
- Line 533: Update tests that call StreamScannerHandler (e.g., the call at the
line using StreamScannerHandler(c, resp, info, func(data string, sr
*StreamResult) {})) to capture its returned error instead of discarding it, and
add two assertions: simulate an abnormal end with zero chunks and assert the
returned error is a non-nil retriable channel error (match error type or message
like "channel:*"), and simulate an abnormal end after at least one chunk and
assert the returned error is nil; use the same StreamScannerHandler invocation
and StreamResult hook to produce the chunk/no-chunk scenarios so the new retry
contract is covered across the file.
🪄 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: b1f81ca0-ed9d-485e-bdf5-f54ed39a3512

📥 Commits

Reviewing files that changed from the base of the PR and between c9611c4 and cca5a4e.

📒 Files selected for processing (12)
  • relay/channel/baidu/relay-baidu.go
  • relay/channel/claude/relay-claude.go
  • relay/channel/dify/relay-dify.go
  • relay/channel/gemini/relay-gemini.go
  • relay/channel/openai/audio.go
  • relay/channel/openai/chat_via_responses.go
  • relay/channel/openai/relay-openai.go
  • relay/channel/openai/relay_responses.go
  • relay/channel/xai/text.go
  • relay/common/stream_status.go
  • relay/helper/stream_scanner.go
  • relay/helper/stream_scanner_test.go

Comment thread relay/helper/stream_scanner.go Resolved

@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

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@relay/channel/claude/relay-claude.go`:
- Around line 890-897: The early return on stream error in the
StreamScannerHandler call can leak the HTTP response body (resp); add explicit
cleanup by calling service.CloseResponseBodyGracefully(resp) before returning
the streamErr, or preferably add a defer
service.CloseResponseBodyGracefully(resp) at the start of the surrounding
function so resp is always closed; update the block that calls
helper.StreamScannerHandler(c, resp, info, ...) to ensure resp is closed on the
new error path (reference resp, helper.StreamScannerHandler,
HandleStreamResponseData, and service.CloseResponseBodyGracefully).
🪄 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: 84f2cbf8-7bc7-46d5-83bb-3a630ffb3847

📥 Commits

Reviewing files that changed from the base of the PR and between cca5a4e and 8635b93.

📒 Files selected for processing (12)
  • relay/channel/baidu/relay-baidu.go
  • relay/channel/claude/relay-claude.go
  • relay/channel/dify/relay-dify.go
  • relay/channel/gemini/relay-gemini.go
  • relay/channel/openai/audio.go
  • relay/channel/openai/chat_via_responses.go
  • relay/channel/openai/relay-openai.go
  • relay/channel/openai/relay_responses.go
  • relay/channel/xai/text.go
  • relay/common/stream_status.go
  • relay/helper/stream_scanner.go
  • relay/helper/stream_scanner_test.go
✅ Files skipped from review due to trivial changes (3)
  • relay/channel/dify/relay-dify.go
  • relay/channel/openai/audio.go
  • relay/helper/stream_scanner_test.go
🚧 Files skipped from review as they are similar to previous changes (7)
  • relay/channel/openai/chat_via_responses.go
  • relay/channel/openai/relay-openai.go
  • relay/common/stream_status.go
  • relay/channel/gemini/relay-gemini.go
  • relay/channel/xai/text.go
  • relay/helper/stream_scanner.go
  • relay/channel/baidu/relay-baidu.go

Comment thread relay/channel/claude/relay-claude.go Resolved
…sponse

When an upstream provider accepts a streaming connection (HTTP 200) but
never sends any tokens, the stream eventually times out. Previously this
was silently treated as success with zero tokens billed, and the retry
mechanism never triggered.

Now StreamScannerHandler returns a retriable channel error (502) when the
stream ends abnormally (timeout, scanner error, ping failure) and no
tokens were received. The existing retry loop picks it up and tries the
next available channel automatically.

Closes #2989, addresses #357, #1562
@0-don

0-don commented Jul 22, 2026

Copy link
Copy Markdown
Contributor Author

Closing: no longer maintaining these against upstream.

@0-don 0-don closed this Jul 22, 2026
@0-don
0-don deleted the fix/stream-timeout-retry branch July 22, 2026 18:30
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.

流式空回记录为成功,未触发重试

1 participant