Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
160 changes: 160 additions & 0 deletions scripts/pm/bounce-reading.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

/**
* bounce-reading — the ONE reading of "was this pull sent back for changes, and has a re-review on its current head
* cleared that since?" (`landing-operations.md`: a 退回 takes `pm:awaiting-merge` off in the same stroke, and
* 「复审过再挂、入队,其间不补四件」).
*
* ## Why it is its own file
*
* Two readers prescribe the hand-off's pieces: H48 in `check-half-states.mjs` (`h48GovernedVerdictWithoutBrief`,
* whose remedy is「add `pm:awaiting-merge`」) and `label-write.mjs --handoff` (whose `--dry-run` answers exit 7, a
* piece owed, and whose real stroke adds the label). On a bounced pull whose ACCEPT and same-head PASS are still on
* the thread both used to prescribe the label back. They read the bounce HERE, through one wrapper
* (`h48BounceReading` in `check-half-states.mjs`, which hands this file the contract-review readers), so the patrol
* row and the hand-off door cannot disagree. ⛔ Never re-spell a trigger in either reader.
*
* ⛔ No imports, no network, no I/O: rows in, a reading out. The contract-review readers are HANDED in (`readers`),
* because they live in `check-half-states.mjs` and a static import back would close a module cycle with that file's
* top-level await (its H62 banner measures both import directions for a sibling that does this). A sibling of its readers, ⛔ not under a `lib/`
* subdirectory (`seat-record.mjs` says why).
*
* ## The three triggers (card #39516), each with the moment it happened
*
* queue-red a red merge-queue build of this pull: the merge-queue-triage workflow's comment on the pull
* thread (`MERGE_QUEUE_TRIAGE_MARKER`, author `MERGE_QUEUE_TRIAGE_AUTHOR`). That workflow runs on
* every merge_group CI run that concluded failure, and the failure is what ejects the entry.
* ⚠️ Source measured on #39400 (2026-12-04): the REST timeline's `removed_from_merge_queue` event
* carries no head sha, no reason and no run (`commit_id` null; GraphQL is not reachable from a
* session), and also fires when the pull merges or a person dequeues it; the queue's check-runs
* sit on the merge-group commit, never on the pull's head. The triage comment names the red run
* and is on the thread both readers already hold. A comment carrying the triage workflow's
* `infra:no-runner` marker is NOT a bounce: the red was runners nobody got, the flake class the
* ruling keeps the label through (「flake/缺批准被踢不摘」).
* review-record the NEWEST `## Contract review` record on the thread (trusted author, names a head) reads FAIL,
* or carries an open must-fix or should-fix.
* changes-requested a trusted reviewer's newest deciding review is CHANGES_REQUESTED — trusted by the same
* record-author binding the records are read through (the relay identity and
* `GOVERNED_APPROVERS`: the maintainer asking for changes, 「维护者要改」), never a second login
* list. ⚠️ Not `author_association`: measured on #39400, the maintainer's own review there reads
* `CONTRIBUTOR`. A later APPROVED or a dismissal by the same reviewer supersedes it, and a
* COMMENTED review decides nothing (GitHub's own review-decision rule).
*
* ## Since when, and the one exit
*
* The bounce dates from the NEWEST trigger. It clears only on a trusted `## Contract review` record that names the
* pull's CURRENT head, reads one PASS line with no FAIL spelling and no open or unreadable grade (the queue guard's
* standard), and is NEWER than that trigger. An undated trigger can never be cleared (fail closed).
*
* ⚠️ The queue-red trigger is not narrowed to the current head. A fix pushed after the red moves the head and leaves
* no PASS on it, so the pull stays bounced until its re-review — the ruling's 「复审过再挂」. Narrowing it to the same
* head would read the pull as clear between the fix push and the re-review, and H48 would ask for the label back.
*
* ## Three input states, never two (#4690)
*
* A thread or a review page that was not read (`undefined`) or could not be read (`null`), or a record-author
* binding that did not load, is `unread`: no trigger can be ruled out and no PASS trusted.
*/

/** The trigger names, in the order the header gives them. */
export const BOUNCE_TRIGGERS = Object.freeze(['queue-red', 'review-record', 'changes-requested']);

/** The identity the merge-queue-triage workflow comments as (`github.rest.issues.createComment` under GITHUB_TOKEN). */
export const MERGE_QUEUE_TRIAGE_AUTHOR = 'github-actions[bot]';

/** The workflow's per-run marker line, `merge-queue-triage:RUN` inside an HTML comment, on a line of its own. */
export const MERGE_QUEUE_TRIAGE_MARKER = /^<!-- merge-queue-triage:(\d+) -->$/m;

/** The workflow's `infra:no-runner` marker: every red job was a runner nobody got — the flake class, no bounce. */
export const MERGE_QUEUE_NO_RUNNER_MARKER = /^<!-- merge-queue-infra:no-runner\|pr=\d+\|head=[0-9a-f]{40}\|run=\d+ -->$/m;

/** The review states that decide a reviewer's standing; COMMENTED and PENDING decide nothing. */
const DECIDING_REVIEW_STATES = Object.freeze(['APPROVED', 'CHANGES_REQUESTED', 'DISMISSED']);

const stampOf = (iso) => {
const parsed = Date.parse(iso ?? '');
return Number.isFinite(parsed) ? parsed : null;
};

/** An undated moment sorts after every dated one, so it can never be cleared (fail closed). */
const laterOrEqual = (a, b) => (a.stamp === null ? true : b.stamp === null ? false : a.stamp >= b.stamp);

/**
* Every red merge-queue build the triage workflow recorded on this thread, oldest first in thread order:
* `{ id, at, stamp, run }`. A comment by any other author, or one carrying the no-runner marker, is not one. Pure.
*/
export function queueRedRemovals(rows) {
return (Array.isArray(rows) ? rows : [])
.filter((row) => String(row?.user?.login ?? '') === MERGE_QUEUE_TRIAGE_AUTHOR)
.map((row) => ({ row, triage: MERGE_QUEUE_TRIAGE_MARKER.exec(String(row?.body ?? '')) }))
.filter(({ row, triage }) => triage !== null && !MERGE_QUEUE_NO_RUNNER_MARKER.test(String(row?.body ?? '')))
.map(({ row, triage }) => ({ id: row?.id ?? null, at: row?.created_at ?? null, stamp: stampOf(row?.created_at), run: triage[1] }));
}

/**
* The CHANGES_REQUESTED reviews still standing: per reviewer `admits` trusts (the record-author binding), the NEWEST
* deciding review, kept when it is CHANGES_REQUESTED. `{ id, login, at, stamp }`. Pure.
*/
export function changesRequestedReviews(reviews, admits = () => false) {
const newest = new Map();
(Array.isArray(reviews) ? reviews : []).forEach((review, index) => {
const login = String(review?.user?.login ?? '');
if (!login || !DECIDING_REVIEW_STATES.includes(String(review?.state ?? ''))) return;
if (!admits(review)) return;
const candidate = { review, index, stamp: stampOf(review?.submitted_at) };
const best = newest.get(login);
const newer = best === undefined || (candidate.stamp === null || best.stamp === null ? index > best.index : candidate.stamp >= best.stamp);
if (newer) newest.set(login, candidate);
});
return [...newest.entries()]
.filter(([, { review }]) => review?.state === 'CHANGES_REQUESTED')
.map(([login, { review, stamp }]) => ({ id: review?.id ?? null, login, at: review?.submitted_at ?? null, stamp }));
}

/**
* The reading. `rows` is the pull's issue-comment thread, `reviews` its submitted-review page, `headSha` its CURRENT
* head, `authors` the queue guard's record-author binding (`{ available, admits(row) }`). `readers` carries the
* contract-review readers: `recordOf(body, headSha)` → `null` (no record that names a head) or
* `{ fails, open, pass, onHead }`, and `newestOf(rows)` → the newest record row's `{ index, createdAt, stamp }`.
*
* @returns {{ state: 'unread', reason: string }
* | { state: 'clear', since: null, clearedBy: null }
* | { state: 'clear', since: object, clearedBy: { id: number|null, at: string|null } }
* | { state: 'bounced', since: { trigger: string, id: number|null, at: string|null, stamp: number|null, ref: string } }}
*/
export function bouncedSince({ rows, reviews, headSha, authors } = {}, readers = {}) {
if (rows === undefined || rows === null) return { state: 'unread', reason: 'the pull thread was not read' };
if (reviews === undefined || reviews === null) return { state: 'unread', reason: 'the submitted-review page was not read' };
if (authors?.available !== true) return { state: 'unread', reason: `the record-author binding did not load (${authors?.reason ?? 'no reason given'})` };
if (typeof readers.recordOf !== 'function' || typeof readers.newestOf !== 'function') {
return { state: 'unread', reason: 'no contract-review reader was handed in' };
}
const thread = Array.isArray(rows) ? rows : [];
const records = thread
.filter((row) => authors.admits(row))
.map((row) => ({ row, standing: readers.recordOf(row?.body, headSha) }))
.filter(({ standing }) => standing !== null);

const triggers = [];
for (const red of queueRedRemovals(thread)) {
triggers.push({ trigger: 'queue-red', id: red.id, at: red.at, stamp: red.stamp, ref: `merge-queue-triage comment ${red.id ?? '(no id)'} on queue run ${red.run}` });
}
const newest = readers.newestOf(records.map(({ row }) => row));
const newestRecord = newest === null ? null : records[newest.index];
if (newestRecord && (newestRecord.standing.fails || newestRecord.standing.open)) {
const why = newestRecord.standing.fails ? 'reads FAIL' : 'carries an open must-fix or should-fix';
triggers.push({ trigger: 'review-record', id: newestRecord.row?.id ?? null, at: newestRecord.row?.created_at ?? null, stamp: stampOf(newestRecord.row?.created_at), ref: `the newest \`## Contract review\` (comment ${newestRecord.row?.id ?? '(no id)'}) ${why}` });
}
for (const cr of changesRequestedReviews(reviews, (review) => authors.admits(review))) {
triggers.push({ trigger: 'changes-requested', id: cr.id, at: cr.at, stamp: cr.stamp, ref: `review ${cr.id ?? '(no id)'} by \`${cr.login}\` requests changes` });
}
if (triggers.length === 0) return { state: 'clear', since: null, clearedBy: null };
const since = triggers.reduce((best, t) => (laterOrEqual(t, best) ? t : best));

const clearing = since.stamp === null
? []
: records.filter(({ row, standing }) => standing.onHead && standing.pass && (stampOf(row?.created_at) ?? -Infinity) > since.stamp);
if (clearing.length === 0) return { state: 'bounced', since };
const by = clearing[clearing.length - 1].row;
return { state: 'clear', since, clearedBy: { id: by?.id ?? null, at: by?.created_at ?? null } };
}
Loading
Loading