Skip to content

fix: separate calibrated context display from the safety bound; add model provenance to k̂ (#2117) - #2142

Merged
ranxianglei merged 5 commits into
masterfrom
2026-10-05_context-estimate-provenance
Oct 6, 2026
Merged

ranxianglei merged 5 commits into
masterfrom
2026-10-05_context-estimate-provenance

Conversation

@ranxianglei

Copy link
Copy Markdown
Owner

Closes #2117

What

The admin page rendered the char-count upper bound of the last outbound send on the same progress bar as upstream-measured usage, with no provenance distinction — a mid-request refresh could read "206K / 204K(估算)" while the settled usage of that request was 98K (~2.1× gap from counting every character as one token). Separately, the learned estimator scale k̂ (#1933 F1) was keyed by route only, so a mid-session model switch kept applying another model's billing scale.

Changes

A — display caliber separation (display-only; decision paths byte-identical)

B — k̂ model dimension

  • Evidence ring keyed by route AND model (calibrationRing.model, new calibratedEstimateModel); publish/clear carry the model; all read sites (preflight gate ×2) go through new currentCalibrationFactor(), which treats a cross-model factor as ABSENT (raw estimate) while keeping factors whose model is unknown on either side — missing information never invalidates, legacy factors retire through normal ring rollover.
  • Native-compaction reset drops the new fields with the rest of the baseline stats.

Behavior changes (disclosure)

  1. Admin bar/list value during an in-flight request changes. Old: char-count upper bound — could read ~2–3.5× over actual for ASCII-heavy payloads. New: k̂-calibrated billing-caliber estimate when a usage anchor exists, else the bound (now labeled as such). Display-only: no decision path reads the new field; preflight/nudge/overflow logic untouched.
  2. Same-route model switch now invalidates k̂ immediately. Old: factor persisted until ring rollover, blending two models' billing scales. During the ≤3-request relearn window preflight may trigger EARLIER (raw estimate) — backstopped by the usage-baseline floor (DSH: 切换模型后,preflight 在窗口远未满时提前触发压缩 #1933 F2), converges after ≥2 consistent samples. This is the safe direction: a stale k̂<1 deflates estimates and can fire compression too LATE.

Config surface

NONE. No new config keys, env vars, or CLI flags. Internal session.stats fields only; the web JSON API is additive (optional contextBest, contextUpperTokens, lastInputTokensOrigin, contextMeasuredAt, estimateCalibration). Session-file format: new optional stats fields are saved via the existing whole-stats spread and simply absent on load (existing loader-whitelist behavior — see #2141 for the drift this exposes).

Tests

Found while working → filed separately

#2141 — persist.ts load whitelist does not restore k̂/ring/localInputEstimate/lastUsageGradeTokens despite session.ts comments claiming persistence (every restart silently loses calibration). Distinct failure domain (persistence fidelity), NOT bundled here.

@github-actions

github-actions Bot commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

📦 Built Package Artifact

Branch: 2026-10-05_context-estimate-provenance (4ba4441)

Option A — Install this exact build (recommended)

npm install -g billion-context@0.0.2291-pr.2142.e66dfb2

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-pr2142.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] 🏷 收到,开始 review PR #2142(Closes #2117)。正在拉取分支、核对原 issue 与 CI 状态,随后按七问给出结论。

… B x #2129)

Merged-tree CI red: #2129's restart e2e 502s on this branch's head. The
restore whitelist drops ring.model / calibratedEstimateModel (#2141 gap), so
after a restart the first usage settle saw a model-less ring vs a known
settle model, treated it as a cross-model switch, reset the ring, and the
insufficient-samples branch deleted the just-restored k̂ — reintroducing the
#2122/#2129 incident shape (over-raw resend folds instead of forwarding).

The factor gate (currentCalibrationFactor) already follows "missing info
never invalidates"; the ring condition now does too: a model-less ring
continues and adopts the first known model; a known-vs-known mismatch still
starts a fresh ring. Provenance stamps from the ring key so an unknown-model
settle cannot blank an established one.

Tests: re-pinned the two B-ring cases that asserted discard; the #2129 e2e
(forward-without-folds after restart) is the regression pin — green on the
merged tree again (68/68 targeted).
@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

[bot] 🏷 Review 完成:发现并修复一处跨分支语义回归(已推 additive commit),其余通过。合并判定见文末。

审查范围(不止读 diff):


结构化七问

  1. 是什么问题:管理页上下文条把三种口径(字符数保守上界 / 计费口径校准估算 / 上游实测用量)混在一根条上展示,in-flight 期间显示的是高估 2–3.5× 的上界,用量落盘后又跳回实测值——用户看到的数字既不是"实际用了多少"也不是"安全边界",两头不靠。
  2. 什么原因导致的:forward() 只发布单一 contextTokens(source=estimate 时是字符数上界),settle 后才被 usage 覆盖,UI 单条无口径区分;且 k̂ 证据环只按 route 键控,模型维度缺失使跨模型系数存在串味风险。本 PR 的 A/B 方案方向正确。真正的事故是审查中发现的第三层:PR 基线早于 Restart loses measurement state: buildSession() omits stats fields buildRecord() persists (k̂, usage anchor, baseline origin, localInputEstimate) #2129 落地,作者的 16 文件定向清单里没有 Restart loses measurement state: buildSession() omits stats fields buildRecord() persists (k̂, usage anchor, baseline origin, localInputEstimate) #2129 的测试,而两者在"重启后第一次 usage settle"这条路径上语义相撞(详见第 3 问)。
  3. 怎么修复的:A 部分——forward() 双口径发布(upperBound ≡ legacy 值不动 + 计费口径 textOverhead,k̂ 仅在 route+model 双匹配时缩放),新增 displayContextBest() 选择器(usage > 有锚校准估算 > 标注上界),UI 主数值切到选择器结果、上界降级为标注副行、详情加 k̂ 证据 chip;B 部分——环键控升级为 route+model,读侧统一走 currentCalibrationFactor()(缺信息不失效)。我补的修复(df3337ba):原实现中环的重置条件 ring.model !== settleModel 把"恢复后的环没有 model 字段"当成跨模型切换——Restart loses measurement state: buildSession() omits stats fields buildRecord() persists (k̂, usage anchor, baseline origin, localInputEstimate) #2129 的加载白名单不带新字段([Bug] persist 加载白名单漂移:k̂/localInputEstimate 等校准统计字段落盘后重启即丢(注释声称 Persisted) #2141 缺口),于是重启后第一次 settle 重置空环 → 样本不足分支删掉刚恢复的 k̂ → 下一次 over-raw resend 用裸估算撞窗 502,正是 Output clamp starves DSH compression despite ample actual context #2122/Restart loses measurement state: buildSession() omits stats fields buildRecord() persists (k̂, usage anchor, baseline origin, localInputEstimate) #2129 钉死的事故形态复发。修法是把环对齐因子门已有的纪律:缺一侧 model 信息永不失效——无 model 键的环继续累积并采纳首个已知模型;两侧都已知且不同才开新环;provenance 改从环键打戳防未知模型 settle 抹掉既有出处。PR 自身注释声称 legacy 环"≤2 samples 内旧因子仍可发布",代码实际是立即清除——注释与代码不符,本次一并对齐。
  4. 是否有回归问题:审过的既有行为逐项——① 决策路径(preflight/nudge/baseline floor):零触碰,k̂ 读侧门控只增不改值;② 出站字节:stats 写入在 sentBody 构建之后,wire 零变化(e2e 钉住);③ 上界口径:localInputEstimate/contextTokens(source=estimate) 数值与公式不变,never-reporting upstream 的 fail-closed 展示不变(无锚 → 仍显示上界);④ 兼容 wrapper outboundContextEstimate() = .upperBound([perf] knobs re-read config file per call (~5-10/request) and forward() re-parses full wire body for outbound estimate #2078 套件绿);⑤ native-compaction 清理点同步扩了新字段;⑥ 高危模式排查:唯一的意外破坏就是上面第 3 问那条(修 A 坏 B 型跨分支回归),已修并有 Restart loses measurement state: buildSession() omits stats fields buildRecord() persists (k̂, usage anchor, baseline origin, localInputEstimate) #2129 e2e 作回归钉。残留已知边缘(非阻塞):display 锚点不按 route 域化——换到从不报用量的新 route 后 in-flight 会显示新 route 的计费口径估算(标注"未校准"),有 label、决策路径不受影响,符合 issue 方向 4 的意图。
  5. 是否破坏缓存:不涉及。prompt cache 路由、前缀稳定性、cache ledger 采样均未触碰;k̂ 学习环窗口/一致性参数(≥2 样本 ×2 一致、window 3、clamp [0.25,1])全部不变。
  6. 是否改了设计方向:PR 本身不改方向(展示层分离 + 证据溯源,与 fix(#2029): status readers share provenance-aware input baseline #2056/Status readers still trust estimate-grade failure baselines after #1846 #2029 先例同构)。我的补修改了一个实现级设计点,必须披露(旧→新+原因):legacy/无 model 键环遇到首个已知模型样本——旧行为:丢弃重学(且立即清除已发布 k̂);新行为:继续累积并采纳该模型(k̂ 存活)。原因:丢弃语义与 PR 自己因子门的"缺信息不失效"原则矛盾、与其自身注释矛盾、且在重启场景下清除的是同模型同会话的合法证据(model 字段只是被白名单丢掉,不是真的跨了模型),直接复活 Restart loses measurement state: buildSession() omits stats fields buildRecord() persists (k̂, usage anchor, baseline origin, localInputEstimate) #2129 钉死的事故类。真正的跨模型切换(两侧都已知且不同)仍然开新环,B 的设计意图完整保留。
  7. 是否引入了新的配置:无。仅 session.stats 内部可选字段(contextEstimateTokens/contextEstimateCalibrated/calibratedEstimateModel、ring.model)与 web JSON 附加字段;无 env/config/CLI 面变化。session 文件格式为向后兼容的可选扩展。

测试有效性:新文件 8 个测试断言有牙(gate 三态、legacy≡ 四协议、选择器阶梯七例、环键控含切回/legacy/未知模型、边界清理、hermetic e2e 走 startServer 真链路);#2129 e2e 是本回归的兜底钉(forward-without-folds 全链路)。作者定向清单遗漏 #2129 文件的根因是基线陈旧(§7.5 重灾区 1),不是测试质量问题。diff 整洁度:9 文件全部与本 PR 目的相关,无跑题/空白噪声 ✓。

遗留事项:#2141(加载白名单不恢复 k̂/环/锚点字段族)仍在独立处理中——补修后即使白名单未补齐,重启后 k̂ 也能存活(环采纳模型并重发布);#2141 落地后 model provenance 也完整往返,届时本 PR 的注释引用自然闭环。floor 4 你问的"平滑过渡"按 floor 6 的结论执行(立即失效、基线地板兜底),实现与之一致 ✓。

判定:代码质量与方向均达标;跨分支回归已由我在 PR 分支修复(df3337ba,additive,可单独 revert 不影响原 PR)。等 df3337ba 的 CI 全绿即可合并——合并动作留给你。

@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

[bot] 🏷 补充确认:修复后的 head df3337ba CI 已全部跑完——20/20 checks 全绿(含此前挂掉的 4 个 test 矩阵 job,#2129 e2e 恢复通过)。可以合并了。

@ranxianglei

Copy link
Copy Markdown
Owner Author

冲突

@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

[bot] 🏷 收到,冲突已在处理。原因:master 新合入的 #1937(bounded web sessions index)重写了 src/web/sessions-data.ts(摘要行改为有界索引、不再构造完整 Session),与本 PR 新增的展示字段在同文件相撞。

已解决并本地验证(typecheck + 定向测试 71/71 含 #2129 e2e + build),正在推送合并提交到 PR 分支——当前网络代理对 push 的 POST 持续返回 408 超时,重试中。推上去后跑 CI 并回报。

@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

[bot] 🏷 冲突已解决,CI 21/21 全绿(head 88a008eba),可以合并。本轮两件事:①解决与 master 的冲突;②冲突 rebase 过程中发现 master 自身是红的(#2152 引入的既有 bug,与本 PR 无关),顺手修掉并单独成 commit,否则本 PR 在 CI 上永远绿不了。

一、冲突原因与解决

master 期间合入的 #1937(bounded web sessions index) 重写了 src/web/sessions-data.ts:列表数据改走「有界磁盘摘要索引」(SummarySource 最小形状 + summaryFromRecord 白名单 normalizer),与本 PR 在同一文件加 display 字段正面相撞。

二、顺带发现:master 自 #2152 起就是红的(非本 PR 引入)

冲突后第一次 CI:4 个 test job 全部挂在同一个测试 tests/advisory-endpoint-parity.test.ts(#2152)——/__bili/overview 返回 500:ENOENT scandir '.../sessions'。证据:master 头 4af31e0a 自己的 CI job 日志一字不差同样失败 → 这是 #2152 合入时就带进来的,与本 PR 无关;只是之前没人把 PR rebase 到最新 master 触发过它。

  • 根因:refreshIndex()(sessions-data.ts)对「顶层目录不存在」直接向上抛(无快照时);而 sessions 目录是首次保存时才懒创建(persist.ts)——全新安装/全新 CI runner 上目录必然不存在 → /__bili/overview 必 500。同仓先例:session-gc.ts 早已把目录缺失当空结果处理,只有这里漏了。
  • 修复(独立标注 commit 88a008eba,fix: treat missing sessions dir as empty index instead of 500 (#2152)):目录缺失且无历史快照 → 空索引 + 每进程一条 warn 日志;目录存在过后来消失 → 继续服务旧快照(管理页面全量加载历史会话时触发堆 OOM:需要有界分页、摘要统计与详情懒加载 #1937 行为不变);其他错误(EACCES 等)照旧上抛。同步更新 管理页面全量加载历史会话时触发堆 OOM:需要有界分页、摘要统计与详情懒加载 #1937 那条 pin(原断言「无快照+缺目录必须 reject」改为期望空列表)——理由:fs 层面「未创建」与「配错路径」不可区分,loudness 从 HTTP 500 移到日志,而不是拿全新安装的正常初始状态去撞 500。

行为变更披露(旧值→新值):全新安装(或持久化从未写过任何会话)时 /__bili/overview / /__bili/sessions:HTTP 500 → HTTP 200 空列表,外加每进程一条 [acp-web] sessions dir … does not exist yet — serving empty index warn。决策路径、wire、缓存均不涉及;已有数据的部署行为零变化。

三、结构化七问

  1. 是什么问题:管理页同一根条混用两种口径(飞行中显示字符数保守上界 ~2–3.5×,usage 落定后跳到实测值),[Bug] 上下文展示估算 206K,usage 返回后为 98K:希望校准估算并区分安全上界 #2117 报告的 206K→98K 跳变即此。
  2. 什么原因导致的:forward() 把 char-count 上界写进 stats.contextTokens(source=estimate),usage 回来后被覆写(source=usage),UI 单根条无口径区分;k̂ 校准又缺 model 维度。
  3. 怎么修复的:A——决策路径字节不动,新增 billing-caliber 估算字段(仅 provenance 匹配时 k̂ 缩放)+ displayContextBest() 选择器(usage > anchored calibrated estimate > labeled bound),UI 主值换 caliber、上界降为标注副行、校准证据 chip;B——校准环按 route+model 键控,跨 model factor 视为缺失(raw estimate,保守方向),model 未知一侧保留(信息缺失不作废)。
  4. 是否有回归问题:审过全部既有读取点——决策读取只有 preflight ×2,均已走 currentCalibrationFactor() 门控;outboundContextEstimates().upperBound 与原公式四协议 fixture 逐字节一致([perf] knobs re-read config file per call (~5-10/request) and forward() re-parses full wire body for outbound estimate #2078 suite 钉绿)。review 中抓到一个真回归(Restart loses measurement state: buildSession() omits stats fields buildRecord() persists (k̂, usage anchor, baseline origin, localInputEstimate) #2129 重启 e2e 挂 502:无 model 的恢复环被当跨 model 重置)已在首轮修掉(commit df3337ba,legacy 环 discard→continue-and-adopt,方向披露见首轮回复);本轮又抓到 管理页面全量加载历史会话时触发堆 OOM:需要有界分页、摘要统计与详情懒加载 #1937 rebase 语义坑与 [web] advisory banner 是死代码:/__bili/overview 不含 advisory 字段,web 客户端从不调用 /__bili/status #2152 master-red,均已如上处理。结论:无残留回归。
  5. 是否破坏缓存:不涉及——不动 prefix cache、重试、增量游标;web 索引只是展示层读路径。
  6. 是否改了设计方向:无转向;沿用 DSH: 切换模型后,preflight 在窗口远未满时提前触发压缩 #1933/fix(#2029): status readers share provenance-aware input baseline #2056/[perf] knobs re-read config file per call (~5-10/request) and forward() re-parses full wire body for outbound estimate #2078 既有 provenance 门控体系,只补 display 分离与 k̂ model 维度。floor-4 问的「平滑过渡」按 floor-6 结论执行(立即失效,baseline floor 兜底,重学窗口 ≤3 请求)。
  7. 是否引入新配置:无。纯 session.stats 内部可选字段 + web JSON 增量字段;session 文件格式向后兼容(旧文件无新字段 = 按现状渲染)。

已知非阻塞边角(记录不改):display anchor 不按 route 隔离——切到从不报 usage 的新 route 时,飞行中会短暂显示带「估算·未校准」标签的 billing-caliber 值(决策路径不受影响,标签如实)。遗留 #2141(persist 白名单不恢复 k̂/环,每次重启丢校准)仍单独挂着。

判定:可合并——冲突已解、master-red 已修、CI 21/21 绿(88a008eba)。分支 2026-10-05_context-estimate-provenance 共 3 个增量 commit:df3337ba(#2129 回归修复)、merge commit(解冲突+语义补齐)、88a008eba(#2152 缺目录修复)。PR 合并留给人工操作。

@ranxianglei

Copy link
Copy Markdown
Owner Author

又冲突

@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

[bot] 🏷 收到,正在查 master 新进的冲突提交并解决,完成后报告。

# Conflicts:
#	src/web/sessions-data.ts
#	tests/web-sessions.test.ts
@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

[bot] 🏷 第二次冲突已解决,CI 24/24 全绿(head 4ba44411c,base 已是最新 master 64c9f28b),mergeable=true,可以合并。

冲突原因

master 这批新进的提交里,#2180(ef404a85b + 0d30cec07)修掉了和我上一轮 commit 88a008eba 完全同一个 bug——#2152 引入的「全新安装 /__bili/overview ENOENT 500」。两边改了同一处代码(refreshIndex() 的顶层 walk 失败分支 + web-sessions 那条 #1937 pin),所以撞了。

对比后 master 的 #2180 方案更严谨,我直接采用它的实现、放弃我这版:

我的 88a008eba master #2180
触发条件 任何 ENOENT 都当「无数据」→ 空索引 仅 pristine 默认布局(未设 BILI_SESSIONS_DIR 且 XDG data root 本身不存在)→ 空索引;显式 override 指到不存在的路径保持响亮拒绝(那可能是配错路径,真实会话在别处,静默空列表会掩盖问题)
目录存在过后来消失 有快照→stale 同 + resolvedPristine latch:一旦成功 walk 过,根目录消失一律按 #1937 breakage 处理(stale snapshot),不再误判成 fresh install
日志 warn info,每进程一次

我的版本会把「用户显式配错 BILI_SESSIONS_DIR」也吞成空列表——这正是 #2180 设计里刻意保留 loud 的场景。所以冲突解决 = 三处冲突块全部取 master 侧(doc comment、catch 分支、测试 pin 标题+断言恢复为 assert.rejects),本 PR 自己的 display 字段改动(SummarySource 扩展、summaryFromRecord 透传 4 字段、displayContextBest 调用点)均无冲突、原样保留并已确认在位。

行为变更披露(相对我上一轮回复):上一轮我说「缺目录无快照 → 空索引」,经 #2180 细化为——仅 pristine 默认布局(真·全新安装)返回空索引;显式 BILI_SESSIONS_DIR 指向不存在路径仍 500 响亮报错。对用户可见的最终效果不变(全新安装不再 500),但误配置场景从「静默空列表」修正回「响亮失败」,是更对的语义。

验证

分支现在共 4 个增量 commit:df3337ba(#2129 回归修复)+ merge① + 88a008eba(#2152 修复,已被 #2180 取代、净效果为零但保留在历史里)+ merge②(本次)。

判定:可合并——两轮冲突均已解决且全部向更优的 master 实现对齐,无残留回归,等人工合并。

@ranxianglei
ranxianglei merged commit 9268d7c into master Oct 6, 2026
24 checks passed
@github-actions

github-actions Bot commented Oct 6, 2026

Copy link
Copy Markdown
Contributor

📦 Merged Build Published

This merge to master was published as 0.0.61-master.9268d7c (rolling master tag).

npm install -g billion-context@0.0.61-master.9268d7c  # 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] 上下文展示估算 206K,usage 返回后为 98K:希望校准估算并区分安全上界

1 participant