Skip to content

feat: bili acp-cache diff — prefix-diff attribution over ACP_DUMP_BODY dumps (#1266) - #1269

Merged
ranxianglei merged 3 commits into
masterfrom
2026-09-24_acp-cache-diff
Sep 26, 2026
Merged

ranxianglei merged 3 commits into
masterfrom
2026-09-24_acp-cache-diff

Conversation

@ranxianglei

Copy link
Copy Markdown
Owner

What

bili acp-cache diff <dump-dir> — read-only diagnostic that turns #1249's manual dump-diffing into one command (split out of #1254 suggestion ①).

For each session in an ACP_DUMP_BODY dump dir, it pairs adjacent requests (INCOMING = client raw wire; REQ = proxy-rebuilt wire) and classifies each pair:

Category Meaning
pure-append prefix stable, growth only at the tail → healthy
mid-stream-rewrite first divergent byte inside the shared prefix → reports byte offset + first divergent message + attribution (proxy / client / both)
prefix-stable-miss outgoing prefix append but provider usage shows the cached prefix collapsed → upstream TTL/eviction (the unattributed bucket of acp-kernel#393), correlated via [acp-usage] lines from bili.log

Key design points:

  • Two-tier comparison. Byte-prefix first, then JSON message-array-aware: a healthy array append moves the closing bracket, so strict byte comparison would misread it as a mid-stream rewrite. Shared elements are compared span-by-span + byte-exact; divergence is localized to a message index; pre-array field changes (e.g. model switch = different cache pool) are flagged separately.
  • Attribution compares where each side's wire first diverged: incoming append + outgoing mid-drift = proxy rewrite (the [Bug] oh-my-pi 长会话缓存命中率波动:相邻请求 99%→4%,125 folds 估算净收益为负 #1249 shape); identical drift on both sides = client; outgoing diverging earlier than incoming = both.
  • Usage correlation via --log FILE, --no-log, or auto-discovery (<dump-dir>/bili.log, then the default log path). Samples align to requests by timestamp (≤2 s slack). Miss threshold: cached_B < input_A − max(512, 2%·input_A).
  • Output: per-pair lines + top-5 worst offenders; --json for machine-readable reports. Purely read-only — no request-path or kernel changes; ACP_DUMP_BODY stays a manual diagnostic switch.

Prerequisite fix (in this issue's scope)

INCOMING dump filenames now carry the bound session id: <ts>-INCOMING.txt → <ts>-<sid>-INCOMING.txt (OUTGOING already had it) — without it, concurrent sessions cannot be paired. The dump site moves from pre-prepare to just after prepare, where the session is bound; content/masking unchanged. Legacy session-less INCOMING dumps still parse via timestamp proximity (nearest OUT within 30 s).

Behavior changes (disclosed)

  1. INCOMING dump filename: <ts>-INCOMING.txt → <ts>-<sid>-INCOMING.txt. Why: multi-session pairing ([Enhancement] bili acp-cache diff <dump-dir>: prefix-diff attribution over ACP_DUMP_BODY dumps (from #1254 ①) #1266 req 1). No in-repo consumer breaks (all DUMP_FILE_RE regexes still match).
  2. INCOMING dump timing: written post-prepare instead of pre-prepare. Requests rejected before prepare (bypass/passthrough/unknown paths) no longer produce an INCOMING dump — they never produced a REQ dump either, so no pairing data is lost. Content/format unchanged.

Pre-flight

  • npm run typecheck ✅
  • npm test: 2465/2470 pass. The 3 failures are tests/claude-native.test.ts hook-e2e tests (ps-walk/spawn-based) that fail identically on clean master (verified by stash A/B) — sandbox environment issues, unrelated to this diff.
  • npm run build ✅
  • New tests: 16/16 in tests/acp-cache-diff.test.ts (synthetic dump pairs for all three shapes, legacy filenames, usage alignment, render modes, plus a full-proxy harness test pinning the new INCOMING filename) + 2 parseArgs cases ✅
  • E2E codex: zero-token preflight ✅. Full 4-phase run blocked in this environment — the local sglang upstream (127.0.0.1:8199) was down at run time (ECONNREFUSED), and clean master fails the same way here. Note the server.ts change in this diff is inert unless ACP_DUMP_BODY=1 (not set by e2e). Please run the CI manual-dispatch E2E before merging.

Fixes #1266

中文摘要:新增只读诊断命令 bili acp-cache diff <dump-dir>,对 ACP_DUMP_BODY dump 做同会话相邻请求入站/出站前缀 diff,自动把缓存失效分类为 pure-append / mid-stream-rewrite(含代理 vs 客户端归因,#1249 形态可直接识别)/ prefix-stable-miss(对齐 bili.log 的 [acp-usage] 行,对应 acp-kernel#393 的 unattributed 桶),并顺带修复 INCOMING dump 文件名缺 session id 的前置问题;typecheck/build 通过、新增 18 个用例全绿,全量测试 3 个 claude-native 失败为沙箱环境问题(clean master 同样失败),完整 E2E 因本地上游服务临时不可用未跑通(clean master 一致),建议合并前跑一次 CI 手动 E2E。

@github-actions

github-actions Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

📦 Built Package Artifact

Branch: 2026-09-24_acp-cache-diff (362cdd9)

Option A — Install from npm PR tag (recommended)

npm install -g billion-context@pr-1269

Each push to this PR publishes a new version under the pr-1269 npm tag.

Option B — Download artifact

  1. Download the artifact from the Actions run
  2. Extract the tarball and install:
tar xzf billion-context-pr1269.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 #1269 reviewed — code verified against live master, all CI checks green. Per protocol I did not redo the work: fetched ranxianglei:2026-09-24_acp-cache-diff, read the full diff (7 files, +1056/−15), ran local verification, and made one small comment-accuracy commit (5507ccad) directly on the PR branch.

① Direction (vs #1266): Right root-cause framing. #1249 showed that attributing cache-prefix instability required manual dump-diffing; this turns that procedure into one read-only command without touching the request path or the kernel. The two-tier comparison (byte-prefix first, then JSON message-array-aware) is the correct design — strict byte comparison would misread every healthy array append (the closing bracket shifts position) as a rewrite, which is exactly the false-positive class #1249 suffered from. The attribution ladder (incoming-append + outgoing-mid-drift = proxy; identical drift both sides = client; outgoing diverging earlier = both) matches the observed #1249 shapes, and correlating [acp-usage] lines cleanly separates upstream TTL/eviction misses (the unattributable bucket from acp-kernel#393) from wire rewrites.

② Regression inventory (existing behaviors on touched paths):

  • INCOMING dump filename <ts>-INCOMING.txt → <ts>-<sid>-INCOMING.txt (disclosed): audited every in-repo consumer — tests/dump-mask.test.ts:25 (DUMP_FILE_RE) and its /-INCOMING\.txt$/ checks are suffix-based and still match; no other reader exists in-repo. ✅
  • INCOMING dump timing pre-prepare → post-prepare (disclosed): accurate for reject-before-prepare paths (no REQ dump exists for them). One nuance the description gets slightly wrong — bypass/passthrough requests do reach upstream and still emit <ts>-unknown-REQ.txt (src/server.ts:4244,4277), so pure-passthrough deployments lose their incoming side going forward. Impact is minor (the proxy rewrites nothing in those modes; outgoing-side analysis and usage correlation still work fully). See F1.
  • src/cli.ts parseArgs: unknown flags still exit 2; --json/--log/--no-log/--session are parsed globally like the existing export-only --full/--output — consistent with the file's convention. Side effect, flagged per behavior-change policy: e.g. bili start --json was previously rejected as an unknown option; it is now accepted and ignored.
  • The src/server.ts change is gated on bodyDumpEnabled() (ACP_DUMP_BODY=1) — inert otherwise; the e2e-codex job exercises the real client through the proxy without it. ✅
  • CONFIGURATION.md/.zh-CN.md: one table row each, zh/en in sync. ✅

③ Code review: clean. Chunked 64KiB prefix comparison avoids double-buffering; the JSON-aware tier requires exact span-count equality before trusting element alignment (falls back to byte mode otherwise); usage alignment is timestamp-based with 2s slack; legacy-filename pairing is bounded to a 30s window. One theoretical weakness, acceptable for a diagnostic: msgArrayInfo's regex could in principle match an escaped "messages" inside a JSON string value — guarded by the span-count equality requirement, worst case is a misclassification, never data corruption. No as any/@ts-ignore, no console.error, no kernel/wire changes.

④ Test quality: real tests with teeth, not ceremony. The critical regression pin is present: "healthy message-array append is append(json-tail), not a rewrite (#1266)" — this fails precisely if the #1249 misread shape returns. Coverage spans all three categories, the attribution ladder (proxy/client branches), the miss-threshold boundary (missedPrefix 500 < 512 floor stays pure-append; 99000 → miss), legacy filenames, model-change notes, empty-dir error, parseUsageLog loop/plugin variants + malformed-line skipping, plus a full-proxy harness test that pins the new INCOMING filename against a real server round-trip (port 0, env restored in finally — deterministic per §7.2). Gaps (acceptable for v1 of a diagnostic): the both attribution branch and preArray-divergence at the runDiff level aren't covered end-to-end.

⑤ Diff cleanliness: every line serves the PR's purpose; no whitespace churn, no lockfile/generated noise. Single linear commit; GitHub reports mergeable=true (master moved +10 commits since the branch point, touching only different regions of the two CONFIG docs).

F1 (minor, fixed in place): the comment at src/server.ts:2119 claimed requests skipping prepare "never reach upstream and have no REQ dump to pair" — true for reject paths, inaccurate for bypass/passthrough (they emit -unknown-REQ.txt). I corrected the comment to state the actual boundary precisely — commit 5507ccad (comment-only, pushed to the PR branch). The PR description's parenthetical "(they never produced a REQ dump either, no pairing data lost)" carries the same inaccuracy for bypass/passthrough; I didn't edit your description — suggest amending that sentence. Restoring an INCOMING dump on the fallback path (so passthrough users keep incoming-side data) is your call; my recommendation is not to bother, since the proxy rewrites nothing in that mode and the REQ dump already carries the verbatim body bytes.

Verification: local typecheck ✅; tests/acp-cache-diff.test.ts + tests/cli-parseargs.test.ts 22/22 ✅; CI on 29ca2c63: all 9 checks green (e2e zero-token, build, version-guard, test×4 OSes, pi lane, CODEX_HOME overlay). New commit 5507ccad is comment-only; CI re-running.

Verdict: mergeable — ready for human merge whenever you are.


中文摘要:审查了 PR #1269(新增只读诊断命令 bili acp-cache diff,对 ACP_DUMP_BODY dump 做前缀差分归因)——方向正确(两级比较避免了把健康数组追加误判为重写),代码干净,测试有牙且钉住了 #1249 的回归形态,CI 全绿;顺手修了一处不准确的注释(bypass/passthrough 请求仍会产出 sid=unknown 的 REQ dump,原注释称其"没有 REQ dump"不成立,已在 PR 分支补 commit 5507ccad),可以合并。

@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

[bot] 🏷 Follow-up: CI on the updated head 5507ccad (comment-fix commit) — all 9 checks green (e2e zero-token, build, version-guard, test ×4 OSes, pi lane, CODEX_HOME overlay). PR is in final state: 2 commits, mergeable=true, ready for human merge.

中文摘要:新 commit 5507ccad 的 CI 全绿,PR 已处于最终状态,可以合并。

@ranxianglei

Copy link
Copy Markdown
Owner Author

Independent deep review complete — one real bug found and fixed (head 51f0ee3), everything else verified.

Verified sound: two-tier compare (strict byte prefix / json-tail element stability — the array-append bracket-move problem is handled correctly), INCOMING↔REQ per-session pairing incl. legacy 30s adoption, attribution ladder (incoming append + outgoing drift → proxy; earlier incoming offset → client; passthrough-pair → client; both → both), prefix-stable-miss floors (512 abs ∧ 2% rel), worst-offender severity (earlier break ranks worse), JSON mode, session filter, and the INCOMING dump-site move in server.ts (trade-offs disclosed: pre-prepare rejections and bypass lanes lose INCOMING — they carry no attribution signal anyway).

End-to-end smoke (synthetic dumps through the real CLI): proxy-rewrite shape → MID-STREAM-REWRITE(proxy) with msg[2] pinpointed + "#1249 shape" note; client-rewrite shape → MID-STREAM-REWRITE(client); unparseable filenames ignored with a clear error. All three verdicts exact.

🔴 Bug fixed — alignUsage skew ran in the wrong direction. Condition outTs[i] <= s.ts + 2000 let a LATER request's dump claim an EARLIER response's usage line whenever adjacent requests sat < 2s apart — the compress-loop regime this tool exists to diagnose. Request A then lost its usage data and prefix-stable-miss detection silently disabled for exactly the dense case. Same-process clocks guarantee a request's dump precedes its own response's line, so the window now only absorbs write-ordering noise (USAGE_SKEW_MS = 50). Mutation-verified: the old window fails the new dense-cadence regression test (16/17), the fix passes (17/17).

Gates: typecheck ✓ / 2469 tests 0 fail / build ✓. Existing prefix-stable-miss tests never caught this because they use a 6.5s request gap — the new test pins the 1.5s gap.

@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

[bot] 🏷 Independent verification of the alignUsage fix (head 51f0ee3c) — bug confirmed real, fix correct, test has teeth.

Bug reproduction (independent of your analysis): traced the old condition outTs[i] <= s.ts + 2000 against a concrete timeline — A dumped @t+0.5s, B dumped @t+2.0s, A's usage line @t+1.0s: iterating from the latest request, B's dump (T+2.0s <= T+1.0s + 2s) grabs A's line, leaving A with no usage data → prefix-stable-miss silently disabled for exactly the <2s compress-loop cadence. Confirmed as described.

Mutation check (done myself, not just taken on faith): reverted USAGE_SKEW_MS to 2000 in a scratch copy and ran the suite — result 16/17, failing only the new dense-cadence test, matching your claimed mutation signature exactly. Restored; tree clean.

Fix review: direction is now correct — a sample can only attach to a request whose dump predates it (+50ms noise margin). The load-bearing invariant ("same-process clocks put the request dump before its own response's usage line") holds because [acp-usage] is logged at response completion and the next request in a session can only arrive after that response finished (per-session serialization makes concurrent dumps impossible). Degradation path is graceful: a sample matching nothing is dropped, not misfiled forward. 50ms is arbitrary-but-safe for a diagnostic; the invariant guarantees zero skew would already be sufficient.

Gates: local typecheck ✅; tests/acp-cache-diff.test.ts 17/17 ✅; CI on 51f0ee3c: all 11 checks green (full test suite ×4 OSes, e2e, hermetic registry e2e, build, version-guard, pi lane, CODEX_HOME overlay) — this covers your "2469 tests 0 fail" claim authoritatively. Commit is single-purpose (+38/−1, fix + regression test), no incidental churn.

Verdict: fix verified end-to-end. PR is in final state (51f0ee3c), ready for human merge.


中文摘要:独立验证了 alignUsage 的修复——旧窗口(+2000ms 方向反了)确实会让间隔 <2s 的后一个请求偷走前一个响应的 usage 行,使密集压缩场景下 prefix-stable-miss 静默失效;我本人做了变异测试(旧窗口 16/17、仅新回归用例失败,与你所述一致),修复逻辑与不变量成立,CI 全绿(11/11),可以合并。

ework-agent and others added 3 commits September 25, 2026 23:43
…Y dumps (#1266)

New read-only diagnostic command 'bili acp-cache diff <dump-dir>': pairs
adjacent same-session requests from ACP_DUMP_BODY dumps (INCOMING = client
wire, REQ = proxy-rebuilt wire) and classifies each pair:

- pure-append         prefix stable, growth only at the tail (healthy)
- mid-stream-rewrite  first divergent byte inside the shared prefix; reports
                      byte offset + first divergent message and attributes
                      proxy vs client vs both by comparing where each side's
                      wire first diverged (#1249 shape = incoming append +
                      outgoing mid drift -> proxy)
- prefix-stable-miss  outgoing prefix append but provider usage shows the
                      cached prefix collapsed (--log / bili.log correlation;
                      upstream TTL/eviction, the unattributed bucket of
                      acp-kernel#393)

Comparison is two-tier: byte-prefix first, then JSON message-array-aware so
a healthy array append (which moves the closing bracket) is not misread as a
mid-stream rewrite. Output: per-pair lines + worst offenders; --json emits
the machine-readable report. --log FILE / --no-log control usage-log
correlation (default auto-discovers <dump-dir>/bili.log or defaultLogFile()).

Prerequisite fix in the same issue scope: INCOMING dump filenames now carry
the bound session id (<ts>-<sid>-INCOMING.txt; OUTGOING already had it) so
concurrent sessions can be paired; the dump moves from the pre-prepare site
to right after prepare, where the session is bound. Requests rejected before
prepare no longer get an INCOMING dump (they never got a REQ dump either);
legacy session-less INCOMING dumps still parse via timestamp proximity.

Tests: synthetic dump pairs for all three shapes + legacy filenames + usage
alignment + render modes (tests/acp-cache-diff.test.ts), parseArgs cases,
and a full-proxy harness test pinning the new INCOMING filename.

Behavior changes (disclosed):
1. INCOMING body-dump filename: <ts>-INCOMING.txt -> <ts>-<sid>-INCOMING.txt.
   Any external tooling keying on the old shape must adapt (none in-repo does;
   DUMP_FILE_RE regexes still match).
2. INCOMING dumps now written post-prepare instead of pre-prepare (content and
   masking unchanged); pre-prepare rejections (bypass/passthrough/unknown
   paths) no longer produce INCOMING dumps.
…the predecessor's usage line

The +2000ms window ran in the wrong direction: request B's dump could claim
response A's usage line whenever B followed A by < 2s — exactly the
compress-loop cadence this tool diagnoses. Request A then lost its usage data
and prefix-stable-miss detection silently disabled. Same-process clocks put
the dump before its own response's line; 50ms absorbs write-ordering noise
only. Mutation-verified regression test (dense cadence, 1.5s gap).
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.

[Enhancement] bili acp-cache diff <dump-dir>: prefix-diff attribution over ACP_DUMP_BODY dumps (from #1254 ①)

1 participant