: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(devex): fail cloud deploys on unconfigured product db routes (#70338)
Julian Bez412ed370462d
diff --git a/posthog/apps.py b/posthog/apps.pyindex a080decbd310..06c4c1e50833 100644--- a/posthog/apps.py+++ b/posthog/apps.py@@ -48,6 +48,12 @@ class PostHogConfig(AppConfig):# shell) would lose them. They live in dedicated import-light modules — never wire# ready() through an API module, even one that looks light today.import posthog.storage.checks # noqa: F401, PLC0415++ # Product-DB route checks must register even when no PRODUCT_DB_* env+ # vars are set — the unconfigured case is exactly what+ # check_product_db_routes_configured guards — and Django only imports+ # the router module when at least one route is configured.+ import posthog.product_db_router # noqa: F401, PLC0415import posthog.caching.organization_serializer_cache # noqa: F401, PLC0415import posthog.models.activity_logging.signal_handlers # noqa: F401, PLC0415diff --git a/posthog/product_db_config.py b/posthog/product_db_config.pyindex dae310ee36f7..2fc3ef2fa005 100644--- a/posthog/product_db_config.py+++ b/posthog/product_db_config.py@@ -16,6 +16,7 @@ class ProductDBRoute:app_label: strdatabase: strsource: str+ optional: bool = Falsedef routes_model(self, model: object) -> bool:model_meta = getattr(model, "_meta", None)@@ -44,11 +45,24 @@ def load_product_db_routes(base_dir: Path | str) -> tuple[ProductDBRoute, ...]:)continue+ optional = route_config.get("optional", False)+ if not isinstance(optional, bool):+ # Fail closed: a quoted value like "false" is a truthy string, and+ # treating it as optional would suppress the deploy-gating check.+ logger.warning(+ "Non-boolean 'optional' value %r for route %r in %s; treating the route as required",+ optional,+ app_label,+ config_path,+ )+ optional = False+routes.append(ProductDBRoute(app_label=app_label,database=database,source=str(config_path),+ optional=optional,))diff --git a/posthog/product_db_router.py b/posthog/product_db_router.pyindex 04053fba2fc4..7b8b77bd6d78 100644--- a/posthog/product_db_router.py+++ b/posthog/product_db_router.py@@ -3,10 +3,11 @@ from __future__ import annotationsfrom functools import lru_cachefrom django.conf import settings-from django.core.checks import Error, register+from django.core.checks import CheckMessage, Error, Warning, registerfrom posthog.product_db_config import ProductDBRoute, load_product_db_routesfrom posthog.settings.base_variables import TEST+from posthog.settings.utils import DEPLOYED_CLOUD_DEPLOYMENTS@lru_cache(maxsize=1)@@ -85,3 +86,46 @@ def check_product_db_routes(app_configs, **kwargs):app_label_to_database[route.app_label] = route.databasereturn errors+++def product_db_routes_configured_errors(routes: tuple[ProductDBRoute, ...]) -> list[CheckMessage]:+ # Only enforced on deployed cloud environments, where charts always injects+ # the PRODUCT_DB_* env vars. E2E (local cloud-features dev) and self-hosted+ # (no CLOUD_DEPLOYMENT) intentionally run product models on the default+ # database instead. DEBUG needs no guard: settings import rejects DEBUG on+ # deployed cloud (assert_debug_not_in_production, same deployment tuple).+ if settings.TEST:+ return []+ if (settings.CLOUD_DEPLOYMENT or "").upper() not in DEPLOYED_CLOUD_DEPLOYMENTS:+ return []++ messages: list[CheckMessage] = []+ for route in routes:+ configured = f"{route.database}_db_writer" in settings.DATABASES+ if route.optional and configured:+ messages.append(+ Warning(+ f"Product database '{route.database}' (app '{route.app_label}') is configured but "+ f"still marked 'optional: true' in {route.source}.",+ hint="Once the database is provisioned in every environment, remove the 'optional' "+ "flag so a missing connection fails deploys instead of silently falling back.",+ id="posthog.W001",+ )+ )+ elif not route.optional and not configured:+ env_var = f"PRODUCT_DB_{route.database.upper()}_WRITER_URL"+ messages.append(+ Error(+ f"Product database '{route.database}' (app '{route.app_label}') has no connection configured, "+ "so its models would silently fall back to the default database.",+ hint=f"Set {env_var} in the deployment, or mark the route 'optional: true' in {route.source} "+ "while the database is still being provisioned.",+ id="posthog.E005",+ )+ )+ return messages+++@register()+def check_product_db_routes_configured(app_configs, **kwargs):+ return product_db_routes_configured_errors(get_product_db_routes())diff --git a/posthog/settings/data_stores.py b/posthog/settings/data_stores.pyindex 9ca7405fb765..590ecdc4554b 100644--- a/posthog/settings/data_stores.py+++ b/posthog/settings/data_stores.py@@ -209,6 +209,9 @@ for route in product_routes:writer_url = f"postgres://{PG_USER}:{PG_PASSWORD}@{PG_HOST}:{PG_PORT}/{PG_DATABASE}_{db}"if not writer_url:+ # Intentional fail-open outside deployed cloud: self-hosted runs product+ # models on the default database. On cloud, check_product_db_routes_configured+ # fails the deploy's migrate step for non-optional routes instead.continuePRODUCT_DB_WRITER_URLS[db] = writer_urldiff --git a/posthog/settings/utils.py b/posthog/settings/utils.pyindex fa112d01e042..2f6abc77646f 100644--- a/posthog/settings/utils.py+++ b/posthog/settings/utils.py@@ -7,6 +7,7 @@ from django.core.exceptions import ImproperlyConfiguredfrom posthog.utils import str_to_bool__all__ = [+ "DEPLOYED_CLOUD_DEPLOYMENTS","assert_debug_not_in_production","generate_rsa_private_key_pem","get_from_env",@@ -14,6 +15,10 @@ __all__ = ["str_to_bool",]+# Deployed, charts-managed cloud environments. E2E is cloud-like (is_cloud()+# includes it) but only runs locally and in automated tests, so it's not listed.+DEPLOYED_CLOUD_DEPLOYMENTS: tuple[str, ...] = ("US", "EU", "DEV")+def assert_debug_not_in_production(*, debug: bool, cloud_deployment: Optional[str], test: bool) -> None:"""Refuse to boot with DEBUG enabled on a deployed cloud environment (US/EU/DEV).@@ -23,7 +28,7 @@ def assert_debug_not_in_production(*, debug: bool, cloud_deployment: Optional[stTEST is excluded because the suite runs with DEBUG=1 (see posthog/settings/overrides.py). E2E isnot listed: it runs only in automated tests and never sets DEBUG, so the guard can't fire there."""- if debug and not test and (cloud_deployment or "").upper() in ("US", "EU", "DEV"):+ if debug and not test and (cloud_deployment or "").upper() in DEPLOYED_CLOUD_DEPLOYMENTS:raise ImproperlyConfigured(f"DEBUG must not be enabled on deployed cloud environments (CLOUD_DEPLOYMENT={cloud_deployment!r}). ""Unset DEBUG. Developing cloud-only features locally? Use CLOUD_DEPLOYMENT=E2E instead — "diff --git a/posthog/test/test_product_db_router.py b/posthog/test/test_product_db_router.pyindex 9dd445af4242..105ff639063d 100644--- a/posthog/test/test_product_db_router.py+++ b/posthog/test/test_product_db_router.py@@ -1,10 +1,18 @@+import tempfilefrom pathlib import Pathfrom types import SimpleNamespacefrom django.test import SimpleTestCase, override_settings+from parameterized import parameterized+from posthog.product_db_config import ProductDBRoute, load_product_db_routes-from posthog.product_db_router import ProductDBRouter, check_product_db_routes, get_product_db_routes+from posthog.product_db_router import (+ ProductDBRouter,+ check_product_db_routes,+ get_product_db_routes,+ product_db_routes_configured_errors,+)FAKE_PRODUCT_DATABASES: dict[str, dict] = {"default": {},@@ -13,19 +21,20 @@ FAKE_PRODUCT_DATABASES: dict[str, dict] = {}+def _visual_review_route(optional: bool = False) -> ProductDBRoute:+ return ProductDBRoute(+ app_label="visual_review",+ database="visual_review",+ source="products/db_routing.yaml",+ optional=optional,+ )++@override_settings(DATABASES=FAKE_PRODUCT_DATABASES)class TestProductDBRouter(SimpleTestCase):def setUp(self) -> None:super().setUp()- self.router = ProductDBRouter(- routes=(- ProductDBRoute(- app_label="visual_review",- database="visual_review",- source="products/db_routing.yaml",- ),- )- )+ self.router = ProductDBRouter(routes=(_visual_review_route(),))def test_routes_visual_review_model_to_configured_aliases(self) -> None:model = SimpleNamespace(_meta=SimpleNamespace(app_label="visual_review", model_name="run"))@@ -42,15 +51,7 @@ class TestProductDBRouter(SimpleTestCase):@override_settings(DATABASES={"default": {}})def test_only_enables_routes_with_configured_aliases(self) -> None:- router = ProductDBRouter(- routes=(- ProductDBRoute(- app_label="visual_review",- database="visual_review",- source="products/db_routing.yaml",- ),- )- )+ router = ProductDBRouter(routes=(_visual_review_route(),))model = SimpleNamespace(_meta=SimpleNamespace(app_label="visual_review", model_name="run"))@@ -67,6 +68,29 @@ class TestProductDBRouteLoading(SimpleTestCase):self.assertEqual(visual_review_routes[0].database, "visual_review")self.assertTrue(visual_review_routes[0].source.endswith("products/db_routing.yaml"))+ def test_parses_optional_flag(self) -> None:+ with tempfile.TemporaryDirectory() as base_dir:+ config_path = Path(base_dir) / "products" / "db_routing.yaml"+ config_path.parent.mkdir(parents=True)+ config_path.write_text(+ "routes:\n"+ " - app_label: staged_product\n"+ " database: staged_product\n"+ " optional: true\n"+ " - app_label: established_product\n"+ " database: established_product\n"+ " - app_label: quoted_product\n"+ " database: quoted_product\n"+ ' optional: "false"\n'+ )++ routes = {route.app_label: route for route in load_product_db_routes(base_dir)}++ self.assertTrue(routes["staged_product"].optional)+ self.assertFalse(routes["established_product"].optional)+ # Non-boolean values fail closed: a quoted "false" is a truthy string.+ self.assertFalse(routes["quoted_product"].optional)+class TestProductDBRouteChecks(SimpleTestCase):@override_settings(BASE_DIR=Path(__file__).resolve().parents[2])@@ -75,3 +99,40 @@ class TestProductDBRouteChecks(SimpleTestCase):self.addCleanup(get_product_db_routes.cache_clear)self.assertEqual(check_product_db_routes(None), [])+++class TestProductDBRoutesConfiguredCheck(SimpleTestCase):+ @parameterized.expand(+ [+ ("enforced_on_cloud", "US", False, 1),+ ("self_hosted_unenforced", None, False, 0),+ ("e2e_unenforced", "E2E", False, 0),+ ("optional_route_allowed", "US", True, 0),+ ]+ )+ def test_missing_writer_alias(self, _name, cloud_deployment, optional, expected_errors) -> None:+ route = _visual_review_route(optional=optional)+ with override_settings(DATABASES={"default": {}}, CLOUD_DEPLOYMENT=cloud_deployment, TEST=False):+ errors = product_db_routes_configured_errors((route,))++ self.assertEqual(len(errors), expected_errors)+ if expected_errors:+ self.assertEqual(errors[0].id, "posthog.E005")++ def test_configured_route_passes(self) -> None:+ with override_settings(+ DATABASES={"default": {}, "visual_review_db_writer": {}},+ CLOUD_DEPLOYMENT="US",+ TEST=False,+ ):+ self.assertEqual(product_db_routes_configured_errors((_visual_review_route(),)), [])++ def test_configured_optional_route_warns_to_remove_flag(self) -> None:+ with override_settings(+ DATABASES={"default": {}, "visual_review_db_writer": {}},+ CLOUD_DEPLOYMENT="US",+ TEST=False,+ ):+ messages = product_db_routes_configured_errors((_visual_review_route(optional=True),))++ self.assertEqual([message.id for message in messages], ["posthog.W001"])diff --git a/products/README.md b/products/README.mdindex 6f52339c8cfb..4ef57a9c5001 100644--- a/products/README.md+++ b/products/README.md@@ -230,7 +230,9 @@ This automatically:- Runs migrations via `bin/migrate` (calls `migrate_product_databases` management command)- Creates the database in local Docker via the Postgres init script-Locally (`DEBUG=1`), it auto-connects to `posthog_visual_review` on localhost. In prod, the infrastructure handles env vars and connections automatically. If the env var is absent, the route is silently skipped.+Locally (`DEBUG=1`), it auto-connects to `posthog_visual_review` on localhost. Self-hosted and local setups skip a route silently if its env var is absent — the product's models just run on the default database.++On PostHog Cloud (`CLOUD_DEPLOYMENT` set to a deployed environment), that silent fallback is dangerous: a misconfigured deploy would misroute writes without anyone noticing. There, a missing connection for a non-optional route fails Django's system checks, which blocks the deploy's `migrate` step. New routes are scaffolded with `optional: true` for exactly this reason — it's a staged rollout escape hatch for when code lands before infra has provisioned the database. Remove the flag once the database is up, so a missing connection fails loudly from then on — a system-check warning nags about routes that are configured but still marked optional.### Adding a new product databasediff --git a/tools/hogli-commands/hogli_commands/product/scaffold.py b/tools/hogli-commands/hogli_commands/product/scaffold.pyindex e1ec9c7dff27..3f1c7fb02529 100644--- a/tools/hogli-commands/hogli_commands/product/scaffold.py+++ b/tools/hogli-commands/hogli_commands/product/scaffold.py@@ -140,7 +140,7 @@ def _get_existing_databases() -> list[str]:def _add_to_db_routing(product_name: str, database_name: str, *, dry_run: bool) -> None:- route_entry = f" - app_label: {product_name}\n database: {database_name}\n"+ route_entry = f" - app_label: {product_name}\n database: {database_name}\n optional: true\n"def write(content: str) -> str:return content.rstrip() + "\n" + route_entry@@ -190,6 +190,11 @@ def _prompt_for_separate_db(name: str) -> tuple[bool, str | None]:"be provisioned by #team-infrastructure (Terraform + charts).",fg="yellow",)+ click.echo(+ " The route starts with 'optional: true' in db_routing.yaml, so cloud deploys "+ "won't fail before infra provisions the database. Remove that line once it's "+ "provisioned, so cloud deploys fail loudly if the connection ever goes missing."+ )existing_dbs = _get_existing_databases()if existing_dbs:click.echo(f" Existing databases: {', '.join(existing_dbs)}")