Skip to content

fix: attribute proxy mode/projection switches distinctly from host prompt rewrites (#2867) - #2873

Merged
ranxianglei merged 3 commits into
masterfrom
wt-2867-ework-daemon
Oct 12, 2026
Merged

ranxianglei merged 3 commits into
masterfrom
wt-2867-ework-daemon

Conversation

@ranxianglei

@ranxianglei ranxianglei commented Oct 12, 2026 •

Copy link
Copy Markdown
Owner

What

Closes #2867

When a Responses session self-heals from plugin mode to proxy mode (#2155), the same mid-history system/developer items are projected differently by the two modes (plugin keeps them in place via __bili_inplace_sysdev, #1638; proxy hoists them into the front developer block, #1085). The forwarded-system fingerprint therefore flips even though the host changed nothing — and the cache ledger (#2350) narrated every such flip as host rewrote the system prompt. This PR separates the two fingerprints and classifies each flip at settle time.

How

  • Two fingerprints, one per question (src/fold-reconcile.ts, src/server/prepare-responses.ts):
    • existing systemFp = the FORWARDED projection (what actually went upstream; unchanged semantics);
    • NEW canonicalSysFp = the canonical INCOMING view (role + text + wire order of every sys/dev item, computed before mode-dependent marking, independent of pluginMode). Hash/length/mode/reason only — never the prompt body.
  • Classification at settle (src/cache-ledger.ts): projection flipped + canonical stable ⇒ new cause projection (new sparse line flags pf/pm, agg projSwitches/projSwitchMissed, own cold window, report section + invalidation bucket); canonical also changed ⇒ host-side prompt as today; canonical-only flip (e.g. mid-history edit under plugin in-place rules) ⇒ observational cf flag, no billing bucket; unknown sides never classify (legacy reading preserved for non-responses lanes).
  • Mode transition observability: prepare-responses records the serving mode (lastResponsesMode) and logs ONE line per transition with the reason (self-heal degrade / restore / header absent).
  • Web/admin parity: 🔀 column chip, detail attr chip + event table (src/web/client.ts, src/web/i18n.ts en+zh), stats fields (src/server/admin.ts).

Behavior changes (old → new)

  1. promptSwitches / cause=prompt / "PROMPT SWITCHES (host rewrote system prompt)" now fire ONLY when the canonical incoming view also changed. Sessions with pure self-heal mode switches show FEWER prompt events than before — those events move to the new projection dimension. Charged-token totals are unchanged (partition only).
  2. Cold rounds following a PURE projection flip now charge projection, not prompt. Before this PR the flip line opened BOTH switch windows (promptSwitched is true whenever the forwarded bytes change, which it does on a mode switch), so the cold tail re-attributed the proxy's own mode change to the host — the same bug class as the headline issue, found by the new test suite.
  3. New report surface: PROJECTION SWITCHES section, projection switch: invalidation line, report.projSwitches, readProjSwitchStats(), /__bili/stats fields projSwitches/projSwitchMissedTokens.
  4. New log line per mode transition: [responses] compression mode switched X→Y (reason).
  5. NO wire/message-shape or projection-behavior change: hoist ([Feature] Optimize the cache by reorganizing the context. #1085) and in-place ([Bug] bili 启动 OMP 后缓存命中率 82.7%,连续请求多次骤降至 4992 cached tokens #1638) rules are untouched — issue fix item 3 is resolved as the explicit-recording fallback (mode + reason recorded at every transition) rather than carrying one mode's projection across the switch, which would be a wire-shape change requiring owner sign-off.

Config surface

N/A — no new config file fields, env vars, or CLI flags. canonicalSysFp and lastResponsesMode are internal session.metadata keys (forensics inputs for the ledger), not user-facing configuration. Persistence format stays v1; new ledger fields are sparse and normalize-in-place on load (same mechanism as prior agg additions).

Verification

Golden regeneration justification (storage-render, follow-up commit 41cede6)

Per the rule in tests/golden-storage-render.test.ts (regeneration requires stated justification): this PR intentionally grows the persisted session surface, so the four storage-render goldens were regenerated. Only metadata-section digests changed (wire bytes / state / blockContents / stats unchanged):

  • cacheLedger.agg.projSwitches / .projSwitchMissed — zero-initialized on every lane, same established pattern as the existing switch-family counters (promptSwitches, keySwitches, …); covered by the normalize list so legacy sessions load them as 0.
  • responses lane: cacheLedger.lastKnownCanon (canonical incoming system fingerprint, needed to classify lines across a proxy restart) and per-line pm (mode under which the request was prepared); both undefined-gated at read time, so legacy sessions keep the legacy host-side reading.
  • session.metadata.canonicalSysFp + session.metadata.lastResponsesMode (responses lane, hash-only values, as documented above).

A/B proof: pre-PR master head cd02d2dc5 passes these goldens 5/5; the PR head reproduced the exact CI failure digests before regeneration. Reader paths verified legacy-safe (src/cache-ledger.ts: normalize list :656, lastKnownCanon gating :811-812, readProjSwitchStats fallback :1536). Report surface stays byte-identical when counts are zero.

@github-actions

github-actions Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

📦 Built Package Artifact

Branch: wt-2867-ework-daemon (41cede6)

Option A — Install this exact build (recommended)

npm install -g billion-context@0.0.3195-pr.2873.09243ec

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-pr2873.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] 🏷 收到,开始按 PR review 规范处理:拉取分支核对代码、检查 CI 状态、审查方向与回归面,结论将按结构化八问回复。

The committed self-heal e2e could never pass as written; CI red confirmed
it. All four defects were in the test itself — product code behaved exactly
as designed (verified via server logs):

1. Admin URL routed through the bili tunnel: `/__bili/cache-report`
   hit the mock upstream (any bodyless GET → 200 {}), so rj.reports.find
   threw before any attribution assertion ran. Use the loopback proxy port
   directly (same form as issue1547-nonstream-cache-ledger).
2. Zombie-window off-by-one: the kernel's first-turn tokenCount is 0
   (baseline stamped 0/falsy), so growth reads 0 at t2 and that round is
   nudge-idle — injections land t3..t7 and SELF_HEAL_WINDOW=5 arms at end
   of t7, making t8 (not t7) the first degraded prepare. Six headerless
   rounds now, with the timing documented inline. FILLER also grew
   repeat(28)→repeat(230) so mass outside the 5-message recent window
   clears minCompressRange/T1 threshold, plus a hermetic
   nudge.minGrowthFloor:100 override (issue2432 pattern).
3. Missing stream:true: only the streaming lane settles usage into the
   cache ledger; the non-streaming branch JSON-parses the SSE reply,
   fails, and passes through unaccounted (#1547) → "0 requests" report.
4. Malformed response.completed frame: data was a bare response object
   without the {type, response:{...}} wrapper; dispatch still fired via
   the event:-line fallback but data.response.usage read undefined →
   empty usage → no settle (plus in-band truncation errors from the pipe
   observer).

Verified locally: this suite 2/2 green; report shows PROJECTION SWITCHES
(1 switch · 9980 tok re-billed), projection switch: 9980 (1), prompt
rewrite: 0 (0), no PROMPT SWITCHES section; neighbors
cache-ledger-projection-switch/prompt-switch + responses-plugin-dev-position
21/21 green; typecheck clean.
@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

[bot] 🏷 PR #2873 review 结论(含我在 PR 分支上直接修掉的一处问题)

先说判定:这个 PR 的方向和产品代码是对的,但提交时的 e2e 测试按原样永远过不了——CI 红(ubuntu-22/24、windows-24 的 test job 全挂),本地复现确认。四个缺陷全在测试夹具本身,产品代码一个都没有。我已按「小问题直接修」在 PR 分支补了一个标注 commit(0629b65cf,仅 1 个测试文件 +50/−27,零产品代码改动)并 push,CI 正在新 head 上重跑(回帖时 15 in-progress / 10 queued)。

四个缺陷(均在 tests/responses-mode-switch-fingerprint.test.ts):

  1. admin URL 走隧道:${base}/__bili/cache-report 经 bili 隧道打到 mock upstream(对任何无 body GET 回 200 {}),rj.reports.find 在任何归属断言之前就 TypeError。已改为直连 loopback 代理端口(与 issue1547 测试同款形式)。
  2. zombie 窗口 off-by-one:kernel 首轮 tokenCount 为 0(baseline 记成 0/falsy)→ t2 growth≡0 → t2 是 nudge-idle → 注入实际落在 t3..t7 → SELF_HEAL_WINDOW=5 在 t7 末尾才 arm → 首个 degraded prepare 是 t8 而非原假设的 t7。已加一轮对齐时序并注释说明;同时 FILLER repeat(28)→repeat(230)(让 recent-window 外的质量越过 minCompressRange/T1 阈值)+ 测试内 nudge.minGrowthFloor:100 hermetic override(issue2432 同模式)。
  3. 缺 stream:true:只有 streaming lane 会把 usage 结算进 ledger;非流式分支对 SSE 文本做 JSON.parse 失败后原样透传、不记账(cache ledger: non-streaming rewriter path never records usage samples (ledger blind for stream:false sessions) #1547 共享结算路径)→ 报告恒为 "0 requests"。
  4. response.completed 帧畸形:data 是裸 response 对象,缺 {type, response:{...}} wrapper;dispatch 靠 event: 行 fallback(extractEventType rejects valid data:-only SSE streams → synthetic "upstream returned no response" #549)仍能触发,但 data.response.usage 读到 undefined → 空 usage → 无轮次结算(pipe observer 还会发 in-band truncation error)。

修复后的证据(本地实测):e2e 2/2 绿;/__bili/cache-report 输出 PROJECTION SWITCHES: 1 switch(es) · 9980 tok re-billed、失效分解 projection switch: 9980 (1) + prompt rewrite: 0 (0)、无 PROMPT SWITCHES 段、identity check residual 0。日志同时证实产品行为链完整:[self-heal] plugin lane gone for 5 nudged rounds … degraded to proxy mode → 本 PR 新增行 [responses] compression mode switched plugin→proxy (self-heal degrade-to-proxy (#2155)) … attributed to this projection switch, not a host rewrite (#2867) → [fold-reconcile] system prompt changed (2 → 86 chars)。相邻套件 cache-ledger-projection-switch / prompt-switch + responses-plugin-dev-position 共 21/21 绿;typecheck 干净。

结构化八问:

  1. 是什么问题:self-heal degrade-to-proxy 会翻转 forwarded-system 投影(plugin 保持中历史 sys/dev in-place [Bug] bili 启动 OMP 后缓存命中率 82.7%,连续请求多次骤降至 4992 cached tokens #1638 vs proxy 提升到前部 developer block [Feature] Optimize the cache by reorganizing the context. #1085),cache ledger([cache-ledger] fold-reconcile 检测到宿主侧系统提示词改写但未接入归因:prompt 改写被误归入未归因 TTL 残差 #2350)把每次这种翻转误叙述成「host 重写了系统提示词」。
  2. 什么原因导致的:两层——(a) PR 的上游根因:ledger 只有一维指纹(forwarded projection),无法区分「bili 自己的模式/投影切换」和「host 真的改了 prompt」;(b) PR 自身:产品代码无缺陷,但验证用 e2e 夹具带四个独立缺陷,使 PR 正文的 Verification 声明对提交代码为假(CI 红即证据)。
  3. 影响范围与严重程度:bug 本体影响所有经历 self-heal degrade 的 Responses 会话——纯归属误标,计费总额不变(只是桶间划分错了);坏测试意味着该功能此前没有有效的端到端回归网且 CI 红挡合并。我的修复是 test-only,生产零影响。
  4. 怎么修复的:双指纹(canonicalSysFp = 模式无关的 canonical incoming 视图,在 mode-dependent marking 之前计算,只存哈希不存 prompt body)+ settle 时分类(投影翻转且 canonical 稳定 ⇒ projection;canonical 也变 ⇒ prompt;仅 canonical 变 ⇒ 观察性 cf)+ 每次模式切换一行日志 + web/admin 展示对齐。我这边按上述四项最小化修复夹具,未动产品代码(临时插桩已全部还原,diff 只剩一个测试文件)。
  5. 是否有回归问题:无。逐项过既有行为:cache-ledger-prompt-switch 8 测([cache-ledger] fold-reconcile 检测到宿主侧系统提示词改写但未接入归因:prompt 改写被误归入未归因 TTL 残差 #2350 原语义)不变且绿;responses-plugin-dev-position 4 测([Bug] bili 启动 OMP 后缓存命中率 82.7%,连续请求多次骤降至 4992 cached tokens #1638 in-place 规则)不变且绿;fold-reconcile 的 sp 语义未动(canonical 是新增独立 key);persistence v1 未动(新字段 sparse + load 时 normalize);wire/message shape 无变化(hoist/in-place 两条投影路径原样);全量回归交给 CI。
  6. 是否破坏缓存:不涉及缓存/重试/游标/去重策略;ledger 本身只是观测面。
  7. 是否改了设计方向:没有。归属维度增加一维(projection),分类仍互斥且总和守恒,与 [cache-ledger] fold-reconcile 检测到宿主侧系统提示词改写但未接入归因:prompt 改写被误归入未归因 TTL 残差 #2350 框架一致。
  8. 是否引入新配置:无新 config/env/CLI。canonicalSysFp/lastResponsesMode 是内部 metadata key;minGrowthFloor:100 override 只存在于测试自建 server 实例内,不随包发布。

行为变更披露(本 PR 自身,沿用 PR 正文):promptSwitches/cause=prompt 现在仅在 canonical incoming 视图也变化时才触发 → 纯 self-heal 切换移入新的 projection 维度(token 总额不变,划分调整);纯投影翻转后的冷轮次现在记 projection 而非 prompt;新增 report/stats/web 面(PROJECTION SWITCHES 段、projSwitches/projSwitchMissedTokens、🔀 chip);每次模式切换多一行 info 日志。wire 形状无任何变化。

收工判定:base 即当前 master,本地 typecheck + 定向套件全绿,diff 收敛到单一测试文件且每行都服务于本次修复——CI 转绿即可合并。合并链接:#2873

…ode fields

Justification (tests/golden-storage-render.test.ts header requires stated
justification for regeneration):

PR #2873 intentionally grows the persisted session surface; the committed
goldens predate it. Only the metadata-section digests drift — wire bytes,
state, blockContents and stats digests are all unchanged:

- cacheLedger.agg gains projSwitches/projSwitchMissed zero-initialized on
  every lane: the same established pattern as promptSwitches/keySwitches/
  wireSwitches/... (every switch-family counter is unconditionally
  zero-initialized); the normalize list (src/cache-ledger.ts:656) covers
  them, so legacy sessions without the keys load as 0.
- responses lane only: cacheLedger.lastKnownCanon (the canonical incoming
  system fingerprint, required to classify future lines across a proxy
  restart) and per-line pm (the mode under which each request was
  prepared); both are undefined-gated at read time (src/cache-ledger.ts:
  811-812), so legacy sessions keep the legacy host-side reading.
- session.metadata gains canonicalSysFp + lastResponsesMode (responses
  lane, hash-only values, documented in the PR body).

A/B proof: pre-PR master head cd02d2d passes these goldens 5/5; the PR
head reproduced the exact CI failure digests before regeneration. Reader
paths verified legacy-safe (normalize list :656, lastKnownCanon gating
:811-812, readProjSwitchStats fallback :1536). No report-surface change:
sections stay byte-identical when counts are zero.
@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

[bot] 🏷 第三轮更新:第二次 CI 红已解决 — golden 快照过期(非产品回归)

上一轮推入 fixture 修复(0629b65cf)后 CI 再次变红,但这次失败的不是我们的测试文件:tests/golden-storage-render.test.ts 四条 wire(chat/anthropic/responses/google)全挂,且只有 metadata 段 digest 漂移(state/blockContents/stats 全部一致)。

八问(本轮增量):

  1. 是什么问题:golden 快照生成于本 PR 之前;PR 有意扩大了持久化 session 面,旧快照没有新字段 → 纯快照过期,不是功能回归。
  2. 什么原因导致的:产品代码写入了三类新持久内容——① 所有 lane 的 cacheLedger.agg.projSwitches/projSwitchMissed 零初始化(沿用既有模式:promptSwitches/keySwitches/wireSwitches 等全部开关族计数器本就无条件零初始化);② responses lane 的 ledger 顶层 lastKnownCanon(canonical 指纹,跨 proxy 重启分类所必需)+ 每行 pm(mode 标记,只写无读);③ session.metadata 新增 canonicalSysFp/lastResponsesMode 两键。三者都是 PR 设计内行为(正文已声明 "persistence stays v1, new ledger fields sparse + normalize-in-place on load")。
  3. 影响范围与严重程度:无生产影响。新字段全部可选,读取路径逐一验证 legacy-safe(normalize 清单 src/cache-ledger.ts:656;lastKnownCanon undefined 门控 :811-812;readProjSwitchStats 的 ?? 0 兜底 :1536);计数为零时报告面字节级不变。严重度 = 仅测试基建挡合并。
  4. 怎么修复的:用 scripts/update-storage-render-goldens.ts 重新生成四个 storage-render golden。diff 共 8 行(每 wire 仅 stateDigest + metadata digest),wire 字节/state/blockContents/stats 均未变。理由按测试文件头规则写入 commit body 并追加到 PR 描述(Golden regeneration justification 一节)。
  5. 是否有回归问题:无。A/B 证据:pre-PR master head cd02d2dc5 上这些 golden 5/5 通过;PR head 在再生前精确复现 CI 的失败 digest → 漂移来源唯一锁定为本 PR 的有意持久化扩展。再生后本地 golden 套件 5/5。
  6. 是否破坏缓存:不影响。缺新字段的老 session 加载正常(上述三处读取路径验证)。
  7. 是否改了设计方向:否。
  8. 是否引入新配置:否。

当前状态:分支 wt-2867-ework-daemon @ 41cede6d6 已推送(775afb0 原 PR + 0629b65 fixture 修复 + 41cede6 golden 再生)。CI 首轮轮询:21 绿 / 8 running(含此前红的 4 个 test 矩阵 job),暂无 failure。等 CI 全绿即可合并。

@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

[bot] 🏷 CI 全绿,收工判定

41cede6d6 上 29/29 check 全部通过(含此前红的 4 个 test 矩阵 job),无 failure/cancel。

分支 wt-2867-ework-daemon 最终形态(3 commits):

产品代码零改动(相对原 PR);行为变更披露维持原 PR 正文所列五项不变。本地定向验证(golden 5/5、e2e 2/2、邻接套件 21/21、typecheck)与 CI 全量回归一致。

判定:可合并。 合并由人执行:#2873

@ranxianglei
ranxianglei merged commit 56063ce into master Oct 12, 2026
29 checks passed
@github-actions

Copy link
Copy Markdown
Contributor

📦 Merged Build Published

This merge to master was published as 0.0.308-master.56063ce (rolling master tag).

npm install -g billion-context@0.0.308-master.56063ce  # 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] Responses self-heal 切换投影规则后,提示词指纹变化被误归因为宿主改写

1 participant