Skip to content

fix(core): fail SSE streams that end before the declared terminator instead of silently truncating - #4042

Open
linlihuiyang wants to merge 9 commits into
agentscope-ai:mainfrom
linlihuiyang:fix/openai-stream-early-termination
Open

linlihuiyang wants to merge 9 commits into
agentscope-ai:mainfrom
linlihuiyang:fix/openai-stream-early-termination

Conversation

@linlihuiyang

@linlihuiyang linlihuiyang commented Nov 7, 2026 •

Copy link
Copy Markdown

Problem

When an OpenAI-compatible provider or gateway closes the SSE connection mid-generation without emitting [DONE] (and without a finish_reason chunk), the streaming pipeline treats it as a normal completion: the partial text is delivered as the final answer and the surrounding turn completes successfully, with no signal that the content was truncated.

Observed in production against an OpenAI-compatible gateway during a period of upstream instability: a model call stalled mid-sentence, the connection closed cleanly, and the turn finalized as completed with a 46-character truncated reply.

Fixes #4040
Fixes #3808

Root cause

The built-in SSE transports (JdkHttpTransport, OkHttpTransport) already recognize [DONE], but they swallow it: they stop reading and complete the stream without telling the client whether the marker was seen. From OpenAIClient's perspective, "stream ended after [DONE]" and "connection closed mid-generation" are indistinguishable, so both complete normally.

Fix

  • TransportConstants.STREAM_TERMINATOR_HEADER (X-AgentScope-Stream-Terminator): callers may declare the expected SSE terminator. When set, both built-in transports fail the stream with the new StreamTerminationException if the body ends before the marker. When unset, behavior is unchanged (DashScope-style streams without [DONE] keep working).
  • OpenAIClient declares [DONE] on every streaming request and maps StreamTerminationException to OpenAIException with error code stream_terminated_early and an EOFException cause, which flows into the existing ModelUtils retry path (safe retry only before user-visible content; otherwise the error propagates instead of silently completing).
  • The client keeps its [DONE] takeWhile for transports that pass the marker through.

Tests

  • JdkHttpTransportTest / OkHttpTransportTest: header unset → lenient completion (unchanged); header set + marker missing → StreamTerminationException; header set + marker seen → completes.
  • OpenAIStreamTerminationTest: client declares the terminator header; transport-reported early termination maps to retryable stream_terminated_early; [DONE]-only and finish_reason-only completions still pass.
  • OpenAIChatModelStreamingRetryTest: real OkHttp transport retries truncation before visible content and does not retry after visible content.

Notes

  • Custom HttpTransport implementations that neither honor the header nor pass [DONE] through keep the old lenient behavior; enforcement is opt-in per request.
  • With terminator enforcement enabled, an empty SSE body (zero chunks) is treated as truncation rather than a silent successful completion.

…nstead of silently truncating

A clean connection close is not proof of complete content: providers and
gateways can cut an SSE stream mid-generation without emitting [DONE] or a
finish_reason chunk. The built-in transports swallowed [DONE], so
OpenAIClient could not distinguish a finished stream from a truncated one
and delivered partial content as a normal completion.

- TransportConstants.STREAM_TERMINATOR_HEADER lets callers declare the
  expected terminator; JdkHttpTransport/OkHttpTransport then raise
  StreamTerminationException when the body ends before it. Unset keeps
  the lenient behavior (e.g. providers without a terminal marker).
- OpenAIClient declares [DONE] and maps early termination to
  OpenAIException with error code stream_terminated_early, feeding the
  existing ModelUtils retry semantics (retried only before user-visible
  content).

Fixes agentscope-ai#4040

@juruoO-o juruoO-o left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[P1] 请统一真实 transport 与客户端测试的成功条件,避免把已完成响应误判为截断。

当前 OpenAIClient 无条件声明 [DONE] terminator;JdkHttpTransport/OkHttpTransport 在该标记缺失时必定抛 StreamTerminationException,不考虑已收到 finish_reason=stop 的情况。另一方面,本 PR 的 finishReasonWithoutDoneSentinelCompletes 测试明确将“有 finish_reason、没有 [DONE]”视为正常完成,但它使用自定义 closingTransport,绕过了新增的真实 transport 校验。因此同样的响应在假 transport 上成功,在默认内置 transport 上失败。

以上为代码路径确认,未本地执行真实 HTTP 复现。请明确并统一 OpenAI 完成契约;若保留测试声明的 lenient gateway 兼容行为,就需要使内置 transport 路径同样接受该响应,并增加真实 JDK/OkHttp transport 的集成断言,而不是仅在客户端 mock 上验证。也请与 #3810 协调为同一套完成信号语义。

@linlihuiyang

Copy link
Copy Markdown
Author

@juruoO-o 已在 016a667 统一完成信号语义:

  • OpenAIClient 追踪任一 choice 的 finish_reason;收到该信号后,内置 transport 因缺少 [DONE] 产生的 StreamTerminationException 会被转换为正常完成。
  • 未收到 [DONE] 且未收到 finish_reason 时,仍抛出 stream_terminated_early,截断检测保持不变。
  • 新增基于本地 HTTP 服务的真实 JDK/OkHttp transport 集成测试,覆盖“有 finish_reason、无 [DONE]”场景;与 fix(openai): 流式响应缺完成信号即结束判定为截断,并在推理层安全重试 #3810 的完成契约一致。

验证:OpenAIStreamTerminationTest 7/7 通过;OpenAI 本地套件 590 个测试通过、4 个跳过;Spotless 与 git diff --check 通过。官方 OpenAI E2E 未纳入本地验证(基线因本机凭据 401 失败)。

@linlihuiyang

Copy link
Copy Markdown
Author

补充更正前面的表述:这里与 #3810 一致的是完成信号定义([DONE] 或任一非空 finish_reason),但两个 PR 当前实现不能直接叠加。

建议按以下分层协调:

  1. 本 PR 负责内置 transport 的截断检测,以及 OpenAI 客户端对 finish_reason 的兼容;自定义 transport 继续保持 opt-in。
  2. fix(openai): 流式响应缺完成信号即结束判定为截断,并在推理层安全重试 #3810 在本 PR 基础上 rebase 后,移除 OpenAIClient 中重复的 sawCompletionSignal / concatWith 检测,避免内置 transport 已消费 [DONE] 时发生误判。
  3. fix(openai): 流式响应缺完成信号即结束判定为截断,并在推理层安全重试 #3810 将无完成信号产生的 StreamTerminationException 接入 IncompleteStreamException / PartialStreamContent 及安全重试路径,保留其 ReAct 状态重置和可观测性改动。
  4. 合并前共同覆盖:仅 [DONE]、仅 finish_reason、两者都有、两者都没有,以及真实 JDK/OkHttp transport 和截断后的安全重试。

这样可以避免双重检测、异常类型冲突及重试路径失效。

@juruoO-o juruoO-o left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

复审 head 7ffa0b1:上次提出的真实 transport 与 mock 成功条件不一致已修复。OpenAIClient 收到 finish_reason 后,会将内置 transport 因缺少 [DONE] 产生的 StreamTerminationException 转为正常完成;缺少两种完成信号时仍报截断。

本轮在该 head 隔离副本执行 JdkHttpTransportTest 55 项、OkHttpTransportTest 18 项、OpenAIStreamTerminationTest 7 项,共 80 项通过,包含真实 JDK/OkHttp 的 finish_reason-only 路径。未发现新的确定性代码阻塞;未运行官方 OpenAI E2E 或全仓 verify。

本批准针对代码修复本身。仍有合入阻碍:与本次 fetch 的 main@c627cc7c9 在 OkHttpTransport.java 存在内容冲突,涉及 main 新的流式资源/取消实现。请整合时保留 main 的取消、调度及资源关闭语义,再接入终止标记检测。#3810 仍需单独修复原阻塞并协调分层,不能直接叠加。

@wahllllll

Copy link
Copy Markdown
Contributor

从 #4100 收敛过来(那边会在本条之后关闭)。transport 层的 enforcement 实现我们完整读过:JDK 的 concatWith(defer(...)) 和 OkHttp 的 !sink.isCancelled() 检查都只在自然完成时触发,NDJSON 豁免、header 未设时行为不变,设计是干净的。补一个核实到的缺口,供 rebase 时参考:

截断错误在默认配置下不会被重试。 OpenAIClient 把 StreamTerminationException 映射为 OpenAIException.create(null, …, "stream_terminated_early", null),异常状态码为 null 且没有 cause。ExecutionConfig.MODEL_DEFAULTS 显式设置 retryOn(RETRYABLE_ERRORS),而 isRetryableError 对这种异常:null 状态码落穿(#3058 之后)→ 非 TimeoutException → 非 IOException → cause 为 null → 返回 false。结果截断以永久失败呈现——而网关截断恰恰是典型瞬时故障,PR 描述里 "flows into the existing ModelUtils retry path" 目前不会生效。

一行修法:映射时挂上 EOFException(isRetryableError 沿 cause 链走到 IOException 分支即判可重试),保留 error code 用带 cause 的构造或映射后 initCause。语义上正好安全:仅在尚未输出可见内容时才会重试,ModelUtils 的可见内容护栏本就封死了输出后再重试。#4100 原本的 EOFException 方案验证过这条链路(openai 模块 595 项测试全绿)。

另一个观察供确认:header 生效后,空 SSE body(零 chunk)也会走截断错误,而 main 上静默完成——我认为这个更严格的选择是对的,只是行为变化值得在 release notes 里提一句。

另外 #3808 与 #4040 是同一底层问题,建议 PR 描述加上 Fixes #3808,一次合并关掉两个 issue。

# Conflicts:
#	agentscope-core/src/main/java/io/agentscope/core/model/transport/OkHttpTransport.java
@linlihuiyang

Copy link
Copy Markdown
Author

@wahllllll @juruoO-o 已在 ee6fb67 补齐并推送:

  • stream_terminated_early 保留原 error code,并挂载 EOFException cause,默认 RETRYABLE_ERRORS 现可正确识别。
  • 新增真实 OkHttp + OpenAIChatModel 回归测试:可见内容前截断会重试并成功;可见内容后截断不重试。
  • 已合并 main@21be74a8a,OkHttp 冲突整合保留了 main 的 Flux.using、doOnCancel(call::cancel)、调度及资源关闭语义。
  • PR 描述已关联 [Bug]: Streaming response terminated without [DONE]/finish_reason is silently accepted as a complete answer #3808,并注明空 SSE body 的严格完成语义。

验证:回归测试先复现 2 个失败,修复后相关 15 个测试通过;mvn -B -T1C -DexcludedGroups=e2e clean verify 全仓 114 个模块 BUILD SUCCESS。官方 OpenAI E2E 未验证(本机凭据 401)。

@juruoO-o juruoO-o left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

感谢补上截断重试。复审 ee6fb67 时,本地 88 项相关测试通过。单候选场景已确认:输出可见内容前截断可以重试,输出部分内容后截断会报错,且不会重复请求。

[P1] 多候选响应仍可能把部分结果当作完整结果交付。 我用本地 HTTP 服务验证了 n=2 的请求:候选 1 只收到部分文本,候选 0 收到 finish_reason=stop,随后响应体结束,没有 [DONE]。JDK 和 OkHttp 两种传输最终都向订阅者发出 onComplete,调用方因此无法知道候选 1 被截断。

在 OpenAIClient.stream 中,任意候选出现 finish_reason 都会置位共享的 sawFinishReason,随后整条流的截断错误就会被忽略。请按候选 index 跟踪结束状态,仅在请求的所有候选都已完成时接受缺少 [DONE] 的响应。建议覆盖两个对照用例:只有一个候选结束时应报告截断,两个候选都结束时应正常完成。这样也能保留单候选网关已有的兼容行为。

@linlihuiyang

Copy link
Copy Markdown
Author

@juruoO-o 已在 91b1c670b 修复多候选截断误判:

  • OpenAIClient 按候选 index 记录 finish_reason,预期候选数取 request.n(未设置时为 1)。仅当所有候选都完成时,才接受缺少 [DONE] 的正常结束;否则仍抛出 stream_terminated_early。
  • 新增真实 JDK/OkHttp transport 的 n=2 对照测试:仅候选 0 完成时报告截断;候选 0、1 都完成时正常完成。

验证:新增部分候选用例在修复前复现 onComplete() 误判,修复后 OpenAIStreamTerminationTest 9/9 通过;OpenAI 本地套件 593 个测试通过、3 个跳过,core 依赖测试通过;Spotless 与 git diff --check 通过。官方 OpenAI E2E 未运行。请复审。

xzxiaoshan added a commit that referenced this pull request Nov 26, 2026
…#4435)

## Background

Swept the last 125 PRs (#4434→#4239), every single-OS-failed CI run
since 2026-11-19 and the main-branch push runs for `mvn -B -T1C clean
verify` failures (one build OS red and the other green on the same
commit = flake suspect). Four test classes still fail on current main:
three fail on windows-latest only, and the fourth sits at its deadline
on both OSes. All fixes are test-side only (no `src/main` changes).

## Fixes and evidence

| Test class | Victims | Signature | Fix |
|---|---|---|---|
| `HarnessAgentStructuredOutputStreamEventsTest` | #4296, #4349, #4071,
main run 44879286932 (2026-11-20 to 11-23), all windows-latest |
`streamEvents(...).block(10s)` timed out at 10.2-11.3s per call; the
class takes 3.7-9.6s on windows-latest when green and 1-1.5s on ubuntu |
ephemeral `InMemoryThreadJournalStore` in the three workspace-backed
tests (the fourth already used one) |
| `HarnessAgentOverflowRecoveryTest` | #4042, #4426 (2026-11-26), both
windows-latest; the journal rows were added by #4399 on 11-25 | row
`[3]` (journal=true) crossed `block(30s)` at 36.3-38.1s and row `[4]`
passed with 33.8s; the same rows take 0.4-1.3s on ubuntu, and main's own
run 45595615922 needed 61s for the class on windows-latest | ephemeral
`InMemoryThreadJournalStore` in `newAgent` |
| `DashScopeMultiModalEmbeddingTest` | #4413 (2026-11-25),
windows-latest | the first SDK request in the fork hit the 5s latch
(7.29s elapsed); the class takes 1.4-4.2s on windows-latest even when
green | first-request latch 5s→15s |
| `AnthropicAutoConfigurationTest` | #2363, run 45137197507
(2026-11-23), windows-latest | the first gateway test crossed
`block(10s)` at 15.66s; the other three take under 1s, and this one
already takes 5-11s on windows-latest and 9-12s on ubuntu when green |
block 10s→30s |

The first two share one cause: since #4154 the default workspace journal
is `SqliteJournalStorage` on Windows, which opens a JDBC connection per
storage operation and commits every CAS as a durable transaction (DELETE
journal, synchronous EXTRA). A journaled turn issues about 20 such
writes at roughly 8ms each on a fast local disk. Neither class asserts
journal persistence, so they now use the ephemeral backend the
repository already documents for tests. Locally on Windows the
overflow-recovery class dropped from 17.9s to 5.6s and the
structured-output class from 3.2s to 1.6s.

## Constraint compliance

- Happy path zero cost: the journal swap removes work, the two
relaxations only move failure deadlines, and no sleeps or weakened
assertions were added.
- Structural hardening first: the journal swap is structural. For the
two cold-start waits the structural alternative, a warm-up request
before the timed section, would add a request to every run, so the
deadline was relaxed instead.
- Minimal widening anchored to measured data: each relaxation is 3x the
deadline that was crossed, and every comment cites its victims and
measured values.
- No `src/main` changes.

## Observed but deliberately not fixed here

-
`WorkerRuntimeTest.saturatedStartsDoNotBlockRecoveryAndDrainPreservesActiveLeases`
(#4294, windows-latest, 36.19s at the `renewed` latch): with the test's
4s worker lease a heartbeat delayed by more than 2.7s finds the lease
already expired and fails with `Worker lease lost` instead of arriving
late, so widening the latch (as #4274 did to 30s) cannot help. That
latch is the only place asserting the runtime renews leases, and a
longer lease would delay the first heartbeat by lease/3, so the fix
needs a design decision.
-
`SubagentFactoryDeclarationTest.declaredFactory_persistSessionIsolatesUsers`
(main run 45172445003, 2026-11-23, 31.45s) and
`ChatControllerTest.httpUsesExplicitCreationAndTargetedIdempotentControls`
(main run 44566773929 and #4255, both 2026-11-19): no recurrence since.
- Two windows-latest hangs that ended at the 2h job timeout:
`AgentSpawnToolPermissionTest` (#4305, run 44760439728) and
`AgentSpawnToolPlanModeTest` (main run 45739005058 on the current head).
Both classes wait with unbounded `.block()`; the root cause is not
established, and the 30-minute Surefire fork timeout in the root pom did
not end either run.
- The cost of the Windows default journal itself (one JDBC connection
and one durable transaction per storage operation) is a production
concern that deserves its own `src/main` change.
- Already fixed upstream, victims predate the fix:
`JevEvidenceProcessorTest` (13 runs, fixed by #4346),
`ChatSessionsTest`, `RocketMqExecutionTest` and `AgentScopeAdapterTest`
(fixed by #4274).

This branch has not been deployed

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

Labels

P0 重要紧急

Projects

None yet

5 participants