Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

compare-incremental-update.ts

413 lines11.3 KB

1/**
2 * Compares two JSON reports produced by `scripts/bench/incremental-update.ts`
3 * and prints a markdown summary of the differences.
4 *
5 * Usage:
6 * tsx scripts/bench/compare-incremental-update.ts \
7 * --base=.tmp/perf/base.json \
8 * --candidate=.tmp/perf/candidate.json \
9 * [--outFile=.tmp/perf/comparison.md] \
10 * [--threshold=0.20] \
11 * [--failOnRegression=false]
12 */
13import { readFileSync, writeFileSync } from 'node:fs'
14​
15type Summary = {
16 iterations: number
17 medianMs: number
18 p75Ms: number
19 p95Ms: number
20 minMs: number
21 maxMs: number
22 stddevMs: number
24​
25type FixtureScale = {
26 label: string
27 issueCount: number
28 userCount: number
29 commentCount: number
31​
32type RunResult = {
33 query: string
34 scenario: string
35 scale: FixtureScale
36 sourceIndexMode: string
37 mutationMode: string
38 coldHydrateMs: number
39 writeSummary: Summary
41​
42type Report = {
43 metadata: {
44 node: string
45 platform: string
46 cpu: string
47 gitSha: string
48 iterations: number
49 warmup: number
50 }
51 results: Array<RunResult>
53​
54type Comparison = {
55 key: string
56 query: string
57 scenario: string
58 scale: FixtureScale
59 sourceIndexMode: string
60 mutationMode: string
61 base: RunResult
62 candidate: RunResult
63 medianRatio: number
64 p95Ratio: number
66​
67// Relative change below which a result is considered noise, and an absolute
68// floor so sub-hundredth-of-a-ms jitter never counts as a change.
69const defaultThreshold = 0.2
70const absoluteFloorMs = 0.05
71​
72const args = parseArgs(process.argv.slice(2))
73​
74const base = readReport(args.base)
75const candidate = readReport(args.candidate)
76​
77const comparisons = compareReports(base, candidate)
78const markdown = formatMarkdown(base, candidate, comparisons, args.threshold)
79​
80if (args.outFile) {
81 writeFileSync(args.outFile, markdown)
83console.log(markdown)
84​
85const regressions = comparisons.filter((comparison) =>
86 isRegression(comparison, args.threshold),
88if (args.failOnRegression && regressions.length > 0) {
89 console.error(`\n${regressions.length} benchmark regression(s) found`)
90 process.exit(1)
92​
93function readReport(path: string): Report {
94 return JSON.parse(readFileSync(path, `utf8`)) as Report
96​
97function resultKey(result: RunResult): string {
98 return [
99 result.query,
100 result.scenario,
101 result.scale.label,
102 result.scale.issueCount,
103 result.scale.userCount,
104 result.scale.commentCount,
105 result.sourceIndexMode,
106 result.mutationMode,
107 ].join(`|`)
109​
110function compareReports(
111 baseReport: Report,
112 candidateReport: Report,
113): Array<Comparison> {
114 const baseByKey = new Map(
115 baseReport.results.map((result) => [resultKey(result), result]),
116 )
117​
118 const matched: Array<Comparison> = []
119 for (const result of candidateReport.results) {
120 const key = resultKey(result)
121 const baseResult = baseByKey.get(key)
122 if (!baseResult) continue
123​
124 matched.push({
125 key,
126 query: result.query,
127 scenario: result.scenario,
128 scale: result.scale,
129 sourceIndexMode: result.sourceIndexMode,
130 mutationMode: result.mutationMode,
131 base: baseResult,
132 candidate: result,
133 medianRatio: ratio(
134 baseResult.writeSummary.medianMs,
135 result.writeSummary.medianMs,
136 ),
137 p95Ratio: ratio(baseResult.writeSummary.p95Ms, result.writeSummary.p95Ms),
138 })
139 }
140​
141 return matched
143​
144function ratio(baseMs: number, candidateMs: number): number {
145 if (baseMs <= 0) return candidateMs <= 0 ? 1 : Number.POSITIVE_INFINITY
146 return candidateMs / baseMs
148​
149function isSignificant(
150 baseMs: number,
151 candidateMs: number,
152 threshold: number,
153): boolean {
154 const relativeChange = Math.abs(ratio(baseMs, candidateMs) - 1)
155 const absoluteChange = Math.abs(candidateMs - baseMs)
156 return relativeChange > threshold && absoluteChange > absoluteFloorMs
158​
159function isRegression(comparison: Comparison, threshold: number): boolean {
160 return (
161 comparison.medianRatio > 1 &&
162 isSignificant(
163 comparison.base.writeSummary.medianMs,
164 comparison.candidate.writeSummary.medianMs,
165 threshold,
166 )
167 )
169​
170function isImprovement(comparison: Comparison, threshold: number): boolean {
171 return (
172 comparison.medianRatio < 1 &&
173 isSignificant(
174 comparison.base.writeSummary.medianMs,
175 comparison.candidate.writeSummary.medianMs,
176 threshold,
177 )
178 )
180​
181function marker(comparison: Comparison, threshold: number): string {
182 if (isRegression(comparison, threshold)) return `🔴`
183 if (isImprovement(comparison, threshold)) return `🟢`
184 return ``
186​
187// Individual rows are noisy at sub-ms timings, but a consistent shift across
188// many rows is a real change even when no single row clears the per-row
189// significance bar — the geometric mean of the ratios captures that.
190function geomeanRatio(group: Array<Comparison>): number {
191 const finite = group
192 .map((comparison) => comparison.medianRatio)
193 .filter((value) => Number.isFinite(value) && value > 0)
194 if (finite.length === 0) return 1
195 return Math.exp(
196 finite.reduce((sum, value) => sum + Math.log(value), 0) / finite.length,
197 )
199​
200function formatRatio(value: number): string {
201 return `${value.toFixed(2)}×`
203​
204function formatMarkdown(
205 baseReport: Report,
206 candidateReport: Report,
207 allComparisons: Array<Comparison>,
208 threshold: number,
209): string {
210 const lines: Array<string> = []
211 const regressed = allComparisons.filter((comparison) =>
212 isRegression(comparison, threshold),
213 )
214 const improved = allComparisons.filter((comparison) =>
215 isImprovement(comparison, threshold),
216 )
217​
218 lines.push(`## Incremental update benchmark`)
219 lines.push(``)
220 lines.push(
221 `Comparing \`${candidateReport.metadata.gitSha}\` (this PR) against \`${baseReport.metadata.gitSha}\` (base). ` +
222 `Times are per-write medians over ${candidateReport.metadata.iterations} iterations ` +
223 `(${candidateReport.metadata.warmup} warmup writes).`,
224 )
225 lines.push(``)
226​
227 if (regressed.length === 0 && improved.length === 0) {
228 lines.push(
229 `**No significant changes** (threshold: ±${Math.round(threshold * 100)}% and >${absoluteFloorMs}ms).`,
230 )
231 } else {
232 lines.push(
233 `**${regressed.length} regression(s), ${improved.length} improvement(s)** ` +
234 `(threshold: ±${Math.round(threshold * 100)}% and >${absoluteFloorMs}ms).`,
235 )
236 }
237 lines.push(``)
238 lines.push(
239 `Overall median write time vs base: **${formatRatio(
240 geomeanRatio(allComparisons),
241 )}** (geometric mean of per-case ratios; lower is faster).`,
242 )
243 lines.push(``)
244​
245 const byQuery = new Map<string, Array<Comparison>>()
246 for (const comparison of allComparisons) {
247 const group = byQuery.get(comparison.query) ?? []
248 group.push(comparison)
249 byQuery.set(comparison.query, group)
250 }
251​
252 lines.push(`| Query | Δ median (geomean) | Best case | Worst case | Flags |`)
253 lines.push(`| --- | ---: | ---: | ---: | :-- |`)
254 for (const [query, group] of byQuery) {
255 const ratios = group
256 .map((comparison) => comparison.medianRatio)
257 .filter((value) => Number.isFinite(value))
258 const best = Math.min(...ratios)
259 const worst = Math.max(...ratios)
260 const redCount = group.filter((comparison) =>
261 isRegression(comparison, threshold),
262 ).length
263 const greenCount = group.filter((comparison) =>
264 isImprovement(comparison, threshold),
265 ).length
266 const flags =
267 [
268 redCount > 0 ? `${redCount} 🔴` : ``,
269 greenCount > 0 ? `${greenCount} 🟢` : ``,
270 ]
271 .filter(Boolean)
272 .join(` `) || `—`
273 lines.push(
274 `| ${query} | ${formatDelta(geomeanRatio(group))} | ${formatDelta(
275 best,
276 )} | ${formatDelta(worst)} | ${flags} |`,
277 )
278 }
279 lines.push(``)
280 lines.push(
281 `Each row aggregates the ${allComparisons.length / byQuery.size || 0} ` +
282 `scale/index/write-mode configurations of that query; per-configuration ` +
283 `tables below.`,
284 )
285 lines.push(``)
286​
287 const groups = new Map<string, Array<Comparison>>()
288 for (const comparison of allComparisons) {
289 const groupKey = `${formatScale(comparison.scale)} | source indexes: ${
290 comparison.sourceIndexMode
291 } | ${comparison.mutationMode} writes`
292 const group = groups.get(groupKey) ?? []
293 group.push(comparison)
294 groups.set(groupKey, group)
295 }
296​
297 for (const [groupKey, group] of groups) {
298 lines.push(`<details>`)
299 const changed = group.filter(
300 (comparison) => marker(comparison, threshold) !== ``,
301 ).length
302 const changedSuffix = changed > 0 ? `, ${changed} change(s)` : ``
303 lines.push(
304 `<summary><b>${groupKey}</b> — geomean ${formatRatio(
305 geomeanRatio(group),
306 )}${changedSuffix}</summary>`,
307 )
308 lines.push(``)
309 lines.push(
310 `| Query | Base median | PR median | Δ median | Base p95 | PR p95 | Δ p95 | |`,
311 )
312 lines.push(`| --- | ---: | ---: | ---: | ---: | ---: | ---: | --- |`)
313 for (const comparison of group) {
314 lines.push(
315 `| ${comparison.query} | ${formatMs(
316 comparison.base.writeSummary.medianMs,
317 )} | ${formatMs(comparison.candidate.writeSummary.medianMs)} | ${formatDelta(
318 comparison.medianRatio,
319 )} | ${formatMs(comparison.base.writeSummary.p95Ms)} | ${formatMs(
320 comparison.candidate.writeSummary.p95Ms,
321 )} | ${formatDelta(comparison.p95Ratio)} | ${marker(
322 comparison,
323 threshold,
324 )} |`,
325 )
326 }
327 lines.push(``)
328 lines.push(`</details>`)
329 lines.push(``)
330 }
331​
332 lines.push(
333 `<sub>Runner: node ${candidate.metadata.node}, ${candidate.metadata.platform}, ${candidate.metadata.cpu}. ` +
334 `Timings on shared CI runners are noisy; treat small deltas as indicative only.</sub>`,
335 )
336​
337 return lines.join(`\n`)
339​
340function formatScale(scale: FixtureScale): string {
341 if (
342 scale.issueCount === scale.userCount &&
343 scale.userCount === scale.commentCount
344 ) {
345 return `${scale.issueCount.toLocaleString(`en-US`)} rows/collection`
346 }
347 return `issues:${scale.issueCount} users:${scale.userCount} comments:${scale.commentCount}`
349​
350function formatMs(value: number): string {
351 return `${value.toFixed(3)}ms`
353​
354function formatDelta(value: number): string {
355 if (!Number.isFinite(value)) return `n/a`
356 const percent = (value - 1) * 100
357 const sign = percent > 0 ? `+` : ``
358 return `${sign}${percent.toFixed(1)}%`
360​
361function parseArgs(argv: Array<string>): {
362 base: string
363 candidate: string
364 outFile?: string
365 threshold: number
366 failOnRegression: boolean
367} {
368 let basePath: string | undefined
369 let candidatePath: string | undefined
370 let outFile: string | undefined
371 let threshold = defaultThreshold
372 let failOnRegression = false
373​
374 for (const arg of argv) {
375 const [name, value] = arg.replace(/^--/, ``).split(`=`)
376 if (!name || value === undefined) continue
377​
378 switch (name) {
379 case `base`:
380 basePath = value
381 break
382 case `candidate`:
383 candidatePath = value
384 break
385 case `outFile`:
386 outFile = value
387 break
388 case `threshold`: {
389 const parsed = Number(value)
390 if (!Number.isFinite(parsed) || parsed <= 0) {
391 throw new Error(`--threshold must be a positive number`)
392 }
393 threshold = parsed
394 break
395 }
396 case `failOnRegression`:
397 failOnRegression = value === `true`
398 break
399 }
400 }
401​
402 if (!basePath || !candidatePath) {
403 throw new Error(`--base and --candidate report paths are required`)
404 }
405​
406 return {
407 base: basePath,
408 candidate: candidatePath,
409 outFile,
410 threshold,
411 failOnRegression,
412 }