Skip to content

fix: anthropic legacy-completion stream error emits a well-formed block lifecycle with index (#2689) - #2691

Merged
ranxianglei merged 3 commits into
masterfrom
2026-10-10_stream-error-anthropic-index
Oct 11, 2026
Merged

ranxianglei merged 3 commits into
masterfrom
2026-10-10_stream-error-anthropic-index

Conversation

@ranxianglei

Copy link
Copy Markdown
Owner

Closes #2689

修了什么

legacyCompletionChunk() 的 anthropic 分支发裸 content_block_delta(无数字 index、无 content_block_start/stop)——严格校验宿主(ZCode)整轮拒绝该帧。#870 路径(src/plugin.ts:2030)硬编码 "completion",使其成为默认可达缺陷。

修复沿用 compress-loop adapter 的 #413 既有纪律(「content block 永不孤儿」):

  • src/stream-error.ts:anthropic 分支补齐全生命周期 content_block_start → content_block_delta → content_block_stop → message_delta → message_stop;index 由调用点传入(客户端已见块数 = 下一个可用索引);若该流还没发过 message_start,先合成一个 start 帧。message_delta 对齐 adapter 的 buildTerminal:补 stop_sequence: null 与零 usage。
  • emitStreamError 增加可选参数 LegacyAnthropicState { blockIndex?, messageStarted? };默认建模新流(index 0 + 合成 start),relay.ts 两个调用点因此无需改动。
  • src/plugin.ts:Plugin passthrough leaves the client an empty turn when the model echoes a render tag #870 调用点传 blocksForwarded;新增 sawMessageStart 标志(在 retryFraming 门后的 dispatch 处置位——retry 自己的 message_start 在那里被消费,不计入)。

行为变更(旧 → 新)

  1. Plugin passthrough leaves the client an empty turn when the model echoes a render tag #870 路径(plugin 模式,恒启用):anthropic 输出由 [裸 delta, message_delta{stop_reason}, message_stop] 变为 [start(N), delta(N), stop(N), message_delta{stop_reason, stop_sequence:null, usage:0}, message_stop],N = 客户端已见块数(该路径下 ≥1)。宽松客户端看到的错误文本不变;严格客户端从整轮拒绝变为接受。
  2. relay.ts:887 / :1410(proxy 模式;仅显式 compat.streamErrorShape="completion" + anthropic):原为裸 delta + 终结帧;现为 [合成 message_start, block 0 全生命周期, 终结帧]——新流首次完全合规。
  3. 所有 anthropic completion 模式的 message_delta 增加 stop_sequence: null + 零 usage(严格 schema 要求字段)。

默认 errorShape="protocol" 路径与其他协议分支不变。无新增配置项、无 kernel 变更、无持久化格式变更。

回归测试

  • tests/proxy-stream-error.test.ts:emitter 级形状钉住——全生命周期顺序、三个块帧共享同一数字 index、默认状态合成 start / mid-stream 不重开、message_delta 字段精确匹配。
  • tests/plugin-empty-turn-retry.test.ts:pipe 级钉住——anthropic echo-only 双退化轮驱动真实 Plugin passthrough leaves the client an empty turn when the model echoes a render tag #870 路径,断言每个 delta 带数字 index、错误块有 owning start/stop、其 index 等于已转发 distinct 块数(不复用)。

本地验证:typecheck + build 绿;定向套件 43/43(proxy-stream-error / plugin-empty-turn-retry / issue2303-draft-tail)。全量套件交 CI。

合并判定

wire/message-shape 变更(两模式均涉)→ 按 §7.4 需人工合并,不走 auto-merge。

判断说明

…ck lifecycle with index (#2689)

Strict clients (ZCode) validate every SSE frame against the Anthropic schema
and rejected the whole turn on the #870 in-band error frame: a bare
content_block_delta with no numeric index and no owning content_block_start.

- legacyCompletionChunk anthropic branch now mirrors the compress-loop
  adapter's #413 pattern: synthesize message_start when the stream never
  began, then content_block_start/delta/stop at the caller's next free
  block index; message_delta gains stop_sequence + usage (adapter parity).
- emitStreamError takes an optional LegacyAnthropicState {blockIndex,
  messageStarted}; defaults model a fresh stream (index 0, synthesize start),
  so the relay call sites need no change.
- plugin.ts #870 call site passes blocksForwarded as the next free index and
  a new sawMessageStart flag (set where the first attempt's message_start is
  dispatched, after the retryFraming gate that consumes the retry's own).
- Regression tests: emitter-level shape pins in proxy-stream-error.test.ts,
  pipe-level next-free-index pin in plugin-empty-turn-retry.test.ts.
@github-actions

github-actions Bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

📦 Built Package Artifact

Branch: 2026-10-10_stream-error-anthropic-index (a8c4b2c)

Option A — Install this exact build (recommended)

npm install -g billion-context@0.0.2910-pr.2691.a158e91

This exact version is immutable and reproducible. The rolling pr tag tracks the newest test build across all PRs.

Option B — Download artifact

  1. Download the artifact from the Actions run
  2. Extract the tarball and install:
tar xzf billion-context-pr2691.tgz
npm install -g package

Install instructions are refreshed on each push.

Review hygiene (小问题直接修): dc8259b flipped the visible error text
from the base file's \u274C escape to a literal UTF-8 ❌ byte sequence.
Runtime output is byte-identical either way; reverting removes one
unrelated line from the diff so every hunk maps to the block-lifecycle
fix. No behavior change.
@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

[bot] 🏷 PR #2691 review 完成(修 #2689)。已对照 live master 做可合入性校验、跑定向验证、并顺手修掉一处 diff 噪音后推回。结论:可合(wire/message-shape 变更,按 §7.4 走人工合并,不 auto-merge)。

审查动作与证据

  • 对照 live master(fefb16faa,PR fix: fold-reconcile survives cross-model re-serialization churn (pi model switch) — assistant-turn key + image-capability variant passes #2644 model-switch-reconcile,只动 fold-reconcile* 文件):git merge-tree --write-tree 零冲突、无文件重叠,可干净合入。
  • 本地(PR 头 dc8259b):typecheck ✅、build ✅(build-info commit=dc8259b66);定向套件 43/43(proxy-stream-error 10 + plugin-empty-turn-retry 19 + issue2303-draft-tail 14)。全量交 CI。
  • 逐行读了改动本体:src/stream-error.ts 全文、src/plugin.ts retryEmptyTurn + dispatch 循环、src/server/relay.ts 两个调用点、src/loop/adapter-anthropic.ts 的 buildSyntheticMessageStart/buildTextBlock/buildTerminal + emitError,核对形状与状态语义。

① 方向关(审原 issue):根因定位正确——在产出点 legacyCompletionChunk() anthropic 分支,不在触发点(#870 的 plugin.ts:2030 硬编码 "completion" 只是让它成为默认可达路径)。按 §7.3「疏不堵」在源头修帧格式。采纳作者判断实现全生命周期而非「只补 index」——后者仍留孤儿 delta(无 owning block),更严的状态机校验器依旧拒收;同函数 responses 分支早已用注释记过同型教训,anthropic 是漏网之鱼。✅

② 回归关(既有行为清点)

  • 默认 errorShape="protocol" 全协议路径:未触碰,形状不变 ✅
  • openai/responses/google 的 completion 分支:一行未动,既有测试绿 ✅
  • Plugin passthrough leaves the client an empty turn when the model echoes a render tag #870 路径:有意变更(见下披露),错误文本内容不变、帧变合规 ✅
  • plugin pipe dispatch 循环:仅新增 sawMessageStart 置位(置于 retryFraming(ev) 门之后——retry 自己的 message_start 被消费、不计入;且在 write() 之前,计数的是真实转发事件);转发/retryFraming/offsetRetryIndices 语义未动,退化重试测试全绿 ✅
  • emitStreamError 永不抛契约:safeWrite/end 结构未动 ✅
  • 高危模式逐项:fail-fast 未变吞错、无阈值/时序漂移、除披露的错误帧外无输出格式变化 ✅

③ 代码关

  • blocksForwarded 是既有计数器(=下一个可用块索引),复用正确;sawMessageStart 声明于 retryEmptyTurn 作用域、每次请求重置,无跨轮陈旧态。
  • 形状与 启动横幅硬编码 raw-HTTP-capture(on) 而真开关是 ACP_DUMP_BODY(默认关):日志永远撒谎,取证被带偏过 #413 blueprint 精确对齐:id msg_acp_error_${Date.now()}、字段集、buildTextBlock 的 start/delta/stop、buildTerminal 的 stop_sequence:null+usage。内联复制(adapter 函数未导出)可接受,两侧各有独立测试钉住。
  • relay.ts:887(非 2xx、body 尚未写出 → 新流模型正确);relay.ts:1410(包住整个 for-await 的 catch,理论上可在已转发部分内容后触发)→ 见下方「已知残留」。

④ 测试关:断言有牙——emitter 级用游标钉死 6 事件顺序 + 逐帧 assert.deepEqual + 三块帧 typeof index==="number" && ===0;pipe 级驱动真实 #870 双退化轮,断言恰好一个 message_start(retry 的被消费)、每个 delta 带数字 index(正是所报缺陷)、错误块有同 index 的 owning start/stop、且该 index == 已转发 distinct 块数(不复用)。无恒真/mock-only。无 relay:1410 mid-stream 用例(与其 scope 一致)。

⑤ diff 整洁度:发现一处与本 PR 目的无关的行——src/stream-error.ts:118 把 base 的 \u274C 转义翻成了字面 UTF-8 ❌(运行时字节完全等价,纯噪音)。已顺手修回:独立 commit 73e4d69(refactor(#2689),标注无行为变更),已 push 并核对远端 ref 指向 73e4d69。现在每个 hunk 都对应块生命周期修复本身。

行为变更披露(确认 PR 所述,旧 → 新)

  1. Plugin passthrough leaves the client an empty turn when the model echoes a render tag #870 路径 anthropic:[裸delta, md{sr}, ms] → [start(N), delta(N), stop(N), md{sr, stop_sequence:null, usage:0}, ms],N=客户端已见块数(该路径 ≥1)。宽松客户端所见文本不变。
  2. relay.ts:887/:1410 显式 compat.streamErrorShape="completion"+anthropic:裸 delta → [合成 message_start, block 0 全生命周期, 终结帧]。
  3. 所有 anthropic completion 模式 message_delta 增加 stop_sequence:null+零 usage。
    三者均「更严格更合规」,无阈值/时序/格式漂移。

已知残留(同一机制的另一处产出点,非本 PR 引入、非回归)
relay.ts:1410 的 catch 包住整条流式循环,理论上可在已转发部分 anthropic 内容后触发;此时 emitStreamError 默认按「新流」建模(合成 message_start + block 0)会与已转发前文重复 message_start / 撞 block 0。但常规 compress-loop 的流失败走的是状态感知的 adapter.emitError(adapter-anthropic.ts:690+:跟踪 messageStartForwarded、先关 openBlocks、用 clientIndex++ 取下一空闲索引),已正确处理;:1410 仅是绕过 adapter 的罕见兜底,且需显式非默认 streamErrorShape="completion"+anthropic 才可达。旧代码在此处同样是非法裸 delta,故非回归。按粒度政策(同一失败域不拆分成多 issue)作为本 issue 的 follow-up checklist 项记录,供你决定是否另起修复——要彻底需让 relay 跟踪 anthropic 生命周期,或改走 adapter 的状态感知 emitter。

结构化八问

  1. 是什么问题:Plugin passthrough leaves the client an empty turn when the model echoes a render tag #870 的 in-band 错误帧在 anthropic 下不是合法 SSE 块生命周期——裸 content_block_delta 缺数字 index、无 owning start/stop(孤儿 delta),严格校验宿主(ZCode)整轮 Type validation failed。
  2. 什么原因导致的:产出点 legacyCompletionChunk() anthropic 分支当年漏补块生命周期(responses 分支已踩坑留注释,anthropic 漏网);Plugin passthrough leaves the client an empty turn when the model echoes a render tag #870 硬编码 "completion" 使其成为默认可达路径。
  3. 影响范围与严重程度:走 Plugin passthrough leaves the client an empty turn when the model echoes a render tag #870 路径的 anthropic 会话(continuation nudge 重试后再退化)+ 显式 completion+anthropic 的 relay 两站点;特定条件下整轮不可用(仅严格 schema 校验宿主),宽松客户端无感;默认 protocol 路径不受影响。
  4. 怎么修复的:沿用 启动横幅硬编码 raw-HTTP-capture(on) 而真开关是 ACP_DUMP_BODY(默认关):日志永远撒谎,取证被带偏过 #413「content block 永不孤儿」纪律补齐 start→delta→stop→message_delta→message_stop;index 取调用点「客户端已见块数」;新流先合成 message_start;message_delta 对齐 buildTerminal。
  5. 是否有回归问题:无。逐项过既有行为(见②),高危模式逐项干净;唯一 wire 变化即上面披露的错误帧形态。
  6. 是否破坏缓存:不涉及。不碰前缀缓存/持久化/更新节流/去重键。
  7. 是否改了设计方向:不涉及。在 上游截断在 compress 内部重发路径无法恢复:重试闸门将 ping 计为已转发输出,且 emitError 合成 end_turn 伪完成 #1455(双形状)/Plugin passthrough leaves the client an empty turn when the model echoes a render tag #870(可见性优先)/启动横幅硬编码 raw-HTTP-capture(on) 而真开关是 ACP_DUMP_BODY(默认关):日志永远撒谎,取证被带偏过 #413(永不孤儿)既有设计内收敛。
  8. 是否引入新配置:不涉及。LegacyAnthropicState 是调用点内部参数,非 env/config/CLI 面。

判定:修复到位、测试钉住、diff 已收敛、可干净合入当前 master。等你人工合并 #2691 —— wire/message-shape 变更按 §7.4 属人工项,我不 auto-merge。CI 全量交远程把关。

@ranxianglei

Copy link
Copy Markdown
Owner Author

ci失败 另外
已知残留(同一机制的另一处产出点,非本 PR 引入、非回归)
是否可直接修复

…rts gate

The type is used only inside src/stream-error.ts; callers pass
structurally-typed object literals so no module imports the name. The
leading 'export' tripped the INTERNAL_ONLY unused-exports guard and
red CI. Dropping it makes the type module-private. No behavior change.
@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

[bot] 🏷 两件事都处理好了。

① CI 失败 —— 已修好并确认变绿

根因(不是测试挂了):PR 原提交 dc8259b 在 src/stream-error.ts:63 加了 export interface LegacyAnthropicState。该类型只在 stream-error.ts 内部使用(两个调用点传的都是结构化对象字面量,没有任何模块 import 它),所以 tier-1 的 unused-exports 守卫按 INTERNAL_ONLY 判它冗余导出。

为什么整轮红、而非某条测试红:.github/workflows/ci.yml:40-41 里 test job 声明 needs: [version-guard, kernel-guard, pi-subagents-guard, lane-guard, docs-sync, docs-coverage, unused-exports] —— fail-fast 分层(#2637)让 ~0-1m 的守卫门控四条平台腿。unused-exports 一失败,整个 test 矩阵(typecheck + kernel/pi-subagents 套件 + 全量 npm test + build)被 SKIPPED。所以之前那次 "CI failure" 是死在 tier 1,全量套件根本没跑过——不是真测试失败。

修法:去掉那个 export(类型仍是文件内接口,行为零变化)。commit a8c4b2cde,已推分支。

CI 确认(对 a8c4b2cde):

  • unused-exports = ✅ success(原来唯一红的守卫)
  • 之前被连带跳过的全量 test 矩阵现在真的在跑且已通过:test (ubuntu-latest, 22) ✅、test (ubuntu-latest, 24) ✅(含 typecheck + kernel 套件 + pi-subagents 套件 + 全量 npm test + build);windows 两条腿收尾中
  • 其余全部守卫 + 各 e2e 腿全绿

即:挡路的守卫已绿,被它连带跳过的全量套件已恢复实际运行并通过(ubuntu 两个 Node 版本),CI 恢复健康。

② 已知残留(relay.ts:1410 中途流)能否直接修 —— 不建议顺手修,建议拆 follow-up

这轮我把上一轮基于推断的部分读代码坐实了:

  • relay 流式分支是协议无关的字节管道:for await over runCompressLoop(src/server/relay.ts:1391)逐块 res.write(chunk)(:1402),不解析 SSE 事件,因此它不知道 anthropic 已转发几个块、有没有发过 message_start。catch(:1409-1411)调 emitStreamError(...) 时用的是默认新流状态(blockIndex 0 / 无 start)。
  • 正确机制其实已存在,且覆盖了常见路径:compress-loop 的 adapter 内部本就跟踪这套生命周期,但没经 CompressLoopAdapter 接口暴露(src/loop/core.ts:284-298 只有 emitter,没有状态 getter)。而 adapter 自己的 emitError(src/loop/adapter-anthropic.ts:690-717)完全状态感知——缺 start 才合成、关掉所有 openBlocks、completion 形状用 clientIndex++(下一个空闲索引)、补终结帧。core.ts:1173/1285/1312/1318 已把 loop 侧上游错误 yield adapter.emitError(...)。所以常规的上游/流错误路径本来就是对的;relay.ts:1410 的通用 emitStreamError 只是「错误从 adapter 自身处理里逃逸(写完 ≥1 个内容块后仍抛出)」时的兜底。
  • 为何不算「小问题直接修」:要让 :1410 也正确,三选一都是设计层改动——(i) 在 relay 热转发路径解析 SSE 数块(非平凡、性能敏感、重复 adapter 已做的事);(ii) 给 CompressLoopAdapter 加状态访问器(拓宽 kernel 相邻边界契约);(iii) 把 :1410 委托给 adapter.emitError(架构最一致——生命周期本就归 adapter 管),但会改动一个跨 4 协议 × 2 形状的共享兜底路径,还需复刻 emitStreamError 的永不抛 + res.end() 语义、并给每个 adapter 补「中途抛错」回归测试。都不是本 PR 这种聚焦 wire-shape 补丁能顺手带上的,硬塞进已需人工合并的本 PR 只会放大二轮返工风险(§7.5)。
  • 回归判定:不动 = 维持现状(非回归——旧的裸 delta 在那里同样不合规);触发条件极窄(显式非默认 compat.streamErrorShape="completion" + anthropic + 写完 ≥1 个内容块后 loop 抛错 + 严格校验宿主)。默认 protocol 路径与其它协议均不受影响。

我的明确建议:不要并进本 PR。它是 #2689 同一机制的另一处产出点,按粒度策略挂在 #2689 名下当一个待办 facet,不另开 issue。等你拍板:若你想现在就做,我开一个小的 follow-up PR(方向就是上面 (iii)——把 :1410 委托给 adapter.emitError,配每个 adapter 的中途抛错回归测试);否则先挂着、后续一起处理。我倾向后者——让本 PR 保持最小、尽快合并。


判定:CI 已修绿、全量套件恢复运行并通过(ubuntu 两版本);残留维持「已知、非回归、极窄」定性,建议拆 follow-up 不进本 PR。本 PR 本身可合(wire/message-shape 变更,按 §7.4 仍需你人工合并)。

@ranxianglei
ranxianglei merged commit a645bf7 into master Oct 11, 2026
27 checks passed
@github-actions

Copy link
Copy Markdown
Contributor

📦 Merged Build Published

This merge to master was published as 0.0.243-master.a645bf7 (rolling master tag).

npm install -g billion-context@0.0.243-master.a645bf7  # this exact build
npm install -g billion-context@master  # always the newest merged build

npm view billion-context@master prints the current version at any time.

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] #870 in-band error 在 anthropic 协议下缺 content_block_delta.index —— 严格校验客户端整轮 Type validation failed

1 participant