The user wants a "Lighthouse CI gate" engineered.
This implies a comprehensive solution, not just a snippet. The requirements are specific:
- Enforcing budgets: Performance budgets (Lighthouse checks).
- Flake mitigation: Handling the inherent variability in web performance testing.
- Release approvals: A mechanism to gate deployments based on these checks.
Scope of the Solution:
I need to provide a system that integrates into a CI/CD pipeline (e.g., GitHub Actions or generic scripts).
Key components needed:
- Configuration: How to define the budgets.
- Execution: How to run Lighthouse programmatically or via CLI in a way that supports repeated runs (for flake mitigation).
- Aggregation/Analysis: Logic to average results or filter outliers.
- Gating/Reporting: Outputting a status (pass/fail) and potentially commenting on a PR.
Step-by-Step Engineering:
-
The Budget Configuration:
- Standard Lighthouse approach:
lighthouse.json or budget.json.
- I should define a strict
budgets configuration.
-
Flake Mitigation Strategy:
- Problem: Running Lighthouse once is unreliable.
- Solution: Run N times, calculate the median (or trimmed mean), then compare against the budget.
- Implementation: A Node.js script is best here. It gives control over the loop, collecting results, and calculating statistics.
-
The Gate Logic (Release Approval):
- This needs to happen in the CI provider.
- I will use GitHub Actions as the default example because it's the most common modern CI/CD tool, but I'll keep the core logic generic enough (Node.js script) so it works elsewhere.
-
Architecture of the Node.js Script:
- Dependencies:
lighthouse, chrome-launcher, yargs (for CLI args).
- Flow:
- Launch Chrome.
- Run Lighthouse N times.
- Collect specific metrics (LCP, FID, CLS, TBT, etc.).
- Aggregate: Median is usually best for performance metrics to ignore outliers.
- Compare: Check against defined thresholds.
- Output: Markdown report for the PR, exit code 0 or 1 for the Gate.
-
Drafting the Code Structure:
- Config File (
lighthouse.config.js): Holds the thresholds.
- The Runner (
run-lighthouse.js): The heavy lifter.
- Function
runAudit(): Returns raw LHR object.
- Function
analyzeResults(results): Calculates medians.
- Function
checkBudgets(aggregated): Pass/Fail logic.
- CI Workflow (
.github/workflows/ci.yml): Shows how to use it.
-
Refining Flake Mitigation Details:
- Just running 5 times isn't enough if the environment is noisy.
- I should mention
standardDeviation. If the standard deviation is too high, the test should maybe fail or warn, indicating the environment is too unstable to trust the result.
- However, for a "Gate", a simple median of N runs is the industry standard approach to balance speed and accuracy. Let's stick to N=3 or N=5.
-
Refining Release Approvals:
- "Release Approval" implies a manual step or a conditional deployment.
- In the context of a CI gate, this usually means: "If this check passes, the artifact is promoted to release candidate."
- I will add a "Soft Gate" vs "Hard Gate" concept. E.g., Regressions < 10% = Warning, > 10% = Fail.
-
Writing the specific code components:
- Script: Need to handle Chrome launching.
- Budgets: Define numeric limits (e.g., LCP < 2500).
- Output: JSON report is good for machines, Markdown summary for humans.
-
Review against User Prompt:
- Enforcing budgets? Yes, the script checks values.
- Flake mitigation? Yes, multiple runs + median calculation.
- Release approvals? Yes, via the exit code blocking the merge/deploy stage.
-
Final Polish:
- Add comments explaining why we do things (e.g.,
--headless).
- Ensure error handling (if Chrome crashes).
- Add a section on "Environment Standardization" (Docker) because flake mitigation requires a stable CPU.
(Self-Correction during drafting): Initially, I thought about using Lighthouse CI (@lhci/cli).
- Pros: Built-in server, complex assertions.
- Cons: Configuration can be opaque. Custom flake mitigation (like taking the median of 5 runs manually) is sometimes harder to tweak than a raw node script.
- Decision: I will provide a custom Node.js wrapper script. Why? It demonstrates the engineering of the logic (how to average, how to compare) rather than just configuring a black box tool. It's more flexible for specific "Gate" logic. However, I should mention
lhci as an alternative.
Let's build the Custom Node.js Gate. It's more robust for the specific "flake mitigation via median" request.
Plan:
- Philosophy: Explain the "Median of N" approach.
- The Configuration:
performance-budget.json.
- The Engine:
lighthouse-gate.js (The script that runs N times, averages, checks, and decides to pass/fail).
- The CI Integration: GitHub Actions workflow example.
- The Approval Mechanism: Branch protection rules.
Let's write the code.
Code specifics:
- Use
chrome-launcher to handle the browser instance.
- Use
lighthouse library directly.
- Metrics to track:
largest-contentful-paint, cumulative-layout-shift, total-blocking-time, speed-index.
- Logic:
- Loop
iterations times.
- Wait a bit between runs to cool down.
- Collect numbers.
- Sort and pick median.
- Compare.
This looks solid. I will structure the response clearly with these sections. Use TypeScript/JS (ESM) for modern feel, or stick to JS for simplicity? JS is more accessible for CI scripts usually. I'll stick to Node.js.
Let's refine the "Release Approval" aspect.
To make this a true approval gate, the script must output a specific file or status that the CI uses.
I'll add a "Report Generator" part to the script that outputs a lighthouse-report.md which can be posted as a PR comment.
Final check on "Flake Mitigation":
Simply running N times isn't enough if the machine is overloaded. I should advise running this on a dedicated runner or standardizing CPU usage. I will add a note about docker or CI runner resources.
Let's generate the response.
This solution engineers a robust CI gate using a custom Node.js script. While tools like Lighthouse CI (LHCI) exist, writing a custom gate script provides granular control over flake mitigation (statistical analysis of multiple runs) and conditional release approvals.
Architecture Overview
- Budgets: Defined in a JSON config file.
- Flake Mitigation: Instead of one run, we execute N runs and calculate the Median (P50) for every metric. This filters out statistical outliers common in CI environments.
- Release Gate: The script exits with code
1 (blocking the pipeline) if the Median value violates the budget.
- Reporting: Generates a Markdown report for the Pull Request.
1. The Configuration (lighthouse.config.json)
Define your performance budgets and audit targets here.
{
"url": "http://localhost:3000",
"runs": 5,
"budgets": {
"performance-score": { "max": 0.9, "unit": "score" },
"largest-contentful-paint": { "max": 2500, "unit": "ms" },
"cumulative-layout-shift": { "max": 0.1, "unit": "unitless" },
"total-blocking-time": { "max": 300, "unit": "ms" }
}
}
2. The Engine (lighthouse-gate.js)
This script handles browser spinning, result aggregation, and gating logic.
const lighthouse = require('lighthouse');
const chromeLauncher = require('chrome-launcher');
const fs = require('fs');
const path = require('path');
// Load Config
const configPath = path.resolve(process.cwd(), 'lighthouse.config.json');
const config = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
const { url, runs, budgets } = config;
// Helper: Calculate Median (P50) to mitigate flakes
const getMedian = (arr) => {
const sorted = [...arr].sort((a, b) => a - b);
const mid = Math.floor(sorted.length / 2);
return sorted.length % 2 !== 0 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;
};
// Helper: Extract specific metrics from Lighthouse Result Object
const extractMetrics = (lhr) => {
const { audits } = lhr;
// Helper to get numeric value safely
const getValue = (id) => {
const audit = audits[id];
if (!audit) return null;
// Handle different types of metric returns (seconds vs ms vs score)
if (id.includes('score')) return audit.score; // 0-1 range
return audit.numericValue; // ms or unitless
};
return {
'performance-score': getValue('performance-score') ?? lhr.categories.performance.score,
'largest-contentful-paint': getValue('largest-contentful-paint'),
'cumulative-layout-shift': getValue('cumulative-layout-shift'),
'total-blocking-time': getValue('total-blocking-time'),
};
};
async function runLighthouseGate() {
console.log(`🚦 Starting Lighthouse Gate for ${url}`);
console.log(`Executing ${runs} runs for flake mitigation...`);
let chrome;
try {
chrome = await chromeLauncher.launch({ chromeFlags: ['--headless', '--no-sandbox'] });
const opts = {
logLevel: 'error',
output: 'json',
port: chrome.port,
onlyCategories: ['performance'] // Focus on performance for speed
};
const metricsHistory = [];
// Run Loop
for (let i = 0; i < runs; i++) {
console.log(`Run ${i + 1}/${runs}...`);
try {
const runnerResult = await lighthouse(url, opts);
const metrics = extractMetrics(runnerResult.lhr);
metricsHistory.push(metrics);
} catch (runError) {
console.warn(`⚠️ Run ${i + 1} failed: ${runError.message}`);
// Optionally push null to track failure rate, or just skip
}
}
await chrome.kill();
if (metricsHistory.length === 0) {
throw new Error('All Lighthouse runs failed. Check connectivity or config.');
}
// Aggregate Results
const aggregated = {};
const metricKeys = Object.keys(budgets);
metricKeys.forEach(key => {
const values = metricsHistory.map(m => m[key]).filter(v => v !== null);
if (values.length > 0) {
aggregated[key] = getMedian(values);
} else {
aggregated[key] = Infinity; // Fail safe
}
});
// Evaluate Gate
let passed = true;
const reportLines = ["## 🛑 Lighthouse Performance Gate\n"];
metricKeys.forEach(key => {
const value = aggregated[key];
const budget = budgets[key].max;
const isScore = budgets[key].unit === 'score';
// Logic: Score must be >= budget, Metrics must be <= budget
const isPass = isScore ? (value >= budget) : (value <= budget);
const status = isPass ? '✅' : '❌';
const displayValue = isScore ? `${(value * 100).toFixed(0)}` : `${value.toFixed(2)}`;
const displayBudget = isScore ? `${(budget * 100).toFixed(0)}` : `${budget}`;
if (!isPass) passed = false;
reportLines.push(
`**${status} ${key}**: ${displayValue} (Budget: ${displayBudget})`
);
});
// Output Markdown Report for CI (e.g., GitHub Actions)
console.log('---REPORT_START---');
console.log(reportLines.join('\n'));
console.log('---REPORT_END---');
if (!passed) {
console.error("🚫 Gate Failed: Performance budgets exceeded.");
process.exit(1);
} else {
console.log("✅ Gate Passed: Release approved.");
process.exit(0);
}
} catch (error) {
console.error('Fatal Error in Gate:', error);
process.exit(1);
}
}
runLighthouseGate();
3. CI Integration (GitHub Actions Example)
This workflow demonstrates how to inject the gate into a pipeline, post the comment to the PR, and upload artifacts for regression analysis.
File: .github/workflows/performance-gate.yml
name: Lighthouse Performance Gate
on:
pull_request:
branches: [main]
jobs:
gate:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Setup Node
uses: actions/setup-node@v3
with:
node-version: 18
- name: Install Dependencies
run: npm ci
# Install Lighthouse Engine requirements
- name: Install Audit Tools
run: npm install -g lighthouse chrome-launcher
- name: Build Application
run: npm run build
- name: Run Server & Lighthouse Gate
uses: JakobMiksch/easy-parallelization@v1.2.0
with:
# Start the app server
start: npm run start
# Wait for port, then run the gate script
command: node lighthouse-gate.js
wait-on: 'http://localhost:3000'
- name: Post Result to PR
if: always()
uses: actions/github-script@v6
with:
script: |
const output = `${process.env.LH_OUTPUT}`;
// In a real implementation, capture the script stdout
// to a file or env var between steps.
// Here we assume we parsed the markdown report.
github.rest.issues.createComment({
issue_number: context.issue.number,
owner: context.repo.owner,
repo: context.repo.repo,
body: "### Lighthouse Results\n" + output
})
4. Engineering Features Explained
1. Median vs Average (Flake Mitigation)
Performance data is rarely normally distributed; it is often skewed by garbage collection or network jitter.
- The Engineer's Choice: We use Median (P50).
- If we run 5 tests and LCP is
[1200, 1250, 5000, 1180, 1220] (where 5000 is a fluke), the Average is 1970 (Fail), but the Median is 1220 (Pass). The gate ignores the outlier, preventing false-negative build failures.
2. The Approval Mechanism
- Hard Gate: The script utilizes
process.exit(1). This signals standard CI runners (Jenkins, GitHub, GitLab, CircleCI) that the step failed, immediately blocking the artifact from progressing to the next stage (e.g., deployment to production).
- Configurable Thresholds: By separating config into JSON, non-engineers (PMs/QA) can adjust budgets without touching the logic code.
3. Deterministic Environment
To reduce flakes further, ensure the CI runner is consistent:
- Use a dedicated runner class (e.g.,
runs-on: ubuntu-latest).
- The script flags
--headless and --no-sandbox (essential for Docker/CI environments).
- Note: For ultimate stability, you would wrap the
chrome-launcher options to throttle CPU (e.g., --cpu-throttling=4) to simulate a mid-tier mobile device, making the gate more realistic than a high-powered CI server.
4. How to Run
- Install dependencies:
npm install lighthouse chrome-launcher
- Start your local dev server:
npm start
- Run the gate:
node lighthouse-gate.js