Skip to content

[PR] fix(#2612): refuse Claude Code native compaction on the wire — bili owns compression - #2849

Closed
ranxianglei wants to merge 2 commits into
masterfrom
fix/2612-claude-compaction-guard
Closed

ranxianglei wants to merge 2 commits into
masterfrom
fix/2612-claude-compaction-guard

Conversation

@ranxianglei

Copy link
Copy Markdown
Owner

What

Claude Code's native compaction is now refused on the wire by default, mirroring the #1729/#2028 dsh compaction guard — one PR covering the four pieces agreed in #2612/#2728:

# Piece Where
① Detector: the CC 2.1.x summarize template on the final user message, BOTH production phrases (strict-AND) src/server/claude-compaction-guard.ts (new)
② Wire interceptor: 403 refusal in the pipeline lane, never forwarded, kernel state untouched, metadata counters src/server/handle.ts (after the dsh guard)
③ Auto-compact primary lever: DISABLE_AUTO_COMPACT=1 in the managed block — already existed (applyClaudeManagedBlock); note text updated to say manual /compact is now refused instead of "survives" src/plugin-install.ts
④ Escape hatch: claude.allowNativeCompaction (config file) / BILI_ALLOW_CLAUDE_COMPACTION (env) src/config.ts + docs surfaces

Why refuse instead of letting it run

The two failure directions are both unrecoverable from bili's side:

Refusal channel = 403 API error, not text: CC renders it through its "Error during compaction" surface, the transcript stays verbatim, nothing executes. (A text reply would risk CC adopting it as the summary — the exact transcript destruction we're preventing.)

Detector contract (strict-AND) vs #2619 (either-phrase)

#2619 (merged earlier today) exempts CC compaction requests from the #2303 draft-tail retry by matching EITHER instruction phrase — fail-open by design, since a missed exemption only costs one wasted retry. The wire guard inverts the bias because it refuses a turn outright: it requires BOTH phrases, so a user legitimately asking for that output format ("summarize this, use an <analysis> block followed by a <summary> block") is not 403'd. A reworded CC template degrades to a miss → the request forwards → #2619's exemption still protects the retry path. Defense in depth, each layer failing in the safe direction for its own blast radius.

Coverage: anthropic (CC native), openai + responses (CC behind claude-code-router style installs keep the template text). Google stays out of scope (CC speaks no google wire). The #1117 passthrough lane is deliberately not guarded: it exists for unattributed in-process callers (#2709), never for external HTTP clients like CC.

Escape hatch

"claude": { "allowNativeCompaction": true } in the bili config file, or BILI_ALLOW_CLAUDE_COMPACTION=1 (env wins; 0 forces the guard back on when the file opted out) — the claude twin of dsh.allowDshCompaction (#2028). Opting in means accepting the desync trade documented in the config reference. Docs surfaces updated: server.yaml seed (EN+ZH), CONFIGURATION.md + CONFIGURATION.zh-CN.md via the generator (idempotent, check-coverage green).

Tests

tests/issue2612-claude-compaction-guard.test.ts (12 tests):

  • detector: full template on final user message across anthropic/openai/responses; single-phrase paraphrase NOT refused; mid-history quote NOT refused (final-user decisive); ordinary traffic; unparseable/unknown-protocol/google fail-open
  • refusal shape: anthropic {type:"error"} envelope vs openai/responses {error:{code:"claude_compaction_refused",retryable:false}}; message names the real opt-in
  • config resolution matrix: default OFF / file enables / env 0 beats file / env 1 / non-"0" env values enable (house BILI_ semantics); allowClaudeCompactionState sources
  • division of labor with fix: skip draft-tail retry when the request itself asks for the summary (#2612) #2619 pinned: requestExpectsProseSummary stays either-phrase, guard stays both-phrase
  • integration (real server + mock upstream): default → 403, zero bytes reach upstream, idempotent on repeat; half-phrase traffic forwards untouched; allowClaudeCompaction:true lifetime forwards the envelope

Regression-checked locally: issue2028-dsh-compaction-toggle (20+13 across the passthrough/guard files), dsh-compaction-guard, issue2612-compaction-draft-tail (#2619), issue1815-unknown-top-level-keys, plugin-agent, config-surface-guard, plugin-install-opencode, mitm, abort-rewind-cache-seam, issue2709-passthrough-compaction-guard, claude-subagent-split, issue2451/issue2432/codex-compact — all green. (claude-native.test.ts has 4 failures on this machine both with and without the branch — machine-local zone-port sticky record pins 18788 over ZONE_PORT_BASE 18787; hermetic CI unaffected.)

Closes #2612 (the ⅲ direction; ⅰⅱ were fixed by #2619, already merged). Relates to #2728 (boundary work for genuinely passing compaction through stays out of scope — the documented answer is: don't).

…wns compression

CC's own compaction (manual /compact, precomputed compression, auto-compact
when the managed DISABLE_AUTO_COMPACT=1 block is not in force) is now
refused locally with 403 before it can burn a full raw-history round-trip
upstream and desync CC's transcript from the fold ledger (#2612/#2728).
Escape hatch: claude.allowNativeCompaction in the config file, or
BILI_ALLOW_CLAUDE_COMPACTION=1 (#2728 opt-in family, mirrors #2028 dsh).
@github-actions

github-actions Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

📦 Built Package Artifact

Branch: fix/2612-claude-compaction-guard (1adef80)

Option A — Install this exact build (recommended)

npm install -g billion-context@0.0.3159-pr.2849.f116578

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-pr2849.tgz
npm install -g package

Install instructions are refreshed on each push.

@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

[bot] 🏷 Picked up. Identified PR #2849 (fix/2612-claude-compaction-guard @ d4324c5, base master, 9 files +584/−9). Kicking off the full review pass — direction vs #2612/#2728/#2619, regression surface, code, test validity, diff cleanliness — plus a targeted local test run and CI status. Structured conclusion (八问) to follow shortly.

…test

The step-C assertion accepted both 403 and 200 (a tautology — it passed under any behavior) because startServer does not hot-reload opts.allowClaudeCompaction within a lifetime. Tighten it to assert.equal(r.status, 403): this server was started without the opt-in, so it keeps refusing even after the config file flips above. The opt-in forwarding path is already covered by the fresh-server test below.
@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

[bot] 🏷 Review 完成(PR #2849 / 分支 fix/2612-claude-compaction-guard)。已本地定向验证并顺手修掉一处测试缺陷(见下)。按结构化八问给结论。

结论:可合(pending CI green on updated head)

中文八问

  1. 是什么问题:Claude Code 自己的压缩(手动 /compact、auto-compact、precomputed compression)经 bili 运行时,一旦成功 CC 会把本地转录改写为摘要,而 bili 的折叠账本仍锚定原始历史 —— 两边不可恢复地失同步([bug] bili claude: ACP state mismatch after CC native /compact (stale compressed block orphaned: acp_status/search_context reports no blocks, yet decompress can still retrieve by ID) | [bug] bili claude:CC 原生 /compact 后 ACP 状态失配(旧压缩块脱钩:acp_status/search_… #2728 家族);且该请求恰在"已经出事"时把完整原始历史再发一遍上游。

  2. 什么原因导致的:同一会话出现两个独立的压缩 owner。CC 单方面决定压缩并通过改写自己的转录来"宣布",bili 无从感知 → 折叠账本与 CC 转录永久分叉。缺陷的生产者是"CC 执行了一个 bili 未参与的压缩",不是某个可拦截的表面字节。

  3. 影响范围与严重程度:任何经 bili 路由的 Claude Code 安装(anthropic 原生线 + CC-router 装在 openai/responses 上),触发原生压缩时中招。严重度:这些会话里发生不可恢复的上下文失同步(非整体宕机——压缩触发前正常轮次照常工作)。因守卫默认 OFF,当前行为改变:旧=转发(→失同步);新=本地 403 拒绝,CC 显示 "Error during compaction"、转录逐字保留。

  4. 怎么修复的:拒绝而非转发。新增 claude 版线守卫(nudge 死锁无检测:同一 session 交替收到两种结构互斥的请求流(巨型单消息 ↔ 多轮)时不告警 #1729/在bili网页配置界面支持关闭和开启dsh的自动压缩功能 #2028 dsh 守卫的同构孪生):检测 CC 压缩信封(最后一条 user 消息同时携带 CC 摘要模板的两句短语,strict-AND;非命中 fail-open),跨 anthropic/openai/responses 三线路,在触碰任何 kernel 状态前本地 403 拒绝——零字节到上游、CC 转录逐字保留。逃生舱 claude.allowNativeCompaction / BILI_ALLOW_CLAUDE_COMPACTION=1 才转发(接受 [bug] bili claude: ACP state mismatch after CC native /compact (stale compressed block orphaned: acp_status/search_context reports no blocks, yet decompress can still retrieve by ID) | [bug] bili claude:CC 原生 /compact 后 ACP 状态失配(旧压缩块脱钩:acp_status/search_… #2728 权衡)。与 fix: skip draft-tail retry when the request itself asks for the summary (#2612) #2619 草稿尾重试豁免(任一句、fail-open)职责分离,互不吞对方触发器。

  5. 是否有回归问题:无。逐项过触碰路径——handle.ts 拦截块插在 dsh 守卫与 标题生成等侧请求污染主会话状态:prepareAnthropic 缺 isTitleGen 守卫、快照无条件覆盖、survivedCount 每请求空转 #388 side-lane 之间(两者均未动);config 纯增量键(无改名/改语义,unknown-key 守卫绿);dsh-compaction-guard.ts 两 helper 由 private→export(非语义);plugin-install.ts 仅修正 note 文案(旧文 "manual /compact survives" 现已不成立,属披露的行为变更);fix: skip draft-tail retry when the request itself asks for the summary (#2612) #2619 degenerate-turn 检测器本 PR 未改(只被新测试钉住)。本地定向跑:新守卫套件 12/12 绿;覆盖触碰路径的回归套件(draft-tail/fix: skip draft-tail retry when the request itself asks for the summary (#2612) #2619、claude-native、dsh-compaction-toggle、unknown-top-level-keys)62 pass / 0 fail / 8 skip(平台门控);typecheck 干净。高危模式逐项过:fail-fast 保留(拒绝是硬 403 非吞错)、无阈值/时序/输出格式漂移、wire 形状仅在拒绝路径引入(标准错误信封)、转发路径逐字节(测试钉死)。

  6. 是否破坏缓存:不涉及。前缀缓存不受影响(守卫在转发前运行,拒绝即不发);session metadata 新增两个计数(once-flag + refusals 计数),纯增量,不使既有缓存/去重键/游标失效。

  7. 是否改了设计方向:不变向。就是既有 dsh 守卫机制扩到 claude 车道,强化"bili owns compression"这一既定不变量;无新边界/数据流。

  8. 是否引入了新的配置:是,一个 opt-out(owner-gated 面,已按规范上报——config-surface-guard 绿):

    • 文件:{ "claude": { "allowNativeCompaction": true } }
    • env:BILI_ALLOW_CLAUDE_COMPACTION=1(0 强制开启守卫,即使文件已 opt-out;默认 unset/false = 守卫生效)
    • 已在 CONFIGURATION.md(en+zh)与 server.yaml 记录。迁移:无需(默认保留安全行为)。

我顺手修的一处(小问题直接修,已推独立标注 commit)

集成测试 step C 原断言 assert.ok(r.status === 403 || r.status === 200) 是恒真(任何行为都过)——因为 startServer 不在生命周期内热重载 opts.allowClaudeCompaction。已收紧为 assert.equal(r.status, 403) 并注释钉住"无热重载"契约(opt-in 转发路径已由下方 fresh-server 用例覆盖)。实测:收紧后 12/12 仍绿,证明该步确定性返回 403。

  • commit 1adef8098 test(#2612): pin the no-hot-reload contract in the guard integration test,作为加法提交叠在你原提交之上(未 rebase/替换你的工作与署名)。CI 正在更新后的 head 重跑。

其余各文件逐行读过:检测器用非全局正则(无 lastIndex 坑)、google 与 #1117 passthrough 明确排除在外(有文档说明)、config 解析矩阵(default OFF / file ON / env-0-beats-file / env-1 / 非"0"-enable)与 dsh 孪生完全同构。diff 干净:9 文件、无 version bump、无 lockfile/生成物连带变更、每行都与本 PR 目的相关。

小提醒(非阻塞):PR 正文列的回归文件名与仓库实际略有出入(如 issue2619-… 实际是 tests/issue2612-compaction-draft-tail.test.ts、issue2028-dsh-compaction-guard 实际为 …-toggle);我按实际覆盖触碰路径的套件跑的,均绿。不影响合并。

判定:方向正确、无回归、测试现已有牙、diff 干净 → 可合(等更新后 head 的 CI 全绿即可人工合并)。

@ranxianglei

Copy link
Copy Markdown
Owner Author

(ai: zhipuai-lb/glm-5.3)

陈旧票清理(第三批动作①):目标 issue #2612 已关。为避免重复劳动关闭本 PR;如判断有误请直接 reopen 并留言。

@ranxianglei ranxianglei changed the title fix(#2612): refuse Claude Code native compaction on the wire — bili owns compression [PR] fix(#2612): refuse Claude Code native compaction on the wire — bili owns compression Oct 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant