Skip to content

fix(#2565): scrub unpaired surrogate escapes out of every outgoing body - #2566

Merged
ranxianglei merged 3 commits into
ranxianglei:masterfrom
sorasoras:2026-10-10_lone-surrogate-wire-scrub
Oct 10, 2026
Merged

ranxianglei merged 3 commits into
ranxianglei:masterfrom
sorasoras:2026-10-10_lone-surrogate-wire-scrub

Conversation

@sorasoras

@sorasoras sorasoras commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Closes #2565

What

A strict upstream could permanently kill a conversation: every request from that session answered 400 invalid_request (non-retryable), while every other conversation on the same provider and key worked. Cause was an unpaired surrogate escape in the outgoing JSON body combined with two gaps:

  1. Nothing scrubbed the wire. scrubLoneSurrogates() existed in src/text-safe.ts, but its only caller was summaryFingerprintLine (src/stream.ts) — the human-readable log line. The outgoing body was never scrubbed.
  2. The existing guard cannot see the half anyway. JSON.stringify renders a lone half as the six-character escape text \uXXXX. By the time the body is a string there is no code unit left for the code-unit regex to match, so even a guard applied at the send seam would have found nothing. The wire needs an escape-text scanner.

Where the half came from: a compression summary holding a real lone code unit. A model that copies literal \uXXXX prose out of tool output (our ACP-status panel text is emitted in exactly that form) has it re-decoded along the summarizer path; stored verbatim, it re-serialized unpaired on every later request, so retries never healed. Cross-check on the live incident: the client-side recorded requests contained 0 unpaired escapes, while bili's stored summary for that session contained 1 — the poison was produced by the compression layer.

Changes

  • src/text-safe.ts
    • scrubLoneSurrogateEscapes(text): walks backslash runs — an escape only starts on an odd-length run, so doubled \\uXXXX (literal prose a model quoted) stays byte-identical; a well-formed high+low escape pair is kept verbatim; an unpaired half becomes the \uFFFD escape; ordinary escapes (\n, \t, \", \u0041, \u4e2d, …), short hex and a trailing backslash are untouched.
    • scrubLoneSurrogatesOnWire(text) = the above over the existing real-unit scrub. Use at send seams; use scrubLoneSurrogates alone on text that is not yet JSON-encoded.
  • Send seams (scrubLoneSurrogatesOnWire):
    • src/loop/core.ts — fetchUpstream's wireBodyStr (feeds the log/note views and the sent body, so all three agree).
    • src/server/relay.ts — the final-send seam, applied before applyResign so the signature covers the bytes actually sent, and the context-overflow refold re-send.
    • src/reasoning-guard.ts — the round re-send.
  • kernel — scrubLoneSurrogates() added to kernel/src/truncate.ts and applied to range summaries in kernel/src/compress.ts (applyCompression) so a half is never stored in the first place; the wire layer remains the belt-and-braces for already-poisoned persisted state.

Buffer bodies (raw passthrough) are deliberately untouched — only serialized JSON strings are scanned.

Pre-flight

  • npm run typecheck — clean (exit 0, no error TS).
  • npm run build — clean (tsup bundle + write-build-info + dist-import-annotations: OK).
  • npm test — 4953 pass; the 27 failures are pre-existing on this Windows box (they read a real ~/.zcode store and exercise symlink privileges) and reproduce identically on a pristine 4d5dab9 worktree; the one name that differed between the two runs (#1892 cert-MITM degraded mc-entry) is flaky — it passes on this branch and fails on pristine, so it is not a regression.
  • New tests all green:
    • tests/text-safe.test.ts — escape-scanner cases (lone high/low escape → \uFFFD, valid escape pair kept, doubled-backslash prose kept, ordinary escapes/short hex/trailing backslash kept, scrubLoneSurrogatesOnWire round-trip on a serialized poisoned body).
    • tests/wire-lone-surrogate-scrub.test.ts (new) — e2e against a mock upstream: a poisoned body still gets a 200, the upstream receives no unpaired half anywhere, the valid pair survives, U+FFFD present, and no udcca escape remains; a clean body is not over-scrubbed (content preserved, no U+FFFD introduced).
    • kernel/tests/scrub-lone-surrogates.test.ts (new) — code-unit scrub plus the ingest scrub of a stored summary.

Notes

Fourth site of the #816 / #828 / #1615 family — same signature (an unpaired half reaching JSON.stringify kills the whole body), but the first one where the escaping step itself is what hides the half from the existing guard. Confirmed still present in 0.1.189.


kernel-change: #2565 ingest scrub — scrub lone-surrogate halves out of range summaries at applyCompression so an unpaired half is never stored in compression state (kernel/src/compress.ts, kernel/src/truncate.ts); pairs with the host-side wire scrub in this same PR. Kernel bumped 0.0.111 -> 0.0.112.

@ranxianglei

Copy link
Copy Markdown
Owner

🤖 Powered by ework · qwen3.8-27b

[bot] 🏷 收到,正在按 PR Review 规范审查本 PR(wire / kernel 改动,人工合并范畴)。先审原 issue #2565 方向、再逐层回归 + 代码 + 测试有效性 + diff 整洁度,稍后给结构化八问结论。

@ranxianglei

Copy link
Copy Markdown
Owner

🤖 Powered by ework · qwen3.8-27b

[bot] 🏷 PR #2566 审查结论 — 方向对、修法正确且测试有牙,但当前不可合并(kernel-guard 红 + 需 rebase + pi-ws 待确认)。 已按规范走完五关(原 issue / 回归 / 代码 / 测试 / diff),并对 66-commit base drift 逐段核过。


一、审原 issue #2565(方向关)✅ 通过

  • bug 真实且诊断到位。我核对了 issue 的决定性证据:客户端录制请求 0 个 unpaired escape、bili 存储的压缩 summary 1 个 → poison 由压缩层产生,非客户端。这个分层判断是对的。
  • 根因定位正确,是「双缺陷叠加」而非单点:① ingest——summary 存了真实 lone half(模型把 tool output 里的字面 \uXXXX 抄进 summary,走 summarizer 路径被 re-decode 成真实 code unit);② wire——scrubLoneSurrogates() 唯一调用方只是 src/stream.ts 的日志指纹行,出向 body 从不 scrub,而且 JSON.stringify 把 lone half 渲染成六字符转义文本 \uXXXX,code-unit 正则根本看不到。PR 两个都修了,不是治标(疏非堵)。

二、回归审查(整体关)✅ 无回归

逐项清点触碰路径的既有行为:

三、代码审查(主关)✅ 逻辑正确

scrubLoneSurrogateEscapes() 的反斜杠 run 奇偶判定我逐 case 手推验证过:lone high/low→\ufffd、合法 high+low pair verbatim、\\uXXXX(双反斜杠=字面 prose)不动、\n \t \" \u0041 \u4e2d 等普通转义不动、短 hex/trailing backslash 不动、三连反斜杠相邻(\\\udcca)正确拆成「字面反斜杠 + 单 low escape」。边界(串尾 lone high、high 后跟非 surrogate escape)都对。实现健壮。

四、测试有效性(质量关)✅ 断言有牙

  • tests/text-safe.test.ts escape-scanner case:钉死精确字节行为含 over-scrub 守卫,非恒真。
  • tests/wire-lone-surrogate-scrub.test.ts(新):真实 poisoned body 过 proxy→mock upstream,断言 200 + upstream 收不到任何 unpaired half + 合法 pair 存活 + clean body 不被误伤。这是真集成覆盖,能兜底本 bug 回归。
  • kernel/tests/scrub-lone-surrogates.test.ts(新):code-unit scrub + ingest scrub。
  • CI 主 test job(ubuntu/windows 22、24)全绿——PR 自己的新测试通过,修复本身成立。

五、diff 整洁度 ✅ 干净

10 文件全部与本 fix 相关,无跑题文件、无生成物/锁文件连带变更。CHANGELOG 条目符合仓库惯例。


⛔ 合并前必须处理(3 项)

1. kernel-guard CI 红 —— 本 PR 自身问题(硬阻塞)
PR 改了 kernel/src/compress.ts + kernel/src/truncate.ts,但:

2. 需 rebase 到当前 master
head 落后 66 commit。我已确认无语义冲突,但按 §7.2 仍须 rebase + CI 全绿后再合。

3. pi-ws e2e test B 在 CI 红 —— 待你 re-run 确认
real pi codex-responses WebSocket lane 的 test B(e2e-pi-codex-ws.test.ts:592,断言 continuation frame carries the fold result)失败。该 workflow 此前连续 14 个 PR 全绿,仅本分支挂,所以不是长期 flaky。但我逐行分析:本 lane 是干净的确定性 mock body,scrub 对它走 fast-path 字节不变、wireTransform 纯/undefined,我不认为 scrub 逻辑是根因,更像这个 real-client 多 tool-loop WebSocket e2e 的时序 flake(该测试注释本身就说明 delta frame 只在多调用进程内浮现、对时序敏感)。受本地测试纪律约束(E2E 交 CI,不在本地预跑),我无法本地复现证明。请你 re-run 该 job:绿了即 flake 放行;若确定性复现,则是独立于本 fix 的另一条线,另查 WS continuation-expansion 路径。


结构化八问

  1. 是什么问题:strict upstream 会因 body 里一个 unpaired surrogate escape 整包 400(non-retryable),会话永久卡死且重试不自愈(compactEntry summary clamp (slice(0,199)+'…') can strand a lone high surrogate → same deterministic UTF-8 gateway 500 family #816/fix(decompress-shared): surrogate-safe clamp in search_context previews #828/[bug] summaryFingerprintLine 的 head/tail 裸码元切片产生孤立代理项 → 上游 JSON 400、会话永久卡死(#816/#828 同族第三站点;0.1.169 仍未修) #1615 家族第 4 处)。
  2. 什么原因导致的:双缺陷——(a) 压缩层把 lone half 存进 summary(模型抄字面 \uXXXX 被 re-decode);(b) 出向 body 从不 scrub,且 JSON.stringify 把 lone half 变转义文本使既有 code-unit 守卫失明。
  3. 影响范围与严重程度:命中 strict serde 类 upstream 的会话完全不可用(p1);触发条件=历史里进了 lone half(压缩 summary 或已污染持久态)。非 strict upstream 不受影响。
  4. 怎么修复的:新增 escape-text scanner(scrubLoneSurrogateEscapes,反斜杠 run 奇偶判定,只改 unpaired half→\uFFFD,合法 pair/prose/普通转义 verbatim)+ OnWire 组合;在 4 个序列化 seam 发送前 scrub(签名覆盖实发字节);kernel 侧 ingest 时 scrub summary 使 poison 不入存储(belt-and-braces)。
  5. 是否有回归问题:无。干净 body 字节不变、签名时序不变、Buffer passthrough 保真、双压缩模式均覆盖、base drift 无冲突(详见第二关)。
  6. 是否破坏缓存:不涉及。不改任何缓存/重试/增量游标/去重键;prefix cache 头部 system 稳定性不受影响。
  7. 是否改了设计方向:不涉及架构转向;仅在既有 send-seam 契约上加一道发送前 scrub,并让 kernel 存储前多一道 ingest scrub。
  8. 是否引入新配置:无新 env/config/默认值。

判定:暂不可合并。 核心修复本身正确、安全、测试充分;补齐 ①kernel-guard(marker+bump 或 split,owner 定)②rebase+CI ③pi-ws re-run 确认后即可合入。

@ranxianglei

Copy link
Copy Markdown
Owner

ework ci问题修复一下吧

@ranxianglei

Copy link
Copy Markdown
Owner

🤖 Powered by ework · qwen3.8-27b

[bot] 🏷 收到,我来修。两处红:①kernel-guard(本 PR 改了 kernel/src 但缺 kernel-change: 标记 + 没 bump kernel 版本)——我直接在 PR 分支补一个 kernel 版本 bump commit + 在 PR 描述加标记;②pi-ws e2e test B——我判断是时序 flake(本 lane 是干净确定性 body,scrub 对它字节不变),补的 commit 会触发全量 CI 重跑,一并验证。稍后回报结果。

sorasoras and others added 2 commits October 10, 2026 09:50
…outgoing body

JSON.stringify renders a lone surrogate half as the six-character escape
text \uXXXX, so once a body is serialized there is no code unit left for
the existing scrubLoneSurrogates() regex to find — and that function's
only caller was the log fingerprint line, never the wire. A summary
holding a lone half (a model re-decoding literal \uXXXX prose copied out
of tool output, our ACP-status panel text being the live trigger) was
therefore stored and re-emitted unpaired on every later request, and a
strict upstream parser rejected the WHOLE body with a non-retryable 400:
the conversation was permanently stuck while every other conversation on
the same provider and key worked.

Fourth site of the ranxianglei#816/ranxianglei#828/ranxianglei#1615 family — same signature, but the
first where the escaping step is what hides the half from the guard.

- src/text-safe.ts: scrubLoneSurrogateEscapes() walks backslash runs so
  an escape only starts on an odd-length run (doubled \uXXXX, literal
  prose a model quoted, stays byte-identical), keeps a well-formed
  high+low escape pair verbatim, rewrites an unpaired half to \uFFFD;
  scrubLoneSurrogatesOnWire() = that over the real-unit scrub.
- Seams: src/loop/core.ts fetchUpstream wireBodyStr, src/server/relay.ts
  final send (before applyResign, so the signature covers the sent bytes)
  and the overflow-refold re-send, src/reasoning-guard.ts round re-send.
- kernel: scrubLoneSurrogates() in kernel/src/truncate.ts, applied to
  range summaries at applyCompression ingest so the half is never stored.
- Buffer bodies (raw passthrough) are deliberately untouched.

Tests: text-safe escape-scanner cases; an e2e against a mock upstream
(poisoned body still 200, no unpaired half on the wire, valid pairs and
clean bodies untouched); kernel code-unit + ingest scrub.
@ranxianglei
ranxianglei force-pushed the 2026-10-10_lone-surrogate-wire-scrub branch from 7fc07e2 to d16c341 Compare October 10, 2026 01:55
@ranxianglei

Copy link
Copy Markdown
Owner

🤖 Powered by ework · qwen3.8-27b

[bot] 🏷 修好了,两处红都清了,PR 现在全绿可合。 新 head 1a2d437b9,14/14 workflow 全 success,mergeable: True。作者原有 commit 内容完整保留(rebase 重放),我只加了两个标注清晰的加法 commit。

① kernel-guard(本 PR 自身问题)— 已修

  • 根因:分支落后 master 66 commit,且 master 的 kernel 已到 0.0.111(PR 分支还停在 0.0.109)。CI guard 用三点 diff 对比 merge-base,要求「改了 kernel/src ⇒ 必须 bump kernel 版本」+「body 声明 kernel-change:」两条。
  • 修法:
    1. rebase 到当前 master(干净无冲突)——顺带解决 §7.2 stale-base,并避免版本行在合并时和 master 的 0.0.111 撞车;
    2. bump kernel/package.json 0.0.111 → 0.0.112(独立 kernel: commit,满足 Kernel Boundary 版本纪律);
    3. PR body 加 kernel-change: 标记(引 [bug] outgoing body is never scrubbed for unpaired surrogate escapes (JSON.stringify hides the half as escape text) → strict upstream 400, session permanently stuck (#816/#828/#1615 family, 4th site; 0.1.189) #2565 ingest scrub 理由,满足规则 1)。
  • 一个坑(已处理):guard 读的是 ${{ github.event.pull_request.body }}——触发时冻结的事件快照。我先前先 push 后改 body,导致那次 run 拿到的是无标记的旧 body。rerun 复用同一快照也没用,所以补了一个空 commit(ci: re-run…)重新触发,让新 run 读到已含标记的 body。该 commit 无任何文件改动,纯 CI 触发用。
  • 结果:kernel-guard = success。

② pi-ws e2e test B — 确认是 flake,非本 PR 引入

  • 之前判断:该 lane 是干净的确定性 mock body,scrub 对它走 fast-path 字节不变,逻辑上不可能被本 fix 影响。
  • 实测证实:重跑后 e2e-pi-codex-ws = success(新一轮也再次 success)。就是那个 real-client 多 tool-loop WebSocket e2e 的时序抖动,不是回归。

结构化结论

  1. 是什么问题:PR 的两个 CI 红灯——kernel-guard(缺门控标记+未 bump 版本)与 pi-ws e2e(时序 flake)。
  2. 什么原因导致的:前者=分支 stale + kernel 改动未按 Kernel Boundary 声明/升版;后者=real-client WS e2e 时序敏感,与本 fix 无关。
  3. 影响范围与严重程度:仅阻塞本 PR 合并,不影响任何运行时行为;非 flake 那条已被证明清白。
  4. 怎么修复的:rebase 到当前 master + 独立 kernel 版本 bump + body 加 kernel-change: 标记 + 空 commit 重新触发以让 CI 读到新 body。
  5. 是否有回归问题:无。我的改动全是 CI/门控卫生(rebase、版本号、body 文本、触发),不触碰任何运行时代码;作者的实际修复行为与其原稿完全一致。全量 suite(ubuntu/windows 22/24 + 全部 e2e lane)绿。
  6. 是否破坏缓存:不涉及。
  7. 是否改了设计方向:不涉及。
  8. 是否引入新配置:无新 env/config。唯一数值变化:acp-kernel 版本随本 PR 0.0.111 → 0.0.112(Kernel Boundary 强制,将随下次 release 一并发布,属预期)。

透明说明:① 我 force-update 了作者的 fork 分支(rebase 需要),其原始 commit 内容与署名保留;② package-lock.json 里 kernel 条目仍停在 0.0.110(master 既有的漂移,无 CI 校验强制、且最近一次 master kernel bump 也未同步它),为保持 diff 最小未改动——如你希望我顺手同步到 0.0.112 说一声即可。

判定:可合入。 等你人工 merge(PR 合并按规矩由人来)。

@ranxianglei
ranxianglei merged commit e207a48 into ranxianglei:master Oct 10, 2026
28 checks passed
@github-actions

Copy link
Copy Markdown
Contributor

📦 Merged Build Published

This merge to master was published as 0.0.211-master.e207a48 (rolling master tag).

npm install -g billion-context@0.0.211-master.e207a48  # 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

2 participants