Skip to content

Commit e4b92af

Browse files
authored
ci: draft inactive PRs awaiting author action (apache#26715)
## Which issue does this PR close? Related to apache#26684. ## Rationale for this change Keep the active review queue focused on PRs that can progress. ## What changes are included in this PR? Automatically draft PRs inactive for 14 days with merge conflicts, failing CI, or changes requested on the latest push. Includes a brief explanation and a manual dry-run mode. ## What is the testing strategy for this PR? Validated with workflow lint and a live dry run (69 eligible PRs); no automated tests added. ## Are there any user-facing changes? Authors can mark their PR ready for review again. The draft notification restarts the existing 60-day stale timer.
1 parent 36f3935 commit e4b92af

3 files changed

Lines changed: 261 additions & 0 deletions

File tree

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
# Licensed to the Apache Software Foundation (ASF) under one
2+
# or more contributor license agreements. See the NOTICE file
3+
# distributed with this work for additional information
4+
# regarding copyright ownership. The ASF licenses this file
5+
# to you under the Apache License, Version 2.0 (the
6+
# "License"); you may not use this file except in compliance
7+
# with the License. You may obtain a copy of the License at
8+
#
9+
# http://www.apache.org/licenses/LICENSE-2.0
10+
#
11+
# Unless required by applicable law or agreed to in writing,
12+
# software distributed under the License is distributed on an
13+
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14+
# KIND, either express or implied. See the License for the
15+
# specific language governing permissions and limitations
16+
# under the License.
17+
18+
name: Draft inactive PRs
19+
20+
on:
21+
schedule:
22+
- cron: "0 1 * * *"
23+
workflow_dispatch:
24+
inputs:
25+
dry_run:
26+
description: "Report eligible PRs without changing them"
27+
type: boolean
28+
default: true
29+
30+
permissions:
31+
checks: read
32+
statuses: read
33+
# Required by the convertPullRequestToDraft GraphQL mutation.
34+
contents: write
35+
pull-requests: write
36+
37+
concurrency:
38+
group: draft-inactive-prs
39+
cancel-in-progress: false
40+
41+
jobs:
42+
draft:
43+
if: github.repository == 'apache/datafusion'
44+
runs-on: ubuntu-slim
45+
timeout-minutes: 15
46+
steps:
47+
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
48+
with:
49+
ref: ${{ github.event.repository.default_branch }}
50+
persist-credentials: false
51+
- uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
52+
env:
53+
DRY_RUN: ${{ github.event_name == 'workflow_dispatch' && inputs.dry_run }}
54+
with:
55+
script: |
56+
const { run } = require('./ci/scripts/draft_inactive_prs.cjs');
57+
const dryRun = process.env.DRY_RUN !== 'false';
58+
const results = await run({ github, context, core, dryRun });
59+
await core.summary
60+
.addHeading(dryRun ? 'Would mark as draft' : 'Marked as draft')
61+
.addTable([
62+
[{ data: 'PR', header: true }, { data: 'Reason', header: true }],
63+
...results.map(({ number, reasons }) => [String(number), reasons.join('; ')]),
64+
])
65+
.write();

‎ci/scripts/draft_inactive_prs.cjs‎

Lines changed: 182 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,182 @@
1+
// Licensed to the Apache Software Foundation (ASF) under one
2+
// or more contributor license agreements. See the NOTICE file
3+
// distributed with this work for additional information
4+
// regarding copyright ownership. The ASF licenses this file
5+
// to you under the Apache License, Version 2.0 (the
6+
// "License"); you may not use this file except in compliance
7+
// with the License. You may obtain a copy of the License at
8+
//
9+
// http://www.apache.org/licenses/LICENSE-2.0
10+
//
11+
// Unless required by applicable law or agreed to in writing,
12+
// software distributed under the License is distributed on an
13+
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14+
// KIND, either express or implied. See the License for the
15+
// specific language governing permissions and limitations
16+
// under the License.
17+
18+
const { setTimeout } = require("node:timers/promises");
19+
20+
const IDLE_DAYS = 14;
21+
const QUERY = `query(
22+
$owner: String!, $repo: String!, $number: Int!,
23+
$checksCursor: String, $reviewsCursor: String,
24+
$loadChecks: Boolean!, $loadReviews: Boolean!
25+
) {
26+
repository(owner: $owner, name: $repo) {
27+
pullRequest(number: $number) {
28+
id number state isDraft updatedAt headRefOid mergeable
29+
mergeQueueEntry { id }
30+
latestOpinionatedReviews(first: 100, after: $reviewsCursor) @include(if: $loadReviews) {
31+
nodes { state commit { oid } }
32+
pageInfo { hasNextPage endCursor }
33+
}
34+
commits(last: 1) @include(if: $loadChecks) {
35+
nodes { commit {
36+
statusCheckRollup {
37+
contexts(first: 100, after: $checksCursor) {
38+
nodes {
39+
... on CheckRun { status conclusion }
40+
... on StatusContext { state }
41+
}
42+
pageInfo { hasNextPage endCursor }
43+
}
44+
}
45+
} }
46+
}
47+
}
48+
}
49+
}`;
50+
51+
const sameVersion = (a, b) =>
52+
a.headRefOid === b.headRefOid && a.updatedAt === b.updatedAt;
53+
54+
async function loadPullRequest(github, repo, number) {
55+
const variables = { ...repo, number, loadChecks: true, loadReviews: true };
56+
let pr;
57+
const checks = [];
58+
const reviews = [];
59+
while (variables.loadChecks || variables.loadReviews) {
60+
const { repository } = await github.graphql(QUERY, variables);
61+
const current = repository.pullRequest;
62+
if (!current || (pr && !sameVersion(pr, current))) return null;
63+
pr = { ...pr, ...current };
64+
if (variables.loadChecks) {
65+
const connection =
66+
current.commits.nodes[0]?.commit.statusCheckRollup?.contexts;
67+
checks.push(...(connection?.nodes ?? []));
68+
variables.loadChecks = connection?.pageInfo.hasNextPage ?? false;
69+
variables.checksCursor = connection?.pageInfo.endCursor;
70+
}
71+
if (variables.loadReviews) {
72+
const connection = current.latestOpinionatedReviews;
73+
reviews.push(...connection.nodes);
74+
variables.loadReviews = connection.pageInfo.hasNextPage;
75+
variables.reviewsCursor = connection.pageInfo.endCursor;
76+
}
77+
}
78+
return { ...pr, checks, reviews };
79+
}
80+
81+
function reasonsToDraft(pr, cutoff) {
82+
if (
83+
!pr ||
84+
pr.state !== "OPEN" ||
85+
pr.isDraft ||
86+
pr.mergeQueueEntry ||
87+
!(Date.parse(pr.updatedAt) <= cutoff)
88+
)
89+
return [];
90+
91+
const reasons = [];
92+
if (pr.mergeable === "CONFLICTING") reasons.push("merge conflicts");
93+
// The rollup reports FAILURE for cancelled checks too.
94+
if (
95+
pr.checks.some(
96+
(check) =>
97+
(check.status === "COMPLETED" &&
98+
["FAILURE", "TIMED_OUT"].includes(check.conclusion)) ||
99+
["FAILURE", "ERROR"].includes(check.state)
100+
)
101+
)
102+
reasons.push("failing CI checks");
103+
104+
if (
105+
pr.reviews.some(
106+
(review) =>
107+
review.state === "CHANGES_REQUESTED" &&
108+
review.commit?.oid === pr.headRefOid
109+
)
110+
)
111+
reasons.push("changes requested on the latest push");
112+
return reasons;
113+
}
114+
115+
async function run({ github, context, core, dryRun = true }) {
116+
const repo = { owner: context.repo.owner, repo: context.repo.repo };
117+
const cutoff = Date.now() - IDLE_DAYS * 24 * 60 * 60 * 1000;
118+
// Collect the list before mutations change updated_at and its pagination.
119+
const prs = await github.paginate(github.rest.pulls.list, {
120+
...repo,
121+
state: "open",
122+
sort: "updated",
123+
direction: "asc",
124+
per_page: 100,
125+
});
126+
const candidates = prs.filter(
127+
(listed) => !listed.draft && Date.parse(listed.updated_at) <= cutoff
128+
);
129+
if (!candidates.length) return [];
130+
131+
// GitHub computes mergeability lazily; warm every candidate before deciding.
132+
for (const listed of candidates) {
133+
await loadPullRequest(github, repo, listed.number);
134+
}
135+
await setTimeout(30_000);
136+
137+
const results = [];
138+
for (const listed of candidates) {
139+
let pr = await loadPullRequest(github, repo, listed.number);
140+
if (pr?.mergeable === "UNKNOWN") {
141+
core.warning(`Mergeability is still unknown for #${listed.number}.`);
142+
}
143+
let reasons = reasonsToDraft(pr, cutoff);
144+
if (!reasons.length) continue;
145+
if (!dryRun) {
146+
const fresh = await loadPullRequest(github, repo, listed.number);
147+
if (!fresh || !sameVersion(pr, fresh)) continue;
148+
pr = fresh;
149+
reasons = reasonsToDraft(pr, cutoff);
150+
if (!reasons.length) continue;
151+
await github.graphql(
152+
`mutation($id: ID!) {
153+
convertPullRequestToDraft(input: { pullRequestId: $id }) {
154+
pullRequest { id }
155+
}
156+
}`,
157+
{ id: pr.id }
158+
);
159+
// Respect GitHub's secondary rate limits between writes.
160+
await setTimeout(1000);
161+
await github.rest.issues.createComment({
162+
...repo,
163+
issue_number: pr.number,
164+
body:
165+
`Marked as draft after ${IDLE_DAYS} days without activity: ${reasons.join(
166+
"; "
167+
)}.\n\n` +
168+
"Please address these items and mark **Ready for review** when ready.",
169+
});
170+
await setTimeout(1000);
171+
}
172+
core.info(
173+
`${dryRun ? "Would draft" : "Drafted"} #${pr.number}: ${reasons.join(
174+
"; "
175+
)}`
176+
);
177+
results.push({ number: pr.number, reasons });
178+
}
179+
return results;
180+
}
181+
182+
module.exports = { run };

‎docs/source/contributor-guide/index.md‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -205,8 +205,22 @@ The good thing about open code and open development is that any issues in one ch
205205

206206
## Stale PRs
207207

208+
Open, non-draft PRs with no activity for 14 days are automatically marked as
209+
draft if they have merge conflicts, failing CI checks, or an outstanding
210+
changes-requested review on the latest push. PRs awaiting review with none of
211+
these conditions remain ready for review. Cancelled, pending, skipped, or missing
212+
CI checks do not trigger drafting. PRs in the merge queue are excluded.
213+
214+
The automation leaves a comment explaining why the PR was drafted. After
215+
addressing the listed items, mark the PR **Ready for review**. If you need help
216+
or a CI failure is unrelated to your changes, leave a comment on the PR.
217+
218+
Maintainers can preview eligible PRs by running the **Draft inactive PRs**
219+
workflow manually with its default `dry_run` input enabled.
220+
208221
Pull requests will be marked with a `stale` label after 60 days of inactivity and then closed 7 days after that.
209222
Commenting on the PR will remove the `stale` label.
223+
The automatic draft notification also counts as activity and restarts this timer.
210224

211225
## CI Runners
212226

0 commit comments

Comments
 (0)