ci: keep each outside contributor to two open pull requests (#4466)

* ci: keep each outside contributor to two open pull requests

A pr-limit workflow (pull_request_target: opened, reopened) closes a pull
request beyond its author's oldest two open ones, with a comment that
explains the limit. The owner, members, collaborators and bots are exempt.
It checks out only the base commit and passes event data through env, as
tests/test_cla_workflow.py requires of privileged workflows.
CONTRIBUTING.md documents the limit (it replaces the old advisory five).

* docs(changelog): open pull request limit (#4466)

* ci: drop the gitleaks entry for a commit squashed out of main

* ci: reconcile every open pull request against the limit; drop issues:write

A reopened older pull request, or one whose queued run was superseded,
could stay open above the limit. Each run now keeps the author's oldest two
other open pull requests and closes the rest, the triggering one first.

* ci: close the triggering pull request first
This commit is contained in:
Palash Debnath authored and GitHub committed 2026-11-25 16:21:11 +05:30
1 parent 3cff27bb99
commit 02aea1b0a6
6 files changed
+218 -5

No files matched your search

+7 -1
View File
@@ -220,9 +220,15 @@ Open an [issue](https://github.com/debpalash/VoiceStudio/issues/new) with:
### Pull Requests
**At most two open pull requests per contributor.** Unless you are the owner, a
member or a collaborator, keep no more than two pull requests open at once. A
third one, including one you reopen, is closed automatically with a comment (`.github/workflows/pr-limit.yml`);
reopen or resubmit it once one of your open pull requests is merged or closed.
Batch related small fixes into one pull request rather than opening many.
1. **Fork** the repo and create a branch from the latest `main`. In a clone of your fork, add this repository once with `git remote add upstream https://github.com/debpalash/VoiceStudio.git`, then `git fetch upstream` and `git switch -c <branch> upstream/main`
2. **Keep it current with `main`**: merge the latest `main` into your branch right before every push. `main` requires branches to be up to date, so a PR that is behind can't merge and has to run CI again once it's updated
3. **Keep PRs focused** — one feature or fix per PR. Keep **at most 5 PRs open at a time**; open the next one when one lands. Every PR uses CI resources and gets read before merge
3. **Keep PRs focused** — one feature or fix per PR. Keep **at most 2 PRs open at a time** (enforced, see above); open the next one when one lands. Every PR uses CI resources and gets read before merge
4. **Prefer user-facing fixes**: bugs with an open issue or a reproducible failure come first. For new meta-tests, CI policy or tooling-only changes, open an issue first so maintainers can say whether they want them
5. **Run tests** before pushing:
```bash
+105
View File
@@ -0,0 +1,105 @@
#!/usr/bin/env python3
"""Keep each outside contributor to at most two open pull requests.
Run from the base branch on ``pull_request_target`` (opened / reopened). The
repository owner, organisation members, collaborators and bots are exempt. For
anyone else, their oldest ``LIMIT`` other open pull requests stay open; the
opened or reopened one, and any other beyond the limit, is closed with a comment explaining the limit, so review and CI capacity go to
pull requests that can be reviewed.
Security: no pull-request code is checked out or executed. The script only
reads the open pull-request list and closes or comments through the API.
"""
from __future__ import annotations
import json
import os
import sys
import urllib.request
API = "https://api.github.com"
LIMIT = 2
EXEMPT_ASSOCIATIONS = {"OWNER", "MEMBER", "COLLABORATOR"}
MESSAGE = (
"Thanks for contributing! This repository keeps each outside contributor to "
f"at most {LIMIT} open pull requests at a time, so every one can get a real "
"review and a CI run. You already have {open_count} open: {others}. This one "
"is closed for now; reopen or resubmit it once one of those is merged or "
"closed, and please batch related small fixes into one pull request."
)
def is_exempt(association: str, user_type: str) -> bool:
return association.upper() in EXEMPT_ASSOCIATIONS or user_type == "Bot"
def plan(number: int, author: str, open_prs: list[dict], limit: int = LIMIT) -> tuple[list[int], list[int]]:
"""``(kept, to_close)`` for ``author``'s open pull requests.
The author's other open pull requests are kept oldest first, and the
triggering one ``number`` comes last, so a newly opened or reopened pull
request is the first to close. Every run reconciles the whole set, so a pull
request that a skipped or superseded run never checked is closed too.
"""
others = sorted(
pr["number"] for pr in open_prs
if (pr.get("user") or {}).get("login") == author and pr["number"] != number
)
ordered = [*others, number]
kept, excess = ordered[:limit], ordered[limit:]
# The triggering pull request closes first, so a failed later API call
# never leaves it open.
if number in excess:
excess = [number, *(n for n in excess if n != number)]
return kept, excess
def _api(method: str, path: str, token: str, body: dict | None = None):
request = urllib.request.Request(
API + path,
method=method,
data=json.dumps(body).encode() if body is not None else None,
headers={
"Authorization": f"Bearer {token}",
"Accept": "application/vnd.github+json",
"X-GitHub-Api-Version": "2022-11-28",
},
)
with urllib.request.urlopen(request, timeout=30) as response:
data = response.read()
return json.loads(data) if data else None
def open_pulls(repo: str, token: str) -> list[dict]:
pulls: list[dict] = []
for page in range(1, 21):
batch = _api("GET", f"/repos/{repo}/pulls?state=open&per_page=100&page={page}", token)
pulls.extend(batch)
if len(batch) < 100:
break
return pulls
def main() -> int:
token = os.environ["GITHUB_TOKEN"]
repo = os.environ["GITHUB_REPOSITORY"]
number = int(os.environ["PR"])
author = os.environ["AUTHOR"]
if is_exempt(os.environ.get("ASSOCIATION", ""), os.environ.get("AUTHOR_TYPE", "")):
print(f"#{number}: {author} is exempt")
return 0
kept, to_close = plan(number, author, open_pulls(repo, token))
if not to_close:
print(f"#{number}: within the limit")
return 0
others = ", ".join(f"#{n}" for n in kept)
for closing in to_close:
_api("POST", f"/repos/{repo}/issues/{closing}/comments", token,
{"body": MESSAGE.format(open_count=len(kept), others=others)})
_api("PATCH", f"/repos/{repo}/pulls/{closing}", token, {"state": "closed"})
print(f"#{closing}: closed ({author} keeps {others} open)")
return 0
if __name__ == "__main__":
sys.exit(main())
+42
View File
@@ -0,0 +1,42 @@
# Keep each outside contributor to at most two open pull requests.
#
# A flood of micro pull requests from one author starves review and the
# repository's shared runner slots. The owner, members, collaborators and bots
# are exempt; for anyone else every run keeps their oldest two other open pull
# requests and closes the rest, newest-opened first, with a comment (.github/scripts/enforce_pr_limit.py).
#
# Security: pull_request_target holds a write token, so this checks out only the
# base commit and never runs pull-request code; tests/test_cla_workflow.py
# enforces that for every privileged workflow.
name: pr-limit
on:
pull_request_target:
types: [opened, reopened]
permissions:
contents: read
pull-requests: write
concurrency:
group: pr-limit-${{ github.event.pull_request.user.login }}
cancel-in-progress: false
jobs:
limit:
name: Open pull request limit
runs-on: ubuntu-24.04
timeout-minutes: 5
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Close a pull request beyond the author's limit
run: python3 .github/scripts/enforce_pr_limit.py
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
PR: ${{ github.event.pull_request.number }}
AUTHOR: ${{ github.event.pull_request.user.login }}
AUTHOR_TYPE: ${{ github.event.pull_request.user.type }}
ASSOCIATION: ${{ github.event.pull_request.author_association }}
-4
View File
@@ -14,7 +14,3 @@ f6d634e19902c0fd0e64947e635359d5bc1f85de:electron/tests/fake-health-backend.test
# The Crockford base32 alphabet that generates the report idempotency key, not a credential.
4dab817e78d54b055967860581687eeb5bb77472:mobile/android/core/network/src/main/kotlin/com/voicestudio/mobile/network/ContentReports.kt:generic-api-key:38
#
# Synthetic test fixture value in a #4371 translation-error test (not a credential;
# later commits build it at runtime).
481aa43be57ec256349e659063c2f0d7751b8008:tests/test_translation_apis.py:generic-api-key:195
+1
View File
@@ -0,0 +1 @@
Outside contributors can keep at most two pull requests open at a time; newer ones are closed automatically with an explanation (#4466)
+63
View File
@@ -0,0 +1,63 @@
"""The two-open-pull-request limit for outside contributors."""
import importlib.util
from pathlib import Path
import yaml
ROOT = Path(__file__).resolve().parents[1]
def _script():
spec = importlib.util.spec_from_file_location("enforce_pr_limit", ROOT / ".github/scripts/enforce_pr_limit.py")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def _pr(number, login):
return {"number": number, "user": {"login": login}}
def test_a_third_pull_request_is_closed_and_two_stay_open():
limit = _script()
prs = [_pr(10, "a"), _pr(12, "a"), _pr(11, "b"), _pr(15, "a")]
assert limit.plan(15, "a", prs) == ([10, 12], [15])
assert limit.plan(11, "b", prs) == ([11], [])
assert limit.plan(12, "a", [_pr(10, "a"), _pr(12, "a")]) == ([10, 12], [])
def test_a_pull_request_missing_from_the_listing_still_counts():
limit = _script()
assert limit.plan(20, "a", [_pr(10, "a"), _pr(12, "a")]) == ([10, 12], [20])
def test_reopening_an_older_pull_request_closes_that_one():
limit = _script()
prs = [_pr(3, "a"), _pr(10, "a"), _pr(12, "a")]
assert limit.plan(3, "a", prs) == ([10, 12], [3])
def test_a_pull_request_a_skipped_run_missed_is_closed_too():
limit = _script()
prs = [_pr(1, "a"), _pr(2, "a"), _pr(4, "a"), _pr(5, "a")]
assert limit.plan(5, "a", prs) == ([1, 2], [5, 4]) # the triggering one first
def test_maintainers_and_bots_are_exempt():
limit = _script()
for association in ("OWNER", "MEMBER", "COLLABORATOR", "owner"):
assert limit.is_exempt(association, "User")
assert limit.is_exempt("NONE", "Bot")
for association in ("CONTRIBUTOR", "FIRST_TIME_CONTRIBUTOR", "FIRST_TIMER", "NONE"):
assert not limit.is_exempt(association, "User")
def test_the_workflow_runs_on_open_and_reopen_and_passes_event_data_via_env():
text = (ROOT / ".github/workflows/pr-limit.yml").read_text(encoding="utf-8")
workflow = yaml.safe_load(text)
on = workflow.get("on", workflow.get(True))
assert set(on["pull_request_target"]["types"]) == {"opened", "reopened"}
step = workflow["jobs"]["limit"]["steps"][1]
assert "${{" not in step["run"]
assert step["env"]["ASSOCIATION"] == "${{ github.event.pull_request.author_association }}"
assert workflow["permissions"] == {"contents": "read", "pull-requests": "write"}