Repository navigation
Description
总跟踪:#841。
基于提交 f98d6a4737461ba8d8ee100f113b5a7c3a0001a0 的只读审计及合成复现。
问题
当前 Web UI 在接收 message_update 时,即使只有正在生成的消息变化,也会创建新的 snapshot 引用,使 transcript 重建历史条目并重新序列化其中的消息。随着历史窗口增大,流式更新需要反复支付与历史内容大小相关的计算和分配成本。
Refs #434。该已关闭问题解决的是不变历史 Markdown 的 memo。本轮发现位于 Markdown 渲染之前的消息签名、轮次归属计算及 thinking 时间状态;不表示历史 Markdown memo 失效,也不建议重新实现该修复。
主路径:流式更新引发历史消息重新签名
- store 在每个已选中 Session 事件中更新 cursor,随后无条件重建 snapshot/runtime。非工具事件的 reducer 返回原 liveTools,但外层仍创建新对象。
- App 整体订阅 store。Transcript 的 buildEntries memo 依赖整个 snapshot 和 liveMessages,因此新引用使其重算。
buildEntries先为持久 assistant/toolResult 消息构建完整 JSON 签名,后面又为全部 native messages 构建 legacySignature。历史没有变化时,这两轮仍会执行。
单次成本至少与当前历史字节数成正比。这里需要分别优化 snapshot 的无变化写入,以及 live 消息变化时持久历史的重复签名;只去掉新 snapshot 仍不能消除后者。
同一路径的两个相关放大点
- thinkingStarts/thinkingDurations 每个消息事件都被完整复制。live 消息有 8 条保留上限,但 timing 字典没有随之淘汰;同一 Session 普通刷新也只在 cursor reset、controller/selection 变化时重置。这不是跨所有 Session 永久泄漏,但在长驻 Session 中会持续增长,并增加每次更新的复制成本。
renderTurns对每个 timing row 从 rows 起点 findIndex 查 prompt,成本为 O(turns × rows)。历史窗口有界,仍存在可避免的二次扫描。
可复制的合成复现
在目标 checkout 根目录运行。使用既有依赖,不启动 Pi、不连接 provider、不读取真实会话。样本环境为 Bun 1.3.14。
git rev-parse HEAD
# 预期:f98d6a4737461ba8d8ee100f113b5a7c3a0001a0
bun install --frozen-lockfile --ignore-scripts
cat > /tmp/openpi-web-perf-repro.ts <<'TS'
import { readFileSync } from 'node:fs';
const root=process.cwd();
const { JSDOM }=await import(root+'/node_modules/jsdom/lib/api.js');
const dom=new JSDOM('',{url:'http://localhost'});
Object.assign(globalThis,{window:dom.window,document:dom.window.document,location:dom.window.location,sessionStorage:dom.window.sessionStorage,localStorage:dom.window.localStorage});
Object.defineProperty(globalThis,'navigator',{value:dom.window.navigator,configurable:true});
const {createWebStore}=await import(root+'/web/ui/src/store/web-store.ts');
const nav=await import(root+'/web/protocol/prompt-navigation.ts');
const source=readFileSync(root+'/web/ui/src/features/transcript/Transcript.tsx','utf8');
const code=source.slice(source.indexOf('function messageIdentity('),source.indexOf('\nfunction ProcessSequence('));
const js=new Bun.Transpiler({loader:'ts'}).transformSync(code);
const build=new Function('setupDisplayMessage','setupPromptParent','isSetupPromptEcho',js+'\nreturn buildEntries;')(nav.setupDisplayMessage,nav.setupPromptParent,nav.isSetupPromptEcho);
const snapshot={currentSessionId:'s',currentSessionPath:'/tmp/s',selectedSession:{id:'s',path:'/tmp/s',entries:[]},runtime:{status:'running',capabilities:{},liveTools:[]},sessions:[]};
let callback;
const store=createWebStore({}, {consumeEvents:(options)=>{callback=options.onEvent;return new Promise(resolve=>options.signal.addEventListener('abort',resolve));}});
store.setState({snapshot,cursor:0,selectedPath:'/tmp/s'});
store.getState().actions.start();
let notifications=0;store.subscribe(()=>notifications++);
let seq=0;
const event=(key)=>({sequence:++seq,type:'message_update',detail:{sessionId:'s',messageKey:key,message:{role:'assistant',content:'ok',parts:[{type:'thinking',thinking:'reason'}]}}});
for(let i=0;i<1000;i++) callback(event('live-'+i));
console.log(JSON.stringify({case:'real_store_1000_distinct_thinking_messages',notifications,liveMessages:store.getState().liveMessages.length,thinkingStarts:Object.keys(store.getState().thinkingStarts).length,thinkingDurations:Object.keys(store.getState().thinkingDurations).length}));
for (const n of [0,1000,10000]) {
const timings=Object.fromEntries(Array.from({length:n},(_,i)=>['old-'+i,i]));
store.setState({thinkingStarts:timings,thinkingDurations:{...timings}});notifications=0;
const before=store.getState().snapshot;const start=performance.now();
for(let i=0;i<1000;i++) callback(event('live-current'));
console.log(JSON.stringify({case:'real_store_1000_updates',preexistingTimingKeys:n,milliseconds:performance.now()-start,notifications,snapshotChanged:before!==store.getState().snapshot}));
}
store.getState().actions.stop();
for(const n of [250,1000]) {
const entries=Array.from({length:n},(_,i)=>({id:'e'+i,type:'message',message:{role:'assistant',timestamp:i,content:'x'.repeat(1000),parts:[{type:'text',text:'x'.repeat(1000)}]}}));
const snap={...snapshot,selectedSession:{...snapshot.selectedSession,entries}};
const live=[{key:'live-x',message:{role:'assistant',content:'delta',timestamp:10001}}];
for(let i=0;i<10;i++)build(snap,live,new Map());
let count=0,chars=0;const stringify=JSON.stringify;JSON.stringify=(...args)=>{const s=stringify(...args);count++;chars+=s?.length??0;return s;};
const start=performance.now();for(let i=0;i<100;i++)build(snap,live,new Map());
const milliseconds=performance.now()-start;JSON.stringify=stringify;
console.log(JSON.stringify({case:'actual_extracted_buildEntries_100_calls',entries:n,payloadBytes:Buffer.byteLength(JSON.stringify(entries)),milliseconds,stringifyCalls:count,stringifiedChars:chars}));
}
const turnSource=source.slice(source.indexOf('function renderTurns('),source.indexOf(' return turns.map((turn) => ('))+'return turns.length;\n}';
const group=new Function(new Bun.Transpiler({loader:'ts'}).transformSync(turnSource)+'\nreturn renderTurns;')();
for(const t of [50,100,250,333]) {
const rows=Array.from({length:t},(_,i)=>[{key:'p'+i,kind:'prompt',promptEntryId:'p'+i,turn:i+1},{key:'a'+i,kind:'response',turn:i+1},{key:'t'+i,kind:'custom',timing:{promptEntryId:'p'+i},turn:i+1}]).flat();
let comparisons=0;rows.findIndex=function(fn){return Array.prototype.findIndex.call(this,(...args)=>{comparisons++;return fn(...args);});};
group(rows,false);console.log(JSON.stringify({case:'actual_extracted_renderTurns',rows:rows.length,turns:t,promptSearchComparisons:comparisons}));
}
TS
bun /tmp/openpi-web-perf-repro.ts脚本直接导入真实 store;另提取当前源码中的 buildEntries 和 renderTurns 非 JSX 计算部分,使用真实 prompt-navigation helpers。样本全部为合成内容。后两档 timing key 数量通过预置状态构造,用于观察规模变化,不代表日常会话已达到该规模。
样本结果:
| 场景 | 观测 |
|---|---|
| 1000 个不同 thinking 消息更新 | liveMessages 为 8,thinkingStarts 为 1000;3000 次 store 通知 |
| 1000 次更新;预置 timing keys 为 0 / 1000 / 10000 | 约 2.3 / 60.7 / 525.7 ms;均产生新 snapshot 引用 |
| 250 条历史消息,buildEntries 执行 100 次 | 约 40.4 ms;50100 次 stringify;处理约 104M 字符 |
| 1000 条历史消息,buildEntries 执行 100 次 | 约 153.4 ms;200100 次 stringify;处理约 415M 字符 |
| 150 / 300 / 750 / 999 rows 的轮次归属计算 | prompt 查找比较 3725 / 14950 / 93625 / 166167 次 |
**证据边界:**计时是 Bun 合成算法样本,不是真实浏览器卡顿证明,也没有测量端到端 token 延迟。Zustand 通知数不等于 React commit 或绘制次数,React 可以批处理。默认历史为 250 entries/2MiB,阅读窗口上限 1000 entries/8MiB,不能把它描述为无限历史渲染。此次复现与超大 SSE 事件导致的断线/重新取 snapshot 是不同问题;普通 snapshot refresh 也已有 160ms 合并。
建议的最小改进
- reducer 返回相同 liveTools 时,避免仅为该 reducer 写出新 snapshot/runtime。
- 将持久 entries 的消息签名/基础投影与 live 消息合并拆开缓存,基于稳定 entries 身份复用;保留现有精确身份、重复消息和 optimistic prompt 对账规则。
- 用一次扫描建立 promptEntryId 到 row index 的映射,替代每个 timing row 从头查询;避免新增通用渲染框架。
- 在 timing 不再被当前显示或 live 对账使用时淘汰对应 key,保留可见历史的耗时。不应为了限长直接清空仍在使用的 timing。
验收标准
- 对未变化的持久 entries,连续 live 更新不重复序列化全部历史消息;使用计数型验证证明缓存命中,避免用机器相关的毫秒阈值作为唯一门禁。
- 非工具事件不为没有变化的 liveTools 单独创建新 snapshot/runtime;事件 cursor 顺序、恢复和终态依旧正确。
- 轮次归属计算随 rows/turns 接近线性增长,且多次运行、timing 归属及排队 prompt 的现有语义不变。
- 长驻 Session 的 timing 字典有明确保留依据;live 淘汰后不会无界累积,同时可见 reasoning 耗时保持正确。
- 保持 perf(web): avoid reparsing unchanged history during streaming #434 对未变化历史 Markdown 的优化,以及重复内容、truncated message、optimistic prompt 转 native 等身份对账回归测试。
- 在合成 250/1000 entries 的真实浏览器页面中记录 stream 更新的 React commit、long task 与输入响应,单独报告浏览器证据。
- 运行
bun run check和bun run test。
Activity