Repository navigation
perf(web): equations no longer force a layout when a thread opens - #37639
zhaoshenzhai wants to merge 3 commits into
Conversation
Every equation measured whether it overflows in a layout effect, which read scrollWidth mid-commit and forced a layout of everything the commit inserted. On a thread switch that is the whole new thread, and the timeline list's own layout effect writes to the DOM right after, so that layout was thrown away and done again. The equation already observes its viewport and content, and the observer's first delivery comes after layout and is applied before paint, so the extra measure is removed. Built by Claude Opus 5.5 in Claude Code, running in T3 Code. Co-Authored-By: Claude Opus 5.5 <[email protected]>
ApprovabilityVerdict: Approved at Macroscope's review found this PR approvable — Equation overflow measurement now waits for the existing resize observer rather than forcing layout when a thread opens. The change is limited to UI measurement timing, with existing overflow handling and cleanup retained. You can add or adjust custom eligibility rules. Learn more. |
|
No actionable comments were generated in the recent review. Walkthrough
Merge Risk:
|
Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
The automated pipeline stopped on this pull request and will not merge it: the fix is written and reviewed, but proving it needs something no worker has:
It stays open for a person to finish or close. |
|
Here are the measurements the pipeline couldn't take, from an Apple M4 on macOS 27.0.1 with Playwright 1.64.1's headless Chromium. Base is Setup. A scenario home from Run medians, four runs each:
Base spread is at most 32, 17 and 16 ms, and head spread at most 13, 8 and 8 ms. The medians of the run medians differ by 201, 199 and 36 ms, and every head run is faster than every base run. These numbers are higher than the ones in the description because this recording adds the wide equation. Keyboard scrolling. In every run, base and head behaved the same. After a switch opened the thread, six equations had the "Scroll display equation" scroller. Clicking the text before the last one and pressing Tab reached that scroller (10 presses on both, with Harness (local only, not part of this PR)
{ id: "heavy", name: "Heavy", file: "./dev-replay/heavy_transcript.ndjson" },
{"type": "transcript_start", "provider": "acpRegistry", "protocol": "acp.ndjson-jsonrpc", "version": "1", "scenario": "dev_replay_heavy", "metadata": {"generatedBy": "local measurement"}}
{"type": "expect_outbound", "frame": {"kind": "request", "method": "session/prompt", "params": "<any>"}}
{"type": "emit_inbound", "frame": {"kind": "notification", "method": "session/update", "params": {"sessionId": "dev-replay-session", "update": {"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": "## Lifting the factorization\n\nLet $G$ be a finite group and $H \\le G$ a subgroup of index $n$. The transfer $V \\colon G \\to H^{ab}$ is defined by\n$$V(g) = \\prod_{i=1}^{n} h_i(g) \\, [H,H],$$\nwhere $g t_i = t_{\\sigma(i)} h_i(g)$ for a transversal $t_1, \\dots, t_n$.\n\n1. **Independence.** The class of $V(g)$ does not depend on the transversal, since replacing $t_i$ by $t_i k_i$ changes each factor by $k_{\\sigma(i)}^{-1} h_i(g) k_i$.\n2. **Homomorphism.** For $g, g' \\in G$ we get $V(gg') = V(g) V(g')$ because $\\sigma_{gg'} = \\sigma_g \\sigma_{g'}$.\n3. **Evaluation.** If $g$ is central then $V(g) = g^n [H,H]$.\n\n```python\ndef transfer(G, H, g):\n reps = G.transversal(H)\n acc = H.identity()\n for t in reps:\n s = G.coset_rep(H, g * t)\n acc = acc * (s.inverse() * g * t)\n return acc.abelianize()\n```\n\n| Step | Claim | Uses |\n| --- | --- | --- |\n| 1 | well defined | $k_i \\in H$ |\n| 2 | homomorphism | $\\sigma_{gg'} = \\sigma_g\\sigma_{g'}$ |\n| 3 | central case | $Z(G)$ |\n\nBy Burnside's theorem, if a Sylow $p$-subgroup $P$ satisfies $P \\le Z(N_G(P))$ then $G$ has a normal $p$-complement, so $G \\cong N \\rtimes P$ with $|N| = |G|/|P|$ and $\\gcd(|N|, p) = 1$.\n## Lifting the factorization\n\nLet $G$ be a finite group and $H \\le G$ a subgroup of index $n$. The transfer $V \\colon G \\to H^{ab}$ is defined by\n$$V(g) = \\prod_{i=1}^{n} h_i(g) \\, [H,H],$$\nwhere $g t_i = t_{\\sigma(i)} h_i(g)$ for a transversal $t_1, \\dots, t_n$.\n\n1. **Independence.** The class of $V(g)$ does not depend on the transversal, since replacing $t_i$ by $t_i k_i$ changes each factor by $k_{\\sigma(i)}^{-1} h_i(g) k_i$.\n2. **Homomorphism.** For $g, g' \\in G$ we get $V(gg') = V(g) V(g')$ because $\\sigma_{gg'} = \\sigma_g \\sigma_{g'}$.\n3. **Evaluation.** If $g$ is central then $V(g) = g^n [H,H]$.\n\n```python\ndef transfer(G, H, g):\n reps = G.transversal(H)\n acc = H.identity()\n for t in reps:\n s = G.coset_rep(H, g * t)\n acc = acc * (s.inverse() * g * t)\n return acc.abelianize()\n```\n\n| Step | Claim | Uses |\n| --- | --- | --- |\n| 1 | well defined | $k_i \\in H$ |\n| 2 | homomorphism | $\\sigma_{gg'} = \\sigma_g\\sigma_{g'}$ |\n| 3 | central case | $Z(G)$ |\n\nBy Burnside's theorem, if a Sylow $p$-subgroup $P$ satisfies $P \\le Z(N_G(P))$ then $G$ has a normal $p$-complement, so $G \\cong N \\rtimes P$ with $|N| = |G|/|P|$ and $\\gcd(|N|, p) = 1$.\n\n\nThe full expansion is\n$$a_{1} b_{1} \\cdot \\frac{x^{1}}{1!} + a_{2} b_{2} \\cdot \\frac{x^{2}}{2!} + a_{3} b_{3} \\cdot \\frac{x^{3}}{3!} + a_{4} b_{4} \\cdot \\frac{x^{4}}{4!} + a_{5} b_{5} \\cdot \\frac{x^{5}}{5!} + a_{6} b_{6} \\cdot \\frac{x^{6}}{6!} + a_{7} b_{7} \\cdot \\frac{x^{7}}{7!} + a_{8} b_{8} \\cdot \\frac{x^{8}}{8!} + a_{9} b_{9} \\cdot \\frac{x^{9}}{9!} + a_{10} b_{10} \\cdot \\frac{x^{10}}{10!} + a_{11} b_{11} \\cdot \\frac{x^{11}}{11!} + a_{12} b_{12} \\cdot \\frac{x^{12}}{12!} + a_{13} b_{13} \\cdot \\frac{x^{13}}{13!} + a_{14} b_{14} \\cdot \\frac{x^{14}}{14!} + a_{15} b_{15} \\cdot \\frac{x^{15}}{15!} + a_{16} b_{16} \\cdot \\frac{x^{16}}{16!} + a_{17} b_{17} \\cdot \\frac{x^{17}}{17!} + a_{18} b_{18} \\cdot \\frac{x^{18}}{18!} + a_{19} b_{19} \\cdot \\frac{x^{19}}{19!} + a_{20} b_{20} \\cdot \\frac{x^{20}}{20!} + a_{21} b_{21} \\cdot \\frac{x^{21}}{21!} + a_{22} b_{22} \\cdot \\frac{x^{22}}{22!} + a_{23} b_{23} \\cdot \\frac{x^{23}}{23!} + a_{24} b_{24} \\cdot \\frac{x^{24}}{24!} + a_{25} b_{25} \\cdot \\frac{x^{25}}{25!} + a_{26} b_{26} \\cdot \\frac{x^{26}}{26!} + a_{27} b_{27} \\cdot \\frac{x^{27}}{27!} + a_{28} b_{28} \\cdot \\frac{x^{28}}{28!} + a_{29} b_{29} \\cdot \\frac{x^{29}}{29!} + a_{30} b_{30} \\cdot \\frac{x^{30}}{30!} + a_{31} b_{31} \\cdot \\frac{x^{31}}{31!} + a_{32} b_{32} \\cdot \\frac{x^{32}}{32!} + a_{33} b_{33} \\cdot \\frac{x^{33}}{33!} + a_{34} b_{34} \\cdot \\frac{x^{34}}{34!} + a_{35} b_{35} \\cdot \\frac{x^{35}}{35!} + a_{36} b_{36} \\cdot \\frac{x^{36}}{36!} + a_{37} b_{37} \\cdot \\frac{x^{37}}{37!} + a_{38} b_{38} \\cdot \\frac{x^{38}}{38!} + a_{39} b_{39} \\cdot \\frac{x^{39}}{39!} + a_{40} b_{40} \\cdot \\frac{x^{40}}{40!}$$\n"}}}}}
{"type": "emit_inbound", "frame": {"kind": "response", "method": "session/prompt", "result": {"stopReason": "end_turn"}}}
// Disposable measurement, not a proof: times thread.next from keydown to the next thread's
// history on screen, for never-opened, persisted-cache and in-memory threads.
import * as NodeFS from "node:fs";
import * as NodePath from "node:path";
import { chromium, type Page } from "playwright-core";
import { T3_HOME } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";
const THREADS = Number(process.env.SWITCH_THREADS ?? 6);
const TURNS = Number(process.env.SWITCH_TURNS ?? 6);
const OUT = process.env.SWITCH_OUT ?? "/tmp/switch";
const PROFILE = process.env.SWITCH_PROFILE === "1";
const instrument = (page: Page, markers: Record<string, string>) =>
page.evaluate((markerMap) => {
const w = window as unknown as { __m: { samples: Array<any>; events: Array<any> }; __hooked?: boolean };
w.__m = { samples: [], events: [] };
if (w.__hooked) return;
w.__hooked = true;
new PerformanceObserver((list) => {
for (const e of list.getEntries() as Array<PerformanceEventTiming>) {
if (e.name === "keydown") {
w.__m.events.push({ start: e.startTime, duration: e.duration });
}
}
}).observe({ type: "event", durationThreshold: 16 });
window.addEventListener(
"keydown",
(event) => {
if (event.key !== "}" && event.key !== "{") return;
const sample: any = { t0: event.timeStamp, from: location.pathname };
w.__m.samples.push(sample);
const check = () => {
if (location.pathname === sample.from) return false;
sample.tUrl ??= performance.now();
const id = decodeURIComponent(location.pathname.split("/").pop() ?? "");
const marker = markerMap[id];
if (!marker || !document.body.textContent?.includes(marker)) return false;
sample.tDom = performance.now();
requestAnimationFrame(() => {
setTimeout(() => {
sample.tPaint = performance.now();
}, 0);
});
return true;
};
const observer = new MutationObserver(() => {
if (check()) observer.disconnect();
});
observer.observe(document.body, { childList: true, subtree: true, characterData: true });
// A thread in memory renders inside this keydown, before the URL changes, so poll too.
const poll = () => {
if (sample.tDom !== undefined) return;
if (check()) observer.disconnect();
else if (performance.now() - sample.t0 < 3000) requestAnimationFrame(poll);
};
requestAnimationFrame(poll);
},
{ capture: true },
);
}, markers);
const collect = (page: Page) =>
page.evaluate(() => (window as unknown as { __m: unknown }).__m);
test("thread.next paths", { ...WEB, timeout: 900_000 }, async ({ t3, app }) => {
const project = await t3.project("demo");
for (let i = 0; i < Number(process.env.SWITCH_FILLER ?? 0); i++) {
await t3.thread({ project, title: `Filler ${i}`, messages: [`filler ${i}`] });
}
const ids: Array<string> = [];
const markers: Record<string, string> = {};
for (let i = 0; i < THREADS; i++) {
const messages = Array.from({ length: TURNS }, (_, j) => `marker-t${i}-m${j}`);
const thread = await t3.thread({
project,
title: `Thread ${i}`,
messages,
...(process.env.SWITCH_MODEL ? { model: process.env.SWITCH_MODEL } : {}),
});
ids.push(thread.threadId);
markers[thread.threadId] = `marker-t${i}-m${TURNS - 1}`;
}
const base = app.baseUrl ?? "";
const environment = (
(await (await fetch(`${base}/.well-known/t3/environment`)).json()) as { environmentId: string }
).environmentId;
const pairing = NodeFS.readFileSync(NodePath.join(T3_HOME, "pairing-path"), "utf8");
const browser = await chromium.launch({
headless: true,
args: ["--disable-features=LocalNetworkAccessChecks,BlockInsecurePrivateNetworkRequests"],
});
const results: Record<string, unknown> = {};
try {
const page = await browser.newPage({ viewport: { width: 1440, height: 900 } });
if (process.env.SWITCH_MATH === "1") {
await page.addInitScript(() => {
const key = "t3code:client-settings:v1";
const current = JSON.parse(localStorage.getItem(key) ?? "{}");
localStorage.setItem(key, JSON.stringify({ ...current, mathRenderingEnabled: true }));
});
}
if (process.env.SWITCH_COUNT === "1") {
await page.addInitScript(() => {
const stats: Record<string, { n: number; ms: number; slow: number }> = {};
(window as unknown as { __layoutStats: unknown }).__layoutStats = stats;
const wrap = (proto: object, prop: string, kind: "method" | "getter") => {
const desc = Object.getOwnPropertyDescriptor(proto, prop)!;
const original = (kind === "method" ? desc.value : desc.get) as (...a: Array<unknown>) => unknown;
const timed = function (this: unknown, ...args: Array<unknown>) {
const t = performance.now();
const r = original.apply(this, args);
const d = performance.now() - t;
const s = (stats[prop] ??= { n: 0, ms: 0, slow: 0 });
s.n++;
s.ms += d;
if (d > 1) {
s.slow++;
const log = ((stats as any).__slow ??= []) as Array<unknown>;
log.push([prop, Math.round(t), Math.round(d), (new Error().stack ?? "").split("\n").slice(2, 7).map((l) => l.trim().replace(/\(.*\/assets\//, "(").replace(/^at /, "")).join(" < ")]);
}
return r;
};
Object.defineProperty(proto, prop, kind === "method" ? { ...desc, value: timed } : { ...desc, get: timed });
};
wrap(Element.prototype, "getBoundingClientRect", "method");
wrap(Element.prototype, "getClientRects", "method");
wrap(Element.prototype, "scrollWidth", "getter");
wrap(Element.prototype, "clientWidth", "getter");
wrap(Element.prototype, "scrollHeight", "getter");
wrap(Element.prototype, "clientHeight", "getter");
wrap(HTMLElement.prototype, "offsetHeight", "getter");
wrap(HTMLElement.prototype, "offsetWidth", "getter");
wrap(Element.prototype, "scrollIntoView", "method");
});
}
const dist = process.env.SWITCH_DIST;
if (dist) {
await page.route(`${base}/**`, async (route) => {
const request = route.request();
const url = new URL(request.url());
if (request.resourceType() === "document") {
return route.fulfill({ path: NodePath.join(dist, "index.html") });
}
const file = NodePath.join(dist, decodeURIComponent(url.pathname));
if (url.pathname !== "/" && NodeFS.existsSync(file) && NodeFS.statSync(file).isFile()) {
return route.fulfill({ path: file });
}
return route.continue();
});
}
const last = ids[ids.length - 1]!;
const openLast = async () => {
await page.goto(`${base}/${environment}/${last}`);
await page.getByText(markers[last]!).first().waitFor({ timeout: 30_000 });
await page.waitForTimeout(2500);
await instrument(page, markers);
};
const pass = async (key: string) => {
for (let i = 0; i < THREADS - 1; i++) {
await page.keyboard.press(key);
await page.waitForTimeout(1000);
}
};
await page.goto(`${base}${pairing}`);
await page.waitForURL((url) => !/\/pair(?:[?#]|$)/.test(url.pathname), { timeout: 60_000 });
// Never opened in this browser: nothing cached.
await openLast();
await pass("Meta+Shift+BracketRight");
results.fresh = await collect(page);
// Visited before, page reloaded: the persisted cache holds them, memory does not.
await page.goto(`${base}/`);
await page.waitForTimeout(1500);
await openLast();
const pcdp = process.env.SWITCH_PROFILE === "persisted" ? await page.context().newCDPSession(page) : null;
if (pcdp) {
await pcdp.send("Profiler.enable");
await pcdp.send("Profiler.setSamplingInterval", { interval: 100 });
await pcdp.send("Profiler.start");
}
const resetStats = () =>
page.evaluate(() => {
const s = (window as unknown as { __layoutStats?: Record<string, unknown> }).__layoutStats;
if (s) for (const k of Object.keys(s)) delete s[k];
});
await resetStats();
await pass("Meta+Shift+BracketRight");
results.persistedLayout = await page.evaluate(
() => (window as unknown as { __layoutStats?: unknown }).__layoutStats ?? null,
);
if (pcdp) {
const { profile } = await pcdp.send("Profiler.stop");
NodeFS.writeFileSync(`${OUT}-persisted.cpuprofile`, JSON.stringify(profile));
}
results.persisted = await collect(page);
// Keyboard scrolling of the wide equation in the thread the last switch opened.
{
await page.waitForTimeout(1500);
const lead = page.getByText("The full expansion is", { exact: true }).last();
await lead.click();
let tabs = 0;
let label: string | null = null;
while (tabs < 30 && label !== "Scroll display equation") {
await page.keyboard.press("Tab");
tabs++;
label = await page.evaluate(() => document.activeElement?.getAttribute("aria-label") ?? null);
}
const focused = { label, tabs };
const before = await page.evaluate(() => (document.activeElement as HTMLElement).scrollLeft);
for (let i = 0; i < 5; i++) await page.keyboard.press("ArrowRight");
await page.waitForTimeout(500);
const after = await page.evaluate(() => (document.activeElement as HTMLElement).scrollLeft);
const scrollers = await page.getByLabel("Scroll display equation").count();
results.keyboard = { focused, scrollLeftBefore: before, scrollLeftAfter: after, scrollers };
await page.screenshot({ path: `${OUT}-keyboard.png` });
}
// Just visited: retained in memory.
await pass("Meta+Shift+BracketLeft");
await instrument(page, markers);
const cdp = PROFILE ? await page.context().newCDPSession(page) : null;
if (cdp) {
await cdp.send("Profiler.enable");
await cdp.send("Profiler.setSamplingInterval", { interval: 100 });
await cdp.send("Profiler.start");
}
await pass("Meta+Shift+BracketRight");
await pass("Meta+Shift+BracketLeft");
if (cdp) {
const { profile } = await cdp.send("Profiler.stop");
NodeFS.writeFileSync(`${OUT}.cpuprofile`, JSON.stringify(profile));
}
results.warm = await collect(page);
NodeFS.writeFileSync(`${OUT}.json`, JSON.stringify(results));
} finally {
await browser.close();
}
});Measured by Claude Opus 5.5 in Claude Code, running in T3 Code. |
|
This PR conflicts with See the conflict window. |
|
Thanks for this. Main already has the change, as of 0fb6ac6. Main already removes the forced layout this change targets. The renderer replacement in 0fb6ac6e65 deleted MarkdownMath and renders equations as static SVG with CSS scrolling, so there is no equation layout effect left to defer. Your profiling identified a real cost in the previous renderer. The later measurements remain useful evidence, but this patch now targets code that has been removed. Closing as superseded. |
Problem
Switching to a thread with math is slow. Every
MarkdownMathchecked whether it overflows in a layout effect, readingscrollWidthmid-commit. That read forces a layout of everything the commit inserted, which on a thread switch is the whole new thread. The timeline list's layout effect then moves its rows (sortContainerElements) and readsgetBoundingClientRect, so the browser lays the thread out again. With math rendering on, that layout is the most expensive one in a switch.Change
The layout effect no longer measures. It already observes the viewport and content through
observeResize, whose first delivery comes after layout and is flushed before paint, sooverflowsis still correct in the first painted frame.overflowsonly setstabIndexand anaria-label, so nothing about layout depends on it.Scope
A small fix for a real performance problem, with no behavior change. It needs no issue.
Verification
Test.
MarkdownMath.browser.test.tsxgains a case that mounts a short and an overflowing equation. It countsscrollWidthreads before a later sibling's ref attaches, and checks that the overflowing equation still becomes keyboard scrollable. Onmainit fails withexpected 2 to be +0; here it passes, with the existing keyboard-scroll case.vp run check:changedpasses.Measurement. I found this by profiling
thread.next(mod+shift+]) in a production build of the web client (vp build, served in place of the dev client's assets). The server was a scenario home (start-app.ts) with six Replay threads of six turns each, using a recording whose reply has about 50 inline and display formulas, plusmathRenderingEnabled. Instrumenting the layout reads showed three forced full layouts per switch, each about 80 ms on this machine, in this order:MarkdownMathscrollWidth(≈90 ms), legend-listmeasureContainersInLayoutEffect(≈82 ms) and the scroll area'sscrollHeight(≈74 ms). With this change the first one is gone.Median from keydown to the next thread's history on screen and painted (5 switches per phase, 2 runs each, alternating base and head, headless Chromium on an Apple Silicon Mac):
mainkeydownevent durationNot checked: the desktop app itself, and threads without math (no formulas means no reads, so nothing changes there).
Built by Claude Opus 5.5 in Claude Code, running in T3 Code.
🤖 Generated with Claude Code