Retry failed review requests

This commit is contained in:
lezi-fun committed 2026-05-16 18:42:56 +08:00
1 parent 50d0ae5be9
commit fd9479590a
5 files changed
+191 -118

No files matched your search

+1
View File
@@ -18,6 +18,7 @@ GitHub Actions bot that reviews pull requests with an AI reviewer, leaves inline
- If the reviewer detects clearly malicious code, the bot comments with the reason and closes the pull request. - If the reviewer detects clearly malicious code, the bot comments with the reason and closes the pull request.
- Posts inline comments only on valid added diff lines. - Posts inline comments only on valid added diff lines.
- Approves clean pull requests. - Approves clean pull requests.
- Retries transient OpenAI and GitHub API request failures up to 5 times before giving up.
- If `AUTO_MERGE=true`, merges only after: - If `AUTO_MERGE=true`, merges only after:
- the AI reviewer says the PR is safe, - the AI reviewer says the PR is safe,
- GitHub reports the PR as mergeable, - GitHub reports the PR as mergeable,
+8 -5
View File
@@ -2,6 +2,7 @@ import fs from "node:fs";
import { config } from "../config.js"; import { config } from "../config.js";
import { createGitHubClient } from "../github/client.js"; import { createGitHubClient } from "../github/client.js";
import { logger } from "../logger.js"; import { logger } from "../logger.js";
import { withRetry } from "../retry.js";
import { import {
processLenientCheckComment, processLenientCheckComment,
processPullRequest, processPullRequest,
@@ -73,11 +74,13 @@ async function main(): Promise<void> {
if (eventName === "pull_request_target") { if (eventName === "pull_request_target") {
const prPayload = payload as PullRequestPayload; const prPayload = payload as PullRequestPayload;
if (prPayload.action === "opened") { if (prPayload.action === "opened") {
await octokit.rest.issues.createComment({ await withRetry("github.issues.createComment.started", async () => {
owner: prPayload.repository.owner.login, return octokit.rest.issues.createComment({
repo: prPayload.repository.name, owner: prPayload.repository.owner.login,
issue_number: prPayload.pull_request.number, repo: prPayload.repository.name,
body: "Automated review has started. I am checking this pull request now." issue_number: prPayload.pull_request.number,
body: "Automated review has started. I am checking this pull request now."
});
}); });
} }
+47
View File
@@ -0,0 +1,47 @@
import { logger } from "./logger.js";
const MAX_ATTEMPTS = 5;
const BASE_DELAY_MS = 1_000;
export async function withRetry<T>(
label: string,
operation: () => Promise<T>,
options?: {
maxAttempts?: number;
baseDelayMs?: number;
}
): Promise<T> {
const maxAttempts = options?.maxAttempts ?? MAX_ATTEMPTS;
const baseDelayMs = options?.baseDelayMs ?? BASE_DELAY_MS;
let lastError: unknown;
for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
try {
return await operation();
} catch (error) {
lastError = error;
logger.warn(
{
error,
label,
attempt,
maxAttempts
},
"Request failed."
);
if (attempt === maxAttempts) {
break;
}
await delay(baseDelayMs * attempt);
}
}
throw lastError;
}
function delay(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
+54 -51
View File
@@ -1,6 +1,7 @@
import { OpenAI } from "openai"; import { OpenAI } from "openai";
import { z } from "zod"; import { z } from "zod";
import { config } from "../config.js"; import { config } from "../config.js";
import { withRetry } from "../retry.js";
import type { PullRequestFile, ReviewDecision, ReviewMode } from "../types.js"; import type { PullRequestFile, ReviewDecision, ReviewMode } from "../types.js";
const reviewDecisionSchema = z.object({ const reviewDecisionSchema = z.object({
@@ -31,62 +32,64 @@ export class OpenAiReviewer {
files: PullRequestFile[]; files: PullRequestFile[];
mode: ReviewMode; mode: ReviewMode;
}): Promise<ReviewDecision> { }): Promise<ReviewDecision> {
const response = await this.client.responses.create({ const response = await withRetry("openai.responses.create", async () => {
model: config.openAiModel, return this.client.responses.create({
temperature: 0.1, model: config.openAiModel,
...(config.openAiReasoningEffort ? { reasoning: { effort: config.openAiReasoningEffort } } : {}), temperature: 0.1,
text: { ...(config.openAiReasoningEffort ? { reasoning: { effort: config.openAiReasoningEffort } } : {}),
format: { text: {
name: "pull_request_review", format: {
type: "json_schema", name: "pull_request_review",
strict: true, type: "json_schema",
schema: { strict: true,
type: "object", schema: {
additionalProperties: false, type: "object",
required: ["safeToMerge", "shouldClosePullRequest", "closeReason", "summary", "findings"], additionalProperties: false,
properties: { required: ["safeToMerge", "shouldClosePullRequest", "closeReason", "summary", "findings"],
safeToMerge: { type: "boolean" }, properties: {
shouldClosePullRequest: { type: "boolean" }, safeToMerge: { type: "boolean" },
closeReason: { type: "string" }, shouldClosePullRequest: { type: "boolean" },
summary: { type: "string" }, closeReason: { type: "string" },
findings: { summary: { type: "string" },
type: "array", findings: {
items: { type: "array",
type: "object", items: {
additionalProperties: false, type: "object",
required: ["path", "line", "severity", "title", "body"], additionalProperties: false,
properties: { required: ["path", "line", "severity", "title", "body"],
path: { type: "string" }, properties: {
line: { type: "integer", minimum: 1 }, path: { type: "string" },
severity: { type: "string", enum: ["blocking", "suggestion"] }, line: { type: "integer", minimum: 1 },
title: { type: "string" }, severity: { type: "string", enum: ["blocking", "suggestion"] },
body: { type: "string" } title: { type: "string" },
body: { type: "string" }
}
} }
} }
} }
} }
} }
} },
}, instructions: buildSystemPrompt(input.mode),
instructions: buildSystemPrompt(input.mode), input: [
input: [ {
{ role: "user",
role: "user", content: JSON.stringify({
content: JSON.stringify({ pullRequest: {
pullRequest: { title: input.title,
title: input.title, body: input.body ?? ""
body: input.body ?? "" },
}, files: input.files.map((file) => ({
files: input.files.map((file) => ({ path: file.filename,
path: file.filename, status: file.status,
status: file.status, additions: file.additions,
additions: file.additions, deletions: file.deletions,
deletions: file.deletions, patch: file.patch ?? ""
patch: file.patch ?? "" }))
})) })
}) }
} ]
] });
}); });
const raw = response.output_text; const raw = response.output_text;
+81 -62
View File
@@ -3,6 +3,7 @@ import { config } from "../config.js";
import { requiredChecksAreGreen } from "../github/checks.js"; import { requiredChecksAreGreen } from "../github/checks.js";
import { collectValidNewLines, toDiffPosition } from "../github/diff.js"; import { collectValidNewLines, toDiffPosition } from "../github/diff.js";
import { logger } from "../logger.js"; import { logger } from "../logger.js";
import { withRetry } from "../retry.js";
import type { PullRequestFile, PullRequestRef, ReviewDecision, ReviewFinding, ReviewMode } from "../types.js"; import type { PullRequestFile, PullRequestRef, ReviewDecision, ReviewFinding, ReviewMode } from "../types.js";
import { formatReviewBody } from "./format.js"; import { formatReviewBody } from "./format.js";
import { OpenAiReviewer } from "./openaiReviewer.js"; import { OpenAiReviewer } from "./openaiReviewer.js";
@@ -188,11 +189,13 @@ export async function processLenientCheckComment(
"Processing lenient check comment command." "Processing lenient check comment command."
); );
await octokit.rest.issues.createComment({ await withRetry("github.issues.createComment.lenientRequested", async () => {
owner: params.owner, return octokit.rest.issues.createComment({
repo: params.repo, owner: params.owner,
issue_number: params.pullNumber, repo: params.repo,
body: `Lenient check requested by @${params.commenterLogin}. Re-running the review with runtime and security focus only.` issue_number: params.pullNumber,
body: `Lenient check requested by @${params.commenterLogin}. Re-running the review with runtime and security focus only.`
});
}); });
await processPullRequest( await processPullRequest(
@@ -234,11 +237,13 @@ async function maybeMergePullRequest(
}); });
if (!approvedByOwner) { if (!approvedByOwner) {
await octokit.rest.issues.createComment({ await withRetry("github.issues.createComment.awaitLenientApproval", async () => {
owner, return octokit.rest.issues.createComment({
repo, owner,
issue_number: pullNumber, repo,
body: `Lenient check passed, but this PR will not be merged until @${config.lenientApprovalUser} approves the current head commit.` issue_number: pullNumber,
body: `Lenient check passed, but this PR will not be merged until @${config.lenientApprovalUser} approves the current head commit.`
});
}); });
logger.info({ owner, repo, pullNumber, reviewer: config.lenientApprovalUser }, "Waiting for lenient approval before merging."); logger.info({ owner, repo, pullNumber, reviewer: config.lenientApprovalUser }, "Waiting for lenient approval before merging.");
return; return;
@@ -247,11 +252,13 @@ async function maybeMergePullRequest(
const mergeablePullRequest = await waitForMergeable(octokit, owner, repo, pullNumber); const mergeablePullRequest = await waitForMergeable(octokit, owner, repo, pullNumber);
if (mergeablePullRequest.mergeable !== true || mergeablePullRequest.mergeable_state === "dirty") { if (mergeablePullRequest.mergeable !== true || mergeablePullRequest.mergeable_state === "dirty") {
await octokit.rest.issues.createComment({ await withRetry("github.issues.createComment.notMergeable", async () => {
owner, return octokit.rest.issues.createComment({
repo, owner,
issue_number: pullNumber, repo,
body: `Automated review approved this PR, but it was not merged because GitHub reports mergeable=${mergeablePullRequest.mergeable} and mergeable_state=${mergeablePullRequest.mergeable_state}.` issue_number: pullNumber,
body: `Automated review approved this PR, but it was not merged because GitHub reports mergeable=${mergeablePullRequest.mergeable} and mergeable_state=${mergeablePullRequest.mergeable_state}.`
});
}); });
return; return;
} }
@@ -263,22 +270,26 @@ async function maybeMergePullRequest(
ref: params.headSha ref: params.headSha
}); });
if (!checks.ok) { if (!checks.ok) {
await octokit.rest.issues.createComment({ await withRetry("github.issues.createComment.requiredChecks", async () => {
owner, return octokit.rest.issues.createComment({
repo, owner,
issue_number: pullNumber, repo,
body: `Automated review approved this PR, but it was not merged because required checks are not green. ${checks.reason ?? ""}`.trim() issue_number: pullNumber,
body: `Automated review approved this PR, but it was not merged because required checks are not green. ${checks.reason ?? ""}`.trim()
});
}); });
return; return;
} }
} }
await octokit.rest.pulls.merge({ await withRetry("github.pulls.merge", async () => {
owner, return octokit.rest.pulls.merge({
repo, owner,
pull_number: pullNumber, repo,
merge_method: config.mergeMethod, pull_number: pullNumber,
commit_title: `${params.title} (#${pullNumber})` merge_method: config.mergeMethod,
commit_title: `${params.title} (#${pullNumber})`
});
}); });
} }
@@ -380,14 +391,16 @@ async function submitReview(
const event: "APPROVE" | "REQUEST_CHANGES" = const event: "APPROVE" | "REQUEST_CHANGES" =
params.decision.safeToMerge && !hasBlockingFinding ? "APPROVE" : "REQUEST_CHANGES"; params.decision.safeToMerge && !hasBlockingFinding ? "APPROVE" : "REQUEST_CHANGES";
await octokit.rest.pulls.createReview({ await withRetry("github.pulls.createReview", async () => {
owner: params.owner, return octokit.rest.pulls.createReview({
repo: params.repo, owner: params.owner,
pull_number: params.pullNumber, repo: params.repo,
commit_id: params.commitId, pull_number: params.pullNumber,
event, commit_id: params.commitId,
body: formatReviewBody(params.decision, unpostedFindings, params.mode), event,
comments body: formatReviewBody(params.decision, unpostedFindings, params.mode),
comments
});
}); });
} }
@@ -406,24 +419,26 @@ async function upsertReviewCheckRun(
const conclusion = const conclusion =
params.decision.shouldClosePullRequest || hasBlockingFinding || !params.decision.safeToMerge ? "action_required" : "success"; params.decision.shouldClosePullRequest || hasBlockingFinding || !params.decision.safeToMerge ? "action_required" : "success";
await octokit.rest.checks.create({ await withRetry("github.checks.create", async () => {
owner: params.owner, return octokit.rest.checks.create({
repo: params.repo, owner: params.owner,
name: CHECK_RUN_NAME, repo: params.repo,
head_sha: params.headSha, name: CHECK_RUN_NAME,
status: "completed", head_sha: params.headSha,
conclusion, status: "completed",
output: { conclusion,
title: params.decision.shouldClosePullRequest output: {
? "Malicious code detected" title: params.decision.shouldClosePullRequest
: params.mode === "lenient" ? "Malicious code detected"
? "Lenient review completed" : params.mode === "lenient"
: "Strict review completed", ? "Lenient review completed"
summary: params.decision.shouldClosePullRequest : "Strict review completed",
? `${params.decision.summary}\n\nClose reason: ${params.decision.closeReason}` summary: params.decision.shouldClosePullRequest
: params.decision.summary ? `${params.decision.summary}\n\nClose reason: ${params.decision.closeReason}`
}, : params.decision.summary
details_url: `https://github.com/${params.owner}/${params.repo}/pull/${params.pullNumber}` },
details_url: `https://github.com/${params.owner}/${params.repo}/pull/${params.pullNumber}`
});
}); });
} }
@@ -440,18 +455,22 @@ async function closeMaliciousPullRequest(
reason: string; reason: string;
} }
): Promise<void> { ): Promise<void> {
await octokit.rest.issues.createComment({ await withRetry("github.issues.createComment.closeMalicious", async () => {
owner: params.owner, return octokit.rest.issues.createComment({
repo: params.repo, owner: params.owner,
issue_number: params.pullNumber, repo: params.repo,
body: `This PR was automatically closed because the review detected clearly malicious code.\n\nReason: ${params.reason}` issue_number: params.pullNumber,
body: `This PR was automatically closed because the review detected clearly malicious code.\n\nReason: ${params.reason}`
});
}); });
await octokit.rest.pulls.update({ await withRetry("github.pulls.update.closeMalicious", async () => {
owner: params.owner, return octokit.rest.pulls.update({
repo: params.repo, owner: params.owner,
pull_number: params.pullNumber, repo: params.repo,
state: "closed" pull_number: params.pullNumber,
state: "closed"
});
}); });
} }