Skip to content
← Public packages

@kody/kody-factory

Forkable multi-project software factory: signals, priority queue, project UI, sweep job. Agent runners and Sentry reach it by events.

FollowFork

Files

analyze.ts

460 lines · 21.7 KB · TypeScript
import { normalizeName, runnerMultipliers, runnerOsOf, type RunnerOs } from './shared.ts'
import { countBy, mean, minutesBetween, percentiles, round2, sum } from './stats.ts'
import type { CriticalPath, Dataset, JobMetrics, JobSummary, Metrics, RunSummary, WorkflowMetrics } from './types.ts'

const failing = new Set(['failure', 'timed_out'])
const setupPattern = /setup|install|deps|npm ci|cache|restore|checkout/i
const duplicatePattern = /setup|install|deps|npm ci|build|bundle|compile|checkout/i
const docsPattern = /(^docs\/|\.(md|mdx|txt)$)/i

function zeroOs(): Record<RunnerOs, number> {
	return { linux: 0, windows: 0, macos: 0, other: 0 }
}

function jobMinutes(job: JobSummary) {
	return minutesBetween(job.startedAt, job.completedAt)
}

function ran(job: JobSummary) {
	return job.conclusion !== null && job.conclusion !== 'skipped' && job.conclusion !== 'cancelled' && (jobMinutes(job) ?? 0) > 0
}

/** Runner minutes GitHub bills for one job: each job rounds up to the next whole minute. */
export function billedJobMinutes(job: JobSummary) {
	const minutes = jobMinutes(job)
	return minutes && minutes > 0 ? Math.ceil(minutes) : 0
}

export function runWallMinutes(run: RunSummary) {
	return minutesBetween(run.runStartedAt || run.createdAt, run.updatedAt)
}

/**
 * Failing jobs that carry signal. A short gate job that only reports other
 * jobs' results is dropped when another job failed too.
 */
export function signalFailures(jobs: ReadonlyArray<JobSummary>, workflowName: string) {
	const failed = jobs.filter((job) => job.conclusion !== null && failing.has(job.conclusion))
	if (failed.length <= 1) return failed
	const gateName = normalizeName(workflowName).toLowerCase()
	const real = failed.filter((job) => {
		const isGate = normalizeName(job.name).toLowerCase() === gateName || (jobMinutes(job) ?? 0) < 0.75
		return !isGate
	})
	return real.length ? real : failed
}

/** Next run of the same workflow on the same branch after `run`. */
function nextRunOnBranch(runs: ReadonlyArray<RunSummary>, run: RunSummary) {
	return runs.find((other) => other.id !== run.id && other.headBranch === run.headBranch && other.createdAt > run.createdAt && other.status === 'completed' && other.conclusion !== 'cancelled' && other.conclusion !== 'skipped')
}

/** Infer the job chain that ended a run from job timestamps (needs edges are not in the API). */
export function inferChain(run: RunSummary, jobs: ReadonlyArray<JobSummary>) {
	const done = jobs.filter((job) => ran(job) && job.completedAt)
	if (done.length === 0) return []
	const runStart = Date.parse(run.runStartedAt || run.createdAt)
	let current = done.reduce((latest, job) => (Date.parse(job.completedAt!) > Date.parse(latest.completedAt!) ? job : latest))
	const chain = [current]
	const used = new Set([current.id])
	for (let guard = 0; guard < 20; guard++) {
		const created = current.createdAt ? Date.parse(current.createdAt) : NaN
		const anchor = Number.isFinite(created) && created - runStart > 20000 ? created : Date.parse(current.startedAt!)
		const candidates = done.filter((job) => !used.has(job.id) && Date.parse(job.completedAt!) <= anchor + 5000)
		if (candidates.length === 0) break
		const pred = candidates.reduce((latest, job) => (Date.parse(job.completedAt!) > Date.parse(latest.completedAt!) ? job : latest))
		chain.push(pred)
		used.add(pred.id)
		current = pred
	}
	return chain.reverse()
}

function cachePrefix(key: string) {
	const parts = key.split('-')
	const kept: string[] = []
	for (const part of parts) {
		if (/^[0-9a-f]{12,}$/i.test(part) || /^\d{5,}$/.test(part)) break
		kept.push(part)
	}
	return kept.join('-') || key.slice(0, 24)
}

export function isDocsOnly(files: ReadonlyArray<string>) {
	return files.length > 0 && files.every((file) => docsPattern.test(file) && !file.startsWith('.github/'))
}

/** Turn a collected dataset into weekly metrics. Pure. */
export function analyze(dataset: Dataset): Metrics {
	const notes = [...dataset.notes]
	const windowDays = Math.max(1, (Date.parse(dataset.until) - Date.parse(dataset.since)) / 86400000)
	const perWeek = 7 / windowDays
	const workflows: WorkflowMetrics[] = []
	const jobAcc = new Map<string, { workflow: string; job: string; os: RunnerOs; durations: number[]; queues: number[]; failures: number; sole: number; soleFixed: number; soleRerun: number; flaky: number; steps: Map<string, number[]> }>()
	const runnerWeek = zeroOs()
	const billedWeek: Record<string, number> = {}
	const setupSteps: Metrics['setupSteps'] = []
	const duplicates: Metrics['duplicates'] = []
	const coFailing: Metrics['coFailing'] = []

	const accFor = (workflow: string, job: JobSummary) => {
		const key = `${workflow} / ${job.name}`
		let acc = jobAcc.get(key)
		if (!acc) {
			acc = { workflow, job: job.name, os: runnerOsOf(job.labels), durations: [], queues: [], failures: 0, sole: 0, soleFixed: 0, soleRerun: 0, flaky: 0, steps: new Map() }
			jobAcc.set(key, acc)
		}
		return acc
	}

	for (const workflow of dataset.workflows) {
		if (workflow.runs.length === 0) continue
		const runs = workflow.runs
		const scale = workflow.listingScale || 1
		const completed = runs.filter((run) => run.status === 'completed' && run.conclusion !== 'skipped')
		const durations = completed
			.filter((run) => run.conclusion === 'success' || (run.conclusion !== null && failing.has(run.conclusion)))
			.map((run) => runWallMinutes(run) ?? NaN)
		const sampled = completed.filter((run) => dataset.jobsByRun[String(run.id)])

		// Flaky: same SHA fails then passes (rerun of one run, or a later run for the same SHA).
		const flakyShas = new Set<string>()
		for (const run of completed) {
			if (run.runAttempt > 1 && run.conclusion === 'success') {
				const previous = dataset.previousAttemptJobs[String(run.id)]
				if (!previous || previous.some((job) => job.conclusion !== null && failing.has(job.conclusion))) flakyShas.add(run.headSha)
			}
		}
		const bySha = new Map<string, RunSummary[]>()
		for (const run of completed) bySha.set(run.headSha, [...(bySha.get(run.headSha) ?? []), run])
		for (const [sha, list] of bySha) {
			const failedAt = list.filter((run) => run.conclusion !== null && failing.has(run.conclusion)).map((run) => run.createdAt).sort()[0]
			if (failedAt && list.some((run) => run.conclusion === 'success' && run.createdAt > failedAt)) flakyShas.add(sha)
		}

		// Superseded PR runs that kept running after a newer commit started.
		let superseded = 0
		let supersededWall = 0
		const prRuns = runs.filter((run) => run.event === 'pull_request')
		const byBranch = new Map<string, RunSummary[]>()
		for (const run of prRuns) byBranch.set(run.headBranch, [...(byBranch.get(run.headBranch) ?? []), run])
		for (const list of byBranch.values()) {
			list.sort((a, b) => a.createdAt.localeCompare(b.createdAt))
			for (let index = 0; index < list.length - 1; index++) {
				const older = list[index]
				const newer = list[index + 1]
				if (older.headSha === newer.headSha || older.conclusion === 'cancelled') continue
				const overlap = minutesBetween(newer.createdAt, older.updatedAt)
				if (overlap && overlap > 0.5) {
					superseded += 1
					supersededWall += overlap
				}
			}
		}

		// Runner minutes per run from sampled successful runs.
		const perRunOs: Array<Record<RunnerOs, number>> = []
		const firstAttempts = sampled.filter((run) => run.conclusion === 'success' && run.runAttempt === 1)
		for (const run of firstAttempts.length ? firstAttempts : sampled.filter((run) => run.conclusion === 'success')) {
			const os = zeroOs()
			for (const job of dataset.jobsByRun[String(run.id)]) os[runnerOsOf(job.labels)] += billedJobMinutes(job)
			perRunOs.push(os)
		}
		const runsPerWeek = completed.length * scale * perWeek
		const weekOs = zeroOs()
		let perRunTotal = 0
		if (perRunOs.length) {
			for (const os of Object.keys(weekOs) as RunnerOs[]) {
				const avg = mean(perRunOs.map((entry) => entry[os]))
				weekOs[os] = Math.round(avg * runsPerWeek)
				perRunTotal += avg
			}
		} else {
			// No job detail: wall time on one Linux runner is a lower bound.
			weekOs.linux = Math.round(sum(completed.map((run) => Math.ceil(runWallMinutes(run) ?? 0))) * scale * perWeek)
			perRunTotal = completed.length ? weekOs.linux / runsPerWeek : 0
		}
		for (const os of Object.keys(weekOs) as RunnerOs[]) runnerWeek[os] += weekOs[os]

		// Billed minutes from the timing API, scaled the same way.
		const timings = sampled.map((run) => dataset.timing[String(run.id)]).filter(Boolean)
		if (timings.length) {
			const keys = new Set(timings.flatMap((timing) => Object.keys(timing)))
			for (const key of keys) {
				const avg = mean(timings.map((timing) => Number(timing[key]?.total_ms ?? 0) / 60000))
				billedWeek[key] = (billedWeek[key] ?? 0) + Math.round(avg * runsPerWeek)
			}
		}

		const p50Wall = percentiles(durations).p50
		const parallelism = p50Wall > 0 ? Math.max(1, perRunTotal / p50Wall) : 1
		workflows.push({
			id: workflow.id,
			name: workflow.name,
			path: workflow.path,
			runsInWindow: Math.round(runs.length * scale),
			analyzedRuns: runs.length,
			sampledRuns: sampled.length,
			events: countBy(runs, (run) => run.event),
			conclusions: countBy(runs, (run) => run.conclusion ?? run.status),
			durationMin: percentiles(durations),
			rerunRate: round2(completed.length ? completed.filter((run) => run.runAttempt > 1).length / completed.length : 0),
			flakyRate: round2(bySha.size ? flakyShas.size / bySha.size : 0),
			flakyShas: flakyShas.size,
			supersededRuns: Math.round(superseded * scale),
			supersededMinutesPerWeek: Math.round(supersededWall * parallelism * scale * perWeek),
			runnerMinutesPerRun: round2(perRunTotal),
			runnerMinutesPerWeek: weekOs,
			file: workflow.file,
		})

		// Job level metrics, catch value, duplicates, co-failure.
		const failureSets = new Map<string, Set<number>>()
		const dupPerRun = new Map<string, { jobs: number; minutes: number[] }>()
		for (const run of sampled) {
			const jobs = dataset.jobsByRun[String(run.id)]
			const failed = signalFailures(jobs, workflow.name)
			const next = failed.length === 1 ? nextRunOnBranch(runs, run) : undefined
			for (const job of jobs) {
				if (!ran(job) && !(job.conclusion && failing.has(job.conclusion))) continue
				const acc = accFor(workflow.name, job)
				const duration = jobMinutes(job)
				if (duration !== null && job.conclusion === 'success') acc.durations.push(duration)
				const queue = minutesBetween(job.createdAt, job.startedAt)
				if (queue !== null) acc.queues.push(queue)
				if (job.conclusion && failing.has(job.conclusion)) {
					if (!failed.includes(job)) continue
					acc.failures += 1
					failureSets.set(job.name, (failureSets.get(job.name) ?? new Set()).add(run.id))
					if (failed.length === 1) {
						acc.sole += 1
						if (next && next.conclusion === 'success') {
							if (next.headSha === run.headSha) acc.soleRerun += 1
							else acc.soleFixed += 1
						}
					}
				}
				if (job.conclusion === 'success') {
					for (const step of job.steps) {
						const minutes = minutesBetween(step.startedAt, step.completedAt)
						if (minutes === null || step.conclusion === 'skipped') continue
						const name = normalizeName(step.name)
						acc.steps.set(name, [...(acc.steps.get(name) ?? []), minutes])
					}
				}
			}
			// Same step name across several jobs of one run.
			const stepJobs = new Map<string, number[]>()
			for (const job of jobs.filter((job) => job.conclusion === 'success')) {
				for (const step of job.steps) {
					const name = normalizeName(step.name)
					if (!duplicatePattern.test(name)) continue
					const minutes = minutesBetween(step.startedAt, step.completedAt)
					if (minutes === null) continue
					stepJobs.set(name, [...(stepJobs.get(name) ?? []), minutes])
				}
			}
			for (const [name, list] of stepJobs) {
				if (list.length < 3) continue
				const entry = dupPerRun.get(name) ?? { jobs: 0, minutes: [] }
				entry.jobs = Math.max(entry.jobs, list.length)
				entry.minutes.push(sum(list) - Math.max(...list))
				dupPerRun.set(name, entry)
			}
		}
		// Reruns: jobs that failed on the earlier attempt of a run that later passed.
		for (const run of completed.filter((run) => run.runAttempt > 1 && run.conclusion === 'success')) {
			const previous = dataset.previousAttemptJobs[String(run.id)]
			if (!previous) continue
			for (const job of signalFailures(previous, workflow.name)) accFor(workflow.name, job).flaky += 1
		}
		for (const [name, entry] of dupPerRun) {
			const perRun = percentiles(entry.minutes).p50
			duplicates.push({ workflow: workflow.name, step: name, jobs: entry.jobs, minutesPerRun: round2(perRun), minutesPerWeek: Math.round(perRun * runsPerWeek) })
		}
		const repeatFailers = [...failureSets.entries()].filter(([, set]) => set.size >= 2)
		const grouped = new Set<string>()
		for (const [name, set] of repeatFailers) {
			if (grouped.has(name)) continue
			const same = repeatFailers.filter(([other, otherSet]) => other !== name && otherSet.size === set.size && [...set].every((id) => otherSet.has(id)))
			if (same.length) {
				const names = [name, ...same.map(([other]) => other)]
				for (const entry of names) grouped.add(entry)
				coFailing.push({ workflow: workflow.name, jobs: names, failures: set.size })
			}
		}
	}

	// Presence: share of the newer half of sampled runs that ran the job, so a
	// job added mid-week is projected at its current frequency.
	const recentPresence = new Map<string, number>()
	for (const workflow of dataset.workflows) {
		const sampled = workflow.runs
			.filter((run) => run.status === 'completed' && run.conclusion !== 'skipped' && dataset.jobsByRun[String(run.id)])
			.sort((a, b) => a.createdAt.localeCompare(b.createdAt))
		const recent = sampled.slice(Math.floor(sampled.length / 2))
		if (recent.length < 4) continue
		const counts = new Map<string, number>()
		for (const run of recent) {
			const keys = new Set<string>()
			for (const job of dataset.jobsByRun[String(run.id)]) {
				if (!ran(job) && !(job.conclusion && failing.has(job.conclusion))) continue
				keys.add(`${workflow.name} / ${job.name}`)
			}
			for (const key of keys) counts.set(key, (counts.get(key) ?? 0) + 1)
		}
		for (const [key, count] of counts) recentPresence.set(key, round2(count / recent.length))
	}

	const jobs: JobMetrics[] = [...jobAcc.entries()].map(([key, acc]) => {
		const samples = acc.durations.length + acc.failures
		const presence = recentPresence.get(key) ?? 1
		const steps = [...acc.steps.entries()].map(([name, list]) => ({ name, p50Min: percentiles(list).p50, n: list.length })).sort((a, b) => b.p50Min - a.p50Min)
		for (const step of steps) {
			if (setupPattern.test(step.name) && step.p50Min >= 0.5) setupSteps.push({ workflow: acc.workflow, job: acc.job, step: step.name, p50Min: step.p50Min, os: acc.os })
		}
		return {
			key,
			workflow: acc.workflow,
			job: acc.job,
			os: acc.os,
			isGate: normalizeName(acc.job).toLowerCase() === normalizeName(acc.workflow).toLowerCase(),
			samples,
			presence,
			durationMin: percentiles(acc.durations),
			queueMin: percentiles(acc.queues),
			failures: acc.failures,
			soleFailures: acc.sole,
			soleFailuresFixedByCommit: acc.soleFixed,
			soleFailuresPassedOnRerun: acc.soleRerun,
			flakyFailures: acc.flaky,
			alwaysPassed: acc.failures === 0 && acc.flaky === 0 && samples >= 5,
			catchRate: round2(samples ? acc.soleFixed / samples : 0),
			steps: steps.slice(0, 8),
		}
	})

	// PR time to green across workflows, by head SHA. Only the first run of each
	// workflow per SHA counts, so later label or reopen re-runs do not stretch it.
	const prBySha = new Map<string, RunSummary[]>()
	for (const workflow of dataset.workflows) {
		const firstPerSha = new Map<string, RunSummary>()
		for (const run of workflow.runs.filter((run) => run.event === 'pull_request' && run.conclusion !== 'skipped')) {
			const seen = firstPerSha.get(run.headSha)
			if (!seen || run.createdAt < seen.createdAt) firstPerSha.set(run.headSha, run)
		}
		for (const run of firstPerSha.values()) prBySha.set(run.headSha, [...(prBySha.get(run.headSha) ?? []), run])
	}
	const ttg: number[] = []
	const lastWorkflow: Record<string, number> = {}
	for (const list of prBySha.values()) {
		if (!list.every((run) => run.status === 'completed' && run.conclusion === 'success')) continue
		const start = list.map((run) => run.createdAt).sort()[0]
		const last = list.reduce((latest, run) => (run.updatedAt > latest.updatedAt ? run : latest))
		const minutes = minutesBetween(start, last.updatedAt)
		if (minutes === null) continue
		ttg.push(minutes)
		lastWorkflow[last.workflowName] = (lastWorkflow[last.workflowName] ?? 0) + 1
	}

	const criticalPath = computeCriticalPath(dataset, workflows, lastWorkflow)

	const caches = dataset.caches
	const byPrefix = new Map<string, { entries: number; reused: number; size: number }>()
	let reused = 0
	for (const entry of caches ?? []) {
		const prefix = cachePrefix(entry.key)
		const value = byPrefix.get(prefix) ?? { entries: 0, reused: 0, size: 0 }
		value.entries += 1
		value.size += entry.sizeBytes
		const wasReused = (minutesBetween(entry.createdAt, entry.lastAccessedAt) ?? 0) > 10
		if (wasReused) {
			value.reused += 1
			reused += 1
		}
		byPrefix.set(prefix, value)
	}
	if (!caches) notes.push('cache list not visible')

	const prFileLists = Object.values(dataset.prFiles)
	const runnerTotal = sum(Object.values(runnerWeek))
	const billableEquivalent = sum((Object.keys(runnerWeek) as RunnerOs[]).map((os) => runnerWeek[os] * runnerMultipliers[os]))
	const billedTotal = sum(Object.values(billedWeek))
	return {
		repo: dataset.repo,
		defaultBranch: dataset.defaultBranch,
		since: dataset.since,
		until: dataset.until,
		apiCalls: dataset.apiCalls,
		workflows: workflows.sort((a, b) => sum(Object.values(b.runnerMinutesPerWeek)) - sum(Object.values(a.runnerMinutesPerWeek))),
		jobs: jobs.sort((a, b) => b.durationMin.p50 - a.durationMin.p50),
		runnerMinutesPerWeek: { ...runnerWeek, total: runnerTotal, billableEquivalent },
		billedMinutesPerWeek: { ...billedWeek, total: billedTotal, source: Object.keys(billedWeek).length ? 'timing api (sampled runs, scaled)' : 'not visible' },
		prTimeToGreenMin: { ...percentiles(ttg), lastWorkflow },
		criticalPath,
		caches: {
			visible: Boolean(caches),
			entries: caches?.length ?? 0,
			sizeMb: Math.round(sum((caches ?? []).map((entry) => entry.sizeBytes)) / 1048576),
			createdInWindow: (caches ?? []).filter((entry) => entry.createdAt >= dataset.since).length,
			reusedRate: round2(caches?.length ? reused / caches.length : 0),
			byPrefix: [...byPrefix.entries()]
				.map(([prefix, value]) => ({ prefix, entries: value.entries, reusedRate: round2(value.reused / value.entries), sizeMb: Math.round(value.size / 1048576) }))
				.sort((a, b) => b.sizeMb - a.sizeMb)
				.slice(0, 10),
		},
		setupSteps: setupSteps.sort((a, b) => b.p50Min - a.p50Min).slice(0, 15),
		duplicates: duplicates.filter((entry) => entry.minutesPerWeek > 0).sort((a, b) => b.minutesPerWeek - a.minutesPerWeek).slice(0, 10),
		coFailing,
		docsOnlyPrs: { sampled: prFileLists.length, docsOnly: prFileLists.filter(isDocsOnly).length },
		notes,
	}
}

/** Typical PR critical path in the slowest PR workflow, inferred from job timestamps. */
export function computeCriticalPath(dataset: Dataset, workflows: ReadonlyArray<WorkflowMetrics>, lastWorkflow: Record<string, number> = {}): CriticalPath | null {
	// The workflow that most often finishes last on a PR carries the typical critical path.
	const prWorkflows = workflows
		.filter((workflow) => (workflow.events.pull_request ?? 0) > 0 && workflow.sampledRuns > 0)
		.sort((a, b) => (lastWorkflow[b.name] ?? 0) - (lastWorkflow[a.name] ?? 0) || b.durationMin.p50 - a.durationMin.p50)
	for (const workflow of prWorkflows) {
		const info = dataset.workflows.find((entry) => entry.id === workflow.id)
		if (!info) continue
		const chains: Array<{ signature: string; run: RunSummary; chain: JobSummary[] }> = []
		// First attempts only: a rerun mixes job timestamps from two attempts.
		for (const run of info.runs.filter((run) => run.event === 'pull_request' && run.conclusion === 'success' && run.runAttempt === 1)) {
			const jobs = dataset.jobsByRun[String(run.id)]?.filter((job) => job.runAttempt === 1)
			if (!jobs?.length) continue
			const chain = inferChain(run, jobs)
			// Tiny gate or report jobs do not change which path is typical.
			const signature = chain.filter((job) => (jobMinutes(job) ?? 0) >= 0.5).map((job) => job.name).join(' > ')
			if (chain.length) chains.push({ signature: signature || chain.map((job) => job.name).join(' > '), run, chain })
		}
		if (chains.length === 0) continue
		// Weight recent runs: the pipeline can change during the week, and the newest shape is what PRs hit next.
		chains.sort((a, b) => a.run.createdAt.localeCompare(b.run.createdAt))
		const recent = chains.slice(-Math.max(3, Math.ceil(chains.length / 2)))
		const counts = countBy(recent, (entry) => entry.signature)
		const signature = Object.entries(counts).sort((a, b) => b[1] - a[1])[0][0]
		const typical = recent.filter((entry) => entry.signature === signature && entry.chain.length === recent.find((other) => other.signature === signature)!.chain.length)
		const names = typical[0].chain.map((job) => job.name)
		const runJobsStart = (entry: (typeof typical)[number]) => {
			const jobs = dataset.jobsByRun[String(entry.run.id)] ?? []
			return jobs.map((job) => job.createdAt ?? job.startedAt ?? '').filter(Boolean).sort()[0] ?? entry.run.runStartedAt
		}
		const totals = typical.map((entry) => minutesBetween(runJobsStart(entry), entry.chain[entry.chain.length - 1].completedAt) ?? NaN)
		const total = percentiles(totals)
		return {
			workflow: workflow.name,
			samples: typical.length,
			chain: names.map((name, index) => ({
				job: name,
				queueP50Min: percentiles(typical.map((entry) => minutesBetween(entry.chain[index].createdAt, entry.chain[index].startedAt) ?? NaN)).p50,
				durationP50Min: percentiles(typical.map((entry) => minutesBetween(entry.chain[index].startedAt, entry.chain[index].completedAt) ?? NaN)).p50,
			})),
			totalP50Min: total.p50,
			totalP90Min: total.p90,
		}
	}
	return null
}