Repository navigation
ci: classify pull request risk with Jev #1323
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,225 @@ | ||
| import assert from "node:assert/strict"; | ||
| import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; | ||
| import { createRequire } from "node:module"; | ||
| import { tmpdir } from "node:os"; | ||
| import { join } from "node:path"; | ||
| import test from "node:test"; | ||
|
|
||
| // Execute the actual workflow script so the tests cannot drift from production. | ||
| const workflow = readFileSync( | ||
| new URL("../workflows/pr-risk-jev.yml", import.meta.url), | ||
| "utf8", | ||
| ); | ||
| const script = workflow.match(/^ {10}script: \|\n((?: {12}.*\n|\n)+)/m)?.[1]; | ||
| assert.ok(script, "Publish risk label script must exist"); | ||
| const AsyncFunction = Object.getPrototypeOf(async () => {}).constructor; | ||
|
Check warning on line 15 in .github/tests/pr-risk-labels.test.mjs
|
||
| const publish = new AsyncFunction( | ||
| "require", | ||
| "github", | ||
| "context", | ||
| "core", | ||
| script, | ||
| ); | ||
| const require = createRequire(import.meta.url); | ||
| const repo = { owner: "example", repo: "cli" }; | ||
| const head = "a".repeat(40); | ||
| const base = "b".repeat(40); | ||
|
|
||
| async function withPR(options, check) { | ||
| const directory = mkdtempSync(join(tmpdir(), "pr-risk-labels-")); | ||
| const previousDirectory = process.cwd(); | ||
| const previousNumber = process.env.PR_NUMBER; | ||
| const labels = new Set(options.labels ?? ["area: auth", "risk: high"]); | ||
| const repositoryLabels = new Set( | ||
| options.repositoryLabels ?? ["risk: low", "risk: medium", "risk: high"], | ||
| ); | ||
| const writes = []; | ||
| const warnings = []; | ||
| const pr = { | ||
| state: "open", | ||
| head: { sha: head }, | ||
| base: { sha: base }, | ||
| title: "Update behavior", | ||
| body: "Describe this change", | ||
| ...options.pr, | ||
| }; | ||
| const result = { | ||
| repo: "example/cli", | ||
| number: 42, | ||
| status: "ok", | ||
| risk_label: "low", | ||
| snapshot: { source_head_sha: head, source_base_sha: base }, | ||
| ...options.result, | ||
| }; | ||
| const error = (status) => | ||
| Object.assign(new Error(`GitHub HTTP ${status}`), { status }); | ||
| const github = { | ||
| rest: { | ||
| pulls: { | ||
| get: async () => ({ | ||
| data: structuredClone({ | ||
| ...pr, | ||
| labels: [...labels].map((name) => ({ name })), | ||
| }), | ||
| }), | ||
| }, | ||
| issues: { | ||
| getLabel: async ({ name }) => { | ||
| if (!repositoryLabels.has(name)) throw error(404); | ||
| return { data: { name } }; | ||
| }, | ||
| createLabel: async ({ name }) => { | ||
| repositoryLabels.add(name); | ||
| if (options.createRace) throw error(422); | ||
| return { data: { name } }; | ||
| }, | ||
| addLabels: async ({ labels: added }) => { | ||
| writes.push(["add", ...added]); | ||
| for (const label of added) labels.add(label); | ||
| options.afterAdd?.(pr); | ||
| }, | ||
| removeLabel: async ({ name }) => { | ||
| writes.push(["remove", name]); | ||
| if (!labels.delete(name)) throw error(404); | ||
| }, | ||
| }, | ||
| }, | ||
| }; | ||
| try { | ||
| process.chdir(directory); | ||
| process.env.PR_NUMBER = "42"; | ||
| if (!options.missingResult) | ||
| writeFileSync("risk-pr-result.json", JSON.stringify(result)); | ||
| await check({ | ||
| run: () => | ||
| publish( | ||
| require, | ||
| github, | ||
| { repo }, | ||
| { warning: (message) => warnings.push(message), info: () => {} }, | ||
| ), | ||
| labels, | ||
| writes, | ||
| warnings, | ||
| }); | ||
| } finally { | ||
| process.chdir(previousDirectory); | ||
| if (previousNumber === undefined) delete process.env.PR_NUMBER; | ||
| else process.env.PR_NUMBER = previousNumber; | ||
| rmSync(directory, { recursive: true, force: true }); | ||
| } | ||
| } | ||
|
|
||
| for (const risk of ["low", "medium", "high"]) { | ||
| test(`publishes ${risk}, replacing only risk labels`, async () => { | ||
| await withPR( | ||
| { | ||
| result: { risk_label: risk }, | ||
| labels: ["area: auth", "risk: low", "risk: medium", "risk: high"], | ||
| }, | ||
| async ({ run, labels }) => { | ||
| await run(); | ||
| assert.deepEqual([...labels].sort(), ["area: auth", `risk: ${risk}`]); | ||
| }, | ||
| ); | ||
| }); | ||
| } | ||
|
|
||
| test("context rejection removes stale risk labels and remains unclassified", async () => { | ||
| await withPR( | ||
| { result: { status: "context_rejected", risk_label: null } }, | ||
| async ({ run, labels, warnings }) => { | ||
| await run(); | ||
| assert.deepEqual([...labels], ["area: auth"]); | ||
| assert.ok(warnings.some((message) => message.includes("unclassified"))); | ||
| }, | ||
| ); | ||
| }); | ||
|
|
||
| test("moved or closed PRs are left untouched before publication", async (t) => { | ||
| for (const pr of [ | ||
| { head: { sha: "c".repeat(40) } }, | ||
| { base: { sha: "d".repeat(40) } }, | ||
| { state: "closed" }, | ||
| ]) { | ||
| await t.test(JSON.stringify(pr), async () => { | ||
| await withPR({ pr }, async ({ run, labels, writes }) => { | ||
| await run(); | ||
| assert.deepEqual(writes, []); | ||
| assert.deepEqual([...labels], ["area: auth", "risk: high"]); | ||
| }); | ||
| }); | ||
| } | ||
| }); | ||
|
|
||
| test("movement or metadata edits during publication roll back the verdict", async (t) => { | ||
| for (const [name, afterAdd] of [ | ||
| [ | ||
| "head", | ||
| (pr) => { | ||
| pr.head.sha = "c".repeat(40); | ||
| }, | ||
| ], | ||
| [ | ||
| "title", | ||
| (pr) => { | ||
| pr.title = "A different change"; | ||
| }, | ||
| ], | ||
| [ | ||
| "closed", | ||
| (pr) => { | ||
| pr.state = "closed"; | ||
| }, | ||
| ], | ||
| ]) { | ||
| await t.test(name, async () => { | ||
| await withPR({ afterAdd }, async ({ run, labels }) => { | ||
| await run(); | ||
| assert.deepEqual([...labels], ["area: auth"]); | ||
| }); | ||
| }); | ||
| } | ||
| }); | ||
|
|
||
| test("results for another PR or an invalid risk cannot publish", async (t) => { | ||
| for (const result of [ | ||
| { repo: "example/another" }, | ||
| { number: 43 }, | ||
| { risk_label: "critical" }, | ||
| { risk_label: "toString" }, | ||
| ]) { | ||
| await t.test(JSON.stringify(result), async () => { | ||
| await withPR({ result }, async ({ run, writes }) => { | ||
| await assert.rejects(run, /does not match/); | ||
| assert.deepEqual(writes, []); | ||
| }); | ||
| }); | ||
| } | ||
| }); | ||
|
|
||
| test("a missing result does not publish or remove labels", async () => { | ||
| await withPR({ missingResult: true }, async ({ run, writes, warnings }) => { | ||
| await run(); | ||
| assert.deepEqual(writes, []); | ||
| assert.equal(warnings.length, 1); | ||
| }); | ||
| }); | ||
|
|
||
| test("concurrent repository label creation still publishes", async () => { | ||
| await withPR( | ||
| { repositoryLabels: [], createRace: true }, | ||
| async ({ run, labels }) => { | ||
| await run(); | ||
| assert.deepEqual([...labels], ["area: auth", "risk: low"]); | ||
| }, | ||
| ); | ||
| }); | ||
|
|
||
| test("repeated publication leaves one risk label and preserves unrelated labels", async () => { | ||
| await withPR({}, async ({ run, labels }) => { | ||
| await run(); | ||
| await run(); | ||
| assert.deepEqual([...labels], ["area: auth", "risk: low"]); | ||
| }); | ||
| }); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,120 @@ | ||
| name: PR Risk (Jev) | ||
|
|
||
| on: | ||
| pull_request_target: | ||
| types: [opened, synchronize, reopened, ready_for_review, edited] | ||
| workflow_dispatch: | ||
| inputs: | ||
| pr_number: | ||
| description: Pull request number to analyze | ||
| required: true | ||
| type: number | ||
|
|
||
| permissions: | ||
| contents: read | ||
| pull-requests: write | ||
|
Check warning on line 15 in .github/workflows/pr-risk-jev.yml
|
||
|
|
||
|
betegon marked this conversation as resolved.
Resolved
|
||
| concurrency: | ||
| group: pr-risk-jev-${{ github.event.pull_request.number || inputs.pr_number }} | ||
| cancel-in-progress: true | ||
|
|
||
| jobs: | ||
| risk: | ||
| name: PR risk (Jev) | ||
| runs-on: ubuntu-latest | ||
| timeout-minutes: 10 | ||
| if: github.event_name == 'workflow_dispatch' || github.event.pull_request.draft == false | ||
| steps: | ||
| # The Action reads PR Git objects without checking out or executing PR code. | ||
| - name: Classify PR risk | ||
| id: risk | ||
| uses: getsentry/pr-risk-action@42934115c8d8417f2758462bbf918f71360ac2b1 | ||
| env: | ||
| AI_GATEWAY_API_KEY: ${{ secrets.AI_GATEWAY_API_KEY }} | ||
| with: | ||
| repo: ${{ github.repository }} | ||
| pr-number: ${{ github.event.pull_request.number || inputs.pr_number }} | ||
| expected-head-sha: ${{ github.event.pull_request.head.sha }} | ||
| result-path: risk-pr-result.json | ||
|
|
||
| - name: Publish risk label | ||
| if: ${{ !cancelled() && steps.risk.outcome != 'skipped' }} | ||
| uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8 | ||
| env: | ||
| PR_NUMBER: ${{ github.event.pull_request.number || inputs.pr_number }} | ||
| with: | ||
| script: | | ||
| // Only this trusted workflow publishes labels; PR source is never executed. | ||
| const fs = require('node:fs'); | ||
| if (!fs.existsSync('risk-pr-result.json')) { | ||
| core.warning('Risk analysis did not produce a result; no label was published.'); | ||
| return; | ||
| } | ||
| const result = JSON.parse(fs.readFileSync('risk-pr-result.json', 'utf8')); | ||
| const prNumber = Number(process.env.PR_NUMBER); | ||
| const repo = context.repo; | ||
| const colors = { low: '0E8A16', medium: 'FBCA04', high: 'B60205' }; | ||
| const riskLabels = Object.keys(colors).map(risk => `risk: ${risk}`); | ||
| if (!Number.isSafeInteger(prNumber) || prNumber <= 0 | ||
| || result.number !== prNumber || result.repo !== `${repo.owner}/${repo.repo}` | ||
| || typeof result.status !== 'string' | ||
| || (result.status === 'ok' && !Object.hasOwn(colors, result.risk_label))) { | ||
| throw new Error('Risk result does not match this PR or a valid risk class.'); | ||
| } | ||
| const snapshot = result.snapshot; | ||
| if (result.status === 'pr_changed' || !snapshot?.source_head_sha || !snapshot?.source_base_sha) { | ||
| core.warning('Risk analysis has no current revision; no label was published.'); | ||
| return; | ||
| } | ||
| const { data: pr } = await github.rest.pulls.get({ ...repo, pull_number: prNumber }); | ||
| if (pr.state !== 'open' || pr.head.sha !== snapshot.source_head_sha | ||
| || pr.base.sha !== snapshot.source_base_sha) { | ||
| core.warning('PR changed after risk analysis; no label was published.'); | ||
| return; | ||
| } | ||
| const target = result.status === 'ok' ? `risk: ${result.risk_label}` : null; | ||
| const existing = pr.labels.map(label => label.name); | ||
| if (target) { | ||
| try { | ||
| await github.rest.issues.getLabel({ ...repo, name: target }); | ||
| } catch (error) { | ||
| if (error.status !== 404) throw error; | ||
| try { | ||
| await github.rest.issues.createLabel({ | ||
| ...repo, name: target, color: colors[result.risk_label], | ||
| description: `PR risk score: ${result.risk_label}`, | ||
| }); | ||
| } catch (error) { | ||
| if (error.status !== 422) throw error; | ||
| // Another PR may have created the shared repository label. | ||
| await github.rest.issues.getLabel({ ...repo, name: target }); | ||
| } | ||
| } | ||
| await github.rest.issues.addLabels({ ...repo, issue_number: prNumber, labels: [target] }); | ||
| } | ||
| // A failed classification must not leave an earlier low/medium/high verdict. | ||
| for (const name of existing.filter(name => riskLabels.includes(name) && name !== target)) { | ||
| try { | ||
| await github.rest.issues.removeLabel({ ...repo, issue_number: prNumber, name }); | ||
| } catch (error) { | ||
| if (error.status !== 404) throw error; | ||
| } | ||
| } | ||
| const { data: latest } = await github.rest.pulls.get({ ...repo, pull_number: prNumber }); | ||
| if (target && (latest.state !== 'open' || latest.head.sha !== pr.head.sha | ||
| || latest.base.sha !== pr.base.sha || latest.title !== pr.title || latest.body !== pr.body)) { | ||
| await github.rest.issues.removeLabel({ ...repo, issue_number: prNumber, name: target }); | ||
| core.warning('PR changed while publishing; removed the outdated risk label.'); | ||
| return; | ||
| } | ||
| if (!target) core.warning(`PR remains unclassified: ${result.status}. Previous risk labels were cleared.`); | ||
| core.info(target ? `Published ${target}` : 'No risk label published.'); | ||
|
|
||
| - name: Upload risk result | ||
| if: always() | ||
| uses: actions/upload-artifact@v7 | ||
| with: | ||
| name: pr-risk-jev-${{ github.event.pull_request.number || inputs.pr_number }} | ||
| path: risk-pr-result.json | ||
| if-no-files-found: warn | ||
| retention-days: 30 | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,28 @@ | ||
| name: PR Risk Label Tests | ||
|
|
||
| on: | ||
| pull_request: | ||
| paths: | ||
| - .github/workflows/pr-risk-jev.yml | ||
| - .github/workflows/pr-risk-labels-test.yml | ||
| - .github/tests/pr-risk-labels.test.mjs | ||
| push: | ||
| branches: [main] | ||
| paths: | ||
| - .github/workflows/pr-risk-jev.yml | ||
| - .github/workflows/pr-risk-labels-test.yml | ||
| - .github/tests/pr-risk-labels.test.mjs | ||
|
|
||
| permissions: | ||
| contents: read | ||
|
|
||
| jobs: | ||
| test: | ||
| runs-on: ubuntu-latest | ||
| timeout-minutes: 5 | ||
| steps: | ||
| - uses: actions/checkout@v6 | ||
| - uses: actions/setup-node@v6 | ||
| with: | ||
| node-version: '24.18.0' | ||
| - run: node --test .github/tests/pr-risk-labels.test.mjs |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Risk label creation fails when the shared label is absent
The workflow grants only
pull-requests: write, butissues.createLabelrequires the Issues write permission. On a repository where a target risk label has not been pre-created, the 404 fallback attempts to create it and receives 403, so the classification fails before the PR receives its risk label.Evidence
.github/workflows/pr-risk-jev.ymlexplicitly grants onlycontents: readandpull-requests: write, so the Issues permission is unset.issues.getLabeland, when the shared label is missing, callsissues.createLabelbeforeissues.addLabels.issues: write; therefore a missingrisk: low,risk: medium, orrisk: highlabel causes the create call to fail with 403 and prevents publication.Also found at 1 additional location
.github/workflows/pr-risk-jev.yml:13-15Identified by Warden · code-review · YJ8-XDK