App: replace a silent socket instead of hanging; blink the terminal cursor on a timer; keep one markdown cache entry per streamed reply
A socket that outlived a sleep or network change looked open, so every queued request waited its own 30 s timeout behind the last until the page was reopened. The client now replaces a socket whose request times out unheard (or after two timeouts in a row), and probes it with a ping after a quiet spell or on returning to the foreground. The terminal's blinking cursor ran a Ticker (a frame every vsync); a 530 ms timer now flips it. Streamed deltas no longer flood the markdown cache and evict finished answers. Adds tool/perf/idle_session_bench.mjs (idle frames, long-session heap, snapshot census) and notes/perf-hangs-idle.md. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,193 @@
|
||||
#!/usr/bin/env node
|
||||
// Idle and long-session bench over the full-app fixture
|
||||
// (tool/search_selection_probe_entry.dart; a `--profile` build keeps names).
|
||||
//
|
||||
// For each idle scenario it loads a route, lets it settle, then counts the
|
||||
// animation frames the page asks for (wrapped `requestAnimationFrame`) over
|
||||
// `--idle` seconds with nothing changing: an idle app should ask for none.
|
||||
//
|
||||
// `--session N` then simulates a long day in one page: N rounds of opening
|
||||
// each fixture chat (history pushState + popstate, as the app's own path
|
||||
// routing does on Back/Forward), letting live replies stream, visiting Runs,
|
||||
// Pipelines and Search, and opening the terminal panel. After every round it
|
||||
// forces a GC and reports the used JS heap, the long tasks (>50 ms) and the
|
||||
// longest task seen, so growth over the session shows as a trend.
|
||||
//
|
||||
// node tool/perf/idle_session_bench.mjs --build build/probe-app \
|
||||
// [--idle 5] [--session 6] [--gpu] [--only 'name;name'] [--stacks]
|
||||
//
|
||||
// Headless Chrome without --gpu rasterises on the CPU (CanvasKit).
|
||||
import { parseArgs } from 'node:util';
|
||||
import { setTimeout as delay } from 'node:timers/promises';
|
||||
import { openBrowser } from '../capture/browser.mjs';
|
||||
import { serveBuild } from '../capture/serve.mjs';
|
||||
|
||||
const { values: opts } = parseArgs({
|
||||
options: {
|
||||
build: { type: 'string' }, idle: { type: 'string', default: '5' },
|
||||
session: { type: 'string', default: '0' }, gpu: { type: 'boolean' },
|
||||
only: { type: 'string' }, census: { type: 'boolean' }, stacks: { type: 'boolean' }, size: { type: 'string', default: '1280x800' },
|
||||
},
|
||||
});
|
||||
if (!opts.build) throw new Error('usage: --build <dir>');
|
||||
|
||||
const CHATS = 6;
|
||||
const base = { chats: String(CHATS), header: '1', rich: '1', msgs: '80,30' };
|
||||
const IDLE = [
|
||||
{ name: 'runs list', route: '/runs', q: {} },
|
||||
{ name: 'run detail', route: '/runs/7', q: {} },
|
||||
{ name: 'pipelines', route: '/pipelines', q: {} },
|
||||
{ name: 'chat (rich, 80 msgs)', route: '/chat/perf-chat-0', q: base },
|
||||
{ name: 'chat after live reply', route: '/chat/perf-chat-0', q: { ...base, live: '40' }, wait: 7000 },
|
||||
{ name: 'chat + terminal panel', route: '/chat/perf-chat-0', q: { ...base, terminals: '1' }, keys: ['Alt+t'] },
|
||||
{ name: 'chat list running', route: '/chat/perf-chat-1', q: { ...base, activity: '1' } },
|
||||
{ name: 'settings', route: '/settings', q: {} },
|
||||
];
|
||||
|
||||
const INSTRUMENT = `
|
||||
(() => {
|
||||
const raf = window.requestAnimationFrame.bind(window);
|
||||
window.__raf = 0;
|
||||
window.__stacks = {};
|
||||
window.requestAnimationFrame = (cb) => {
|
||||
window.__raf++;
|
||||
if (window.__trace) { const k = (new Error().stack || '').split(String.fromCharCode(10)).slice(2, 14).join(String.fromCharCode(10)); window.__stacks[k] = (window.__stacks[k] || 0) + 1; }
|
||||
return raf(cb);
|
||||
};
|
||||
window.__long = [];
|
||||
try {
|
||||
new PerformanceObserver((list) => {
|
||||
for (const e of list.getEntries()) window.__long.push(Math.round(e.duration));
|
||||
}).observe({ type: 'longtask', buffered: true });
|
||||
} catch (_) {}
|
||||
})();`;
|
||||
|
||||
const server = await serveBuild(opts.build);
|
||||
const browser = await openBrowser({ gpu: Boolean(opts.gpu) });
|
||||
const { send, on } = browser;
|
||||
const evaluate = async (expression) => (await send('Runtime.evaluate', { expression, returnByValue: true, awaitPromise: true })).result?.value;
|
||||
const errors = [];
|
||||
on('Runtime.exceptionThrown', (p) => errors.push(String(p.exceptionDetails?.exception?.description ?? p.exceptionDetails?.text).slice(0, 200)));
|
||||
|
||||
const MODIFIERS = { Alt: 1, Control: 2, Meta: 4, Shift: 8 };
|
||||
async function key(chord) {
|
||||
const parts = chord.split('+');
|
||||
const name = parts.pop();
|
||||
const modifiers = parts.reduce((bits, part) => bits | MODIFIERS[part], 0);
|
||||
const code = /^[a-z]$/i.test(name) ? `Key${name.toUpperCase()}` : name;
|
||||
const k = { modifiers, key: name, code, windowsVirtualKeyCode: name.toUpperCase().charCodeAt(0) };
|
||||
for (const part of parts) await send('Input.dispatchKeyEvent', { type: 'rawKeyDown', key: part, code: `${part}Left`, modifiers });
|
||||
await send('Input.dispatchKeyEvent', { type: 'rawKeyDown', ...k });
|
||||
await send('Input.dispatchKeyEvent', { type: 'keyUp', ...k });
|
||||
for (const part of parts) await send('Input.dispatchKeyEvent', { type: 'keyUp', key: part, code: `${part}Left`, modifiers: 0 });
|
||||
}
|
||||
|
||||
function url(route, q) {
|
||||
const u = new URL('/', server.origin);
|
||||
u.searchParams.set('route', route);
|
||||
u.searchParams.set('theme', 'light');
|
||||
for (const [k, v] of Object.entries(q)) u.searchParams.set(k, v);
|
||||
return u.href;
|
||||
}
|
||||
async function load(route, q) {
|
||||
await send('Page.navigate', { url: url(route, q) });
|
||||
for (let i = 0; i < 200; i++) {
|
||||
if (await evaluate('!!document.querySelector("flutter-view, flt-glass-pane")')) break;
|
||||
await delay(50);
|
||||
}
|
||||
await delay(2500);
|
||||
}
|
||||
async function idleFrames(seconds) {
|
||||
await evaluate('window.__raf = 0');
|
||||
await delay(seconds * 1000);
|
||||
return evaluate('window.__raf');
|
||||
}
|
||||
async function heapMb() {
|
||||
await send('HeapProfiler.collectGarbage');
|
||||
await delay(300);
|
||||
await send('HeapProfiler.collectGarbage');
|
||||
const { usedSize } = await send('Runtime.getHeapUsage');
|
||||
return Math.round(usedSize / 1e5) / 10;
|
||||
}
|
||||
// Object counts by constructor name from a heap snapshot (after a GC).
|
||||
async function census() {
|
||||
let chunks = '';
|
||||
const off = on('HeapProfiler.addHeapSnapshotChunk', (p) => { chunks += p.chunk; });
|
||||
await send('HeapProfiler.collectGarbage');
|
||||
await send('HeapProfiler.takeHeapSnapshot', { reportProgress: false });
|
||||
off?.();
|
||||
const snap = JSON.parse(chunks);
|
||||
const f = snap.snapshot.meta.node_fields;
|
||||
const stride = f.length, iName = f.indexOf('name'), iSize = f.indexOf('self_size'), iType = f.indexOf('type');
|
||||
const types = snap.snapshot.meta.node_types[0];
|
||||
const counts = new Map();
|
||||
for (let i = 0; i < snap.nodes.length; i += stride) {
|
||||
const type = types[snap.nodes[i + iType]];
|
||||
const name = type === 'object' ? snap.strings[snap.nodes[i + iName]] : `(${type})`;
|
||||
const c = counts.get(name) ?? [0, 0];
|
||||
c[0]++; c[1] += snap.nodes[i + iSize];
|
||||
counts.set(name, c);
|
||||
}
|
||||
return counts;
|
||||
}
|
||||
let lastCensus = null;
|
||||
const go = (route) => evaluate(`history.pushState(null, '', ${JSON.stringify(route)}); dispatchEvent(new PopStateEvent('popstate', { state: null })); true`);
|
||||
|
||||
try {
|
||||
await send('Page.enable');
|
||||
await send('Runtime.enable');
|
||||
await send('HeapProfiler.enable');
|
||||
await send('Page.addScriptToEvaluateOnNewDocument', { source: INSTRUMENT });
|
||||
await send('Emulation.setEmulatedMedia', { features: [{ name: 'prefers-color-scheme', value: 'light' }] });
|
||||
const [w, h] = opts.size.split('x').map(Number);
|
||||
await send('Emulation.setDeviceMetricsOverride', { width: w, height: h, deviceScaleFactor: 1, mobile: false });
|
||||
const only = opts.only?.split(';');
|
||||
for (const s of IDLE.filter((s) => !only || only.includes(s.name))) {
|
||||
await load(s.route, s.q);
|
||||
for (const k of s.keys ?? []) { await key(k); await delay(1200); }
|
||||
if (s.wait) await delay(s.wait);
|
||||
await delay(1500);
|
||||
if (opts.stacks) await evaluate('window.__stacks = {}; window.__trace = true');
|
||||
const n = await idleFrames(Number(opts.idle));
|
||||
console.log(`idle ${s.name.padEnd(26)} frames requested in ${opts.idle}s: ${n}`);
|
||||
if (opts.stacks && n > 0) {
|
||||
const stacks = await evaluate('window.__trace = false; Object.entries(window.__stacks).sort((a, b) => b[1] - a[1]).slice(0, 3)');
|
||||
for (const [stack, count] of stacks) console.log(` ${count}x\n${stack}`);
|
||||
}
|
||||
}
|
||||
const rounds = Number(opts.session);
|
||||
if (rounds > 0) {
|
||||
await load('/chat/perf-chat-0', { ...base, live: '60', terminals: '1' });
|
||||
await evaluate('window.__long = []');
|
||||
console.log(`session start heap ${await heapMb()} MB`);
|
||||
for (let r = 1; r <= rounds; r++) {
|
||||
const t0 = Date.now();
|
||||
for (let c = 0; c < CHATS; c++) {
|
||||
await go(`/chat/perf-chat-${c}`);
|
||||
await delay(c === r % CHATS ? 7500 : 900);
|
||||
}
|
||||
await key('Alt+t'); await delay(800);
|
||||
for (const route of ['/runs', '/runs/7', '/pipelines', '/search', '/chat/perf-chat-0']) {
|
||||
await go(route); await delay(900);
|
||||
}
|
||||
await key('Alt+t'); await delay(800);
|
||||
const long = await evaluate('window.__long.splice(0)');
|
||||
const idle = await idleFrames(3);
|
||||
if (opts.census && (r === 2 || r === rounds)) {
|
||||
const now = await census();
|
||||
if (lastCensus) {
|
||||
const grown = [...now].map(([k, [n, b]]) => [k, n - (lastCensus.get(k)?.[0] ?? 0), b - (lastCensus.get(k)?.[1] ?? 0)])
|
||||
.sort((a, b) => b[2] - a[2]).slice(0, 25);
|
||||
console.log(`census growth rounds 2..${r} (name, count, bytes):`);
|
||||
for (const g of grown) console.log(` ${g[0].slice(0, 60)} ${g[1]} ${g[2]}`);
|
||||
}
|
||||
lastCensus = now;
|
||||
}
|
||||
console.log(`round ${r}: heap ${await heapMb()} MB, long tasks ${long.length} (max ${Math.max(0, ...long)} ms), idle frames/3s ${idle}, ${Math.round((Date.now() - t0) / 1000)} s`);
|
||||
}
|
||||
}
|
||||
if (errors.length) console.log('page errors (first 5):', [...new Set(errors)].slice(0, 5));
|
||||
} finally {
|
||||
await browser.close().catch(() => {});
|
||||
await server.close();
|
||||
}
|
||||
Reference in New Issue
Block a user