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(migrations): guide operators off an unsupported postgresql (#96973)

posthog[bot]a4c06d0b69ec
diff --git a/bin/migrate b/bin/migrate
index ee8b72c7995f..06d8623b1071 100755
--- a/bin/migrate
+++ b/bin/migrate
@@ -92,6 +92,8 @@ if [ "$RUN_POSTGRES" = "1" ]; then
MIGRATE_MAX_RETRIES=${MIGRATE_MAX_RETRIES:-10}
MIGRATE_RETRY_DELAY=${MIGRATE_RETRY_DELAY:-3}
MIGRATE_BACKOFF=${MIGRATE_BACKOFF:-2}
+ # Must match UNSUPPORTED_DATABASE_EXIT_CODE in posthog/management/commands/migrate.py
+ MIGRATE_UNSUPPORTED_DATABASE=78
MIGRATE_ATTEMPT=1
MIGRATE_SUCCESS=false
@@ -119,10 +121,17 @@ if [ "$RUN_POSTGRES" = "1" ]; then
if $MIGRATE_CMD && python manage.py migrate_product_databases; then
MIGRATE_SUCCESS=true
break
+ else
+ MIGRATE_STATUS=$?
fi
echo "[migrate] Django migration failed"
+ if [ "$MIGRATE_STATUS" = "$MIGRATE_UNSUPPORTED_DATABASE" ]; then
+ echo "[migrate] the database version is not supported, so retrying cannot help"
+ break
+ fi
+
if [ $MIGRATE_ATTEMPT -ge $MIGRATE_MAX_RETRIES ]; then
echo "[migrate] max retries reached, aborting"
break
diff --git a/posthog/management/commands/migrate.py b/posthog/management/commands/migrate.py
index 7f8ef5a8ca9e..629e62dabd71 100644
--- a/posthog/management/commands/migrate.py
+++ b/posthog/management/commands/migrate.py
@@ -18,11 +18,13 @@ import shutil
import warnings
import subprocess
from pathlib import Path
+from typing import TYPE_CHECKING
from django.conf import settings
from django.core.management import call_command
+from django.core.management.base import CommandError
from django.core.management.commands.migrate import Command as DjangoMigrateCommand
-from django.db import DEFAULT_DB_ALIAS
+from django.db import DEFAULT_DB_ALIAS, NotSupportedError
from django.db.migrations.recorder import MigrationRecorder
from posthog.cloud_utils import is_ci
@@ -38,6 +40,9 @@ from common.migration_utils import (
temporary_migration_file,
)
+if TYPE_CHECKING:
+ from django.db.backends.base.base import BaseDatabaseWrapper
+
def get_managed_apps() -> set[str]:
"""Get apps we manage migrations for (PostHog apps, not third-party)."""
@@ -190,6 +195,38 @@ def rollback_orphaned_migration(app_label: str, migration_name: str, previous: s
return False
+# EX_CONFIG from sysexits.h. bin/migrate reads it to skip its retries.
+UNSUPPORTED_DATABASE_EXIT_CODE = 78
+
+
+def check_database_version(connection: BaseDatabaseWrapper) -> None:
+ """Stop with recovery steps when the server is older than Django supports.
+
+ Django refuses to connect below its minimum version, so without this the run
+ dies on its first query with a raw driver error and no way forward.
+ """
+ try:
+ connection.ensure_connection()
+ except NotSupportedError as exc:
+ raise CommandError(
+ f"{exc}\n\n"
+ "No migration ran, so the database is unchanged. Upgrade the PostgreSQL "
+ "server to a supported version, then deploy again.\n\n"
+ "On a Docker Compose deployment:\n"
+ " 1. Back up the data. Stop here if this reports an error:\n"
+ " docker compose exec -T db pg_dumpall --clean -U posthog > posthog-backup.sql && gzip -f posthog-backup.sql\n"
+ " 2. Check that the backup is complete. The last lines must say the cluster dump is complete:\n"
+ " gunzip -c posthog-backup.sql.gz | tail -3\n"
+ " 3. Stop the stack, then delete the old postgres-data volume. The backup file is now the only copy of the data.\n"
+ " 4. Start the db service again. It uses the PostgreSQL version PostHog pins.\n"
+ " 5. Restore the data. Errors about the posthog role and database already existing are expected:\n"
+ " gunzip -c posthog-backup.sql.gz | docker compose exec -T db psql -U posthog\n"
+ " 6. Check that the data is back. This must print a count, not an error:\n"
+ " docker compose exec -T db psql -U posthog -c 'select count(*) from django_migrations'",
+ returncode=UNSUPPORTED_DATABASE_EXIT_CODE,
+ ) from exc
+
+
class Command(DjangoMigrateCommand):
"""Extended migrate command with caching and orphan detection."""
@@ -239,6 +276,8 @@ class Command(DjangoMigrateCommand):
connection = connections[database]
+ check_database_version(connection)
+
# Check for orphaned migrations before proceeding
if not skip_orphan_check and not options.get("check_unapplied"):
try:
diff --git a/posthog/management/commands/test/test_migrate.py b/posthog/management/commands/test/test_migrate.py
new file mode 100644
index 000000000000..b3b4051df761
--- /dev/null
+++ b/posthog/management/commands/test/test_migrate.py
@@ -0,0 +1,31 @@
+from unittest.mock import MagicMock
+
+from django.core.management.base import CommandError
+from django.db import NotSupportedError, OperationalError
+from django.test import SimpleTestCase
+
+from posthog.management.commands.migrate import UNSUPPORTED_DATABASE_EXIT_CODE, check_database_version
+
+
+def fake_connection(error: Exception) -> MagicMock:
+ connection = MagicMock()
+ connection.ensure_connection.side_effect = error
+ return connection
+
+
+class TestCheckDatabaseVersion(SimpleTestCase):
+ def test_stops_with_recovery_steps_on_an_unsupported_server(self):
+ error = NotSupportedError("PostgreSQL 14 or later is required (found 11.22).")
+
+ with self.assertRaises(CommandError) as raised:
+ check_database_version(fake_connection(error))
+
+ assert raised.exception.returncode == UNSUPPORTED_DATABASE_EXIT_CODE
+ assert "found 11.22" in str(raised.exception)
+ assert "pg_dumpall" in str(raised.exception)
+
+ def test_lets_a_transient_connection_failure_through(self):
+ error = OperationalError("could not connect to server")
+
+ with self.assertRaises(OperationalError):
+ check_database_version(fake_connection(error))
diff --git a/posthog/settings/service_requirements.py b/posthog/settings/service_requirements.py
index 475b6d217d55..668305c91b1b 100644
--- a/posthog/settings/service_requirements.py
+++ b/posthog/settings/service_requirements.py
@@ -17,7 +17,8 @@ if SKIP_SERVICE_VERSION_REQUIREMENTS and not (TEST or DEBUG):
logger.warning(["Skipping service version requirements. This is dangerous and PostHog might not work as expected!"])
SERVICE_VERSION_REQUIREMENTS = [
- ServiceVersionRequirement(service="postgresql", supported_version=">=11.0.0,<=14.1.0"),
+ # Floor tracks Django's own minimum: below it the driver refuses to connect.
+ ServiceVersionRequirement(service="postgresql", supported_version=">=14.0.0"),
ServiceVersionRequirement(service="redis", supported_version=">=7.0.0,<8.0.0"),
ServiceVersionRequirement(service="clickhouse", supported_version=">=24.8,<=25.12"),
]
diff --git a/posthog/test/test_version_requirement.py b/posthog/test/test_version_requirement.py
index 1d2dbc770089..f6bc251fa409 100644
--- a/posthog/test/test_version_requirement.py
+++ b/posthog/test/test_version_requirement.py
@@ -1,5 +1,7 @@
from unittest.mock import patch
+from django.conf import settings
+from django.db.backends.postgresql.features import DatabaseFeatures as PostgresFeatures
from django.test.testcases import TestCase
from semantic_version.base import SimpleSpec, Version
@@ -95,3 +97,12 @@ class TestServiceVersionRequirement(TestCase):
v5 = ServiceVersionRequirement(service="postgresql", supported_version=">=11.0.0,<=13.0.0")
in_range, _ = v5.is_service_in_accepted_version()
self.assertEqual(in_range, True)
+
+ def test_postgres_requirement_starts_at_the_version_django_needs(self):
+ requirement = next(r for r in settings.SERVICE_VERSION_REQUIREMENTS if r.service == "postgresql")
+ minimum = PostgresFeatures.minimum_database_version
+ assert minimum is not None
+ major = minimum[0]
+
+ assert requirement.supported_version.match(Version(major=major, minor=0, patch=0))
+ assert not requirement.supported_version.match(Version(major=major - 1, minor=99, patch=0))