Unverified Commit 433d9718 authored by vercel-fleet-prod[bot]'s avatar vercel-fleet-prod[bot] Committed by GitHub

Compare analyzer bundle snapshots

Co-authored-by: 's avatarWill Binns-Smith <755844+wbinnssmith@users.noreply.github.com>
parent 45a6001a
...@@ -5,7 +5,6 @@ import z from 'next/dist/compiled/zod' ...@@ -5,7 +5,6 @@ import z from 'next/dist/compiled/zod'
const DEFAULT_LIMIT = 50 const DEFAULT_LIMIT = 50
const MAX_LIMIT = 100 const MAX_LIMIT = 100
const MAX_CHUNKS = 100
const MAX_MODULE_CANDIDATES = 100 const MAX_MODULE_CANDIDATES = 100
const MAX_GRAPH_NODES = 10_000 const MAX_GRAPH_NODES = 10_000
const MAX_COUNTERFACTUAL_GRAPH_ITEMS = 50_000 const MAX_COUNTERFACTUAL_GRAPH_ITEMS = 50_000
...@@ -40,6 +39,21 @@ interface SourceRow { ...@@ -40,6 +39,21 @@ interface SourceRow {
chunkCount: number chunkCount: number
} }
interface DiffRow {
key: string
baselineRawSize: number
comparisonRawSize: number
baselineCompressedSize: number
comparisonCompressedSize: number
status: 'added' | 'removed' | 'changed' | 'identical'
delta: number
}
interface DiffInput extends Omit<DiffRow, 'status' | 'delta'> {
baselinePresent: boolean
comparisonPresent: boolean
}
interface OverviewArgs { interface OverviewArgs {
snapshot?: string snapshot?: string
environment?: 'total' | 'client' environment?: 'total' | 'client'
...@@ -117,6 +131,18 @@ interface ImportEdgeArgs extends InitialGraphArgs { ...@@ -117,6 +131,18 @@ interface ImportEdgeArgs extends InitialGraphArgs {
limit?: number limit?: number
} }
interface CompareArgs {
baselineSnapshot: string
comparisonSnapshot?: string
granularity?: 'route' | 'source' | 'package'
route?: string
environment?: Environment
metric?: Metric
search?: string
offset?: number
limit?: number
}
class DetailedToolError extends Error { class DetailedToolError extends Error {
constructor( constructor(
message: string, message: string,
...@@ -1059,6 +1085,71 @@ function selectModuleCandidate( ...@@ -1059,6 +1085,71 @@ function selectModuleCandidate(
return selected return selected
} }
function diffStatus(
inBaseline: boolean,
inComparison: boolean,
baselineRawSize: number,
comparisonRawSize: number
): DiffRow['status'] {
if (!inBaseline) return 'added'
if (!inComparison) return 'removed'
return baselineRawSize === comparisonRawSize ? 'identical' : 'changed'
}
function summarizeDiff(
rows: DiffInput[],
metric: Metric,
offset: number,
limit: number
) {
const completed: DiffRow[] = rows.map(
({ baselinePresent, comparisonPresent, ...row }) => {
const status = diffStatus(
baselinePresent,
comparisonPresent,
row.baselineRawSize,
row.comparisonRawSize
)
const delta =
metric === 'compressed'
? row.comparisonCompressedSize - row.baselineCompressedSize
: row.comparisonRawSize - row.baselineRawSize
return { ...row, status, delta }
}
)
completed.sort(
(a, b) => Math.abs(b.delta) - Math.abs(a.delta) || compareText(a.key, b.key)
)
const counts = { added: 0, removed: 0, changed: 0, identical: 0 }
let baselineRawSize = 0
let comparisonRawSize = 0
let baselineCompressedSize = 0
let comparisonCompressedSize = 0
for (const row of completed) {
counts[row.status]++
baselineRawSize += row.baselineRawSize
comparisonRawSize += row.comparisonRawSize
baselineCompressedSize += row.baselineCompressedSize
comparisonCompressedSize += row.comparisonCompressedSize
}
const paged = page(completed, offset, limit)
return {
counts,
totals: {
baselineRawSize,
comparisonRawSize,
baselineCompressedSize,
comparisonCompressedSize,
delta:
metric === 'compressed'
? comparisonCompressedSize - baselineCompressedSize
: comparisonRawSize - baselineRawSize,
},
rows: paged.values,
pagination: paged.pagination,
}
}
function provenance(metadata: SnapshotMetadata) { function provenance(metadata: SnapshotMetadata) {
return { return {
id: metadata.id, id: metadata.id,
...@@ -1809,6 +1900,122 @@ export function createAnalyzeQueryRegistry(repository: AnalyzeRepository) { ...@@ -1809,6 +1900,122 @@ export function createAnalyzeQueryRegistry(repository: AnalyzeRepository) {
}) })
) )
registerQuery(
'compare_bundles',
{
baselineSnapshot: z.string().max(100),
comparisonSnapshot: snapshotSchema,
granularity: z.enum(['route', 'source', 'package']).optional(),
route: z.string().max(4096).optional(),
environment: environmentSchema,
metric: metricSchema,
search: z.string().max(1000).optional(),
...pagingSchema,
},
safeQuery(async (args: CompareArgs) => {
const granularity = args.granularity ?? 'route'
const environment = args.environment ?? 'total'
const metric = args.metric ?? 'raw'
const baseline = await repository.getSnapshot(args.baselineSnapshot)
const comparison = await repository.getSnapshot(args.comparisonSnapshot)
const search = args.search?.toLocaleLowerCase()
let rows: DiffInput[]
if (granularity === 'route') {
if (environment === 'server') {
throw new Error(
'Route comparisons support total or client environments'
)
}
const keys = [...new Set([...baseline.routes, ...comparison.routes])]
.filter(
(route) => !search || route.toLocaleLowerCase().includes(search)
)
.sort()
rows = []
for (const route of keys) {
const baselineSizes = baseline.routes.includes(route)
? routeSizes(
await repository.loadRoute(args.baselineSnapshot, route),
environment
)
: { rawSize: 0, compressedSize: 0 }
const comparisonSizes = comparison.routes.includes(route)
? routeSizes(
await repository.loadRoute(args.comparisonSnapshot, route),
environment
)
: { rawSize: 0, compressedSize: 0 }
rows.push({
key: route,
baselinePresent: baseline.routes.includes(route),
comparisonPresent: comparison.routes.includes(route),
baselineRawSize: baselineSizes.rawSize,
comparisonRawSize: comparisonSizes.rawSize,
baselineCompressedSize: baselineSizes.compressedSize,
comparisonCompressedSize: comparisonSizes.compressedSize,
})
}
} else {
if (!args.route)
throw new Error('route is required for source/package comparisons')
const groupBy = granularity === 'package' ? 'package' : 'source'
const inBaseline = baseline.routes.includes(args.route)
const inComparison = comparison.routes.includes(args.route)
if (!inBaseline && !inComparison) {
throw new Error(`Unknown route: ${args.route}`)
}
const baselineRows = new Map(
(inBaseline
? collectSources(
await repository.loadRoute(args.baselineSnapshot, args.route),
{ search: args.search, environment, groupBy }
)
: []
).map((row) => [row.key, row])
)
const comparisonRows = new Map(
(inComparison
? collectSources(
await repository.loadRoute(args.comparisonSnapshot, args.route),
{ search: args.search, environment, groupBy }
)
: []
).map((row) => [row.key, row])
)
rows = [...new Set([...baselineRows.keys(), ...comparisonRows.keys()])]
.sort()
.map((key) => {
const a = baselineRows.get(key)
const b = comparisonRows.get(key)
return {
key,
baselinePresent: a !== undefined,
comparisonPresent: b !== undefined,
baselineRawSize: a?.rawSize ?? 0,
comparisonRawSize: b?.rawSize ?? 0,
baselineCompressedSize: a?.compressedSize ?? 0,
comparisonCompressedSize: b?.compressedSize ?? 0,
}
})
}
return {
granularity,
route: args.route,
environment,
metric,
baseline: provenance(baseline.metadata),
comparison: provenance(comparison.metadata),
...summarizeDiff(
rows,
metric,
args.offset ?? 0,
args.limit ?? DEFAULT_LIMIT
),
caveats: [COMPRESSED_CAVEAT],
}
})
)
return new AnalyzeQueryRegistry(queries) return new AnalyzeQueryRegistry(queries)
} }
......
...@@ -109,7 +109,8 @@ describe('next experimental-analyze', () => { ...@@ -109,7 +109,8 @@ describe('next experimental-analyze', () => {
'{"limit":1}', '{"limit":1}',
]) ])
expect(query.exitCode).toBe(0) expect(query.exitCode).toBe(0)
expect(JSON.parse(query.stdout)).toMatchObject({ const overview = JSON.parse(query.stdout)
expect(overview).toMatchObject({
pagination: { limit: 1, returned: 1 }, pagination: { limit: 1, returned: 1 },
routes: [{ route: expect.any(String), rawSize: expect.any(Number) }], routes: [{ route: expect.any(String), rawSize: expect.any(Number) }],
}) })
...@@ -210,6 +211,19 @@ describe('next experimental-analyze', () => { ...@@ -210,6 +211,19 @@ describe('next experimental-analyze', () => {
sccEvidence: 'producer-petgraph', sccEvidence: 'producer-petgraph',
}, },
}) })
const comparison = await next.runCommand([
'experimental-analyze',
'query',
'compare_bundles',
'--input',
JSON.stringify({ baselineSnapshot: overview.snapshot.id, limit: 1 }),
])
expect(comparison.exitCode).toBe(0)
expect(JSON.parse(comparison.stdout)).toMatchObject({
counts: { identical: expect.any(Number) },
rows: [{ status: 'identical', delta: 0 }],
})
}) })
}) })
}) })
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment