mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 07:24:56 -10:00
365 lines
17 KiB
YAML
365 lines
17 KiB
YAML
name: "Profiling Changes"
|
|
|
|
on:
|
|
pull_request:
|
|
# Everything the benchmarks build from or load, which also makes up the baseline's cache key below
|
|
paths: &benchmark-inputs
|
|
- "node-graph/**"
|
|
- "document/**"
|
|
- "libraries/**"
|
|
- "demo-artwork/**"
|
|
- "Cargo.toml"
|
|
- "Cargo.lock"
|
|
- ".cargo/config.toml"
|
|
- ".github/workflows/comment-profiling-changes.yaml"
|
|
# Measures each master commit's baseline once, so PR runs can restore it rather than measuring their base commit themselves
|
|
push:
|
|
branches:
|
|
- master
|
|
paths: *benchmark-inputs
|
|
|
|
concurrency:
|
|
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.sha }}
|
|
cancel-in-progress: true
|
|
|
|
env:
|
|
CARGO_TERM_COLOR: always
|
|
# The four benchmarks, built and run by one `cargo bench` call so their slow thin-LTO links happen in parallel
|
|
BENCHMARKS: --bench compile_demo_art_gungraun --bench update_executor_gungraun --bench run_once_gungraun --bench run_cached_gungraun
|
|
|
|
jobs:
|
|
profile:
|
|
# Fork PRs always run on GitHub's own runners, while the `LINUX_RUNNER` repo variable can point the rest at another provider
|
|
runs-on: ${{ github.event.pull_request.head.repo.fork && 'ubuntu-latest' || vars.LINUX_RUNNER || 'ubuntu-latest' }}
|
|
continue-on-error: true
|
|
permissions:
|
|
contents: read
|
|
pull-requests: write
|
|
steps:
|
|
- uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
|
|
with:
|
|
# A PR's merge commit plus its first parent, the master commit it's measured against
|
|
fetch-depth: 2
|
|
|
|
- name: Install Rust
|
|
uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable
|
|
|
|
- name: Cache Rust dependencies
|
|
uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
|
|
with:
|
|
# Cache on Cargo.lock file
|
|
cache-on-failure: true
|
|
|
|
- name: Install gungraun-runner and valgrind
|
|
uses: gungraun/setup-gungraun@62591572561bb2f4ed2ae300b8a8bea99ea8ddaf # v1.1.3
|
|
|
|
- name: Checkout baseline commit
|
|
if: github.event_name == 'pull_request'
|
|
run: git checkout --detach HEAD^1
|
|
|
|
- name: Get toolchain info
|
|
id: toolchain-info
|
|
run: |
|
|
# Instruction counts match across x64 CPU models, but new releases of Rust, Valgrind, or the C library change them
|
|
echo "hash=$( (rustc -vV; valgrind --version; ldd --version | sed -n 1p) | sha256sum | cut -c1-8)" >> $GITHUB_OUTPUT
|
|
|
|
- name: Restore benchmark baseline
|
|
id: restore-baseline
|
|
uses: actions/cache/restore@caa296126883cff596d87d8935842f9db880ef25 # v5.1.0
|
|
with:
|
|
path: target/gungraun
|
|
# Keyed by the baseline commit's benchmark inputs, so master commits that don't change them share one baseline
|
|
key: ${{ runner.os }}-${{ runner.arch }}-${{ steps.toolchain-info.outputs.hash }}-gungraun-baseline-${{ hashFiles('node-graph/**', 'document/**', 'libraries/**', 'demo-artwork/**', 'Cargo.toml', 'Cargo.lock', '.cargo/config.toml', '.github/workflows/comment-profiling-changes.yaml') }}
|
|
|
|
- name: Run baseline benchmarks
|
|
if: steps.restore-baseline.outputs.cache-hit != 'true'
|
|
run: cargo bench $BENCHMARKS -- --save-baseline=master
|
|
|
|
# Saved before the PR benchmarks run, since they write their own results into the same folder
|
|
- name: Save benchmark baseline
|
|
if: steps.restore-baseline.outputs.cache-hit != 'true'
|
|
uses: actions/cache/save@caa296126883cff596d87d8935842f9db880ef25 # v5.1.0
|
|
with:
|
|
path: target/gungraun
|
|
key: ${{ steps.restore-baseline.outputs.cache-primary-key }}
|
|
|
|
- name: Checkout PR merge commit
|
|
if: github.event_name == 'pull_request'
|
|
run: git checkout --detach ${{ github.sha }}
|
|
|
|
- name: Run PR benchmarks
|
|
if: github.event_name == 'pull_request'
|
|
# Unlike the default, this sets `pipefail`, so a failed benchmark fails the step rather than leaving its results empty
|
|
shell: bash
|
|
run: |
|
|
cargo bench $BENCHMARKS -- --baseline=master --output-format=json | jq -sc | sed 's/\\"//g' > /tmp/all_output.json
|
|
|
|
# Split the results into one file per benchmark for the analysis below
|
|
split_results() { jq -c --arg prefix "$1::" '[.[] | select(.module_path | startswith($prefix))]' /tmp/all_output.json > "/tmp/$2_output.json"; }
|
|
split_results compile_demo_art_gungraun compile
|
|
split_results update_executor_gungraun update
|
|
split_results run_once_gungraun run_once
|
|
split_results run_cached_gungraun run_cached
|
|
|
|
- name: Make old comments collapsed by default
|
|
# Only run if we have write permissions (not a fork)
|
|
if: github.event.pull_request.head.repo.full_name == github.repository
|
|
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
|
|
with:
|
|
github-token: ${{secrets.GITHUB_TOKEN}}
|
|
script: |
|
|
const { data: comments } = await github.rest.issues.listComments({
|
|
issue_number: context.issue.number,
|
|
owner: context.repo.owner,
|
|
repo: context.repo.repo,
|
|
});
|
|
|
|
const botComments = comments.filter((comment) =>
|
|
comment.user.type === 'Bot' && comment.body.includes('Performance Benchmark Results') && comment.body.includes('<details open>')
|
|
);
|
|
|
|
for (const comment of botComments) {
|
|
// Edit the comment to remove the "open" attribute from the <details> tag
|
|
await github.rest.issues.updateComment({
|
|
owner: context.repo.owner,
|
|
repo: context.repo.repo,
|
|
comment_id: comment.id,
|
|
body: comment.body.replace('<details open>', '<details>')
|
|
});
|
|
}
|
|
|
|
- name: Analyze profiling changes
|
|
id: analyze
|
|
if: github.event_name == 'pull_request'
|
|
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
|
|
with:
|
|
script: |
|
|
const fs = require('fs');
|
|
|
|
function isSignificantChange(diffPct, absoluteChange, benchmarkType) {
|
|
const meetsPercentageThreshold = Math.abs(diffPct) > 5;
|
|
const meetsAbsoluteThreshold = absoluteChange > 200000;
|
|
const isCachedExecution = benchmarkType === 'run_cached' ||
|
|
benchmarkType.includes('Cached Execution');
|
|
|
|
return isCachedExecution
|
|
? (meetsPercentageThreshold && meetsAbsoluteThreshold)
|
|
: meetsPercentageThreshold;
|
|
}
|
|
|
|
// Each Callgrind metric holds its counts in `values.old` and `values.new`, plus `change.diff_pct` (a string) when compared against the baseline
|
|
function callgrindMetrics(benchmark) {
|
|
return benchmark.profiles?.find((profile) => profile.tool === 'Callgrind')?.data?.total?.metrics;
|
|
}
|
|
|
|
const allOutputs = [
|
|
JSON.parse(fs.readFileSync('/tmp/compile_output.json', 'utf8')),
|
|
JSON.parse(fs.readFileSync('/tmp/update_output.json', 'utf8')),
|
|
JSON.parse(fs.readFileSync('/tmp/run_once_output.json', 'utf8')),
|
|
JSON.parse(fs.readFileSync('/tmp/run_cached_output.json', 'utf8'))
|
|
];
|
|
const outputNames = ['compile', 'update', 'run_once', 'run_cached'];
|
|
const sectionTitles = ['Compilation', 'Update', 'Run Once', 'Cached Execution'];
|
|
|
|
// Fail instead of reporting no changes when a benchmark has no baseline comparison, such as after gungraun changes its output format
|
|
const missingComparisons = [];
|
|
allOutputs.forEach((benchmarkOutput, i) => {
|
|
if (benchmarkOutput.length === 0) missingComparisons.push(`${outputNames[i]} (no results)`);
|
|
|
|
benchmarkOutput
|
|
.filter((benchmark) => !callgrindMetrics(benchmark)?.Ir?.change)
|
|
.forEach((benchmark) => missingComparisons.push(`${benchmark.module_path} ${benchmark.id}`));
|
|
});
|
|
if (missingComparisons.length > 0) {
|
|
core.setFailed(`Benchmark results without a baseline comparison: ${missingComparisons.join(', ')}`);
|
|
return;
|
|
}
|
|
|
|
let hasSignificantChanges = false;
|
|
let hasRegressions = false;
|
|
let regressionDetails = [];
|
|
|
|
allOutputs.forEach((benchmarkOutput, i) => {
|
|
const outputName = outputNames[i];
|
|
const sectionTitle = sectionTitles[i];
|
|
|
|
benchmarkOutput.forEach((benchmark) => {
|
|
const instructions = callgrindMetrics(benchmark).Ir;
|
|
const diffPct = parseFloat(instructions.change.diff_pct);
|
|
const absoluteChange = Math.abs(instructions.values.new - instructions.values.old);
|
|
|
|
if (isSignificantChange(diffPct, absoluteChange, outputName)) {
|
|
hasSignificantChanges = true;
|
|
|
|
// Only an increase in instruction count is a regression; improvements must not fail CI.
|
|
if (diffPct > 0) {
|
|
hasRegressions = true;
|
|
regressionDetails.push({
|
|
module_path: benchmark.module_path,
|
|
id: benchmark.id,
|
|
diffPct,
|
|
absoluteChange,
|
|
sectionTitle
|
|
});
|
|
}
|
|
}
|
|
});
|
|
});
|
|
|
|
core.setOutput('has-significant-changes', hasSignificantChanges);
|
|
core.setOutput('has-regressions', hasRegressions);
|
|
core.setOutput('regression-details', JSON.stringify(regressionDetails));
|
|
|
|
- name: Comment PR
|
|
if: github.event.pull_request.head.repo.full_name == github.repository
|
|
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
|
|
with:
|
|
github-token: ${{secrets.GITHUB_TOKEN}}
|
|
script: |
|
|
const fs = require('fs');
|
|
|
|
const compileOutput = JSON.parse(fs.readFileSync('/tmp/compile_output.json', 'utf8'));
|
|
const updateOutput = JSON.parse(fs.readFileSync('/tmp/update_output.json', 'utf8'));
|
|
const runOnceOutput = JSON.parse(fs.readFileSync('/tmp/run_once_output.json', 'utf8'));
|
|
const runCachedOutput = JSON.parse(fs.readFileSync('/tmp/run_cached_output.json', 'utf8'));
|
|
|
|
const hasSignificantChanges = '${{ steps.analyze.outputs.has-significant-changes }}' === 'true';
|
|
let commentBody = "";
|
|
|
|
function formatNumber(num) {
|
|
return String(num).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
|
|
}
|
|
|
|
function formatPercentage(pct) {
|
|
const sign = pct >= 0 ? '+' : '';
|
|
return `${sign}${pct.toFixed(2)}%`;
|
|
}
|
|
|
|
function padRight(str, len) {
|
|
return str.padEnd(len);
|
|
}
|
|
|
|
function padLeft(str, len) {
|
|
return str.padStart(len);
|
|
}
|
|
|
|
function callgrindMetrics(benchmark) {
|
|
return benchmark.profiles?.find((profile) => profile.tool === 'Callgrind')?.data?.total?.metrics;
|
|
}
|
|
|
|
function processBenchmarkOutput(benchmarkOutput, sectionTitle, isLast = false) {
|
|
let sectionBody = "";
|
|
let hasResults = false;
|
|
let hasSignificantChanges = false;
|
|
|
|
function isSignificantChange(diffPct, absoluteChange, benchmarkType) {
|
|
const meetsPercentageThreshold = Math.abs(diffPct) > 5;
|
|
const meetsAbsoluteThreshold = absoluteChange > 200000;
|
|
const isCachedExecution = benchmarkType === 'run_cached' ||
|
|
benchmarkType.includes('Cached Execution');
|
|
|
|
return isCachedExecution
|
|
? (meetsPercentageThreshold && meetsAbsoluteThreshold)
|
|
: meetsPercentageThreshold;
|
|
}
|
|
|
|
benchmarkOutput.forEach((benchmark) => {
|
|
const metrics = callgrindMetrics(benchmark);
|
|
const instructions = metrics?.Ir;
|
|
if (!instructions?.change) return;
|
|
|
|
hasResults = true;
|
|
const diffPct = parseFloat(instructions.change.diff_pct);
|
|
const changePercentage = formatPercentage(diffPct);
|
|
const color = diffPct > 0 ? "red" : "lime";
|
|
const name = [benchmark.id, benchmark.description].filter(Boolean).join(':');
|
|
|
|
sectionBody += `**${benchmark.module_path} ${name}**\n`;
|
|
sectionBody += `Instructions: \`${formatNumber(instructions.values.old)}\` (master) → \`${formatNumber(instructions.values.new)}\` (HEAD) : `;
|
|
sectionBody += `$$\\color{${color}}${changePercentage.replace("%", "\\\\%")}$$\n\n`;
|
|
|
|
sectionBody += "<details>\n<summary>Detailed metrics</summary>\n\n```\n";
|
|
sectionBody += `Baselines: master| HEAD\n`;
|
|
|
|
Object.entries(metrics).forEach(([metricName, metricData]) => {
|
|
if (!metricData.change) return;
|
|
|
|
const changePercentage = formatPercentage(parseFloat(metricData.change.diff_pct));
|
|
const line = `${padRight(metricName, 20)} ${padLeft(formatNumber(Math.round(metricData.values.old)), 11)}|${padLeft(formatNumber(Math.round(metricData.values.new)), 11)} ${padLeft(changePercentage, 15)}`;
|
|
sectionBody += `${line}\n`;
|
|
});
|
|
|
|
sectionBody += "```\n</details>\n\n";
|
|
|
|
if (isSignificantChange(diffPct, Math.abs(instructions.values.new - instructions.values.old), sectionTitle)) {
|
|
hasSignificantChanges = true;
|
|
}
|
|
});
|
|
|
|
if (hasResults) {
|
|
// Wrap section in collapsible details, open only if there are significant changes
|
|
const openAttribute = hasSignificantChanges ? " open" : "";
|
|
const ruler = isLast ? "" : "\n\n---";
|
|
return `<details${openAttribute}>\n<summary><h2>${sectionTitle}</h2></summary>\n\n${sectionBody}${ruler}\n</details>`;
|
|
}
|
|
return "";
|
|
}
|
|
|
|
// Process each benchmark category
|
|
const sections = [
|
|
{ output: compileOutput, title: "🔧 Graph Compilation" },
|
|
{ output: updateOutput, title: "🔄 Executor Update" },
|
|
{ output: runOnceOutput, title: "🚀 Render: Cold Execution" },
|
|
{ output: runCachedOutput, title: "⚡ Render: Cached Execution" }
|
|
];
|
|
|
|
// Generate sections and determine which ones have results
|
|
const generatedSections = sections.map(({ output, title }) =>
|
|
processBenchmarkOutput(output, title, true) // temporarily mark all as last
|
|
).filter(section => section.length > 0);
|
|
|
|
// Re-generate with correct isLast flags
|
|
let sectionIndex = 0;
|
|
const finalSections = sections.map(({ output, title }) => {
|
|
const section = processBenchmarkOutput(output, title, true); // check if it has results
|
|
if (section.length > 0) {
|
|
const isLast = sectionIndex === generatedSections.length - 1;
|
|
sectionIndex++;
|
|
return processBenchmarkOutput(output, title, isLast);
|
|
}
|
|
return "";
|
|
}).filter(section => section.length > 0);
|
|
|
|
// Combine all sections
|
|
commentBody = finalSections.join("\n\n");
|
|
|
|
if (commentBody.length > 0) {
|
|
const output = `<details open>\n<summary>Performance Benchmark Results</summary>\n\n${commentBody}\n</details>`;
|
|
|
|
if (hasSignificantChanges) {
|
|
github.rest.issues.createComment({
|
|
issue_number: context.issue.number,
|
|
owner: context.repo.owner,
|
|
repo: context.repo.repo,
|
|
body: output
|
|
});
|
|
} else {
|
|
console.log("No significant performance changes detected. Skipping comment.");
|
|
console.log(output);
|
|
}
|
|
} else {
|
|
console.log("No benchmark results to display.");
|
|
}
|
|
|
|
- name: Fail on significant regressions
|
|
if: steps.analyze.outputs.has-regressions == 'true'
|
|
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
|
|
env:
|
|
REGRESSION_DETAILS: ${{ steps.analyze.outputs.regression-details }}
|
|
with:
|
|
script: |
|
|
const regressionDetails = JSON.parse(process.env.REGRESSION_DETAILS);
|
|
const firstRegression = regressionDetails[0];
|
|
|
|
core.setFailed(`Significant performance regression detected: ${firstRegression.module_path} ${firstRegression.id} increased by ${firstRegression.absoluteChange.toLocaleString()} instructions (${firstRegression.diffPct.toFixed(2)}%)`);
|