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
32 changes: 19 additions & 13 deletions apps/writer/scripts/perf/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,29 +58,35 @@ Result JSON is generated evidence: the default is `out/perf/large-collection.jso

## Paired interactive Chromium profile

Start a DEV server for each revision on a separate port. Copy the benchmark's
`interactive-profile.mjs`, `outline.bench.tsx`, `large-demo.ts` and `DemoRoot.tsx`
to the same locations in the baseline checkout. The last two files enable
the same fixture sizes on both revisions.
Start a DEV server for each revision on a separate port. Use the same large
demo fixture on both revisions and run the driver from the candidate checkout.
Set the same SDK environment on both servers. The production SDK below
negotiates larger contract pages with capable replicas. The default LAB SDK
caps them at 128. Both use local demo data.

```sh
# In separate shells, from each checkout
pnpm -C apps/writer dev --port 5437 # baseline
pnpm -C apps/writer dev --port 5438 # candidate
VITE_MDBASE_ENV=production pnpm -C apps/writer dev --port 5437 # baseline
VITE_MDBASE_ENV=production pnpm -C apps/writer dev --port 5438 # candidate

# From the candidate checkout
BASELINE=http://127.0.0.1:5437 BASE=http://127.0.0.1:5438 PROFILE_CHAPTERS=120 \
pnpm -C apps/writer exec node scripts/perf/interactive-profile.mjs > paired.jsonl
```

Each of seven rounds runs the two-chapter worked example and a large manuscript
on both revisions. Revision order reverses each round. Each sample opens a fresh
browser context, waits for the chapter count and bibliography revision, then
uses the visible Sources panel, outline search, editor and citation completion.
Typing must synchronously checkpoint the exact edit in local storage, and normal
SDK autosave must confirm the same body. Startup timings include navigation,
demo seeding and development module loading. The bibliography timing includes
full preview rendering. Action timings include Playwright input and waiting for
the result. Renderer CPU uses CDP thread ticks.
browser context. `indexReady` records collection index readiness, `hydration`
also waits for the expected chapter sessions, failures, library and outline
word count, and `previewWithBibliography` waits for a drawn revision with the
expected references. These timings start at navigation and include demo seeding
and development module loading. Action timings include Playwright input and
waiting for the visible result. The citation test accepts the matching
completion, checks the exact citation in the chapter, and undoes it before the
typing phase. Typing must synchronously checkpoint the exact edit in local storage,
and SDK autosave must confirm the same body. Renderer CPU uses CDP thread ticks.
For a separate diagnostic run, set `PROFILE_CPU=out/perf/cpu` to capture V8
profiles through hydration and during the switch pair.

The 120-chapter demo explicitly checks the pinned SDK's session limit. The
workspace must discover all 120 chapters and report 57 failed opens alongside
Expand Down
62 changes: 46 additions & 16 deletions apps/writer/scripts/perf/interactive-profile.mjs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import assert from "node:assert/strict";
import { mkdirSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { chromium } from "playwright";

const browser = await chromium.launch({ executablePath: process.env.CHROME });
Expand All @@ -9,43 +11,62 @@ assert.ok(chapters === 60 || chapters === 120);
const sizes = process.env.PROFILE_LARGE_ONLY === "1" ? [true] : [false, true];
const servers = [process.env.BASELINE, process.env.BASE].filter(Boolean);
assert.ok(servers.length);
const cpuProfiles = process.env.PROFILE_CPU;
if (cpuProfiles) mkdirSync(cpuProfiles, { recursive: true });

async function profile(base, large) {
async function profile(base, large, run) {
const page = await browser.newPage({ viewport: { width: 1500, height: 950 }, serviceWorkers: "block" });
const errors = [];
page.on("pageerror", e => errors.push(e.message));
const times = {};
const cdp = await page.context().newCDPSession(page);
const now = () => page.evaluate(() => performance.now());
const measure = async (label, action) => {
const start = await now();
await action();
times[label] = await now() - start;
};
const startProfile = async () => {
if (cpuProfiles) await cdp.send("Profiler.start");
};
const stopProfile = async label => {
if (!cpuProfiles) return;
const { profile } = await cdp.send("Profiler.stop");
writeFileSync(join(cpuProfiles, `${run}-${new URL(base).port}-${large ? "large" : "small"}-${label}.cpuprofile`), JSON.stringify(profile));
};
try {
if (cpuProfiles) await cdp.send("Profiler.enable");
const main = large ? "manuscripts/main.md" : "manuscripts/patient-observation.md";
const chapter = large ? "chapters/chapter-00000.md" : "chapters/reefs.md";
const other = large ? "chapters/chapter-00012.md" : "chapters/worms.md";
const key = large ? "source04999" : "darwinStructure42";
const params = new URLSearchParams({ demo: large ? "large" : "", manuscript: main });
if (large) { params.set("largeManuscript", String(chapters)); params.set("longChapter", "1"); }
await page.goto(new URL("?" + params, base).href);
await startProfile();
await page.goto(new URL("?" + params, base).href, { waitUntil: "commit" });
const timeOrigin = await page.evaluate(() => performance.timeOrigin);
times.indexReady = await page.waitForFunction(() => {
const s = window.writer?.workspace?.getSnapshot();
return s?.indexLoad.phase === "ready" && performance.now();
}, undefined, { timeout: 90_000 }).then(handle => handle.jsonValue());
const expectedChapters = large ? chapters : 2;
await page.waitForFunction(count => {
times.hydration = await page.waitForFunction(count => {
const w = window.writer?.workspace;
const s = w?.getSnapshot();
return s && w.readingOrder().length === count + 1
&& s.records.size === Math.min(count + 1, 64)
&& s.recordProblems.size === Math.max(count + 1 - 64, 0)
&& s.library.length === (count > 2 ? 5000 : 9)
&& document.querySelector(".outline-manuscript .record-words")?.textContent.match(/[1-9]/);
}, expectedChapters, { timeout: 90_000 });
times.hydration = await now();
await page.waitForFunction(large => {
&& document.querySelector(".outline-manuscript .record-words")?.textContent.match(/[1-9]/)
? performance.now() : false;
}, expectedChapters, { timeout: 90_000 }).then(handle => handle.jsonValue());
await stopProfile("hydration");
times.previewWithBibliography = await page.waitForFunction(large => {
const s = window.writer.workspace.getSnapshot();
return s.result?.references.length === (large ? 100 : 4) && s.artifactRevision > 0
&& Number(document.querySelector(".preview-pages")?.dataset.renderedRevision) === s.artifactRevision;
}, large, { timeout: 90_000 });
times.previewWithBibliography = await now();
&& Number(document.querySelector(".preview-pages")?.dataset.renderedRevision) === s.artifactRevision
? performance.now() : false;
}, large, { timeout: 90_000 }).then(handle => handle.jsonValue());
await measure("citedSourcesPanel", async () => {
await page.getByRole("tab", { name: /Sources/ }).click();
await page.getByRole("list", { name: "In this manuscript" }).locator(".source-row").first().waitFor();
Expand All @@ -67,20 +88,28 @@ async function profile(base, large) {
await page.locator(`.record-row[data-path="${path}"]`).click();
await page.getByRole("textbox", { name: `Markdown for ${path}`, exact: true }).waitFor();
};
await startProfile();
await measure("switchPair", async () => { await open(other); await open(chapter); });
await stopProfile("switch");
const editor = page.getByRole("textbox", { name: `Markdown for ${chapter}`, exact: true });
const editorBody = () => page.evaluate(path => window.writer.workspace.getSnapshot().records.get(path).snapshot.body, chapter);
const original = await editorBody();
await editor.focus();
await page.keyboard.press("ControlOrMeta+End");
await measure("autocomplete", async () => {
await page.keyboard.insertText(" [@" + key.slice(0, -1));
await page.keyboard.insertText(` [@${key.slice(0, -1)}]`);
await page.keyboard.press("ArrowLeft");
await page.keyboard.press("Control+Space");
await page.locator(".cm-tooltip-autocomplete li").first().waitFor();
await page.getByRole("option").filter({ hasText: key }).waitFor();
});
await measure("citationInsert", async () => {
await page.getByRole("option").filter({ hasText: key }).click();
assert.equal(await editorBody(), original + ` [@${key}]`);
});
await page.keyboard.press("Escape");
await page.keyboard.press("ControlOrMeta+z");
const original = await page.evaluate(path => window.writer.workspace.getSnapshot().records.get(path).snapshot.body, chapter);
if (await editorBody() !== original) await page.keyboard.press("ControlOrMeta+z");
assert.equal(await editorBody(), original);
const phrase = "The archives show that";
const cdp = await page.context().newCDPSession(page);
await cdp.send("Performance.enable", { timeDomain: "threadTicks" });
const cpu = async () => (await cdp.send("Performance.getMetrics")).metrics.find(m => m.name === "TaskDuration").value * 1000;
const cpuStart = await cpu();
Expand All @@ -100,6 +129,7 @@ async function profile(base, large) {
}, { chapter, expected: original + phrase });
});
assert.deepEqual(errors, []);
assert.equal(await page.evaluate(() => performance.timeOrigin), timeOrigin, "A reload resets the fixture and the timing origin");
return times;
} finally { await page.close(); }
}
Expand All @@ -108,7 +138,7 @@ try {
for (let run = 1; run <= samples; run++) {
for (const large of sizes) {
for (const base of run % 2 ? servers : [...servers].reverse()) {
console.log(JSON.stringify({ chromium: browser.version(), run, large, chapters: large ? chapters : 2, base, ms: await profile(base, large) }));
console.log(JSON.stringify({ chromium: browser.version(), run, large, chapters: large ? chapters : 2, base, ms: await profile(base, large, run) }));
}
}
}
Expand Down
22 changes: 22 additions & 0 deletions apps/writer/src/backend/native.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,28 @@ describe("native Writer domain backend", () => {
expect(get).not.toHaveBeenCalled(); expect(h.metadata).not.toHaveBeenCalled();
expect("writeFile" in h.backend).toBe(false);
});
it("loads every source when a larger source page must be retried at a smaller size", async () => {
const h = await fixture();
for (let index = 0; index < 500; index++) {
const key = `source-${index}`;
h.replica.seed({path: `sources/${key}.md`, types: ["native-source"], frontmatter: {
type: "native-source", heading: key, citation: new Map([["id", key], ["type", "article-journal"], ["title", key]]),
}});
}
const original = h.client.queryContract.bind(h.client);
const requests: (number | undefined)[] = [];
vi.spyOn(h.client, "queryContract").mockImplementation(async (contract, options) => {
if (contract.id === "dev.mdbase.reader.source") {
requests.push(options?.pageSize);
if (options?.pageSize === 1_000) throw new MdbaseError({code: "too_large", recovery: "none", message: "Contract projection exceeds its page budget.", reason: "contract_projection_budget"});
}
return original(contract, options);
});

const library = await h.backend.library();
expect(library.ok && new Set(library.value.map(entry => entry.key))).toEqual(new Set(["paper", ...Array.from({length: 500}, (_, index) => `source-${index}`)]));
expect(requests).toEqual([1_000, 500, 500]);
});
it("lists manuscripts by paging the manuscript contract alone without scanning the full collection", async () => {
const h = await fixture();
const second = h.replica.seed({path: "manuscripts/second.md", types: ["native-manuscript"], frontmatter: {type: "native-manuscript", meta: new Map([["heading", "Second"]]), layout: "thesis", style: "chicago-author-date"}, body: "Second\n"});
Expand Down
9 changes: 5 additions & 4 deletions apps/writer/src/backend/native.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,10 @@ interface DomainScope {
const RECONNECT_MIN_MS = 500, RECONNECT_MAX_MS = 30_000;
/** The producer's default contract page; a refused page is asked for again at half. */
const CONTRACT_PAGE_SIZE = 128;
/** Manuscripts carry small projections (title, template, csl), so 200 stays within
* the replica's 1 MiB projection budget; a refused page still halves like any domain. */
const MANUSCRIPT_PAGE_SIZE = 200;
/** The SDK clamps to the replica's supported limit. Larger library pages reduce
* repeated queries for sources and annotations. Manuscripts page separately
* to show progress on Home. All domains halve the size if it exceeds budget. */
const CONTRACT_PAGE_SIZES: Partial<Record<Domain, number>> = {manuscript: 200, source: 1_000, annotation: 1_000};
const COLLECTION_DOMAINS = ["source", "annotation", "comment", "person"] as const;
/** Pauses before each further account check after a transient failure. */
const PEOPLE_RETRY_MS = [250, 1_000, 3_000];
Expand Down Expand Up @@ -413,7 +414,7 @@ export class NativeWriterBackend implements WriterBackend {
// The producer refuses a page whose projection exceeds its fixed budget
// (`too_large`), and only it knows record sizes: ask again for fewer.
// A cursor is bound to its page size, so the domain restarts.
let pageSize = this.contractPageSizes.get(domain) ?? (domain === "manuscript" ? MANUSCRIPT_PAGE_SIZE : CONTRACT_PAGE_SIZE);
let pageSize = this.contractPageSizes.get(domain) ?? CONTRACT_PAGE_SIZES[domain] ?? CONTRACT_PAGE_SIZE;
for (;;) {
try {
progress?.onReset?.();
Expand Down
7 changes: 4 additions & 3 deletions apps/writer/src/ui/Home.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -102,9 +102,10 @@ it("orders by record modification time and reorders on collection notifications"

it("names an unavailable type plainly, once, without blocking the rest", async () => {
render(<Home backend={backend({recordPaths: [], filePaths: [], notePaths: [], unavailableTypes: [{name: "native-comment", message}]}, fail(message))} onOpen={vi.fn()} />);
expect(await screen.findByText(message)).toBeTruthy();
expect(screen.getAllByText(message)).toHaveLength(1);
expect(screen.queryByRole("button", {name: "Retry loading"})).toBeNull();
await waitFor(() => {
expect(screen.getAllByText(message)).toHaveLength(1);
expect(screen.queryByRole("button", {name: "Retry loading"})).toBeNull();
});
});

it("keeps an index refusal out of the banner text until its details are opened", async () => {
Expand Down
4 changes: 2 additions & 2 deletions apps/writer/src/ui/SourcesPanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ export interface SourcesRequest {
readonly nonce: number;
}

export function SourcesPanel({
export const SourcesPanel = memo(function SourcesPanel({
query,
setQuery,
library,
Expand Down Expand Up @@ -332,7 +332,7 @@ export function SourcesPanel({
)}
</section>
);
}
});

const SourceRow = memo(function SourceRow({
locators,
Expand Down
10 changes: 5 additions & 5 deletions apps/writer/src/ui/WorkspaceView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -490,11 +490,11 @@ export function WorkspaceView({ workspace, since, onClose }: { workspace: Manusc
setLayout((l) => (l.view === "preview" ? { ...l, view: "both" } : l));
setCursor({ record, offset });
revealRequest.current = { record, offset, ...options };
if (record === active && editor.current) editor.current.reveal(offset, options);
if (record === citationNavRef.current.active && editor.current) editor.current.reveal(offset, options);
else {
setActive(record);
}
}, [active, setLayout]);
}, [setLayout]);
const selectThread = useCallback((p: PlacedThread) => {
setActiveComment(p.thread.root.path);
if (p.at && p.at !== "whole") jump(p.record, p.at.from);
Expand Down Expand Up @@ -597,7 +597,6 @@ export function WorkspaceView({ workspace, since, onClose }: { workspace: Manusc

// Where a source is cited, named by section, for the Sources panel.
const sitesFor = useCallback((key: string): readonly CitationSite[] => {
const { order, snap } = citationNavRef.current;
const out: CitationSite[] = [];
const seen = new Set<string>();
for (const record of order) {
Expand All @@ -612,7 +611,7 @@ export function WorkspaceView({ workspace, since, onClose }: { workspace: Manusc
}
}
return out;
}, []);
}, [order, snap.records]);

// The next or previous citation of a source, in reading order from the cursor.
const stepCitation = useCallback((key: string, direction: 1 | -1) => {
Expand Down Expand Up @@ -904,6 +903,7 @@ export function WorkspaceView({ workspace, since, onClose }: { workspace: Manusc
return () => window.removeEventListener("keydown", listener, true);
}, []);

const retrySources = useCallback(() => { void workspace.retryMetadata(); }, [workspace]);
const sourcesPanel = (
<SourcesPanel
query={sourceQuery}
Expand All @@ -916,7 +916,7 @@ export function WorkspaceView({ workspace, since, onClose }: { workspace: Manusc
loading={snap.libraryLoad.phase === "loading"}
problem={snap.libraryLoad.problem}
details={snap.libraryLoad.details}
onRetry={() => void workspace.retryMetadata()}
onRetry={retrySources}
notSetUp={workspace.setupStatus?.sources === false}
annotationsNotSetUp={workspace.setupStatus?.annotations === false}
canInsert={Boolean(activeView && activeView.snapshot.state !== "deleted" && !snap.recoveredDrafts.has(active))}
Expand Down