ci: make nightly merge opt-out and simplify Docbot labels (#10601)

* ci: make nightly merge opt-out and simplify Docbot labels

Signed-off-by: shuiyisong <xixing.sys@gmail.com>

* ci: scope nightly label migration and sync to main

Use the saved nightly preference only for PRs targeting main at both
snapshot and apply time. Clean up docs-not-required across all bases.

Restore the skip label when it is removed while the opt-out box is
checked.

Signed-off-by: shuiyisong <xixing.sys@gmail.com>

* ci: honor cleared nightly opt-outs on retry

Signed-off-by: shuiyisong <xixing.sys@gmail.com>

---------

Signed-off-by: shuiyisong <xixing.sys@gmail.com>
This commit is contained in:
shuiyisong
2026-11-24 10:42:29 +00:00
committed by GitHub
parent 21d6a25dfb
commit 81e60511b5
9 changed files with 594 additions and 122 deletions
+72 -18
View File
@@ -1,18 +1,20 @@
# Nightly merge
The PR template opts new PRs into the `merge nightly` label. The Nightly Merge
workflow reconciles the label on PR creation, edits, and reopening. Existing PRs
without the checkbox can opt in by adding the label manually; label sync leaves
their labels unchanged. Unchecking removes the label; it does not
request an immediate merge or cancel an existing queue entry/auto-merge request.
Open PRs targeting `main` participate by default, including automated PRs
without a checklist. Check **Skip nightly merge** to opt out. The scheduler
honors the checkbox immediately, and label sync adds `skip nightly merge`.
Uncheck the box to release the bot's hold. Maintainers can also apply the label
directly and remove it when ready. If someone removes the label while the box
is checked, label sync restores it. A manually applied label survives title
and description edits.
Every day at 02:10, 03:10, 04:10, 05:10, 06:10, 07:10, and 08:10
Asia/Shanghai (UTC+8), the workflow enqueues up to five eligible PRs targeting
`main` per run, oldest first. Already queued PRs do not count toward this limit.
GitHub may delay scheduled runs.
The label alone controls nightly opt-in; the enqueue job does not check the PR
body. PRs must be approved and clean, and have all
review threads resolved. Drafts are skipped.
PRs must be approved and clean, with all review threads resolved. Drafts are
skipped. The workflow rechecks the current opt-out label and checkbox before
enqueueing at the reviewed head SHA.
If GitHub rejects enqueueing because a PR belongs to a stack, the workflow skips
it and continues without failing the run or counting it toward the five-PR limit.
Other API errors still fail the run. Dry runs do not call the enqueue API, so
@@ -23,7 +25,7 @@ scheduled run; this workflow never enables auto-merge on their behalf.
## Repository setup
- Create the `merge nightly` label before enabling the workflow.
- Create the `skip nightly merge` label before enabling the workflow.
- Require the merge queue, reviews, status checks, and conversation resolution
on `main`. Conversation resolution must also be enforced by GitHub to cover
new comments arriving between the script's check and enqueueing.
@@ -32,18 +34,70 @@ scheduled run; this workflow never enables auto-merge on their behalf.
branch-rule bypass. This credential is already referenced by other workflows;
its actual permissions have not been validated by the local tests.
- Run **Nightly Merge** manually with the default `dry_run: true` first and
inspect its job summary. Setting it to false explicitly enqueues outside the
scheduled time as well. Merge queue build concurrency is configured separately
in GitHub; this workflow does not change it.
inspect its job summary. The repository variable `NIGHTLY_MERGE_ENABLED`
must be `true` for scheduled runs and manual dispatches that enqueue PRs.
Set it after completing the migration below.
The workflow never checks out or executes PR code. Label reconciliation uses
`GITHUB_TOKEN`; enqueueing uses the automation credential so downstream CI can
run. No runner remains allocated while waiting for the nightly schedule.
The PR event job reads the checklist helper from the trusted workflow commit.
Label reconciliation uses `GITHUB_TOKEN`. Enqueueing uses the automation
credential so downstream CI can run.
## One-time migration of open PRs
Use a maintainer's authenticated `gh` session from the checkout containing
this change. PR body edits made by this account trigger checkbox label sync.
1. Before merging, create the opt-out label. Leave `NIGHTLY_MERGE_ENABLED`
unset so the new workflow starts with enqueueing paused. Dry runs and label
sync remain available. Let any active enqueue job from the old workflow finish.
2. Immediately after merging, capture the open PRs with their old labels.
Supply the rollout PR number so the snapshot excludes PRs opened at or
after GitHub's recorded merge time. New PRs can open throughout the rollout.
Finish or rerun any pending label updates from the old workflow before
taking the snapshot. Keep the file for verification and retries.
```sh
node .github/scripts/migrate-pr-labels.cjs snapshot /tmp/pr-labels.json ROLLOUT_PR_NUMBER
```
3. Apply the saved snapshot. The migration removes `docs-not-required` from
captured open PRs on every base branch. For PRs targeting `main` both in
the snapshot and at apply time, it also converts legacy checkboxes and
removes `merge nightly`. A converted checkbox is unchecked if the PR had
`merge nightly` in the snapshot and checked otherwise. For PRs that lacked
the old label, `apply` adds a manual hold only when the checkbox is missing.
If an author unchecks **Skip nightly merge**, retrying `apply` honors that
choice. Coordinate retargeting and description edits during apply because
GitHub accepts the complete PR body on update.
```sh
node .github/scripts/migrate-pr-labels.cjs apply /tmp/pr-labels.json
```
4. Let checkbox sync finish, then verify against the same snapshot. Verification
lists outstanding changes and exits unsuccessfully for any mismatch. If a
checked box still needs a label, rerun its failed label job or edit its
description to trigger sync. Confirm any new manual opt-out with the
maintainer and record it as an intentional difference. For a PR retargeted
into `main`, record its current choice with a **Skip nightly merge** checkbox
(checked to hold, unchecked to participate) or a manual `skip nightly merge`
label. Verification flags a retargeted PR until it has a current choice.
An interrupted apply can be rerun with the original snapshot.
```sh
node .github/scripts/migrate-pr-labels.cjs verify /tmp/pr-labels.json
```
5. Run **Nightly Merge** with `dry_run: true` and inspect its summary. Once the
verified pool is correct, set `NIGHTLY_MERGE_ENABLED` to `true` to resume enqueueing.
Docbot now adds `docs-required` when requested. On merge, that label controls
whether it creates a follow-up issue in the docs repository.
## Local validation
Run `actionlint .github/workflows/nightly-merge.yml .github/workflows/checks.yml`
and `node --test .github/scripts/tests/nightly-merge.test.cjs`.
The tests execute the actual inline workflow scripts with mocked GitHub APIs,
Run `actionlint .github/workflows/{nightly-merge,docbot,checks}.yml`,
`node --test .github/scripts/tests/nightly-merge.test.cjs`, and `pnpm --dir cyborg test`.
The tests execute the workflow scripts with mocked GitHub APIs,
including one-factor comparisons against an eligible PR. They do not validate
live GitHub permissions, branch rules, or runner savings.
+2 -2
View File
@@ -28,11 +28,11 @@ Please convert it to a draft if some of the following conditions are not met.
## Merge timing
- [x] Merge during the nightly window <!-- nightly-merge -->
- [ ] Skip nightly merge
<!--
Eligible PRs enter the merge queue hourly from 02:10 through 08:10 Beijing time (UTC+8), up to five per run.
Uncheck to opt out and remove the `merge nightly` label; this does not enable immediate merging.
Check to opt out. To resume, uncheck the box and remove any manually applied `skip nightly merge` label.
Maintainers can use **Merge when ready** to merge earlier.
Changing this checkbox does not cancel an existing queue entry or manually enabled auto-merge.
-->
+126
View File
@@ -0,0 +1,126 @@
// Copyright 2023 Greptime Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
const { execFileSync } = require('node:child_process');
const { readFileSync, writeFileSync } = require('node:fs');
const { checklistItems, skipCheckboxState, skipLabel } = require('./nightly-merge.cjs');
const repository = 'GreptimeTeam/greptimedb';
const oldNightly = 'merge nightly';
const oldDocs = 'docs-not-required';
function api(path, args = [], data) {
const input = data === undefined ? undefined : JSON.stringify(data);
return execFileSync('gh', ['api', `repos/${repository}/${path}`, ...args,
...(input === undefined ? [] : ['--input', '-'])], { encoding: 'utf8', input });
}
function migrateBody(body, hold) {
let updated = body;
// Work backwards so each replacement keeps the offsets of earlier items valid.
for (const item of [...checklistItems(body)].reverse()) {
const old = /^Merge during the nightly window\b(?:[ \t]*<!-- nightly-merge -->)?/i.exec(item.text);
if (old) {
const following = updated.slice(item.end).replace(/^(?:[ \t]*\r?\n)+ {0,3}<!--[\s\S]*?-->/, comment =>
comment.replace(/^Uncheck to opt out and remove the `merge nightly` label; this does not enable immediate merging\.$/m,
'Check to opt out. To resume, uncheck the box and remove any manually applied `skip nightly merge` label.'));
updated = updated.slice(0, item.index) + (hold ? '[x]' : '[ ]') + item.space +
'Skip nightly merge' + item.text.slice(old[0].length) + following;
}
}
return updated;
}
function changesFor(entry, pr) {
const labels = new Set(pr.labels.map(label => label.name));
const targetsMain = pr.base.ref === 'main';
const migrateNightly = targetsMain && entry.base === 'main';
const hold = migrateNightly && !entry.optedIn;
const body = migrateNightly ? migrateBody(pr.body, hold) : pr.body;
const checkbox = targetsMain ? skipCheckboxState(body) : null;
const labeled = labels.has(skipLabel);
const obsolete = migrateNightly ? [oldNightly, oldDocs] : [oldDocs];
return {
body,
// A converted checked box gets a bot-owned label from its edit event.
addHold: hold && checkbox === null && !labeled,
remove: obsolete.filter(label => labels.has(label)),
waitingForSync: checkbox === true && !labeled,
extraHold: migrateNightly && entry.optedIn && (checkbox === true || labeled),
needsChoice: targetsMain && !migrateNightly && checkbox === null && !labeled,
};
}
function openBefore(mergedAt) {
const rows = api('pulls?state=open&sort=created&direction=asc&per_page=100', ['--paginate', '--jq',
`.[] | select(.created_at < ${JSON.stringify(mergedAt)}) | {number, base: .base.ref, optedIn: any(.labels[]; .name == "${oldNightly}")} | @json`]);
return rows.trim().split('\n').filter(Boolean).map(line => JSON.parse(line));
}
function main([mode, file, rolloutPR]) {
if (!file || !['snapshot', 'apply', 'verify'].includes(mode) || (mode === 'snapshot' && !/^[1-9]\d*$/.test(rolloutPR))) {
throw new Error('Usage: node .github/scripts/migrate-pr-labels.cjs snapshot SNAPSHOT.json ROLLOUT_PR | apply|verify SNAPSHOT.json');
}
if (mode === 'snapshot') {
const { merged_at: mergedAt, base } = JSON.parse(api(`pulls/${rolloutPR}`));
if (!mergedAt || base.ref !== 'main') throw new Error(`Rollout PR #${rolloutPR} must be merged into main`);
const prs = openBefore(mergedAt);
writeFileSync(file, JSON.stringify({ repository, rolloutPR, mergedAt, prs }, null, 2) + '\n', { flag: 'wx' });
console.log(`Saved ${prs.length} open PRs to ${file}`);
return;
}
const snapshot = JSON.parse(readFileSync(file, 'utf8'));
if (snapshot.repository !== repository || !snapshot.mergedAt || !Array.isArray(snapshot.prs) || !snapshot.prs.every(entry =>
Number.isSafeInteger(entry.number) && entry.number > 0 && typeof entry.base === 'string' && typeof entry.optedIn === 'boolean')) {
throw new Error('Invalid migration snapshot');
}
let open = 0;
if (mode === 'verify') {
const captured = new Set(snapshot.prs.map(entry => entry.number));
for (const pr of openBefore(snapshot.mergedAt)) {
if (!captured.has(pr.number)) {
console.error(`#${pr.number}: open before rollout but missing from the snapshot`);
process.exitCode = 1;
}
}
}
for (const entry of snapshot.prs) {
const number = entry.number;
const pr = JSON.parse(api(`pulls/${number}`));
if (pr.state !== 'open') continue;
open++;
const { body, addHold, remove, waitingForSync, extraHold, needsChoice } = changesFor(entry, pr);
if (mode === 'apply') {
if (body !== pr.body) api(`pulls/${number}`, ['--method', 'PATCH', '--silent'], { body });
if (addHold) api(`issues/${number}/labels`, ['--method', 'POST', '--silent'], { labels: [skipLabel] });
for (const label of remove) {
api(`issues/${number}/labels/${encodeURIComponent(label)}`, ['--method', 'DELETE', '--silent']);
}
} else {
const pending = remove.map(label => `remove ${label}`);
if (body !== pr.body) pending.push('convert legacy checkbox');
if (addHold || waitingForSync) pending.push(`missing ${skipLabel}`);
if (extraHold) pending.push('review opt-out added since snapshot');
if (needsChoice) pending.push(`record a nightly preference after retargeting from ${entry.base} to main`);
if (pending.length) {
console.error(`#${number}: ${pending.join(', ')}`);
process.exitCode = 1;
}
}
}
console.log(`${mode === 'apply' ? 'Applied migration to' : 'Checked'} ${open} open PRs from ${file}`);
}
if (require.main === module) main(process.argv.slice(2));
module.exports = { changesFor };
+79
View File
@@ -0,0 +1,79 @@
// Copyright 2023 Greptime Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
const skipLabel = 'skip nightly merge';
// Exclude quoted, commented and fenced examples from both sync and migration.
function* checklistItems(body) {
let fence = '';
let inComment = false;
const listIndents = [0];
for (const match of (body || '').matchAll(/^[^\r\n]+/gm)) {
const line = match[0];
if (!line.trim()) continue;
const block = line.includes('\t') ? line.split('\t').reduce((before, after) =>
before + ' '.repeat(4 - before.length % 4) + after) : line;
const indent = /^ */.exec(block)[0].length;
// Leaving a list item also ends its fence, even without a closing delimiter.
while (indent < listIndents.at(-1)) {
listIndents.pop();
fence = '';
}
let content = block.slice(listIndents.at(-1));
if (!fence && !inComment) {
let list;
while ((list = /^ {0,3}(?:[-*+]|\d{1,9}[.)]) {1,4}(?=\S)/.exec(content))) {
listIndents.push(listIndents.at(-1) + list[0].length);
content = content.slice(list[0].length);
}
}
const marker = /^ {0,3}(`{3,}(?=[^`]*$)|~{3,})/.exec(content)?.[1];
if (fence) {
if (marker?.startsWith(fence) && content.trim() === marker) fence = '';
} else if (inComment) {
inComment = !line.includes('-->');
} else if (marker) {
fence = marker;
} else {
inComment = line.trimStart().startsWith('<!--') && line.lastIndexOf('<!--') > line.lastIndexOf('-->');
const item = /^( {0,3}[-*+][ \t]+)\[([ xX])\]([ \t]+)(.*)$/.exec(line);
if (item) {
yield { index: match.index + item[1].length, end: match.index + line.length,
checked: item[2] !== ' ', space: item[3], text: item[4] };
}
}
}
}
// Rollout verification distinguishes a missing checkbox from an unchecked one.
function skipCheckboxState(body) {
let state = null;
for (const item of checklistItems(body)) {
if (!/^Skip nightly merge\b/i.test(item.text)) continue;
if (item.checked) return true;
state = false;
}
return state;
}
function skipChecked(body) {
return skipCheckboxState(body) === true;
}
function eligibleForNightly(pr) {
return pr.state === 'open' && !pr.draft && pr.base.ref === 'main' &&
!pr.labels.some(label => label.name === skipLabel) && !skipChecked(pr.body);
}
module.exports = { checklistItems, skipLabel, skipCheckboxState, skipChecked, eligibleForNightly };
+194 -25
View File
@@ -19,27 +19,48 @@ const assert = require('node:assert/strict');
const { test } = require('node:test');
const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor;
const workflow = readFileSync(resolve(__dirname, '../../workflows/nightly-merge.yml'), 'utf8');
const template = readFileSync(resolve(__dirname, '../../pull_request_template.md'), 'utf8');
const scripts = [...workflow.matchAll(/ script: \|\n((?: .*\n|\n)+)/g)]
.map(match => new AsyncFunction('github', 'context', 'core', 'process', match[1].replace(/^ /gm, '')));
.map(match => new AsyncFunction('github', 'context', 'core', 'process', 'require', match[1].replace(/^ /gm, '')));
assert.equal(scripts.length, 2);
const checked = '- [x] Merge during the nightly window <!-- nightly-merge -->';
const { changesFor } = require('../migrate-pr-labels.cjs');
const label = 'skip nightly merge';
const checked = '- [x] Skip nightly merge';
const unchecked = '- [ ] Skip nightly merge';
const legacy = '- [x] Merge during the nightly window <!-- nightly-merge -->';
async function run({ sync = false, body = checked, labels = ['merge nightly'],
detail = {}, current = {}, threads = [[true]], count = 1, dryRun = false,
function migrateMainPr(optedIn, pr) {
return changesFor({ base: 'main', optedIn }, { ...pr, base: { ref: 'main' } });
}
async function run({ sync = false, body = unchecked, labels = [], events = [], payload = {},
detail = {}, listed = {}, current = {}, threads = [[true]], count = 1, dryRun = false,
failFirst = false, enqueueError = Error('head changed') } = {}) {
const calls = [];
let page = 0;
const pr = { state: 'open', draft: false, base: { ref: 'main' }, body, labels: labels.map(name => ({ name })) };
const github = {
rest: {
pulls: { get: async () => ({ data: { state: 'open', draft: false, base: { ref: 'main' },
body, labels: labels.map(name => ({ name })), ...current } }) },
pulls: { list() {}, get: async () => {
if (!sync) calls.push(['get']);
return { data: { ...pr, ...current } };
} },
issues: {
listForRepo: () => {},
listEvents() {},
addLabels: async args => calls.push(['add', args.labels]),
removeLabel: async args => calls.push(['remove', args.name])
}
},
paginate: async () => Array.from({ length: count }, (_, i) => ({ number: i + 1, pull_request: {} })),
paginate: async (route, args) => {
if (route === github.rest.issues.listEvents) {
assert.equal(args.issue_number, 1);
return events;
}
assert.equal(route, github.rest.pulls.list);
assert.deepEqual(args, { owner: 'GreptimeTeam', repo: 'greptimedb', state: 'open', base: 'main',
sort: 'created', direction: 'asc', per_page: 100 });
return Array.from({ length: count }, (_, i) => ({ ...pr, number: i + 1, ...listed }));
},
graphql: async (query, args) => {
if (query.includes('mutation')) {
calls.push(['enqueue', args]);
@@ -60,26 +81,77 @@ async function run({ sync = false, body = checked, labels = ['merge nightly'],
};
const summary = { addHeading() { return this; }, addTable(rows) { calls.push(['summary', rows]); return this; }, async write() {} };
await scripts[sync ? 0 : 1](github,
{ repo: { owner: 'GreptimeTeam', repo: 'greptimedb' }, payload: { pull_request: { number: 1 } } },
{ repo: { owner: 'GreptimeTeam', repo: 'greptimedb' }, payload: { pull_request: { number: 1 }, ...payload } },
{ summary, info() {}, warning() {}, setFailed: message => calls.push(['failed', message]) },
{ env: { DRY_RUN: String(dryRun) } });
{ env: { DRY_RUN: String(dryRun) } }, path => require(resolve(__dirname, '../../..', path)));
return calls;
}
test('label sync grants PR label write permission without checking out PR code', () => {
test('label sync reads the helper from the trusted workflow commit', () => {
const syncJob = workflow.split(' sync-label:\n')[1].split(' enqueue:\n')[0];
assert.match(syncJob, /^ pull-requests: write$/m);
assert.doesNotMatch(syncJob, /uses: actions\/checkout/);
assert.match(syncJob, /ref: \$\{\{ github\.sha \}\}/);
assert.match(syncJob, /persist-credentials: false/);
assert.doesNotMatch(syncJob, /pull_request\.head/);
});
test('template opts in and checkbox edits reconcile only the nightly label', async () => {
assert.ok(readFileSync(resolve(__dirname, '../../pull_request_template.md'), 'utf8').includes(checked));
assert.deepEqual(await run({ sync: true, labels: ['bug'] }), [['add', ['merge nightly']]]);
test('removing the skip label reconciles the current checkbox on main', async () => {
const trigger = workflow.split(' pull_request_target:\n')[1].split(' schedule:\n')[0];
assert.match(trigger, /branches: \[main\]/);
assert.match(trigger, /types: \[[^\]\n]*\bunlabeled\b/);
const guard = workflow.split(' sync-label:\n')[1].match(/ if: >-\n((?: .*\n)+)/)[1];
const enabled = new Function('github', `return (${guard});`);
const payload = { action: 'unlabeled', label: { name: label } };
const admits = event => enabled({ repository: 'GreptimeTeam/greptimedb', event_name: 'pull_request_target', event });
assert.equal(admits(payload), true);
assert.equal(admits({ ...payload, label: { name: 'docs-required' } }), false);
assert.equal(admits({ action: 'edited' }), true);
const opts = { sync: true, payload };
assert.deepEqual(await run({ ...opts, body: checked }), [['add', [label]]]);
for (const body of [unchecked, null]) assert.deepEqual(await run({ ...opts, body }), []);
assert.deepEqual(await run({ ...opts, body: checked, current: { base: { ref: 'release/v1.3' } } }), []);
});
test('enqueueing requires rollout activation and dry runs work while paused', () => {
const guard = workflow.split(' enqueue:\n')[1].match(/ if: >-\n((?: .*\n)+)/)[1];
const enabled = new Function('github', 'vars', 'inputs', `return (${guard});`);
const repo = { repository: 'GreptimeTeam/greptimedb' };
for (const flag of ['', 'false', 'true']) {
const vars = { NIGHTLY_MERGE_ENABLED: flag };
const scheduled = { ...repo, event_name: 'schedule' };
const manual = { ...repo, event_name: 'workflow_dispatch' };
assert.equal(enabled(scheduled, vars, {}), flag === 'true');
assert.equal(enabled(manual, vars, { dry_run: false }), flag === 'true');
assert.equal(enabled(manual, vars, { dry_run: true }), true);
assert.equal(enabled({ ...repo, event_name: 'pull_request_target' }, vars, {}), false);
}
});
test('default template needs no label and a checked opt-out is effective before sync', async () => {
assert.ok(template.includes(unchecked));
assert.deepEqual(await run({ sync: true, body: template }), []);
for (const body of [checked, checked.replace('[x]', '[X]') + ' — wait for backport',
checked + ' <!-- note --> more details', unchecked + '\r\n' + checked]) {
assert.deepEqual(await run({ sync: true, body, labels: ['bug'] }), [['add', [label]]]);
assert.equal((await run({ body })).some(c => c[0] === 'enqueue'), false);
}
assert.deepEqual(await run({ sync: true }), []);
for (const body of [checked.replace('[x]', '[ ]')]) {
assert.deepEqual(await run({ sync: true, body }), [['remove', 'merge nightly']]);
assert.deepEqual(await run({ sync: true, body: checked, labels: [label] }), []);
});
test('a coalesced uncheck releases a bot hold; delayed edits and reopens preserve a newer manual hold', async () => {
const bot = { id: 1, created_at: '2026-01-01T00:00:00Z', event: 'labeled', label: { name: label },
actor: { login: 'github-actions[bot]' } };
const removed = { ...bot, id: 2, event: 'unlabeled' };
const manual = { ...bot, id: 3, actor: { login: 'maintainer' } };
for (const payload of [{ action: 'edited', changes: { title: { from: 'before' } } },
{ action: 'edited', changes: { body: { from: checked } } }, { action: 'reopened' }]) {
const opts = { sync: true, labels: [label], payload };
assert.deepEqual(await run({ ...opts, events: [bot] }), [['remove', label]]);
assert.deepEqual(await run({ ...opts, events: [manual, bot, removed] }), []);
assert.deepEqual(await run({ ...opts, events: [] }), []);
}
assert.deepEqual(await run({ sync: true, body: checked.replace('[x]', '[X]'), labels: [] }), [['add', ['merge nightly']]]);
});
test('eligible PR is enqueued with its checked head; dry run performs no mutation', async () => {
@@ -89,7 +161,8 @@ test('eligible PR is enqueued with its checked head; dry run performs no mutatio
test('each eligibility gate independently prevents enqueueing', async () => {
for (const options of [
{ labels: [] },
{ labels: [label] }, { listed: { draft: true } }, { current: { labels: [{ name: label }] } },
{ current: { body: checked } },
{ current: { draft: true } }, { current: { state: 'closed' } }, { current: { base: { ref: 'release/v1.3' } } },
{ detail: { reviewDecision: 'REVIEW_REQUIRED' } }, { detail: { reviewDecision: 'CHANGES_REQUESTED' } },
{ detail: { mergeStateStatus: 'BLOCKED' } }, { detail: { mergeStateStatus: 'UNKNOWN' } },
@@ -103,6 +176,7 @@ test('each eligibility gate independently prevents enqueueing', async () => {
test('all thread pages are checked before enqueueing', async () => {
const calls = await run({ threads: [[true], [true]] });
assert.deepEqual(calls.filter(c => c[0] === 'threads'), [['threads', null], ['threads', 'page-0']]);
assert.ok(calls.findIndex(c => c[0] === 'get') > calls.findLastIndex(c => c[0] === 'threads'));
assert.equal(calls.filter(c => c[0] === 'enqueue').length, 1);
});
@@ -113,15 +187,110 @@ test('per-run cap and individual failures do not prevent later candidates', asyn
assert.equal(calls.filter(c => c[0] === 'failed').length, 1);
});
test('label-only opt-in survives PRs without a template and does not require a checkbox', async () => {
for (const body of ['', null, 'Existing PR description', `> ${checked}`]) {
test('checkbox-free PRs enter by default and manual holds work on any description', async () => {
for (const body of ['', null, 'Automated PR', `> ${checked}`, `\`\`\`md\n${checked}\n\`\`\``,
`<!--\n${checked}\n-->`, legacy, legacy.replace('[x]', '[ ]')]) {
assert.deepEqual(await run({ sync: true, body }), []);
assert.deepEqual(await run({ sync: true, body, labels: [] }), []);
assert.equal((await run({ body })).filter(call => call[0] === 'enqueue').length, 1);
assert.equal((await run({ body, labels: [] })).some(call => call[0] === 'enqueue'), false);
assert.equal((await run({ body, labels: [label] })).some(call => call[0] === 'enqueue'), false);
}
// The label is authoritative for admission, even before checkbox synchronization.
assert.equal((await run({ body: checked.replace('[x]', '[ ]') })).some(call => call[0] === 'enqueue'), true);
});
test('list fences hide example checkboxes and leave the following merge checklist effective', async () => {
for (const [opening, indent, closing] of [
['1. ```sql', ' ', ' ```'],
['10) ~~~md', ' ', ' ~~~~'],
['- ```md', ' ', ''],
['1.\t```md', ' ', '\t```'],
['1. Reproduction\n ```md', ' ', '']
]) {
const description = (sample, box) =>
[opening, indent + 'SELECT 1;', '', indent + sample, closing, '', '## Merge timing', '', box].join('\n');
for (const [sample, box] of [[unchecked, checked], [checked, unchecked]]) {
const body = description(sample, box);
assert.deepEqual(await run({ sync: true, body }), box === checked ? [['add', [label]]] : [], body);
assert.equal((await run({ body })).some(call => call[0] === 'enqueue'), box === unchecked, body);
}
assert.equal(migrateMainPr(false, { body: description(legacy, legacy), labels: [] }).body,
description(legacy, checked));
}
});
test('migration follows the snapshotted label, edits only visible legacy items and preserves docs overrides', () => {
for (const optedIn of [false, true]) {
const old = '- [ ] Merge during the nightly window';
const before = ['Author notes', `> ${old}`, '```md', old, '```', '<!--', old, '-->', ''];
const pr = { body: [...before, old + ' — note', legacy + ' (later)'].join('\r\n'),
labels: ['docs-required', 'bug', 'docs-not-required', ...(optedIn ? ['merge nightly'] : [])].map(name => ({ name })) };
const result = migrateMainPr(optedIn, pr);
const replacement = optedIn ? unchecked : checked;
assert.equal(result.body, [...before, replacement + ' — note', replacement + ' (later)'].join('\r\n'));
assert.deepEqual(result.remove, optedIn ? ['merge nightly', 'docs-not-required'] : ['docs-not-required']);
assert.equal(result.addHold, false);
assert.equal(result.waitingForSync, !optedIn);
const migrated = { body: result.body, labels: optedIn ? [] : [{ name: label }] };
assert.deepEqual(migrateMainPr(optedIn, migrated), { body: migrated.body, addHold: false, remove: [],
waitingForSync: false, extraHold: false, needsChoice: false });
}
});
test('retrying migration honors a cleared nightly opt-out checkbox', () => {
const retry = migrateMainPr(false, { body: unchecked, labels: [] });
assert.deepEqual(retry, { body: unchecked, addHold: false, remove: [],
waitingForSync: false, extraHold: false, needsChoice: false });
});
test('migration only cleans the old docs label on release PRs, including PRs retargeted from main', () => {
const release = 'release/v1.3';
for (const [base, optedIn] of [[release, true], ['main', false]]) {
const names = ['docs-required', 'docs-not-required', ...(optedIn ? ['merge nightly'] : [])];
for (const body of [legacy, null, checked]) {
const pr = { base: { ref: release }, body, labels: names.map(name => ({ name })) };
assert.deepEqual(changesFor({ base, optedIn }, pr), { body, addHold: false, remove: ['docs-not-required'],
waitingForSync: false, extraHold: false, needsChoice: false });
}
}
});
test('a PR retargeted into main needs a current checkbox or manual hold', () => {
const entry = { base: 'release/v1.3', optedIn: true };
for (const [body, names, needsChoice, waitingForSync] of [
[legacy, ['merge nightly'], true, false], [null, [], true, false],
['> ' + unchecked, [], true, false], [unchecked, [], false, false],
[checked, [], false, true], [null, [label], false, false]
]) {
const pr = { base: { ref: 'main' }, body, labels: names.map(name => ({ name })) };
assert.deepEqual(changesFor(entry, pr), { body, addHold: false, remove: [],
waitingForSync, extraHold: false, needsChoice });
}
});
test('migration updates the stock help only in the comment following a converted checkbox', () => {
const oldHelp = 'Uncheck to opt out and remove the `merge nightly` label; this does not enable immediate merging.';
const newHelp = 'Check to opt out. To resume, uncheck the box and remove any manually applied `skip nightly merge` label.';
const migrate = (body, optedIn) => migrateMainPr(optedIn, { body, labels: [] }).body;
assert.ok(template.includes(newHelp));
assert.equal(migrate(template.replace(unchecked, legacy).replace(newHelp, oldHelp), true), template);
const description = (box, help) => [
oldHelp, '', '```md', legacy, '<!--', oldHelp, '-->', '```', '',
box + ' — waiting for a backport', '', '<!--', 'Author note', help, '-->', '',
'<!--', oldHelp, '-->'
].join('\r\n');
assert.equal(migrate(description(legacy, oldHelp), false), description(checked, newHelp));
assert.equal(migrate(description(legacy, oldHelp + ' Custom note.'), false),
description(checked, oldHelp + ' Custom note.'));
assert.equal(migrate(description(checked, oldHelp), false), description(checked, oldHelp));
});
test('migration holds checkbox-free PRs across retries and flags a later manual opt-out for review', () => {
const pr = { body: null, labels: [] };
assert.equal(migrateMainPr(false, pr).addHold, true);
assert.equal(migrateMainPr(true, pr).addHold, false);
pr.labels.push({ name: label });
assert.equal(migrateMainPr(false, pr).addHold, false);
assert.equal(migrateMainPr(true, pr).extraHold, true);
assert.equal(migrateMainPr(false, pr).body, null);
});
const stackMessage = 'This pull request is part of a stack and must be enqueued using the asynchronous merge REST API. For more information, see https://docs.github.com/rest/pulls/pulls#merge-a-pull-request-asynchronously';
+9 -4
View File
@@ -3,12 +3,17 @@ on:
pull_request_target:
types: [opened, edited, closed]
concurrency:
group: ${{ github.workflow }}-${{ github.event.action }}-${{ github.head_ref || github.run_id }}
cancel-in-progress: true
jobs:
docbot:
# An unrelated edit must not displace a pending docs checkbox change.
if: >-
github.event.action != 'edited' ||
(github.event.changes.body &&
contains(github.event.changes.body.from, '[x] This PR requires documentation updates.') !=
contains(github.event.pull_request.body, '[x] This PR requires documentation updates.'))
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number }}-${{ github.event.action == 'closed' && 'close' || 'labels' }}
cancel-in-progress: false
runs-on: ubuntu-latest
permissions:
pull-requests: write
+51 -25
View File
@@ -3,7 +3,8 @@ name: Nightly Merge
on:
pull_request_target:
types: [opened, edited, reopened]
branches: [main]
types: [opened, edited, reopened, unlabeled]
schedule:
# Hourly from 02:10 through 08:10 Asia/Shanghai (UTC+8), inclusive.
# GitHub may delay scheduled runs.
@@ -19,44 +20,68 @@ permissions: {}
jobs:
sync-label:
if: github.repository == 'GreptimeTeam/greptimedb' && github.event_name == 'pull_request_target'
if: >-
github.repository == 'GreptimeTeam/greptimedb' && github.event_name == 'pull_request_target' &&
(github.event.action != 'unlabeled' || github.event.label.name == 'skip nightly merge')
runs-on: ubuntu-latest
timeout-minutes: 5
permissions:
# PR label mutations require pull-request write permission.
contents: read
pull-requests: write
issues: write
concurrency:
group: nightly-merge-label-${{ github.event.pull_request.number }}
cancel-in-progress: false
steps:
# No checkout: PR contents are untrusted data, never executable code.
# On pull_request_target github.sha identifies trusted base-repository code.
- uses: actions/checkout@v4
with:
ref: ${{ github.sha }}
sparse-checkout: .github/scripts/nightly-merge.cjs
sparse-checkout-cone-mode: false
persist-credentials: false
- uses: actions/github-script@v7
with:
script: |
const { skipChecked, skipLabel } = require('./.github/scripts/nightly-merge.cjs');
const { owner, repo } = context.repo;
const issue_number = context.payload.pull_request.number;
const { data: pr } = await github.rest.pulls.get({ owner, repo, pull_number: issue_number });
const checkbox = /^- \[([ xX])\] Merge during the nightly window <!-- nightly-merge -->\s*$/m.exec(pr.body || '');
// PRs without the template manage their opt-in through the label.
if (!checkbox) return;
const selected = checkbox[1].toLowerCase() === 'x';
const label = 'merge nightly';
const labeled = pr.labels.some(item => item.name === label);
if (selected && !labeled) {
await github.rest.issues.addLabels({ owner, repo, issue_number, labels: [label] });
} else if (!selected && labeled) {
await github.rest.issues.removeLabel({ owner, repo, issue_number, name: label });
if (pr.state !== 'open' || pr.base.ref !== 'main') return;
const selected = skipChecked(pr.body);
const labeled = pr.labels.some(item => item.name === skipLabel);
if (selected === labeled) return;
if (selected) {
await github.rest.issues.addLabels({ owner, repo, issue_number, labels: [skipLabel] });
} else {
// Only undo the bot's own label. A maintainer may have applied a hold since the edit.
const events = await github.paginate(github.rest.issues.listEvents, { owner, repo, issue_number, per_page: 100 });
const [last] = events.filter(event => event.label?.name === skipLabel &&
(event.event === 'labeled' || event.event === 'unlabeled'))
.sort((a, b) => b.created_at.localeCompare(a.created_at) || b.id - a.id);
if (last?.event === 'labeled' && last.actor?.login === 'github-actions[bot]') {
await github.rest.issues.removeLabel({ owner, repo, issue_number, name: skipLabel });
}
}
enqueue:
if: github.repository == 'GreptimeTeam/greptimedb' && github.event_name != 'pull_request_target'
if: >-
github.repository == 'GreptimeTeam/greptimedb' && github.event_name != 'pull_request_target' &&
(vars.NIGHTLY_MERGE_ENABLED == 'true' || (github.event_name == 'workflow_dispatch' && inputs.dry_run))
runs-on: ubuntu-latest
timeout-minutes: 10
permissions:
contents: read
concurrency:
group: nightly-merge-enqueue
cancel-in-progress: false
steps:
- uses: actions/checkout@v4
with:
ref: ${{ github.sha }}
sparse-checkout: .github/scripts/nightly-merge.cjs
sparse-checkout-cone-mode: false
persist-credentials: false
# Reuses the automation credential used by backport and compat updates.
# A PAT (or App token) lets subsequent merge_group workflows run.
- uses: actions/github-script@v7
@@ -65,25 +90,20 @@ jobs:
with:
github-token: ${{ secrets.GH_PERSONAL_ACCESS_TOKEN }}
script: |
const { eligibleForNightly } = require('./.github/scripts/nightly-merge.cjs');
const { owner, repo } = context.repo;
const dryRun = process.env.DRY_RUN === 'true';
const candidates = await github.paginate(github.rest.issues.listForRepo, {
owner, repo, state: 'open', labels: 'merge nightly',
const candidates = await github.paginate(github.rest.pulls.list, {
owner, repo, state: 'open', base: 'main',
sort: 'created', direction: 'asc', per_page: 100
});
const rows = [];
let enqueued = 0;
for (const candidate of candidates) {
if (!candidate.pull_request || enqueued >= 5) continue;
if (enqueued >= 5) break;
if (!eligibleForNightly(candidate)) continue;
const number = candidate.number;
try {
// Fetch current labels and PR state, not the earlier list snapshot.
const { data: current } = await github.rest.pulls.get({ owner, repo, pull_number: number });
if (current.state !== 'open' || current.draft || current.base.ref !== 'main' ||
!current.labels.some(label => label.name === 'merge nightly')) {
rows.push([String(number), 'Skipped: not opted in, draft, closed, or not targeting main']);
continue;
}
const { repository: { pullRequest: pr } } = await github.graphql(`
query($owner: String!, $repo: String!, $number: Int!) {
repository(owner: $owner, name: $repo) {
@@ -120,6 +140,12 @@ jobs:
rows.push([String(number), 'Skipped: unresolved review threads']);
continue;
}
// An opt-out may have arrived while checking reviews and threads.
const { data: current } = await github.rest.pulls.get({ owner, repo, pull_number: number });
if (!eligibleForNightly(current)) {
rows.push([String(number), 'Skipped: opted out, draft, closed, or not targeting main']);
continue;
}
if (!dryRun) {
// GitHub enforces branch rules; never bypass or enable auto-merge.
try {