Skip to content

fix cancelled run handling in workflow prefetcher#38579

Open
aIbrahiim wants to merge 1 commit into
apache:masterfrom
aIbrahiim:fix/cancelled-flaky-workflows
Open

fix cancelled run handling in workflow prefetcher#38579
aIbrahiim wants to merge 1 commit into
apache:masterfrom
aIbrahiim:fix/cancelled-flaky-workflows

Conversation

@aIbrahiim
Copy link
Copy Markdown
Contributor

@aIbrahiim aIbrahiim commented May 21, 2026

This change updates how cancelled workflow runs are counted for flaky test detection. Pull request runs that end as cancelled are ignored and for scheduled runs that are cancelled, we count them as failed if they ran for more than one hour or if they have no jobs. Short cancelled scheduled runs that still have jobs are ignored and for short cancelled schedule runs we call the GitHub jobs API only when we need to check if there are zero jobs


Thank you for your contribution! Follow this checklist to help us incorporate your contribution quickly and easily:

  • Mention the appropriate issue in your description (for example: addresses #123), if applicable. This will automatically add a link to the pull request in the issue. If you would like the issue to automatically close on merging the pull request, comment fixes #<ISSUE NUMBER> instead.
  • Update CHANGES.md with noteworthy changes.
  • If this contribution is large, please file an Apache Individual Contributor License Agreement.

See the Contributor Guide for more tips on how to make review process smoother.

To check the build health, please visit https://github.com/apache/beam/blob/master/.test-infra/BUILD_STATUS.md

GitHub Actions Tests Status (on master branch)

Build python source distribution and wheels
Python tests
Java tests
Go tests

See CI.md for more information about GitHub Actions CI or the workflows README to see a list of phrases to trigger workflows.

@github-actions github-actions Bot added the infra label May 21, 2026
@aIbrahiim aIbrahiim marked this pull request as ready for review May 21, 2026 08:28
@gemini-code-assist
Copy link
Copy Markdown
Contributor

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request refines the logic for detecting flaky tests by improving how cancelled workflow runs are processed. By introducing more granular handling for cancelled scheduled runs and integrating additional job count data, the system can more accurately identify genuine failures versus transient cancellations, thereby reducing noise in flakiness metrics.

Highlights

  • Cancelled Run Handling: Updated the workflow prefetcher to better handle cancelled runs by distinguishing between pull request and scheduled events.
  • Flaky Test Detection Logic: Cancelled scheduled runs are now treated as failures if they exceed a one-hour duration or have zero jobs, while short cancelled runs with jobs are ignored.
  • API Enrichment: Added logic to asynchronously fetch job counts for cancelled scheduled runs to improve the accuracy of flakiness reporting.
New Features

🧠 You can now enable Memory (public preview) to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize the Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counterproductive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Copy Markdown
Contributor

@gemini-code-assist gemini-code-assist Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces logic to refine flakiness metrics by treating certain cancelled GitHub workflow runs as failures, specifically those that are scheduled and either exceed a one-hour duration or have zero jobs. It adds asynchronous API calls to fetch job counts and updates the data models to support this. Feedback focuses on optimizing performance and resource management, including reusing a single aiohttp.ClientSession for batch requests, adding a giveup condition to the retry logic for non-recoverable errors, and reordering operations to slice the run list before performing API-intensive enrichment.

Comment on lines +206 to +220
async def enrich_cancelled_schedule_run_jobs(workflows, semaphore, headers):
tasks = []
for workflow in workflows:
for run in workflow.runs:
if run.event != "schedule" or run.status != "cancelled":
continue
if run_duration(run.started_at, run.updated_at) > CANCELLED_FAILURE_MIN_DURATION:
continue
jobs_url = (
f"https://api.github.com/repos/{GIT_ORG}/beam/actions/runs/{run.id}/jobs"
)
tasks.append(fetch_jobs_count(jobs_url, run, semaphore, headers))

if tasks:
await asyncio.gather(*tasks)
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Creating a new aiohttp.ClientSession for every request is inefficient and can lead to resource exhaustion. It is recommended to create a single session and reuse it for all requests in the batch. Additionally, consider passing this session to fetch_jobs_count.

Suggested change
async def enrich_cancelled_schedule_run_jobs(workflows, semaphore, headers):
tasks = []
for workflow in workflows:
for run in workflow.runs:
if run.event != "schedule" or run.status != "cancelled":
continue
if run_duration(run.started_at, run.updated_at) > CANCELLED_FAILURE_MIN_DURATION:
continue
jobs_url = (
f"https://api.github.com/repos/{GIT_ORG}/beam/actions/runs/{run.id}/jobs"
)
tasks.append(fetch_jobs_count(jobs_url, run, semaphore, headers))
if tasks:
await asyncio.gather(*tasks)
async def enrich_cancelled_schedule_run_jobs(workflows, semaphore, headers):
tasks = []
async with aiohttp.ClientSession() as session:
for workflow in workflows:
for run in workflow.runs:
if run.event != "schedule" or run.status != "cancelled":
continue
if run_duration(run.started_at, run.updated_at) > CANCELLED_FAILURE_MIN_DURATION:
continue
jobs_url = (
f"https://api.github.com/repos/{GIT_ORG}/beam/actions/runs/{run.id}/jobs"
)
tasks.append(fetch_jobs_count(session, jobs_url, run, semaphore, headers))
if tasks:
await asyncio.gather(*tasks)

Comment on lines +223 to +241
@backoff.on_exception(backoff.constant, aiohttp.ClientResponseError, max_tries=5)
async def fetch_jobs_count(url, run, semaphore, headers):
async with semaphore:
async with aiohttp.ClientSession() as session:
async with session.get(url, headers=headers) as response:
if response.status == 200:
result = await response.json()
run.jobs_count = result.get("total_count", 0)
return
if response.status == 403:
print(f"Retry for: {url}")
headers["Authorization"] = get_token()
raise aiohttp.ClientResponseError(
response.request_info,
response.history,
status=response.status,
message=response.reason,
headers=response.headers,
)
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The backoff decorator should include a giveup condition to avoid retrying on non-recoverable errors like 404 (Not Found). Also, the function signature should be updated to accept a shared session to avoid creating one per request.

@backoff.on_exception(
    backoff.constant,
    aiohttp.ClientResponseError,
    max_tries=5,
    giveup=lambda e: e.status not in [403, 429, 500, 502, 503, 504]
)
async def fetch_jobs_count(session, url, run, semaphore, headers):
    async with semaphore:
        async with session.get(url, headers=headers) as response:
            if response.status == 200:
                result = await response.json()
                run.jobs_count = result.get("total_count", 0)
                return
            if response.status == 403:
                print(f"Retry for: {url}")
                headers["Authorization"] = get_token()
            raise aiohttp.ClientResponseError(
                response.request_info,
                response.history,
                status=response.status,
                message=response.reason,
                headers=response.headers,
            )

Comment on lines +531 to +537
workflows_list = list(workflows.values())
await enrich_cancelled_schedule_run_jobs(workflows_list, semaphore, headers)
for workflow in workflows_list:
runs = sorted(workflow.runs, key=lambda r: r.started_at, reverse=True)
workflow.runs = runs[: int(GH_NUMBER_OF_WORKFLOW_RUNS_TO_FETCH)]
workflow.runs = prepare_workflow_runs_for_flakiness(
runs[: int(GH_NUMBER_OF_WORKFLOW_RUNS_TO_FETCH)]
)
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

It is more efficient to sort and slice the workflow runs before calling enrich_cancelled_schedule_run_jobs. This avoids making unnecessary API calls to fetch job counts for runs that will eventually be discarded by the slice.

    workflows_list = list(workflows.values())
    for workflow in workflows_list:
        workflow.runs = sorted(workflow.runs, key=lambda r: r.started_at, reverse=True)[: int(GH_NUMBER_OF_WORKFLOW_RUNS_TO_FETCH)]
    await enrich_cancelled_schedule_run_jobs(workflows_list, semaphore, headers)
    for workflow in workflows_list:
        workflow.runs = prepare_workflow_runs_for_flakiness(workflow.runs)

@github-actions
Copy link
Copy Markdown
Contributor

Assigning reviewers:

R: @chamikaramj added as fallback since no labels match configuration

Note: If you would like to opt out of this review, comment assign to next reviewer.

Available commands:

  • stop reviewer notifications - opt out of the automated review tooling
  • remind me after tests pass - tag the comment author after tests pass
  • waiting on author - shift the attention set back to the author (any comment or push by the author will return the attention set to the reviewers)

The PR bot will only process comments in the main thread (not review comments).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant