Skip to content

feat: resume a mid-stream anonymous break on a new exit - #75

Closed
mcheiyue wants to merge 1 commit into
jasonxu114514:mainfrom
mcheiyue:feat/stream-continuation
Closed

mcheiyue wants to merge 1 commit into
jasonxu114514:mainfrom
mcheiyue:feat/stream-continuation

Conversation

@mcheiyue

@mcheiyue mcheiyue commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

Summary

An anonymous SSE stream that dies mid-flight currently surfaces an in-band error and the client loses the remainder of the answer. This adds an opt-in resume: when a stream dies unexpectedly after visible text was delivered, the gateway fetches a continuation segment on a new exit and splices its frames into the same downstream stream, so the client sees one continuous, error-free response.

Design

  • ForwardStreamResumable (new, internal/protocol/stream_resume.go) relays one or more upstream segments into the same writer. It only attempts a resume when: a resumer is provided, the resume budget is left, visible text or reasoning was delivered, no tool call appeared, and the client has not canceled.
  • ForwardStream is a thin wrapper over the new function with no resumer, so the historical path is byte-for-byte unchanged.
  • Continuation body = the original upstream body with the delivered partial as a trailing assistant message, followed by a short continuation instruction, so every other field (tools, stream options, effort) survives and the free-tier shape is re-asserted downstream.
  • The exit that just broke is marked failed on the pool, so the session's FNV cursor rotates onto a different one for the continuation fetch instead of landing on the same dead exit.
  • The continuation fetch runs on its own budget derived from the client connection (stream_continuation_timeout_seconds), not on the request-level retry budget, which may already be exhausted by the time a stream breaks mid-flight. The number of resumes is capped by stream_continuation_max.
  • Reason-only breaks (visible text empty, reasoning non-empty) resume by injecting the captured reasoning plus an instruction to skip the repeated reasoning and emit the final answer, rather than hard-joining thinking text into content.
  • Continuation segments drop the replayed role frame, empty content frames and repeated reasoning frames; usage accumulates per segment (input from the first segment, output across segments).
  • Guards: tool calls (tool_start/tool_delta seen) and clients that canceled never resume; non-chat protocols and key tiers keep the old path; the partial is capped.
  • Two splice details: a torn frame is terminated before the continuation's first frame (an unterminated record would otherwise swallow it), and the overlap with the delivered tail is trimmed across the first frames (fail-open - a parse/rewrite failure passes the frame through untouched).
  • Telemetry: continued, resume_kind, resume_attempts/resume_failures and resume_skipped (with the skip reason) on the request line.

Verification

  • gofmt -l . (no output), go build ./..., go vet ./..., go test ./... all clean against current main.
  • Tests were run locally only; no test files are included in the tree, per this repository's convention.
  • The continuation instruction shape was verified against the live free tier before implementing: a bare trailing assistant message regenerates from scratch (no prefill), while the partial + instruction continues cleanly, including with the core tool set present.
  • The feature was exercised end-to-end against real anonymous-lane traffic on a self-hosted deployment, where it triggered on genuine mid-stream breaks.

Compatibility

  • stream_continuation is opt-in and defaults to false; stream_continuation_max defaults to 1 and stream_continuation_timeout_seconds defaults to 60. Setting stream_continuation=false keeps the exact old behavior; the disabled path copies and counts nothing.
  • Only Chat-to-Chat anonymous streams are covered; key tiers, non-chat and non-streaming paths are untouched.

Review notes

@jasonxu114514

Copy link
Copy Markdown
Owner

Thanks for the careful write-up. Resuming a broken anonymous stream is worth having, but a few things need fixing before it can land:

  1. It is on by default. StreamContinuation: true is the default in config.go, the README and config.example.json, which contradicts "opt-in". Please default it to false.
  2. The disabled path is not free. With no resumer attached, the output bytes are identical, but the observer still copies every visible text delta (up to 1 MiB per stream) on every protocol and tier, and TextRunes/TailRunes re-convert the buffer each time. Only collect text when a resumer is attached.
  3. Overlap trimming effectively never fires. lcpTrimReader inspects only the first content frame, then stops. Real Chat streams send roughly one token per frame, and lcpMinOverlapRunes is 4, so a restart like "The quick…" is never trimmed. The unit tests pass only because they put the whole overlap in one frame. Match across the first N frames or runes instead.
  4. Reasoning and the role chunk are replayed. The continuation is a fresh completion, so reasoning models emit reasoning_content again, and the leading role:"assistant" chunk with a new id/created is forwarded mid-stream. Both should be dropped from the continuation segment.
  5. Usage is wrong after a resume. mergeBridgeUsage overwrites Input and Output, so the reported usage is only the continuation's: its input includes the partial text, and the first segment's output is lost.
  6. An exit gets penalized for the client's budget. When the break is caused by requestCtx expiring, markCurrentStreamExitFailed runs before the dead context is noticed. Check requestCtx.Err() first.
  7. Smaller things:
    • buildContinuationBody and doAnonymousUpstream both call prepareAnonymousBody, so the body is shaped twice.
    • A trailing assistant message with array content makes the build fail with an error.
    • Please mention in the README that only Chat→Chat anonymous streams are covered.

Also:

@mcheiyue

Copy link
Copy Markdown
Contributor Author

感谢细致的 review,七条意见已全部落实。先汇报各条的处理,再附上一份现网真实流量的验证数据。

七条 review 的落实情况

  1. 默认改为 false — 已改。config.go 种子配置、README(中英文)、config.example.json 三处统一 stream_continuation: false;文档行为说明也从 "enabled by default" 改为 opt-in。

  2. 禁用路径零开销 — 已改。streamUsageObserver 新增 trackContent 门控:未挂 resumer 时不拷贝文本(与上游当前行为一致),rune 计数移到 ForwardStreamResumable 内的 resumer 短路逻辑里——禁用路径现在既不拷贝也不计数,字节和 CPU 与原版完全相同。

  3. 跨帧 LCP — 已改。lcpTrimReader 重写为:缓冲续写段开头若干帧的累积 content,按 rune 上限(200)统一判定重叠并跨帧裁剪。真实的 Chat 流是 ~1 token/帧的碎片,重叠跨越多帧;原实现只在单帧内找 LCP,生产上从未命中过(这正是 review 指出的问题)。

  4. 续写段帧过滤器 — 已改。新增 continuationFrameFilter:丢弃续写段的 role 头帧、空 content 帧、reasoning 帧;保留正文、finish_reason、usage、[DONE]。

  5. 按段 usage 累加 — 已改。ForwardStreamResumable 不再覆盖 usage:Input/CachedTokens 取首段值,OutputTokens/ReasoningTokens 跨段累加(首段 usage 正确性由协议测试锁定)。

  6. 先判 ctx 再罚出口 — 已修。父预算耗尽时直接返回 context.Cause(ctx),不再调用 markCurrentStreamExitFailed(错误归因在 doInferenceAttempt 已完成)。

  7. 杂项 — 已改。删除 buildContinuationBody 里的 prepareAnonymousBody 双调(发送车道本就会再调一次);数组形态的 content 现在会展开为纯文本(多模态请求不再因 JSON marshal 失败而放弃续写);README 补充了续写范围说明。

另外,针对 "思维链断流"(visible=0 但 reasoning>0 时原实现直接放弃)补了一个增强:截获的思考过程以语义化指令注入续写请求("不要重复推理,直接输出最终答案"),换新出口催产正文,而不是把思考文本当 content 硬拼给客户端。这一部分如认为超出本 PR 范围,可以拆成独立 PR。

现网验证(VPS 生产环境,fork 镜像 v1.4.0-oc-cont4,含全部 review 修复)

运行约 24 小时,真实流量数据:

  • 续写机制在真实断流中 5/5 正确触发(resume_kind=reasoning、reasoning_bytes 73-92KB 落日志);
  • 2 笔成功完成换出口续写(continued=1,续写段继续正常吐内容),1 笔完整交付(200、输出 12.7k tokens);
  • 3 笔失败原因是上游 Zen 匿名池 429 风暴(单请求 attempts=16-23,出口池整体命中率塌缩),续写段在独立 60s 预算内未能等到限流窗口松动——属于上游容量事件,不是续写机制缺陷;
  • 禁用路径零开销(review 期待大佬打包一个ui可以简单配置 #2)已通过单测锁定:trackContent=false 时 Text() 返回空、visibleBytes 不再被填充。

上游同步状态

本分支已合并到最新 main(v1.4.0,含 #59/#64 等近期修复),当前 HEAD 68d7f75。之前 base 落后导致的 CONFLICTING 状态在 rebase 后应消失,push 后会刷新。

测试文件说明(此前讨论过):为保持树内干净可以移除,测试命令与要点可以写进 PR 描述——如需要请告知,我会在 push 前处理。

再次感谢细致的 review,特别是跨帧 LCP 和禁用路径开销这两条——它们指出了两个我在本地测试里不容易暴露的真实问题。

An anonymous SSE stream that dies mid-flight currently emits an in-band
error and the client loses the rest of the answer. The free tier has no
assistant prefill, so a bare trailing assistant message regenerates from
scratch, but a delivered partial followed by a short continuation
instruction continues cleanly (verified live, including with the core tool
set present).

ForwardStreamResumable relays one or more upstream segments into the same
downstream stream. When a segment dies unexpectedly after visible text was
delivered, forward of any tool call, and before the resume budget is spent,
it asks the resumer for a continuation segment, closes the torn frame so the
next segment cannot join it, trims the first overlap with the delivered tail
(fail-open, decided across the first frames rather than within a single one),
and keeps relaying. With no resumer it is byte-for-byte the historical
ForwardStream.

The gateway builds the continuation body from the original upstream body plus
the partial and the instruction, cools down the exit that just broke (so the
pool cursor rotates onto a different one instead of landing on the same dead
exit), and fetches the next segment on its own budget derived from the client
connection rather than the request-level retry budget, which may already be
exhausted by the time the stream breaks. Tool calls, non-chat protocols, key
tiers and canceled clients keep the old behavior, and the whole feature is
one performance flag (stream_continuation, opt-in, default false).

A reasoning-only break (visible text empty, reasoning non-empty) resumes by
injecting the captured reasoning as context plus an instruction to skip the
repeated reasoning and emit the final answer, instead of hard-joining thinking
text into content. Continuation segments drop the replayed role frame, empty
content frames and repeated reasoning frames; usage is accumulated per segment
(input from the first segment, output across segments).

The disabled path is free: with no resumer attached nothing is copied or
counted, so the bytes and CPU match the previous implementation.

Tested: go build ./..., go vet ./..., go test ./... all pass. Test files are
intentionally not included, per this repository's convention; the feature was
also exercised end-to-end against real anonymous-lane traffic on a self-hosted
deployment, where it triggered on genuine mid-stream breaks.
@mcheiyue
mcheiyue force-pushed the feat/stream-continuation branch from 68d7f75 to fbc2ec6 Compare October 18, 2026 16:15
@mcheiyue

Copy link
Copy Markdown
Contributor Author

已按你的要求 rebase 并清理,三条要求的状态如下。

  1. Rebase —— 已完成。分支重建在当前 main(9aa2133)之上,补丁只落在 10 个文件、+1070/−47。upstream.go 那 556 行重写已逐处对账,我们那两处改动(出口持有者、成功路径记录服务出口)按新结构重新落位;gateway.go 保留了你们的 streamBody(即 RenameStreamReader 改写后的 reader),没有回退成 resp.Body。冲突状态已从 CONFLICTING 变为 MERGEABLE。

  2. 删除树内测试文件 —— 已完成。continue_test.go、stream_resume_test.go 以及我新增的 config_test.go 已全部移出树,测试命令与结果写进了 PR 描述。这一条上一轮我没有直接执行、反而反问了你,是我处理不当。

  3. feat: per-model proxy pools, A→B fallback, hidden models, stream resilience #67 的 servingBinding 重叠 —— 已自动消解:#67 现为 CLOSED、未合并,"只能落一个"的前提不再存在。

另外两点说明:

  • stream_continuation_timeout_seconds 的校验放宽为 0..86400。我原先写成 1..86400,会让 Normalize 拒绝零值——你们的 TestNormalizeAcceptsPoolProxy 正好照出来了。0 现在按"关闭续写预算"处理,与 first_event_timeout_seconds 的 0 语义保持一致。
  • 思维链(reason-only)断流续写仍在这条 PR 内。如果你认为它超出本 PR 范围,我可以拆成独立 PR。

本地门禁:gofmt -l . 无输出,go build ./... / go vet ./... / go test ./... 全绿。CI 已过的 job 均通过。

@jasonxu114514

Copy link
Copy Markdown
Owner

已在 main 以 fac8dd3 安全重作並驗證,本 PR 由該提交取代,將納入 v1.5.2。retry.stream_resume_enabled 預設 false;只支援匿名 Chat→Chat,預設續傳 1 段、每段總期限 60 秒。保留完整 SSE 驗證與錯誤遮蔽,續段工具呼叫不會丟失,遇工具/取消/上游錯誤或不相容結構不再續傳;保留 ID/別名並累加各段實際用量。感謝提案;關閉舊分支而不直接合併。

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.

2 participants