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.

fix(ci): skip master's clickhouse migrations on stacked prs (#105891)

Raúl Negrón-Oterodcbfda2ff37e
diff --git a/.depot/workflows/ci-backend.yml b/.depot/workflows/ci-backend.yml
index 246c52f31ce1..dde4efc53f8e 100644
--- a/.depot/workflows/ci-backend.yml
+++ b/.depot/workflows/ci-backend.yml
@@ -1968,9 +1968,10 @@ jobs:
app_name=$(sed -E 's|^([^/]+/)*([^/]+)/migrations/.*|\2|' <<< "$file")
fi
- # Only show SQL for new migrations, not modifications to existing ones
- if git cat-file -e "$BASE_SHA:$file" 2>/dev/null; then
- echo "Skipping $file (already exists on base branch)"
+ # A stacked PR can carry master's migration at this path. Keep a
+ # conflicting version visible even when master has the same path.
+ if git cat-file -e "$BASE_SHA:$file" 2>/dev/null || git diff --quiet upstream/master HEAD -- "$file"; then
+ echo "Skipping $file (already exists on the base branch or matches master)"
continue
fi
@@ -2300,24 +2301,39 @@ jobs:
DATABASE_URL="postgres://posthog:posthog@localhost:5432/posthog_persons" \
sqlx migrate info --source rust/persons_migrations/
python manage.py makemigrations --check --dry-run
- - name: Check CH migrations
+ - name: List this PR's ClickHouse migrations
env:
- BASE_REF: ${{ github.event.pull_request.base.ref }}
+ BASE_SHA: ${{ github.event.pull_request.base.sha }}
run: |
- # Count only migrations this PR adds; a stacked PR's base branch already carries the lower layers'.
+ set -euo pipefail
+ export LC_ALL=C
DIFF_BASE=upstream/master
- if [ -n "$BASE_REF" ] && [ "$BASE_REF" != "master" ]; then
- if git fetch --no-tags --depth=1 --filter=blob:none origin "$BASE_REF:refs/remotes/origin/$BASE_REF"; then
- DIFF_BASE="origin/$BASE_REF"
- else
- echo "::warning::Could not fetch base ref $BASE_REF; counting CH migrations against master instead"
+ if [ -n "$BASE_SHA" ]; then
+ if ! git cat-file -e "$BASE_SHA^{commit}" 2>/dev/null; then
+ git remote get-url origin >/dev/null 2>&1 || git remote add origin "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY"
+ git fetch --no-tags --depth=1 --filter=blob:none origin "$BASE_SHA"
fi
+ DIFF_BASE="$BASE_SHA"
fi
+ ch_migrations() {
+ # Migrations share most of their text, so rename detection would pair this PR's
+ # migration with one master added later and report it as R, dropping it here.
+ git diff --no-renames --name-only --diff-filter="$1" "$2"..HEAD -- 'posthog/clickhouse/migrations/[0-9]*' | sort
+ }
+ ch_migrations A upstream/master > "$RUNNER_TEMP/ch-master-added.txt"
+ ch_migrations AM upstream/master > "$RUNNER_TEMP/ch-master-changed.txt"
+ # A stacked branch can carry master's migrations, and master can edit one later.
+ # Only a file that master lacks counts as this PR's addition.
+ ch_migrations A "$DIFF_BASE" | comm -12 - "$RUNNER_TEMP/ch-master-added.txt" > "$RUNNER_TEMP/ch-migrations-added.txt"
+ ch_migrations AM "$DIFF_BASE" | comm -12 - "$RUNNER_TEMP/ch-master-changed.txt" > "$RUNNER_TEMP/ch-migrations-changed.txt"
+ cat "$RUNNER_TEMP/ch-migrations-changed.txt"
+
+ - name: Check CH migrations
+ run: |
# test_ch_migrations_are_safe requires a local master branch, while the
# comparison checkout is registered as upstream/master.
git show-ref --verify --quiet refs/heads/master || git branch master upstream/master
- # Same as above, except now for CH looking at files that were added in posthog/clickhouse/migrations/
- git diff --name-status "$DIFF_BASE"..HEAD | grep "A\sposthog/clickhouse/migrations/" | grep -v README | awk '{print $2}' | python manage.py test_ch_migrations_are_safe
+ python manage.py test_ch_migrations_are_safe < "$RUNNER_TEMP/ch-migrations-added.txt"
- name: Render CH migration SQL per cloud environment
# CH migrations can build different `operations` lists at import time depending on
@@ -2329,18 +2345,8 @@ jobs:
# grouped together; if all environments match, the environment level is collapsed.
id: render_ch_sql
if: github.event_name == 'pull_request'
- env:
- BASE_REF: ${{ github.event.pull_request.base.ref }}
run: |
- DIFF_BASE=upstream/master
- if [ -n "$BASE_REF" ] && [ "$BASE_REF" != "master" ]; then
- if git fetch --no-tags --depth=1 --filter=blob:none origin "$BASE_REF:refs/remotes/origin/$BASE_REF"; then
- DIFF_BASE="origin/$BASE_REF"
- else
- echo "::warning::Could not fetch base ref $BASE_REF; rendering CH migrations against master instead"
- fi
- fi
- CHANGED=$(git diff --name-only --diff-filter=AM "$DIFF_BASE"..HEAD | grep '^posthog/clickhouse/migrations/[0-9]' | grep -v __pycache__ || true)
+ CHANGED=$(cat "$RUNNER_TEMP/ch-migrations-changed.txt")
if [ -z "$CHANGED" ]; then
echo "No ClickHouse migrations changed."
echo "has_changes=false" >> "$GITHUB_OUTPUT"
diff --git a/.github/scripts/test_ci_migration_selection.py b/.github/scripts/test_ci_migration_selection.py
new file mode 100644
index 000000000000..5b29c0116703
--- /dev/null
+++ b/.github/scripts/test_ci_migration_selection.py
@@ -0,0 +1,137 @@
+import os
+import functools
+import subprocess
+from pathlib import Path
+
+import pytest
+
+import yaml
+
+ROOT = Path(__file__).resolve().parents[2]
+MIGRATIONS = "posthog/clickhouse/migrations"
+MIGRATION_TEMPLATE = """from posthog.clickhouse.client.migration_tools import run_sql_with_exceptions
+from posthog.clickhouse.cluster import NodeRole
+
+operations = [
+ run_sql_with_exceptions(
+ "ALTER TABLE {table} ADD COLUMN IF NOT EXISTS example String",
+ node_roles=[NodeRole.DATA],
+ ),
+]
+"""
+OWN = f"{MIGRATIONS}/0003_own.py"
+
+
+def git(repo: Path, *args: str) -> str:
+ return subprocess.check_output(["git", "-C", str(repo), *args], text=True).strip()
+
+
+def commit_file(repo: Path, name: str, content: str) -> str:
+ path = repo / MIGRATIONS / name
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(content)
+ git(repo, "add", ".")
+ git(repo, "commit", "-qm", "fixture")
+ return git(repo, "rev-parse", "HEAD")
+
+
+def commit_on_master(repo: Path, master: str, name: str, content: str) -> None:
+ git(repo, "checkout", "-q", "master")
+ commit_file(repo, name, content)
+ git(repo, "update-ref", f"refs/remotes/{master}", "HEAD")
+ git(repo, "checkout", "-q", "topic")
+
+
+def list_step(engine: str) -> str:
+ workflow = yaml.safe_load((ROOT / engine / "workflows/ci-backend.yml").read_text())
+ return next(
+ step["run"]
+ for job in workflow["jobs"].values()
+ for step in job.get("steps", [])
+ if step.get("name") == "List this PR's ClickHouse migrations"
+ )
+
+
[email protected]("engine,master", [(".github", "origin/master"), (".depot", "upstream/master")])
+ "case,expected",
+ [
+ ("based on master", ([OWN], [OWN])),
+ ("stale base", ([OWN], [OWN])),
+ ("stale base carries master's migration", ([], [])),
+ ("master adds a similar migration later", ([OWN], [OWN])),
+ ("master edits a migration the branch carries", ([], [f"{MIGRATIONS}/0002_master.py"])),
+ ("edits an existing migration", ([], [f"{MIGRATIONS}/0001_base.py"])),
+ ("base missing from the clone", ([f"{MIGRATIONS}/0004_own.py"], [f"{MIGRATIONS}/0004_own.py"])),
+ ("unknown base", None),
+ ("no master ref", None),
+ ],
+)
+def test_lists_only_this_prs_migrations(
+ engine: str,
+ master: str,
+ case: str,
+ expected: tuple[list[str], list[str]] | None,
+ tmp_path: Path,
+) -> None:
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ git(repo, "init", "-q", "-b", "master")
+ git(repo, "config", "user.name", "CI fixture")
+ git(repo, "config", "user.email", "[email protected]")
+ git(repo, "config", "commit.gpgsign", "false")
+ base = commit_file(repo, "0001_base.py", "base\n")
+ commit_file(repo, "0002_master.py", "master\n")
+ git(repo, "update-ref", f"refs/remotes/{master}", "HEAD")
+ git(repo, "checkout", "-qb", "topic")
+
+ if case == "based on master":
+ base = git(repo, "rev-parse", "HEAD")
+ commit_file(repo, "0003_own.py", "own\n")
+ elif case == "stale base":
+ commit_file(repo, "0003_own.py", "own\n")
+ elif case == "master adds a similar migration later":
+ commit_on_master(repo, master, "0003_master.py", MIGRATION_TEMPLATE.format(table="master_table"))
+ commit_file(repo, "0003_own.py", MIGRATION_TEMPLATE.format(table="own_table"))
+ elif case == "master edits a migration the branch carries":
+ commit_on_master(repo, master, "0002_master.py", "master fixed\n")
+ elif case == "edits an existing migration":
+ commit_file(repo, "0001_base.py", "modified\n")
+ elif case == "base missing from the clone":
+ base = commit_file(repo, "0003_lower_layer.py", "lower\n")
+ commit_file(repo, "0004_own.py", "own\n")
+ source = tmp_path / "upstream.git"
+ repo.rename(source)
+ subprocess.run(
+ ["git", "clone", "-q", "--depth=1", "--no-single-branch", "-b", "topic", source.as_uri(), str(repo)],
+ check=True,
+ )
+ if engine == ".depot":
+ git(repo, "update-ref", f"refs/remotes/{master}", "refs/remotes/origin/master")
+ git(repo, "remote", "remove", "origin")
+ elif case == "unknown base":
+ base = "0" * 40
+ elif case == "no master ref":
+ git(repo, "update-ref", "-d", f"refs/remotes/{master}")
+
+ result = subprocess.run(
+ ["bash", "-e", "-c", list_step(engine)],
+ cwd=repo,
+ env={
+ **os.environ,
+ "BASE_SHA": base,
+ "RUNNER_TEMP": str(tmp_path),
+ "GITHUB_SERVER_URL": str(tmp_path),
+ "GITHUB_REPOSITORY": "upstream.git",
+ },
+ text=True,
+ capture_output=True,
+ )
+ if expected is None:
+ assert result.returncode != 0
+ return
+ assert result.returncode == 0, result.stderr
+ added = (tmp_path / "ch-migrations-added.txt").read_text().splitlines()
+ changed = (tmp_path / "ch-migrations-changed.txt").read_text().splitlines()
+ assert (added, changed) == expected
diff --git a/.github/workflows/ci-backend.yml b/.github/workflows/ci-backend.yml
index dae5ea04c0b0..8d1dcfd49f60 100644
--- a/.github/workflows/ci-backend.yml
+++ b/.github/workflows/ci-backend.yml
@@ -1862,9 +1862,10 @@ jobs:
app_name=$(echo $file | sed -E 's|^([^/]+/)*([^/]+)/migrations/.*|\2|')
fi
- # Only show SQL for new migrations, not modifications to existing ones
- if git cat-file -e "$BASE_SHA:$file" 2>/dev/null; then
- echo "Skipping $file (already exists on base branch)"
+ # A stacked PR can carry master's migration at this path. Keep a
+ # conflicting version visible even when master has the same path.
+ if git cat-file -e "$BASE_SHA:$file" 2>/dev/null || git diff --quiet origin/master HEAD -- "$file"; then
+ echo "Skipping $file (already exists on the base branch or matches master)"
continue
fi
@@ -2226,21 +2227,34 @@ jobs:
sqlx migrate info --source rust/persons_migrations/
python manage.py makemigrations --check --dry-run
- - name: Check CH migrations
+ - name: List this PR's ClickHouse migrations
env:
- BASE_REF: ${{ github.event.pull_request.base.ref }}
+ BASE_SHA: ${{ github.event.pull_request.base.sha }}
run: |
- # Count only migrations this PR adds; a stacked PR's base branch already carries the lower layers'.
+ set -euo pipefail
+ export LC_ALL=C
DIFF_BASE=origin/master
- if [ -n "$BASE_REF" ] && [ "$BASE_REF" != "master" ]; then
- if git fetch --no-tags --depth=1 --filter=blob:none origin "$BASE_REF:refs/remotes/origin/$BASE_REF"; then
- DIFF_BASE="origin/$BASE_REF"
- else
- echo "::warning::Could not fetch base ref $BASE_REF; counting CH migrations against master instead"
+ if [ -n "$BASE_SHA" ]; then
+ if ! git cat-file -e "$BASE_SHA^{commit}" 2>/dev/null; then
+ git fetch --no-tags --depth=1 --filter=blob:none origin "$BASE_SHA"
fi
+ DIFF_BASE="$BASE_SHA"
fi
- # Same as above, except now for CH looking at files that were added in posthog/clickhouse/migrations/
- git diff --name-status "$DIFF_BASE"..HEAD | grep "A\sposthog/clickhouse/migrations/" | grep -v README | awk '{print $2}' | python manage.py test_ch_migrations_are_safe
+ ch_migrations() {
+ # Migrations share most of their text, so rename detection would pair this PR's
+ # migration with one master added later and report it as R, dropping it here.
+ git diff --no-renames --name-only --diff-filter="$1" "$2"..HEAD -- 'posthog/clickhouse/migrations/[0-9]*' | sort
+ }
+ ch_migrations A origin/master > "$RUNNER_TEMP/ch-master-added.txt"
+ ch_migrations AM origin/master > "$RUNNER_TEMP/ch-master-changed.txt"
+ # A stacked branch can carry master's migrations, and master can edit one later.
+ # Only a file that master lacks counts as this PR's addition.
+ ch_migrations A "$DIFF_BASE" | comm -12 - "$RUNNER_TEMP/ch-master-added.txt" > "$RUNNER_TEMP/ch-migrations-added.txt"
+ ch_migrations AM "$DIFF_BASE" | comm -12 - "$RUNNER_TEMP/ch-master-changed.txt" > "$RUNNER_TEMP/ch-migrations-changed.txt"
+ cat "$RUNNER_TEMP/ch-migrations-changed.txt"
+
+ - name: Check CH migrations
+ run: python manage.py test_ch_migrations_are_safe < "$RUNNER_TEMP/ch-migrations-added.txt"
- name: Render CH migration SQL per cloud environment
# CH migrations can build different `operations` lists at import time depending on
@@ -2253,7 +2267,7 @@ jobs:
id: render_ch_sql
if: github.event_name == 'pull_request'
run: |
- CHANGED=$(git diff --name-only --diff-filter=AM origin/master..HEAD | grep '^posthog/clickhouse/migrations/[0-9]' | grep -v __pycache__ || true)
+ CHANGED=$(cat "$RUNNER_TEMP/ch-migrations-changed.txt")
if [ -z "$CHANGED" ]; then
echo "No ClickHouse migrations changed."
echo "has_changes=false" >> "$GITHUB_OUTPUT"