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.

chore(ci): report cancelled, not failure, on superseded required gates (#92226)

Paul D'Ambrabeecbd8604cc
diff --git a/.agents/skills/authoring-ci-workflows/SKILL.md b/.agents/skills/authoring-ci-workflows/SKILL.md
index 1092dfa7cc8e..a7cdb877a501 100644
--- a/.agents/skills/authoring-ci-workflows/SKILL.md
+++ b/.agents/skills/authoring-ci-workflows/SKILL.md
@@ -98,18 +98,42 @@ concurrency:
The "gate" is the collate job that emits the required status check by reading `needs.*.result`.
By convention its display name ends in `Pass` (`Django Tests Pass`, `Visual regression tests pass`), but `WF007` also finds gates structurally when a step reads `needs.<dep>.result`, because the convention is not universally followed.
A job that inspects results without gating anything opts out with `# hogli-lint: not-a-required-gate — <reason>` above the job key.
-Gates and the workers they inspect need **opposite** conditions:
+Gates and the workers they inspect share the **same** condition:
-| Job | Condition | Why |
-| ------- | ------------------ | ----------------------------------------------------------------------------- |
-| Gate | `if: always()` | It must run and emit an explicit verdict, even when everything upstream died. |
-| Workers | `if: !cancelled()` | So a superseded run actually stops instead of holding the concurrency slot. |
+| Job | Condition | Why |
+| ------- | ------------------------- | ------------------------------------------------------------------------------------------------------------- |
+| Gate | `if: ${{ !cancelled() }}` | It emits an explicit verdict on every completed run, and a superseded run records `cancelled`, not `failure`. |
+| Workers | `if: !cancelled()` | So a superseded run actually stops instead of holding the concurrency slot. |
-The gate condition must be exactly `always()`, with optional `${{ }}` wrapping.
-Adding another predicate can skip the required check, so `always() && <condition>` is rejected.
+The gate condition must contain `!cancelled()`, with optional `${{ }}` wrapping.
+`always()` is rejected: it is identical to `!cancelled()` on any run that is not cancelled, but on a superseded run it runs the gate after the cancel and reports `failure`, which inflates every CI failure-rate metric with runs a developer merely pushed over.
-`!cancelled()` is identical to `always()` on any run that is not cancelled, so failure-path reporting still works; only cancelled runs skip.
-Measured on a live superseded run ([evidence](https://github.com/PostHog/posthog/actions/runs/29765284128)): an `always()` worker dispatched and ran to completion _after_ the cancel, while the `!cancelled()` worker never started and reported `cancelled` (not `skipped`), so the gate still fails closed.
+**Extra predicates may only be OR-ed on, never AND-ed.**
+This is a correctness rule, not a style one.
+A conjunction gives the gate a second way to be false, and a job skipped by its own condition records `skipped`, which branch protection reads as a pass.
+Both conclusions occur in the same cancelled run: in [run 33496887370](https://github.com/PostHog/posthog/actions/runs/33496887370) `Calculate running time` recorded `cancelled` while `Backend coverage report` recorded `skipped`, because an AND-ed predicate of its own was already false.
+A disjunction cannot be false while `!cancelled()` is true, so cancellation stays the gate's one false predicate and the conclusion stays `cancelled`.
+
+Cancellation still fails closed.
+A gate on `!cancelled()` that never starts records conclusion `cancelled`, never `skipped`.
+Measured on a superseded run ([evidence](https://github.com/PostHog/posthog/actions/runs/33513529762)): the gate recorded `cancelled` with zero steps, while the `always()` control ran after the cancel and recorded `failure`.
+GitHub's [status checks reference](https://docs.github.com/en/pull-requests/reference/status-checks) lists `success`/`neutral`/`skipped` as passing and never places `cancelled` among them, and a commit whose only checks are cancelled rolls up to `FAILURE` ([evidence](https://github.com/PostHog/posthog/actions/runs/33513732017)).
+That is inference rather than a documented guarantee, which is the reason for the next rule.
+
+**A workflow that cancels its own run must OR that signal onto its gate.**
+`ci-backend` cancels itself when repo checks or OpenAPI types fail deterministically, to stop paying for runners on a failure a retry cannot fix.
+Under a bare `!cancelled()` those real failures would report `cancelled` too, which both hides them from the failure-rate metric and rests merge safety on the inference above.
+OR-ing the deterministic-failure output back on keeps the honest verdict, because the disjunct is true, so the gate dispatches despite the cancel:
+
+```yaml
+if: >
+ !cancelled()
+ || needs.repo-checks.outputs.deterministic_failure == 'true'
+ || needs.check-openapi-types.outputs.deterministic_failure == 'true'
+```
+
+Measured on a self-cancelled run ([evidence](https://github.com/PostHog/posthog/actions/runs/33513529687)): the bare `!cancelled()` gate recorded `cancelled`, the OR-ed gate ran and recorded `failure`.
+Only superseded runs then report `cancelled`, and every real failure keeps a `failure` conclusion.
Four rules for the gate body:
@@ -126,7 +150,7 @@ Four rules for the gate body:
Comparisons in another step, comments, logs, or branches that do not exit nonzero prove nothing and are rejected.
A result whose guard `WF007` cannot follow is reported rather than assumed safe, so an unusual routing may need the checks moved inline.
-`WF007` enforces 1, 4, and the `always()` condition, and it takes the dependency list from `needs:` as well as the step body, so a job you wired into `needs:` and then forgot to test is reported rather than silently trusted.
+`WF007` enforces 1, 4, and the `!cancelled()` condition, and it takes the dependency list from `needs:` as well as the step body, so a job you wired into `needs:` and then forgot to test is reported rather than silently trusted.
The half of rule 2 it cannot check is whether you named the right jobs in `needs:` to begin with: "reporting job" and "coverage job" look identical to a linter, so that one is on you and the reviewer.
## Checkout / clone — sparse first, then shallow
diff --git a/.depot/workflows/ci-backend.yml b/.depot/workflows/ci-backend.yml
index 989daa27d551..cde928441cfc 100644
--- a/.depot/workflows/ci-backend.yml
+++ b/.depot/workflows/ci-backend.yml
@@ -64,6 +64,13 @@
# strips artifact uploads (above), so those changes are depot-exempt.
# - OpenAPI types: validation remains a separate job like canonical, but its
# auto-commit side effect is dropped
+# - Deterministic-failure self-cancel: canonical cancels its own run when repo-checks or
+# check-openapi-types fails deterministically, and ORs those jobs' deterministic_failure
+# outputs onto the gate condition so a real failure still reports failure rather than
+# cancelled. The shadow has neither the cancelling jobs nor those outputs, so the
+# disjuncts are depot-exempt. The gate keeps its sampling `&&` for the same reason
+# canonical may not use one: an `&&` can skip the gate, and only here is that harmless,
+# because this status never blocks a merge.
# - events_json variants: gated on the test-new-events-schema label only; canonical also
# doubles the matrices on workflow_dispatch, but shadow dispatches stay legacy-only so
# trial runs do the same work as sampled PR runs
@@ -2547,9 +2554,10 @@ jobs:
name: '[optional, does not block merge] Django Tests Pass'
runs-on: depot-ubuntu-24.04
timeout-minutes: 5
- # always() collates skipped/failed matrix jobs; gated on the sampling result so it
- # doesn't spin up a lone runner when this run was sampled out (or the shadow is off).
- if: always() && needs.sample.outputs.sampled == 'true'
+ # !cancelled() collates skipped/failed matrix jobs without reporting failure on a
+ # superseded run (mirrors canonical); gated on the sampling result so it doesn't
+ # spin up a lone runner when this run was sampled out (or the shadow is off).
+ if: ${{ !cancelled() && needs.sample.outputs.sampled == 'true' }}
steps:
- name: Summarize dependency results
run: |
diff --git a/.github/workflows/cd-sandbox-base-image.yml b/.github/workflows/cd-sandbox-base-image.yml
index 30f00d7f1c8c..0338ac97440b 100644
--- a/.github/workflows/cd-sandbox-base-image.yml
+++ b/.github/workflows/cd-sandbox-base-image.yml
@@ -438,7 +438,7 @@ jobs:
name: Sandbox Base Image Pass
runs-on: ubuntu-latest
timeout-minutes: 5
- if: always()
+ if: ${{ !cancelled() }}
permissions: {}
steps:
- name: Check all sandbox image jobs
diff --git a/.github/workflows/ci-agent-proxy.yml b/.github/workflows/ci-agent-proxy.yml
index d7f5cf82b693..66b812c5e29d 100644
--- a/.github/workflows/ci-agent-proxy.yml
+++ b/.github/workflows/ci-agent-proxy.yml
@@ -111,11 +111,11 @@ jobs:
name: Agent Proxy CI Pass
runs-on: ubuntu-latest
timeout-minutes: 5
- # always(), not !cancelled(): a skipped required check is treated as a pass by
- # branch protection, so on cancellation the gate must run and emit an explicit
- # result rather than skip into a green. A cancelled or timed-out job is caught
- # by the != success && != skipped checks below; a legitimate no-change skip passes.
- if: always()
+ # !cancelled(): a superseded run records cancelled (which branch protection
+ # does not treat as a pass) instead of running on to report failure. A cancelled
+ # or timed-out dependency on a live run is still caught by the != success &&
+ # != skipped checks below; a legitimate no-change skip passes.
+ if: ${{ !cancelled() }}
steps:
- name: Check outcomes
run: |
diff --git a/.github/workflows/ci-backend.yml b/.github/workflows/ci-backend.yml
index 9c404b123e90..347fb5ff6e40 100644
--- a/.github/workflows/ci-backend.yml
+++ b/.github/workflows/ci-backend.yml
@@ -3823,9 +3823,15 @@ jobs:
runs-on: ubuntu-latest
# Headroom for downloading every shard's JUnit for the failure rollup.
timeout-minutes: 8
- # Intentional always(): this required gate must inspect failed and cancelled
- # dependencies and fail closed.
- if: always()
+ # Intentional !cancelled(): the gate inspects failed dependencies and fails
+ # closed on live runs; a superseded run records cancelled, not failure.
+ # The deterministic-failure disjuncts cover this workflow cancelling its
+ # own run: without them a real repo or OpenAPI failure would report
+ # cancelled too, and the failure-rate metric would lose it.
+ if: >
+ !cancelled()
+ || needs.repo-checks.outputs.deterministic_failure == 'true'
+ || needs.check-openapi-types.outputs.deterministic_failure == 'true'
steps:
- name: Summarize dependency results
run: |
diff --git a/.github/workflows/ci-dagster.yml b/.github/workflows/ci-dagster.yml
index c65f63fe0222..00cd7faf07c5 100644
--- a/.github/workflows/ci-dagster.yml
+++ b/.github/workflows/ci-dagster.yml
@@ -734,7 +734,7 @@ jobs:
name: Dagster Tests Pass
runs-on: ubuntu-latest
timeout-minutes: 5
- if: always()
+ if: ${{ !cancelled() }}
steps:
- name: Check matrix outcome
run: |
diff --git a/.github/workflows/ci-e2e-playwright.yml b/.github/workflows/ci-e2e-playwright.yml
index 51947a38c773..58e03447ba3d 100644
--- a/.github/workflows/ci-e2e-playwright.yml
+++ b/.github/workflows/ci-e2e-playwright.yml
@@ -1301,7 +1301,7 @@ jobs:
name: Playwright tests pass
runs-on: ubuntu-latest
timeout-minutes: 5
- if: always()
+ if: ${{ !cancelled() }}
steps:
- name: Check outcome
run: |
diff --git a/.github/workflows/ci-frontend.yml b/.github/workflows/ci-frontend.yml
index 6d2f70a7b672..edeb1f7eec9a 100644
--- a/.github/workflows/ci-frontend.yml
+++ b/.github/workflows/ci-frontend.yml
@@ -1209,7 +1209,7 @@ jobs:
name: Frontend Tests Pass
runs-on: ubuntu-latest
timeout-minutes: 5
- if: always()
+ if: ${{ !cancelled() }}
steps:
- run: exit 0
- name: Check outcomes
diff --git a/.github/workflows/ci-llm-gateway.yml b/.github/workflows/ci-llm-gateway.yml
index 9e11539d5af2..3ca9b8113004 100644
--- a/.github/workflows/ci-llm-gateway.yml
+++ b/.github/workflows/ci-llm-gateway.yml
@@ -104,11 +104,11 @@ jobs:
name: LLM Services Tests Pass
runs-on: ubuntu-latest
timeout-minutes: 5
- # always(), not !cancelled(): a skipped required check is treated as a pass by
- # branch protection, so on cancellation the gate must run and emit an explicit
- # result rather than skip into a green. A cancelled or timed-out job is caught
- # by the != success && != skipped checks below; a legitimate no-change skip passes.
- if: always()
+ # !cancelled(): a superseded run records cancelled (which branch protection
+ # does not treat as a pass) instead of running on to report failure. A cancelled
+ # or timed-out dependency on a live run is still caught by the != success &&
+ # != skipped checks below; a legitimate no-change skip passes.
+ if: ${{ !cancelled() }}
steps:
- name: Check outcomes
run: |
diff --git a/.github/workflows/ci-mcp-ui-apps.yml b/.github/workflows/ci-mcp-ui-apps.yml
index 1b02dcc8ea88..5bad38189d11 100644
--- a/.github/workflows/ci-mcp-ui-apps.yml
+++ b/.github/workflows/ci-mcp-ui-apps.yml
@@ -153,7 +153,7 @@ jobs:
name: MCP UI Apps CI
runs-on: ubuntu-latest
timeout-minutes: 5
- if: always()
+ if: ${{ !cancelled() }}
steps:
- name: Check results
run: |
diff --git a/.github/workflows/ci-mcp.yml b/.github/workflows/ci-mcp.yml
index 602690fd7273..537a5ba1c562 100644
--- a/.github/workflows/ci-mcp.yml
+++ b/.github/workflows/ci-mcp.yml
@@ -861,7 +861,7 @@ jobs:
name: MCP Tests Pass
runs-on: ubuntu-latest
timeout-minutes: 5
- if: always()
+ if: ${{ !cancelled() }}
steps:
- name: Check all MCP jobs
run: |
diff --git a/.github/workflows/ci-nodejs.yml b/.github/workflows/ci-nodejs.yml
index b1a9e1f562b3..3c36df209ff8 100644
--- a/.github/workflows/ci-nodejs.yml
+++ b/.github/workflows/ci-nodejs.yml
@@ -1039,7 +1039,7 @@ jobs:
name: Node.js Tests Pass
runs-on: ubuntu-latest
timeout-minutes: 5
- if: always()
+ if: ${{ !cancelled() }}
steps:
- run: exit 0
- name: Check outcomes
diff --git a/.github/workflows/ci-oauth-proxy.yml b/.github/workflows/ci-oauth-proxy.yml
index d66cc969a310..55dcaaede4a2 100644
--- a/.github/workflows/ci-oauth-proxy.yml
+++ b/.github/workflows/ci-oauth-proxy.yml
@@ -71,7 +71,7 @@ jobs:
name: OAuth Proxy Tests Pass
runs-on: ubuntu-latest
timeout-minutes: 5
- if: always()
+ if: ${{ !cancelled() }}
steps:
- name: Check all oauth-proxy jobs
run: |
diff --git a/.github/workflows/ci-proto.yml b/.github/workflows/ci-proto.yml
index 8bc668d1d002..5ef5a9738027 100644
--- a/.github/workflows/ci-proto.yml
+++ b/.github/workflows/ci-proto.yml
@@ -184,7 +184,7 @@ jobs:
name: Proto Checks Pass
runs-on: ubuntu-latest
timeout-minutes: 5
- if: always()
+ if: ${{ !cancelled() }}
steps:
- name: Check all proto jobs
run: |
diff --git a/.github/workflows/ci-python.yml b/.github/workflows/ci-python.yml
index ef05b18aa6a6..74159e686cb3 100644
--- a/.github/workflows/ci-python.yml
+++ b/.github/workflows/ci-python.yml
@@ -408,7 +408,7 @@ jobs:
name: Python code quality checks
runs-on: ubuntu-latest
timeout-minutes: 5
- if: always()
+ if: ${{ !cancelled() }}
steps:
- name: Check Python CI status
run: |
diff --git a/.github/workflows/ci-rust.yml b/.github/workflows/ci-rust.yml
index bddfa290f25f..13748a873c6d 100644
--- a/.github/workflows/ci-rust.yml
+++ b/.github/workflows/ci-rust.yml
@@ -904,7 +904,7 @@ jobs:
name: Rust Tests Pass
runs-on: ubuntu-latest
timeout-minutes: 5
- if: always()
+ if: ${{ !cancelled() }}
permissions: {}
steps:
- name: Check all Rust jobs
diff --git a/.github/workflows/ci-security.yaml b/.github/workflows/ci-security.yaml
index fa7e9e61ad2b..066ff2ac979c 100644
--- a/.github/workflows/ci-security.yaml
+++ b/.github/workflows/ci-security.yaml
@@ -561,7 +561,7 @@ jobs:
name: Semgrep Checks Pass
runs-on: ubuntu-latest
timeout-minutes: 5
- if: always()
+ if: ${{ !cancelled() }}
steps:
- name: Check matrix outcome
run: |
diff --git a/.github/workflows/ci-storybook.yml b/.github/workflows/ci-storybook.yml
index 5af3c1f8ef6f..f35acc0162ed 100644
--- a/.github/workflows/ci-storybook.yml
+++ b/.github/workflows/ci-storybook.yml
@@ -769,7 +769,7 @@ jobs:
name: Visual regression tests pass
runs-on: ubuntu-latest
timeout-minutes: 5
- if: always()
+ if: ${{ !cancelled() }}
steps:
- name: Check matrix outcome
run: |
diff --git a/.github/workflows/desktop-build.yml b/.github/workflows/desktop-build.yml
index 188d84af2558..4a8fb0778354 100644
--- a/.github/workflows/desktop-build.yml
+++ b/.github/workflows/desktop-build.yml
@@ -126,7 +126,7 @@ jobs:
name: Desktop Build Pass
runs-on: depot-ubuntu-24.04
timeout-minutes: 5
- if: always()
+ if: ${{ !cancelled() }}
steps:
- name: Check results
run: |
diff --git a/.github/workflows/desktop-ci.yml b/.github/workflows/desktop-ci.yml
index fe20eb20e8bd..181746f75731 100644
--- a/.github/workflows/desktop-ci.yml
+++ b/.github/workflows/desktop-ci.yml
@@ -94,7 +94,7 @@ jobs:
tests-pass:
name: Desktop Tests Pass
needs: [build, quality, typecheck, test, backend-coupling]
- if: always()
+ if: ${{ !cancelled() }}
runs-on: depot-ubuntu-24.04
timeout-minutes: 5
steps:
diff --git a/.github/workflows/desktop-quality.yml b/.github/workflows/desktop-quality.yml
index d50a318a8c91..59b30efbc939 100644
--- a/.github/workflows/desktop-quality.yml
+++ b/.github/workflows/desktop-quality.yml
@@ -103,7 +103,7 @@ jobs:
name: Desktop Quality Pass
runs-on: depot-ubuntu-24.04
timeout-minutes: 5
- if: always()
+ if: ${{ !cancelled() }}
steps:
- name: Check results
run: |
diff --git a/.github/workflows/desktop-test.yml b/.github/workflows/desktop-test.yml
index 23343a6f8eab..2869a0c2bed3 100644
--- a/.github/workflows/desktop-test.yml
+++ b/.github/workflows/desktop-test.yml
@@ -346,7 +346,7 @@ jobs:
name: Desktop Tests Pass
runs-on: depot-ubuntu-24.04
timeout-minutes: 5
- if: always()
+ if: ${{ !cancelled() }}
steps:
- name: Check results
run: |
diff --git a/.github/workflows/desktop-typecheck.yml b/.github/workflows/desktop-typecheck.yml
index e77264a5c318..9a805772be39 100644
--- a/.github/workflows/desktop-typecheck.yml
+++ b/.github/workflows/desktop-typecheck.yml
@@ -123,7 +123,7 @@ jobs:
name: Desktop Typecheck Pass
runs-on: depot-ubuntu-24.04
timeout-minutes: 5
- if: always()
+ if: ${{ !cancelled() }}
steps:
- name: Check results
run: |
diff --git a/AGENTS.md b/AGENTS.md
index bd0299c683f0..bbc8fa6a13d5 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -101,7 +101,7 @@ git commit --allow-empty -m "chore(ci): run the full matrix" && git push
Do not add `labeled`/`unlabeled` back to a merge gate's `on.pull_request.types` to avoid that push.
GitHub cannot filter a label trigger by name, so every unrelated label re-runs the full matrices against a commit CI has already covered.
-Guarding it inside the workflow is worse: skipping the gate job cascades to the `if: always()` aggregator, which counts a skipped dependency as success and posts a green required check with no tests behind it.
+Guarding it inside the workflow is worse: skipping the gate job cascades to the `if: !cancelled()` aggregator, which counts a skipped dependency as success and posts a green required check with no tests behind it.
#### Stacked PRs
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 1836b79fa65e..9b1f93b66179 100644
--- a/tools/hogli-commands/hogli_commands/tests/test_workflow_lint.py
+++ b/tools/hogli-commands/hogli_commands/tests/test_workflow_lint.py
@@ -1195,7 +1195,9 @@ class TestCli:
# The shape these fixtures guard against: a `changes` detector cleared with a bare
# `== "failure"`, then its outputs read to decide "nothing to test". Those outputs
# are empty on a cancelled job, so the gate exits 0 green with no tests run.
-def _gate(body: str, condition: str = "always()") -> str:
+def _gate(body: str, condition: str | None = "${{ !cancelled() }}", step_condition: str | None = None) -> str:
+ step_if = f"if: {step_condition}\n " if step_condition is not None else ""
+ job_if = f" if: {condition}\n" if condition is not None else ""
return f"""
name: ci-thing
on: pull_request
@@ -1212,9 +1214,8 @@ def _gate(body: str, condition: str = "always()") -> str:
name: Thing Tests Pass
needs: [changes, build]
timeout-minutes: 5
- if: {condition}
- steps:
- - run: |
+{job_if} steps:
+ - {step_if}run: |
{textwrap.indent(textwrap.dedent(body).strip(), " " * 14)}
"""
@@ -1350,7 +1351,7 @@ ENV_LOOP_GATE = """
name: Thing Tests Pass
needs: [build]
timeout-minutes: 5
- if: always()
+ if: ${{ !cancelled() }}
steps:
- name: Check outcomes
env:
@@ -1376,7 +1377,7 @@ CROSS_STEP_ENV_GATE = """
name: Thing Tests Pass
needs: [build]
timeout-minutes: 5
- if: always()
+ if: ${{ !cancelled() }}
steps:
- name: Log outcome
env:
@@ -1393,7 +1394,7 @@ CROSS_STEP_ENV_GATE = """
# A gate whose display name doesn't end in "Pass", so only structural detection finds it.
-def _off_convention_gate(marker: str = "", condition: str = "always()") -> str:
+def _off_convention_gate(marker: str = "", condition: str = "${{ !cancelled() }}") -> str:
yaml_ = _gate(MIXED_BODY, condition=condition).replace("Thing Tests Pass", "Thing decision")
if marker:
yaml_ = yaml_.replace(" thing_tests:", f" # {marker}\n thing_tests:")
@@ -1423,21 +1424,33 @@ class TestRequiredGateCheck:
"content",
[
_gate(SAFE_BODY),
- _gate(SAFE_BODY, condition="${{ always() }}"),
+ _gate(SAFE_BODY, condition='"!cancelled()"'),
+ _gate(SAFE_BODY, step_condition="always()"),
_gate(HELPER_BODY),
_gate(LOCAL_ALIAS_HELPER_BODY),
_gate(COMMENTED_CALL_BODY),
_gate(PAREN_LABEL_CALL_BODY),
ENV_LOOP_GATE,
+ _gate(SAFE_BODY, step_condition="${{ !cancelled() }}"),
+ _gate(SAFE_BODY, condition="${{ !cancelled() || needs.build.outputs.deterministic_failure == 'true' }}"),
+ _gate(
+ SAFE_BODY,
+ condition="${{ !cancelled() || needs.build.outputs.deterministic_failure == 'true' }}",
+ step_condition="always()",
+ ),
],
ids=[
"inline-allowlist",
- "wrapped-always",
+ "quoted-bare-not-cancelled",
+ "guards-in-step-level-always",
"shared-helper",
"helper-via-local",
"helper-call-with-trailing-comment",
"helper-call-with-parens-in-label",
"env-block-loop",
+ "step-level-not-cancelled",
+ "not-cancelled-or-deterministic-failure",
+ "always-step-in-or-widened-gate",
],
)
def test_passes_when_every_dependency_is_allowlisted(self, tmp_path: Path, content: str) -> None:
@@ -1456,28 +1469,36 @@ class TestRequiredGateCheck:
issues = RequiredGateCheck().run(_read_all(tmp_path)).issues
assert sorted(i.message.split("'")[1] for i in issues) == expected_deps
+ # A gate with no condition defaults to success(), so it disappears the moment a
+ # dependency fails — the fail-open this rule exists to stop.
@pytest.mark.parametrize(
"condition",
- ["${{ !cancelled() }}", "${{ always() && false }}", "${{ !always() }}"],
- ids=["cancelled-condition", "conditional-always", "negated-always"],
+ ["always()", "${{ !cancelled() && false }}", "${{ cancelled() }}", None],
+ ids=["bare-always", "conditional-not-cancelled", "unnegated-cancelled", "no-condition"],
)
- def test_flags_gate_that_can_skip_itself(self, tmp_path: Path, condition: str) -> None:
+ def test_flags_gate_condition_other_than_not_cancelled(self, tmp_path: Path, condition: str | None) -> None:
_write(tmp_path, "ci-thing.yml", _gate(SAFE_BODY, condition=condition))
issues = RequiredGateCheck().run(_read_all(tmp_path)).issues
assert len(issues) == 1
- assert "always()" in issues[0].message
+ assert "!cancelled()" in issues[0].message
# Every fixture can exit zero for a cancelled dependency despite mentioning
# the expected statuses or guard shape.
@pytest.mark.parametrize(
- "body",
+ "content",
[
- UNSAFE_HELPER_BODY,
- DECOY_COMMENT_BODY,
- DECOY_ECHO_BODY,
- NON_FAILING_ALLOWLIST_BODY,
- INVERTED_ALLOWLIST_BODY,
- LOGGED_ONLY_BODY,
+ _gate(UNSAFE_HELPER_BODY),
+ _gate(DECOY_COMMENT_BODY),
+ _gate(DECOY_ECHO_BODY),
+ _gate(NON_FAILING_ALLOWLIST_BODY),
+ _gate(INVERTED_ALLOWLIST_BODY),
+ _gate(LOGGED_ONLY_BODY),
+ _gate(SAFE_BODY, step_condition="${{ always() && false }}"),
+ _gate(
+ SAFE_BODY,
+ condition="${{ !cancelled() || needs.build.outputs.deterministic_failure == 'true' }}",
+ step_condition="${{ !cancelled() }}",
+ ),
],
ids=[
"failure-only-helper",
@@ -1486,10 +1507,12 @@ class TestRequiredGateCheck:
"non-failing-allowlist",
"inverted-allowlist",
"results-only-logged",
+ "guards-in-conditional-step",
+ "not-cancelled-step-in-or-widened-gate",
],
)
- def test_flags_gate_whose_results_reach_no_fail_closed_guard(self, tmp_path: Path, body: str) -> None:
- _write(tmp_path, "ci-thing.yml", _gate(body))
+ def test_flags_gate_whose_results_reach_no_fail_closed_guard(self, tmp_path: Path, content: str) -> None:
+ _write(tmp_path, "ci-thing.yml", content)
issues = RequiredGateCheck().run(_read_all(tmp_path)).issues
assert sorted(i.message.split("'")[1] for i in issues) == ["build", "changes"]
assert all("fail-closed guard" in i.message for i in issues)
@@ -1501,8 +1524,8 @@ class TestRequiredGateCheck:
assert "never reaches" in issues[0].message
def test_ignores_non_gate_jobs(self, tmp_path: Path) -> None:
- # Worker jobs *should* use !cancelled() so they stop when superseded;
- # only the collate gate is held to always().
+ # Worker jobs share the !cancelled() condition, but they gate nothing,
+ # so WF007 has no dependency-guard demands on them.
_write(
tmp_path,
"ci-thing.yml",
@@ -1526,10 +1549,10 @@ class TestRequiredGateCheck:
issues = RequiredGateCheck().run(_read_all(tmp_path)).issues
assert [i.message.split("'")[1] for i in issues] == ["changes"]
- def test_finds_off_convention_gate_without_always(self, tmp_path: Path) -> None:
- _write(tmp_path, "ci-thing.yml", _off_convention_gate(condition="${{ !cancelled() }}"))
+ def test_finds_off_convention_gate_without_not_cancelled(self, tmp_path: Path) -> None:
+ _write(tmp_path, "ci-thing.yml", _off_convention_gate(condition="always()"))
issues = RequiredGateCheck().run(_read_all(tmp_path)).issues
- assert any("unconditional `if: always()`" in issue.message for issue in issues)
+ assert any("must use `if: ${{ !cancelled() }}`" in issue.message for issue in issues)
assert [issue.message.split("'")[1] for issue in issues if "dependency" in issue.message] == ["changes"]
def test_finds_env_routed_gate_not_named_pass(self, tmp_path: Path) -> None:
diff --git a/tools/hogli-commands/hogli_commands/workflow_lint/checks/required_gates.py b/tools/hogli-commands/hogli_commands/workflow_lint/checks/required_gates.py
index 67e5c77fcfd2..df715ac71742 100644
--- a/tools/hogli-commands/hogli_commands/workflow_lint/checks/required_gates.py
+++ b/tools/hogli-commands/hogli_commands/workflow_lint/checks/required_gates.py
@@ -1,11 +1,20 @@
-"""Collate gates must run unconditionally and fail closed on every dependency.
+"""Collate gates must run on every completed run and fail closed on every dependency.
A "collate gate" is the job that emits a required status check by inspecting its
dependencies' ``needs.*.result``. Two properties keep it honest:
-1. ``if: always()`` — the gate must run and emit an explicit verdict. Worker jobs
- should use ``!cancelled()`` so they actually stop when a run is superseded, but
- the gate itself is what branch protection reads, so it has to report.
+1. ``if: !cancelled()`` — the gate must emit an explicit verdict on every run that
+ is not superseded. On a cancelled run a ``!cancelled()`` job records conclusion
+ ``cancelled``, never ``skipped``, and branch protection passes only
+ ``success``/``skipped``/``neutral``, so the gate still fails closed while CI
+ failure-rate metrics stop counting superseded runs as failures. ``always()``
+ would instead run the gate after the cancel and report ``failure``.
+
+ Extra predicates may only be OR-ed on. A disjunction cannot be false while
+ ``!cancelled()`` is true, so cancellation stays the gate's one false predicate
+ and the conclusion stays ``cancelled``. A conjunction gives the gate a second
+ way to be false, and a job skipped by its own condition records ``skipped``,
+ which branch protection reads as a pass.
2. Allowlist **per dependency** — assert ``success``/``skipped`` and block
everything else. One bad dependency is enough, so judging the step as a whole
@@ -17,7 +26,7 @@ dependencies' ``needs.*.result``. Two properties keep it honest:
Gates are found two ways, because the "name it ``… Pass``" convention is not
universally followed: by that name, and structurally when a step reads
``needs.<dep>.result`` in its shell or environment. Detection is independent of
-the job condition so a gate missing ``always()`` cannot disappear from the rule.
+the job condition so a gate missing ``!cancelled()`` cannot disappear from the rule.
Jobs that inspect results without gating anything opt out with ``ALLOW_MARKER``
plus a reason.
@@ -44,6 +53,7 @@ ALLOW_MARKER = "hogli-lint: not-a-required-gate"
GATE_NAME = re.compile(r"\bpass$", re.IGNORECASE)
ALWAYS = re.compile(r"always\s*\(\s*\)")
+NOT_CANCELLED = re.compile(r"!\s*cancelled\s*\(\s*\)")
READS_RESULT = re.compile(r"needs\.(?P<dep>[A-Za-z0-9_\-]+)\.result")
# `foo() {` / `function foo() {`, whose body ends at the first `}` sitting at or
@@ -137,15 +147,54 @@ def _is_gate(job: Job) -> bool:
return any(READS_RESULT.search(source) for source in _result_sources(job))
-def _uses_only_always(condition: object) -> bool:
+def _normalized_condition(condition: object) -> str | None:
if not isinstance(condition, str):
- return False
+ return None
normalized = condition.strip()
if normalized.startswith("${{") or normalized.endswith("}}"):
if not (normalized.startswith("${{") and normalized.endswith("}}")):
- return False
+ return None
normalized = normalized[3:-2].strip()
- return ALWAYS.fullmatch(normalized) is not None
+ return normalized
+
+
+def _condition_matches(condition: object, pattern: re.Pattern[str]) -> bool:
+ normalized = _normalized_condition(condition)
+ return normalized is not None and pattern.fullmatch(normalized) is not None
+
+
+def _uses_only_not_cancelled(condition: object) -> bool:
+ return _condition_matches(condition, NOT_CANCELLED)
+
+
+def _gate_condition_ok(condition: object) -> bool:
+ """``!cancelled()``, alone or OR-ed with predicates that can only widen it.
+
+ ci-backend cancels its own run when a repo or OpenAPI check fails
+ deterministically, so under a bare ``!cancelled()`` a real failure would
+ report ``cancelled``. OR-ing that signal back on keeps the honest verdict:
+ the disjunct is true, so the gate dispatches despite the cancel and reports
+ ``failure``. ``&&`` anywhere is rejected — see the module docstring.
+ """
+ normalized = _normalized_condition(condition)
+ if normalized is None or "&&" in normalized:
+ return False
+ return any(NOT_CANCELLED.fullmatch(term.strip()) for term in normalized.split("||"))
+
+
+def _step_runs_whenever_gate_runs(job: Job, step: Step) -> bool:
+ """Guards only count in steps that execute on every path the gate takes.
+
+ No ``if`` and ``always()`` both run the step whenever the enclosing job
+ runs. A step-level ``!cancelled()`` only covers every path when the job
+ itself is bare ``!cancelled()``: an OR-widened gate dispatches specifically
+ while ``cancelled()`` is true, and there the step is skipped — its guard
+ would certify nothing on the one path the widening exists for.
+ """
+ condition = step.raw.get("if")
+ if condition is None or _condition_matches(condition, ALWAYS):
+ return True
+ return _uses_only_not_cancelled(condition) and _uses_only_not_cancelled(job.raw.get("if"))
def _without_heredocs(bash: str) -> str:
@@ -272,7 +321,7 @@ def _trace_step(job: Job, step: Step) -> tuple[set[str], dict[str, set[str]]]:
loops = _loop_names(scope.body)
lines = scope.body.splitlines()
- if step.raw.get("if") is None or _uses_only_always(step.raw.get("if")):
+ if _step_runs_whenever_gate_runs(job, step):
for index in range(len(lines)):
guard_operand = _guard_operand(lines, index)
if guard_operand is not None:
@@ -330,8 +379,12 @@ def _dependencies(job: Job) -> set[str]:
def _problems(job: Job) -> Iterator[str]:
- if not _uses_only_always(job.raw.get("if")):
- yield "required-check gate must use unconditional `if: always()` so it always emits a verdict"
+ if not _gate_condition_ok(job.raw.get("if")):
+ yield (
+ "required-check gate must use `if: ${{ !cancelled() }}` so it emits a verdict on every "
+ "completed run and reports `cancelled` (not `failure`) when superseded. Extra predicates "
+ "may only be OR-ed on; `&&` lets the gate skip, which branch protection reads as a pass"
+ )
step_traces = [_trace_step(job, step) for step in job.steps]
for dep in sorted(_dependencies(job)):
@@ -347,12 +400,13 @@ def _problems(job: Job) -> Iterator[str]:
class RequiredGateCheck(WorkflowCheck):
id = "WF007-required-check-gates"
label = "required-check gates"
- description = "collate gates use always() and allowlist each dependency's result"
+ description = "collate gates use !cancelled() and allowlist each dependency's result"
@property
def fix_hint(self) -> str | None:
return (
- "Use only `if: always()` on the gate, and test every dependency as "
+ "Use `if: ${{ !cancelled() }}` on the gate, OR-ing on any extra predicate rather than "
+ "`&&`-ing it, and test every dependency as "
'`!= "success" && != "skipped"` rather than `== "failure"`. Inline tests, an `env:` '
"block and a shared shell helper all work, so long as the failing branch exits nonzero. "
"A job that reads results without gating anything opts out with "