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

test: record test timings per CI variant

Co-authored-by: 's avatarTobias Koppers <1365881+sokra@users.noreply.github.com>
parent 43cb38c7
......@@ -197,6 +197,9 @@ const DEFAULT_NUM_RETRIES = 2
const DEFAULT_CONCURRENCY = 2
const RESULTS_EXT = `.results.json`
const isTestJob = !!process.env.NEXT_TEST_JOB
// Legacy flat `{ [file]: seconds }` map shared by every CI variant. Still read
// as a fallback, but no longer written: CI runs on older versions of this
// script keep reading and writing it.
const KV_TIMINGS_KEY = 'test-timings'
const kvClient =
......@@ -240,6 +243,248 @@ async function retryKVOperation(operation, operationName, maxRetries = 3) {
)
}
// --- Per-variant test timings ---
// The same test file can take seconds in one CI variant and minutes in
// another (e.g. dev vs. turbopack production), so timings are recorded per
// variant. Each variant is its own Redis hash (`test-timings-v2:<variant>`,
// field = test file, value = seconds), so parallel shards update individual
// fields atomically instead of overwriting each other's read-modify-write.
// `test-timings-v2:variants` lists the variants that have been recorded.
const KV_TIMINGS_V2_PREFIX = 'test-timings-v2:'
const KV_TIMINGS_V2_VARIANTS_KEY = `${KV_TIMINGS_V2_PREFIX}variants`
/**
* Identifies the CI variant a run's timings belong to, from the env vars that
* distinguish the CI jobs using `--timings` (see `build_and_test.yml` and
* `test_e2e_deploy_release.yml`): mode, bundler, cache components, React
* version and adapter. Flags set identically on every timing job (e.g. strict
* route types) are deliberately not part of the key.
*
* @param {Record<string, string | undefined>} env
* @returns {string} e.g. `start|turbopack|cache-components`
*/
function getTimingsVariant(env) {
const mode = env.NEXT_TEST_MODE || 'none'
const bundler =
env.NEXT_TEST_USE_RSPACK === '1' || env.NEXT_RSPACK
? 'rspack'
: env.IS_TURBOPACK_TEST
? 'turbopack'
: 'webpack'
const parts = [mode, bundler]
if (env.__NEXT_CACHE_COMPONENTS === 'true') parts.push('cache-components')
const reactVersion = env.NEXT_TEST_REACT_VERSION?.trim()
if (reactVersion) parts.push(`react-${reactVersion}`)
if (env.NEXT_ENABLE_ADAPTER === '1') parts.push('adapter')
return parts.join('|')
}
/** @param {unknown} value */
function isValidTiming(value) {
return typeof value === 'number' && Number.isFinite(value) && value > 0
}
/**
* The longest recorded duration of each test file across all variants. Used
* as a conservative fallback for variants that haven't recorded a file yet.
*
* @param {Record<string, Record<string, unknown>>} variants
* @returns {Record<string, number>}
*/
function computeMaxTimings(variants) {
/** @type {Record<string, number>} */
const max = {}
for (const variantTimings of Object.values(variants)) {
for (const [file, seconds] of Object.entries(variantTimings)) {
if (isValidTiming(seconds)) {
max[file] = Math.max(max[file] ?? 0, /** @type {number} */ (seconds))
}
}
}
return max
}
/**
* @typedef {{
* variants: Record<string, Record<string, unknown>>,
* max: Record<string, unknown>,
* legacy: Record<string, unknown>,
* }} TestTimings
*/
/**
* Normalizes loaded timings data. Accepts the versioned format written by
* `fetchTestTimings`, as well as a legacy flat `{ [file]: seconds }` map (or
* the `{}` the workflow writes when no timings could be fetched).
*
* @param {unknown} data
* @returns {TestTimings | null}
*/
function normalizeTimings(data) {
if (!data || typeof data !== 'object' || Array.isArray(data)) {
return null
}
const record = /** @type {Record<string, any>} */ (data)
if (record.version !== 2) {
return { variants: {}, max: {}, legacy: record }
}
/** @type {TestTimings['variants']} */
const variants = {}
for (const [variant, variantTimings] of Object.entries(
record.variants || {}
)) {
if (variantTimings && typeof variantTimings === 'object') {
variants[variant] = variantTimings
}
}
return {
variants,
max:
record.max && typeof record.max === 'object'
? record.max
: computeMaxTimings(variants),
legacy:
record.legacy && typeof record.legacy === 'object' ? record.legacy : {},
}
}
/**
* Resolves the recorded duration of a test file for the given variant: the
* variant's own timing, else the maximum across all variants, else the legacy
* shared timing (only relevant until any variant has recorded the file).
*
* @param {TestTimings | null} testTimings
* @param {string} variant
* @param {string} file
* @returns {{ seconds: number, source: 'variant' | 'max' | 'legacy' } | undefined}
*/
function resolveTiming(testTimings, variant, file) {
if (!testTimings) return undefined
const fromVariant = testTimings.variants[variant]?.[file]
if (isValidTiming(fromVariant)) {
return { seconds: /** @type {number} */ (fromVariant), source: 'variant' }
}
const fromMax = testTimings.max[file]
if (isValidTiming(fromMax)) {
return { seconds: /** @type {number} */ (fromMax), source: 'max' }
}
const fromLegacy = testTimings.legacy[file]
if (isValidTiming(fromLegacy)) {
return { seconds: /** @type {number} */ (fromLegacy), source: 'legacy' }
}
return undefined
}
/**
* @param {Record<string, unknown> | null | undefined} hash
* @returns {Record<string, number>}
*/
function toTimingsMap(hash) {
/** @type {Record<string, number>} */
const result = {}
for (const [file, value] of Object.entries(hash || {})) {
// Redis returns hash values as numbers or numeric strings.
const seconds = typeof value === 'string' ? Number(value) : value
if (isValidTiming(seconds)) result[file] = /** @type {number} */ (seconds)
}
return result
}
/**
* Fetches the timings of every variant, plus the legacy shared map as a
* fallback, in the versioned format consumed by `normalizeTimings`.
* Returns `null` when no timings are available at all.
*
* @param {any} client KV client
* @param {typeof retryKVOperation} retry
*/
async function fetchTestTimings(client, retry) {
if (!client) {
console.warn('KV client not configured, skipping timing fetch')
return null
}
/** @type {Record<string, Record<string, number>>} */
let variants = {}
try {
variants = await retry(async () => {
/** @type {string[]} */
const names = (await client.smembers(KV_TIMINGS_V2_VARIANTS_KEY)) || []
/** @type {Record<string, Record<string, number>>} */
const result = {}
for (const name of names) {
const variantTimings = toTimingsMap(
await client.hgetall(`${KV_TIMINGS_V2_PREFIX}${name}`)
)
if (Object.keys(variantTimings).length > 0) {
result[name] = variantTimings
}
}
return result
}, 'fetch variant timings')
} catch (err) {
console.log('Failed to fetch variant timings:', err.message)
}
/** @type {Record<string, number>} */
let legacy = {}
try {
legacy = toTimingsMap(
await retry(() => client.get(KV_TIMINGS_KEY), 'fetch legacy timings')
)
} catch (err) {
console.log('Failed to fetch legacy timings:', err.message)
}
if (Object.keys(variants).length === 0 && Object.keys(legacy).length === 0) {
console.log('No timing data found in KV store')
return null
}
return {
version: 2,
variants,
max: computeMaxTimings(variants),
legacy,
}
}
/**
* Records this run's timings for its variant. Only touches the variant's own
* hash and the variant index; other variants and the legacy key are left as
* they are.
*
* @param {any} client KV client
* @param {typeof retryKVOperation} retry
* @param {string} variant
* @param {Record<string, number>} curTimings seconds per test file
* @param {(file: string) => boolean} fileExists
*/
async function writeTestTimings(
client,
retry,
variant,
curTimings,
fileExists
) {
const key = `${KV_TIMINGS_V2_PREFIX}${variant}`
if (Object.keys(curTimings).length > 0) {
await retry(async () => {
await client.hset(key, curTimings)
await client.sadd(KV_TIMINGS_V2_VARIANTS_KEY, variant)
}, 'update timings')
console.log(`Successfully updated test timings for variant ${variant}`)
}
// Clean up stale timings for deleted tests, within this variant only
const recorded =
(await retry(() => client.hgetall(key), 'read timings')) || {}
const stale = Object.keys(recorded).filter((file) => !fileExists(file))
if (stale.length > 0) {
for (const file of stale) console.log('removing stale timing', file)
await retry(() => client.hdel(key, ...stale), 'remove stale timings')
}
}
const testFilters = {
development: new RegExp('^(test/(development|e2e))'),
production: new RegExp('^(test/(production|e2e))'),
......@@ -379,22 +624,6 @@ const isMatchingPattern = (pattern, file) => {
}
}
async function getTestTimings() {
if (!kvClient) {
console.warn('KV client not configured, skipping timing fetch')
return null
}
const timings = await retryKVOperation(async () => {
const data = await kvClient.get(KV_TIMINGS_KEY)
if (!data) {
console.log('No timing data found in KV store')
}
return data
}, 'fetch timings')
return timings || null
}
async function main() {
// Ensure we have the arguments awaited from yargs.
argv = await argv
......@@ -526,7 +755,7 @@ async function main() {
if (!prevTimings && !options.requireTimings) {
try {
prevTimings = await getTestTimings()
prevTimings = await fetchTestTimings(kvClient, retryKVOperation)
if (prevTimings) {
console.log('Fetched previous timings data successfully from KV')
} else {
......@@ -557,6 +786,9 @@ async function main() {
tests = externalTestsFilter(tests)
}
const timingsVariant = getTimingsVariant(process.env)
const testTimings = normalizeTimings(prevTimings)
let testSet = new Set()
tests = tests
.map((test) => {
......@@ -574,10 +806,12 @@ async function main() {
const groupPos = parseInt(groupParts[0], 10)
const groupTotal = parseInt(groupParts[1], 10)
if (prevTimings) {
if (testTimings) {
/** @type {TestFile[][]} */
const groups = [[]]
const groupTimes = [0]
/** @type {Record<'variant' | 'max' | 'legacy' | 'none', number>} */
const timingSources = { variant: 0, max: 0, legacy: 0, none: 0 }
for (const test of tests) {
let smallestGroup = groupTimes[0]
......@@ -597,9 +831,15 @@ async function main() {
}
}
groups[smallestGroupIdx].push(test)
groupTimes[smallestGroupIdx] += prevTimings[test.file] || 1
const timing = resolveTiming(testTimings, timingsVariant, test.file)
timingSources[timing?.source ?? 'none']++
groupTimes[smallestGroupIdx] += timing?.seconds || 1
}
console.log(
`Test timings for variant ${timingsVariant}: ${timingSources.variant} from variant, ${timingSources.max} from max across variants, ${timingSources.legacy} from legacy, ${timingSources.none} without timing`
)
const curGroupIdx = groupPos - 1
tests = groups[curGroupIdx]
......@@ -1087,6 +1327,7 @@ ${ENDGROUP}`)
}
if (options.timings) {
/** @type {Record<string, number>} */
const curTimings = {}
// let junitData = `<testsuites name="jest tests">`
/*
......@@ -1116,26 +1357,13 @@ ${ENDGROUP}`)
if (shouldUseSharedTimings) {
if (kvClient) {
try {
// Fetch existing timings and merge with new ones
const existingTimings = (await getTestTimings()) || {}
const newTimings = {
...existingTimings,
...curTimings,
}
// Clean up stale timings for deleted tests
for (const test of Object.keys(newTimings)) {
if (!fs.existsSync(path.join(__dirname, test))) {
console.log('removing stale timing', test)
delete newTimings[test]
}
}
// Update KV store with retries
await retryKVOperation(async () => {
await kvClient.set(KV_TIMINGS_KEY, newTimings)
console.log('Successfully updated test timings in KV store')
}, 'update timings')
await writeTestTimings(
kvClient,
retryKVOperation,
timingsVariant,
curTimings,
(file) => fs.existsSync(path.join(__dirname, file))
)
} catch (err) {
console.log('Failed to update timings data', err)
}
......
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