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
22 changes: 22 additions & 0 deletions apps/writer/scripts/perf/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,28 @@ Both runs used `PROFILE_EDITOR_ONLY=1` on an AMD Ryzen 9 7940HS with Node 22.22.

Both exports produced a 27,086-byte DOCX containing the Word document part. The two browser runs had long tasks above 20 seconds around export and source interactions. The browser measurements are single observations. The repeated Vitest runs establish the outline comparison.

### Word export during a chapter save

With `pnpm dev` running, use the dedicated Chromium benchmark to time a chapter
save overlapping a Word download. Each run opens a fresh browser context, edits
the first chapter with Outline and Comments open, starts a save, and uses the
Word export menu. The browser fixture has 60 chapters, 300 manuscript comment
records, and 5,000 sources.

```sh
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
```

Run the first command with the benchmark and fixture on the baseline revision.
The script takes three samples by default. It reports save-to-download time,
time before the export handler starts, time inside the handler, and main-thread
long-task time. Python checks the ZIP, all 480 chapter passages, the edit, the
bibliography and the cited footnote. Every uncompressed package part is
compared, with creation and modification timestamps normalized. Writer review
threads stay in the collection.

### Earlier browser measurements

On the fixture-corrected product comparison, cold preview went from 3,426 to
Expand Down
155 changes: 155 additions & 0 deletions apps/writer/scripts/perf/docx-profile.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
// Use the DEV-only large manuscript and the real Word download controls.
import assert from "node:assert/strict";
import { execFileSync } from "node:child_process";
import { mkdir } from "node:fs/promises";
import { resolve } from "node:path";
import { chromium } from "playwright";

const base = process.env.BASE ?? "http://127.0.0.1:5320/";
const output = resolve(process.env.PROFILE_OUTPUT ?? "out/perf/docx");
const referencePath = process.env.PROFILE_REFERENCE;
const runs = Number(process.env.PROFILE_RUNS ?? 3);
assert.ok(Number.isInteger(runs) && runs > 0, "PROFILE_RUNS must be a positive integer");
const manuscript = "manuscripts/main.md";
const chapter = "chapters/chapter-00000.md";
const typed = " ordinary typing";
await mkdir(output, { recursive: true });

// Validate every ZIP entry and fingerprint the uncompressed package. Pandoc
// records the export time in core.xml and in the ZIP container.
const inspect = String.raw`
import hashlib, json, sys, zipfile
from xml.etree import ElementTree as ET

w = "{http://schemas.openxmlformats.org/wordprocessingml/2006/main}"
terms = "{http://purl.org/dc/terms/}"
def text(root):
return "".join(n.text or "" for n in root.iter(w + "t"))

with zipfile.ZipFile(sys.argv[1]) as package:
assert package.testzip() is None
doc = ET.fromstring(package.read("word/document.xml"))
paragraphs = [text(p) for p in doc.iter(w + "p")]
for chapter in range(1, 61):
for section in range(1, 9):
expected = (f"Evidence in chapter {chapter}, section {section}, supports the manuscript’s "
"argument. Further analysis puts the result in context.")
assert any(p.startswith(expected) for p in paragraphs), expected
assert text(doc).count(" ordinary typing" * 24) == 1
assert "Bibliography" in paragraphs
assert "Synthetic research 00099" in text(doc)
assert "Author00099, 2024" in text(doc)
assert list(doc.iter(w + "footnoteReference"))
footnotes = ET.fromstring(package.read("word/footnotes.xml"))
assert "Footnote text with a citation (Author00000, 2000)." in text(footnotes)
# Writer review threads stay in the collection, outside the Word document.
assert not list(doc.iter(w + "commentReference"))
if "word/comments.xml" in package.namelist():
comments = ET.fromstring(package.read("word/comments.xml"))
assert not list(comments.iter(w + "comment"))
parts = {}
for name in sorted(package.namelist()):
content = package.read(name)
if name == "docProps/core.xml":
root = ET.fromstring(content)
for node in root:
if node.tag in (terms + "created", terms + "modified"):
node.text = ""
content = ET.tostring(root)
parts[name] = hashlib.sha256(content).hexdigest()
print(json.dumps(parts))
`;

const browser = await chromium.launch({ executablePath: process.env.CHROME });
const inspectDocx = (path) => JSON.parse(execFileSync("python3", ["-c", inspect, path], { encoding: "utf8" }));
try {
const fixture = new URL(base);
fixture.search = new URLSearchParams({ demo: "large", largeManuscript: "1", manuscript }).toString();
let reference = referencePath ? inspectDocx(resolve(referencePath)) : undefined;
for (let run = 1; run <= runs; run++) {
const page = await browser.newPage({ viewport: { width: 1500, height: 950 }, serviceWorkers: "block" });
const errors = [];
page.on("pageerror", error => errors.push(error.message));
page.setDefaultTimeout(120_000);
const cdp = await page.context().newCDPSession(page);
await cdp.send("Network.enable");
await cdp.send("Network.setCacheDisabled", { cacheDisabled: true });
await page.addInitScript(() => {
localStorage.setItem("mdbase-writer:layout", JSON.stringify({ view: "write" }));
window.tasks = [];
new PerformanceObserver((list) => window.tasks.push(...list.getEntries().map(e => [e.startTime, e.duration])))
.observe({ type: "longtask" });
});
await page.goto(fixture.href);
await page.waitForFunction(() => {
const workspace = window.writer?.workspace;
if (!workspace) return false;
const snap = workspace.getSnapshot();
const order = workspace.readingOrder();
return order.length === 61 && order.every(path => snap.records.has(path))
&& ["indexLoad", "libraryLoad", "annotationsLoad", "commentsLoad"].every(key => snap[key].phase === "ready");
});
assert.deepEqual(await page.evaluate(() => {
const snap = window.writer.workspace.getSnapshot();
return { comments: snap.comments.length, sources: snap.library.length };
}), { comments: 300, sources: 5_000 });
await page.getByRole("tab", { name: "Outline", exact: true }).click();
await page.locator(`.record-row[data-path="${chapter}"]`).click();
const editor = page.locator(".cm-content");
const type = async () => {
await editor.focus();
await page.keyboard.press("ControlOrMeta+End");
for (let i = 0; i < 12; i++) await page.keyboard.insertText(typed);
};
await type();
await page.getByRole("tab", { name: /Comments/ }).click();
await page.locator(".mdbase-threads > .mdbase-thread").first().waitFor();
await type();
await page.waitForFunction(({ chapter, suffix }) => window.writer.workspace.getSnapshot().records.get(chapter).snapshot.body.endsWith(suffix),
{ chapter, suffix: typed.repeat(24) });

// Save at the export boundary to reproduce the autosave refresh on demand.
// Both paths use the ordinary SDK record session and collection watch.
const start = await page.evaluate(chapter => {
const workspace = window.writer.workspace;
const exportDocx = workspace.exportDocx.bind(workspace);
workspace.exportDocx = async (...args) => {
performance.mark("export:start");
try { return await exportDocx(...args); }
finally { performance.mark("export:end"); }
};
const start = performance.now();
window.save = workspace.retrySave(chapter);
return start;
}, chapter);

const download = page.waitForEvent("download");
await page.getByRole("button", { name: "Export formats" }).click();
await page.getByRole("menuitem").filter({ has: page.getByText("Word (DOCX)", { exact: true }) }).click();
await page.waitForFunction(() => performance.getEntriesByName("export:end").length === 1);
const review = page.getByRole("button", { name: "Export anyway", exact: true });
if (await review.isVisible()) await review.click();
const file = await download;
const timing = await page.evaluate(start => {
const exportStart = performance.getEntriesByName("export:start")[0].startTime;
const exportEnd = performance.getEntriesByName("export:end")[0].startTime;
return {
saveToDownloadMs: Math.round(performance.now() - start),
beforeExportMs: Math.round(exportStart - start),
exportMs: Math.round(exportEnd - exportStart),
mainLongTaskMs: Math.round(window.tasks.filter(([at]) => at >= start).reduce((sum, [, duration]) => sum + duration, 0)),
};
}, start);
assert.equal((await page.evaluate(() => window.save)).ok, true);
assert.deepEqual(errors, []);
const path = resolve(output, `run-${run}.docx`);
await file.saveAs(path);
const parts = inspectDocx(path);
if (reference) assert.deepEqual(parts, reference);
reference = parts;
console.log(JSON.stringify({ run, ...timing, parts }));
await page.context().close();
}
} finally {
await browser.close();
}
4 changes: 3 additions & 1 deletion apps/writer/scripts/perf/generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@ export function generateCollection(seed: (path: string, type: string, fm: JsonOb
const noteBody = "Ordinary collection note.\n".repeat(80);
const commentBody = "A comment discussing the passage. ".repeat(16);
const abstract = "Source metadata. ".repeat(40);
const mainBody = browserChapters.length ? `${body}${browserChapters.map(path => `![[${path}]]`).join("\n\n")}\n` : body;
const mainBody = browserChapters.length
? `${body}The manuscript includes a footnote.[^fixture]\n\n[^fixture]: Footnote text with a citation [@source00000].\n\n${browserChapters.map(path => `![[${path}]]`).join("\n\n")}\n`
: body;
for (let i = 0; i < counts.manuscripts; i++) seed(i === 0 ? main : `manuscripts/paper-${pad(i)}.md`, "writer-manuscript", { title: `Paper ${pad(i)}`, csl: "apa", template: "article" }, i === 0 ? mainBody : body);
for (const [i, path] of browserChapters.entries()) {
const sections = Array.from({ length: 8 }, (_, section) => `### Section ${section + 1}\n\nEvidence in chapter ${i + 1}, section ${section + 1}, supports the manuscript's argument. Further analysis puts the result in context.`);
Expand Down
28 changes: 18 additions & 10 deletions apps/writer/scripts/perf/large-collection.bench.ts
Original file line number Diff line number Diff line change
Expand Up @@ -233,16 +233,24 @@ it("large collection baseline (opt-in)", async () => {
cloneLibrary5000: measure(() => structuredClone({ type: "library", library: library.map((e) => e.item) })),
};
const previousRecords = workspace.getSnapshot().recordPaths;
const refreshMessagesStart = compiler.messages.length;
const refreshStart = performance.now();
f.replica.editElsewhere("notes/note-00000.md", { body: "Changed in another app" });
await until(workspace, () => {
const current = workspace!.getSnapshot();
return current.indexLoad.phase === "ready" && current.libraryLoad.phase === "ready" && current.annotationsLoad.phase === "ready" && (current.recordPaths !== previousRecords || f.transfers.some((t) => t.operation === "query:changed-paths" || t.operation === "read:note"));
const note = "notes/note-00000.md";
const noteMessagesStart = compiler.messages.length;
const noteChanged = new Promise<void>(resolve => {
const stop = f.backend.onCollectionChange(delta => {
if (!delta.paths.includes(note)) return;
stop();
resolve();
});
});
const externalRefreshMs = performance.now() - refreshStart;
const externalTransfers = totals(f.transfers.splice(0));
const noteWorkerMessages = compiler.messages.slice(refreshMessagesStart);
const noteStart = performance.now();
f.replica.editElsewhere(note, { body: "Changed in another app" });
await noteChanged;
expect(await f.backend.readBody(note)).toEqual({ ok: true, value: "Changed in another app" });
const noteChangeAndReadMs = performance.now() - noteStart;
const noteTransfers = totals(f.transfers.splice(0));
const noteWorkerMessages = compiler.messages.slice(noteMessagesStart);
expect(noteTransfers.byOperation).toEqual({ "read:note": 1 });
expect(workspace.getSnapshot().recordPaths).toBe(previousRecords);
f.seed("sources/new-source.md", "reader-source", { csl: { id: "newsource", type: "book", title: "A newly imported source" } }, "New source");
const sourceChangeStart = performance.now();
const sourceMessagesStart = compiler.messages.length;
Expand All @@ -251,7 +259,7 @@ it("large collection baseline (opt-in)", async () => {
const newSourceMs = performance.now() - sourceChangeStart;
const newSourceTransfers = totals(f.transfers.splice(0));
const sourceWorkerMessages = compiler.messages.slice(sourceMessagesStart);
output.push({ run: run + 1, seedMs, homeListMs, homeBackgroundMs, readyMs, sourcesUsableMs, sourcesFirstSearchMs, commentsUsableMs, annotationIndexMs, sourceAnnotationsMs, annotationsUsableMs, previewInitializedMs, externalRefreshMs, newSourceMs, newSourceTransfers, commentTransfers, annotationIdentityTransfers, returnHomeMs, returnHomeTransfers, navigationTransfers, noteWorkerMessages, sourceWorkerMessages, homeTransfers, readyTransfers, workspaceTransfers, externalTransfers, computations, workerMessages: [...compiler.messages] });
output.push({ run: run + 1, seedMs, homeListMs, homeBackgroundMs, readyMs, sourcesUsableMs, sourcesFirstSearchMs, commentsUsableMs, annotationIndexMs, sourceAnnotationsMs, annotationsUsableMs, previewInitializedMs, noteChangeAndReadMs, noteTransfers, newSourceMs, newSourceTransfers, commentTransfers, annotationIdentityTransfers, returnHomeMs, returnHomeTransfers, navigationTransfers, noteWorkerMessages, sourceWorkerMessages, homeTransfers, readyTransfers, workspaceTransfers, computations, workerMessages: [...compiler.messages] });
} finally { await workspace?.dispose(); await f.close(); }
// Same collection size, redistributed highlights: one book has 300, not six.
// Only its no-body annotation discovery pages are 6x slower, exposing preview gating.
Expand Down
62 changes: 62 additions & 0 deletions apps/writer/src/backend/native.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,68 @@ describe("native Writer domain backend", () => {
expect(pages).not.toHaveBeenCalled();
opened.value.release();
});
it("keeps collection metadata after a chapter edit and reads its latest confirmed body", async () => {
const h = await fixture();
const path = "chapters/typed.md";
const chapter = h.replica.seed({path, types: ["note"], body: "Original chapter"});
const pages = vi.spyOn(h.client, "pages");
const index = await h.backend.index();
const library = await h.backend.library();
if (!index.ok || !library.ok) throw new Error("Missing fixture metadata");
const changed = vi.fn(); h.backend.onCollectionChange(changed);

h.replica.editElsewhere(chapter.id, {body: "Edited chapter"});
await vi.waitFor(() => expect(changed).toHaveBeenCalledWith({paths: [path]}));
expect(await h.backend.readBody(path)).toEqual({ok: true, value: "Edited chapter"});
const currentIndex = await h.backend.index();
const currentLibrary = await h.backend.library();
expect(currentIndex.ok && currentIndex.value).toBe(index.value);
expect(currentLibrary.ok && currentLibrary.value).toBe(library.value);
expect(pages).toHaveBeenCalledOnce();

const get = h.client.get.bind(h.client);
const getSpy = vi.spyOn(h.client, "get");
getSpy.mockImplementationOnce(async (...args) => {
const record = await get(...args);
return {...record, state: {...record.state, unresolved: 1}};
});
expect((await h.backend.readBody(path)).ok).toBe(false);
getSpy.mockImplementationOnce(async (...args) => {
const record = await get(...args);
changed.mockClear();
h.replica.editElsewhere(chapter.id, {body: "Newer chapter"});
await vi.waitFor(() => expect(changed).toHaveBeenCalledWith({paths: [path]}));
return record;
});
expect((await h.backend.readBody(path)).ok).toBe(false);
getSpy.mockRestore();
expect(await h.backend.readBody(path)).toEqual({ok: true, value: "Newer chapter"});

h.replica.renameElsewhere(chapter.id, "chapters/renamed.md");
await vi.waitFor(() => expect(changed).toHaveBeenCalledWith({paths: [path], reset: true}));
const moved = await h.backend.index();
expect(moved.ok && moved.value.recordPaths).toContain("chapters/renamed.md");
expect(moved.ok && moved.value.recordPaths).not.toContain(path);
expect(pages).toHaveBeenCalledTimes(2);
});
it("reloads metadata when a watch batch has an unknown type, changed type or different identity", async () => {
const watch = controlledWatch();
const h = await fixture(client => {vi.spyOn(client, "watchChanges").mockReturnValue(watch.watch);});
const chapter = h.replica.seed({path: "chapters/typed.md", types: ["note"]});
const onChange = vi.mocked(h.client.watchChanges).mock.calls[0]?.[0];
if (!onChange) throw new Error("Missing watch callback");
const changed = vi.fn(); h.backend.onCollectionChange(changed);
const pages = vi.spyOn(h.client, "pages");
const put = {id: chapter.id, path: chapter.path, kind: "put", entity: "record", version: 1} as const;
await h.backend.index();

for (const uncertain of [put, {...put, types: ["native-source"]}, {...put, types: ["note"], id: crypto.randomUUID()}]) {
onChange({changes: [{...put, types: ["note"]}, uncertain], cursor: "change", reset: false});
expect(changed).toHaveBeenLastCalledWith({paths: [chapter.path, chapter.path], reset: true});
expect((await h.backend.index()).ok).toBe(true);
}
expect(pages).toHaveBeenCalledTimes(4);
});
it("unrelated invalid definitions do not hide Writer records or untyped notes", async () => {
const h = await fixture();
h.description.issues.push({code: "type_invalid", severity: "error", message: "An unrelated custom type is invalid", details: {path: "_types/unrelated.md"}});
Expand Down
Loading