Skip to content

fix: preserve Responses SSE framing on chat stream errors - #6417

Closed
AmPlace wants to merge 2 commits into
QuantumNous:mainfrom
AmPlace:agent/fix-chat-to-responses-stream-errors
Closed

AmPlace wants to merge 2 commits into
QuantumNous:mainfrom
AmPlace:agent/fix-chat-to-responses-stream-errors

Conversation

@AmPlace

@AmPlace AmPlace commented Jul 23, 2026 •

Copy link
Copy Markdown

⚠️ 提交说明 / PR Notice

Important

  • 请提供人工撰写的简洁摘要,避免直接粘贴未经整理的 AI 输出。

📝 变更描述 / Description

这个 PR 修的是 /v1/responses 转发到 Chat Completions 时,流式请求中途报错会把 SSE 和普通 JSON 混在一起的问题。

目前 Chat SSE 可能已经转换并输出了 response.created 或其他 Responses 事件,后面上游才返回错误。之前 OaiChatToResponsesStreamHandler 检测到错误以后,会直接把错误返回给上层控制器;控制器发现有错误后,又会在已经开始输出的 SSE 后面继续写一段普通 JSON,最后响应会变成这样:

event: response.created
data: {...}

event: response.output_text.delta
data: {...}

{"error": {...}}

这里主要有两个问题:

  1. 同一个 HTTP 响应里同时出现 SSE 和普通 JSON;
  2. Responses 流已经开始了,但最后没有输出合法的 response.failed。

这个 PR 把首包前和首包后的错误分开处理:

  • 如果上游在第一个 Responses 事件输出前就返回错误,继续走原来的错误处理逻辑;
  • 如果 Responses SSE 已经实际开始输出,后面再报错,就发送 response.failed 结束;
  • response.failed.response.error 会保留原来的 code 和 message;
  • 失败事件复用当前响应的 ID、创建时间和模型信息;
  • 控制器发现响应已经写出后,不再往 SSE 末尾继续追加普通 JSON;
  • 同时检查 SSE 写入结果,避免写入失败了还被当成已经成功发送。

新增回归测试:

  • Chat SSE 在任何 Responses 事件输出前就返回错误;
  • Chat SSE 已经输出 response.created,之后才返回错误。

说明:本次修改由 AI 辅助完成,代码和测试结果已经人工检查。

🚀 变更类型 / Type of change

  • 🐛 Bug 修复 (Bug fix) - 请关联对应 Issue,避免将设计取舍、理解偏差或预期不一致直接归类为 bug
  • ✨ 新功能 (New feature) - 重大特性建议先通过 Issue 沟通
  • ⚡ 性能优化 / 重构 (Refactor)
  • 📝 文档更新 (Documentation)

🔗 关联任务 / Related Issue

目前没有精确对应的 Issue。

✅ 提交前检查项 / Checklist

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

📸 运行证明 / Proof of Work

运行:

go test ./relay/channel/openai ./relay/helper ./service/relayconvert/... ./controller

结果:

ok github.com/QuantumNous/new-api/relay/channel/openai
ok github.com/QuantumNous/new-api/relay/helper
ok github.com/QuantumNous/new-api/service/relayconvert
ok github.com/QuantumNous/new-api/service/relayconvert/internal/oai_chat
ok github.com/QuantumNous/new-api/service/relayconvert/internal/oai_responses
ok github.com/QuantumNous/new-api/controller

另外运行:

git diff --check

未发现空白符或补丁格式问题。

Summary by CodeRabbit

  • Bug Fixes
    • Improved streaming error handling for Responses-based chat requests.
    • Errors before any output now return cleanly without producing an invalid response/body.
    • Errors after streaming begins now emit a clear response.failed event (with status plus code/message) and omit response.completed.
    • Prevented duplicate JSON error responses when a response has already started sending.
  • New Features
    • Added sequence_number to streamed responses events for stable event ordering.
  • Tests
    • Expanded coverage for failure timing (before/after output) and SSE framing/ordering, including monotonic sequence_number validation.

@coderabbitai

coderabbitai Bot commented Jul 23, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

OpenAI Responses streaming now assigns sequence numbers to emitted events, emits response.failed after output begins, suppresses pre-output responses, records response timestamps, and prevents duplicate Relay error writes.

Changes

OpenAI streaming error handling

Layer / File(s) Summary
Sequenced response event state
dto/openai_response.go, service/relayconvert/internal/oai_chat/..., service/relayconvert/response_registry.go
Responses events now include monotonic sequence_number values, use centralized event construction, and support failure-event generation through the stream state.
Stream failure propagation and finalization
relay/channel/openai/responses_via_chat.go
The handler records creation time, stops emission on chunk errors, and emits response.failed only after output has been written.
Failure and SSE validation
relay/channel/openai/chat_via_responses_test.go, controller/relay.go
Tests cover pre-output errors, post-output failures, sequence ordering, error payloads, and SSE framing; Relay avoids duplicate JSON error writes.

Estimated code review effort: 3 (Moderate) | ~15 minutes

Possibly related PRs

  • QuantumNous/new-api#5825: Adds related response conversion and stream registry infrastructure used by the sequencing and failure-event changes.

Suggested reviewers: calcium-ion

Poem

I’m a rabbit with packets to send,
When streams break, failure notes mend.
Before output: stay still,
After output: fail with skill,
No duplicate carrots at the end!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.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
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly matches the main change: preserving Responses SSE framing when chat stream errors occur.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ 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: 3

🤖 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 `@controller/relay.go`:
- Around line 102-106: The Relay response-handling path must prevent retries
after OaiChatToResponsesStreamHandler writes a terminal response.failed or
response.error SSE. Mark streamErr as non-retryable before returning the handler
error, or bypass the post-handler retry path whenever the response has already
been written, while preserving normal retries for failures without a written
terminal response.

In `@relay/channel/openai/chat_via_responses_test.go`:
- Around line 210-219: Update the test assertions around the response.created
and response.failed events to decode both payloads and verify the required
response identity fields: matching response IDs, matching creation timestamps,
and model set to gpt-test. Preserve the existing failure status, code, message,
and event-order assertions.

In `@relay/channel/openai/responses_via_chat.go`:
- Around line 140-168: Centralize the post-write terminal-error handling
currently implemented for scanner-phase streamErr into a reusable finalization
path near the response streaming flow. Update the FinalizeStreamResponse and
final-result conversion error branches to invoke that path after
response.created has been written, so each emits response.failed with the same
code/message fallback behavior instead of returning directly; preserve direct
returns for errors that occur before any response is written.
🪄 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 Plus

Run ID: bdcfbe71-0911-400d-aeff-6b0e92255fc6

📥 Commits

Reviewing files that changed from the base of the PR and between 1721144 and 4c7bb0b.

📒 Files selected for processing (3)
  • controller/relay.go
  • relay/channel/openai/chat_via_responses_test.go
  • relay/channel/openai/responses_via_chat.go

Comment thread controller/relay.go
Comment on lines +102 to +106
if !c.Writer.Written() {
c.JSON(newAPIError.StatusCode, gin.H{
"error": newAPIError.ToOpenAIError(),
})
}

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.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

ast-grep outline controller/relay.go --items all --match 'Relay|shouldRetry'

rg -n -C 10 --glob '*.go' \
  'func shouldRetry\b|shouldRetry\s*\(' \
  .

rg -n -C 10 --glob '*.go' \
  'OaiChatToResponsesStreamHandler|response\.failed' \
  controller relay

Repository: QuantumNous/new-api

Length of output: 22872


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect the control flow around handler calls, error handling, retry guard, and channel reset after a retry.
sed -n '68,240p' controller/relay.go | cat -n
sed -n '295,365p' controller/relay.go | cat -n

Repository: QuantumNous/new-api

Length of output: 10112


Prevent retries after terminal streaming failures.

If OaiChatToResponsesStreamHandler emits response.failed, it writes SSE and then returns http.StatusInternalServerError; when retry is still allowed, Relay can invoke getChannel again and select another channel. response.failed/response.error from OpenAI responses streams must be terminal, so mark streamErr as a skip-retry error before returning it or bypass the post-handler retry path after a written response.

🤖 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 `@controller/relay.go` around lines 102 - 106, The Relay response-handling path
must prevent retries after OaiChatToResponsesStreamHandler writes a terminal
response.failed or response.error SSE. Mark streamErr as non-retryable before
returning the handler error, or bypass the post-handler retry path whenever the
response has already been written, while preserving normal retries for failures
without a written terminal response.

Comment on lines +210 to +219
got := recorder.Body.String()
require.Contains(t, got, `event: response.created`)
require.Contains(t, got, `event: response.failed`)
require.Contains(t, got, `"status":"failed"`)
require.Contains(t, got, `"code":"upstream_failure"`)
require.Contains(t, got, `"message":"upstream failed"`)
require.NotContains(t, got, `event: response.completed`)
requireOrderedSubstrings(t, got,
`event: response.created`,
`event: response.failed`,

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.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Assert the failed response identity fields.

This test does not verify the required reused response ID, creation time, and model. Decode the response.created and response.failed payloads, then assert matching ID/created values and model gpt-test.

As per coding guidelines, backend tests must protect API contracts.

🤖 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 `@relay/channel/openai/chat_via_responses_test.go` around lines 210 - 219,
Update the test assertions around the response.created and response.failed
events to decode both payloads and verify the required response identity fields:
matching response IDs, matching creation timestamps, and model set to gpt-test.
Preserve the existing failure status, code, message, and event-order assertions.

Source: Coding guidelines

@AmPlace
AmPlace marked this pull request as ready for review July 23, 2026 10:40
@coderabbitai coderabbitai Bot mentioned this pull request Jul 23, 2026
7 of 11 tasks

@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)
relay/channel/openai/chat_via_responses_test.go (1)

262-265: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Two identical require/assert mismatches for non-fatal per-event checks. Both loops correctly use require.NotNilf to guard the nil dereference, but follow it with require.Equalf for a non-fatal value comparison that should use assert.Equalf so all mismatched events surface instead of stopping at the first failure.

  • relay/channel/openai/chat_via_responses_test.go#L262-L265: change require.Equalf(t, int64(i), *event.SequenceNumber, ...) to assert.Equalf(...), keep require.NotNilf as-is.
  • relay/channel/openai/chat_via_responses_test.go#L334-L337: same change to assert.Equalf(...), keep require.NotNilf as-is.
🤖 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 `@relay/channel/openai/chat_via_responses_test.go` around lines 262 - 265, In
both event-validation loops in relay/channel/openai/chat_via_responses_test.go
at lines 262-265 and 334-337, replace the non-nil-guarded require.Equalf
sequence-number comparison with assert.Equalf while keeping require.NotNilf
unchanged, so all mismatched events are reported without stopping at the first
failure.

Source: Coding guidelines

🤖 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 `@relay/channel/openai/chat_via_responses_test.go`:
- Around line 339-346: Extend the failure-event assertions in the relevant
response stream tests, including
TestOaiChatToResponsesStreamHandlerEmitsFailureAfterOutput, to verify
failed.Payload["response"] reuses the original response ID, created timestamp,
and model. Capture or reference the initial response values and compare them
against the corresponding fields on response.failed while preserving the
existing error.code and error.message checks.

---

Nitpick comments:
In `@relay/channel/openai/chat_via_responses_test.go`:
- Around line 262-265: In both event-validation loops in
relay/channel/openai/chat_via_responses_test.go at lines 262-265 and 334-337,
replace the non-nil-guarded require.Equalf sequence-number comparison with
assert.Equalf while keeping require.NotNilf unchanged, so all mismatched events
are reported without stopping at the first failure.
🪄 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 Plus

Run ID: 2b4ea8e6-312a-404a-89b5-1dbb5563eb45

📥 Commits

Reviewing files that changed from the base of the PR and between 4c7bb0b and 3afd747.

📒 Files selected for processing (6)
  • dto/openai_response.go
  • relay/channel/openai/chat_via_responses_test.go
  • relay/channel/openai/responses_via_chat.go
  • service/relayconvert/internal/oai_chat/to_oai_responses_resp.go
  • service/relayconvert/internal/oai_chat/to_oai_responses_stream_resp.go
  • service/relayconvert/response_registry.go
💤 Files with no reviewable changes (1)
  • service/relayconvert/internal/oai_chat/to_oai_responses_resp.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • relay/channel/openai/responses_via_chat.go

Comment on lines +339 to +346
failed := events[len(events)-1]
require.Equal(t, "response.failed", failed.Type)
response, ok := failed.Payload["response"].(map[string]any)
require.True(t, ok)
errorObject, ok := response["error"].(map[string]any)
require.True(t, ok)
require.Equal(t, "upstream_failure", errorObject["code"])
require.Equal(t, "upstream failed", errorObject["message"])

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.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Assert reused response identity (ID/created/model) on response.failed.

Only error.code/error.message are checked. Per the PR objective, the failure event must reuse the original response's ID, created time, and model — this new test still doesn't verify that, the same gap flagged on the earlier (unchanged) TestOaiChatToResponsesStreamHandlerEmitsFailureAfterOutput test.

🤖 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 `@relay/channel/openai/chat_via_responses_test.go` around lines 339 - 346,
Extend the failure-event assertions in the relevant response stream tests,
including TestOaiChatToResponsesStreamHandlerEmitsFailureAfterOutput, to verify
failed.Payload["response"] reuses the original response ID, created timestamp,
and model. Capture or reference the initial response values and compare them
against the corresponding fields on response.failed while preserving the
existing error.code and error.message checks.

@AmPlace

AmPlace commented Aug 1, 2026

Copy link
Copy Markdown
Author

由于当前仓库限制同一作者同时维护的开放 PR 数量,先暂时关闭。本分支和提交会保留;该补丁跨越 relaykit 迁移且目前与 main 冲突,后续会按当前流处理结构拆小、补充关联 Issue 后再提交。

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