Skip to content

ci: runs of merge groups the queue dissolved are not reliably cancelled and compete with the live group for runners #4874

Open

Description

@yannickmonney

Summary

When main moves or an entry ahead leaves the queue, the queue builds new merge groups on new temporary branches and deletes the old ones. The runs of a group that no longer exists are not reliably cancelled: some end cancelled on their own, others stay queued for runners beside the live group's jobs, on a plan with about 20 concurrent jobs. A plain cancel does not clear the stuck ones, because the if: always() aggregate jobs of each workflow stay queued. The repository documents a tool that retires one run at a time. This issue collects the evidence and the options. It proposes no fix.

What the repository says

  • .github/CI.md:62-67 (## Retiring a deleted merge-group revision): "Rebuilding the merge queue gives its temporary branches new names. Workflow concurrency is keyed by the complete ref, so an old revision can keep running after GitHub deletes its branch."
  • tools/cli/scripts/ci-retire-merge-group.ts retires one run per invocation (--run <id>): read-only by default, then an ordinary cancellation with a receipt, only for a run of one of the seven validation workflows whose ref returns 404 and whose head is absent from the queue. "It does not escalate to force cancellation"; "Ordinary cancellation may leave an always() aggregate queued; the explicit finishing mode below is a separate decision" (CI.md:91-92).
  • Each workflow's concurrency group is the full ref, on purpose: "a merge-group ref … is unique, so queued runs never cancel each other or a PR run" (CI.md:991).
  • Budget: "the public repository's free plan runs about 20 jobs at once across every PR and queue run, a full merge-group run needs dozens … a queued run can wait hours for a runner" (CI.md:968).

What was observed

On 2026-10-12, while #4849 and #4853 waited in the queue (see #4873 for why the groups were rebuilt):

  • At about 14:35 UTC the repository had 64 queued and 4 in-progress workflow runs. 28 of the queued or running merge_group runs belonged to 8 groups that no longer existed (their heads were not entries of the queue): three groups of fix(platform): harden chat tools and light sandboxes after review #4849, three of fix(platform): hold up under a load burst and a database restart #4853 and two of test(cli): exempt the smoke fixture suite from the target guard #4856. The oldest, a Build run, had been queued since 13:51.
  • A job as small as Lint commits (the Commitlint workflow's only job that does work; it took 36 s on a pull request run) had been queued for 13 minutes when the live group of fix(platform): harden chat tools and light sandboxes after review #4849 was checked at 14:34.
  • A plain gh run cancel did not finish the runs. After it, run 38265555277 (Checks) showed its other jobs finished or cancelled, but Unit, the always() aggregate, was still queued, and so was the run. gh run cancel --force finished it (completed/cancelled).
  • Queued runs repository-wide went from 64 to 55 at 14:37, after a first sweep of plain cancellations (27 runs), and to 29 at about 15:00, after later sweeps with --force. Not all of that is attributable to the cancellations.
  • Each rebuild left more. Later sweeps kept finding runs of dissolved groups, between 2 and 12 per sweep, some of them runs whose earlier plain cancel had not finished.
  • Some runs are cancelled without manual action. Of the 330 merge-group runs that had settled by 14:35 UTC, before any manual cancellation, 247 succeeded, 18 failed and 65 (20%) ended cancelled. I did not establish what cancelled them. The 400 most recent runs (2026-10-11 23:22Z to 2026-10-12 14:54Z) cover 57 groups for 21 PRs.

Why it matters

A rebuild is supposed to replace a group, but the replaced group's runs keep competing for the same ~20 runner slots. The live group can wait behind work whose result nobody will read, and every direct merge to main (#4873) creates another batch of such runs. At 14:34 the live group's Commitlint run, the lightest of its seven workflows, had not started 13 minutes after it was created.

Options (not exhaustive, no preference stated)

  1. Retire in bulk. Run the existing retire command, or the sketch below, over every eligible run on a schedule (a workflow with actions: write), keeping the documented safety checks: ref returns 404, head absent from the queue.
  2. Cancel from inside the new group. When a merge-group workflow starts for a PR, cancel older runs for the same PR whose heads are no longer queue entries.
  3. Key merge-group concurrency by PR number so a PR's groups cancel each other. Trade-offs: a group can contain several PRs and its ref names only the last one; and "queued runs never cancel each other" (CI.md:991) is a deliberate property.
  4. Reduce the work per group, so a rebuild costs fewer jobs.
  5. Add runner capacity, so dissolved runs drain harmlessly.

Questions

  • Is force cancellation acceptable for a group that no longer exists? CI.md calls the finishing mode "a separate decision".
  • Who retires obsolete runs today, and how often?
  • Should retirement be part of the queue's own tooling, or stay a manual maintenance step?

Reproduce

A sketch of the check used above (needs an authenticated gh; it is a dry run unless --apply is given):

retire-dissolved-groups.py
#!/usr/bin/env python3
"""List, and with --apply force-cancel, the merge-group runs whose group no longer exists.

usage: python3 retire-dissolved-groups.py            # dry run: prints what would be cancelled
       python3 retire-dissolved-groups.py --apply

A run is eligible only when both hold:
  1. its head commit is not the head of any entry in the merge queue right now, and
  2. its temporary branch (gh-readonly-queue/main/pr-<number>-<sha>) no longer exists.
If the queue or a branch cannot be read, nothing is cancelled. --force is used because a plain cancel leaves the
`if: always()` aggregate jobs ("Unit", "CI ready (...)") queued, so the run would stay in the backlog.
"""
import json
import subprocess
import sys

REPO = 'tale-project/tale'
APPLY = '--apply' in sys.argv


def gh(*args, check=True):
    return subprocess.run(['gh', *args], capture_output=True, text=True, check=check)


def queue_heads():
    query = ('query { repository(owner:"tale-project", name:"tale") { mergeQueue(branch:"main") '
             '{ entries(first:100) { nodes { headCommit { oid } } } } } }')
    nodes = json.loads(gh('api', 'graphql', '-f', f'query={query}').stdout)['data']['repository']['mergeQueue']['entries']['nodes']
    return {node['headCommit']['oid'] for node in nodes if node['headCommit']}


def branch_is_gone(branch):
    result = gh('api', f'repos/{REPO}/git/ref/heads/{branch}', check=False)
    if result.returncode == 0:
        return False
    if '404' in result.stderr or 'Not Found' in result.stderr:
        return True
    raise RuntimeError(f'cannot tell whether {branch} exists: {result.stderr.strip()}')


heads = queue_heads()
runs = []
for status in ('queued', 'in_progress', 'waiting', 'pending'):
    out = gh('run', 'list', '--repo', REPO, '--event', 'merge_group', '--status', status, '--limit', '100',
             '--json', 'databaseId,headSha,headBranch,workflowName,createdAt').stdout
    runs += json.loads(out or '[]')

gone = {}
eligible = []
for run in runs:
    if run['headSha'] in heads:
        continue
    branch = run['headBranch']
    if branch not in gone:
        gone[branch] = branch_is_gone(branch)
    if gone[branch]:
        eligible.append(run)

print(f'{len(runs)} merge_group runs are queued or running; {len(eligible)} belong to groups that no longer exist')
for run in sorted(eligible, key=lambda r: r['createdAt']):
    print(f"  {run['createdAt'][5:16]}Z  {run['workflowName']:<10} {run['headBranch'].rsplit('/', 1)[-1][:28]}")
    if APPLY:
        gh('run', 'cancel', '--force', str(run['databaseId']), '--repo', REPO, check=False)
if eligible and not APPLY:
    print('dry run: pass --apply to cancel them')

The group statistics come from merge-group-stats.py in #4873.

Related

#4873 (how changes reach main, and what a direct merge does to the groups in the queue), #3951 (an earlier case of newer main builds starving a pinned validation).

Observed at main a83e645e27.

Activity

  1. added
    priority: medium
    needs discussion
    improvement
    on Oct 12, 2026
  2. yannickmonney commented on Oct 13, 2026

    @yannickmonney
    ContributorAuthor

    Evidence from 2026-10-13 (UTC), the same mechanics with a different harm: the live first group lost its jobs.

  3. yannickmonney commented on Nov 14, 2026

    @yannickmonney
    ContributorAuthor

    Decision

    Rule: main has no merge queue, so no dissolved merge groups exist and none need retiring. Close this issue as resolved by removing the queue. Add a guard so the queue cannot return without a plan for its dissolved groups.

    What changed since the report

    • 0da0820 made every pull request land on its own, run its full suite, and stop going through the merge queue. It deleted ci-retire-merge-group.ts and ci-merge-group-finish.ts.
    • 9548d00 (closes ci: remove the dormant merge_group triggers and the Forgejo port's train tier #5108) removed the merge_group trigger from every workflow. GitHub now reports no merge queue for main, and the required-CI ruleset only requires status checks.
    • The runs left are pull request and push runs. Their concurrency is keyed by ref with cancel-in-progress, so a new push supersedes the older run on the same ref. The exception is Build on a push to main, which deliberately keeps running. The one leftover case, an always() tail left queued after a cancel, is covered by ci-retire-tail.ts. It force-cancels a single run only after re-checking that it is obsolete, and it writes a receipt.

    Answers

    • Is force cancellation acceptable? Merge groups no longer exist, so the question no longer applies. In general, force cancellation is acceptable only for a run proven obsolete and re-checked just before the cancel, with a receipt, as ci-retire-tail.ts does. A blind sweep is not acceptable.
    • Who retires obsolete runs, and how often? Ref concurrency cancels superseded PR and main runs automatically. An operator or agent uses ci-retire-tail.ts on demand for a stuck tail. Nothing runs on a schedule.
    • Queue tooling or a manual step? There is no queue. If one ever returns, cancelling dissolved groups must ship in the same change that brings it back.

    Rationale: Removing the queue removed the cause, so every option listed here would be code for an event that never fires. A scheduled force-cancel job with actions: write would be a privileged component with nothing to do. A guard test is cheap. Without it, turning the queue back on would quietly bring back the runner starvation and the cancelled live groups recorded here.

    Implementation units

    1. ci: guard against a merge_group trigger returning without retirement (S, main). Add a test that every workflow has no merge_group trigger. Its failure message points to a new CI.md paragraph stating the rule above.
    2. Close this issue once unit 1 lands, citing 0da0820, 9548d00 and the guard commit. Cross-link Decision: how changes should land on main — the merge queue, direct merges, or a defined mix? (83 of 123 merges since 10 Oct skipped the queue) #4873.
  4. added
    agent-ready
    and removed
    needs discussion
    on Nov 14, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    agent-readyimprovementpriority: medium

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions