From 7c1acad4f9fbb8793c9bdbac9b07b8800925a70b Mon Sep 17 00:00:00 2001 From: WIZARDspace Date: Sun, 6 Sep 2026 08:20:34 +0100 Subject: [PATCH 1/6] feat(queue-guard): say when a fork PR's CI has not run (#693) A fork PR from an author with no merged PR here has its CI run created as action_required and never executed. Nothing on the PR says so: protected-files reports success and overlap reports skipped, so the checks list looks populated, and the only hint is mergeable_state: blocked, which does not say why. A third job in queue-guard comments once when that is the case, upserted and deleted by marker like the overlap comment, so it disappears when the run is released. It does not change the gate. Approving a run stays a maintainer action; this only makes the wait legible, so an approval is not read as "the repo's gate passed". Matched on the workflow path rather than the CI display name, and it polls briefly because pull_request and pull_request_target dispatch from the same push -- a false "CI never ran" on a healthy PR is worse than a late comment. No run at all stays silent, since that is ambiguous. pull_request_target runs the workflow from the base branch, so this job cannot run on its own pull request; it takes effect only once merged. --- .github/workflows/queue-guard.yml | 72 +++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) diff --git a/.github/workflows/queue-guard.yml b/.github/workflows/queue-guard.yml index 7431f9e07..505d0f038 100644 --- a/.github/workflows/queue-guard.yml +++ b/.github/workflows/queue-guard.yml @@ -89,3 +89,75 @@ jobs: { ...context.repo, comment_id: mine.id, body }); else await github.rest.issues.createComment( { ...context.repo, issue_number: pr.number, body }); + + ci-not-run: + # #693: a fork PR from an author with no merged PR here has its CI run created as + # `action_required` and never executed. Nothing on the PR says so — `protected-files` + # reports success and `overlap` reports skipped, so the checks list looks populated, + # and the only hint is `mergeable_state: blocked`, which does not say why. This says + # why, once, in the thread where people are already looking. + # + # It does not change the gate. Approving the run stays a maintainer action; this only + # makes the wait legible so an approval is not read as "the repo's gate passed". + if: >- + github.event.action == 'opened' || github.event.action == 'reopened' + || github.event.action == 'synchronize' + runs-on: ubuntu-latest + permissions: + # Narrower than the workflow default: this job reads run state and writes one + # comment, so it needs `actions: read` on top of the comment scope, and nothing else. + pull-requests: write + actions: read + steps: + - uses: actions/github-script@v9 + with: + script: | + // Same fork test as protected-files: a head branch in this repository cannot + // be a fork, and only forks are gated. author_association is not consulted -- + // it reports MEMBER for authors who still need approval (see #567). + const pr = context.payload.pull_request; + if (pr.head.repo && pr.head.repo.full_name === pr.base.repo.full_name) return; + const marker = ''; + // `pull_request` and `pull_request_target` dispatch from the same push, so the + // CI run may not be listed yet when this job reaches the API. Poll briefly + // rather than reporting "never ran" against a run that is seconds from + // existing -- a false positive here is worse than a late comment, because it + // says the opposite of the truth on a PR that is fine. + const CI = '.github/workflows/ci.yml'; + let run = null; + for (let i = 0; i < 6 && !run; i++) { + if (i) await new Promise(r => setTimeout(r, 10000)); + const res = await github.rest.actions.listWorkflowRunsForRepo({ + ...context.repo, head_sha: pr.head.sha, per_page: 100, + }); + // Matched on path, not display name: the name is prose and can be edited + // without anyone thinking of this file. + run = res.data.workflow_runs.find(r => r.path === CI) || null; + } + // Only `action_required` is reported. A queued or running CI is not a problem, + // and no run at all after the poll is ambiguous -- it can mean the event was + // filtered -- so it stays silent rather than guessing. + const blocked = run !== null && run.conclusion === 'action_required'; + const comments = await github.paginate(github.rest.issues.listComments, { + ...context.repo, issue_number: pr.number, per_page: 100, + }); + const mine = comments.find(c => c.body && c.body.includes(marker)); + if (!blocked) { + // Upserted and removed by marker, like the overlap comment: once the run is + // approved the notice is wrong, and a stale warning is its own bug. + if (mine) await github.rest.issues.deleteComment( + { ...context.repo, comment_id: mine.id }); + return; + } + const body = marker + '\nCI has not run on this head: the workflow run was ' + + 'created as `action_required` and is waiting for a maintainer to approve ' + + 'it. Until then the checks above do not mean the repo\'s gate passed — ' + + '`lint + tests + image` has not executed at all.\n\nThis is the default ' + + '"require approval for first-time contributors" setting, not anything ' + + 'wrong with this pull request, and it clears once a maintainer releases ' + + 'the run (#693).'; + if (mine && mine.body === body) return; + if (mine) await github.rest.issues.updateComment( + { ...context.repo, comment_id: mine.id, body }); + else await github.rest.issues.createComment( + { ...context.repo, issue_number: pr.number, body }); From 4a1aad6f82b54431ac6069f83164e4d49b8ba2d9 Mon Sep 17 00:00:00 2001 From: WIZARDspace Date: Sun, 6 Sep 2026 08:49:19 +0100 Subject: [PATCH 2/6] fix(queue-guard): clear the CI-not-run notice when CI actually runs Approving a gated workflow run emits no pull_request_target event, so the notice added in the previous commit could not clear itself on the one transition it describes: it would sit on the PR saying CI has not run, immediately after CI ran. Raised by yukkie3276 on #735. Checked rather than assumed. The apparent counter-example is not one -- #156's queue-guard run at 2026-09-06T05:31:32Z looks like an approval firing pull_request_target, but its head b83fc306 is a merge commit authored four seconds earlier, so that was Update branch (a synchronize), not the approval. A second trigger, workflow_run on CI completing, is the transition pull_request_target cannot see. workflow_run.pull_requests is empty for a fork PR -- the same gap #693 had to work around -- so the head SHA is matched against open PRs instead, and a CI run from a push to main returns before that walk. protected-files gains an explicit event guard: it reads context.payload.pull_request, which a workflow_run event does not carry, and it was the only job without an `if` to keep it off the new trigger. --- .github/workflows/queue-guard.yml | 60 +++++++++++++++++++++++++++++-- 1 file changed, 58 insertions(+), 2 deletions(-) diff --git a/.github/workflows/queue-guard.yml b/.github/workflows/queue-guard.yml index 505d0f038..36e845148 100644 --- a/.github/workflows/queue-guard.yml +++ b/.github/workflows/queue-guard.yml @@ -1,17 +1,27 @@ # The automated half of CONTRIBUTING.md "Overlapping work": one comment naming open PRs # that cite the same issues, and a failure on PRs editing maintainer-regenerated files. -# Runs on pull_request_target and never checks out PR code — both jobs read only the API, -# so an untrusted branch gets no execution here. +# Never checks out PR code — every job reads only the API, so an untrusted branch gets no +# execution here. That is what makes the workflow_run trigger below safe as well: it runs in +# base-repo context, which is only dangerous to a workflow that runs the code it was told +# about, and none of these do. name: queue-guard on: pull_request_target: types: [opened, reopened, edited, synchronize] + # ci-not-run-clear only. Matched by workflow *name* because that is the only thing this + # filter accepts — the job body still matches on path, which is the stable identifier. + workflow_run: + workflows: [CI] + types: [completed] permissions: pull-requests: write jobs: protected-files: + # Every job here is pull_request_target's except ci-not-run-clear, and this one reads + # context.payload.pull_request, which a workflow_run event does not carry. + if: github.event_name == 'pull_request_target' runs-on: ubuntu-latest steps: - uses: actions/github-script@v9 @@ -161,3 +171,49 @@ jobs: { ...context.repo, comment_id: mine.id, body }); else await github.rest.issues.createComment( { ...context.repo, issue_number: pr.number, body }); + + ci-not-run-clear: + # The other half of ci-not-run, and the reason it needs one: approving a gated run emits + # no pull_request_target event at all, so the notice cannot clear itself from that + # trigger. It would sit there saying CI has not run, immediately after CI ran, which is + # the moment the message is most wrong. Raised by @yukkie3276 on #735. + # + # Checked rather than assumed, because the obvious counter-example is not one: #156's + # queue-guard run at 2026-09-06T05:31:32Z looks like an approval firing the trigger, but + # its head `b83fc306` is a merge commit authored four seconds earlier — that was Update + # branch, i.e. a synchronize, not the approval. + # + # A CI run reaching `completed` is the transition pull_request_target cannot see: it is + # what a released run does, and what an already-running one does anyway. + if: github.event_name == 'workflow_run' + runs-on: ubuntu-latest + permissions: + # No `actions: read` here: the run that fired this is in the event payload, and + # nothing else about it is read. + pull-requests: write + steps: + - uses: actions/github-script@v9 + with: + script: | + // `workflow_run.pull_requests` is empty for a fork PR — the same reason #693 + // had to resolve heads by hand — so the head SHA is matched against open PRs. + // No match is the normal case for a push to main, and does nothing. + // A CI run on a push to main has no PR to clear, and matching it would cost a + // walk of every open pull request (212 of them today) on every merge. + const run = context.payload.workflow_run; + if (run.event !== 'pull_request') return; + const sha = run.head_sha; + const marker = ''; + const prs = await github.paginate(github.rest.pulls.list, { + ...context.repo, state: 'open', per_page: 100, + }); + const pr = prs.find(p => p.head.sha === sha); + if (!pr) return; + const comments = await github.paginate(github.rest.issues.listComments, { + ...context.repo, issue_number: pr.number, per_page: 100, + }); + const mine = comments.find(c => c.body && c.body.includes(marker)); + // Deleted whatever the run concluded. A failed run is still a run: the notice + // says CI has not executed, and once it has, that is false regardless of result. + if (mine) await github.rest.issues.deleteComment( + { ...context.repo, comment_id: mine.id }); From 4b18ef8b9c8f7771a51bc460d38658184e0e0d23 Mon Sep 17 00:00:00 2001 From: WIZARDspace Date: Mon, 7 Sep 2026 22:31:41 +0100 Subject: [PATCH 3/6] ci: re-trigger checks after merging main The previous run failed on tests/unit/test_note_count.py::test_the_global_cap_ binds_exactly_under_concurrent_processes (63 of 64), a test this branch does not touch: src/store.py and the test file are byte-identical to main, and this branch's only diff is .github/workflows/queue-guard.yml. Fork PR runs cannot be re-run from the API, so this empty commit is the re-trigger. From 4709b93d08a31e0504ce138467e87ba2b9f6c1ff Mon Sep 17 00:00:00 2001 From: WIZARDspace Date: Tue, 8 Sep 2026 12:53:47 +0100 Subject: [PATCH 4/6] fix(queue-guard): only match the bot's own CI-not-run notice Two defects in the notice's lifecycle, both found re-verifying against current main. comments.find() matched any comment containing the marker, so a human quoting `` in the thread became `mine`. On this PR that is yukkie3276's comment (marker at offset 388): the !blocked branch and ci-not-run-clear would both delete it, and the blocked branch would overwrite it. Match on the bot's authorship and require the marker to start the body, where the job's own template puts it. A gated run is `status: completed, conclusion: action_required`, so it reaches the workflow_run trigger without having executed a job. ci-not-run-clear would then delete the notice ci-not-run posts for that same head, on the one transition the notice is about. Return early on that conclusion. overlap has the same find() pattern and no live exposure; left alone. --- .github/workflows/queue-guard.yml | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/.github/workflows/queue-guard.yml b/.github/workflows/queue-guard.yml index 36e845148..fd5b2f54b 100644 --- a/.github/workflows/queue-guard.yml +++ b/.github/workflows/queue-guard.yml @@ -151,7 +151,9 @@ jobs: const comments = await github.paginate(github.rest.issues.listComments, { ...context.repo, issue_number: pr.number, per_page: 100, }); - const mine = comments.find(c => c.body && c.body.includes(marker)); + const mine = comments.find( + c => c.user && c.user.type === 'Bot' + && c.body && c.body.startsWith(marker)); if (!blocked) { // Upserted and removed by marker, like the overlap comment: once the run is // approved the notice is wrong, and a stale warning is its own bug. @@ -202,6 +204,11 @@ jobs: // walk of every open pull request (212 of them today) on every merge. const run = context.payload.workflow_run; if (run.event !== 'pull_request') return; + // A gated run is `status: completed, conclusion: action_required`, so it + // reaches this trigger without having executed a single job. Clearing on + // it would delete the notice ci-not-run is posting for that same head, on + // the one transition the notice is about. It has not run; the notice stays. + if (run.conclusion === 'action_required') return; const sha = run.head_sha; const marker = ''; const prs = await github.paginate(github.rest.pulls.list, { @@ -212,8 +219,11 @@ jobs: const comments = await github.paginate(github.rest.issues.listComments, { ...context.repo, issue_number: pr.number, per_page: 100, }); - const mine = comments.find(c => c.body && c.body.includes(marker)); - // Deleted whatever the run concluded. A failed run is still a run: the notice - // says CI has not executed, and once it has, that is false regardless of result. + const mine = comments.find( + c => c.user && c.user.type === 'Bot' + && c.body && c.body.startsWith(marker)); + // Deleted whatever the run concluded, the gated case above excepted. A failed + // run is still a run: the notice says CI has not executed, and once it has, + // that is false regardless of result. if (mine) await github.rest.issues.deleteComment( { ...context.repo, comment_id: mine.id }); From c7745cd00acf42555c37b8a2000907a26b9d9487 Mon Sep 17 00:00:00 2001 From: WIZARDspace Date: Wed, 9 Sep 2026 13:35:49 +0100 Subject: [PATCH 5/6] fix(queue-guard): an unobserved CI run must not delete the notice `ci-not-run` folded three observations into a boolean. `blocked === false` meant both "a run was observed and is not gated" and "no run was observed at all", and both deleted the notice. A synchronize whose new head's run had not surfaced within the ~50s poll therefore removed the previous head's warning, and nothing put it back: this job fires only on opened/reopened/synchronize, and ci-not-run-clear returns early on `action_required` by design. The file's own comment already said the no-run case "stays silent rather than guessing" -- the code deleted instead. Reported by @yukkie3276. Every read here is also a snapshot, and approving a gated run emits no event this job can see, so a run can leave `action_required` between the read and the write. Re-reading before the write only narrows that window; it stays check-then-act. The reconcile now runs after the write, which is the point at which a stale notice exists to be removed. Reported by @Minh3132. tests/unit/test_queue_guard_ci_notice.py pins all three properties: the unobserved-run early return precedes every delete, the three observations stay named, and the post-write re-read reaches a delete. All three fail on 4709b93. Structural rather than behavioural, deliberately: no JavaScript executes in this suite, and an executable regression would need a Node runner and a github-script shim -- a larger change than the workflow it would test. --- .github/workflows/queue-guard.yml | 40 ++++++++-- tests/unit/test_queue_guard_ci_notice.py | 98 ++++++++++++++++++++++++ 2 files changed, 132 insertions(+), 6 deletions(-) create mode 100644 tests/unit/test_queue_guard_ci_notice.py diff --git a/.github/workflows/queue-guard.yml b/.github/workflows/queue-guard.yml index fd5b2f54b..607bc0d80 100644 --- a/.github/workflows/queue-guard.yml +++ b/.github/workflows/queue-guard.yml @@ -147,14 +147,25 @@ jobs: // Only `action_required` is reported. A queued or running CI is not a problem, // and no run at all after the poll is ambiguous -- it can mean the event was // filtered -- so it stays silent rather than guessing. - const blocked = run !== null && run.conclusion === 'action_required'; + // Three states, not two. `blocked === false` meant both "a run was observed + // and it is not gated" and "no run was observed at all", and both deleted. On a + // synchronize whose new run has not surfaced within the poll above, that deleted + // the previous head's notice and nothing re-posted it: this job fires only on + // opened/reopened/synchronize, and ci-not-run-clear ignores `action_required` by + // design. The comment above already calls the no-run case ambiguous; deleting on + // it was the code disagreeing with that. Raised by @yukkie3276. + const state = run === null ? 'unknown' + : run.conclusion === 'action_required' ? 'gated' : 'ran'; + // An unobserved run is not evidence that CI executed, so nothing is written and + // nothing is removed. Whatever is on the thread outlives this event. + if (state === 'unknown') return; const comments = await github.paginate(github.rest.issues.listComments, { ...context.repo, issue_number: pr.number, per_page: 100, }); const mine = comments.find( c => c.user && c.user.type === 'Bot' && c.body && c.body.startsWith(marker)); - if (!blocked) { + if (state === 'ran') { // Upserted and removed by marker, like the overlap comment: once the run is // approved the notice is wrong, and a stale warning is its own bug. if (mine) await github.rest.issues.deleteComment( @@ -168,11 +179,28 @@ jobs: '"require approval for first-time contributors" setting, not anything ' + 'wrong with this pull request, and it clears once a maintainer releases ' + 'the run (#693).'; - if (mine && mine.body === body) return; - if (mine) await github.rest.issues.updateComment( - { ...context.repo, comment_id: mine.id, body }); - else await github.rest.issues.createComment( + if (!mine) await github.rest.issues.createComment( { ...context.repo, issue_number: pr.number, body }); + else if (mine.body !== body) await github.rest.issues.updateComment( + { ...context.repo, comment_id: mine.id, body }); + // Compare-after-write. Every read above is a snapshot, and approving a gated run + // emits no event this job can see, so the state can move between the read and the + // write -- and the write is the thing that makes a stale notice observable, so + // the reconcile belongs after it rather than in front of it. Re-checking before + // the write would only narrow the window. Raised by @Minh3132. + const after = await github.rest.actions.listWorkflowRunsForRepo({ + ...context.repo, head_sha: pr.head.sha, per_page: 100, + }); + const now = after.data.workflow_runs.find(r => r.path === CI) || null; + if (now === null || now.conclusion === 'action_required') return; + const fresh = await github.paginate(github.rest.issues.listComments, { + ...context.repo, issue_number: pr.number, per_page: 100, + }); + const stale = fresh.find( + c => c.user && c.user.type === 'Bot' + && c.body && c.body.startsWith(marker)); + if (stale) await github.rest.issues.deleteComment( + { ...context.repo, comment_id: stale.id }); ci-not-run-clear: # The other half of ci-not-run, and the reason it needs one: approving a gated run emits diff --git a/tests/unit/test_queue_guard_ci_notice.py b/tests/unit/test_queue_guard_ci_notice.py new file mode 100644 index 000000000..04fa68380 --- /dev/null +++ b/tests/unit/test_queue_guard_ci_notice.py @@ -0,0 +1,98 @@ +"""`ci-not-run`'s lifecycle: which observations may remove the CI-has-not-run notice. + +The notice is a single upserted comment, so every bug in it is a bug about *when the +comment is deleted* rather than about what it says. Two of those were found on review, and +both fail silently -- the workflow goes green, and the only symptom is a thread that says +the wrong thing about whether CI ran. + +The first is a three-state problem written as a boolean. `ci-not-run` polls for the head's +CI run, and "no run visible yet" is not the same observation as "a run exists and is not +gated": the first is ignorance, the second is evidence. Collapsing them means a synchronize +whose new run has not surfaced within the poll deletes the *previous* head's notice, and +nothing puts it back -- this job fires only on opened/reopened/synchronize, and +`ci-not-run-clear` ignores `action_required` by design. + +The second is that every read here is a snapshot. Approving a gated run emits no event this +job can see, so the run can leave `action_required` between the read and the write, and the +job then posts a notice that is already false. Re-reading *before* the write only narrows +that window; the reconcile has to come after the write, because the write is what makes the +stale notice exist. + +Both are pinned structurally rather than behaviourally, and that limit is worth stating: no +JavaScript runs in this suite. `tests/package.json` is Playwright for the browser gate and +says so, and `tests/edge/test_edge_worker.py` -- the one other test whose subject is +JavaScript -- also asserts agreement by parsing rather than by executing. An executable +regression would mean a Node runner and a `github-script` shim, which is a larger change +than the workflow it would be testing. + +Parsed with a regex rather than a YAML library, for the reason +`tests/unit/test_browser_gate.py` gives: PyYAML is here only as somebody else's transitive +dependency, and these tests should not acquire one. + +Run: uv run --group dev python -m pytest tests/unit/test_queue_guard_ci_notice.py +""" + +from __future__ import annotations + +import re +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +WORKFLOW = ROOT / ".github" / "workflows" / "queue-guard.yml" + +# The `ci-not-run` job's inline script, up to the next job at the same indentation. +# `ci-not-run-clear` is a separate lifecycle with its own rules and must not be caught here. +_JOB = re.compile(r"^ ci-not-run:\n(.*?)(?=^ [a-z][a-z0-9-]*:\n)", re.M | re.S) +_SCRIPT = re.compile(r"^ *script: \|\n(.*)", re.M | re.S) + + +def _ci_not_run_script() -> str: + job = _JOB.search(WORKFLOW.read_text(encoding="utf-8")) + assert job, "the ci-not-run job is no longer findable in queue-guard.yml" + script = _SCRIPT.search(job.group(1)) + assert script, "the ci-not-run job no longer has an inline `script:` block" + return script.group(1) + + +def test_an_unobserved_run_is_not_evidence_and_never_deletes_the_notice(): + """The regression: `blocked === false` once meant both "observed, not gated" and "not + observed at all", and both deleted. A PR whose replacement head is still waiting for + approval then loses the warning at the moment it is most true, and stays silent until + some other PR action happens to re-run the job.""" + script = _ci_not_run_script() + assert "if (state === 'unknown') return;" in script, ( + "the unobserved case must return before anything is written or removed; " + "a boolean that folds it in with 'the run is fine' is the bug this pins" + ) + guard = script.index("if (state === 'unknown') return;") + first_delete = script.index("deleteComment") + assert guard < first_delete, ( + "an unobserved run reaches a deleteComment: the early return must precede " + "every delete path, or ignorance deletes on the strength of nothing" + ) + + +def test_the_three_observations_stay_distinct(): + """Naming them is the fix; a later edit that reduces them to two states brings the + bug back with the tests still passing, because every other assertion here is about + ordering rather than about how many cases exist.""" + script = _ci_not_run_script() + for state in ("'unknown'", "'gated'", "'ran'"): + assert state in script, f"the {state} observation is gone from ci-not-run" + + +def test_the_gated_path_rechecks_the_run_after_it_writes(): + """Approving a run emits no event this job sees, so the notice can be false the moment + it is posted. The re-read has to sit after the write: before it, this is still + check-then-act with a shorter gap, which is the same defect measured differently.""" + script = _ci_not_run_script() + write = max(script.rindex("createComment"), script.rindex("updateComment")) + recheck = script.rindex("listWorkflowRunsForRepo") + assert recheck > write, ( + "the run state is never re-read after the notice is written, so a run approved " + "during the job leaves a notice saying it was not" + ) + assert script.rindex("deleteComment") > recheck, ( + "the post-write re-read reaches no delete, so it observes the stale notice " + "and leaves it in place" + ) From f61c5b1b29e360b530f9561a2c47d77de97017ce Mon Sep 17 00:00:00 2001 From: WIZARDspace Date: Fri, 9 Oct 2026 11:26:19 +0100 Subject: [PATCH 6/6] fix(queue-guard): an older head's job cannot clear a newer head's ci-not-run notice The notice was one comment shared by every head of the PR, so an older head's job could delete the warning a newer, still-gated head had just written: head A's post-write cleanup after A's run left action_required, or ci-not-run-clear for A's completed run while its open-PR list still showed A. The notice now carries the head it is about. A job may remove its own head's notice, or another head's only while its head is still the PR's (re-read, not taken from the payload) -- the second half so that a notice an older head left, when the next head's run had not surfaced within the poll, is still cleared once the current head runs. The posting job is serialised per PR with a concurrency group, which closes the list-then-delete window the head check alone only narrows. tests/queue_guard_ci_notice.mjs runs both job scripts unchanged against an in-memory GitHub API and replays both interleavings and the stranded-notice case; it needs only node, and fails rather than skips under CI. Raised by @renhi and @luch91. --- .github/workflows/queue-guard.yml | 44 ++++-- tests/queue_guard_ci_notice.mjs | 170 +++++++++++++++++++++++ tests/unit/test_queue_guard_ci_notice.py | 80 ++++++++++- 3 files changed, 280 insertions(+), 14 deletions(-) create mode 100644 tests/queue_guard_ci_notice.mjs diff --git a/.github/workflows/queue-guard.yml b/.github/workflows/queue-guard.yml index 607bc0d80..86363a09f 100644 --- a/.github/workflows/queue-guard.yml +++ b/.github/workflows/queue-guard.yml @@ -112,6 +112,15 @@ jobs: if: >- github.event.action == 'opened' || github.event.action == 'reopened' || github.event.action == 'synchronize' + # One posting job per PR at a time. Two pushes in quick succession otherwise run two of + # these side by side, and the older head's post-write cleanup can land after the newer + # head's write -- deleting the notice for a head that is still gated. Not + # cancel-in-progress: the running job finishes its write-then-reconcile before the next + # head's starts, and a newer pending job already replaces an older pending one. Raised + # by @renhi and @luch91 on #735. + concurrency: + group: queue-guard-ci-not-run-${{ github.event.pull_request.number }} + cancel-in-progress: false runs-on: ubuntu-latest permissions: # Narrower than the workflow default: this job reads run state and writes one @@ -128,6 +137,18 @@ jobs: const pr = context.payload.pull_request; if (pr.head.repo && pr.head.repo.full_name === pr.base.repo.full_name) return; const marker = ''; + // The notice names the head it is about, and that decides who may remove it: this + // job may remove its own head's notice, and another head's only while this head is + // still the PR's head -- then the notice is about a commit the PR has left. So an + // older head's late observation (its run approved, superseded, or read after the + // next push) cannot take down the warning for a newer head that is still gated, + // and a notice left by an older head is still cleared once the current head runs. + // The PR is re-read for this rather than trusted from the event payload, which + // is as old as the job. + const head = ''; + const removable = async c => c.body.includes(head) + || (await github.rest.pulls.get({ ...context.repo, pull_number: pr.number })) + .data.head.sha === pr.head.sha; // `pull_request` and `pull_request_target` dispatch from the same push, so the // CI run may not be listed yet when this job reaches the API. Poll briefly // rather than reporting "never ran" against a run that is seconds from @@ -168,14 +189,15 @@ jobs: if (state === 'ran') { // Upserted and removed by marker, like the overlap comment: once the run is // approved the notice is wrong, and a stale warning is its own bug. - if (mine) await github.rest.issues.deleteComment( + if (mine && await removable(mine)) await github.rest.issues.deleteComment( { ...context.repo, comment_id: mine.id }); return; } - const body = marker + '\nCI has not run on this head: the workflow run was ' + - 'created as `action_required` and is waiting for a maintainer to approve ' + - 'it. Until then the checks above do not mean the repo\'s gate passed — ' + - '`lint + tests + image` has not executed at all.\n\nThis is the default ' + + const body = marker + '\n' + head + '\nCI has not run on this head: the ' + + 'workflow run was created as `action_required` and is waiting for a ' + + 'maintainer to approve it. Until then the checks above do not mean the ' + + 'repo\'s gate passed — `lint + tests + image` has not executed at all.' + + '\n\nThis is the default ' + '"require approval for first-time contributors" setting, not anything ' + 'wrong with this pull request, and it clears once a maintainer releases ' + 'the run (#693).'; @@ -199,7 +221,7 @@ jobs: const stale = fresh.find( c => c.user && c.user.type === 'Bot' && c.body && c.body.startsWith(marker)); - if (stale) await github.rest.issues.deleteComment( + if (stale && await removable(stale)) await github.rest.issues.deleteComment( { ...context.repo, comment_id: stale.id }); ci-not-run-clear: @@ -252,6 +274,12 @@ jobs: && c.body && c.body.startsWith(marker)); // Deleted whatever the run concluded, the gated case above excepted. A failed // run is still a run: the notice says CI has not executed, and once it has, - // that is false regardless of result. - if (mine) await github.rest.issues.deleteComment( + // that is false regardless of result. By ci-not-run's rule: this run's own + // head's notice, or any notice while this head is still the PR's head. The list + // above is a snapshot, and the PR may since have moved to a newer head whose + // notice is not this run's to clear. + const removable = async c => c.body.includes('') + || (await github.rest.pulls.get({ ...context.repo, pull_number: pr.number })) + .data.head.sha === sha; + if (mine && await removable(mine)) await github.rest.issues.deleteComment( { ...context.repo, comment_id: mine.id }); diff --git a/tests/queue_guard_ci_notice.mjs b/tests/queue_guard_ci_notice.mjs new file mode 100644 index 000000000..a3d6a263a --- /dev/null +++ b/tests/queue_guard_ci_notice.mjs @@ -0,0 +1,170 @@ +// Executes queue-guard.yml's ci-not-run and ci-not-run-clear scripts, unchanged, against an +// in-memory GitHub API, and prints what each scenario leaves on the thread as JSON. +// tests/unit/test_queue_guard_ci_notice.py runs it and holds the assertions; this file +// only replays interleavings that a single workflow run cannot produce on demand. +// +// No dependencies: the scripts are lifted out of the YAML block scalars by indentation, and +// `github` is a fake carrying only the calls they make. A script calling anything else +// throws, so a new API call cannot slip past the fixture unmodelled. +// +// Run: node tests/queue_guard_ci_notice.mjs + +import { readFileSync } from 'node:fs'; + +const WORKFLOW = new URL('../.github/workflows/queue-guard.yml', import.meta.url); +const CI = '.github/workflows/ci.yml'; +const AsyncFunction = (async () => {}).constructor; + +function jobScript(yaml, job) { + const lines = yaml.split('\n'); + const start = lines.indexOf(` ${job}:`); + if (start < 0) throw new Error(`no ${job} job in queue-guard.yml`); + const at = lines.findIndex((l, i) => i > start && /^ +script: \|$/.test(l)); + const indent = lines[at].indexOf('script') + 2; + const body = []; + for (const l of lines.slice(at + 1)) { + if (l.trim() && l.length - l.trimStart().length < indent) break; + body.push(l.slice(indent)); + } + // `setTimeout` is a parameter so the poll's 10 s sleeps cost nothing here: shadowing the + // global is how the "no run visible yet" path runs without waiting out the real poll. + return new AsyncFunction('github', 'context', 'setTimeout', body.join('\n')); +} + +const yaml = readFileSync(WORKFLOW, 'utf8'); +const postJob = jobScript(yaml, 'ci-not-run'); +const clearJob = jobScript(yaml, 'ci-not-run-clear'); + +// One PR, its CI runs by head, and its comments. `hooks.runs` fires on each +// listWorkflowRunsForRepo call, which is where a second job is spliced in. +function world() { + const w = { head: null, runs: {}, comments: [], nextId: 1, hooks: {} }; + const repo = { owner: 'flop-labs', repo: 'technocore-chat' }; + const pr = () => ({ + number: 735, + head: { sha: w.head, repo: { full_name: 'fork/technocore-chat' } }, + base: { repo: { full_name: 'flop-labs/technocore-chat' } }, + }); + const github = { + paginate: async (fn, args) => (await fn(args)).data, + rest: { + actions: { + listWorkflowRunsForRepo: async ({ head_sha }) => { + if (w.hooks.runs) await w.hooks.runs(head_sha); + const r = w.runs[head_sha]; + return { data: { workflow_runs: r ? [{ path: CI, head_sha, ...r }] : [] } }; + }, + }, + pulls: { + list: async () => ({ data: [w.listed ?? pr()] }), + get: async () => ({ data: pr() }), + }, + issues: { + listComments: async () => ({ data: w.comments.map(c => ({ ...c })) }), + createComment: async ({ body }) => { + w.comments.push({ id: w.nextId++, body, user: { type: 'Bot' } }); + }, + updateComment: async ({ comment_id, body }) => { + w.comments.find(c => c.id === comment_id).body = body; + }, + deleteComment: async ({ comment_id }) => { + w.comments = w.comments.filter(c => c.id !== comment_id); + }, + }, + }, + }; + const now = fn => fn(); + w.post = () => postJob(github, { repo, payload: { pull_request: pr() } }, now); + w.clear = (sha, conclusion) => clearJob(github, { + repo, payload: { workflow_run: { event: 'pull_request', head_sha: sha, conclusion } }, + }, now); + w.notice = () => { + const c = w.comments.find(c => c.body.startsWith('')); + return c ? (c.body.match(//) || [null, 'untagged'])[1] : null; + }; + return w; +} + +const scenarios = { + // Controls: the lifecycle #735 already had, run rather than parsed. + async gated_posts() { + const w = world(); + w.head = 'aaa'; w.runs.aaa = { conclusion: 'action_required' }; + await w.post(); + return w.notice(); + }, + async approval_clears() { + const w = world(); + w.head = 'aaa'; w.runs.aaa = { conclusion: 'action_required' }; + await w.post(); + w.runs.aaa = { conclusion: 'success' }; + await w.clear('aaa', 'success'); + return w.notice(); + }, + async ran_head_clears_its_own() { + const w = world(); + w.head = 'aaa'; w.runs.aaa = { conclusion: 'action_required' }; + await w.post(); + w.runs.aaa = { conclusion: 'success' }; + await w.post(); + return w.notice(); + }, + // The race @renhi measured. Head A's job writes its notice; before its post-write + // re-read, the PR is pushed to B, B's job sees B gated and writes, and A's run stops + // being action_required. A's cleanup then reads "not gated" for A -- and must not + // remove a notice that is now about B. + async older_cleanup_after_newer_write() { + const w = world(); + w.head = 'aaa'; w.runs.aaa = { conclusion: 'action_required' }; + let calls = 0; + w.hooks.runs = async sha => { + if (sha !== 'aaa' || ++calls !== 2) return; + w.hooks.runs = null; + w.head = 'bbb'; w.runs.bbb = { conclusion: 'action_required' }; + await w.post(); + w.runs.aaa = { conclusion: 'cancelled' }; + }; + await w.post(); + return w.notice(); + }, + // The same shape through ci-not-run-clear: its open-PR list still shows head A when A's + // run completes, while the thread already carries B's notice. + async clear_for_older_head_after_newer_write() { + const w = world(); + w.head = 'aaa'; w.runs.aaa = { conclusion: 'action_required' }; + await w.post(); + w.listed = { number: 735, head: { sha: 'aaa' } }; + w.head = 'bbb'; w.runs.bbb = { conclusion: 'action_required' }; + await w.post(); + w.runs.aaa = { conclusion: 'success' }; + await w.clear('aaa', 'success'); + return w.notice(); + }, + // Head identity must not strand a notice. A is gated and noticed; the PR moves to B, + // whose run has not surfaced within the poll, so B's job leaves A's notice standing (the + // 'unknown' rule). When B's run is approved and completes, the PR's current head has + // run: a notice about a head the PR has left is false, and must go. + async newer_head_run_clears_an_older_heads_notice() { + const w = world(); + w.head = 'aaa'; w.runs.aaa = { conclusion: 'action_required' }; + await w.post(); + w.head = 'bbb'; + await w.post(); + w.runs.bbb = { conclusion: 'success' }; + await w.clear('bbb', 'success'); + return w.notice(); + }, + // The same through the posting job: a synchronize to B whose run is seen running. + async newer_head_seen_running_clears_an_older_heads_notice() { + const w = world(); + w.head = 'aaa'; w.runs.aaa = { conclusion: 'action_required' }; + await w.post(); + w.head = 'bbb'; w.runs.bbb = { conclusion: null }; + await w.post(); + return w.notice(); + }, +}; + +const out = {}; +for (const [name, run] of Object.entries(scenarios)) out[name] = await run(); +console.log(JSON.stringify(out)); diff --git a/tests/unit/test_queue_guard_ci_notice.py b/tests/unit/test_queue_guard_ci_notice.py index 04fa68380..5862bcbc2 100644 --- a/tests/unit/test_queue_guard_ci_notice.py +++ b/tests/unit/test_queue_guard_ci_notice.py @@ -18,12 +18,17 @@ that window; the reconcile has to come after the write, because the write is what makes the stale notice exist. -Both are pinned structurally rather than behaviourally, and that limit is worth stating: no -JavaScript runs in this suite. `tests/package.json` is Playwright for the browser gate and -says so, and `tests/edge/test_edge_worker.py` -- the one other test whose subject is -JavaScript -- also asserts agreement by parsing rather than by executing. An executable -regression would mean a Node runner and a `github-script` shim, which is a larger change -than the workflow it would be testing. +Those two are pinned structurally. The third is not, because it was found by running the +scripts: the notice is one comment shared by every head of the PR, so an older head's job +-- its post-write cleanup, or ci-not-run-clear for its completed run -- could delete the +notice a newer, still-gated head had just written. That is an interleaving of two jobs, and +no assertion about one script's text can see it, so `tests/queue_guard_ci_notice.mjs` +executes both scripts unchanged against an in-memory GitHub API and replays it. A job now +removes its own head's notice, or another head's only while its head is still the PR's; +the second half is replayed too, because without it a notice an older head left is +stranded once the current head runs. The fixture needs only `node` (no npm install; +`tests/package.json` stays Playwright's) and is skipped without one, except under CI, where +a missing Node is a failure rather than a pass. Raised by @renhi and @luch91. Parsed with a regex rather than a YAML library, for the reason `tests/unit/test_browser_gate.py` gives: PyYAML is here only as somebody else's transitive @@ -34,11 +39,18 @@ from __future__ import annotations +import json +import os import re +import shutil +import subprocess from pathlib import Path +import pytest + ROOT = Path(__file__).resolve().parents[2] WORKFLOW = ROOT / ".github" / "workflows" / "queue-guard.yml" +FIXTURE = ROOT / "tests" / "queue_guard_ci_notice.mjs" # The `ci-not-run` job's inline script, up to the next job at the same indentation. # `ci-not-run-clear` is a separate lifecycle with its own rules and must not be caught here. @@ -96,3 +108,59 @@ def test_the_gated_path_rechecks_the_run_after_it_writes(): "the post-write re-read reaches no delete, so it observes the stale notice " "and leaves it in place" ) + + +@pytest.fixture(scope="module") +def replayed() -> dict[str, str | None]: + node = shutil.which("node") + if node is None: + if os.environ.get("CI"): + pytest.fail("node is not on PATH; the ci-not-run interleavings did not run") + pytest.skip("node is not on PATH") + out = subprocess.run([node, str(FIXTURE)], capture_output=True, text=True, timeout=60) + assert out.returncode == 0, out.stderr + return json.loads(out.stdout) + + +def test_the_lifecycle_still_posts_and_clears(replayed): + """Controls, so the race tests below cannot pass by a fixture that never posts.""" + assert replayed["gated_posts"] == "aaa", "a gated head gets a notice naming it" + assert replayed["approval_clears"] is None, "a completed run clears its head's notice" + assert replayed["ran_head_clears_its_own"] is None, "a head seen running clears its own" + + +def test_an_older_heads_cleanup_leaves_a_newer_heads_notice(replayed): + """Head A's job posts, the PR moves to B and B's job posts, then A's run leaves + `action_required` and A's post-write re-read sees it. Deleting there removed B's + warning while B was still gated, and nothing would put it back.""" + assert replayed["older_cleanup_after_newer_write"] == "bbb" + + +def test_clearing_an_older_heads_run_leaves_a_newer_heads_notice(replayed): + """The same race through ci-not-run-clear, which sits outside the posting job's + concurrency group: its open-PR list can still show head A when A's run completes.""" + assert replayed["clear_for_older_head_after_newer_write"] == "bbb" + + +def test_a_newer_heads_run_clears_a_notice_an_older_head_left(replayed): + """The other side of head identity. A synchronize whose run has not surfaced within the + poll leaves the previous head's notice standing, by the 'unknown' rule; once the PR's + current head has run, that notice is false and must go. A rule of "only ever your own + head's notice" stranded it for good, through both jobs.""" + assert replayed["newer_head_run_clears_an_older_heads_notice"] is None + assert replayed["newer_head_seen_running_clears_an_older_heads_notice"] is None + + +def test_posting_jobs_are_serialised_per_pr(): + """Head identity stops a wrong delete; the concurrency group stops two posting jobs + reading and writing the same comment at once, which head identity alone narrows but + does not close (a list, then a newer head's update, then a delete by id).""" + job = _JOB.search(WORKFLOW.read_text(encoding="utf-8")) + assert job + assert re.search( + r"^ concurrency:\n" + r" group: queue-guard-ci-not-run-\$\{\{ github\.event\.pull_request\.number \}\}\n" + r" cancel-in-progress: false\n", + job.group(1), + re.M, + ), "ci-not-run is no longer serialised per pull request"