Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 22 additions & 4 deletions apps/writer/scripts/browser-polish-r4-test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,15 @@ async function typeInEditor(page, text) {
assert.ok(await page.evaluate(text => [...window.writer.workspace.getSnapshot().records.values()].some(record => record.snapshot.body.includes(text)), text), `Typing after handoff lost ${text}`);
}

const editorState = page => page.evaluate(async () => (await import("/scripts/browser-a11y-fixture.tsx")).editorSnapshot());

async function assertInsertion(page, before, text) {
const expected = before.text.slice(0, before.from) + text + before.text.slice(before.to);
assert.equal((await editorState(page)).text, expected, `Editor lost or misplaced ${text.trim()}`);
const saved = await page.evaluate(() => window.writer.workspace.getSnapshot().records.get("chapters/reefs.md").snapshot.body);
assert.equal(saved, expected, `Workspace did not receive ${text.trim()}`);
}

async function command(page, query) {
await page.keyboard.press("Control+k");
await page.locator(".mdbase-command-palette input").waitFor();
Expand Down Expand Up @@ -155,6 +164,9 @@ async function continuePosition(page, width, reduced) {
// Logged on success too, so CI shows how close the hide runs to its budget.
console.log(`sidebar hide longest tasks ${reduced ? "reduce" : "no-preference"}: median ${median}ms of ${JSON.stringify(longestTasks)}`);
assert.ok(median < 50, `Sidebar long-task budget exceeded: median of the longest task per hide is ${median}ms (${JSON.stringify(longestTasks)})`);
const afterSidebar = await visible();
assert.equal(afterSidebar.text, anchor.text, "Toggling the sidebar changed the first visible line");
assert.ok(Math.abs(afterSidebar.y - anchor.y) < 2, `Toggling the sidebar moved the viewport: ${JSON.stringify({ anchor, afterSidebar })}`);
}
await page.getByRole("button", { name: "Manuscripts", exact: true }).click();
await page.locator(".continue-card").waitFor();
Expand All @@ -165,7 +177,7 @@ async function continuePosition(page, width, reduced) {
await editor.waitFor();
await page.waitForTimeout(220);
const restored = await visible();
assert.equal(restored.text, anchor.text);
assert.equal(restored.text, anchor.text, `Continue moved to another line: ${JSON.stringify({ anchor, restored, position })}`);
assert.ok(Math.abs(restored.y - anchor.y) < 2, `Continue moved visible text: ${JSON.stringify({ anchor, restored, position })}`);
const before = await page.evaluate(() => { const workspace = window.writer.workspace; return workspace.getSnapshot().records.get(workspace.main).snapshot.body; });
await page.keyboard.type("RESUMED");
Expand Down Expand Up @@ -193,6 +205,7 @@ async function continuePosition(page, width, reduced) {

async function immediateResume(page, shortcut, overlay, text, reduced) {
await page.locator(".cm-content").focus();
const before = await editorState(page);
await page.keyboard.press(shortcut);
await page.locator(overlay).waitFor();
await page.locator(overlay).evaluate(element => Promise.all(element.getAnimations().map(animation => animation.finished)));
Expand All @@ -218,7 +231,7 @@ async function immediateResume(page, shortcut, overlay, text, reduced) {
}, { overlay });
await page.keyboard.press("Escape");
await page.keyboard.type(text, { delay: 3 });
assert.ok(await page.evaluate(text => [...window.writer.workspace.getSnapshot().records.values()].some(record => record.snapshot.body.includes(text)), text), `Immediate Escape resume lost ${text}`);
await assertInsertion(page, before, text);
const [first] = await page.evaluate(() => window.resumeKeys);
assert.equal(first.editor, true, JSON.stringify(first));
if (!reduced) assert.deepEqual({ attached: first.attached, inert: first.inert }, { attached: true, inert: true });
Expand All @@ -228,11 +241,12 @@ async function immediateResume(page, shortcut, overlay, text, reduced) {
async function roundFive(page, width, reduced) {
for (const [shortcut, selector, text] of [["Control+k", ".mdbase-command-palette", " PALETTE_POINTER "], ["Control+/", ".shortcuts-dialog", " HELP_POINTER "]]) {
await page.locator(".cm-content").focus();
const before = await editorState(page);
await page.keyboard.press(shortcut);
await page.locator(selector).waitFor();
await page.mouse.click(4, 10);
await page.keyboard.type(text, { delay: 3 });
assert.ok(await page.evaluate(text => [...window.writer.workspace.getSnapshot().records.values()].some(record => record.snapshot.body.includes(text)), text), `Pointer dismissal lost ${text}`);
await assertInsertion(page, before, text);
assert.equal(await page.evaluate(() => document.activeElement?.matches(".cm-content")), true);
await page.locator(selector).waitFor({ state: "hidden" });
}
Expand All @@ -246,11 +260,14 @@ async function roundFive(page, width, reduced) {
await page.keyboard.press("Escape");
await page.locator(".mdbase-command-palette").waitFor({ state: "hidden" });
await immediateResume(page, "Control+/", ".shortcuts-dialog", " HELP_ESCAPE ", reduced);
await page.keyboard.press("Shift+ArrowLeft");
const beforeHelp = await editorState(page);
assert.ok(beforeHelp.from < beforeHelp.to, "Select text before opening the palette");
await command(page, "Keyboard shortcuts");
await page.locator(".shortcuts-dialog").waitFor();
await page.keyboard.press("Escape");
await page.keyboard.type(" PALETTE_HELP ", { delay: 3 });
assert.ok(await page.evaluate(() => [...window.writer.workspace.getSnapshot().records.values()].some(record => record.snapshot.body.includes(" PALETTE_HELP "))));
await assertInsertion(page, beforeHelp, " PALETTE_HELP ");
await page.locator(".shortcuts-dialog").waitFor({ state: "hidden" });
await command(page, "Settings");
await page.locator(".settings-sheet").waitFor();
Expand Down Expand Up @@ -385,6 +402,7 @@ try {
await context.route("**/*", route => new URL(route.request().url()).origin === origin ? route.continue() : route.abort());
const page = await context.newPage();
page.setDefaultTimeout(7000);
page.setDefaultNavigationTimeout(30_000);
const errors = [];
page.on("pageerror", error => errors.push(error.message));
try {
Expand Down
48 changes: 46 additions & 2 deletions apps/writer/scripts/perf/README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Large collection benchmark (opt-in, local only)
# Large collection benchmarks (opt-in)

From the repository root:

Expand All @@ -8,7 +8,7 @@ rpnpm --filter @mdbase-writer/app typecheck:perf
pnpm -C apps/writer typecheck
```

Run both benchmarks with `rpnpm --filter @mdbase-writer/app test:perf-fixture`. This uses one zero-latency run of the collection fixture.
Run all Vitest benchmarks with `rpnpm --filter @mdbase-writer/app test:perf-fixture`. This uses one zero-latency run of the collection fixture.

Run just the mounted outline benchmark from the repository root:

Expand Down Expand Up @@ -58,6 +58,50 @@ Result JSON is generated evidence: the default is `out/perf/large-collection.jso

## Recorded outcomes

### Source lookup, long-chapter typing and Word export

The baseline is `d10c4ef` (#246). Copy `citations.bench.ts`, `citation-typing-profile.mjs`, `docx-profile.mjs` and `generator.ts` from this revision into the matching `apps/writer/scripts/perf` directory of a baseline checkout. Also copy `apps/writer/src/backend/large-demo.ts` and `apps/writer/src/ui/DemoRoot.tsx` to enable the long chapter in the baseline demo.

```sh
rpnpm --filter @mdbase-writer/app test:perf-fixture scripts/perf/citations.bench.ts
pnpm dev
```

Run the Chromium profiles in a separate shell. Set `BASE` if the development server uses a different port. Use separate output directories on each revision and point the second DOCX run at the first revision's `run-1.docx`.

```sh
pnpm -C apps/writer exec node scripts/perf/citation-typing-profile.mjs
PROFILE_OUTPUT=/tmp/writer-docx-before pnpm -C apps/writer exec node scripts/perf/docx-profile.mjs
PROFILE_OUTPUT=/tmp/writer-docx-after PROFILE_REFERENCE=/tmp/writer-docx-before/run-1.docx \
pnpm -C apps/writer exec node scripts/perf/docx-profile.mjs
```

Vitest used Node 22.22.0 on the remote builder (AMD EPYC 9B14) and took seven measurements after two warmups. It loads 5,000 sources and builds the real APA preview bibliography for 100 cited entries. Warm lookup timings average 100 calls per sample.

| Vitest median | Before | After |
|---|---:|---:|
| Cold source index and broad lookup | 8.82 ms | 6.74 ms |
| Warm broad source lookup | 0.399 ms | 0.114 ms |
| Warm precise citekey lookup | 0.508 ms | 0.521 ms |
| Cold APA bibliography | 390.0 ms | 413.4 ms |
| Cached APA bibliography | 0.066 ms | 0.066 ms |

Chromium 149.0.7827.55 ran on an AMD Ryzen 9 7940HS with Node 22.22.0. Each sample uses a fresh context and waits for the collection and preview assembly. The typing run clears source search, opens the Outline and inserts 22 characters into a 78,762-byte chapter. Picker timing includes Playwright round trips and React rendering. Typing timing measures from `beforeinput` to the next animation-frame callback. CDP reports renderer main-thread CPU time for the typing phase. `PROFILE_CPU` can capture a DevTools profile for each run.

| Chromium median | Before | After |
|---|---:|---:|
| Sources query to matching row, 5 contexts | 29.6 ms | 26.3 ms |
| Typing input to animation frame, 5 contexts | 23.2 ms | 14.5 ms |
| Typing p90 input to animation frame, 5 contexts | 37.0 ms | 24.4 ms |
| Renderer main-thread CPU for 22 inputs, 5 contexts | 1,139 ms | 516 ms |
| Word export preflight, 3 contexts | 371 ms | 81 ms |
| Inside Word export handler, 3 contexts | 2,008 ms | 1,789 ms |
| Chapter save to Word download, 3 contexts | 3,518 ms | 3,236 ms |

The Word run uses 60 chapters, 480 chapter passages, 100 cited sources and 5,000 available sources. All three DOCX files match the baseline package parts after timestamp normalization. Warm broad lookup benefits from stopping after the top metadata matches are known. Word preflight now reuses dependency and diagnostic analysis while Pandoc formats the citations and bibliography. Fetching and converting with Pandoc accounts for 1.67 seconds of the after median. These are development fixture timings using the SDK's in-memory replica on a shared host.

### Earlier collection and outline measurements

Outline comparison on the remote builder (AMD EPYC 9B14, Node 22.22.0). The two revisions ran the same outline benchmark three times each, with Writer at `ba47bda` for the control. The p50 columns are medians of the three runs. The p95 columns show the spread across runs.

| Operation | Before p50 | After p50 | Before p95 range | After p95 range |
Expand Down
86 changes: 86 additions & 0 deletions apps/writer/scripts/perf/citation-typing-profile.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import assert from "node:assert/strict";
import { writeFile } from "node:fs/promises";
import { chromium } from "playwright";

const fixture = new URL(process.env.BASE ?? "http://127.0.0.1:5320/");
const main = "manuscripts/main.md";
const chapter = "chapters/chapter-00000.md";
fixture.search = new URLSearchParams({ demo: "large", largeManuscript: "1", longChapter: "1", manuscript: main }).toString();
const runs = Number(process.env.PROFILE_RUNS ?? 5);
assert.ok(Number.isInteger(runs) && runs > 0, "PROFILE_RUNS must be a positive integer");
const median = values => {
const sorted = [...values].sort((a, b) => a - b);
const mid = Math.floor(sorted.length / 2);
return (sorted[mid] + sorted[Math.ceil(sorted.length / 2) - 1]) / 2;
};
const browser = await chromium.launch({ executablePath: process.env.CHROME });
console.log(JSON.stringify({ chromium: browser.version(), node: process.version }));
try {
for (let run = 1; run <= runs; run++) {
const page = await browser.newPage({ viewport: { width: 1500, height: 950 }, serviceWorkers: "block" });
try {
const errors = [];
page.on("pageerror", error => errors.push(error.message));
await page.addInitScript(() => localStorage.setItem("mdbase-writer:layout", JSON.stringify({ view: "write" })));
await page.goto(fixture.href);
await page.waitForFunction(() => {
const workspace = window.writer?.workspace;
if (!workspace) return false;
const snap = workspace.getSnapshot();
return snap.library.length === 5000 && snap.records.size === 61 && !snap.compiling
&& [snap.indexLoad, snap.annotationsLoad, snap.commentsLoad].every(load => load.phase === "ready");
}, undefined, { timeout: 60_000 });
await page.getByRole("tab", { name: /Sources/ }).click();
const search = page.locator(".sources input[type=search]");
const timings = [];
for (const [query, key] of [["source", "source00000"], ["synthetic research", "source00000"], ["source04999", "source04999"], ["author00124 2024", "source00124"]]) {
const start = await page.evaluate(() => performance.now());
await search.fill(query);
await page.getByRole("list", { name: "Matching sources" }).locator(`.source-row[data-key="${key}"]`).first().waitFor();
timings.push(await page.evaluate(start => performance.now() - start, start));
}
await search.fill("");
await page.getByRole("tab", { name: "Outline", exact: true }).click();
await page.locator(`.record-row[data-path="${chapter}"]`).click();
const editor = page.getByRole("textbox", { name: `Markdown for ${chapter}`, exact: true });
const original = await page.evaluate(path => window.writer.workspace.getSnapshot().records.get(path).snapshot.body, chapter);
const chapterBytes = Buffer.byteLength(original);
assert.ok(chapterBytes >= 50_000 && chapterBytes <= 100_000);
await editor.focus();
await page.keyboard.press("ControlOrMeta+End");
await editor.evaluate(el => {
window.inputFrames = [];
el.addEventListener("beforeinput", () => {
const start = performance.now();
requestAnimationFrame(() => window.inputFrames.push(performance.now() - start));
}, { capture: true });
});
const cdp = await page.context().newCDPSession(page);
await cdp.send("Performance.enable", { timeDomain: "threadTicks" });
const taskTime = async () => (await cdp.send("Performance.getMetrics")).metrics.find(metric => metric.name === "TaskDuration").value * 1000;
if (process.env.PROFILE_CPU) {
await cdp.send("Profiler.enable");
await cdp.send("Profiler.start");
}
const phrase = "The archives show that";
const taskStart = await taskTime();
for (const [index, char] of [...phrase].entries()) {
await page.keyboard.insertText(char);
await page.waitForFunction(count => window.inputFrames.length === count, index + 1);
}
assert.equal(await page.evaluate(path => window.writer.workspace.getSnapshot().records.get(path).snapshot.body, chapter), original + phrase);
const typingMainCpuMs = await taskTime() - taskStart;
if (process.env.PROFILE_CPU) {
const { profile: samples } = await cdp.send("Profiler.stop");
await writeFile(`${process.env.PROFILE_CPU}-${run}.cpuprofile`, JSON.stringify(samples));
}
const frames = await page.evaluate(() => window.inputFrames);
console.log(JSON.stringify({ run, chapterBytes, pickerMs: median(timings), pickerSamplesMs: timings, typingFrameMs: median(frames), typingP90Ms: [...frames].sort((a, b) => a - b)[Math.ceil(frames.length * .9) - 1], typingMainCpuMs }));
assert.deepEqual(errors, []);
} finally {
await page.context().close();
}
}
} finally {
await browser.close();
}
66 changes: 66 additions & 0 deletions apps/writer/scripts/perf/citations.bench.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
// Deterministic Node proxy for the source picker and preview bibliography.
import { readFileSync } from "node:fs";
import { cpus } from "node:os";
import { Citeproc, type CslItem } from "@mdbase-writer/core/citeproc";
import { expect, it } from "vitest";
import type { LibraryEntry } from "../../src/backend/types.js";
import { searchLibrary } from "../../src/editor/library-search.js";
import { counts, generateCollection } from "./generator.js";

const asset = (name: string) => readFileSync(new URL(`../../../../packages/core/assets/csl/${name}`, import.meta.url), "utf8");
const median = (values: number[]) => values.sort((a, b) => a - b)[Math.floor(values.length / 2)];
const measure = <T>(run: () => T) => {
const start = performance.now();
const result = run();
return { ms: performance.now() - start, result };
};

it("profiles 5,000 sources with 100 cited entries", () => {
const library: LibraryEntry[] = [];
generateCollection((path, type, fields) => {
if (type !== "reader-source") return;
const item = fields["csl"] as CslItem;
library.push({ path, key: item.id, title: String(item["title"]), item });
});
expect(library).toHaveLength(counts.sources);
const items = new Map(library.map(entry => [entry.key, entry.item]));
const cited = new Set(library.slice(0, 100).map(entry => entry.key));
const requests = [...cited].map(key => ({ items: [{ key, prefix: "", suffix: "", suppressAuthor: false }], noteIndex: 0 }));
const locales = new Map(["en-US", "en-GB"].map(locale => [locale, asset(`locales-${locale}.xml`)]));
const style = asset("apa.csl");
const samples = [];
for (let run = 0; run < 9; run++) {
const sources = [...library];
const cold = measure(() => searchLibrary(sources, "research", 60, cited));
expect(cold.result.at(0)?.key).toBe("source00000");
expect(cold.result).toHaveLength(60);
const broad = measure(() => {
for (let i = 0; i < 100; i++) searchLibrary(sources, "research", 60, cited);
});
const exact = measure(() => {
for (let i = 0; i < 100; i++) searchLibrary(sources, "source04999", 60, cited);
});
expect(searchLibrary(sources, "source04999", 60, cited).at(0)?.key).toBe("source04999");
const fresh = measure(() => {
const engine = new Citeproc(style, locales, items);
return { engine, formatted: engine.process(requests) };
});
const { engine, formatted } = fresh.result;
expect(formatted.bibliography.entries).toHaveLength(cited.size);
expect(new Set(formatted.bibliography.entries.map(entry => entry.key))).toEqual(cited);
const warm = measure(() => engine.process(requests));
expect(warm.result.mode).toBe("cached");
expect(warm.result.bibliography).toBe(formatted.bibliography);
if (run > 1) samples.push({ cold: cold.ms, broad: broad.ms / 100, exact: exact.ms / 100, bibliography: fresh.ms, cached: warm.ms });
}
console.log(JSON.stringify({
node: process.version, cpu: cpus()[0]?.model, samples,
medians: {
coldSearchMs: median(samples.map(row => row.cold)),
broadSearchMs: median(samples.map(row => row.broad)),
exactSearchMs: median(samples.map(row => row.exact)),
bibliographyMs: median(samples.map(row => row.bibliography)),
cachedBibliographyMs: median(samples.map(row => row.cached)),
},
}));
});
Loading