Skip to content

fix: eliminate 0.1.193 long-session CPU regression — unused SimHash sketches + duplicate history conversions (#2824) - #2828

Merged
ranxianglei merged 3 commits into
masterfrom
2026-10-12_issue2824-sketch-image-perf
Oct 12, 2026
Merged

ranxianglei merged 3 commits into
masterfrom
2026-10-12_issue2824-sketch-image-perf

Conversation

@ranxianglei

Copy link
Copy Markdown
Owner

Closes #2824

What this fixes

Two independent CPU costs introduced at the request entry point between 0.1.192 and 0.1.193, which together took long-session local time from ~1.3s to ~3.2s per turn.

RC1 — identified-session fingerprint computed SimHash sketches it never used

After #2791/#2807 moved chainFingerprint to the wire-neutral domain, EVERY request of an identified session ran the fused hash+sketch pass (neutralFingerprints) — but its product contains NO sketches, and identified note() stores none. On a 24K-turn session that was ~22K SimHash evaluations per request; SKETCH_MEMO_CAP=8192 cannot warm across a sequential scan longer than itself, so even repeated resends recomputed ~22K.

Fix: neutralFingerprints(turns, sketchCap = 0) — sketches opt-in per caller:

  • resolve() passes SKETCH_MAX_DEPTH (2048) — the only caller whose consumer reads sketches (simhash adoption). Provably equivalent: alignment's alignLen is bounded by the stored side's cap and note() slices to it anyway, so positions ≥ 2048 were never read from incoming sketches.
  • chainFingerprint / findResumeParent / findResumeParentWithin / chainContinues pass 0 (hashes-only products).

All return values are byte-identical to before; only CPU drops. Also removes the dead v1 itemFingerprints (zero references since #2791) and adds simhashComputeCountForTest() for regression observability.

RC2 — no-image requests converted the full history wire→core twice extra

Every regular request ran buildIncomingImageIndex in prepare AND refreshIncomingImageIndex after prepare — each build re-converts the ENTIRE history before discovering there are no images.

Fix: bodyMightCarryImages(bodyText, protocol) — one cheap raw-text pass over the already-parsed body string, computed once after JSON.parse while the protocol is stable. It OVER-APPROXIMATES BY DESIGN: markers mirror every shape messageImageBytes indexes (data-URL for openai/responses/anthropic source.url; anthropic source.type:"base64"; google inlineData top-level + nested in functionResponse), so a false positive costs one wasted conversion and a false negative cannot drop image recovery. When false, both sites yield exactly what today's builds return for an image-free body (empty / unchanged index). Image-bearing sessions run BOTH builds unchanged — the #1995/#2607 ref-refresh + recovery contract is preserved.

Behavior changes (CPU-only; all wire/persistence products byte-identical)

Path 0.1.193 After
identified-session chainFingerprint ~N SimHashes/request (N ≈ turns; memo thrashes > 8192) 0
anonymous cold resolve N SimHashes ≤ 2048 (SKETCH_MAX_DEPTH; note() sliced to this anyway, adoption never reads past the stored cap)
no-image request 2 extra full-history wire→core conversions 0
image-bearing request unchanged unchanged (predicate true → both builds run)

Audited-safe edge: openai single-object content: {type:"image_url"} fires the predicate but the kernel never sidecars an image from non-array content — guarded and unconditional builds both return ∅ (pre-existing kernel behavior, out of scope).

Config surface

N/A — no new config field, env var, or CLI flag. Pure internal optimization; no wire, persistence, or API change.

Verification

  • New tests/issue2824-regression.test.ts (7 tests, green): 8300-message deep history (> memo cap 8192, > sketch cap 2048) — hashes-only paths compute ZERO sketches; cold resolve computes exactly 2048 and a warm resend recomputes zero (memo stays warm); similarity adoption still works beyond the sketch cap (via simhash, coverage ≥ 0.9); predicate flags every indexable shape non-vacuously (each fixture also builds ≥ 1 entry); negatives stay false; guarded path ≡ unconditional build across the corpus.
  • Targeted suites green locally: prefix-affinity, prefix-affinity-simhash, image-restore, fold-images-archive (58/58), prefix-affinity-orphan (5/5); typecheck clean. Full suite + e2e to CI.
  • Matches the issue's offline A/B anchors: chainFingerprint median 521ms (0.1.192) / 1940ms (0.1.193) / 603ms (prototype); no-image openaiToCore 1×/166ms (old) vs 3×/518ms (new); forwarded-body SHA256 identical across rounds.

ework-agent added 3 commits October 12, 2026 01:31
The #2791/#2807 wire-neutral rewrite made chainFingerprint run the fused hash+sketch pass, but its product carries no sketches and identified note() stores none — every request of a long session recomputed ~22K SimHashes (SKETCH_MEMO_CAP=8192 cannot warm across a sequential scan longer than itself): 0.1.193's ~2.2s/request identified-path cost.

neutralFingerprints now takes a sketchCap (first N positions, default 0 = none): resolve() passes SKETCH_MAX_DEPTH (alignment can never read beyond the stored side's cap and note() slices to it anyway — provably byte-identical products); chainFingerprint/findResumeParent/findResumeParentWithin/chainContinues pass 0. All return values unchanged; only CPU drops.

Also removes the dead v1 itemFingerprints (zero references since #2791) and adds simhashComputeCountForTest for regression observability.
…2824)

Every regular request ran buildIncomingImageIndex in prepare AND refreshIncomingImageIndex after it — each build re-converts the FULL history wire→core before discovering there are no images (~351ms of extra conversion per turn on the 32MiB fixture; old 0.1.192 built at most once behind the stripImages condition).

bodyMightCarryImages(bodyText, protocol) is one cheap raw-text pass over the already-parsed body string, computed once after JSON.parse while the protocol is stable. It OVER-APPROXIMATES by design — markers mirror every shape messageImageBytes indexes (data-URLs for openai/responses/anthropic source.url, anthropic source.type base64, google inlineData top-level and nested), so false positives cost one wasted conversion and a false negative cannot drop image recovery.

When the predicate is false both sites yield exactly what today's builds return for an image-free body: an empty index (entry) / the unchanged previous index (refresh). Image-bearing sessions run both builds unchanged, preserving the #1995/#2607 ref-refresh + recovery contract.
Pins both regression facets on an 8300-message deep history (> SKETCH_MEMO_CAP 8192 and > SKETCH_MAX_DEPTH 2048): chainFingerprint/findResumeParent/findResumeParentWithin/chainContinues compute ZERO SimHashes; anonymous cold resolve computes exactly 2048 and a warm resend recomputes zero (memo stays warm); similarity adoption still works beyond the sketch cap (via 'simhash', coverage >= 0.9). Image-index guard: bodyMightCarryImages flags every indexable shape non-vacuously (each fixture also builds >= 1 entry), stays false for text-only/remote-URL bodies, and the guarded path deep-equals the unconditional build across the corpus.
@github-actions

Copy link
Copy Markdown
Contributor

📦 Built Package Artifact

Branch: 2026-10-12_issue2824-sketch-image-perf (4c084af)

Option A — Install this exact build (recommended)

npm install -g billion-context@0.0.3133-pr.2828.9cc867e

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-pr2828.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 镜像(对应 GitHub PR #2828,分支 2026-10-12_issue2824-sketch-image-perf,基于 master 47386e6f0,3 commits / 5 files / +305−35)。开始独立核对:拉分支读全量 diff、按 PR Review 规范过方向关/回归关/代码关/测试关/整洁度,定向本地验证后给八问结论。

@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

[bot] 🏷

PR #2828 独立审查结论(修 #2824):可合并(仅剩 2 条 Windows CI leg 在跑)。

所有声明都在 PR head(4c084afd,base == 当前 master 47386e6f,无需 rebase)上逐行读码独立核实,未照抄 PR 描述。

结构化八问:

  1. 是什么问题:0.1.193 长会话每 turn 本地耗时 1.3s→3.2s。两个独立的请求入口 CPU 成本:①identified 会话每个请求在 chainFingerprint 里计算从不被使用的 SimHash sketch(24K turn 会话 ~22K 次/请求,memo cap 8192 < 扫描长度,重复 resend 也命中不了);②无图请求多跑两次全历史 wire→core 转换(buildIncomingImageIndex + prepare 后 refreshIncomingImageIndex)。
  2. 什么原因导致的:①dsh anthropic-messages lane bypasses native-intercept fetch patch: anonymous pfa-* session, fold ledger orphaned, silent ~182s re-fold on cross-protocol switch #2791/fix(sessions): wire-neutral affinity hashing for cross-protocol continuity (#2791) #2807 迁 wire-neutral 域后 hash 与 sketch 融合进同一 pass(neutralFingerprints),而 hashes-only 调用方的产物从来就没有 sketch 字段——计算与消费脱钩;②stripImages 滑窗剥离的图片无恢复通道,且滑窗每轮击穿 prompt cache(billion-context-pi#593 同族缺口) #1995/建议:compress.stripImages 默认开启——否则带图消息不可压缩会形成只升不降的输入地板撑爆上下文 #2607 把图片索引从旧的 stripImages 条件分支改为无条件构建时,丢掉了无图请求的零成本路径。都是「机制变更引入无条件成本」,不是负载问题。
  3. 影响范围与严重程度:所有 identified 会话请求(长会话最重,~2.4× 变慢)+ 所有无图常规请求(全部纯文本会话)。纯性能回归,非功能缺陷——压缩、wire、持久化行为均不受影响。
  4. 怎么修复的:①sketch 改 opt-in:neutralFingerprints(turns, sketchCap = 0),唯一消费方 resolve() 传 SKETCH_MAX_DEPTH(2048),其余四个 hashes-only 调用点传 0;顺带删除零引用的 v1 itemFingerprints。②新增原始文本预检 bodyMightCarryImages(bodyText, protocol),JSON.parse 后算一次,false 时两处索引位直接产出空 Map。两个修法都移除成本的产生源头而非过滤症状,符合「疏不堵」原则。
  5. 是否有回归问题:未发现破坏。既有行为逐项清点:
    • 匿名解析:我证明了 alignLen = min(entry.depth, entry.sketches.length≤2048, incSketches.length≤2048) 与改动前逐字节相等(stored 侧本就 ≤2048,incoming cap 不改变 min 结果);ALIGN_MIN_DEPTH(8) 守卫同证不变;mint 路径存储的 sketch 经 note() 本来就会 slice 到 2048 → 持久化内容与旧值相同。adoption 行为由新测试在 8300 turn 深度钉住(via=simhash,coverage≥0.9)。
    • identified 路径:chainFingerprint 返回形状 {depth,tailHash,itemHashes,normTailHash?,tailFrags?} 本就不含 sketch 字段,产物字节相等;findResumeParent/findResumeParentWithin/chainContinues 只用 .hashes。
    • 图片索引:谓词标记与 messageImageBytes 实际索引的 8 种形状逐一对照全覆盖(anthropic base64/url/嵌套 tool_result、responses input_image 含 function_call_output.output、openai content-parts/singular content、google inlineData 顶层+functionResponse 嵌套);parseDataUrl(/^data:([^;,]+)(?:;base64)?,(.+)$/i)与标记正则等价(JSON 字符串值不含裸引号);refresh 跳过是结果等价的(body 无图片字节时任何新 ref 的 messageImageBytes 都返回 [],refresh 不可能产生条目);count_tokens / protocol=null / 空 body 路径按原样短路。
    • 高危模式:无语义漂移、无 fail-fast 变吞错、无阈值/时序/输出格式漂移;forwarded body 字节不变(diff 未触碰 forward/loop 路径,SHA256 恒等声明可由 diff 本身推出)。
    • 残留(非阻塞):谓词作用于原始文本,若某序列化器把 ASCII 字母 unicode 转义(如 \u0064ata:)会假阴性——主流序列化器均不转义 ASCII,且即便发生也只使图片恢复退化为 pre-stripImages 滑窗剥离的图片无恢复通道,且滑窗每轮击穿 prompt cache(billion-context-pi#593 同族缺口) #1995(不恢复),不会损坏数据;属其文档化的 over-approximate 设计边界,不值得单独立项。
  6. 是否破坏缓存:否。prefix-cache key = forwarded body 字节,不变;会话持久化格式不变;simhash memo 语义不变。
  7. 是否改了设计方向:否。现有机制内的纯性能修复(sketch 只算给消费者;可证明为空的工作跳过)。
  8. 是否引入新配置:否(PR 自报 config surface N/A,diff 确认无 env/config/flag)。

测试有效性:有牙。8300 消息深历史(> memo cap 8192、> sketch cap 2048)钉住「hashes-only 零计算」「冷 resolve 恰好 2048、热 resend 零重算」「超 cap adoption 仍工作」;图片侧 fixture 非空断言(每个 fixture 同时断言索引出 ≥1 条目,防谓词断言空真)+ guarded≡unconditional 语料等价 + 故意 over-approx 用例(pdf inlineData 触发但 ∅)。本地复跑:9 个文件 86/86 绿(issue2824-regression + prefix-affinity×3 + affinity-neutral/crosswire-fold/persist + image-restore + fold-images-archive),typecheck 干净,build 干净(4c084af)。

CI:27/29 绿(ubuntu test×2、e2e、kernel-guard、各 lane 套件、registry e2e、image billing 等),剩 2 条 windows-latest test leg in_progress——与 ubuntu 同一套全量单测,ubuntu 已绿;若红我再定向追。

diff 整洁度:5 文件 +305/−35,每行都与本 issue 相关,无 lockfile/空白噪声。

判定:可合并。 auto-merge 门(§7.4):单机制性能修复 + 回归测试 + rebased-head 绿 + 不触碰 config schema/wire/kernel/update.ts → 满足;是否自动合并留给人/CI。

@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

[bot] 🏷

CI 收尾:最后两条 windows-latest test leg(22/24)也已通过——4c084afd 上 29/29 全绿,无任何失败项。上一条审查结论维持:可合并,等人工 merge。

@ranxianglei
ranxianglei merged commit 1e8e1aa 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.300-master.1e8e1aa (rolling master tag).

npm install -g billion-context@0.0.300-master.1e8e1aa  # 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.

[性能回归] 0.1.193 长会话本地耗时从 1.3s 升至 3.2s:无用 SimHash 计算与重复历史转换

1 participant