Chat: only the streaming message renders again on each token, so a long chat no longer redoes its whole history per token (Out of Memory report from Mio; heap and main-thread time measured)

This commit is contained in:
Niko1221 committed 2026-10-30 18:58:34 +01:00
1 parent 08e8770c6e
commit ea52e55cd7
4 files changed
+118 -3

No files matched your search

+26
View File
@@ -0,0 +1,26 @@
// Throwaway: serves the demo host unchanged, except POST /api/chat/stream, which streams a long scripted reply (NDJSON frames like the real host).
import http from 'node:http';
const UP = Number(process.env.UP ?? 18791), PORT = Number(process.env.PORT ?? 18790);
const TOK = Number(process.env.REPLY_TOKENS ?? 12000), REASON = Number(process.env.REASON_TOKENS ?? 3000), RATE = Number(process.env.RATE ?? 400);
const sleep = ms => new Promise(r => setTimeout(r, ms));
const para = i => `### Section ${i}\n\nThis is paragraph ${i} with **bold**, *italic*, \`inline code\` and a link [x](https://example.com/${i}). The measured value is about ${i} units and the results agree with the earlier runs, which is what we expected from the model.
More prose follows here so that a paragraph looks like real writing and not like a stress pattern.\n\n- item one of ${i}\n- item two of ${i}\n\n\`\`\`python\ndef f_${i}(a, b):\n total = a + b * ${i}\n return total\n\`\`\`\n\n| a | b |\n|---|---|\n| ${i} | ${i * 2} |\n\n`;
http.createServer(async (req, res) => {
if (req.method === 'POST' && req.url.startsWith('/api/chat/stream')) {
let raw = ''; for await (const c of req) raw += c;
res.writeHead(200, { 'content-type': 'application/x-ndjson' });
const w = o => res.write(JSON.stringify(o) + '\n');
w({ type: 'start', model: 'Mock', contextMax: 131072, requestId: 'r' + Date.now() });
let sent = 0, i = 0;
const per = Math.max(1, Math.round(RATE / 50));
while (sent < REASON) { w({ type: 'reasoning', text: 'thinking about step ' + (i++) + ' of the problem. '.repeat(1) }); sent += 9; if (sent % per < 9) await sleep(20); }
sent = 0; i = 0;
while (sent < TOK) { const p = para(i++); for (let k = 0; k < p.length; k += 24) { w({ type: 'delta', text: p.slice(k, k + 24) }); sent += 6; if ((sent / 6) % Math.max(1, Math.round(per / 2)) === 0) await sleep(10); } w({ type: 'stats', tokensOut: sent, tps: 90 }); }
w({ type: 'done', tokensIn: 100, tokensOut: sent, tps: 90, durationMs: 1000, usageSource: 'engine' });
return res.end();
}
const up = http.request({ host: '127.0.0.1', port: UP, path: req.url, method: req.method, headers: req.headers }, r => { res.writeHead(r.statusCode, r.headers); r.pipe(res); });
up.on('error', () => { res.writeHead(502); res.end(); });
req.pipe(up);
}).listen(PORT, '127.0.0.1', () => console.log('proxy on', PORT));
+57
View File
@@ -0,0 +1,57 @@
// Measures the chat page's heap, DOM size and main-thread time per streamed reply. Needs a throwaway host (STRATA_REAL_ENGINE=0, port 18791), scripts/chat-growth-proxy.mjs (port 18790) and Chrome.
import { chromium } from 'playwright-core';
import { deflateSync } from 'node:zlib';
import { randomBytes } from 'node:crypto';
import { execSync } from 'node:child_process';
const BASE = process.env.BASE ?? 'http://127.0.0.1:18790';
const TURNS = Number(process.env.TURNS ?? 6), PICS = Number(process.env.PICS ?? 3), MON = process.env.MON !== '0';
const crc = (() => { const t = new Int32Array(256).map((_, n) => { let c = n; for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; return c; }); return b => { let c = -1; for (const x of b) c = t[(c ^ x) & 255] ^ (c >>> 8); return (c ^ -1) >>> 0; }; })();
function png(w, h) {
const chunk = (type, data) => { const len = Buffer.alloc(4); len.writeUInt32BE(data.length); const body = Buffer.concat([Buffer.from(type), data]); const c = Buffer.alloc(4); c.writeUInt32BE(crc(body)); return Buffer.concat([len, body, c]); };
const raw = Buffer.alloc((w * 3 + 1) * h); for (let y = 0; y < h; y++) { raw[y * (w * 3 + 1)] = 0; randomBytes(w * 3).copy(raw, y * (w * 3 + 1) + 1); }
const ihdr = Buffer.alloc(13); ihdr.writeUInt32BE(w, 0); ihdr.writeUInt32BE(h, 4); ihdr[8] = 8; ihdr[9] = 2;
return Buffer.concat([Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]), chunk('IHDR', ihdr), chunk('IDAT', deflateSync(raw, { level: 1 })), chunk('IEND', Buffer.alloc(0))]);
}
const browser = await chromium.launch({ executablePath: 'C:/Program Files/Google/Chrome/Application/chrome.exe', headless: true, args: ['--enable-precise-memory-info', '--js-flags=--expose-gc'] });
const ctx = await browser.newContext({ viewport: { width: 1400, height: 900 } });
const page = await ctx.newPage();
const cdp = await ctx.newCDPSession(page);
await cdp.send('Performance.enable');
await fetch(BASE + '/api/model-providers', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ kind: 'custom', provider: null, name: 'Mock model', baseUrl: 'http://127.0.0.1:18898/v1', protocol: 'openai-chat', apiKey: '', models: [{ id: 'mock-model', name: 'Mock model' }] }) });
await page.goto(BASE + '/'); await page.waitForTimeout(1500);
const skip = page.getByText('Go straight to the app'); await skip.waitFor({ timeout: 10000 }).catch(() => {}); if (await skip.count()) { await skip.click(); await page.waitForTimeout(800); }
async function metrics(tag) {
await cdp.send('HeapProfiler.collectGarbage').catch(() => {});
const m = Object.fromEntries((await cdp.send('Performance.getMetrics')).metrics.map(x => [x.name, x.value]));
const dom = await cdp.send('Memory.getDOMCounters').catch(() => ({}));
const sess = await page.evaluate(() => { try { return (localStorage.getItem('strata.sessions.v1') ?? '').length; } catch { return -1; } });
console.log(`${tag.padEnd(22)} heap=${(m.JSHeapUsedSize / 1048576).toFixed(0)}MB total=${(m.JSHeapTotalSize / 1048576).toFixed(0)}MB nodes=${dom.nodes ?? m.Nodes} listeners=${dom.jsEventListeners ?? '-'} docs=${m.Documents} ls=${(sess / 1e6).toFixed(2)}M`);
return m.JSHeapUsedSize;
}
await page.locator('.chat-model-picker').first().click(); await page.locator('.model-picker-api').first().click(); await page.waitForTimeout(500);
await metrics('start');
const ta = page.locator('.composer textarea');
for (let t = 1; t <= TURNS; t++) {
if (t <= PICS) {
const b64 = png(900, 900).toString('base64');
await page.evaluate(b64 => { const bytes = Uint8Array.from(atob(b64), c => c.charCodeAt(0)); const d = new DataTransfer(); d.items.add(new File([bytes], 'image.png', { type: 'image/png' })); document.querySelector('.composer textarea').dispatchEvent(new ClipboardEvent('paste', { clipboardData: d, bubbles: true, cancelable: true })); }, b64);
await page.waitForTimeout(600);
}
await ta.fill('turn ' + t + ' write a long answer');
await page.getByRole('button', { name: 'Send' }).click();
const t0 = Date.now();
let peak = 0; const cpu0 = (await cdp.send('Performance.getMetrics')).metrics.find(x => x.name === 'TaskDuration').value;
for (;;) {
await page.waitForTimeout(2000);
const m = Object.fromEntries((await cdp.send('Performance.getMetrics')).metrics.map(x => [x.name, x.value]));
peak = Math.max(peak, m.JSHeapUsedSize);
const busy = await page.getByRole('button', { name: /Stop/ }).count();
if (!busy || Date.now() - t0 > 240000) break;
}
const cpu1 = (await cdp.send('Performance.getMetrics')).metrics.find(x => x.name === 'TaskDuration').value;
console.log(` turn ${t}: ${(Date.now() - t0) / 1000}s peak-heap=${(peak / 1048576).toFixed(0)}MB main-thread-busy=${(cpu1 - cpu0).toFixed(1)}s`);
await metrics('after turn ' + t);
}
if (MON) { await page.getByText('Monitor', { exact: true }).first().click().catch(() => console.log('no monitor link')); await page.waitForTimeout(25000); await metrics('monitor 25s'); }
try { console.log(execSync('powershell -NoProfile -c "(Get-Process chrome | Measure-Object WorkingSet64 -Sum).Sum/1MB"').toString().trim(), 'MB chrome working set total'); } catch {}
await browser.close();
+14 -3
View File
@@ -33,7 +33,7 @@ import { useLiveStatus } from '../lib/live-status';
import { askQuestion, askSub, askIcon } from '../lib/ask';
import { artifactFromUrl, type PreviewArtifact } from '../lib/artifacts';
/** Chat — talk to the one loaded model. */
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Markdown } from '../components/Markdown';
import { Btn, Icon, IconBtn, ErrorNotice, type IconName } from '../components/ui';
import { composerCap, scrollBehavior } from '../lib/responsive';
@@ -188,6 +188,16 @@ export function ChatScreen() {
if (item)
openPreview(item);
}
/* The message list is memoised (#4640 family: Out of Memory in a long chat): a streamed token changes one message, so the others must not
re-render. These handlers keep one identity for the life of the screen and always call the newest functions above. */
const latestHandlers = useRef({ editPrompt, openPreview, openTimeSkip, openLink });
latestHandlers.current = { editPrompt, openPreview, openTimeSkip, openLink };
const messageHandlers = useMemo(() => ({
onEditPrompt: (text: string) => latestHandlers.current.editPrompt(text),
onPreview: (a: PreviewArtifact) => latestHandlers.current.openPreview(a),
onOpenTimeSkip: (id: string) => latestHandlers.current.openTimeSkip(id),
onOpenLink: (url: string) => latestHandlers.current.openLink(url),
}), []);
const scroller = useRef<HTMLDivElement>(null);
const focusMode = useStore((s) => s.focus);
/** Per-conversation scroll offsets, so returning to one restores the view. */
@@ -445,7 +455,7 @@ export function ChatScreen() {
<div className="chat__inner">
{tr(session.messages.length === 0 ? (session.statsAvailable === false ? <p className="small muted">{tr("Editing from an earlier message. Update the prompt below.")}</p> :
<UsageDashboard loaded={!!loaded}/>) : (session.messages.map((m, i) => (<Message key={m.id} message={m} isLast={i === session.messages.length - 1} onEditPrompt={editPrompt} onPreview={openPreview} onOpenTimeSkip={openTimeSkip} timeSkipDone={!!allTimeSkipRuns.find(r => r.id === m.timeSkipId)?.completedAt} timeSkipReal={!!allTimeSkipRuns.find(r => r.id === m.timeSkipId)?.job} timeSkipRun={allTimeSkipRuns.find(r => r.id === m.timeSkipId)} onOpenLink={openLink}/>))))}
<UsageDashboard loaded={!!loaded}/>) : (session.messages.map((m, i) => (<Message key={m.id} message={m} isLast={i === session.messages.length - 1} onEditPrompt={messageHandlers.onEditPrompt} onPreview={messageHandlers.onPreview} onOpenTimeSkip={messageHandlers.onOpenTimeSkip} timeSkipDone={!!allTimeSkipRuns.find(r => r.id === m.timeSkipId)?.completedAt} timeSkipReal={!!allTimeSkipRuns.find(r => r.id === m.timeSkipId)?.job} timeSkipRun={allTimeSkipRuns.find(r => r.id === m.timeSkipId)} onOpenLink={messageHandlers.onOpenLink}/>))))}
<QueuedMessages chatId={session.id}/>
</div>
</div>
@@ -611,7 +621,8 @@ function Composer({ draft, setDraft, loaded, streaming, onSubmit, onKey, session
</div>) : null)}
</div>);
}
function Message({ message: m, isLast, onEditPrompt, onPreview, onOpenLink, onOpenTimeSkip, timeSkipDone, timeSkipReal, timeSkipRun, }: {
const Message = memo(MessageView);
function MessageView({ message: m, isLast, onEditPrompt, onPreview, onOpenLink, onOpenTimeSkip, timeSkipDone, timeSkipReal, timeSkipRun, }: {
message: ChatMessage;
isLast: boolean;
onEditPrompt: (text: string) => void;
+21
View File
@@ -0,0 +1,21 @@
/** A streamed token changes one message. The others must not render again, or a long chat does work (and makes garbage) for every
* token in proportion to its whole history: measured 0.7 s of main-thread time for a 10-turn reply on a new chat and 1.9 s after ten
* replies, peak heap 95 MB instead of 50 MB (scripts/chat-growth.mjs). Source guards: the DOM is not available in this suite. */
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
const chat = readFileSync(resolve(import.meta.dirname, '../src/screens/Chat.tsx'), 'utf8');
test('the message row is a memoised component', () => {
assert.match(chat, /import \{[^}]*\bmemo\b[^}]*\} from 'react'/);
assert.match(chat, /const Message = memo\(MessageView\)/);
});
test('the list passes handlers whose identity never changes', () => {
assert.match(chat, /const messageHandlers = useMemo\(\(\) => \(\{[\s\S]*?\}\), \[\]\)/);
for (const name of ['onEditPrompt', 'onPreview', 'onOpenTimeSkip', 'onOpenLink'])
assert.match(chat, new RegExp(`${name}=\{messageHandlers\.${name}\}`), name);
assert.doesNotMatch(chat, /onEditPrompt=\{editPrompt\}/);
});