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): post ClickHouse migration SQL per environment as PR comment (#59220)

Paweł Szczurc6e37fa0f529
diff --git a/.github/workflows/ci-backend.yml b/.github/workflows/ci-backend.yml
index b828b1093fdd..5698369431da 100644
--- a/.github/workflows/ci-backend.yml
+++ b/.github/workflows/ci-backend.yml
@@ -1025,22 +1025,106 @@ jobs:
- name: Render CH migration SQL per cloud environment
# CH migrations can build different `operations` lists at import time depending on
- # `settings.CLOUD_DEPLOYMENT` (e.g. cloud-only Kafka tables). Print the rendered SQL
- # each environment will execute so reviewers can spot per-env divergence and verify
- # gated branches don't sneak in ON CLUSTER or other forbidden patterns.
+ # `settings.CLOUD_DEPLOYMENT` (e.g. cloud-only Kafka tables). Render the SQL each
+ # environment will execute so reviewers can spot per-env divergence and verify gated
+ # branches don't sneak in ON CLUSTER or other forbidden patterns. We render once per
+ # environment and reuse the output both for the Actions log groups and the PR comment
+ # (environment -> node type(s) -> SQL). Environments that render identically are
+ # grouped together; if all environments match, the environment level is collapsed.
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)
+ {
+ echo '<!-- ch-migration-sql -->'
+ echo '## ClickHouse migration SQL per cloud environment'
+ echo ''
+ } > ch_migration_sql_comment.md
if [ -z "$CHANGED" ]; then
echo "No ClickHouse migrations changed."
+ echo '_No ClickHouse migrations changed in this PR._' >> ch_migration_sql_comment.md
exit 0
fi
- for deployment in '' US EU DEV; do
- label="${deployment:-<unset>}"
- echo "::group::CLOUD_DEPLOYMENT=${label}"
- CLOUD_DEPLOYMENT="${deployment}" python manage.py print_ch_migration_sql ${CHANGED} || true
+ mkdir -p ch_sql_env
+ DEPLOYMENTS=('' US EU DEV)
+ LABELS=(unset US EU DEV)
+ # Bucket environments by identical rendered output (parallel indexed arrays;
+ # avoids bash 4 associative arrays) so divergent SQL prints once.
+ BUCKET_HASH=()
+ BUCKET_LABEL=()
+ BUCKET_FILE=()
+ for idx in "${!DEPLOYMENTS[@]}"; do
+ file="ch_sql_env/${idx}.md"
+ # Render once per environment; the same output feeds both the log group and the comment.
+ # On failure (e.g. an import error in the migration) write a visible marker rather than
+ # silently dropping the environment — stderr still shows in the step log for debugging.
+ if ! CLOUD_DEPLOYMENT="${DEPLOYMENTS[$idx]}" python manage.py print_ch_migration_sql --format markdown ${CHANGED} > "$file"; then
+ echo '- _⚠️ failed to render SQL for this environment — see the workflow logs_' > "$file"
+ fi
+ echo "::group::CLOUD_DEPLOYMENT=${LABELS[$idx]}"
+ cat "$file"
echo "::endgroup::"
+ h=$(sha1sum "$file" | cut -d' ' -f1)
+ found=-1
+ for b in "${!BUCKET_HASH[@]}"; do
+ if [ "${BUCKET_HASH[$b]}" = "$h" ]; then found=$b; break; fi
+ done
+ if [ "$found" -ge 0 ]; then
+ BUCKET_LABEL[$found]="${BUCKET_LABEL[$found]}, ${LABELS[$idx]}"
+ else
+ BUCKET_HASH+=("$h")
+ BUCKET_LABEL+=("${LABELS[$idx]}")
+ BUCKET_FILE+=("$file")
+ fi
done
+ if [ "${#BUCKET_HASH[@]}" -eq 1 ]; then
+ # Every environment renders the same SQL — collapse the environment level.
+ echo '_Identical across all cloud environments (unset, US, EU, DEV)._' >> ch_migration_sql_comment.md
+ echo '' >> ch_migration_sql_comment.md
+ cat "${BUCKET_FILE[0]}" >> ch_migration_sql_comment.md
+ else
+ for b in "${!BUCKET_HASH[@]}"; do
+ echo "- **${BUCKET_LABEL[$b]}**" >> ch_migration_sql_comment.md
+ sed 's/^/ /' "${BUCKET_FILE[$b]}" >> ch_migration_sql_comment.md
+ done
+ fi
+
+ - name: Post CH migration SQL PR comment
+ # Sticky comment: find the marker and update in place so pushes don't spam the PR.
+ # GITHUB_TOKEN is read-only for fork PRs, so only comment on same-repo PRs.
+ if: github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository
+ uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8
+ with:
+ github-token: ${{ secrets.GITHUB_TOKEN }}
+ script: |
+ const fs = require('fs');
+ const marker = '<!-- ch-migration-sql -->';
+ let body = fs.readFileSync('ch_migration_sql_comment.md', 'utf8');
+ const LIMIT = 65000; // GitHub caps comment bodies at 65536 chars
+ if (body.length > LIMIT) {
+ const runUrl = `${context.serverUrl}/${context.repo.owner}/${context.repo.repo}/actions/runs/${context.runId}`;
+ body = body.slice(0, LIMIT - 400) + `\n\n_…truncated. See the full SQL in the [workflow logs](${runUrl})._`;
+ }
+ const { data: comments } = await github.rest.issues.listComments({
+ owner: context.repo.owner,
+ repo: context.repo.repo,
+ issue_number: context.issue.number,
+ });
+ const existing = comments.find((c) => c.body.includes(marker));
+ if (existing) {
+ await github.rest.issues.updateComment({
+ owner: context.repo.owner,
+ repo: context.repo.repo,
+ comment_id: existing.id,
+ body,
+ });
+ } else {
+ await github.rest.issues.createComment({
+ owner: context.repo.owner,
+ repo: context.repo.repo,
+ issue_number: context.issue.number,
+ body,
+ });
+ }
- name: Install pnpm
uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
diff --git a/posthog/clickhouse/client/migration_tools.py b/posthog/clickhouse/client/migration_tools.py
index 244df1c27cf6..0f0d8072883f 100644
--- a/posthog/clickhouse/client/migration_tools.py
+++ b/posthog/clickhouse/client/migration_tools.py
@@ -111,6 +111,9 @@ def run_sql_with_exceptions(
# Use original_node_roles (before debug override) for validation purposes
operation._sql = sql
operation._node_roles = original_node_roles
+ # node_roles_list reflects the debug/hobby override (e.g. collapsed to NodeRole.ALL),
+ # i.e. the roles this migration actually targets under the current settings.
+ operation._effective_node_roles = node_roles_list
operation._sharded = sharded
operation._is_alter_on_replicated_table = is_alter_on_replicated_table
diff --git a/posthog/management/commands/print_ch_migration_sql.py b/posthog/management/commands/print_ch_migration_sql.py
index d134837767fa..c4047a9baea7 100644
--- a/posthog/management/commands/print_ch_migration_sql.py
+++ b/posthog/management/commands/print_ch_migration_sql.py
@@ -7,6 +7,9 @@ to ClickHouse. It imports the requested migration modules, walks their
attaches). It is the basis for the CI step that prints the SQL each migration
will execute under each ``CLOUD_DEPLOYMENT`` value (cloud-gated migrations build
different ``operations`` lists at import time).
+
+With ``--format markdown`` it instead emits a nested markdown list
+(environment -> node type(s) -> migration -> SQL) suitable for posting as a PR comment.
"""
import importlib
@@ -31,10 +34,30 @@ class Command(BaseCommand):
nargs="+",
help="Migration names or paths (e.g. 0247_foo or posthog/clickhouse/migrations/0247_foo.py).",
)
+ parser.add_argument(
+ "--format",
+ choices=["text", "markdown"],
+ default="text",
+ help="Output format. 'text' (default) for plain log output; 'markdown' for a nested PR-comment list.",
+ )
def handle(self, *args, **options):
+ # Under TEST/E2E settings the MergeTree engine helper appends a random UUID to each
+ # ReplicatedMergeTree ZooKeeper path (to avoid clashes between test runs). That makes
+ # the rendered SQL non-deterministic across environments, breaking per-env comparison
+ # and hiding real divergence. Render production-deterministic ZK paths instead — the
+ # engine reads these flags off django.conf.settings at SQL-build time, so flip them
+ # before importing the migration modules below.
+ settings.TEST = False
+ settings.E2E_TESTING = False
+
names = [self._normalize(name) for name in options["migrations"]]
+ if options["format"] == "markdown":
+ self._handle_markdown(names)
+ else:
+ self._handle_text(names)
+ def _handle_text(self, names: list[str]) -> None:
print(f"# CLOUD_DEPLOYMENT={settings.CLOUD_DEPLOYMENT!r}")
for name in names:
module = importlib.import_module(f"{MIGRATIONS_PACKAGE_NAME}.{name}")
@@ -54,6 +77,47 @@ class Command(BaseCommand):
print(f"\n### op #{idx}")
print(indent(sql, " "))
+ def _handle_markdown(self, names: list[str]) -> None:
+ # Emit only the node type(s) -> SQL list, without an environment header. The
+ # CI step renders this once per CLOUD_DEPLOYMENT and adds the environment level
+ # itself, collapsing it when environments render identically. We don't nest by
+ # migration: CI enforces one migration file per PR, and if several are passed
+ # their operations are merged by node role (first-seen order preserved).
+ groups: dict[str, list[str]] = {}
+ notes: list[str] = []
+ for name in names:
+ module = importlib.import_module(f"{MIGRATIONS_PACKAGE_NAME}.{name}")
+ operations = getattr(module, "operations", None)
+ if operations is None:
+ notes.append(f"`{name}` — no `operations` attribute")
+ continue
+ if not operations:
+ notes.append(f"`{name}` — operations list is empty under this environment")
+ continue
+ for op in operations:
+ sql = getattr(op, "_sql", None)
+ if sql is None:
+ continue
+ groups.setdefault(self._node_role_label(op), []).append(sql)
+
+ if not groups and not notes:
+ print("- _no SQL operations under this environment_")
+ for note in notes:
+ print(f"- {note}")
+ for label, sqls in groups.items():
+ print(f"- **{label}**")
+ for sql in sqls:
+ print(" ```sql")
+ print(indent(sql.strip(), " "))
+ print(" ```")
+
+ @staticmethod
+ def _node_role_label(op) -> str:
+ roles = getattr(op, "_effective_node_roles", None) or getattr(op, "_node_roles", None)
+ if not roles:
+ return "data (default)"
+ return ", ".join(sorted(getattr(role, "value", str(role)) for role in roles))
+
@staticmethod
def _normalize(value: str) -> str:
cleaned = value.strip()