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): download missing semgrep for preflight in background (#112544)

Raúl Negrón-Otero0b8e17970710
diff --git a/.agents/skills/running-ci-preflight/SKILL.md b/.agents/skills/running-ci-preflight/SKILL.md
index e2552029d3f5..da99222c99cd 100644
--- a/.agents/skills/running-ci-preflight/SKILL.md
+++ b/.agents/skills/running-ci-preflight/SKILL.md
@@ -34,7 +34,7 @@ hogli ci:preflight --fix
- **Strict = failures only.** `--strict` (what the hook runs) exits non-zero only on `✗ fail` — advisories are unverifiable-locally classes, so they warn without blocking. A clean exit means "nothing left to fix", not "CI will pass" — CI stays the authoritative gate. Non-blocking is a mechanism limit, not permission to skip.
- **`type-check` is a nudge, not a run.** Only a repo-wide mypy run matches CI (mypy follows imports, so a changed-file subset misses reverse-dependency breakage), and that costs minutes cold — too much to tax every push with. So preflight names the command instead of running it: judge whether your change is type-risky and run it yourself. CI blocks on the same command, so a type error you skip here comes back as a full re-run.
- **`complexity` warns only.** Cyclomatic complexity above 10 in a changed file shows as `⚠ warning` and never blocks; CI annotates the same warning and posts it to the CI report comment. Simplify the function when you next touch it rather than gaming the number.
-- **`semgrep-devex` advises on findings your branch introduced.** It scans the changed files and their merge-base copies within one 15-second budget. Both scans use the cached version `SEMGREP_IMAGE` pins in `.github/workflows/ci-security.yaml`, with network access disabled. Run `hogli ci:preflight --prepare-semgrep` once with network access to prepare that tool. A missing tool or an incomplete scan skips with a reason, without delaying the push for downloads. A finding already on master is not reported. CI blocks on a new one, so fix it before you push. The advisory prints the command that shows the rule.
+- **`semgrep-devex` advises on findings your branch introduced.** It scans the changed files and their merge-base copies within one 15-second budget. Both scans use the cached version `SEMGREP_IMAGE` pins in `.github/workflows/ci-security.yaml`, with network access disabled. A missing tool skips the scan and starts its download in the background, so the next run scans. A cloud task or CI job does not start that download: run `hogli ci:preflight --prepare-semgrep` there with network access. An incomplete scan skips with a reason. A finding already on master is not reported. CI blocks on a new one, so fix it before you push. The advisory prints the command that shows the rule.
- **`snapshot-baselines` advises when `frontend/snapshots.yml` loses entries for stories your branch did not change.** This is what a bad merge-conflict resolution looks like. When the stories still render, the merge queue fails the batch that carries the file. Run the `git diff` the check prints and restore the entries you did not mean to remove. The entries of a story you deleted, renamed or retitled in the same branch pass.
- **`merge-queue-lane` warns only, and the pre-push hook skips it.** It fires when a few cross-cutting files (a CI workflow, a lane script) make the whole PR claim every merge queue lane, which makes the queue merge in series behind it. Move those files to their own PR when the other changes do not need them.
- **Staleness is risk-based.** It fires when merging master _now_ would actually break something — textual merge conflicts (computed via `git merge-tree`, working tree untouched), migrations added on both sides, generated-file inputs changed on both sides, or CI workflows changed on master — plus a behind/age backstop, aggressive by default (5 commits / 2 days; env-tunable via `HOGLI_PREFLIGHT_STALE_COMMITS`/`HOGLI_PREFLIGHT_STALE_DAYS`) so we over-warn to start and tune down from telemetry. Merge master in when it fires. Advisory only, never auto-merged.
diff --git a/tools/hogli-commands/hogli_commands/preflight_checks.py b/tools/hogli-commands/hogli_commands/preflight_checks.py
index 3b1559c0aa42..5848f8de1974 100644
--- a/tools/hogli-commands/hogli_commands/preflight_checks.py
+++ b/tools/hogli-commands/hogli_commands/preflight_checks.py
@@ -15,6 +15,7 @@ from typing import Literal
import yaml
from hogli.manifest import REPO_ROOT
+from hogli.telemetry import is_ci
from hogli_commands.change_detection import matches_globs
from hogli_commands.size_lint import _rename_map
@@ -141,33 +142,42 @@ SEMGREP_SCOPE = [
# CI excludes this tree from its blocking pass over ERROR rules, and from no other pass.
SEMGREP_ERROR_EXCLUDED = ["products/desktop/*"]
_SEMGREP_TIMEOUT_SECONDS = 15
+_SEMGREP_DOWNLOAD_RETRY_SECONDS = 600
# The rule, the file, and the source text the rule matched.
Finding = tuple[str, str, str]
+def _semgrep_spec() -> str | None:
+ """The semgrep version CI pins, as a requirement. None when the workflow pins none."""
+ try:
+ workflow = (REPO_ROOT / SEMGREP_WORKFLOW).read_text()
+ except OSError:
+ return None
+ pin = re.search(r"^\s*SEMGREP_IMAGE:\s*semgrep/semgrep:(\d+\.\d+\.\d+)@", workflow, re.MULTILINE)
+ return f"semgrep=={pin.group(1)}" if pin else None
+
+
def _semgrep_command(*, offline: bool = True) -> list[str] | None:
"""The command that runs the semgrep version CI pins. None when it cannot be built.
uv runs that version from its cache, in an environment of its own, so the scan does not
depend on a semgrep the developer installed. Only preparation downloads the package.
"""
- if shutil.which("uv") is None:
- return None
- try:
- workflow = (REPO_ROOT / SEMGREP_WORKFLOW).read_text()
- except OSError:
- return None
- pin = re.search(r"^\s*SEMGREP_IMAGE:\s*semgrep/semgrep:(\d+\.\d+\.\d+)@", workflow, re.MULTILINE)
- if pin is None:
+ spec = _semgrep_spec()
+ if spec is None or shutil.which("uv") is None:
return None
- return ["uv", "tool", "run", *(["--offline"] if offline else []), "--from", f"semgrep=={pin.group(1)}", "semgrep"]
+ return ["uv", "tool", "run", *(["--offline"] if offline else []), "--from", spec, "semgrep"]
class SemgrepUnavailable(RuntimeError):
pass
+class SemgrepExited(SemgrepUnavailable):
+ """The command exited non-zero, which is how a tool missing from the offline cache shows."""
+
+
def _semgrep_remaining(deadline: float) -> float:
remaining = deadline - time.monotonic()
if remaining <= 0:
@@ -200,11 +210,51 @@ def _run_semgrep(command: list[str], *, cwd: Path, timeout: float) -> subprocess
raise SemgrepUnavailable(f"semgrep could not start: {error}") from error
if result.returncode != 0:
lines = [line.strip() for line in result.stderr.splitlines() if line.strip()]
- detail = " · ".join(lines[-2:])[:240].rstrip(".") or f"exit {result.returncode}"
- raise SemgrepUnavailable(f"{detail}. Run `hogli ci:preflight --prepare-semgrep` to prepare the pinned tool")
+ raise SemgrepExited(" · ".join(lines[-2:])[:240].rstrip(".") or f"exit {result.returncode}")
return result
+def _download_missing_semgrep(command: list[str], *, deadline: float) -> str | None:
+ """Start caching the pinned semgrep when it is absent, without waiting for the download.
+
+ Returns the reason the scan is skipped, or None when the tool is already cached.
+ """
+ try:
+ _run_semgrep([*command, "--version"], cwd=REPO_ROOT, timeout=min(5, _semgrep_remaining(deadline)))
+ return None
+ except SemgrepExited:
+ pass
+ except SemgrepUnavailable:
+ return None
+ spec = _semgrep_spec()
+ manual = f"{spec} is not cached. Run `hogli ci:preflight --prepare-semgrep` to cache it"
+ # A cloud task or CI job starts with an empty cache, so it would download on every session.
+ if is_ci() or os.environ.get("POSTHOG_TASK_RUN_ID"):
+ return manual
+ hogli = shutil.which("hogli")
+ marker = _git("rev-parse", "--git-path", f"hogli-preflight-{spec}")
+ if hogli is None or marker is None:
+ return manual
+ started = REPO_ROOT / marker.decode().strip()
+ # The marker stops a machine that cannot download from starting one on every run.
+ if started.exists() and time.time() - started.stat().st_mtime < _SEMGREP_DOWNLOAD_RETRY_SECONDS:
+ return f"{manual} if the background download that started recently does not finish"
+ try:
+ # A child that holds the hook's output or its session keeps `git push` waiting.
+ subprocess.Popen(
+ [hogli, "ci:preflight", "--prepare-semgrep"],
+ cwd=REPO_ROOT,
+ stdin=subprocess.DEVNULL,
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL,
+ start_new_session=True,
+ )
+ started.touch()
+ except OSError:
+ return manual
+ return f"{spec} is not cached, so its download started in the background and the next run scans"
+
+
def prepare_semgrep() -> Outcome:
command = _semgrep_command(offline=False)
if command is None:
@@ -324,6 +374,9 @@ def check_semgrep_devex(scope: Scope) -> Outcome:
deadline = time.monotonic() + _SEMGREP_TIMEOUT_SECONDS
try:
return _check_semgrep_devex(scope, command, deadline=deadline)
+ except SemgrepExited as error:
+ reason = _download_missing_semgrep(command, deadline=deadline)
+ return "skipped", reason or f"{error}; CI will run the check"
except SemgrepUnavailable as error:
return "skipped", str(error)
except subprocess.TimeoutExpired:
diff --git a/tools/hogli-commands/hogli_commands/tests/test_preflight_checks.py b/tools/hogli-commands/hogli_commands/tests/test_preflight_checks.py
index 7cd8bea44b40..4769cfac7c77 100644
--- a/tools/hogli-commands/hogli_commands/tests/test_preflight_checks.py
+++ b/tools/hogli-commands/hogli_commands/tests/test_preflight_checks.py
@@ -9,6 +9,7 @@ from pathlib import Path
import pytest
from unittest.mock import MagicMock, patch
+from hogli.telemetry import _CI_ENV_VARS
from hogli_commands.preflight_checks import (
Finding,
Scope,
@@ -242,6 +243,60 @@ class TestSemgrepDevex:
assert status == "pass"
assert detail == "no new findings"
+ @pytest.mark.parametrize(
+ "cached,environment,expected_downloads,expected_fragment",
+ [
+ (False, {}, 1, "started in the background"),
+ (False, {"CI": "true"}, 0, "--prepare-semgrep"),
+ (False, {"POSTHOG_TASK_RUN_ID": "run"}, 0, "--prepare-semgrep"),
+ (True, {}, 0, "CI will run the check"),
+ ],
+ )
+ @patch("hogli_commands.preflight_checks.shutil.which", return_value="/usr/bin/tool")
+ def test_a_tool_missing_from_the_cache_downloads_once_in_the_background(
+ self,
+ mock_which: MagicMock,
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ cached: bool,
+ environment: dict[str, str],
+ expected_downloads: int,
+ expected_fragment: str,
+ ) -> None:
+ (tmp_path / ".github/workflows").mkdir(parents=True)
+ (tmp_path / ".github/workflows/ci-security.yaml").write_text(
+ "SEMGREP_IMAGE: semgrep/semgrep:1.175.0@sha256:test\n"
+ )
+ (tmp_path / "posthog").mkdir()
+ (tmp_path / "posthog/a.py").write_text("value = 1\n")
+ for name in (*_CI_ENV_VARS, "POSTHOG_TASK_RUN_ID"):
+ monkeypatch.delenv(name, raising=False)
+ for name, value in environment.items():
+ monkeypatch.setenv(name, value)
+
+ def run(command: list[str], **kwargs: object) -> subprocess.CompletedProcess[object]:
+ if command[0] == "git":
+ return subprocess.CompletedProcess(command, 0, stdout=b"download-marker\n", stderr=b"")
+ if cached and "--version" in command:
+ return subprocess.CompletedProcess(command, 0, stdout="1.175.0", stderr="")
+ return subprocess.CompletedProcess(command, 1, stdout="", stderr="error: not found in the cache")
+
+ scope = Scope(files=["posthog/a.py"], changed=["posthog/a.py"], merge_base="abc123", committed_only=False)
+ with (
+ patch("hogli_commands.preflight_checks.REPO_ROOT", tmp_path),
+ patch("hogli_commands.preflight_checks.subprocess.run", side_effect=run),
+ patch("hogli_commands.preflight_checks.subprocess.Popen") as mock_popen,
+ ):
+ status, detail = check_semgrep_devex(scope)
+ repeat_status, _ = check_semgrep_devex(scope)
+
+ assert (status, repeat_status) == ("skipped", "skipped")
+ assert expected_fragment in detail
+ assert mock_popen.call_count == expected_downloads
+ if expected_downloads:
+ assert mock_popen.call_args.args[0] == ["/usr/bin/tool", "ci:preflight", "--prepare-semgrep"]
+ assert mock_popen.call_args.kwargs["start_new_session"] is True
+
WORKFLOW = ".github/workflows/ci-backend.yml"
PRODUCT_FILE = "products/x/backend/api.py"