An open source design system that's fully customizable and agent ready
TypeScript
chore(sandbox): DiffViewer perf presets cover typical to upper-bound change sets (#9435)
Cindy Zhang6c432dbac255
diff --git a/apps/sandbox/src/app/(fullscreen)/pages/diffviewer-perf/benchmark.test.ts b/apps/sandbox/src/app/(fullscreen)/pages/diffviewer-perf/benchmark.test.tsindex feafa0a252..bee258494c 100644--- a/apps/sandbox/src/app/(fullscreen)/pages/diffviewer-perf/benchmark.test.ts+++ b/apps/sandbox/src/app/(fullscreen)/pages/diffviewer-perf/benchmark.test.ts@@ -1,32 +1,62 @@// Copyright (c) Meta Platforms, Inc. and affiliates.import {describe, expect, it} from 'vitest';+import {createDiffFile} from '../../../../../../../packages/lab/src/DiffViewer/createDiffFile';import {countLines,createMultiFileWorkload,createSingleFileWorkload,formatMegabytes,MULTI_FILE_WORKLOADS,+ SINGLE_FILE_LINES,+ type DiffBenchmarkWorkload,} from './benchmark';+/** Added plus removed lines in the diff DiffViewer renders, per file. */+function diffChangedLines(workload: DiffBenchmarkWorkload): number[] {+ return workload.files.map(file => {+ const diff = createDiffFile({+ oldValue: file.oldContents ?? '',+ newValue: file.newContents ?? '',+ });+ let changed = 0;+ for (const hunk of diff.hunks) {+ for (const line of hunk.lines) {+ if (line.kind !== 'context') {+ changed++;+ }+ }+ }+ return changed;+ });+}+describe('DiffViewer performance workloads', () => {it('builds the same multi-file workload on every call', () => {- const first = createMultiFileWorkload(50, 10_000);- const second = createMultiFileWorkload(50, 10_000);+ const first = createMultiFileWorkload(50, 4000);+ const second = createMultiFileWorkload(50, 4000);expect(second).toEqual(first);expect(first.files).toHaveLength(50);expect(new Set(first.files.map(file => file.path)).size).toBe(50);});it.each(MULTI_FILE_WORKLOADS)(- 'hits about $totalLines lines across $files files, with a realistic mix',- ({files, totalLines}) => {- const workload = createMultiFileWorkload(files, totalLines);+ '$label changes about $changedLines lines across $files files',+ ({files, changedLines}) => {+ const workload = createMultiFileWorkload(files, changedLines);expect(workload.files).toHaveLength(files);expect(workload.totalLines).toBe(countLines(workload.files));expect(- Math.abs(workload.totalLines - totalLines) / totalLines,- ).toBeLessThan(0.05);+ Math.abs(workload.changedLines - changedLines) / changedLines,+ ).toBeLessThan(0.02);+ expect(workload.largestFileChangedLines).toBeLessThan(changedLines);+ },+ );++ it.each(MULTI_FILE_WORKLOADS.filter(({files}) => files >= 50))(+ '$label has a realistic mix of file sizes and changes',+ ({files, changedLines}) => {+ const workload = createMultiFileWorkload(files, changedLines);const sizes = workload.files.map(file =>@@ -34,12 +64,10 @@ describe('DiffViewer performance workloads', () => {).sort((a, b) => a - b);// Mostly small files, with a few far larger than the median.- expect(sizes[Math.floor(files / 2)]).toBeLessThan(400);+ expect(sizes[Math.floor(files / 2)]).toBeLessThan(500);expect(sizes[files - 1]).toBeGreaterThan(sizes[Math.floor(files / 2)] * 10,);- expect(workload.files.some(file => file.oldContents == null)).toBe(true);- expect(workload.files.some(file => file.newContents == null)).toBe(true);expect(workload.files.filter(file =>@@ -51,16 +79,49 @@ describe('DiffViewer performance workloads', () => {},);+ it.each(MULTI_FILE_WORKLOADS.filter(({files}) => files >= 200))(+ '$label adds and deletes some files',+ ({files, changedLines}) => {+ const workload = createMultiFileWorkload(files, changedLines);+ expect(workload.files.some(file => file.oldContents == null)).toBe(true);+ expect(workload.files.some(file => file.newContents == null)).toBe(true);+ },+ );++ it.each([+ ...MULTI_FILE_WORKLOADS.map(({label, files, changedLines}) => ({+ label,+ workload: () => createMultiFileWorkload(files, changedLines),+ })),+ ...SINGLE_FILE_LINES.flatMap(lines =>+ (['sparse', 'rewrite'] as const).map(change => ({+ label: `${lines} lines, ${change}`,+ workload: () => createSingleFileWorkload(lines, change),+ })),+ ),+ ])(+ '$label reports the changed lines its diff renders',+ ({workload: build}) => {+ const workload = build();+ const perFile = diffChangedLines(workload);+ expect(perFile.reduce((total, lines) => total + lines, 0)).toBe(+ workload.changedLines,+ );+ expect(Math.max(...perFile)).toBe(workload.largestFileChangedLines);+ },+ );+it('builds one file of the requested size, sparse or rewritten', () => {const sparse = createSingleFileWorkload(1000, 'sparse');const rewrite = createSingleFileWorkload(1000, 'rewrite');expect(sparse.files).toHaveLength(1);expect(sparse.files[0].oldContents?.split('\n')).toHaveLength(1000);const oldLines = new Set(rewrite.files[0].oldContents?.split('\n'));- const sharedNonBlank = (rewrite.files[0].newContents ?? '')+ const shared = (rewrite.files[0].newContents ?? '').split('\n')- .filter(line => line.trim() !== '' && oldLines.has(line));- expect(sharedNonBlank).toEqual([]);+ .filter(line => oldLines.has(line));+ expect(shared).toEqual([]);+ expect(rewrite.changedLines).toBe(2000);const sparseOld = new Set(sparse.files[0].oldContents?.split('\n'));const kept = (sparse.files[0].newContents ?? '').split('\n')diff --git a/apps/sandbox/src/app/(fullscreen)/pages/diffviewer-perf/benchmark.ts b/apps/sandbox/src/app/(fullscreen)/pages/diffviewer-perf/benchmark.tsindex 0828ef8e7a..7c68dd21fd 100644--- a/apps/sandbox/src/app/(fullscreen)/pages/diffviewer-perf/benchmark.ts+++ b/apps/sandbox/src/app/(fullscreen)/pages/diffviewer-perf/benchmark.ts@@ -2,9 +2,10 @@/*** @file benchmark.ts- * @input A workload id: a multi-file change set or one file of a given size- * @output Deterministic old/new file contents, their totals, and small- * formatting helpers for the DiffViewer performance sandbox+ * @input A workload: a multi-file preset (file count and changed lines) or+ * one file of a given size+ * @output Deterministic old/new file contents, their line and changed-line+ * totals, and small formatting helpers for the DiffViewer performance sandbox* @position Pure support utilities for the DiffViewer performance sandbox;* no React and no DOM, so any harness can render the same fixtures*@@ -13,6 +14,9 @@* edits, a handful of new and deleted files, and a few full rewrites. Every* value comes from a seeded generator, so a workload is byte-identical on* every run and in every harness.+ *+ * A changed line is an added or a removed line, the way a diff summary counts+ * them; a replaced line counts once on each side.*/export interface DiffBenchmarkFile {@@ -29,16 +33,26 @@ export interface DiffBenchmarkWorkload {readonly files: ReadonlyArray<DiffBenchmarkFile>;/** Lines across every file's newer side (the older side for a deleted file). */readonly totalLines: number;+ /** Added plus removed lines across every file. */+ readonly changedLines: number;+ /** Added plus removed lines in the file that changes the most. */+ readonly largestFileChangedLines: number;}-/** Multi-file workloads: file count and the total lines they target. */+/**+ * Multi-file presets by file count and changed lines, from a typical change+ * set to the upper bound: large diffs up to 1,000 files and 100,000 changed+ * lines.+ */export const MULTI_FILE_WORKLOADS = [- {files: 50, totalLines: 10_000},- {files: 200, totalLines: 50_000},- {files: 500, totalLines: 100_000},- {files: 1000, totalLines: 150_000},+ {id: 'typical', label: 'Typical', files: 5, changedLines: 200},+ {id: 'large', label: 'Large', files: 50, changedLines: 4000},+ {id: 'very-large', label: 'Very large', files: 200, changedLines: 20_000},+ {id: 'upper-bound', label: 'Upper bound', files: 1000, changedLines: 100_000},] as const;+export type MultiFileWorkloadId = (typeof MULTI_FILE_WORKLOADS)[number]['id'];+/** Single-file workloads: line counts, each with sparse edits or a rewrite. */export const SINGLE_FILE_LINES = [100, 1000, 5000, 20_000] as const;@@ -62,11 +76,15 @@ function between(random: () => number, min: number, max: number): number {/*** One line of TypeScript-like source, varied by its file and position. A- * variant changes every non-blank line, so two variants share no code.+ * variant changes every line, blank ones included, so two variants share no+ * line and a rewrite changes each line on both sides.*/function sourceLine(fileIndex: number, line: number, variant = ''): string {const base = baseSourceLine(fileIndex, line, variant);- return variant === '' || base === '' ? base : `${base} // ${variant}`;+ if (variant === '') {+ return base;+ }+ return base === '' ? `// ${variant}` : `${base} // ${variant}`;}function baseSourceLine(@@ -103,22 +121,53 @@ function baseSourceLine(}}+/**+ * A file never ends on a blank line: a diff reads a last blank line as the+ * final newline and does not count it, so the changed-line totals would drift.+ */function fileLines(fileIndex: number, count: number, variant = ''): string[] {- return Array.from({length: count}, (_, line) =>+ const lines = Array.from({length: count}, (_, line) =>sourceLine(fileIndex, line, variant),);+ if (lines.at(-1) === '') {+ lines[lines.length - 1] = `// End of file ${fileIndex}`;+ }+ return lines;+}++interface EditedLines {+ readonly lines: string[];+ /** Added plus removed lines: two per replaced line, one per inserted line. */+ readonly changedLines: number;}+/**+ * `createDiffFile` shows a file with more changed lines than this as one+ * replaced block, so a sparse-edited file must not go above it.+ */+const DIFF_EDIT_LIMIT = 2000;+/** A site replaces up to three lines and inserts up to two more. */+const MAX_SITE_CHANGED_LINES = 8;+const MAX_SPARSE_SITES = Math.floor(DIFF_EDIT_LIMIT / MAX_SITE_CHANGED_LINES);+/*** Edit roughly one site per `spacing` lines: each site replaces one to three- * lines and sometimes inserts one or two more.+ * lines and sometimes inserts one or two more. A long file gets a wider+ * spacing, so it never reaches the diff's edit limit.*/function applySparseEdits(lines: ReadonlyArray<string>,random: () => number,- spacing: number,-): string[] {+ minSpacing: number,+): EditedLines {+ // Sites are at least half the spacing apart, so the file holds at most+ // MAX_SPARSE_SITES sites.+ const spacing = Math.max(+ minSpacing,+ 2 * Math.ceil(lines.length / MAX_SPARSE_SITES),+ );const next: string[] = [];+ let changedLines = 0;let line = 0;let isFirst = true;while (line < lines.length) {@@ -134,13 +183,15 @@ function applySparseEdits(const replaced = between(random, 1, 3);for (let i = 0; i < replaced && line < lines.length; i++, line++) {next.push(`${lines[line]} // updated`);+ changedLines += 2;}const inserted = between(random, 0, 2);for (let i = 0; i < inserted; i++) {next.push(` void track('edit-${line}-${i}');`);+ changedLines += 1;}}- return next;+ return {lines: next, changedLines};}const DIRECTORIES = [@@ -177,46 +228,109 @@ function fileSizes(return raw.map(size => Math.max(12, Math.round(size * scale)));}+interface ChangeSet {+ readonly files: DiffBenchmarkFile[];+ readonly changedLines: number;+ readonly largestFileChangedLines: number;+}+/**- * A change set of `files` files whose sides total about `totalLines` lines.* About 5% of the files are new, 2% deleted and 2% rewritten in full; the* rest carry sparse edits.*/-export function createMultiFileWorkload(+function createChangeSet(+ seed: number,files: number,totalLines: number,-): DiffBenchmarkWorkload {- const random = createRandom(files * 7919 + totalLines);+): ChangeSet {+ const random = createRandom(seed);const sizes = fileSizes(random, files, totalLines);- const result: DiffBenchmarkFile[] = sizes.map((size, index) => {+ const kinds = sizes.map(() => random());+ let changedLines = 0;+ let largestFileChangedLines = 0;+ const result = sizes.map((size, index): DiffBenchmarkFile => {const directory = DIRECTORIES[index % DIRECTORIES.length];const path = `${directory}/module_${String(index).padStart(4, '0')}.ts`;const original = fileLines(index, size);- const kind = random();+ const kind = kinds[index];+ let file: DiffBenchmarkFile;+ let changed: number;if (kind < 0.05) {- return {path, oldContents: null, newContents: original.join('\n')};- }- if (kind < 0.07) {- return {path, oldContents: original.join('\n'), newContents: null};- }- if (kind < 0.09) {- return {+ file = {path, oldContents: null, newContents: original.join('\n')};+ changed = size;+ } else if (kind < 0.07) {+ file = {path, oldContents: original.join('\n'), newContents: null};+ changed = size;+ } else if (kind < 0.09) {+ file = {path,oldContents: original.join('\n'),newContents: fileLines(index, size, 'v2').join('\n'),};+ changed = 2 * size;+ } else {+ // Each file draws its own edits, so a file's size never shifts the+ // edits of the files after it.+ const edited = applySparseEdits(+ original,+ createRandom(seed + index + 1),+ 40,+ );+ file = {+ path,+ oldContents: original.join('\n'),+ newContents: edited.lines.join('\n'),+ };+ changed = edited.changedLines;}- return {- path,- oldContents: original.join('\n'),- newContents: applySparseEdits(original, random, 40).join('\n'),- };+ changedLines += changed;+ largestFileChangedLines = Math.max(largestFileChangedLines, changed);+ return file;});+ return {files: result, changedLines, largestFileChangedLines};+}++/**+ * First guess at file lines per changed line, from the mix of sparse edits,+ * new, deleted and rewritten files; later passes correct it.+ */+const FILE_LINES_PER_CHANGED_LINE = 5;+/** Size passes stop once the change set is this close to its target. */+const CHANGED_LINES_TOLERANCE = 0.01;+const MAX_SIZE_PASSES = 5;++/**+ * A change set of `files` files that changes about `changedLines` lines. Each+ * pass measures how many lines the mix changes and scales the file sizes+ * toward the target; every pass draws the same file kinds. Long files get+ * sparser edits, so the scale is not linear and can take a few passes.+ */+export function createMultiFileWorkload(+ files: number,+ changedLines: number,+): DiffBenchmarkWorkload {+ const seed = files * 7919 + changedLines;+ let totalLines = changedLines * FILE_LINES_PER_CHANGED_LINE;+ let changeSet = createChangeSet(seed, files, totalLines);+ for (+ let pass = 1;+ pass < MAX_SIZE_PASSES &&+ Math.abs(changeSet.changedLines - changedLines) >+ changedLines * CHANGED_LINES_TOLERANCE;+ pass+++ ) {+ totalLines = Math.round(+ (totalLines * changedLines) / changeSet.changedLines,+ );+ changeSet = createChangeSet(seed, files, totalLines);+ }return {- id: `files-${files}`,+ id: `files-${files}-changed-${changedLines}`,label: `${files.toLocaleString()} files`,- files: result,- totalLines: countLines(result),+ files: changeSet.files,+ totalLines: countLines(changeSet.files),+ changedLines: changeSet.changedLines,+ largestFileChangedLines: changeSet.largestFileChangedLines,};}@@ -229,13 +343,13 @@ export function createSingleFileWorkload(const original = fileLines(0, lines);const next =change === 'rewrite'- ? fileLines(0, lines, 'v2')+ ? {lines: fileLines(0, lines, 'v2'), changedLines: 2 * lines}: applySparseEdits(original, random, 40);const files = [{path: 'src/large_module.ts',oldContents: original.join('\n'),- newContents: next.join('\n'),+ newContents: next.lines.join('\n'),},];return {@@ -243,6 +357,8 @@ export function createSingleFileWorkload(label: `${lines.toLocaleString()} lines, ${change === 'rewrite' ? 'full rewrite' : 'sparse edits'}`,files,totalLines: countLines(files),+ changedLines: next.changedLines,+ largestFileChangedLines: next.changedLines,};}diff --git a/apps/sandbox/src/app/(fullscreen)/pages/diffviewer-perf/page.tsx b/apps/sandbox/src/app/(fullscreen)/pages/diffviewer-perf/page.tsxindex 5eed08165e..3296b3a274 100644--- a/apps/sandbox/src/app/(fullscreen)/pages/diffviewer-perf/page.tsx+++ b/apps/sandbox/src/app/(fullscreen)/pages/diffviewer-perf/page.tsx@@ -4,8 +4,8 @@/*** @file page.tsx- * @input Deterministic multi-file and single-file diff workloads, view mode,- * and syntax highlighting on or off+ * @input Deterministic diff workloads (multi-file presets from typical to the+ * upper bound, or one file), view mode, and syntax highlighting on or off* @output Interactive DiffViewer benchmark: diff-model time, first file on* screen, total render, long tasks, DOM size, heap, scroll frames, and the* cost of collapse, expand, and view switches; files mount on screen by@@ -54,6 +54,7 @@ import {MULTI_FILE_WORKLOADS,SINGLE_FILE_LINES,type DiffBenchmarkFile,+ type MultiFileWorkloadId,type SingleFileChange,} from './benchmark';@@ -69,6 +70,8 @@ type Mount = 'visible' | 'all';interface RunSubject {label: string;totalLines: number;+ changedLines: number;+ largestFileChangedLines: number;viewMode: DiffViewerViewMode;syntax: Syntax;mount: Mount;@@ -333,7 +336,7 @@ function Metric({label, value}: {label: string; value: string}) {export default function DiffViewerPerfPage() {const [scenario, setScenario] = useState<Scenario>('multi');- const [fileCount, setFileCount] = useState('200');+ const [preset, setPreset] = useState<MultiFileWorkloadId>('large');const [lineCount, setLineCount] = useState('5000');const [change, setChange] = useState<SingleFileChange>('sparse');const [viewMode, setViewMode] = useState<DiffViewerViewMode>('unified');@@ -352,12 +355,16 @@ export default function DiffViewerPerfPage() {const workload = useMemo(() => {if (scenario === 'multi') {const entry =- MULTI_FILE_WORKLOADS.find(w => String(w.files) === fileCount) ??+ MULTI_FILE_WORKLOADS.find(w => w.id === preset) ??MULTI_FILE_WORKLOADS[0];- return createMultiFileWorkload(entry.files, entry.totalLines);+ const generated = createMultiFileWorkload(+ entry.files,+ entry.changedLines,+ );+ return {...generated, label: `${entry.label}, ${generated.label}`};}return createSingleFileWorkload(Number(lineCount), change);- }, [scenario, fileCount, lineCount, change]);+ }, [scenario, preset, lineCount, change]);const language = syntax === 'on' ? undefined : 'plaintext';const diffLines = useMemo(() => diffLineCount(files), [files]);@@ -366,6 +373,8 @@ export default function DiffViewerPerfPage() {const subject: RunSubject = {label: workload.label,totalLines: workload.totalLines,+ changedLines: workload.changedLines,+ largestFileChangedLines: workload.largestFileChangedLines,viewMode,syntax,mount,@@ -567,6 +576,8 @@ export default function DiffViewerPerfPage() {const shown: RunSubject = run.subject ?? {label: workload.label,totalLines: workload.totalLines,+ changedLines: workload.changedLines,+ largestFileChangedLines: workload.largestFileChangedLines,viewMode,syntax,mount,@@ -597,16 +608,16 @@ export default function DiffViewerPerfPage() {</SegmentedControl>{scenario === 'multi' ? (<SegmentedControl- label="Files"- value={fileCount}- onChange={setFileCount}+ label="Size"+ value={preset}+ onChange={value => setPreset(value as MultiFileWorkloadId)}isDisabled={controlsDisabled}size="sm">{MULTI_FILE_WORKLOADS.map(entry => (<SegmentedControlItem- key={entry.files}- value={String(entry.files)}- label={entry.files.toLocaleString()}+ key={entry.id}+ value={entry.id}+ label={entry.label}/>))}</SegmentedControl>@@ -696,6 +707,12 @@ export default function DiffViewerPerfPage() {<Heading level={3}>Run metrics</Heading><HStack gap={2} wrap="wrap"><Badge label={shown.label} />+ <Badge+ label={`${shown.changedLines.toLocaleString()} changed lines`}+ />+ <Badge+ label={`largest file ${shown.largestFileChangedLines.toLocaleString()} changed`}+ /><Badgelabel={`${shown.totalLines.toLocaleString()} file lines`}/>