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(devex): prime test_posthog in django and dagster CI (#54292)

Julian Bez3799b31f4fec
diff --git a/.github/workflows/ci-backend.yml b/.github/workflows/ci-backend.yml
index ab015350be43..4997a58ef6bb 100644
--- a/.github/workflows/ci-backend.yml
+++ b/.github/workflows/ci-backend.yml
@@ -417,6 +417,26 @@ jobs:
CLICKHOUSE_SERVER_IMAGE: clickhouse/clickhouse-server:26.3.9.8
run: bin/ci-wait-for-docker wait
+ - name: Restore schema cache from master
+ if: ${{ github.event_name == 'pull_request' }}
+ uses: actions/cache/restore@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 # v5
+ with:
+ path: schema.sql.gz
+ key: posthog-schema-master-${{ github.sha }}
+ restore-keys: posthog-schema-master-
+
+ - name: Prime test_posthog from cached schema
+ # No-op on cache miss; pytest --reuse-db falls back to a full migrate.
+ if: ${{ github.event_name == 'pull_request' }}
+ run: |
+ if [ ! -f schema.sql.gz ]; then
+ echo "::notice::Schema cache miss — pytest --reuse-db will run full migrations"
+ exit 0
+ fi
+ mkdir -p .postgres-backups
+ mv schema.sql.gz .postgres-backups/schema-latest.sql.gz
+ ./bin/hogli db:restore-test-db
+
- name: Register Temporal search attributes
run: |
bin/wait-for-docker temporal
@@ -1269,6 +1289,26 @@ jobs:
CLICKHOUSE_SERVER_IMAGE: ${{ matrix.clickhouse-server-image || needs.get_clickhouse_versions.outputs.oldest_supported_image }}
run: bin/ci-wait-for-docker wait
+ - name: Restore schema cache from master
+ if: ${{ github.event_name == 'pull_request' }}
+ uses: actions/cache/restore@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 # v5
+ with:
+ path: schema.sql.gz
+ key: posthog-schema-master-${{ github.sha }}
+ restore-keys: posthog-schema-master-
+
+ - name: Prime test_posthog from cached schema
+ # No-op on cache miss; pytest --reuse-db falls back to a full migrate.
+ if: ${{ github.event_name == 'pull_request' }}
+ run: |
+ if [ ! -f schema.sql.gz ]; then
+ echo "::notice::Schema cache miss — pytest --reuse-db will run full migrations"
+ exit 0
+ fi
+ mkdir -p .postgres-backups
+ mv schema.sql.gz .postgres-backups/schema-latest.sql.gz
+ ./bin/hogli db:restore-test-db
+
- name: Determine if --snapshot-update should be on
# UPDATE mode: human commits - update snapshots
# CHECK mode: bot commits (after snapshot update) - verify snapshots match exactly
@@ -1320,7 +1360,7 @@ jobs:
shell: bash
run: | # async_migrations covered in ci-async-migrations.yml
set +e
- pytest -v --tb=short ${{
+ pytest -v --tb=short --reuse-db ${{
matrix.compat
&& env.CLICKHOUSE_COMPAT_PYTEST_TARGETS
|| (
@@ -1387,7 +1427,7 @@ jobs:
MODAL_TOKEN_SECRET: ${{ needs.changes.outputs.tasks_temporal == 'true' && secrets.MODAL_TOKEN_SECRET || '' }}
run: |
set +e
- pytest -v --tb=short --timeout=600 --timeout-method=thread posthog/temporal products/batch_exports/backend/tests/temporal products/tasks/backend/temporal -m "not async_migrations" \
+ pytest -v --tb=short --reuse-db --timeout=600 --timeout-method=thread posthog/temporal products/batch_exports/backend/tests/temporal products/tasks/backend/temporal -m "not async_migrations" \
--splits ${{ matrix.concurrency }} --group ${{ matrix.group }} \
--durations=100 --durations-min=1.0 --store-durations \
--splitting-algorithm=duration_based_chunks \
diff --git a/.github/workflows/ci-dagster.yml b/.github/workflows/ci-dagster.yml
index 23047c25aead..dbc364119de1 100644
--- a/.github/workflows/ci-dagster.yml
+++ b/.github/workflows/ci-dagster.yml
@@ -270,23 +270,54 @@ jobs:
docker compose -f docker-compose.dev.yml exec -T db \
psql -U posthog -c "CREATE DATABASE test_dagster;"
- - name: Run migrations
+ - name: Restore schema cache from master
+ if: ${{ github.event_name == 'pull_request' }}
+ uses: actions/cache/restore@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 # v5
+ id: schema-cache
+ with:
+ path: schema.sql.gz
+ key: posthog-schema-master-${{ github.sha }}
+ restore-keys: posthog-schema-master-
+
+ - name: Prime test_posthog and posthog from cached schema (PR)
+ # Primes both test_posthog (used by pytest --reuse-db) and the prod-style
+ # posthog db (read by migrate_clickhouse → InstanceSetting). pytest's
+ # keepdb=True path layers any PR-added migrations on top.
+ # On cache miss, fall through to a full migrate so migrate_clickhouse works.
+ if: ${{ github.event_name == 'pull_request' }}
+ run: |
+ if [ ! -f schema.sql.gz ]; then
+ echo "::notice::Schema cache miss — falling through to full migrate"
+ python manage.py migrate
+ exit 0
+ fi
+ mkdir -p .postgres-backups
+ mv schema.sql.gz .postgres-backups/schema-latest.sql.gz
+ ./bin/hogli db:restore-test-db
+ gunzip -c .postgres-backups/schema-latest.sql.gz | \
+ docker compose -f docker-compose.dev.yml exec -T db psql -q -U posthog posthog
+
+ - name: Run Django migrations (master)
+ # Master pushes don't restore from cache (the artifact-producing run
+ # is in ci-backend, not here). Run a full migrate so migrate_clickhouse
+ # can read posthog_instancesetting from a populated posthog db.
+ if: ${{ github.event_name != 'pull_request' }}
+ run: python manage.py migrate
+
+ - name: Run persons migrations
run: |
- # Run Django migrations first
- python manage.py migrate
- # Then run persons migrations using sqlx
DATABASE_URL="postgres://posthog:posthog@localhost:5432/posthog_persons" \
sqlx database create
DATABASE_URL="postgres://posthog:posthog@localhost:5432/posthog_persons" \
sqlx migrate run --source rust/persons_migrations/
- name: Run clickhouse migrations
- run: |
- python manage.py migrate_clickhouse
+ run: python manage.py migrate_clickhouse
- name: Run Dagster tests
run: |
pytest posthog/dags products/**/dags \
+ --reuse-db \
--splits ${{ matrix.concurrency }} --group ${{ matrix.group }} \
--durations=100 --durations-min=1.0 --store-durations \
--splitting-algorithm=duration_based_chunks \
diff --git a/hogli.yaml b/hogli.yaml
index 01d986491e28..9d642e316b7c 100644
--- a/hogli.yaml
+++ b/hogli.yaml
@@ -527,6 +527,36 @@ db:
services:
- postgresql
- docker
+ db:prime-test-db:
+ steps:
+ - db:download-schema
+ - db:restore-test-db
+ description: Download pre-migrated schema and prime the test_posthog database for
+ pytest --reuse-db
+ services:
+ - postgresql
+ - docker
+ db:restore-test-db:
+ cmd: |
+ set -e
+ if [ ! -f .postgres-backups/schema-latest.sql.gz ]; then
+ echo "❌ No schema at .postgres-backups/schema-latest.sql.gz — run db:download-schema first"
+ exit 1
+ fi
+ # Validate up front; substitutes for `set -o pipefail` (dash doesn't support it).
+ gunzip -t .postgres-backups/schema-latest.sql.gz
+ docker compose -f docker-compose.dev.yml exec -T db psql -U posthog -c "DROP DATABASE IF EXISTS test_posthog;"
+ docker compose -f docker-compose.dev.yml exec -T db psql -U posthog -c "CREATE DATABASE test_posthog;"
+ gunzip -c .postgres-backups/schema-latest.sql.gz | docker compose -f docker-compose.dev.yml exec -T db psql -q -U posthog test_posthog
+ # Schema-only dumps skip RunPython data migrations (e.g. the Default Theme row from 0537).
+ # Reseed defaults so tests don't hit empty tables. Idempotent.
+ DATABASE_URL=postgres://posthog:posthog@localhost:5432/test_posthog python manage.py ensure_migration_defaults
+ echo "✅ Restored test_posthog from .postgres-backups/schema-latest.sql.gz"
+ description: Restore test_posthog from a local schema dump (no download). Used by
+ CI after restoring the schema from Actions cache.
+ services:
+ - postgresql
+ - docker
db:download-schema:
cmd: "set -e\nmkdir -p .postgres-backups\necho \"Finding latest CI run with migrated-schema\
\ artifact...\"\nRUN_ID=$(gh api 'repos/PostHog/posthog/actions/artifacts?name=migrated-schema&per_page=10'\
diff --git a/posthog/conftest.py b/posthog/conftest.py
index 2f84386b9154..2bde15d717af 100644
--- a/posthog/conftest.py
+++ b/posthog/conftest.py
@@ -1,5 +1,6 @@
import os
import subprocess
+from typing import Any
from urllib.parse import quote_plus
import pytest
@@ -331,40 +332,43 @@ def django_db_setup(django_db_setup, django_db_keepdb, django_db_blocker):
yield from _django_db_setup(django_db_keepdb, django_db_blocker)
[email protected](autouse=True)
-def patch_flush_command_for_persons_db(monkeypatch):
+def _patched_flush_handle(self, **options: Any) -> None:
"""
- Patch Django's flush command to handle persons database properly.
+ Patched Django flush command for two reasons:
+
+ 1. Persons database doesn't have Django's built-in tables (contenttypes,
+ permissions), so we skip post_migrate signals by truncating manually.
- Persons database doesn't have Django's built-in tables (contenttypes, permissions, etc.),
- so we need to skip emitting post_migrate signals that would try to create them.
+ 2. The schema cache can be newer than the branch code, introducing tables
+ Django doesn't know about. CASCADE lets TRUNCATE succeed even when
+ unknown FK constraints reference a table being flushed.
- This is needed for non-Django test classes (pytest, temporal, async tests).
- Django test classes handle this in _fixture_teardown in test/base.py.
+ Applied at module level (not via monkeypatch) so it stays active during
+ pytest-django's _post_teardown, which runs flush AFTER function-scoped
+ fixture teardown.
"""
- original_handle = FlushCommand.handle
-
- def patched_handle(self, **options):
- database = options.get("database")
-
- if database in ("persons_db_writer", "persons_db_reader"):
- # Manually truncate persons database tables without emitting signals
- conn = connections[database]
- with conn.cursor() as cursor:
- cursor.execute("""
- SELECT tablename FROM pg_tables
- WHERE schemaname = 'public'
- AND tablename NOT LIKE 'pg_%'
- AND tablename NOT LIKE '_sqlx_%'
- AND tablename NOT LIKE '_persons_migrations'
- """)
- tables = [row[0] for row in cursor.fetchall()]
- if tables:
- cursor.execute(f"TRUNCATE TABLE {', '.join(tables)} RESTART IDENTITY CASCADE")
- else:
- return original_handle(self, **options)
-
- monkeypatch.setattr(FlushCommand, "handle", patched_handle)
+ database = options.get("database")
+
+ if database in ("persons_db_writer", "persons_db_reader"):
+ conn = connections[database]
+ with conn.cursor() as cursor:
+ cursor.execute("""
+ SELECT tablename FROM pg_tables
+ WHERE schemaname = 'public'
+ AND tablename NOT LIKE 'pg_%'
+ AND tablename NOT LIKE '_sqlx_%'
+ AND tablename NOT LIKE '_persons_migrations'
+ """)
+ tables = [row[0] for row in cursor.fetchall()]
+ if tables:
+ cursor.execute(f"TRUNCATE TABLE {', '.join(tables)} RESTART IDENTITY CASCADE")
+ else:
+ options["allow_cascade"] = True
+ return _original_flush_handle(self, **options)
+
+
+_original_flush_handle = FlushCommand.handle
+FlushCommand.handle = _patched_flush_handle # type: ignore[method-assign] # ty: ignore[invalid-assignment]
@pytest.fixture
diff --git a/posthog/management/commands/ensure_migration_defaults.py b/posthog/management/commands/ensure_migration_defaults.py
index 801010d44870..41816d4cef3b 100644
--- a/posthog/management/commands/ensure_migration_defaults.py
+++ b/posthog/management/commands/ensure_migration_defaults.py
@@ -142,6 +142,7 @@ _PRODUCT_ANALYTICS_TEMPLATE: dict[str, Any] = {
},
],
"tags": [],
+ "scope": "global",
}
_FEATURE_FLAG_TEMPLATE: dict[str, Any] = {