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.

23.3 KB
Raw Blame
"""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``. Three properties keep it honest:

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
   would call a mostly-correct gate clean. The trap is a ``changes`` detector
   cleared with a bare ``== 'failure'`` test: ``cancelled`` passes it, the gate
   then reads ``needs.changes.outputs.*``, which is empty on a cancelled job, and
   takes its "nothing to test" exit — green, with zero tests run.

3. ``needs`` closed over the upstreams that can skip a dependency — the gate must name
   every job whose failure would skip a job it does test, not only the ones it needs
   directly. GitHub skips a job when a job in its ``needs:`` fails, and the gate reads a
   skip as a pass, so a change detector one step further up produces a green check with
   zero tests behind it. Measured on ci-nodejs in run 32472790735: change detection
   failed, every Node.js job skipped, and "Node.js Tests Pass" reported success.

   Only edges that carry the skip count. A test selector whose failure leaves the suite
   running in full is not gate-critical, and demanding it would turn a recovered run
   into a red required check.

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 ``!cancelled()`` cannot disappear from the rule.
Jobs that inspect results without gating anything opt out with ``ALLOW_MARKER``
plus a reason.

Results reach a fail-closed guard directly or indirectly, by way of a step
``env:`` block or a shared shell function. Both forms are judged the same way:
within each step, every dependency's result is traced through assignments,
``${!var}`` indirection, and helper-call argument positions to a canonical guard.
That guard must allowlist one or both safe states with ``!=`` comparisons joined
by ``&&``, then unconditionally exit nonzero. This keeps comparisons in comments,
logs, other steps, and non-failing branches from certifying a dependency.
"""

from __future__ import annotations

import re
from collections.abc import Iterable, Iterator
from dataclasses import dataclass

from ..check import CheckResult, Issue, WorkflowCheck
from ..markers import exempt_jobs
from ..model import Job, Step, Workflow

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")
STATUS_CALL = re.compile(r"(?P<negated>!\s*)?\b(?P<name>always|cancelled|failure|success)\s*\(\s*\)")

# Status calls that are true in the state this module reasons about: an upstream job
# failed and the run itself was not cancelled. `success()` and `cancelled()` are false
# there, so a job conditioned on either is skipped exactly like a job with no status
# call at all.
TRUE_AFTER_UPSTREAM_FAILURE = frozenset({("always", False), ("cancelled", True), ("failure", False), ("success", True)})

# What a failed job's own references read as. Outputs are empty because the job never
# set them; `result` carries the failure itself, which is why the two cannot share a rule.
FAILED_RESULT = "failure"
FAILED_OUTPUT = ""

COMPARISON = re.compile(
    r"""(?P<left>needs\.(?P<ldep>[A-Za-z0-9_\-]+)\.(?P<lkind>outputs\.[A-Za-z0-9_\-]+|result)|'[^']*'|"[^"]*")"""
    r"""\s*(?P<op>==|!=)\s*"""
    r"""(?P<right>needs\.(?P<rdep>[A-Za-z0-9_\-]+)\.(?P<rkind>outputs\.[A-Za-z0-9_\-]+|result)|'[^']*'|"[^"]*")"""
)


# `foo() {` / `function foo() {`, whose body ends at the first `}` sitting at or
# left of the definition's own indentation. Brace counting would be the general
# answer, but gate steps embed brace groups and Python heredocs, so the
# conventional shell layout is the more reliable signal.
FUNC_DEF = re.compile(r"^(?P<indent>[ \t]*)(?:function\s+)?(?P<name>[A-Za-z_][A-Za-z0-9_]*)\s*\(\s*\)\s*\{\s*$")

OPERAND = r"""\$\{\{[^}]*\}\}|\$\{!?[A-Za-z_0-9]+\}|\$[A-Za-z_0-9]+"""
IF_TEST = re.compile(r"^\s*if\s+\[\[\s*(?P<condition>.*?)\s*\]\]\s*;\s*then\s*(?:#.*)?$")
NOT_SAFE_STATUS = re.compile(rf"""["']?(?P<operand>{OPERAND})["']?\s*!=\s*["']?(?P<literal>success|skipped)["']?""")
NONZERO_EXIT = re.compile(r"exit\s+[1-9][0-9]*\s*(?:#.*)?$")
SIMPLE_LOG = re.compile(r"(?:echo|printf)\s+(?:\"[^\"]*\"|'[^']*')\s*$")
HEREDOC = re.compile(r"<<-?\s*[\"']?(?P<delimiter>[A-Za-z_][A-Za-z0-9_]*)[\"']?")

# `local result="$2"` / `val="${!var}"`, which is how a positional or an env value
# picks up the name that the comparison further down actually tests.
ASSIGNMENT = re.compile(
    rf"""^\s*(?:local\s+|declare\s+|export\s+)?(?P<target>[A-Za-z_][A-Za-z_0-9]*)=["']?(?P<source>{OPERAND})["']?"""
)

# `for var in BUILD DEPLOY; do`, giving the candidate names a later `${!var}` can hold.
FOR_LOOP = re.compile(r"^\s*for\s+(?P<var>[A-Za-z_][A-Za-z_0-9]*)\s+in\s+(?P<names>[^;]+?)\s*;?\s*do\b")

IDENTIFIER = re.compile(r"^[A-Za-z_][A-Za-z_0-9]*$")
ARGUMENT = re.compile(r"""\"[^\"]*\"|'[^']*'|\S+""")
VAR_OPERAND = re.compile(r"^\$\{?(?P<indirect>!)?(?P<name>[A-Za-z_0-9]+)\}?$")


@dataclass(frozen=True, slots=True)
class _Scope:
    """A shell body with its own positional parameters: one function, or the step itself."""

    name: str  # "" for the step body outside any function
    body: str


def _env(block: object) -> dict[str, str]:
    if not isinstance(block, dict):
        return {}
    return {name: value for name, value in block.items() if isinstance(name, str) and isinstance(value, str)}


def _effective_env(job: Job, step: Step) -> dict[str, str]:
    return _env(job.raw.get("env")) | _env(step.raw.get("env"))


def _result_sources(job: Job) -> Iterator[str]:
    yield from _env(job.raw.get("env")).values()
    for step in job.steps:
        if step.run:
            yield step.run
        condition = step.raw.get("if")
        if isinstance(condition, str):
            yield condition
        yield from _env(step.raw.get("env")).values()


def _is_gate(job: Job) -> bool:
    name = job.raw.get("name")
    display = name if isinstance(name, str) else job.name
    if GATE_NAME.search(display.strip()):
        return True
    return any(READS_RESULT.search(source) for source in _result_sources(job))


def _normalized_condition(condition: object) -> str | None:
    if not isinstance(condition, str):
        return None
    normalized = condition.strip()
    if normalized.startswith("${{") or normalized.endswith("}}"):
        if not (normalized.startswith("${{") and normalized.endswith("}}")):
            return None
        normalized = normalized[3:-2].strip()
    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:
    lines: list[str] = []
    delimiter: str | None = None
    for line in bash.splitlines():
        if delimiter is not None:
            if line.strip() == delimiter:
                delimiter = None
            lines.append("")
            continue
        lines.append(line)
        match = HEREDOC.search(line)
        if match is not None:
            delimiter = match.group("delimiter")
    return "\n".join(lines)


def _scopes(bash: str) -> list[_Scope]:
    lines = _without_heredocs(bash).splitlines()
    top: list[str] = []
    scopes: list[_Scope] = []

    idx = 0
    while idx < len(lines):
        match = FUNC_DEF.match(lines[idx])
        if match is None:
            top.append(lines[idx])
            idx += 1
            continue
        indent = len(match.group("indent"))
        body: list[str] = []
        idx += 1
        while idx < len(lines):
            line = lines[idx]
            idx += 1
            if line.strip() == "}" and len(line) - len(line.lstrip()) <= indent:
                break
            body.append(line)
        scopes.append(_Scope(match.group("name"), "\n".join(body)))

    scopes.append(_Scope("", "\n".join(top)))
    return scopes


def _loop_names(body: str) -> dict[str, set[str]]:
    """Loop variable to the identifiers it iterates over, so `${!var}` can be resolved."""
    loops: dict[str, set[str]] = {}
    for line in body.splitlines():
        match = FOR_LOOP.match(line)
        if match is None:
            continue
        names = {word for word in match.group("names").split() if IDENTIFIER.match(word)}
        if names:
            loops.setdefault(match.group("var"), set()).update(names)
    return loops


def _operands(scope: _Scope, token: str, loops: dict[str, set[str]]) -> list[str]:
    """Every operand key a shell token can stand for.

    `${{ needs.x.result }}` is global; `$2` and `$result` are local to their
    scope; `${!var}` stands for whichever names the enclosing loop supplies.
    """
    token = token.strip().strip('"').strip("'")
    if "needs." in token:
        match = READS_RESULT.search(token)
        return [f"needs:{match.group('dep')}"] if match else []

    match = VAR_OPERAND.match(token)
    if match is None:
        return []
    name = match.group("name")
    if match.group("indirect"):
        return [f"{scope.name}|var:{held}" for held in sorted(loops.get(name, ()))]
    kind = "arg" if name.isdigit() else "var"
    return [f"{scope.name}|{kind}:{name}"]


def _guard_operand(lines: list[str], index: int) -> str | None:
    match = IF_TEST.match(lines[index])
    if match is None:
        return None

    comparisons: list[re.Match[str]] = []
    for term in re.split(r"\s*&&\s*", match.group("condition")):
        comparison = NOT_SAFE_STATUS.fullmatch(term.strip())
        if comparison is None:
            return None
        comparisons.append(comparison)

    operands = {comparison.group("operand") for comparison in comparisons}
    if len(operands) != 1:
        return None

    for body_line in lines[index + 1 :]:
        stripped = body_line.strip()
        if not stripped or stripped.startswith("#") or SIMPLE_LOG.fullmatch(stripped):
            continue
        if NONZERO_EXIT.fullmatch(stripped):
            return operands.pop()
        return None
    return None


def _trace_step(job: Job, step: Step) -> tuple[set[str], dict[str, set[str]]]:
    """Resolve one shell step into guarded operands and alias edges.

    An edge ``a -> b`` means a result held by ``a`` also flows into ``b``, so a
    fail-closed guard on ``b`` gates ``a``. Steps stay isolated because their
    shells and step-level environments do not persist into later steps.
    """
    scopes = _scopes(step.run or "")
    functions = {scope.name for scope in scopes if scope.name}

    guarded: set[str] = set()
    edges: dict[str, set[str]] = {}

    for name, value in _effective_env(job, step).items():
        for source in _operands(_Scope("", ""), value, {}):
            edges.setdefault(source, set()).add(f"|var:{name}")

    for scope in scopes:
        loops = _loop_names(scope.body)
        lines = scope.body.splitlines()

        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:
                    guarded.update(_operands(scope, guard_operand, loops))

        for line in lines:
            assignment = ASSIGNMENT.match(line)
            if assignment is not None:
                target = f"{scope.name}|var:{assignment.group('target')}"
                for source in _operands(scope, assignment.group("source"), loops):
                    edges.setdefault(source, set()).add(target)

            # A helper call binds each argument to that function's positional parameter.
            # Only a nested definition is skipped here, matched as such rather than by
            # looking for `()` anywhere, which also discards real calls whose arguments
            # or trailing comment happen to contain those two characters.
            call = line.strip()
            if FUNC_DEF.match(call):
                continue
            name, _, rest = call.partition(" ")
            if name not in functions or not rest.strip():
                continue
            for position, argument in enumerate(ARGUMENT.findall(rest), start=1):
                for source in _operands(scope, argument, loops):
                    edges.setdefault(source, set()).add(f"{name}|arg:{position}")

    return guarded, edges


def _reachable(start: str, edges: dict[str, set[str]]) -> Iterable[str]:
    seen = {start}
    queue = [start]
    while queue:
        node = queue.pop()
        yield node
        for nxt in edges.get(node, ()):
            if nxt not in seen:
                seen.add(nxt)
                queue.append(nxt)


def _declared_needs(job: Job) -> set[str]:
    """The job ids in ``needs:``, whether written as one string or a list."""
    declared = job.raw.get("needs") or []
    declared = [declared] if isinstance(declared, str) else declared
    return {dep for dep in declared if isinstance(dep, str)}


def _dependencies(job: Job) -> set[str]:
    """Every dependency the gate is answerable for.

    Taken from ``needs:`` as well as the step body, because a job wired into
    ``needs:`` and then never tested is the drift this check exists to catch:
    reading only the body would judge the assertions that were written and stay
    silent about the one that was forgotten.
    """
    referenced = {dep for source in _result_sources(job) for dep in READS_RESULT.findall(source)}
    return _declared_needs(job) | referenced


def _runs_past_an_upstream_failure(condition: str) -> bool:
    """Does this ``if`` still dispatch its job after a job it needs failed?

    GitHub runs a job only when every job in its ``needs:`` succeeded, unless the
    job's own ``if`` calls a status function. Calling one is not enough on its own:
    the call also has to be true in that state, which `success()` and `cancelled()`
    are not.

    A condition that carries both kinds is read as skipping, without solving the
    boolean expression: `!cancelled() && success()` is false in that state, and the
    conjunction is the only composition of the two anyone writes. Reading it the
    other way would drop a skip-propagating edge and let the gate go green with the
    worker skipped.
    """
    calls = {(call.group("name"), call.group("negated") is not None) for call in STATUS_CALL.finditer(condition)}
    return bool(calls & TRUE_AFTER_UPSTREAM_FAILURE) and not (calls - TRUE_AFTER_UPSTREAM_FAILURE)


def _falsified_by(condition: str, upstream: str) -> bool:
    """Does any comparison in this ``if`` turn false once ``upstream`` fails?

    Each comparison against the failed job is evaluated with the value it really
    reads back: an empty string for an output, and `failure` for `result`. So
    `outputs.x == 'true'` and `result == 'success'` both go false and skip the job,
    while `outputs.mode != 'none'` and a recovery path's `result == 'failure'` stay
    true and let it run.

    A false term is read as a skip without solving the whole boolean expression. That
    over-reports a condition where a disjunct unrelated to the upstream can still
    carry the job, which fails the gate closed rather than open.

    The empty-output model assumes a failed job published nothing. A job that sets an
    output from a `failure()`-guarded step breaks that assumption, and a consumer
    testing the value it did publish would skip without this seeing it. Reading those
    outputs as unknown instead would make every inequality against a selector look
    false, which is what makes a recovered selector gate-critical, so the assumption
    stays and the narrower miss is the accepted cost.
    """
    for comparison in COMPARISON.finditer(condition):
        for side, other in (("l", "right"), ("r", "left")):
            if comparison.group(f"{side}dep") != upstream:
                continue
            literal = comparison.group(other)
            if literal.startswith("needs."):
                continue
            actual = FAILED_RESULT if comparison.group(f"{side}kind") == "result" else FAILED_OUTPUT
            equal = literal[1:-1] == actual
            if equal is (comparison.group("op") == "!="):
                return True
    return False


def _skips_when_upstream_fails(job: Job, upstream: str) -> bool:
    """Would ``job`` be skipped if ``upstream`` failed?

    This is what separates a detector from a selector. `ci-e2e-playwright` reads
    `needs.changes.outputs.shouldRun == 'true'`, so a failed `changes` skips the
    suite. It never reads `select-specs`, and an empty selection makes the suite run
    in full, so a failed selector costs runner time and no coverage.
    """
    condition = job.raw.get("if")
    if not isinstance(condition, str):
        return True
    if not _runs_past_an_upstream_failure(condition):
        return True
    return _falsified_by(condition, upstream)


def _upstream_gaps(job: Job, jobs: dict[str, Job]) -> Iterator[str]:
    """Jobs that a gate dependency needs, whose failure the gate would read as a pass.

    GitHub skips a job when a job in its ``needs:`` fails, and the gate reads a
    skip as a pass. A failure one step further up the graph therefore arrives at
    the gate as a green verdict with no tests behind it. The gate has to name every
    job that can skip one of its dependencies this way.

    Only edges that propagate a skip count. An upstream a dependency recovers from
    stays out, because failing the gate on it turns a recovered run into a red
    required check.
    """
    dependencies = _dependencies(job) & jobs.keys()
    skip_graph = {
        name: {up for up in _declared_needs(other) & jobs.keys() if _skips_when_upstream_fails(other, up)}
        for name, other in jobs.items()
    }
    reached = {upstream for dep in dependencies for upstream in _reachable(dep, skip_graph)}
    for missing in sorted(reached - dependencies):
        yield (
            f"upstream '{missing}' is not a dependency of this gate. A failure there skips a job the "
            f"gate does test, and the gate reads that skip as a pass. Add '{missing}' to `needs:` "
            "and test its result"
        )


def _problems(job: Job, jobs: dict[str, Job]) -> Iterator[str]:
    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)):
        if not any(
            any(operand in guarded for operand in _reachable(f"needs:{dep}", edges)) for guarded, edges in step_traces
        ):
            yield (
                f"dependency '{dep}' result never reaches a fail-closed guard, so nothing blocks a "
                f'cancelled \'{dep}\'. Test `!= "success" && != "skipped"`, then exit nonzero'
            )

    yield from _upstream_gaps(job, jobs)


class RequiredGateCheck(WorkflowCheck):
    id = "WF007-required-check-gates"
    label = "required-check gates"
    description = "collate gates use !cancelled() and allowlist each dependency's result"

    @property
    def fix_hint(self) -> str | None:
        return (
            "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. "
            "`needs:` every job your dependencies need, so an upstream failure meets a guard "
            "instead of a skip. A job that reads results without gating anything opts out with "
            f"`# {ALLOW_MARKER} — <reason>`. See .agents/skills/authoring-ci-workflows/SKILL.md."
        )

    def run(self, workflows: list[Workflow]) -> CheckResult:
        result = CheckResult()
        for wf in workflows:
            gates = [job for job in wf.jobs if not job.is_reusable_call and _is_gate(job)]
            if not gates:
                continue
            # Only worth re-reading the file once we know there's a gate to exempt.
            exempt = exempt_jobs(wf.path, frozenset(job.name for job in wf.jobs), ALLOW_MARKER)
            jobs = {job.name: job for job in wf.jobs}
            for job in gates:
                if job.name in exempt:
                    continue
                for message in _problems(job, jobs):
                    result.issues.append(Issue(workflow=wf.path.name, job=job.name, message=message, file=str(wf.path)))
        return result