We are going to create a baseline performance harness. The goal is to have a system that:
- Profiles the current performance of a system (or application) to establish a baseline.
- Sets budgets (thresholds) for various performance metrics.
- Detects regressions by comparing current runs against the baseline and budgets.
Steps:
-
Profiling: We need to define what to measure and how to measure it.
- Common metrics: load time, first contentful paint, time to interactive, etc. for web apps.
- For other systems, it might be different (e.g., API response times, database query times, etc.)
-
Baseline Establishment: Run the profiler multiple times (to account for variability) and compute a baseline (e.g., median or average).
-
Budgets: Set acceptable thresholds (budgets) for each metric. These could be absolute values or relative to the baseline (e.g., 10% slower than baseline).
-
Regression Detection: In subsequent runs, compare the metrics against the baseline and budgets. If a metric exceeds the budget, flag as regression.
-
Reporting: Generate a report that shows the current metrics, baseline, and whether there's a regression.
-
Automation: This should be automated, perhaps as part of a CI/CD pipeline.
Implementation Plan:
We'll design a simple harness in Python (for example) that can be adapted to the specific context.
Steps in code:
a. Define the metrics we want to measure and how to measure them. (We'll assume we have a way to get a dictionary of metrics.)
b. Collect data for the baseline: run the measurement N times (e.g., 5) and compute the median (or mean) for each metric.
c. Define budgets: For each metric, we can have:
- absolute_budget: a fixed number (e.g., 2000ms for load time)
- relative_budget: a percentage (e.g., 110% of baseline)
We can combine: if both are defined, use the stricter one (or one of them). Alternatively, we can have one type.
d. For each run (including baseline runs and subsequent runs), we record the metrics.
e. Compare the current run (or median of multiple runs) against the baseline and budgets.
f. Output a report.
Let's design a class:
class PerfHarness:
def __init__(self, metrics_budgets):
"""
metrics_budgets: a dict where key is metric name and value is a dict with:
- 'absolute': optional absolute budget (float)
- 'relative': optional relative budget (e.g., 1.1 for 110%)
"""
self.metrics_budgets = metrics_budgets
self.baseline = None # will be a dict of metric: baseline_value
def collect_sample(self):
"""
This method should be implemented by the user or overridden to collect one sample of metrics.
Returns a dict of metric_name: value.
"""
raise NotImplementedError
def collect_baseline(self, runs=5):
"""
Collect multiple samples and compute the median for each metric to establish baseline.
"""
samples = []
for _ in range(runs):
sample = self.collect_sample()
samples.append(sample)
# Transpose to get list of values for each metric
metrics = samples[0].keys()
baseline = {}
for metric in metrics:
values = [s[metric] for s in samples]
baseline[metric] = np.median(values) # using numpy for median, or we can use statistics.median
self.baseline = baseline
return baseline
def check_budget(self, metric, value):
"""
Check if the given value for a metric is within budget.
Returns (within_budget, budget_value, baseline_value)
"""
if self.baseline is None:
raise ValueError("Baseline not set. Call collect_baseline first.")
baseline_val = self.baseline[metric]
budget_config = self.metrics_budgets.get(metric, {})
# Determine the budget limit
budget_limit = None
if 'absolute' in budget_config:
budget_limit = budget_config['absolute']
if 'relative' in budget_config:
relative_limit = baseline_val * budget_config['relative']
if budget_limit is None or relative_limit < budget_limit:
budget_limit = relative_limit
# If no budget defined, then we don't have a limit? We can treat as always within budget.
if budget_limit is None:
return (True, None, baseline_val)
within_budget = value <= budget_limit
return (within_budget, budget_limit, baseline_val)
def run_and_check(self, runs=1):
"""
Collect one or more runs (usually one for a check) and compare against baseline and budgets.
If multiple runs, we can take the median of the current runs? But typically we might want to run once and check.
However, to account for variability, we might run multiple times and take median for the check too.
Let's assume we run `runs` times and take median for current.
"""
samples = []
for _ in range(runs):
sample = self.collect_sample()
samples.append(sample)
current = {}
metrics = samples[0].keys()
for metric in metrics:
values = [s[metric] for s in samples]
current[metric] = np.median(values)
results = {}
for metric, value in current.items():
within_budget, budget_limit, baseline_val = self.check_budget(metric, value)
results[metric] = {
'current': value,
'baseline': baseline_val,
'budget': budget_limit,
'within_budget': within_budget
}
return results
def generate_report(self, results):
"""
Generate a human-readable report from the results dict.
"""
report_lines = []
for metric, data in results.items():
status = "PASS" if data['within_budget'] else "FAIL"
report_lines.append(f"{metric}: {data['current']:.2f} (baseline: {data['baseline']:.2f}, budget: {data['budget']}) - {status}")
return "\n".join(report_lines)
However, note: In a real scenario, the collect_sample method would be specific to the application.
Example for a web page (using Lighthouse or similar):
import subprocess
import json
class WebPerfHarness(PerfHarness):
def collect_sample(self):
# Run lighthouse and parse the output
# This is just an example, we assume lighthouse is installed and we can run it.
cmd = ["lighthouse", self.url, "--output=json", "--quiet"]
result = subprocess.run(cmd, capture_output=True, text=True)
data = json.loads(result.stdout)
metrics = data['audits']['metrics']['details']['items'][0]
# We are interested in:
# firstContentfulPaint, speedIndex, largestContentfulPaint, interactive, etc.
# But note: lighthouse gives many metrics. We can map to our names.
# Let's assume we have a mapping.
mapping = {
'first_contentful_paint': metrics['firstContentfulPaint'],
'speed_index': metrics['speedIndex'],
'largest_contentful_paint': metrics['largestContentfulPaint'],
'interactive': metrics['interactive']
}
return mapping
But note: The above is just an example and might not be the best way (lighthouse might take a while and we might want to run in headless chrome, etc.)
Alternatively, we can use a tool that is faster and more suitable for CI, like webpagetest or sitespeed.io.
However, the harness is designed to be generic.
Another note: We might want to store the baseline in a file so that we can use it across runs.
Let's add:
def save_baseline(self, filename):
with open(filename, 'w') as f:
json.dump(self.baseline, f)
def load_baseline(self, filename):
with open(filename, 'r') as f:
self.baseline = json.load(f)
But note: the baseline might be a dict with string keys and float values, so JSON is fine.
We can also consider:
- Having a way to update the baseline if we intentionally change it (e.g., after a performance improvement).
- Having a way to set budgets per metric in a configuration file.
Let's adjust the init to also take a config file.
Alternatively, we can have a separate configuration step.
But for simplicity, we'll keep the budgets in the code or passed as a dict.
However, for a real project, we might want to have a YAML or JSON configuration.
Example config.yaml:
budgets:
first_contentful_paint:
absolute: 2000
relative: 1.1
speed_index:
absolute: 3000
Then we can load that.
But note: the harness should be flexible.
Let's change the init to:
def __init__(self, config):
"""
config: a dict with:
- 'budgets': as above
- optionally, 'baseline_file': to load/save baseline
"""
self.metrics_budgets = config.get('budgets', {})
self.baseline_file = config.get('baseline_file', None)
self.baseline = None
if self.baseline_file:
self.load_baseline(self.baseline_file)
Then in collect_baseline, after computing, if self.baseline_file is set, save it.
But wait: we might not want to overwrite the baseline every time we run collect_baseline?
Actually, we want to set the baseline once and then use it. So maybe we have:
def set_baseline(self, baseline_dict):
self.baseline = baseline_dict
if self.baseline_file:
self.save_baseline(self.baseline_file)
and collect_baseline returns the computed baseline and then we call set_baseline?
Alternatively, we can have:
baseline = self.collect_baseline(runs=5)
self.set_baseline(baseline)
But note: the user might want to manually adjust the baseline? Then we can have:
self.baseline = manually_set_baseline
So, we can have:
def set_baseline(self, baseline_dict):
self.baseline = baseline_dict
if self.baseline_file:
self.save_baseline(self.baseline_file)
and then:
# To establish a new baseline:
new_baseline = harness.collect_baseline(runs=5)
harness.set_baseline(new_baseline)
# Or load from file in __init__.
However, note that the baseline might be computed from multiple runs and then we set it. We don't want to automatically save on collect_baseline because we might want to review first.
So, let's change:
def collect_baseline(self, runs=5):
... compute ...
return baseline # but not set self.baseline
Then the user does:
baseline = harness.collect_baseline()
# review or adjust
harness.set_baseline(baseline)
But then we have to set the baseline before running checks.
Alternatively, we can have:
def establish_baseline(self, runs=5, save=True):
baseline = self.collect_baseline(runs)
self.set_baseline(baseline)
if save and self.baseline_file:
self.save_baseline()
and then:
def set_baseline(self, baseline_dict):
self.baseline = baseline_dict
if self.baseline_file:
self.save_baseline()
But then we are saving twice? Let's avoid that.
Alternatively, we can have:
def set_baseline(self, baseline_dict, save=True):
self.baseline = baseline_dict
if save and self.baseline_file:
self.save_baseline()
Then:
baseline = harness.collect_baseline(runs=5)
harness.set_baseline(baseline, save=True) # this will save if baseline_file is set.
But note: the user might want to set a baseline without saving? Then save=False.
Also, we might want to load without setting? Actually, in __init__ we load and set.
Let's adjust __init__:
if self.baseline_file:
try:
self.load_baseline(self.baseline_file)
except FileNotFoundError:
# No baseline yet, that's okay.
pass
Then we can run without an existing baseline? But then check will fail because baseline is None.
So we must set baseline before checking.
Alternatively, we can allow checking without baseline? But then we cannot compute relative budgets.
So, we require baseline to be set.
We can also have a mode that only uses absolute budgets without baseline? But then the relative budget doesn't make sense.
Let's require baseline if there is any relative budget.
In check_budget, if baseline is None and we need relative, then error.
We can also allow absolute without baseline.
So, in check_budget:
if 'relative' in budget_config:
if self.baseline is None:
raise ValueError("Baseline required for relative budget on metric: {}".format(metric))
... compute relative ...
And if there's no baseline and only absolute, then we can use absolute.
But then we might have both absolute and relative? We take the stricter (lower) one.
However, without baseline, we cannot compute relative.
So, in check_budget:
budget_limit = None
if 'absolute' in budget_config:
budget_limit = budget_config['absolute']
if 'relative' in budget_config:
if self.baseline is None:
raise ValueError("Baseline required for relative budget on metric: {}".format(metric))
relative_limit = self.baseline[metric] * budget_config['relative']
if budget_limit is None or relative_limit < budget_limit:
budget_limit = relative_limit
This works.
But note: what if the metric is not in the baseline? Then we have a problem.
We should check that the metric exists in the baseline when we set the baseline?
Actually, when we set the baseline, we set a dict of metrics. Then when we check, we expect the same metrics?
We can have a list of required metrics?
Alternatively, we can be flexible and only check the metrics that are in the budget config.
But note: the sample might have more metrics than we have budgets for? Then we ignore the extra ones.
So in run_and_check, we only check the metrics that are in self.metrics_budgets.
But what if a metric in the budget is not in the sample? Then we get a KeyError.
We should handle that.
Let's adjust run_and_check:
for metric in self.metrics_budgets.keys():
if metric not in current:
# We don't have a value for this metric. We can skip and mark as not within budget? Or error?
# Let's mark as not within budget and set current to None? But then we cannot compare.
# We can skip and warn? Or we can treat as failure because we don't have data.
# Let's treat as failure and set current to None.
results[metric] = {
'current': None,
'baseline': self.baseline.get(metric, None),
'budget': budget_limit, # but we haven't computed budget_limit because we don't have value?
'within_budget': False
}
else:
... compute ...
But note: we are iterating over metrics in the budget config, so we might have a metric in the budget that is not in the current sample.
Alternatively, we can iterate over the intersection of current and budget config.
Let's do:
metrics_to_check = set(current.keys()) & set(self.metrics_budgets.keys())
Then for each metric in metrics_to_check, we check.
And for metrics in the budget that are missing, we can add a result with current=None and within_budget=False.
So:
results = {}
# First, for all metrics in budget, we want to report even if missing.
for metric in self.metrics_budgets.keys():
if metric in current:
value = current[metric]
within_budget, budget_limit, baseline_val = self.check_budget(metric, value)
results[metric] = {
'current': value,
'baseline': baseline_val,
'budget': budget_limit,
'within_budget': within_budget
}
else:
results[metric] = {
'current': None,
'baseline': self.baseline.get(metric, None) if self.baseline else None,
'budget': None, # we cannot compute budget without current? Actually we can compute from baseline and config.
'within_budget': False
}
But note: in check_budget we compute budget_limit based on current value and baseline. Without current value, we cannot compute.
Alternatively, we can compute the budget limit without the current value? Yes, because budget is independent of current.
So we can compute budget_limit in the missing case:
budget_config = self.metrics_budgets[metric]
budget_limit = None
if 'absolute' in budget_config:
budget_limit = budget_config['absolute']
if 'relative' in budget_config:
if self.baseline is None:
raise ValueError("Baseline required for relative budget on metric: {}".format(metric))
relative_limit = self.baseline[metric] * budget_config['relative']
if budget_limit is None or relative_limit < budget_limit:
budget_limit = relative_limit
Then we can set:
results[metric] = {
'current': None,
'baseline': self.baseline.get(metric, None) if self.baseline else None,
'budget': budget_limit,
'within_budget': False # because we don't have a value, so we assume it's over budget? Actually, we don't know.
}
But it's better to treat missing metric as a failure because we cannot measure.
So, let's do:
within_budget = False # because we don't have a current value to compare.
And in the report, we say "NO DATA".
Alternatively, we can have a separate status for missing.
Let's change:
'status': 'missing' instead of within_budget.
But then we have to change the report.
Alternatively, we can have:
results[metric] = {
'current': None,
'baseline': ...,
'budget': ...,
'status': 'missing' # or 'no_data'
}
And then in the report, we handle.
However, to keep it simple, let's just set within_budget to False and current to None.
Then in the report, we can print:
if current is None:
print(f"{metric}: NO DATA (baseline: {baseline}, budget: {budget}) - FAIL (no data)")
But then we have two types of failure: over budget and no data.
We can have:
if current is None:
status = "FAIL (no data)"
else:
status = "PASS" if within_budget else "FAIL"
Let's adjust generate_report accordingly.
However, note: the user might have a metric that is not in the baseline? Then baseline_val might be None.
We should handle that too.
Actually, in check_budget we already handle relative budget requiring baseline. But absolute budget does not require baseline.
So, let's adjust:
In check_budget, if the metric is not in the baseline and we need it for relative, we raise.
But what if the metric is in the baseline? Then we are fine.
However, when we set the baseline, we set a dict. So if a metric is missing in the baseline dict, then self.baseline[metric] will raise.
We can use .get(metric) and if None, then we don't have baseline for that metric.
But then relative budget cannot be used.
So, in check_budget:
if 'relative' in budget_config:
baseline_val = self.baseline.get(metric)
if baseline_val is None:
raise ValueError("Baseline value for metric '{}' is missing. Cannot compute relative budget.".format(metric))
... compute ...
And for absolute, we don't need baseline.
Now, in the run_and_check, when we compute the result for a metric that is in the current sample, we call check_budget.
But if the metric is not in the baseline and we have a relative budget, check_budget will raise.
So we must ensure that the baseline dict has all the metrics that we have relative budgets for.
How to enforce? We can check at the time of setting the baseline:
def set_baseline(self, baseline_dict):
# Check that for every metric with relative budget, we have a value in baseline_dict.
for metric, config in self.metrics_budgets.items():
if 'relative' in config:
if metric not in baseline_dict:
raise ValueError("Baseline missing for metric '{}' which has a relative budget.".format(metric))
self.baseline = baseline_dict
...
That's good.
Now, what about metrics that are in the baseline but not in the current sample? We already handled.
Let's code accordingly.
However, note: the baseline might have more metrics than we have budgets for? That's okay.
We only check the ones in the budget config.
But what if we want to track a metric that is not in the budget? We don't check it.
So, the budget config defines which metrics we care about.
We can also have a list of metrics to always collect? But that's in the collect_sample.
Let's assume collect_sample returns a dict with all the metrics we might want.
Then we only check the ones in the budget config.
This seems reasonable.
Now, let's code the class with these considerations.
We'll use the standard library's json and statistics.median (if we don't want to require numpy).
But note: statistics.median requires at least one data point. We are running multiple times, so it's okay.
However, for simplicity, we'll use statistics.median.
Steps:
- In __init__, we set up the budgets and baseline file, and try to load baseline if file exists.
- collect_baseline: run the sample collection `runs` times, and compute the median for each metric that appears in all runs?
Actually, we assume the same keys in every run. If not, we can only compute for the intersection.
Let's compute for the intersection of keys across all runs? Or for the keys of the first run?
We want to establish a baseline for the metrics we care about (the ones in the budget). But what if a metric is missing in one run?
We can skip that run for that metric? But then we have missing values.
Alternatively, we can fail if any run is missing a metric that we expect?
Since we are establishing a baseline, we want consistent metrics.
Let's do:
all_metrics = set(samples[0].keys())
for sample in samples[1:]:
all_metrics = all_metrics & set(sample.keys())
Then we only compute for metrics in all_metrics.
But what if we have a budget for a metric that is not in all_metrics? Then we cannot set baseline for that metric.
We can raise an error.
Alternatively, we can set baseline only for the metrics that are in all_metrics and in the budget?
But then we might not have baseline for a metric that is in the budget but missing in one run.
We can try to run again? Or we can fail.
Let's fail and tell the user.
So:
for metric in self.metrics_budgets.keys():
if metric not in all_metrics:
raise ValueError("Metric '{}' is in the budget but not present in all baseline runs.".format(metric))
Then we compute baseline only for the metrics in the budget that are also in all_metrics.
But wait, what if the budget has a metric that we don't collect? Then it's not in the samples at all.
We should check that the budget metrics are in the first sample? Actually, we are checking against all_metrics.
So, we can do:
required_metrics = set(self.metrics_budgets.keys())
if not required_metrics.issubset(all_metrics):
missing = required_metrics - all_metrics
raise ValueError("Missing metrics in baseline runs: {}".format(missing))
Then we compute baseline for all_metrics (or just the required ones?).
Actually, we might want to compute baseline for all metrics that are in all_metrics, even if not in the budget?
But we don't need them for checking. However, we might want to store them for future reference?
Let's compute baseline for all metrics that are in all_metrics, and then when setting baseline, we only set the ones we need?
But then if we later add a budget for a metric that was collected but not in the budget, we don't have baseline.
So, we can store the entire baseline (for all metrics in all_metrics) and then in check_budget we use self.baseline[metric] if it exists.
But if we have a budget for a metric that is not in the baseline, then we don't have baseline for it.
So, in set_baseline, we should only set the baseline for the metrics that are in the baseline dict?
Actually, we computed the baseline for all_metrics. Then we set self.baseline = {metric: median for metric in all_metrics}.
Then, when we add a new budget for a metric that was already collected, we have baseline.
But if we add a new metric to the budget that was not collected before, we don't have baseline.
So, we must re-establish baseline for that metric? Or we can run the baseline collection again for that metric?
Alternatively, we can have a separate way to set baseline for a single metric?
For simplicity, we assume that the baseline collection collects all the metrics we care about (the ones in the budget) and we set the baseline for all of them.
So, in collect_baseline, we require that the budget metrics are present in all runs.
Then we set baseline for all the metrics that are in all_metrics? Or only the ones in the budget?
Let's set baseline for all the metrics that are in all_metrics. Then if we later add a budget for a metric that was collected, we have baseline.
But note: the baseline might have changed for that metric? We collected the baseline at a certain time.
So, we are storing the baseline for all metrics that were collected. Then when we add a new budget, we use that stored baseline.
However, that baseline might be old. But that's the same for all metrics.
Alternatively, we can only store the baseline for the metrics in the budget?
But then if we add a new budget, we have to re-run baseline.
Let's do:
In collect_baseline, we compute the median for every metric that is in every run.
Then we set self.baseline to that entire dict.
Then in set_baseline, we save the entire dict.
And in check_budget, we use self.baseline[metric] if the metric is in the baseline, else we treat as missing.
But then if a metric is in the budget but not in the baseline (because it wasn't collected in the baseline runs), then we cannot use relative budget.
And we already check in set_baseline that for every relative budget, the metric is in the baseline_dict.
So, when we set the baseline, we are setting a dict that must contain all metrics with relative budgets.
But what about absolute budgets? They don't require baseline.
So, we can have:
In set_baseline:
for metric, config in self.metrics_budgets.items():
if 'relative' in config and metric not in baseline_dict:
raise ...
Then we set self.baseline = baseline_dict.
And in check_budget, we use self.baseline[metric] for relative, and for absolute we don't need baseline.
This seems okay.
Now, what about metrics that are in the baseline but not in the budget? We store them, but we don't use them for checking.
That's fine.
Let's code accordingly.
However, note: the baseline collection might collect more metrics than we have in the budget. We store them all.
But when we save the baseline, we save the entire dict. Then when we load, we load the entire dict.
And then we check only the metrics in the budget.
This is flexible.
Now, let's code the class.
We'll use:
import json
import statistics
And we'll assume the sample collection returns a dict with numeric values.
We'll also assume that the same set of metrics is returned every time.
But we already handle the case where a metric is missing in one run? We are requiring that all runs have the same keys (the intersection).
So, we are being strict: all baseline runs must have the same set of metrics.
Alternatively, we can compute the median only for the metrics that are present in all runs, and then require that the budget metrics are in that set.
That's what we are doing.
Let's code:
Steps in collect_baseline:
samples = [self.collect_sample() for _ in range(runs)]
# Get the intersection of keys
common_metrics = set(samples[0].keys())
for sample in samples[1:]:
common_metrics = common_metrics & set(sample.keys())
# Compute median for each metric in common_metrics
baseline = {}
for metric in common_metrics:
values = [s[metric] for s in samples]
baseline[metric] = statistics.median(values)
return baseline
Then in set_baseline, we check that for every metric with a relative budget, it is in the baseline dict.
But note: the baseline dict might have more metrics than the budget, that's okay.
Now, let's code the entire class.
We'll also add a method to print the baseline.
And we'll adjust run_and_check to run multiple times and take median for the current run?
We are already doing that.
But note: the baseline was computed from multiple runs, and the current run is also multiple runs?
We can run the current check multiple times and take median? We are already doing that.
However, the baseline was computed from 5 runs, and the current check might be from 1 run?
We can let the user specify the number of runs for the current check.
But note: the baseline and current should be comparable. So if we use median for baseline, we should use median for current.
We are doing that.
Now, let's code.
We'll also add a method to run a single sample and return it, for debugging.
And we might want to output the raw samples? But for now, we just output the median.
Let's code.
Note: We are using the `statistics` module, which is in the standard library.
We'll also handle the case where there are no samples? But we are running `runs` times, so at least one.
Let's code the class.
We'll also add a way to update the baseline without re-running? That is, set_baseline with a dict.
And we can load from a file that has the baseline dict.
Now, let's code.</think>
I'll create a comprehensive performance harness with profiling, budgeting, and regression detection. Here's a complete implementation:
Performance Harness Framework
1. Configuration File (perf-config.yaml)
# Performance budgets and thresholds
budgets:
metrics:
- name: "first_contentful_paint"
absolute_max_ms: 1800
relative_warning_pct: 10 # Warn if >10% slower than baseline
relative_fail_pct: 20 # Fail if >20% slower than baseline
- name: "largest_contentful_paint"
absolute_max_ms: 2500
relative_warning_pct: 15
- name: "cumulative_layout_shift"
absolute_max: 0.1
- name: "first_input_delay"
absolute_max_ms: 100
- name: "time_to_interactive"
absolute_max_ms: 3000
# Profiling configuration
profiling:
tools:
- "lighthouse"
- "webpagetest"
- "perf_logging"
runs_per_environment: 5
environments:
- "chrome_latest"
- "chrome_stable"
- "firefox_latest"
- "safari_latest"
- "mobile_emulation"
# Regression thresholds
regression:
significance_level: 0.05 # 95% confidence
min_change_pct: 5 # Minimum change to consider
ignore_metrics: ["cumulative_layout_shift"] # Metrics with high variance
# Storage
storage:
type: "postgresql" # or "json", "bigquery"
connection: "${DB_CONNECTION_STRING}"
baseline_table: "performance_baselines"
results_table: "performance_results"
# Alerting
alerts:
slack_webhook: "${SLACK_WEBHOOK}"
email_recipients: ["team@example.com"]
on_failure: true
on_warning: false
2. Core Harness Implementation (perf_harness.py)
#!/usr/bin/env python3
"""
Performance Baseline Harness
Profiles, budgets, and detects regressions
"""
import json
import yaml
import argparse
import logging
import statistics
import dataclasses
from datetime import datetime
from typing import Dict, List, Optional, Tuple
from pathlib import Path
from dataclasses import dataclass
from abc import ABC, abstractmethod
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
@dataclass
class MetricResult:
"""Single metric result from a performance run"""
name: str
value: float
unit: str
timestamp: datetime
environment: str
url: str
run_id: int
def to_dict(self):
return dataclasses.asdict(self)
@dataclass
class Baseline:
"""Baseline statistics for a metric"""
metric_name: str
environment: str
median: float
p95: float
p99: float
std_dev: float
sample_count: int
created_at: datetime
def to_dict(self):
return dataclasses.asdict(self)
def within_absolute_budget(self, value: float, absolute_max: float) -> Tuple[bool, str]:
"""Check if value is within absolute budget"""
if value <= absolute_max:
return True, "pass"
return False, f"exceeds budget by {value - absolute_max:.2f}{self._get_unit()}"
def within_relative_budget(self, value: float, threshold_pct: float) -> Tuple[bool, str, float]:
"""Check if value is within relative budget (compared to median)"""
change_pct = ((value - self.median) / self.median) * 100 if self.median != 0 else 0
if change_pct <= threshold_pct:
return True, "pass", change_pct
return False, f"{change_pct:.1f}% slower than baseline", change_pct
def _get_unit(self) -> str:
"""Infer unit from metric name (simplified)"""
if 'ms' in self.metric_name or 'delay' in self.metric_name:
return 'ms'
return ''
class Profiler(ABC):
"""Abstract base class for profilers"""
@abstractmethod
def profile(self, url: str, runs: int = 1) -> List[MetricResult]:
"""Profile a URL and return metric results"""
pass
@abstractmethod
def get_supported_metrics(self) -> List[str]:
"""Get list of supported metrics"""
pass
class LighthouseProfiler(Profiler):
"""Lighthouse-based profiler"""
def get_supported_metrics(self) -> List[str]:
return [
'first_contentful_paint',
'largest_contentful_paint',
'cumulative_layout_shift',
'first_input_delay',
'time_to_interactive',
'speed_index'
]
def profile(self, url: str, runs: int = 1) -> List[MetricResult]:
"""Run Lighthouse and extract metrics"""
results = []
for run in range(runs):
# In production, use subprocess to run lighthouse
# For demo, simulate results
mock_metrics = self._simulate_lighthouse_results(url)
for metric_name, value in mock_metrics.items():
result = MetricResult(
name=metric_name,
value=value,
unit='ms' if 'ms' in metric_name else '',
timestamp=datetime.utcnow(),
environment='chrome_latest',
url=url,
run_id=run
)
results.append(result)
return results
def _simulate_lighthouse_results(self, url: str) -> Dict[str, float]:
"""Simulate Lighthouse results for demo"""
import random
return {
'first_contentful_paint': random.uniform(800, 2200),
'largest_contentful_paint': random.uniform(1500, 3500),
'cumulative_layout_shift': random.uniform(0.01, 0.15),
'first_input_delay': random.uniform(30, 150),
'time_to_interactive': random.uniform(2000, 4500),
'speed_index': random.uniform(2000, 4000)
}
class StorageBackend(ABC):
"""Abstract storage backend"""
@abstractmethod
def save_baseline(self, baseline: Baseline):
pass
@abstractmethod
def load_baseline(self, metric_name: str, environment: str) -> Optional[Baseline]:
pass
@abstractmethod
def save_results(self, results: List[MetricResult]):
pass
@abstractmethod
def get_historical_baselines(self, metric_name: str, days: int = 30) -> List[Baseline]:
pass
class JSONStorage(StorageBackend):
"""Simple JSON file storage"""
def __init__(self, filepath: str = "perf_data.json"):
self.filepath = Path(filepath)
self._data = self._load()
def _load(self) -> Dict:
if self.filepath.exists():
with open(self.filepath, 'r') as f:
return json.load(f)
return {"baselines": [], "results": []}
def _save(self):
with open(self.filepath, 'w') as f:
json.dump(self._data, f, indent=2, default=str)
def save_baseline(self, baseline: Baseline):
baseline_dict = baseline.to_dict()
baseline_dict['created_at'] = baseline_dict['created_at'].isoformat()
# Remove existing baseline for same metric+environment
self._data['baselines'] = [
b for b in self._data['baselines']
if not (b['metric_name'] == baseline.metric_name and
b['environment'] == baseline.environment)
]
self._data['baselines'].append(baseline_dict)
self._save()
def load_baseline(self, metric_name: str, environment: str) -> Optional[Baseline]:
for b in self._data['baselines']:
if (b['metric_name'] == metric_name and
b['environment'] == environment):
b['created_at'] = datetime.fromisoformat(b['created_at'])
return Baseline(**b)
return None
def save_results(self, results: List[MetricResult]):
for result in results:
result_dict = result.to_dict()
result_dict['timestamp'] = result_dict['timestamp'].isoformat()
self._data['results'].append(result_dict)
self._save()
def get_historical_baselines(self, metric_name: str, days: int = 30) -> List[Baseline]:
cutoff = datetime.utcnow().timestamp() - (days * 86400)
baselines = []
for b in self._data['baselines']:
if b['metric_name'] == metric_name:
b_time = datetime.fromisoformat(b['created_at']).timestamp()
if b_time > cutoff:
b['created_at'] = datetime.fromisoformat(b['created_at'])
baselines.append(Baseline(**b))
return baselines
class PerformanceHarness:
"""Main performance harness"""
def __init__(self, config_path: str, storage: StorageBackend, profiler: Profiler):
with open(config_path, 'r') as f:
self.config = yaml.safe_load(f)
self.storage = storage
self.profiler = profiler
self.budgets = self.config['budgets']['metrics']
# Validate profiler supports all budgeted metrics
supported = set(profiler.get_supported_metrics())
budgeted = set(m['name'] for m in self.budgets)
unsupported = budgeted - supported
if unsupported:
logger.warning(f"Profiler doesn't support these metrics: {unsupported}")
def establish_baseline(self, url: str, environment: str, runs: int = None) -> Dict[str, Baseline]:
"""Establish new baseline for all metrics"""
if runs is None:
runs = self.config['profiling']['runs_per_environment']
logger.info(f"Establishing baseline for {url} in {environment} with {runs} runs")
# Collect samples
results = self.profiler.profile(url, runs=runs)
self.storage.save_results(results)
# Calculate statistics per metric
baselines = {}
metric_groups = {}
for result in results:
if result.name not in metric_groups:
metric_groups[result.name] = []
metric_groups[result.name].append(result.value)
for metric_name, values in metric_groups.items():
baseline = self._calculate_baseline(metric_name, environment, values)
baselines[metric_name] = baseline
self.storage.save_baseline(baseline)
logger.info(f"Baseline for {metric_name}: median={baseline.median:.2f}, p95={baseline.p95:.2f}")
return baselines
def check_performance(self, url: str, environment: str, runs: int = None) -> Dict:
"""Run performance check and compare against baseline"""
if runs is None:
runs = self.config['profiling']['runs_per_environment']
logger.info(f"Running performance check for {url} in {environment}")
# Collect current results
current_results = self.profiler.profile(url, runs=runs)
self.storage.save_results(current_results)
# Group by metric
current_by_metric = {}
for result in current_results:
if result.name not in current_by_metric:
current_by_metric[result.name] = []
current_by_metric[result.name].append(result.value)
# Compare against baseline
report = {
'url': url,
'environment': environment,
'timestamp': datetime.utcnow().isoformat(),
'metrics': {},
'summary': {'pass': 0, 'warning': 0, 'fail': 0, 'missing': 0}
}
for metric_config in self.budgets:
metric_name = metric_config['name']
if metric_name not in current_by_metric:
report['metrics'][metric_name] = {
'status': 'missing',
'message': 'Metric not collected'
}
report['summary']['missing'] += 1
continue
current_values = current_by_metric[metric_name]
current_median = statistics.median(current_values)
# Get baseline
baseline = self.storage.load_baseline(metric_name, environment)
if not baseline:
report['metrics'][metric_name] = {
'status': 'no_baseline',
'message': 'No baseline established',
'current_median': current_median
}
report['summary']['missing'] += 1
continue
# Check absolute budget
absolute_ok, absolute_msg = baseline.within_absolute_budget(
current_median,
metric_config.get('absolute_max_ms', metric_config.get('absolute_max', float('inf'))
)
# Check relative budget (if configured)
relative_ok = True
relative_msg = ""
change_pct = 0
if 'relative_warning_pct' in metric_config:
relative_ok, relative_msg, change_pct = baseline.within_relative_budget(
current_median,
metric_config['relative_warning_pct']
)
# Determine final status
status = 'pass'
messages = []
if not absolute_ok:
status = 'fail'
messages.append(f"Absolute budget: {absolute_msg}")
if not relative_ok and metric_name not in self.config['regression']['ignore_metrics']:
if change_pct >= metric_config.get('relative_fail_pct', metric_config['relative_warning_pct'] * 1.5):
status = 'fail'
else:
status = 'warning' if status != 'fail' else status
messages.append(f"Relative: {relative_msg}")
# Check statistical significance
if status in ['warning', 'fail'] and self._is_statistically_significant(
current_values,
[baseline.median] * len(current_values),
self.config['regression']['significance_level']
):
# Significant regression
pass
elif status != 'pass':
# Not significant, downgrade to warning if fail
if status == 'fail':
status = 'warning'
report['metrics'][metric_name] = {
'status': status,
'current_median': current_median,
'baseline_median': baseline.median,
'baseline_p95': baseline.p95,
'absolute_budget': metric_config.get('absolute_max_ms', metric_config.get('absolute_max', 'N/A')),
'change_pct': change_pct,
'messages': messages,
'samples': len(current_values)
}
report['summary'][status] += 1
# Generate alerts if needed
if report['summary']['fail'] > 0:
self._send_alert("PERFORMANCE REGRESSION DETECTED", report)
return report
def _calculate_baseline(self, metric_name: str, environment: str, values: List[float]) -> Baseline:
"""Calculate baseline statistics"""
return Baseline(
metric_name=metric_name,
environment=environment,
median=statistics.median(values),
p95=self._percentile(values, 95),
p99=self._percentile(values, 99),
std_dev=statistics.stdev(values) if len(values) > 1 else 0,
sample_count=len(values),
created_at=datetime.utcnow()
)
def _percentile(self, values: List[float], p: int) -> float:
"""Calculate percentile"""
sorted_values = sorted(values)
k = (len(sorted_values) - 1) * (p / 100)
f = int(k)
c = k - f
if f + 1 < len(sorted_values):
return sorted_values[f] + (sorted_values[f + 1] - sorted_values[f]) * c
return sorted_values[f]
def _is_statistically_significant(self, current: List[float], baseline: List[float],
alpha: float = 0.05) -> bool:
"""
Simple Mann-Whitney U test for non-parametric comparison
(For production, use scipy.stats.mannwhitneyu)
"""
# Simplified: Compare median difference relative to variance
current_median = statistics.median(current)
baseline_median = statistics.median(baseline)
current_std = statistics.stdev(current) if len(current) > 1 else 0
baseline_std = statistics.stdev(baseline) if len(baseline) > 1 else 0
# Effect size (Cohen's d approximation)
pooled_std = ((current_std**2 + baseline_std**2) / 2) ** 0.5
if pooled_std == 0:
return False
effect_size = abs(current_median - baseline_median) / pooled_std
# Rough threshold: effect size > 0.5 and change > min_change_pct
min_change = self.config['regression']['min_change_pct']
change_pct = abs(current_median - baseline_median) / baseline_median * 100 if baseline_median != 0 else 0
return effect_size > 0.5 and change_pct > min_change
def _send_alert(self, title: str, report: Dict):
"""Send alert through configured channels"""
message = self._format_alert_message(report)
if 'slack_webhook' in self.config['alerts']:
self._send_slack_alert(self.config['alerts']['slack_webhook'], title, message)
logger.warning(f"ALERT: {title}\n{message}")
def _format_alert_message(self, report: Dict) -> str:
"""Format alert message"""
lines = [
f"URL: {report['url']}",
f"Environment: {report['environment']}",
f"Timestamp: {report['timestamp']}",
"\nMetric Status:",
]
for metric, data in report['metrics'].items():
if data['status'] != 'pass':
lines.append(f" ❌ {metric}: {data['status'].upper()}")
if 'current_median' in data:
lines.append(f" Current: {data['current_median']:.2f}")
lines.append(f" Baseline: {data['baseline_median']:.2f}")
for msg in data.get('messages', []):
lines.append(f" • {msg}")
lines.append(f"\nSummary: {report['summary']['fail']} failed, "
f"{report['summary']['warning']} warnings, "
f"{report['summary']['missing']} missing")
return "\n".join(lines)
def _send_slack_alert(self, webhook: str, title: str, message: str):
"""Send Slack alert (simplified)"""
try:
import requests
payload = {
"text": f"*{title}*\n{message}",
"username": "Perf Harness",
"icon_emoji": ":rotating_light:"
}
requests.post(webhook, json=payload, timeout=5)
except ImportError:
logger.error("requests package required for Slack alerts")
except Exception as e:
logger.error(f"Failed to send Slack alert: {e}")
def main():
parser = argparse.ArgumentParser(description='Performance Harness')
parser.add_argument('--config', default='perf-config.yaml', help='Config file path')
parser.add_argument('--url', required=True, help='URL to test')
parser.add_argument('--environment', default='chrome_latest', help='Environment name')
parser.add_argument('--action', choices=['baseline', 'check'], required=True,
help='Action to perform')
parser.add_argument('--runs', type=int, help='Number of runs')
parser.add_argument('--output', help='Output report as JSON')
args = parser.parse_args()
# Initialize
storage = JSONStorage()
profiler = LighthouseProfiler()
harness = PerformanceHarness(args.config, storage, profiler)
# Execute
if args.action == 'baseline':
baselines = harness.establish_baseline(args.url, args.environment, args.runs)
print(f"Established {len(baselines)} baselines")
for name, baseline in baselines.items():
print(f" {name}: {baseline.median:.2f} (p95: {baseline.p95:.2f})")
elif args.action == 'check':
report = harness.check_performance(args.url, args.environment, args.runs)
# Print summary
print("\n" + "="*50)
print(f"PERFORMANCE REPORT: {args.url}")
print(f"Environment: {args.environment}")
print(f"Total: {sum(report['summary'].values())} metrics")
print(f"✅ Pass: {report['summary']['pass']}")
print(f"⚠️ Warning: {report['summary']['warning']}")
print(f"❌ Fail: {report['summary']['fail']}")
print(f"❓ Missing: {report['summary']['missing']}")
print("="*50 + "\n")
# Print details
for metric, data in report['metrics'].items():
status_icon = {'pass': '✅', 'warning': '⚠️', 'fail': '❌', 'missing': '❓'}[data['status']]
print(f"{status_icon} {metric}: {data['status']}")
if 'current_median' in data:
print(f" Current: {data['current_median']:.2f}")
print(f" Baseline: {data['baseline_median']:.2f} (p95: {data['baseline_p95']:.2f})")
if data.get('change_pct'):
print(f" Change: {data['change_pct']:.1f}%")
# Save output if requested
if args.output:
with open(args.output, 'w') as f:
json.dump(report, f, indent=2, default=str)
print(f"\nReport saved to {args.output}")
if __name__ == "__main__":
main()
3. CI/CD Integration (.github/workflows/perf-check.yml)
name: Performance Regression Check
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
perf-test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: '18'
- name: Install dependencies
run: |
npm install -g lighthouse
pip install pyyaml
- name: Run performance test
env:
SLACK_WEBHOOK: ${{ secrets.SLACK_WEBHOOK }}
run: |
# Establish baseline on main branch only
if [[ ${{ github.ref }} == 'refs/heads/main' ]]; then
python perf_harness.py \
--url https://your-app.com \
--environment production \
--action baseline \
--runs 5
else
# For PRs, run check against existing baseline
python perf_harness.py \
--url https://your-app.com \
--environment production \
--action check \
--runs 3 \
--output perf-report.json
# Fail if any metric failed
if grep -q '"status": "fail"' perf-report.json; then
echo "Performance regression detected!"
exit 1
fi
fi
- name: Upload report
uses: actions/upload-artifact@v3
with:
name: perf-report
path: perf-report.json
4. Dashboard/Reporting Script (perf_dashboard.py)
#!/usr/bin/env python3
"""
Performance Dashboard Generator
"""
import json
import sqlite3
from datetime import datetime, timedelta
from typing import Dict, List
import matplotlib.pyplot as plt
import pandas as pd
class PerfDashboard:
def __init__(self, db_path: str = "perf_data.db"):
self.conn = sqlite3.connect(db_path)
self._init_db()
def _init_db(self):
"""Initialize database tables"""
self.conn.execute("""
CREATE TABLE IF NOT EXISTS baselines (
id INTEGER PRIMARY KEY,
metric_name TEXT,
environment TEXT,
median REAL,
p95 REAL,
p99 REAL,
std_dev REAL,
sample_count INTEGER,
created_at TIMESTAMP,
UNIQUE(metric_name, environment)
)
""")
self.conn.execute("""
CREATE TABLE IF NOT EXISTS results (
id INTEGER PRIMARY KEY,
metric_name TEXT,
environment TEXT,
value REAL,
timestamp TIMESTAMP,
url TEXT,
run_id INTEGER,
baseline_median REAL
)
""")
self.conn.commit()
def generate_trend_report(self, metric_name: str, environment: str, days: int = 30) -> Dict:
"""Generate trend analysis for a metric"""
cutoff = datetime.utcnow() - timedelta(days=days)
query = """
SELECT
DATE(timestamp) as date,
AVG(value) as avg_value,
MEDIAN(value) as median_value,
COUNT(*) as sample_count
FROM results
WHERE metric_name = ?
AND environment = ?
AND timestamp > ?
GROUP BY DATE(timestamp)
ORDER BY date
"""
df = pd.read_sql_query(query, self.conn,
params=(metric_name, environment, cutoff))
# Get current baseline
baseline_query = """
SELECT median, p95, p99 FROM baselines
WHERE metric_name = ? AND environment = ?
"""
cursor = self.conn.execute(baseline_query, (metric_name, environment))
baseline = cursor.fetchone()
return {
'metric': metric_name,
'environment': environment,
'trend_data': df.to_dict('records'),
'current_baseline': {
'median': baseline[0] if baseline else None,
'p95': baseline[1] if baseline else None,
'p99': baseline[2] if baseline else None
},
'chart_path': self._generate_chart(df, metric_name, environment)
}
def _generate_chart(self, df: pd.DataFrame, metric: str, environment: str) -> str:
"""Generate trend chart"""
plt.figure(figsize=(12, 6))
plt.plot(df['date'], df['median_value'], marker='o', label='Median')
plt.fill_between(df['date'],
df['median_value'] - df['avg_value'].std(),
df['median_value'] + df['avg_value'].std(),
alpha=0.3)
plt.title(f'{metric} Trend - {environment}')
plt.xlabel('Date')
plt.ylabel('Value (ms)' if 'ms' in metric else 'Value')
plt.legend()
plt.grid(True, alpha=0.3)
plt.xticks(rotation=45)
plt.tight_layout()
chart_path = f'perf_chart_{metric}_{environment}_{datetime.utcnow().strftime("%Y%m%d")}.png'
plt.savefig(chart_path, dpi=100)
plt.close()
return chart_path
def generate_html_report(dashboard_data: List[Dict], output_path: str = "perf_dashboard.html"):
"""Generate HTML dashboard"""
html_template = """
<!DOCTYPE html>
<html>
<head>
<title>Performance Dashboard</title>
<style>
body { font-family: Arial, sans-serif; margin: 20px; }
.metric-card {
border: 1px solid #ddd;
border-radius: 5px;
padding: 15px;
margin: 10px 0;
background: #f9f9f9;
}
.status-pass { border-left: 4px solid #4CAF50; }
.status-warning { border-left: 4px solid #FF9800; }
.status-fail { border-left: 4px solid #F44336; }
.chart { max-width: 100%; height: auto; }
table { border-collapse: collapse; width: 100%; }
th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
th { background-color: #f2f2f2; }
</style>
</head>
<body>
<h1>Performance Dashboard</h1>
<p>Generated: {timestamp}</p>
<h2>Recent Results</h2>
{metrics_html}
<h2>Trend Charts</h2>
{charts_html}
</body>
</html>
"""
metrics_html = ""
for data in dashboard_data:
status_class = f"status-{data.get('overall_status', 'pass')}"
metrics_html += f"""
<div class="metric-card {status_class}">
<h3>{data['metric']} - {data['environment']}</h3>
<p><strong>Current Median:</strong> {data.get('current_value', 'N/A')} ms</p>
<p><strong>Baseline Median:</strong> {data.get('baseline_median', 'N/A')} ms</p>
<p><strong>Status:</strong> {data.get('overall_status', 'unknown').upper()}</p>
<p><strong>Change:</strong> {data.get('change_pct', 0):.1f}%</p>
</div>
"""
charts_html = ""
for data in dashboard_data:
if 'chart_path' in data:
charts_html += f'<div><img src="{data["chart_path"]}" class="chart" alt="{data["metric"]} trend"></div>'
html = html_template.format(
timestamp=datetime.utcnow().isoformat(),
metrics_html=metrics_html,
charts_html=charts_html
)
with open(output_path, 'w') as f:
f.write(html)
print(f"Dashboard generated: {output_path}")
if __name__ == "__main__":
dashboard = PerfDashboard()
# Example: Generate reports for all metrics
metrics_to_check = [
('first_contentful_paint', 'chrome_latest'),
('largest_contentful_paint', 'chrome_latest'),
('first_input_delay', 'chrome_latest'),
]
dashboard_data = []
for metric, env in metrics_to_check:
report = dashboard.generate_trend_report(metric, env, days=7)
dashboard_data.append({
'metric': metric,
'environment': env,
'current_value': report['trend_data'][-1]['median_value'] if report['trend_data'] else None,
'baseline_median': report['current_baseline']['median'],
'overall_status': 'pass', # Determine from trends
'change_pct': 0, # Calculate from trend
'chart_path': report['chart_path']
})
generate_html_report(dashboard_data)
5. Usage Examples
# Establish baseline
python perf_harness.py \
--url https://your-app.com \
--environment production \
--action baseline \
--runs 5
# Run performance check
python perf_harness.py \
--url https://your-app.com \
--environment production \
--action check \
--runs 3 \
--output report.json
# View dashboard
python perf_dashboard.py
6. Key Features
- Profiling: Uses Lighthouse (extensible to other tools)
- Budgets: Both absolute and relative thresholds
- Statistical Significance: Mann-Whitney U test for regression detection
- Multiple Environments: Test across browsers/devices
- Storage: Abstract storage backend (JSON, PostgreSQL, etc.)
- Alerts: Slack/email notifications
- CI/CD Integration: GitHub Actions example
- Dashboard: HTML reports with trends
- Configurable: YAML-based configuration
7. Extending the Harness
To add new profilers:
class WebPageTestProfiler(Profiler):
def get_supported_metrics(self):
return ['first_view', 'repeat_view', 'speed_index']
def profile(self, url, runs=1):
# Call WebPageTest API and parse results
pass
To add new storage:
class PostgresStorage(StorageBackend):
def __init__(self, connection_string):
import psycopg2
self.conn = psycopg2.connect(connection_string)
8. Best Practices
- Run during off-peak hours for consistent results
- Use same hardware/network conditions for comparisons
- Establish baseline after stable releases
- Monitor trends, not single data points
- Consider business impact when setting budgets
- Warm up caches before measurements
- Run multiple times and use medians
- Document budget rationale in config comments
This harness provides:
- ✅ Baseline establishment with statistical rigor
- ✅ Budget enforcement (absolute & relative)
- ✅ Regression detection with significance testing
- ✅ Alerting & reporting
- ✅ CI/CD integration
- ✅ Extensible architecture
Would you like me to elaborate on any specific component or add additional features like:
- Anomaly detection?
- Performance budgeting dashboards?
- Integration with monitoring tools (Datadog, New Relic)?
- Mobile-specific metrics?
- API performance testing integration?