import { normalizeName, round, runnerMultipliers, type RunnerOs } from './shared.ts' import type { JobMetrics, Metrics, Opportunity, WorkflowMetrics } from './types.ts' /** Flaky jobs matching this are left to the separate daily e2e flake automation. */ export const flakeExclusionPattern = /e2e|playwright/i const installPattern = /install|deps|npm ci/i const setupPattern = /setup|install|deps|npm ci|cache|restore|checkout/i /** Repeated steps worth sharing (checkout and post steps are cheap and unavoidable). */ const sharablePattern = /setup|install|deps|npm ci|build|bundle|compile/i const testStepPattern = /test|e2e|spec|playwright|vitest|jest|validate/i const minStepMinutesForCache = 2 const minCriticalJobMinutes = 6 const minSpeedUpStepMinutes = 5 /** Share of a slow step a profiling pass is assumed to recover without removing work. */ export const speedUpAssumption = 0.2 /** Share of duplicated setup a shared cache or artifact is assumed to remove. */ export const dedupeAssumption = 0.5 function slug(text: string) { return normalizeName(text).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '').slice(0, 60) } function prRunsPerWeek(workflow: WorkflowMetrics | undefined) { if (!workflow) return 0 const share = workflow.analyzedRuns ? (workflow.events.pull_request ?? 0) / workflow.analyzedRuns : 0 return workflow.runsInWindow * share } function runsPerWeek(workflow: WorkflowMetrics | undefined) { return workflow?.runsInWindow ?? 0 } /** Weekly runs of one job: workflow runs times the share of runs the job appears in. */ function jobRunsPerWeek(workflow: WorkflowMetrics | undefined, job: { presence?: number }) { return runsPerWeek(workflow) * (job.presence ?? 1) } /** Billed share of runner minutes for an OS (0 for a public repo on standard runners). */ function billedRatio(metrics: Metrics, os: RunnerOs) { const runner = metrics.runnerMinutesPerWeek[os] const key = os === 'linux' ? 'UBUNTU' : os === 'windows' ? 'WINDOWS' : os === 'macos' ? 'MACOS' : '' const billed = key ? Number(metrics.billedMinutesPerWeek[key] ?? 0) : 0 if (!runner || !billed) return 0 return Math.min(runnerMultipliers[os], billed / runner) } /** * Per-PR wall time a job change can save: only the part of the saving that * exceeds the slack against the other jobs in its workflow. */ export function perPrGain(metrics: Metrics, job: JobMetrics, saving: number) { const own = job.durationMin.p50 + job.queueMin.p50 const onPath = metrics.criticalPath?.workflow === job.workflow && metrics.criticalPath.chain.some((step) => step.job === job.job) if (onPath) { const others = metrics.jobs .filter((other) => other.workflow === job.workflow && other.key !== job.key && !metrics.criticalPath!.chain.some((step) => step.job === other.job)) .map((other) => other.durationMin.p50 + other.queueMin.p50) const pathTotal = metrics.criticalPath!.totalP50Min const nextLongest = others.length ? Math.max(...others) : 0 return Math.max(0, Math.min(saving, pathTotal - nextLongest)) } const others = metrics.jobs.filter((other) => other.workflow === job.workflow && other.key !== job.key).map((other) => other.durationMin.p50 + other.queueMin.p50) const slack = own - (others.length ? Math.max(...others) : 0) return Math.max(0, Math.min(saving, slack)) } function shardOf(name: string) { const match = /\((\d+)\s*\/\s*(\d+)\)/.exec(name) return match ? { index: Number(match[1]), total: Number(match[2]), base: name.replace(match[0], '').trim() } : null } function variantBase(name: string) { return name.replace(/\s*\([^)]*\)\s*$/, '').trim() } function make(metrics: Metrics, input: Omit & { os: RunnerOs; minutesSavedPerPr: number; runnerMinutesSavedPerWeek: number }): Opportunity { const { os, ...rest } = input return { ...rest, minutesSavedPerPr: round(input.minutesSavedPerPr, 1), runnerMinutesSavedPerWeek: Math.round(input.runnerMinutesSavedPerWeek), billedMinutesSavedPerWeek: Math.round(input.runnerMinutesSavedPerWeek * billedRatio(metrics, os)), baseline: round(input.baseline, 2), } } /** Deterministic candidate list from weekly metrics. Pure. */ export function findOpportunities(metrics: Metrics): Opportunity[] { const out: Opportunity[] = [] const workflowByName = new Map(metrics.workflows.map((workflow) => [workflow.name, workflow])) // 1. Setup or install steps far slower than the same step elsewhere (cache miss or no cache). for (const job of metrics.jobs) { const workflow = workflowByName.get(job.workflow) for (const step of job.steps) { if (!installPattern.test(step.name) || step.p50Min < minStepMinutesForCache) continue const peers = metrics.jobs .filter((other) => other.key !== job.key && other.os === job.os) .flatMap((other) => other.steps.filter((entry) => installPattern.test(entry.name)).map((entry) => entry.p50Min)) const best = peers.length ? Math.min(...peers) : step.p50Min * 0.4 if (best > step.p50Min * 0.5) continue const saving = (step.p50Min - best) * 0.5 out.push( make(metrics, { id: `cache-setup:${slug(job.key)}:${slug(step.name)}`, kind: 'cache-setup', title: `Cache the ${step.name} step in ${job.job}`, workflow: job.workflow, job: job.job, os: job.os, evidence: `${step.name} takes ${step.p50Min} min p50 here vs ${round(best, 2)} min for the fastest ${job.os} install elsewhere (${step.n} samples).`, change: `Restore a dependency cache keyed on the lockfile and runner OS/arch for ${job.job} (for example actions/cache of the npm cache or node_modules), so ${step.name} becomes a cache hit. No job or test is removed.`, minutesSavedPerPr: perPrGain(metrics, job, saving), runnerMinutesSavedPerWeek: saving * jobRunsPerWeek(workflow, job), confidenceEffect: 'none', needsWorkflowEdit: true, metricKey: `step:${job.key}:${step.name}:p50`, baseline: step.p50Min, }), ) } } // 2. The same setup step repeated across many jobs of one run. for (const dup of metrics.duplicates) { if (dup.minutesPerWeek < 120 || !sharablePattern.test(dup.step) || /checkout|^post /i.test(dup.step)) continue out.push( make(metrics, { id: `dedupe-setup:${slug(dup.workflow)}:${slug(dup.step)}`, kind: 'dedupe-setup', title: `Share ${dup.step} work across ${dup.jobs} jobs in ${dup.workflow}`, workflow: dup.workflow, job: null, os: 'linux', evidence: `${dup.step} runs in ${dup.jobs} jobs per run; the repeats cost ${dup.minutesPerRun} runner min per run, about ${dup.minutesPerWeek} min per week.`, change: `Build or install once and share it (warm cache written by one job and restored by the others, or an uploaded artifact), keeping every job and check. Estimate assumes ${Math.round(dedupeAssumption * 100)}% of the repeat cost goes away.`, minutesSavedPerPr: 0, runnerMinutesSavedPerWeek: dup.minutesPerWeek * dedupeAssumption, confidenceEffect: 'none', needsWorkflowEdit: true, metricKey: `dup:${dup.workflow}:${dup.step}:minutesPerRun`, baseline: dup.minutesPerRun, }), ) } // 3. The longest job on the critical path: add a shard or rebalance. const path = metrics.criticalPath if (path) { const longest = [...path.chain].sort((a, b) => b.durationP50Min - a.durationP50Min)[0] const job = metrics.jobs.find((entry) => entry.workflow === path.workflow && entry.job === longest?.job) const workStep = job?.steps.find((step) => !setupPattern.test(step.name)) if (job && job.durationMin.p50 >= minCriticalJobMinutes && workStep && testStepPattern.test(workStep.name)) { const shard = shardOf(job.job) const setup = job.steps.filter((step) => setupPattern.test(step.name)).reduce((total, step) => total + step.p50Min, 0) const work = Math.max(0, job.durationMin.p50 - setup) const total = shard?.total ?? 1 const siblings = shard ? metrics.jobs.filter((entry) => entry.workflow === job.workflow && shardOf(entry.job)?.base === shard.base) : [job] const slowest = Math.max(...siblings.map((entry) => entry.durationMin.p50)) const average = siblings.reduce((sumValue, entry) => sumValue + entry.durationMin.p50, 0) / siblings.length const fromShard = work / (total + 1) const fromBalance = Math.max(0, slowest - average) const saving = Math.max(fromShard, fromBalance) const workflow = workflowByName.get(job.workflow) const addsShard = fromShard >= fromBalance out.push( make(metrics, { id: `split-critical-path:${slug(shard?.base ?? job.job)}`, kind: 'split-critical-path', title: addsShard ? `Split ${shard?.base ?? job.job} into ${total + 1} shards` : `Rebalance ${shard?.base} shards`, workflow: job.workflow, job: job.job, os: job.os, evidence: `${job.job} is the longest job on the typical PR path (${job.durationMin.p50} min p50, ${round(setup, 2)} min of it setup; path p50 ${path.totalP50Min} min).${shard ? ` Shards: ${siblings.map((entry) => `${entry.job} ${entry.durationMin.p50} min`).join(', ')}.` : ''}`, change: addsShard ? `Run the same tests across ${total + 1} shards instead of ${total}; every test still runs. Costs about ${round(setup, 1)} extra runner min per run for the added setup.` : 'Balance shard assignment by recorded test duration so the shards finish together; every test still runs.', minutesSavedPerPr: Math.min(saving, path.totalP50Min), runnerMinutesSavedPerWeek: addsShard ? -setup * jobRunsPerWeek(workflow, job) : 0, confidenceEffect: 'none', needsWorkflowEdit: true, metricKey: `path:${path.workflow}:p50`, baseline: path.totalP50Min, }), ) } // 7. A slow non-setup step on the critical path: speed up the code it runs. for (const link of path.chain) { const job = metrics.jobs.find((entry) => entry.workflow === path.workflow && entry.job === link.job) const step = job?.steps.find((entry) => !setupPattern.test(entry.name) && entry.p50Min >= minSpeedUpStepMinutes) if (!job || !step) continue const workflow = workflowByName.get(job.workflow) const saving = step.p50Min * speedUpAssumption out.push( make(metrics, { id: `speed-up-step:${slug(job.key)}:${slug(step.name)}`, kind: 'speed-up-step', title: `Speed up ${step.name} in ${job.job}`, workflow: job.workflow, job: job.job, os: job.os, evidence: `${step.name} takes ${step.p50Min} min p50 on the typical PR path (${step.n} samples). Estimate assumes a profiling pass recovers ${Math.round(speedUpAssumption * 100)}%.`, change: `Profile ${step.name} and fix the slowest parts in repo code (slow setup or teardown, needless sleeps or timeouts, repeated expensive fixtures, serial work that can run concurrently). Keep every test and assertion; never skip, sample, or retry tests to hide time.`, minutesSavedPerPr: perPrGain(metrics, job, saving), runnerMinutesSavedPerWeek: saving * jobRunsPerWeek(workflow, job), confidenceEffect: 'none', needsWorkflowEdit: false, metricKey: `step:${job.key}:${step.name}:p50`, baseline: step.p50Min, }), ) } } // 4. PR runs that keep running after a newer commit lands. for (const workflow of metrics.workflows) { if (workflow.supersededMinutesPerWeek < 60) continue out.push( make(metrics, { id: `cancel-in-progress:${slug(workflow.name)}`, kind: 'cancel-in-progress', title: `Cancel superseded PR runs of ${workflow.name}`, workflow: workflow.name, job: null, os: 'linux', evidence: `${workflow.supersededRuns} PR runs kept running after a newer commit started (about ${workflow.supersededMinutesPerWeek} runner min per week). Workflow file ${workflow.file ? (workflow.file.cancelInProgress ? 'sets cancel-in-progress, but not for every PR path' : 'has no cancel-in-progress') : 'not inspected'}.`, change: 'Add a concurrency group keyed on the workflow and PR number with cancel-in-progress for pull_request events only (never for default branch pushes or deploys).', minutesSavedPerPr: 0, runnerMinutesSavedPerWeek: workflow.supersededMinutesPerWeek, confidenceEffect: 'none', needsWorkflowEdit: true, metricKey: `workflow:${workflow.name}:supersededMinutesPerWeek`, baseline: workflow.supersededMinutesPerWeek, }), ) } // 5. Docs-only PRs that run the whole pipeline. const docs = metrics.docsOnlyPrs if (docs.sampled >= 10 && docs.docsOnly >= 3 && docs.docsOnly / docs.sampled >= 0.1) { const share = docs.docsOnly / docs.sampled const prWorkflows = metrics.workflows.filter((workflow) => (workflow.events.pull_request ?? 0) > 0 && !workflow.file?.hasPullRequestPaths) const minutes = prWorkflows.reduce((total, workflow) => total + prRunsPerWeek(workflow) * workflow.runnerMinutesPerRun * share, 0) out.push( make(metrics, { id: 'path-filter-docs', kind: 'path-filter-docs', title: 'Skip code-only jobs on docs-only PRs', workflow: prWorkflows.map((workflow) => workflow.name).join(', '), job: null, os: 'linux', evidence: `${docs.docsOnly} of ${docs.sampled} sampled PRs changed only docs or Markdown, yet ran the full PR pipeline (${Math.round(minutes)} runner min per week at that share).`, change: 'Add a changes-detection job and job-level if: conditions so code jobs skip when only docs/** or *.md changed, while the required gate job still reports success. Keep any job that reads docs (docs tests, link checks). Do not use workflow-level paths filters on required checks: they leave required checks pending.', minutesSavedPerPr: share * metrics.prTimeToGreenMin.p50, runnerMinutesSavedPerWeek: minutes, confidenceEffect: 'none', needsWorkflowEdit: true, metricKey: 'prs:docsOnlyShare', baseline: share, }), ) } // 6. Flaky jobs (same SHA failed then passed): fixing them protects shipping confidence. for (const job of metrics.jobs) { const events = job.flakyFailures + job.soleFailuresPassedOnRerun if (events < 2 || job.isGate || flakeExclusionPattern.test(job.job)) continue const workflow = workflowByName.get(job.workflow) const prs = Math.max(1, prRunsPerWeek(workflow)) out.push( make(metrics, { id: `fix-flaky:${slug(job.key)}`, kind: 'fix-flaky', title: `Fix flaky ${job.job}`, workflow: job.workflow, job: job.job, os: job.os, evidence: `${job.job} failed and then passed on the same commit ${events} times this week (${job.samples} sampled runs).`, change: `Find the flaky test or step in ${job.job} from the failed attempt logs and fix its cause (race, timing, shared state, network). The fixed test passes on its first attempt and keeps running in full every time.`, minutesSavedPerPr: (events * (job.durationMin.p50 + job.queueMin.p50)) / prs, runnerMinutesSavedPerWeek: events * Math.ceil(job.durationMin.p50), confidenceEffect: 'none', needsWorkflowEdit: false, metricKey: `job:${job.key}:flaky`, baseline: events, }), ) } // 8. Matrix variants that never catch anything the sibling variant misses (coverage trade). const byBase = new Map() for (const job of metrics.jobs) { if (shardOf(job.job)) continue const base = `${job.workflow} / ${variantBase(job.job)}` if (base === `${job.workflow} / ${job.job}`) continue byBase.set(base, [...(byBase.get(base) ?? []), job]) } for (const variants of byBase.values()) { if (variants.length < 2) continue for (const job of variants) { if (job.soleFailures > 0 || job.samples < 10) continue const workflow = workflowByName.get(job.workflow) if (prShare(workflow) === 0) continue const minutes = Math.ceil(job.durationMin.p50) * jobRunsPerWeek(workflow, job) const weighted = minutes * runnerMultipliers[job.os] if (weighted < 120) continue out.push( make(metrics, { id: `drop-redundant-variant:${slug(job.key)}`, kind: 'drop-redundant-variant', title: `Run ${job.job} only on the merge queue or main`, workflow: job.workflow, job: job.job, os: job.os, evidence: `${job.job} was never the only failing job in ${job.samples} sampled runs; sibling variants (${variants.filter((other) => other !== job).map((other) => other.job).join(', ')}) cover the same steps. It costs ${minutes} runner min per week (${job.os}), about ${Math.round(minutes * prShare(workflow))} of that on PR runs.`, change: `Move ${job.job} off PR pushes (keep it on the merge queue or default branch), or drop the variant. PRs lose this platform signal before review.`, minutesSavedPerPr: perPrGain(metrics, job, job.durationMin.p50 + job.queueMin.p50), runnerMinutesSavedPerWeek: minutes * prShare(workflow), confidenceEffect: 'reduces', needsWorkflowEdit: true, metricKey: `job:${job.key}:p50`, baseline: job.durationMin.p50, }), ) } } // 9. Expensive jobs that always passed: defer them (coverage trade). for (const job of metrics.jobs) { if (!job.alwaysPassed || job.samples < 15 || job.isGate || shardOf(job.job)) continue if (out.some((entry) => entry.kind === 'drop-redundant-variant' && entry.job === job.job && entry.workflow === job.workflow)) continue const workflow = workflowByName.get(job.workflow) if (prShare(workflow) === 0) continue const minutes = Math.ceil(job.durationMin.p50) * jobRunsPerWeek(workflow, job) if (minutes * runnerMultipliers[job.os] < 300) continue out.push( make(metrics, { id: `defer-zero-catch-job:${slug(job.key)}`, kind: 'defer-zero-catch-job', title: `Defer ${job.job} to the merge queue`, workflow: job.workflow, job: job.job, os: job.os, evidence: `${job.job} passed in all ${job.samples} sampled runs this week and costs ${minutes} runner min per week (${job.os}). One quiet week is weak evidence.`, change: `Run ${job.job} on the merge queue and default branch only. PR authors find its failures later, at merge time.`, minutesSavedPerPr: perPrGain(metrics, job, job.durationMin.p50 + job.queueMin.p50), runnerMinutesSavedPerWeek: minutes * prShare(workflow), confidenceEffect: 'reduces', needsWorkflowEdit: true, metricKey: `job:${job.key}:p50`, baseline: job.durationMin.p50, }), ) } const seen = new Set() return out.filter((entry) => (seen.has(entry.id) ? false : (seen.add(entry.id), true))) } function prShare(workflow: WorkflowMetrics | undefined) { if (!workflow?.analyzedRuns) return 0 return (workflow.events.pull_request ?? 0) / workflow.analyzedRuns }