Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(ci): lint bare cancel-in-progress on push workflows (#77717)

Raúl Negrón-Otero42dec286074f
diff --git a/.agents/skills/authoring-ci-workflows/SKILL.md b/.agents/skills/authoring-ci-workflows/SKILL.md
index 3c21d647a49e..5bdcf6e9e66d 100644
--- a/.agents/skills/authoring-ci-workflows/SKILL.md
+++ b/.agents/skills/authoring-ci-workflows/SKILL.md
@@ -75,6 +75,8 @@ concurrency:
```
- Cancel superseded **PR** runs; never cancel across **master** pushes.
+ `WF002` rejects a bare `cancel-in-progress: true` on any push-triggered workflow.
+ Where latest-wins is genuinely right (a cache warmer), say so with `# hogli-lint: allow-master-cancel -- <reason>`.
- Use `github.ref` as the fallback, never `github.run_id` — `run_id` is unique per run, so it silently gives every push its own group and dedup is lost.
- Publish-on-push workflows must not let two master pushes race `:latest` / a deploy dispatch.
Key the push arm per-SHA (see `ci-backend.yml`):
diff --git a/.github/workflows/build-phrocs.yml b/.github/workflows/build-phrocs.yml
index e4378cae8104..07c513c3943e 100644
--- a/.github/workflows/build-phrocs.yml
+++ b/.github/workflows/build-phrocs.yml
@@ -22,6 +22,8 @@ on:
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
+ # hogli-lint: allow-master-cancel -- every push deletes and recreates the one mutable
+ # phrocs-latest release, so concurrent runs would race it and the newest must win.
cancel-in-progress: true
permissions:
diff --git a/.github/workflows/ci-rust-flags-integration.yml b/.github/workflows/ci-rust-flags-integration.yml
index 3d4d1e4ad85d..d551e7c3b09f 100644
--- a/.github/workflows/ci-rust-flags-integration.yml
+++ b/.github/workflows/ci-rust-flags-integration.yml
@@ -34,7 +34,7 @@ permissions:
concurrency:
group: ${{ github.workflow }}-${{ github.head_ref || github.ref }}
- cancel-in-progress: true
+ cancel-in-progress: ${{ github.event_name == 'pull_request' }}
env:
# Django SECRET_KEY for cryptographic signing (sessions, CSRF, etc.) - test-only, not used in production
diff --git a/.github/workflows/desktop-warm-caches.yml b/.github/workflows/desktop-warm-caches.yml
index 2623af73c530..beb7e36585a5 100644
--- a/.github/workflows/desktop-warm-caches.yml
+++ b/.github/workflows/desktop-warm-caches.yml
@@ -15,6 +15,8 @@ on:
concurrency:
group: desktop-warm-caches-${{ github.ref }}
+ # hogli-lint: allow-master-cancel -- a cache warmed for the newest master commit supersedes
+ # the older run's, so cancelling that run loses nothing.
cancel-in-progress: true
jobs:
diff --git a/tools/hogli-commands/hogli_commands/tests/test_workflow_lint.py b/tools/hogli-commands/hogli_commands/tests/test_workflow_lint.py
index fb7e41492bb0..7c617304282c 100644
--- a/tools/hogli-commands/hogli_commands/tests/test_workflow_lint.py
+++ b/tools/hogli-commands/hogli_commands/tests/test_workflow_lint.py
@@ -396,6 +396,97 @@ class TestPrConcurrencyCheck:
)
assert PrConcurrencyCheck().run(_read_all(tmp_path)).issues == []
+ @pytest.mark.parametrize(
+ "name,triggers,group,cancel,flagged",
+ [
+ ("publish.yml", "[pull_request, push]", "${{ github.workflow }}-${{ github.ref }}", "true", True),
+ ("publish.yml", "[push]", "${{ github.workflow }}-${{ github.ref }}", "true", True),
+ ("publish.yml", "[pull_request]", "${{ github.workflow }}-${{ github.ref }}", "true", False),
+ (
+ "publish.yml",
+ "[pull_request, push]",
+ "${{ github.workflow }}-${{ github.ref }}",
+ "${{ github.event_name == 'pull_request' }}",
+ False,
+ ),
+ (
+ "publish.yml",
+ "[pull_request, push]",
+ "${{ github.workflow }}-${{ github.event_name == 'push' && github.sha || github.ref }}",
+ "true",
+ False,
+ ),
+ # SKIP exempts a workflow from needing a block, never from cancelling master runs.
+ (
+ next(iter(PrConcurrencyCheck.SKIP)),
+ "[push]",
+ "${{ github.workflow }}-${{ github.ref }}",
+ "true",
+ True,
+ ),
+ # A SHA on a non-push arm still leaves every push sharing one ref.
+ (
+ "publish.yml",
+ "[pull_request, push]",
+ "${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.sha || github.ref }}",
+ "true",
+ True,
+ ),
+ ("publish.yml", "[push]", "${{ github.workflow }}-${{ github.sha }}", "true", False),
+ ],
+ )
+ def test_bare_cancel_flagged_only_when_it_can_kill_a_push_run(
+ self, tmp_path: Path, name: str, triggers: str, group: str, cancel: str, flagged: bool
+ ) -> None:
+ _write(
+ tmp_path,
+ name,
+ f"""
+ name: Publish
+ on: {triggers}
+ concurrency:
+ group: {group}
+ cancel-in-progress: {cancel}
+ jobs:
+ build:
+ runs-on: ubuntu-latest
+ timeout-minutes: 5
+ steps:
+ - run: echo ok
+ """,
+ )
+ issues = PrConcurrencyCheck().run(_read_all(tmp_path)).issues
+ assert bool(issues) is flagged
+
+ @pytest.mark.parametrize(
+ "marker,exempted",
+ [
+ ("# hogli-lint: allow-master-cancel -- cache warmer, latest wins", True),
+ ("# hogli-lint: allow-master-cancel", False),
+ ("# hogli-lint: allow-master-cancel --", False),
+ ],
+ )
+ def test_master_cancel_marker_needs_a_reason_to_exempt(self, tmp_path: Path, marker: str, exempted: bool) -> None:
+ _write(
+ tmp_path,
+ "publish.yml",
+ f"""
+ name: Publish
+ on: [push]
+ concurrency:
+ group: ${{{{ github.workflow }}}}-${{{{ github.ref }}}}
+ {marker}
+ cancel-in-progress: true
+ jobs:
+ build:
+ runs-on: ubuntu-latest
+ timeout-minutes: 5
+ steps:
+ - run: echo ok
+ """,
+ )
+ assert (PrConcurrencyCheck().run(_read_all(tmp_path)).issues == []) is exempted
+
# ---------------------------------------------------------------------------
# DornyNegationCheck
diff --git a/tools/hogli-commands/hogli_commands/workflow_lint/checks/pr_concurrency.py b/tools/hogli-commands/hogli_commands/workflow_lint/checks/pr_concurrency.py
index db5748289a9f..146187b429e9 100644
--- a/tools/hogli-commands/hogli_commands/workflow_lint/checks/pr_concurrency.py
+++ b/tools/hogli-commands/hogli_commands/workflow_lint/checks/pr_concurrency.py
@@ -1,6 +1,6 @@
-"""PR-triggered ``ci-*.yml`` workflows must declare concurrency control.
+"""Workflows must declare concurrency, and cancel only the runs that are safe to cancel.
-Without it, every push to a PR branch starts a fresh run while the in-flight
+Without a block, every push to a PR branch starts a fresh run while the in-flight
one keeps burning minutes. The repo convention (used by 30+ workflows):
concurrency:
@@ -14,25 +14,35 @@ strategies (e.g. some jobs are per-SHA while others are per-branch).
Using ``github.run_id`` as the fallback looks similar but disables dedup for
push events because every run gets a unique group.
-Some workflows are intentionally exempt from cancellation (telemetry / shadow
-measurement, schedule-dominant jobs). Those are listed in ``SKIP`` below with
-a one-line reason each.
+A bare ``cancel-in-progress: true`` on a push-triggered workflow shares one
+group across every commit on the branch, so each push kills the previous
+commit's run and whatever it was proving. Gate it on the event, or key the
+push arm per-SHA when the workflow publishes on push. Its opt-out is the
+inline marker rather than ``SKIP``, so an exemption for one line sits beside
+that line.
+
+Some workflows are intentionally exempt from *requiring* a block (telemetry /
+shadow measurement, schedule-dominant jobs). Those are listed in ``SKIP``
+below with a one-line reason each.
"""
from __future__ import annotations
import re
+from pathlib import Path
from ..check import CheckResult, Issue, WorkflowCheck
from ..model import Workflow
BAD_FALLBACK = re.compile(r"head_ref\s*\|\|\s*github\.run_id")
+PER_SHA_PUSH_ARM = re.compile(r"event_name\s*==\s*['\"]push['\"]\s*&&\s*github\.sha")
+MASTER_CANCEL_MARKER = "hogli-lint: allow-master-cancel"
class PrConcurrencyCheck(WorkflowCheck):
id = "WF002-pr-concurrency"
label = "PR concurrency"
- description = "PR-triggered ci-*.yml workflows declare safe concurrency (top-level or per-job)"
+ description = "ci-*.yml PR workflows declare concurrency; no workflow cancels master runs on push"
# Workflows intentionally exempt from concurrency cancellation. Each entry has
# a one-line reason so the next reader knows why.
@@ -52,23 +62,41 @@ class PrConcurrencyCheck(WorkflowCheck):
@property
def fix_hint(self) -> str | None:
return (
- "Either add a top-level block after `on:`:\n"
+ "Missing concurrency block: add a top-level one after `on:`:\n"
"concurrency:\n"
" group: ${{ github.workflow }}-${{ github.head_ref || github.ref }}\n"
" cancel-in-progress: ${{ github.event_name == 'pull_request' }}\n"
+ "Or give every job its own `concurrency:` block. If any block would lose data\n"
+ "(telemetry, schedule-only PR triggers, etc.), add the filename to\n"
+ f"{type(self).__name__}.SKIP with a one-line reason.\n"
"\n"
- "Or add a `concurrency:` block to every job in the workflow.\n"
- "\n"
- "Do not use `github.run_id` as the fallback; it creates a unique concurrency group per push run.\n"
+ "`github.run_id` fallback: use `github.head_ref || github.ref` instead; run_id is unique\n"
+ "per run, so push runs never deduplicate.\n"
"\n"
- "Or, if cancelling stale runs would lose data (telemetry, schedule-only PR triggers, etc.),\n"
- f"add the filename to {type(self).__name__}.SKIP with a one-line reason."
+ "Bare `cancel-in-progress: true` on push: every push cancels the previous commit's run.\n"
+ "Gate it on the event as above, or key the push arm per-SHA when the workflow publishes:\n"
+ " group: ${{ github.workflow }}-${{ github.event_name == 'push' && github.sha || github.head_ref || github.ref }}\n"
+ f"Where latest-wins is right (a cache warmer), say so with `# {MASTER_CANCEL_MARKER} -- <reason>`.\n"
+ "SKIP does not exempt this rule; the marker is its opt-out."
)
def run(self, workflows: list[Workflow]) -> CheckResult:
result = CheckResult()
for wf in workflows:
group_expr = _concurrency_group_expr(wf.concurrency)
+ if _cancels_master_pushes(wf, group_expr):
+ result.issues.append(
+ Issue(
+ workflow=wf.path.name,
+ message=(
+ "`cancel-in-progress: true` on a push-triggered workflow cancels master runs; "
+ "gate it with `${{ github.event_name == 'pull_request' }}`, or key the push arm "
+ "per-SHA when the workflow publishes on push"
+ ),
+ file=str(wf.path),
+ )
+ )
+
if BAD_FALLBACK.search(group_expr):
result.issues.append(
Issue(
@@ -103,6 +131,46 @@ class PrConcurrencyCheck(WorkflowCheck):
return result
+def _cancels_master_pushes(wf: Workflow, group_expr: str) -> bool:
+ if not isinstance(wf.concurrency, dict) or wf.concurrency.get("cancel-in-progress") is not True:
+ return False
+ if not wf.is_push_triggered:
+ return False
+ if _keys_pushes_per_sha(group_expr):
+ return False
+ return not _has_master_cancel_marker(wf.path)
+
+
+def _keys_pushes_per_sha(group_expr: str) -> bool:
+ """Report whether a push event resolves the group to a per-SHA value.
+
+ Merely mentioning ``github.sha`` is not enough: when the SHA sits on some
+ other arm of a conditional, pushes still fall through to one shared ref and
+ cancel the commit before them.
+ """
+ if PER_SHA_PUSH_ARM.search(group_expr):
+ return True
+ if "&&" in group_expr or "||" in group_expr:
+ return False
+ return "github.sha" in group_expr
+
+
+def _has_master_cancel_marker(path: Path) -> bool:
+ """Report an explicit, reasoned bypass comment anywhere in the file.
+
+ PyYAML drops comments, so the parsed model decides the violation and this
+ raw scan only looks for the reviewable opt-out.
+ """
+ with open(path, encoding="utf-8") as f:
+ for line in f:
+ if MASTER_CANCEL_MARKER not in line:
+ continue
+ reason = line.partition(MASTER_CANCEL_MARKER)[2].strip()
+ if reason.startswith("--") and reason[2:].strip():
+ return True
+ return False
+
+
def _has_job_level_concurrency(wf: Workflow) -> bool:
"""Return True if at least one job in the workflow declares its own concurrency block.
diff --git a/tools/hogli-commands/hogli_commands/workflow_lint/model.py b/tools/hogli-commands/hogli_commands/workflow_lint/model.py
index df02edca3a9c..502734a7f4cc 100644
--- a/tools/hogli-commands/hogli_commands/workflow_lint/model.py
+++ b/tools/hogli-commands/hogli_commands/workflow_lint/model.py
@@ -25,6 +25,7 @@ from pathlib import Path
import yaml
PR_TRIGGERS = frozenset({"pull_request", "pull_request_target"})
+PUSH_TRIGGERS = frozenset({"push"})
class WorkflowParseError(Exception):
@@ -76,14 +77,18 @@ class Workflow:
@property
def is_pr_triggered(self) -> bool:
- return _matches_pr_trigger(self.on)
+ return _matches_trigger(self.on, PR_TRIGGERS)
+
+ @property
+ def is_push_triggered(self) -> bool:
+ return _matches_trigger(self.on, PUSH_TRIGGERS)
-def _matches_pr_trigger(triggers: object) -> bool:
+def _matches_trigger(triggers: object, wanted: frozenset[str]) -> bool:
if isinstance(triggers, str):
- return triggers in PR_TRIGGERS
+ return triggers in wanted
if isinstance(triggers, (list, dict)):
- return any(t in PR_TRIGGERS for t in triggers)
+ return any(t in wanted for t in triggers)
return False
@@ -201,6 +206,7 @@ def read_workflows(workflows_dir: Path, glob: str = "*.y*ml") -> Iterator[Workfl
__all__ = [
"Job",
"PR_TRIGGERS",
+ "PUSH_TRIGGERS",
"Step",
"Workflow",
"WorkflowParseError",