Skip to content

fix(runtime): keep provider thinking signatures across runtime rebuilds - #1973

Merged
vastsa merged 2 commits into
vastsa:mainfrom
zszz3:fix/persist-thinking-signatures
Oct 29, 2026
Merged

vastsa merged 2 commits into
vastsa:mainfrom
zszz3:fix/persist-thinking-signatures

Conversation

@zszz3

@zszz3 zszz3 commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

fixes #1972

问题

assistant 行只保存了拼接后的 thinking 和正文文本。sidecar 一旦重建 runtime(重启,或切换思考档位、模式、规则、模型配置等触发 matches() 不一致),historyToEntries() 重放的历史就没有了 pi-ai 挂在内容块上的签名:

  • Claude 的 thinking 被转成普通 text;
  • Responses 的加密 reasoning item 被丢弃,文本块的真实 message id 换成 msg_pi_N;
  • 非 DeepSeek 的 Completions 推理模型,推理字段不再回放;Gemini 缺少 thoughtSignature。

结果是从第一条带推理的回复开始,请求前缀发生变化,provider 的 prompt cache 整段重写,模型看到的上下文也和重建前不同。实测数据见 #1972。

改动

  • packages/shared:UiMessage.providerReplay?: AssistantProviderReplay,按内容顺序记录每个 thinking / text 块的长度和签名(redacted 也一并记录),不重复保存文本。
  • packages/agent-runtime/src/assistant-provider-replay.ts:
    • captureAssistantProviderReplay:在 message_end 时记录;没有任何签名时不写入,普通行在磁盘上保持不变。
    • restoreAssistantProviderReplay:校验后按长度切回原块并还原签名;长度和不上就返回 undefined。
  • runtime.ts:
  • Gemini 函数调用签名:providerReplay.toolCalls = [{ id, signature }],按 toolCallId 记录 ToolCall.thoughtSignature;historyToEntries() 从工具行重建 toolCall 时按 id 补回。这一步不依赖文本长度。只有函数调用带签名的空回复也会持久化(event-persistence.ts)。跨 provider/模型的隔离沿用 pi-ai 的 resolveThoughtSignature,还原后的消息保留原行的 provider/model。
  • 单行上限:序列化后的 providerReplay 超过 64 KiB 就不写,该行退回纯文本重建。
  • crates/host-core:UiMessage.provider_replay 存到记录的 meta.providerReplay,读取时原样还原。属于附加字段,不需要 SQL 迁移,旧版本会忽略它。
  • 文档:docs/spec/03-runtime/04-data-storage.md(含 zh-CN),以及 docs/project/unreleased.md。

兼容性

providerReplay 是 meta 里的附加字段,不需要迁移:旧版本读新数据会忽略它,新版本读旧数据时没有该字段就走原路径。

  • 旧数据没有 providerReplay,继续走原来的重建路径,行为不变。
  • 新数据被旧版本读取时,meta 中的未知字段会被忽略。
  • 文本如果被修改(长度对不上),会退回原路径,不会发送错位的签名。

验证

  • 新增 packages/agent-runtime/src/assistant-provider-replay.test.ts(6 个用例):
    • 纯函数:完整往返(包括 redacted、多段 thinking/text 交错),无签名时不记录,长度不匹配或格式错误时回退。
    • 重建后的请求:用带 providerReplay 的历史新建 runtime,拦截实际的 Responses 请求体,断言里面有原 reasoning item(encrypted_content)和真实 message id;没有 providerReplay 的行仍是原来的 msg_pi_1、无 reasoning。
    • 在线到重建:驱动 runtime 的 message_start / message_end,把产出的消息 JSON 序列化后作为历史交给新 runtime,断言请求里还原了签名。
    • 变异检查:去掉 restore 或 capture,对应用例都会失败。
  • Gemini 回归(assistant-provider-replay.test.ts):驱动在线 runtime 的 message_start/message_end 与 tool_execution_start/end,按 Host 的方式生成 assistant 行和工具行并做 JSON 往返,再新建 runtime;拦截真实 Google adapter 的请求体,对比在线和重建后的请求。覆盖两种情况:只有 toolCall 带签名;thinking 和两个 toolCall 都带签名。断言 functionCall 签名、调用顺序、functionResponse 的 name/id 与顺序都和在线请求一致。另有纯函数用例覆盖 toolCalls 记录、64 KiB 上限、文本不匹配时只保留调用签名。
  • apps/desktop/test/empty-assistant-persistence.test.mjs:只有函数调用签名的空回复会被持久化。
  • 变异检查:去掉 toolCall 签名还原,两个 Gemini 用例失败;去掉持久化条件,对应 desktop 用例失败。
  • host-core:assistant_provider_replay_roundtrips_in_record_meta,覆盖写入 meta、可见 blocks 不变、读回,以及没有该字段的行。
  • pnpm build:js、pnpm --filter @pi-desktop/desktop typecheck、pnpm lint、node scripts/check-architecture.mjs、docs check:通过。
  • agent-runtime 全量:114 files / 1573 tests 通过;shared 1336 通过;desktop 4568 tests,0 fail。
  • cargo fmt --check 通过;cargo test -p host-core --locked 1088 通过;cargo clippy -p host-core --all-targets 无新增警告(已有 3 条在 transcripts.rs / hashline/tag.rs)。

真实 provider 验证

用构建后的 runtime(packages/agent-runtime/dist),接真实的 Claude 中转(claude-opus-5-5,Anthropic Messages,adaptive thinking,effort high)跑了 3 次,每次流程相同:

  1. 在线 runtime 正常对话 2 轮。第 2 轮附带约 1 万 token 的长文本,两轮回复都带签名的 thinking。
  2. 把 runtime 在 message_end 产出的 assistant 行做一次 JSON 序列化,模拟 host 落库;确认 2/2 行写入了 providerReplay。
  3. 第 3 轮分别用以下四种方式发送:
    • 在线 runtime
    • 去掉 providerReplay 后重建(等同修复前)
    • 带 providerReplay 重建(修复后)
    • 修复后再发一次
第 3 轮请求 第 1 次 read / write 第 2 次 第 3 次 发出的第一条 assistant
在线 runtime 11060 / 91(99.1%) 11048 / 93(99.1%) 11056 / 110(99.0%) thinking 带签名
重建,修复前 559 / 10608(5.0%) 559 / 10608(5.0%) 559 / 10626(5.0%) thinking 无签名 → 被转为 text
重建,修复后 11151 / 0(100%) 11141 / 0(100%) 11166 / 0(100%) thinking 带签名
修复后再发一次 11151 / 0(100%) 11141 / 0(100%) 11166 / 0(100%) thinking 带签名

修复前,重建后只命中 system 部分(559),其余约 1 万 token 要重新写入缓存。修复后,重建后的请求与在线请求的前缀完全一致,3 次都全量命中。

这项验证没有经过 host-core 的真实读写;落库往返由上面的 Rust 测试覆盖。Electron E2E 未跑。

Assistant rows stored only the concatenated thinking and answer text. When
the sidecar rebuilt a runtime (restart, thinking level, mode, rules, model
settings), history was replayed without the signatures pi-ai keeps on
content blocks, so Claude thinking went out as plain text, Responses
reasoning items and message ids were dropped, and other reasoning models
lost their replay fields. The request prefix changed from the first
reasoning reply on and the provider prompt cache was rewritten in full.

Record per-block lengths and signatures as additive transcript metadata
(`meta.providerReplay`, no migration) and restore the original blocks when
a runtime is rebuilt. Rows whose text no longer matches the stored lengths
keep the previous plain rebuild.

fixes vastsa#1972

@vastsa vastsa left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

已确认 #1972 的签名丢失问题真实存在;本 PR 对 thinking/text 的持久化方向合理,但 Gemini 工具调用路径仍留下同一根因,暂不能合入。

独立复现(head b2e708d):构造同一条 assistant 内容 [thinking(thinkingSignature), toolCall(thoughtSignature)],执行本 PR 的 capture -> JSON 可持久化元数据 -> restore,并按 historyToEntries() 的现有工具行路径补回 {type:"toolCall", id, name, arguments}。将 live 与 rebuilt 消息分别交给已安装 pi-ai 的真实 google-shared.convertMessages():live functionCall part 带 thoughtSignature,rebuilt functionCall part 没有;thinking part 的签名则正确保留。断言复现通过,无真实 provider 请求。

原因是 captureAssistantProviderReplay() 只记录 thinking/text,跳过 toolCall;historyToEntries() 从工具行重建时也只补 id/name/arguments。pi-ai 的 Google adapter 会把响应 functionCall 上的签名保存为 ToolCall.thoughtSignature,并在后续请求的 functionCall part 上回放它。这个值与 thinking/text 签名独立,恢复后两者并不能替代它。因此,对 Gemini 的正常工具调用历史,runtime 重建后请求仍不等同于在线历史;只有工具块带签名的消息甚至完全没有 providerReplay。

请沿现有方案最小补全:保存工具调用的 opaque 签名及稳定关联信息,重建对应 toolCall 时恢复(并保留跨模型/账号的签名隔离规则)。添加带工具结果的 Gemini live -> Host 持久化 -> runtime rebuild -> 请求体回归,覆盖只有 toolCall 带签名、以及 thinking 与 toolCall 同时带签名两种情况,验证 functionCall 签名、调用顺序和工具结果关联均保持。

验证说明:六项远端 CI 全绿,diff whitespace check 通过。上述独立生产 helper + provider converter 诊断确认缺失。尝试本地原测试套件时,在收集用例前遇到复用环境的 pi-ai 导出解析冲突(localRequestErrorDetails),不能算本地测试通过。未调用付费 provider、未跑 Electron E2E;原 PR 测试目前只有 Responses 无工具请求体覆盖,不能证明此路径已修复。

@muzimu217 muzimu217 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.

The design is sound and the degradation is the right one: record per-block {type, length, signature?, redacted?} in content order without duplicating text, then restore only when the lengths still line up and otherwise fall back to the plain-text rebuild. Length is a good guard precisely because it fails closed — any later edit, truncation or compaction that changes the text drops the replay instead of reconstructing the wrong blocks.

Carrying the Responses message id in the text block's signature field is a neat reuse and solves the msg_pi_N half of the problem too. Worth one line in the type comment saying so, because a reader who sees signature on a text block will otherwise assume it is thinking-only.

One thing I would like bounded before this lands: there is no cap on the replay payload. Signatures are opaque provider data — Anthropic's are a few hundred bytes per block, but redacted thinking payloads and Responses encrypted reasoning items can be kilobytes each, and this is stored on every assistant row that has reasoning. That trades one cost for another: it improves the cache hit rate on rebuild, and it grows the transcript for exactly the long sessions that already hurt (the full-rewrite inventory in #1836). A per-row ceiling that drops providerReplay above it — and therefore falls back to today's plain-text rebuild for that row — keeps the win for ordinary turns without letting one pathological row add megabytes.

The message_end condition (write only when this response's own text matches the final bubble and the turn did not fail) is the part I would keep an eye on in review: it is what stops a restored-text bubble from being captured as if it were freshly generated, and it deserves the test it apparently has.

Also worth stating in the description: providerReplay is additive in meta, so old builds read rows without it and new builds read old rows without it — no migration. That is the right call and should be said explicitly rather than inferred.

Gemini signs function calls separately from thinking and text, and pi-ai
keeps that value as `ToolCall.thoughtSignature`. The replay data only
covered thinking and text blocks, and rebuilt tool calls only got id,
name and arguments, so a rebuilt runtime still sent unsigned function
calls. A reply whose only signatures sat on its calls stored no replay
data at all, and an empty call-only bubble was not persisted.

Record call signatures by tool call id and restore them when the call
is rebuilt from its tool row; keep empty call-only replies that carry
them. Rows whose serialized replay data exceeds 64 KiB now drop it and
use the plain rebuild, so opaque payloads cannot grow the transcript
without bound.

Refs vastsa#1972
@zszz3

zszz3 commented Oct 29, 2026

Copy link
Copy Markdown
Contributor Author

@vastsa 感谢复现,确实漏了这条路径。已在 c633e52 补全,沿用现有方案:

  • 记录:captureAssistantProviderReplay() 现在会把带 thoughtSignature 的 toolCall 记为 providerReplay.toolCalls = [{ id, signature }],以 toolCallId 作为关联键(工具行带的是同一个 id)。只有 toolCall 带签名的消息也会写入 providerReplay。如果气泡文本不是本次响应自己的(恢复重试的情况),就丢掉 thinking/text 的块边界,只保留按 id 关联的调用签名。
  • 还原:historyToEntries() 从工具行重建 toolCall 时,按 id 从所属 assistant 行的 providerReplay 中补回 thoughtSignature;合成的 carrier 不带签名。还原后的消息保留原行的 provider/model,所以 pi-ai resolveThoughtSignature 的同 provider + 同模型 + base64 校验仍然生效,跨模型和账号的隔离规则不变。
  • 持久化:只有函数调用、没有文本的 Gemini 回复,原来会被 event-persistence.ts 当作空气泡丢弃。现在带 providerReplay 的空行也会保留,否则签名无处可存。

回归测试在 packages/agent-runtime/src/assistant-provider-replay.test.ts 的 “Gemini function-call signatures across a rebuild”:

  • 驱动在线 runtime 的 message_start / message_end 和 tool_execution_start / end,按 Host 的方式生成 assistant 行和工具行,经过 JSON 往返后新建 runtime。拦截 Google adapter 实际发出的请求体,对比在线请求和重建后的请求。
  • 覆盖两种情况:(a) 两个调用中只有第一个 toolCall 带签名;(b) thinking 和两个 toolCall 都带签名。
  • 断言重建后的 model parts 与在线请求完全相等(functionCall 签名、调用顺序都一致),functionResponse 的 name、id 和顺序也一致。
  • 变异检查:去掉 toolCall 签名还原,两个用例都会失败;去掉持久化条件,empty-assistant-persistence.test.mjs 中的新用例会失败。

本地复跑(本 worktree 的依赖解析到 pi-ai 1.4.0 patch,没有遇到 localRequestErrorDetails 冲突):agent-runtime 114 files / 1573 tests、shared 1336、desktop 4568 tests 0 fail、host-core 1088,以及 build / typecheck / lint / architecture / docs 检查,全部通过。没有调用真实的 Gemini,也没跑 Electron E2E。

@zszz3

zszz3 commented Oct 29, 2026

Copy link
Copy Markdown
Contributor Author

@muzimu217 Thanks — both points are in c633e52:

  • Size cap: captureAssistantProviderReplay() returns nothing when the serialized replay data for a row exceeds 64 KiB (MAX_PROVIDER_REPLAY_BYTES), so that row falls back to today's plain-text rebuild. Covered by a unit test.
  • Type comment: AssistantProviderReplayBlock now documents that a text block's signature is pi-ai's textSignature (the Responses message id or a Gemini thought signature), and what a thinking block's signature holds.
  • The description now states explicitly that providerReplay is additive in meta, needs no migration, and old and new builds can each read the other's rows.

The message_end guard is still there and tested; it now keeps only call-id-linked function-call signatures when the bubble text is not this response's own (also covered).

@vastsa vastsa left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

复核 c633e52:上次确认的 Gemini functionCall 签名丢失已补齐,可以合入。

工具签名按 call id 保存并在原 assistant carrier 上恢复;只有工具签名的空 assistant 行现在也经过持久化,既有 provider/account/model 身份处理保持原有隔离。64 KiB 上限提供有界退化,旧行继续走原恢复路径。没有发现额外范围或明显回归。

独立验证:匹配锁文件的隔离依赖环境下,agent-runtime 114 文件 / 1573 测试通过;空 assistant 持久化 13/13;Host providerReplay 元数据 roundtrip 测试通过;shared/runtime build 与 candidate Host build 通过;diff check 通过。另将作者 live/rebuild 请求体测试扩展为真实 Host RPC append -> 停止 -> 重启 -> session.get -> 新 runtime -> Google adapter 请求体比较,11/11 通过(默认 5 秒超时不足,调至 30 秒后通过)。两种 Gemini 签名组合及工具结果关联均通过,无真实 provider 网络请求。未跑本地 Electron UI E2E,远端 Electron 与 Windows transcript E2E 均通过。

最初复用环境实际 pi-ai 1.3.0,与锁定 1.4.0 不兼容,收集失败;已在专用审查目录按锁文件安装解决,未改主工作区依赖。当前 main f32a334 是 head 祖先,PR integration tree 与 head tree 同为 126e5376e790478758d6979498548dd308df0a7b,六项远端 CI 全绿。

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.

重建 runtime 后 thinking 签名丢失,导致 prompt cache 整段失效

3 participants