Skip to content

[PR] fix(kernel): heal unpaired server_tool_use / *_tool_result blocks after folds - #6428

Closed
raydocs wants to merge 0 commit into
ranxianglei:masterfrom
raydocs:fix/heal-unpaired-server-tool-blocks
Closed

raydocs wants to merge 0 commit into
ranxianglei:masterfrom
raydocs:fix/heal-unpaired-server-tool-blocks

Conversation

@raydocs

@raydocs raydocs commented Nov 12, 2026

Copy link
Copy Markdown
Contributor

kernel-change: mechanical wire-legality bug in coreToAnthropic — a fold can split a server-tool exchange (server_tool_use + <name>_tool_result) and the encoder forwards the orphan half, which Anthropic rejects with a hard 400. Fixed under the mechanical-bug exemption (owner policy 2026-11-06): reproducing regression test included; human-only review tier still applies.

What this fixes

Server-side tools (advisor, web_search, code_execution, …) put both halves of an exchange inside one assistant message: server_tool_use (id srvtoolu_…) and its <name>_tool_result (paired by tool_use_id). anthropicToCore splits every content block into its own BiliMessage (unknown types ride the rawAnthropicBlock sidecar, #3410), so a fold can cover one half and leave the other. The encoder then forwards the orphan and Anthropic rejects the whole request:

messages.5.content.0: unexpected tool_use_id found in advisor_tool_result blocks: srvtoolu_…
Each advisor_tool_result block must have a corresponding server_tool_use block in the same message.

Field repro: Claude Code with the advisor tool through the proxy, bili v0.1.213 / acp-kernel 0.0.195. A subagent got 12 consecutive 400s right after folds. Overflow self-heal doesn't recognize this 400 (log: upstream 400 carries no parseable overflow marker), so it isn't retried with a different shape.

Change

healUnpairedServerToolBlocks(out) runs in coreToAnthropic right before healIllegalSystemPositions. For each assistant message it:

  • drops a *_tool_result block (excluding plain tool_result) whose tool_use_id has no server_tool_use in the same message;
  • drops a server_tool_use without its result, except in the last message, where an open server call is legal client state;
  • replaces a message the heal empties with a placeholder text block, so roles keep alternating.

Plain tool_use / tool_result blocks are never touched. Legal messages keep the same object, so the prefix cache sees no churn. Only messages that would already 400 get rewritten, so KDD #10 (thinking signatures) can't turn a request that would have succeeded into a failure.

The suffix rule endsWith("_tool_result") matches the convention legitimatesFollowSide (#5438) already uses for the server-tool result family.

Version: acp-kernel 0.0.195 → 0.0.196 (kernel/package.json plus both lockfiles).

Tests

Config surface

None.

🤖 Generated with Claude Code

@ranxianglei ranxianglei changed the title fix(kernel): heal unpaired server_tool_use / *_tool_result blocks after folds [PR] fix(kernel): heal unpaired server_tool_use / *_tool_result blocks after folds Nov 12, 2026
@ranxianglei

Copy link
Copy Markdown
Owner

🤖 Powered by ework · qwen3.8-27b

(ai: vllm-qwen/qwen3.8-27b)

查重: 不重复 — no other issue/PR (open or closed) covers the server-tool pairing 400 after folds. Nearest neighbors: #5432/#5522 (mid-conversation system positions — same kernel-heal pattern, different constraint) and #3410 (raw-block passthrough — the mechanism that makes the orphan possible).

Review verdict: direction correct, design sound, verified locally + CI green; one discipline gap to close before merge.

Direction — the bug is real. Mechanism confirmed in code: anthropicToCore splits every content block into its own BiliMessage (unknown types ride the rawAnthropicBlock sidecar, #3410), so a fold can cover exactly one half of a same-message server-tool pair; coreToAnthropic re-emits the orphan verbatim and Anthropic 400s the whole request. The production error string matches the API contract — verified against the official anthropic-sdk-typescript source: server-tool result blocks (web_search_tool_result, web_fetch_tool_result, code_execution_tool_result, bash_code_execution_tool_result, text_editor_code_execution_tool_result, tool_search_tool_result, and the newer advisor_tool_result) pair with server_tool_use by tool_use_id inside the same message. The kernel is the right layer: a host-side filter would duplicate the encoder's own logic (same reason #5438 chose the kernel-side heal).

MCP concern — raised and resolved. I initially suspected the endsWith("_tool_result") suffix could match an mcp_tool_result block and break legal MCP pairs (result dropped, use kept → 400). It can't: the current API has no mcp_tool_use/mcp_tool_result block types at all — MCP tools are plain tool_use/tool_result. The suffix matches exactly the server-tool result family and is future-proof for new server tools. No MCP regression.

Regression audit (existing behavior walked):

  • Message replacement out[mi] = {role, content} — AnthropicMessage is exactly {role, content}, so no fields are dropped.
  • Call-site ordering is load-bearing and correct: the pairing heal runs BEFORE healIllegalSystemPositions, so legitimatesFollowSide sees the post-pairing state. Reversed, a mid-conversation system could be legitimized by a result block the pairing heal then drops → 400.
  • KDD release v0.1.3 #10 (thinking signatures): the heal touches only server-tool blocks and only rewrites messages that would 400 anyway.
  • Prefix cache: legal messages keep the same object — zero churn.
  • Golden pin tests/golden/wire-contract/kernel.json: no coreToAnthropic/server-tool surface pinned — no impact.
  • Both compression modes: coreToAnthropic is the shared Anthropic encoder.
  • Edge cases dismissed: an open server_tool_use in a non-last message is essentially unreachable from API-returned state (use+result come back in one atomic message); the last-message exception hedges the interrupted-stream case; host post-append paths (healAnthropicSystemPositions) can't orphan same-message pairs.

Verified locally (pr6428 head ca177b9c, isolated worktree):

  • New suite kernel/tests/server-tool-pair-heal.test.ts: 5/5 pass.
  • PR's claim "3 of 5 fail with the heal disabled": reproduced exactly (the 3 positive rows fail, both negative rows pass).
  • Wire regression suites: 83/83 (wire-bili-message-roundtrip, issue3410-wire-passthrough, issue3939-wire-byte-stability, issue4570-system-position-final-wire, wire-formats).
  • CI on head: 38 success / 14 skipped / 0 failed.

Findings:

  1. (medium — request before merge) No WIRE_RULES ledger entry. §7.3 requires every production upstream rejection to become a permanent ledger entry + gate + fake enforcement INSIDE the fixing PR (pattern: WC-023/WC-024). Concretely: a WC-025 in tests/wire-contract-fakes.ts (ledger entry + validator mirroring the kernel heal: a *_tool_result other than plain tool_result with no same-message server_tool_use in any message; a server_tool_use with no same-message result in a non-last message) + a gate row in tests/wire-contract.test.ts. I cannot push to the author's fork (pull-only access), so this needs a commit from @raydocs.
  2. (minor) healUnpairedServerToolBlocks returns the dropped count (kernel/src/wire/anthropic.ts:546, call site :666) but no call site or test consumes it — dead code per the code-cleanliness bar; make it void or justify.
  3. (note for owner, non-blocking) The mechanical-bug exemption is borderline: this is ~80 lines of new encoder logic, not a wrong literal / typo / provably-false guard. The human-only kernel tier gates the merge regardless, so this is a flag for your merge decision, not a review blocker.

八问 (structured conclusion):

  1. 是什么问题:fold 把一次 server-tool 交换(advisor/web_search/…)的一半压缩掉后,编码器把孤儿块原样转发,Anthropic 对整个请求 400——会话陷入 400 死循环,不可用。
  2. 什么原因导致的:anthropicToCore 把每个 content block 拆成独立 BiliMessage,fold 可以只覆盖同一消息里配对的一半;coreToAnthropic 没有配对兜底,孤儿块被原样转发。
  3. 影响范围与严重程度:Anthropic 线上使用 server tool 的任意客户端(现场复现:Claude Code + advisor);fold 拆散配对后该会话完全不可用(400 循环),p1 级。
  4. 怎么修复的:在 coreToAnthropic 加配对兜底——丢弃孤儿 result;丢弃孤儿 use(最后一条消息除外,那里未完成的 server 调用是合法客户端状态);被清空的用占位文本块保持角色交替。
  5. 是否有回归问题:未发现——逐项审过消息替换的类型形状(无字段丢失)、调用顺序(pairing 先于 system-heal,承重且正确)、KDD release v0.1.3 #10(只改写本来就会 400 的消息)、前缀缓存(合法消息对象不变)、golden pin(不涉及)、两种压缩模式(共享编码器)、MCP(API 中不存在 mcp 块类型)。
  6. 是否破坏缓存:否——合法消息保持同一对象与字节;只有本来就会 400 的请求被改写。
  7. 是否改了设计方向:否——沿用既有的 kernel 侧 heal 模式(kernel authorization request: heal must enforce the FOLLOW side of Anthropic's mid-conversation system position rule (#5432) #5438/[PR] fix(kernel): heal the follow side of Anthropic's mid-conversation system rule (#5438) #5522)。
  8. 是否引入新配置:否。

标签(仅建议,源 PR 按 no-mutate 规则不动):bug、claude-code、scope/kernel、p1——kernel 线路上导致会话级 400 死循环的缺陷。

判定:方向、设计、测试、CI 均已验证通过;补齐 WC-025 台账条目(finding 1)后即可合并。kernel 变更属于 human-only 档,由 owner 合并。

@ranxianglei

Copy link
Copy Markdown
Owner

Landed via batch PR #6482 (merged) — closing as superseded.

@ranxianglei ranxianglei reopened this Nov 14, 2026
@ranxianglei
ranxianglei force-pushed the fix/heal-unpaired-server-tool-blocks branch from ca177b9 to 2153152 Compare November 14, 2026 01:22
ranxianglei pushed a commit that referenced this pull request Nov 14, 2026
…lict at 0.0.198

Master advanced past the PR base (batch4 kernel fixes #6428/#6345/#5166 ->
kernel 0.0.197, storage-render chat golden digest refresh, pi-subagents 0.2.4,
305 files). Content hunks auto-merged (kernel/src/compress.ts,
tests/golden/storage-render/chat.json); the only conflicts were the three
kernel version lines, resolved at 0.0.198 = master's 0.0.197 + this PR's
kernel/src change, per the CI-enforced kernel version discipline.

Targeted local verification: tests/golden-storage-render.test.ts 5/5,
kernel issue6116/issue3769/hide-consumed suites 27/27.
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