This is an automated email from the ASF dual-hosted git repository.
cloud-fan pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/spark.git
The following commit(s) were added to refs/heads/master by this push:
new 341c2ad5a9d2 [SPARK-60879][INFRA] Speed up build status update workflow
341c2ad5a9d2 is described below
commit 341c2ad5a9d2f06f471e37d4b87e2d10e9081f32
Author: Nicholas Chammas <[email protected]>
AuthorDate: Tue Nov 10 09:45:38 2026 +0000
[SPARK-60879][INFRA] Speed up build status update workflow
### What changes were proposed in this pull request?
Following on to #59829, refactor the scheduled build status updater
(`update_build_status.yml`) completely:
- Use batched GraphQL requests instead of per-PR REST requests.
- Only update PR checks that need to be changed. Do a full sync
periodically to catch build updates not associated with PR updates (e.g. a job
is rerun with no new commit).
- Clean up the log to only show key metrics and updates made.
- Move the core logic into its own JavaScript file next to the workflow.
Example of cleaned up log:
```text
https://github.com/apache/spark/pull/60090 1dac863: queued -> in_progress
https://github.com/apache/spark/pull/59954 48a5471: in_progress -> success
726 PRs checked, 36 skipped. Build checks: 7 updated, 2 created, 681
unchanged.
```
### Why are the changes needed?
Currently, an update pass takes about 10 minutes on a 15-minute schedule.
That slows down status updates and makes changes to the workflow painful to
test. Nearly all of that time goes to per-PR REST reads for PRs that haven't
changed in weeks, and to rewriting checks that haven't changed.
Fork runs usually finish within a few hours of a push. Of the latest fork
runs on 690 open PRs, 8 were rerun more than 3 days after the push. The full
sync picks those up.
| | Before | After |
|---|---|---|
| Time per pass | ~10 min | ~45-60 s (~3-5 min for a full sync) |
| PRs synced per pass | ~725 (all open) | ~170 |
| API reads per pass | ~1,480 REST | 7 GraphQL |
| Check updates per pass | ~685 | ~3 |
| Log lines per pass | ~3,400 | ~10-15 |
| Runner time per day | ~16 h | ~3 h |
### Does this PR introduce _any_ user-facing change?
No, not for end-users.
For contributors: `Build` checks update the same way, just sooner. A fork
run rerun more than 3 days after the PR was last updated shows up on the next
full sync, which is scheduled every 4 hours, or on the next pass after any PR
activity (e.g. a comment).
Contributor guidance now explains enabling Actions, using a non-master
branch, and retriggering builds. To keep fork master as an upstream-sync
branch, new Build checks for PRs from master provide `action_required` guidance
rather than linking to a build, even if an older workflow ran there; existing
run-linked checks continue updating.
### How was this patch tested?
Via an agent:
I replayed the old and new scripts read-only against live `apache/spark`
PRs, intercepting writes. The new script made no write the old one didn't. All
but one of the updates it skipped were no-ops. The remaining one was a stuck
rerun on a PR outside the 3-day window, which the full sync covers. A full-sync
replay synced all 727 open PRs.
I also replayed both scripts with existing checks hidden, so every check
had to be created. 724 of 725 creates matched, and each new check had its fork
run's state. The one difference was a PR pushed a few minutes earlier with no
fork run yet, which the new script left for the next pass.
I ran quick and full syncs locally through `actions/github-script` against
live PR data, intercepting writes and simulating responses, including ignored
rerun updates. They checked 169 and 729 PRs in 57 seconds and 264 seconds, and
logged 7 and 8 lines. All 26 focused tests passed, covering unchanged checks,
applied and ignored updates, new checks, PRs from a fork's `master`, and
errors. The test and dry-run harnesses load the JavaScript module directly.
Replaying the 3 open PRs from [...]
Tested on GitHub against my personal fork with a real `GITHUB_TOKEN`: a
full read-only sync checked 728 PRs in 4m30s using 18 GraphQL points. A
temporary fork PR verified check creation, updating the same check from queued
to cancelled, and zero API writes on an unchanged repeat, with no duplicate
checks.
### Was this patch authored or co-authored using generative AI tooling?
Generated-by: GitHub Copilot
Closes #60098 from nchammas/build-status-optimization.
Authored-by: Nicholas Chammas <[email protected]>
Signed-off-by: Wenchen Fan <[email protected]>
skip-checks: true
---
.github/workflows/update_build_status.js | 394 +++++++++++++++++++++++++++
.github/workflows/update_build_status.yml | 433 +++---------------------------
2 files changed, 431 insertions(+), 396 deletions(-)
diff --git a/.github/workflows/update_build_status.js
b/.github/workflows/update_build_status.js
new file mode 100644
index 000000000000..8642815c5396
--- /dev/null
+++ b/.github/workflows/update_build_status.js
@@ -0,0 +1,394 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.
+ */
+
+'use strict';
+
+module.exports = async ({github, context, core, env = process.env, log =
console}) => {
+ // Open PRs are read with one GraphQL query per page of PRs. For each PR it
returns
+ // the Build checks on the head commit (statusCheckRollup.commit) and the
fork's
+ // workflow runs for that commit (headRef.target), both as GitHub Actions
check
+ // suites: fork runs are Actions runs, and Build checks written with the
GITHUB_TOKEN
+ // land in Actions suites too. On the PR side, only suites containing Build
checks
+ // are relevant; unrelated upstream workflow runs must not fill the page.
+ //
+ // A PR rarely has more than a few such suites. A fork's default branch can
collect
+ // thousands from scheduled workflows, but suites are listed oldest first
and a push
+ // creates its runs' suites right away, so they are still among the first.
Should a
+ // page ever not hold everything a PR needs, the PR fails loudly rather than
being
+ // synced from partial data.
+ //
+ // GitHub aborts a GraphQL request after 10 seconds and allows 60 seconds of
GraphQL
+ // CPU time per minute. A page of 25 PRs takes about 3 seconds, so each page
is
+ // followed by a pause as long as it took.
+ //
https://docs.github.com/en/graphql/overview/rate-limits-and-query-limits-for-the-graphql-api
+ const GITHUB_ACTIONS_APP_ID = 15368
+ const PR_PAGE_SIZE = 25
+ // Name of the mirrored PR check, not the workflow.
+ const BUILD_CHECK_NAME = 'Build'
+
+ // Quick syncs cover only open PRs updated in the last
QUICK_SYNC_LOOKBACK_DAYS. A
+ // push, comment, review, or label change updates a PR, but a check change
does not.
+ // Fork runs usually finish within hours of a push, and most reruns happen
within
+ // days. A later rerun, or a gap in quick syncs longer than the lookback, is
picked
+ // up by the next full sync, which covers all open PRs. Both schedules are
defined
+ // in update_build_status.yml.
+ const QUICK_SYNC_LOOKBACK_DAYS = 3
+ const fullSync = env.FULL_SYNC == 'true'
+ const updatedSince = fullSync ? 0
+ : Date.now() - QUICK_SYNC_LOOKBACK_DAYS * 24 * 60 * 60 * 1000
+
+ // A run-linked Build check points at the fork's build_main.yml run for the
PR branch.
+ // Right after a push that run may not be registered yet, so a PR updated in
the last
+ // NEW_RUN_GRACE_MINUTES without a usable run is left for a later pass
instead of
+ // receiving action_required guidance.
+ const BUILD_WORKFLOW = '.github/workflows/build_main.yml'
+ const NEW_RUN_GRACE_MINUTES = 5
+ const runGraceSince = Date.now() - NEW_RUN_GRACE_MINUTES * 60 * 1000
+
+ const prPageQuery = `
+ query($owner: String!, $repo: String!, $size: Int!, $cursor: String,
$appId: Int!) {
+ repository(owner: $owner, name: $repo) {
+ pullRequests(states: OPEN, first: $size, after: $cursor,
+ orderBy: {field: UPDATED_AT, direction: DESC}) {
+ pageInfo { hasNextPage endCursor }
+ nodes {
+ number
+ updatedAt
+ headRefOid
+ statusCheckRollup {
+ commit {
+ oid
+ checkSuites(first: 10, filterBy: {
+ appId: $appId, checkName: "${BUILD_CHECK_NAME}"
+ }) {
+ pageInfo { hasNextPage }
+ nodes {
+ checkRuns(first: 10,
+ filterBy: {
+ checkName: "${BUILD_CHECK_NAME}", checkType: LATEST
+ }) {
+ pageInfo { hasNextPage }
+ nodes { databaseId status conclusion text }
+ }
+ }
+ }
+ }
+ }
+ headRef {
+ name
+ repository { name owner { login } }
+ target {
+ oid
+ ... on Commit {
+ checkSuites(first: 10, filterBy: {appId: $appId}) {
+ pageInfo { hasNextPage }
+ nodes {
+ status
+ conclusion
+ branch { name }
+ workflowRun { databaseId file { path } }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }`
+
+ // Yield the open PRs updated since updatedSince one page at a time, most
recently
+ // updated first, pausing after each page as long as it took (see above). A
PR
+ // updated during the pass moves to the front and may be missed, but it is
then
+ // recent enough for the next pass.
+ async function* listOpenPRs() {
+ let cursor = null
+ for (;;) {
+ const started = Date.now()
+ const data = await github.graphql(prPageQuery, {
+ ...context.repo,
+ size: PR_PAGE_SIZE,
+ cursor,
+ appId: GITHUB_ACTIONS_APP_ID
+ })
+ const took = Date.now() - started
+ const page = data.repository.pullRequests
+ const recent = page.nodes.filter(node =>
+ Date.parse(node.updatedAt) >= updatedSince)
+ yield recent
+ if (recent.length < page.nodes.length || !page.pageInfo.hasNextPage) {
+ return
+ }
+ cursor = page.pageInfo.endCursor
+ await new Promise(resolve => setTimeout(resolve, took))
+ }
+ }
+
+ // Flatten a PR from a page into its number, updatedAt, head sha, fork
owner, repo and
+ // branch, and:
+ // - buildChecks: the head commit's Build checks.
+ // - forkRuns: the fork's workflow runs for the head commit, by run ID, and
+ // forkRunsTruncated: whether the page held only some of them.
+ // - buildRun: the fork's newest build_main.yml run for the PR branch, if
any. The
+ // branch matters because the same commit can have runs from pushes to
different
+ // branches, including a skipped master run and a build on the PR branch.
+ // Statuses and conclusions are lowercased to match the check-runs REST API.
+ // Return null if the fork branch is gone or not at the PR head commit (the
branch
+ // was just pushed to and the PR has yet to follow). Throw if the page does
not hold
+ // all of the PR's Build checks.
+ const toPR = (node) => {
+ const target = node.headRef?.target
+ const commit = node.statusCheckRollup?.commit
+ if (target?.oid != node.headRefOid || (commit && commit.oid !=
node.headRefOid)) {
+ return null
+ }
+ // A commit without any checks or statuses has no rollup.
+ const suites = commit?.checkSuites.nodes ?? []
+ if (commit?.checkSuites.pageInfo.hasNextPage
+ || suites.some(s => s.checkRuns.pageInfo.hasNextPage)) {
+ throw new Error('The PR head commit has more check suites or Build
checks '
+ + 'than a page holds')
+ }
+ // checkName filtering can repeat suites; process each Build check only
once.
+ const checks = new Map(suites.flatMap(s => s.checkRuns.nodes).map(cr =>
[cr.databaseId, cr]))
+ const lower = (value) => value?.toLowerCase()
+ const runs = target.checkSuites.nodes.filter(s => s.workflowRun).map(s =>
({
+ id: s.workflowRun.databaseId,
+ status: lower(s.status),
+ conclusion: lower(s.conclusion),
+ workflow: s.workflowRun.file?.path,
+ branch: s.branch?.name
+ }))
+ return {
+ number: node.number,
+ updatedAt: node.updatedAt,
+ sha: node.headRefOid,
+ forkOwner: node.headRef.repository.owner.login,
+ forkRepo: node.headRef.repository.name,
+ branch: node.headRef.name,
+ buildChecks: [...checks.values()].map(cr => ({
+ id: cr.databaseId,
+ status: lower(cr.status),
+ conclusion: lower(cr.conclusion),
+ text: cr.text
+ })),
+ forkRuns: new Map(runs.map(run => [String(run.id), run])),
+ forkRunsTruncated: target.checkSuites.pageInfo.hasNextPage,
+ buildRun: runs.findLast(run => run.workflow == BUILD_WORKFLOW
+ && run.branch == node.headRef.name)
+ }
+ }
+
+ // The fork run ID a Build check points at, stored as JSON in its output
text, or
+ // undefined if the text is not that JSON (e.g. a check from an older
version or a
+ // manual run).
+ const runIdOf = (cr) => {
+ try {
+ return JSON.parse(cr.text).run_id
+ } catch {
+ return undefined
+ }
+ }
+
+ // The Build check state that shows a fork run's state. The check-runs API
accepts
+ // fewer values than a run reports: the other pending statuses (requested,
waiting,
+ // pending) become queued, and the other conclusions (startup_failure,
stale, or
+ // none), which all mean the run produced no test result, become failure.
+ const checkState = (run) => {
+ if (run.status != 'completed') {
+ return {status: run.status == 'in_progress' ? 'in_progress' : 'queued'}
+ }
+ const conclusions = ['success', 'failure', 'neutral', 'cancelled',
'timed_out',
+ 'action_required', 'skipped']
+ return {
+ status: 'completed',
+ conclusion: conclusions.includes(run.conclusion) ? run.conclusion :
'failure'
+ }
+ }
+ const label = (state) => state.status == 'completed' ? state.conclusion :
state.status
+ const sameState = (a, b) => a.status == b.status
+ && (a.status != 'completed' || a.conclusion == b.conclusion)
+
+ // Record PR-specific failures and fail the step after syncing the rest.
+ // A failed page query instead aborts the pass.
+ const failedPRs = new Set()
+
+ // The log lists only the Build checks a pass creates or updates, and
errors, each
+ // with its PR and head commit. Everything else is counted for a summary at
the end.
+ const count = {prs: 0, skipped: 0, updated: 0, created: 0, unchanged: 0,
notApplied: 0}
+ const prUrl =
`https://github.com/${context.repo.owner}/${context.repo.repo}/pull/`
+
+ log.log(fullSync ? 'Full sync: all open PRs'
+ : 'Quick sync: open PRs updated in the last ' + QUICK_SYNC_LOOKBACK_DAYS +
' days')
+ for await (const prs of listOpenPRs()) {
+ for (const node of prs) {
+ count.prs++
+ const ref = prUrl + node.number + ' ' + node.headRefOid.slice(0, 7)
+ let pr
+ try {
+ pr = toPR(node)
+ } catch (error) {
+ log.error(ref + ': ' + error.message + '; raise the limits in
prPageQuery')
+ failedPRs.add(node.number)
+ continue
+ }
+ if (!pr) {
+ count.skipped++
+ continue
+ }
+
+ // Sync every Build check that points at a fork run, not just the first:
a commit
+ // can carry more than one (e.g. left by the notify workflow this one
replaced).
+ // An action_required guidance check is not linked to a run.
+ let syncableBuildCheck = false
+ for (const cr of pr.buildChecks) {
+ if (cr.conclusion == 'action_required') {
+ continue
+ }
+ const runId = runIdOf(cr)
+ const run = pr.forkRuns.get(String(runId))
+ if (!run) {
+ if (runId && pr.forkRunsTruncated) {
+ // The run may be among the fork's check suites the page left out.
Keep
+ // the backfill from replacing the check, and fail the PR to get
noticed.
+ log.error(ref + ': fork run ' + runId + ' not in the first fork
check '
+ + 'suites; raise the limits in prPageQuery')
+ failedPRs.add(pr.number)
+ syncableBuildCheck = true
+ }
+ // Otherwise the check's output is unusable or its fork run was
deleted, so
+ // it can never be synced; the backfill below replaces it.
+ continue
+ }
+ syncableBuildCheck = true
+
+ // Leave a check alone if it already shows the run's state, as nearly
all do.
+ const state = checkState(run)
+ if (sameState(cr, state)) {
+ count.unchanged++
+ continue
+ }
+ const change = label(cr) + ' -> ' + label(state)
+ try {
+ const {data: updated} = await github.rest.checks.update({
+ ...context.repo,
+ check_run_id: cr.id,
+ ...state
+ })
+ // A successful request can leave the state unchanged, notably when
trying
+ // to reopen a completed check after a rerun.
+ if (sameState(cr, updated)) {
+ count.unchanged++
+ } else {
+ log.log(ref + ': ' + label(cr) + ' -> ' + label(updated))
+ count.updated++
+ }
+ if (!sameState(updated, state)) {
+ count.notApplied++
+ }
+ } catch (error) {
+ log.error(ref + ': ' + change + ' failed: ' + error.message)
+ failedPRs.add(pr.number)
+ }
+ }
+
+ // No syncable Build check: link one to the PR branch's build_main.yml
run, or
+ // create action_required guidance if no run exists, it was skipped, or
the PR
+ // is from fork master. Fork master is reserved for syncing upstream;
new PR
+ // builds must use other branches, even if an older workflow ran on
master.
+ // Existing run-linked checks are still synchronized above.
+ if (!syncableBuildCheck) {
+ const run = pr.branch == 'master' || pr.buildRun?.conclusion ==
'skipped'
+ ? undefined : pr.buildRun
+ if (!run) {
+ // Already provided guidance, or still within the run-registration
grace period.
+ if (pr.buildChecks.some(cr => cr.conclusion == 'action_required')
+ || Date.parse(pr.updatedAt) > runGraceSince) {
+ count.skipped++
+ continue
+ }
+ }
+
+ const state = run ? checkState(run)
+ : {status: 'completed', conclusion: 'action_required'}
+ const check = {
+ ...context.repo, name: BUILD_CHECK_NAME, head_sha: pr.sha, ...state
+ }
+ const change = 'none -> ' + label(state)
+ try {
+ if (run) {
+ const actions_url = 'https://github.com/' + pr.forkOwner + '/' +
pr.forkRepo
+ + '/actions/runs/' + run.id
+ check.output = {
+ title: 'Test results',
+ summary: '[See test results](' + actions_url + ')\n\n'
+ + 'If the tests fail for reasons unrelated to this pull
request, '
+ + 'please rerun the workflow in your forked repository.\n'
+ + 'If the failures are related to this pull request, '
+ + 'please investigate them and push follow-up changes.',
+ text: JSON.stringify({
+ owner: pr.forkOwner,
+ repo: pr.forkRepo,
+ run_id: run.id
+ })
+ }
+ check.details_url = actions_url
+ } else {
+ // No usable run, or a fork-master PR: explain the required setup.
+ check.output = {
+ title: 'PR build setup requires attention',
+ summary: `
+ A supported Build check is not available for this PR head commit.
+
+ 1. If you did not enable GitHub Actions in your forked repository, please
enable it by clicking the button as shown in the image below. See also
[Managing GitHub Actions settings for a
repository](https://docs.github.com/en/repositories/managing-your-repositorys-settings-and-features/enabling-features-for-your-repository/managing-github-actions-settings-for-a-repository)
for more details.
+ 2. For PR build status, use a branch other than \`master\` in your fork.`
+ + (pr.branch == 'master' ? '' : `
+
+ After fixing the cause, push a new commit to your PR branch to start the
build.`),
+ images: [
+ {
+ alt: 'enabling workflows button',
+ image_url:
'https://raw.githubusercontent.com/apache/spark/master/.github/workflows/images/workflow-enable-button.png'
+ }
+ ]
+ }
+ }
+ await github.rest.checks.create(check)
+ log.log(ref + ': ' + change)
+ count.created++
+ } catch (error) {
+ log.error(ref + ': ' + change + ' failed: ' + error.message)
+ failedPRs.add(pr.number)
+ }
+ }
+ }
+ }
+
+ log.log(count.prs + ' PRs checked, ' + count.skipped + ' skipped. '
+ + 'Build checks: ' + count.updated + ' updated, ' + count.created + '
created, '
+ + count.unchanged + ' unchanged.')
+
+ if (count.notApplied > 0) {
+ core.warning(count.notApplied + ' check update(s) did not reach the
requested '
+ + 'state. GitHub cannot reopen completed checks.')
+ }
+
+ if (failedPRs.size > 0) {
+ core.setFailed('Failed to sync ' + failedPRs.size + ' PR(s), will retry
next pass: #'
+ + [...failedPRs].join(', #'))
+ }
+};
diff --git a/.github/workflows/update_build_status.yml
b/.github/workflows/update_build_status.yml
index 43bf185a8236..e23a263fef9a 100644
--- a/.github/workflows/update_build_status.yml
+++ b/.github/workflows/update_build_status.yml
@@ -22,415 +22,56 @@
# workflow only reports their results. Running on a schedule avoids
# `pull_request_target` and needs no maintainer approval for fork PRs.
#
-# Each pass synchronizes existing `Build` checks with their fork runs. A
missing
-# check is created as `queued`, pointing at the fork run for the PR head
commit,
-# and synchronized on a later pass. If no fork run is found, an
`action_required`
-# check with guidance is created instead. GitHub may delay or drop scheduled
-# runs, so neither the initial check nor result updates are immediate.
+# Each pass synchronizes existing `Build` checks with their fork runs. Missing
+# checks are linked to the PR head's fork build, unless no run exists, the run
was
+# skipped, or the PR is from fork master. Those cases get `action_required`
guidance
+# after the registration grace period. Fork master is reserved for syncing
upstream;
+# PR builds should use other branches. Existing run-linked checks remain
supported,
+# including older master-branch builds. GitHub may delay or drop scheduled
runs, so
+# neither the initial check nor result updates are immediate.
-name: Update build status workflow
+name: Build Status
on:
schedule:
- - cron: "*/15 * * * *"
+ # Quick sync: open PRs updated in the last QUICK_SYNC_LOOKBACK_DAYS (set in
the script).
+ - cron: "*/10 * * * *"
+ # Full sync: all open PRs every 4 hours, between quick syncs and away from
the busy top of
+ # the hour and midnight UTC, when GitHub delays or drops scheduled runs.
+ # FULL_SYNC below must match this schedule.
+ - cron: "35 2-22/4 * * *"
+
+# Passes do not overlap, so two passes cannot both create a missing Build
check.
+concurrency:
+ group: ${{ github.workflow }}
+ cancel-in-progress: false
jobs:
update:
- name: Update build status
+ name: Update
+ if: github.repository == 'apache/spark'
runs-on: ubuntu-slim
permissions:
actions: read
checks: write
+ contents: read
+ pull-requests: read
+ statuses: read
steps:
- - name: "Update build status"
+ - name: Checkout build status script
+ uses: actions/checkout@v7
+ with:
+ sparse-checkout: .github/workflows/update_build_status.js
+ sparse-checkout-cone-mode: false
+ persist-credentials: false
+ - name: Sync status updates
uses: actions/github-script@v9
+ env:
+ FULL_SYNC: ${{ github.event.schedule == '35 2-22/4 * * *' }}
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
+ # Retry server errors (including GraphQL timeouts) and 429s with a
short backoff.
+ retries: 3
script: |
- const endpoint = 'GET /repos/:owner/:repo/pulls?state=:state'
- const params = {
- owner: context.repo.owner,
- repo: context.repo.repo,
- state: 'open'
- }
-
- // See
https://docs.github.com/en/graphql/reference/enums#mergestatestatus
- const maybeReady = ['behind', 'clean', 'draft', 'has_hooks',
'unknown', 'unstable'];
-
- // A fork workflow-run lookup can fail transiently (server errors,
network drops, or
- // REST rate limiting, which GitHub returns as 403 with rate-limit
headers or 429).
- // These should be retried on a later scheduled pass rather than
reported to the
- // contributor as a broken fork. Any other failure (e.g. a 404 for
a missing
- // build_main.yml) is treated as permanent.
- //
https://docs.github.com/en/rest/using-the-rest-api/rate-limits-for-the-rest-api
- const isTransientError = (e) => {
- if (!e.status) return true;
- if (e.status >= 500 || e.status == 429) return true;
- if (e.status == 403) {
- const headers = (e.response && e.response.headers) || {};
- return !!headers['retry-after'] ||
headers['x-ratelimit-remaining'] === '0'
- || /rate limit/i.test(e.message || '');
- }
- return false;
- };
-
- // List all check-runs for a commit. github.paginate follows every
page, so the Build
- // check is found even when a SHA accumulates many check-runs (CI
matrix, external
- // checks, duplicate Build checks from reopened PRs); missing it
would leave the PR
- // stuck in 'queued' forever. per_page=100 (not the default 30)
only reduces the
- // number of requests.
- const listCheckRuns = (ref) => github.paginate(
- 'GET /repos/{owner}/{repo}/commits/{ref}/check-runs',
- {
- owner: context.repo.owner,
- repo: context.repo.repo,
- ref: ref,
- per_page: 100
- }
- );
-
- // Parse a Build check's output text into the {owner, repo,
run_id} the run fetch
- // needs, or return null if it is absent, malformed, or missing a
field. JSON.parse
- // succeeding is not enough: a check from an older version, a
manual run, or another
- // app can carry null, {}, or unrelated JSON that parses but lacks
these fields, and
- // the run fetch would then fail.
- const parseRunParams = (cr) => {
- let params;
- try {
- params = JSON.parse(cr.output.text);
- } catch (error) {
- return null;
- }
- if (!params || !params.owner || !params.repo || !params.run_id) {
- return null;
- }
- return params;
- };
-
- // A Build check this updater can actually sync: not
action_required (written when
- // no fork run was found, and it carries no run params) and with
output
- // text carrying the {owner, repo, run_id} needed to fetch the
fork run. A Build check
- // with empty/malformed/fieldless output can never be synced, so
it must not count as
- // present - otherwise it would suppress the backfill and leave
the PR stuck with an
- // unsyncable check.
- const isSyncableBuildCheck = (cr) =>
- cr.name == 'Build' && cr.conclusion != 'action_required'
- && parseRunParams(cr) != null;
-
- // An action_required Build check: the contributor-facing "enable
Actions / rebase"
- // status written when no fork run was found. It is not syncable,
but it already
- // carries the guidance the no-run backfill branch would create,
so it is "useful".
- const isActionRequiredBuildCheck = (cr) =>
- cr.name == 'Build' && cr.conclusion == 'action_required';
-
- // PRs whose sync failed on this pass: listing their check runs,
PATCHing a Build
- // check, or backfilling one. A failed call skips only that PR (it
is retried on the
- // next pass) instead of aborting the whole scheduled run and
leaving every PR later
- // in the iteration unsynced. The step still fails after the pass,
so an error that
- // keeps recurring (e.g. a 422 for a value the endpoint rejects)
stays visible instead
- // of hiding in the log of a green run. Transient fork-run lookup
failures (see
- // isTransientError) are not recorded: they also skip the PR until
a later pass, but
- // leave the step green.
- const failedPRs = new Set();
-
- // PATCH a Build check-run, recording a failure against the PR
instead of throwing.
- const updateCheckRun = async (pr, body) => {
- try {
- await github.request('PATCH
/repos/{owner}/{repo}/check-runs/{check_run_id}', body);
- } catch (error) {
- console.error(' Updating check run ' + body.check_run_id +
' failed; '
- + 'will retry next pass');
- console.error(error);
- failedPRs.add(pr.number);
- }
- };
-
- // Iterate open PRs
- for await (const prs of github.paginate.iterator(endpoint,params))
{
- // Each page
- for await (const pr of prs.data) {
- console.log('SHA: ' + pr.head.sha)
- console.log(' Mergeable status: ' + pr.mergeable_state)
- if (pr.mergeable_state == null ||
maybeReady.includes(pr.mergeable_state)) {
- let checkRuns
- try {
- checkRuns = await listCheckRuns(pr.head.sha)
- } catch (error) {
- console.error(' Listing check runs failed for this PR;
will retry next pass')
- console.error(error)
- failedPRs.add(pr.number)
- continue
- }
-
- // Does this SHA already carry an action_required Build
check? An earlier pass
- // of this updater writes one when no fork run was found. It
is
- // not syncable, so it never suppresses the backfill below -
which means a PR
- // that permanently lacks a fork run (Actions disabled, old
master) would
- // otherwise re-poll on every 15-minute pass forever. When
one is already
- // present, the backfill's re-poll is unnecessary (see
below).
- const hasActionRequiredBuildCheck =
checkRuns.some(isActionRequiredBuildCheck)
-
- // Track whether a syncable Build check exists (see
isSyncableBuildCheck); if
- // not, the backfill after this loop creates one. Sync every
match (no early
- // break): a SHA can carry more than one Build check
(reopened PRs, or
- // overlapping updater runs). Branch protection evaluates
the newest check-run
- // of a given name, so syncing only the first would leave a
newer duplicate
- // stuck in 'queued' and block the PR.
- let syncableBuildCheck = false
- // Build checks whose referenced fork run is permanently
gone (404). They parse
- // as syncable (their output still carries valid run params)
but can never be
- // synced, so the recheck below must not let them suppress
the backfill.
- const staleCheckIds = new Set()
- for await (const cr of checkRuns) {
- if (cr.name == 'Build' && cr.conclusion !=
"action_required") {
- // Skip a check with unusable output (see
parseRunParams) instead of
- // aborting the whole scheduled run, which would block
every PR queued
- // behind it. Leaving syncableBuildCheck false lets the
backfill below
- // replace it rather than stranding the PR.
- const params = parseRunParams(cr)
- if (!params) {
- console.error('Skipping Build check ' + cr.id + ' with
unusable output')
- continue
- }
-
- // Get the workflow run in the forked repository
- let run
- try {
- run = await github.request('GET
/repos/{owner}/{repo}/actions/runs/{run_id}', params)
- } catch (error) {
- console.error(error)
- // The referenced fork run could not be fetched. A
transient failure (5xx,
- // rate limit) should be retried on a later pass, so
count the check as
- // syncable to suppress the backfill this pass. A
permanent not-found (404:
- // the PR author deleted the fork run or disabled
GitHub Actions) means this
- // check can never be synced, so leave
syncableBuildCheck false and let the
- // backfill below recreate a useful status - otherwise
the flag would stay
- // set and leave Build 'queued' indefinitely on every
pass.
- if (isTransientError(error)) {
- syncableBuildCheck = true
- } else {
- staleCheckIds.add(cr.id)
- }
- continue
- }
- // Only now that the run is fetched is this a check we
can actually sync.
- syncableBuildCheck = true
-
- // Keep syncing the status of the checks
- if (run.data.status == 'completed') {
- // PATCH /check-runs accepts only success | failure |
neutral |
- // cancelled | timed_out | action_required | skipped,
but a workflow_run
- // may also conclude startup_failure / stale, or
report a null conclusion.
- // Those all mean the run produced no test result, so
they become failure.
- const conclusions = ['success', 'failure', 'neutral',
'cancelled',
- 'timed_out', 'action_required', 'skipped']
- const conclusion =
conclusions.includes(run.data.conclusion)
- ? run.data.conclusion : 'failure'
- console.log(' Run ' + cr.id + ': set status (' +
run.data.status + ') and conclusion (' + run.data.conclusion + ' -> ' +
conclusion + ')')
- await updateCheckRun(pr, {
- owner: context.repo.owner,
- repo: context.repo.repo,
- check_run_id: cr.id,
- output: cr.output,
- status: run.data.status,
- conclusion: conclusion,
- details_url: run.data.details_url
- })
- } else {
- // PATCH /check-runs accepts only queued | in_progress
| completed,
- // but workflow_run may also report requested /
waiting / pending.
- const status = run.data.status == 'in_progress' ?
'in_progress' : 'queued'
- console.log(' Run ' + cr.id + ': set status (' +
run.data.status + ' -> ' + status + ')')
- await updateCheckRun(pr, {
- owner: context.repo.owner,
- repo: context.repo.repo,
- check_run_id: cr.id,
- output: cr.output,
- status: status,
- details_url: run.data.details_url
- })
- }
- }
- }
-
- // No syncable Build check: none was created yet, or only a
stale action_required
- // one exists. Create it here. Skip if the head repo was
deleted.
- if (!syncableBuildCheck && pr.head.repo) {
- const forkOwner = pr.head.repo.owner.login
- const forkRepo = pr.head.repo.name
- // Look up the fork's build_main.yml runs for the PR
branch.
- // Filter by branch (head.ref), not just head_sha:
- // build_main.yml skips fork pushes to master (the "Sync
fork" case), so the
- // same SHA can carry a skipped/unrelated run on another
branch, and a
- // head_sha-only lookup could attach the Build check to
that run instead of
- // the PR branch's. Then pick the run whose head_sha
equals the settled head
- // SHA so stale runs from earlier commits on the branch
cannot drive the
- // decision. Re-poll a few times: the run is often not yet
registered right
- // after a push, and we must not create the sticky
action_required check below
- // over registration lag. A transient lookup error (5xx,
network, rate limit)
- // aborts to a later scheduled pass; any other error is
treated as "no runs".
- //
- // When an action_required check already exists that lag
risk is already
- // realized, so a single sleepless lookup suffices - this
stops a PR that
- // permanently lacks a fork run (Actions disabled, old
master) from re-polling
- // (3 lookups plus two 3s sleeps) on every 15-minute pass
forever, while still
- // promoting it to a queued check on whichever pass first
sees a run appear.
- const attempts = hasActionRequiredBuildCheck ? 1 : 3
- let matched_run
- let transient = false
- for (let attempt = 0; attempt < attempts; attempt++) {
- let forkRuns
- try {
- const runs = await github.request(
- 'GET
/repos/{owner}/{repo}/actions/workflows/{id}/runs',
- {
- owner: forkOwner,
- repo: forkRepo,
- id: 'build_main.yml',
- branch: pr.head.ref
- }
- )
- forkRuns = runs.data.workflow_runs
- } catch (error) {
- console.error(error)
- // Transient -> retry on a later pass. Permanent (e.g.
a 404 for a
- // missing build_main.yml) -> there is no run to find
and it will not
- // appear in 3s, so stop polling with matched_run
undefined and let the
- // action_required branch below handle it. Either way,
do not burn the
- // remaining retries and sleeps on an error that
cannot resolve here.
- if (isTransientError(error)) {
- transient = true
- }
- break
- }
- matched_run = forkRuns.find(r => r.head_sha ==
pr.head.sha)
- if (matched_run) {
- break
- }
- if (attempt < attempts - 1) {
- await new Promise(resolve => setTimeout(resolve, 3000))
- }
- }
- if (transient) {
- console.log(' Fork run lookup failed transiently; will
retry next pass')
- continue
- }
-
- // An action_required Build check already exists and we
still found no run:
- // the guidance check the no-run branch below would create
is already present,
- // so there is nothing to backfill. Skip the recheck
listing and the create
- // outright.
- if (hasActionRequiredBuildCheck && !matched_run) {
- console.log(' action_required Build check present;
nothing to backfill')
- continue
- }
-
- // Recheck for an existing Build check immediately before
creating one. The
- // poll above can span up to ~6 seconds, during which an
overlapping updater run
- // may create the check; this recheck skips the backfill
in that case.
- // It narrows but cannot fully close the window (there is
no atomic
- // create-if-absent, and the list endpoint is eventually
consistent) - the
- // sync loop above stays tolerant of duplicates so any
that slip through still
- // converge.
- //
- // Skip the backfill only if a check that is already at
least as useful as the
- // one we would create exists. When we found a fork run,
that means a syncable
- // check (the queued check we would create). When we found
no run, that means a
- // syncable OR an action_required check (the guidance
check we would create).
- // In both cases a malformed/fieldless check does NOT
count - the sync loop
- // cannot sync it, so refusing here would strand the PR on
an unsyncable check;
- // we fall through and create a usable one instead. A
check whose fork run the
- // sync loop just found permanently gone (staleCheckIds)
is likewise not useful,
- // even though its output still parses as syncable, so it
too is excluded.
- //
- // The recheck listing and the create below are wrapped so
a failure on one
- // PR degrades to "skip this PR, retry next pass" (see
failedPRs) rather than
- // aborting the whole scheduled run and starving every PR
later in the
- // iteration - the same reason the sync loop above guards
its calls.
- try {
- const recheck = await listCheckRuns(pr.head.sha)
- const existingBuild = recheck.some(cr =>
- (isSyncableBuildCheck(cr) && !staleCheckIds.has(cr.id))
- || (!matched_run && isActionRequiredBuildCheck(cr)))
- if (existingBuild) {
- console.log(' Build check appeared during polling;
skipping backfill')
- continue
- }
-
- if (matched_run) {
- // A run exists for this head commit; point the check
at it and let the
- // next pass sync its status.
- const actions_url = 'https://github.com/' + forkOwner
+ '/' + forkRepo
- + '/actions/runs/' + matched_run.id
- console.log(' Backfilling missing Build check -> ' +
actions_url)
- await github.rest.checks.create({
- owner: context.repo.owner,
- repo: context.repo.repo,
- name: 'Build',
- head_sha: pr.head.sha,
- status: 'queued',
- output: {
- title: 'Test results',
- summary: '[See test results](' + actions_url +
')\n\n'
- + 'If the tests fail for reasons unrelated to
this pull request, '
- + 'please rerun the workflow in your forked
repository.\n'
- + 'If the failures are related to this pull
request, '
- + 'please investigate them and push follow-up
changes.',
- text: JSON.stringify({
- owner: forkOwner,
- repo: forkRepo,
- run_id: matched_run.id
- })
- },
- details_url: actions_url
- })
- } else {
- // No run for this head commit after re-polling (empty
result, permanent
- // lookup failure, or build_main.yml missing): Actions
is disabled, the
- // branch is on an old master, or the commit never
triggered a run. Create
- // an action_required check so the PR carries a
required status
- // telling the contributor how to fix it.
- console.log(' No forked run for head SHA; creating
action_required check')
- await github.rest.checks.create({
- owner: context.repo.owner,
- repo: context.repo.repo,
- name: 'Build',
- head_sha: pr.head.sha,
- status: 'completed',
- conclusion: 'action_required',
- output: {
- title: 'Workflow run detection failed',
- summary: `
- Unable to detect the workflow run for testing the changes in your
PR.
-
- 1. If you did not enable GitHub Actions in your forked repository,
please enable it by clicking the button as shown in the image below. See also
[Managing Github Actions Settings for a
repository](https://docs.github.com/en/repositories/managing-your-repositorys-settings-and-features/enabling-features-for-your-repository/managing-github-actions-settings-for-a-repository)
for more details.
- 2. It is possible your branch is based on the old \`master\`
branch in Apache Spark, please sync your branch to the latest master branch.
For example as below:
- \`\`\`bash
- git fetch upstream
- git rebase upstream/master
- git push origin YOUR_BRANCH --force
- \`\`\``,
- images: [
- {
- alt: 'enabling workflows button',
- image_url:
'https://raw.githubusercontent.com/apache/spark/master/.github/workflows/images/workflow-enable-button.png'
- }
- ]
- }
- })
- }
- } catch (error) {
- console.error(' Backfill failed for this PR; will retry
next pass')
- console.error(error)
- failedPRs.add(pr.number)
- continue
- }
- }
- }
- }
- }
-
- if (failedPRs.size > 0) {
- core.setFailed('Failed to sync ' + failedPRs.size + ' PR(s),
will retry next pass: #'
- + [...failedPRs].join(', #'))
- }
+ await require(process.env.GITHUB_WORKSPACE
+ + '/.github/workflows/update_build_status.js')({github, context,
core})
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]