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(django): remove person db connection (#66488)

Zach Brownec8087aa87e8
diff --git a/ee/clickhouse/views/groups.py b/ee/clickhouse/views/groups.py
index a30ec3010755..c308bc760105 100644
--- a/ee/clickhouse/views/groups.py
+++ b/ee/clickhouse/views/groups.py
@@ -147,7 +147,7 @@ class GroupsTypesViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
serializer_class = GroupTypeSerializer
# DRF requires a queryset for model resolution, but all actions are overridden
# to read via personhog-routed helpers — this queryset is never evaluated.
- queryset = GroupTypeMapping.objects.none() # nosemgrep: no-direct-persons-db-orm
+ queryset = GroupTypeMapping.objects.none()
pagination_class = None
sharing_enabled_actions = ["list"]
lookup_field = "group_type_index"
@@ -273,7 +273,9 @@ class CreateGroupSerializer(serializers.ModelSerializer):
class GroupsViewSet(TeamAndOrgViewSetMixin, mixins.ListModelMixin, mixins.CreateModelMixin, viewsets.GenericViewSet):
scope_object = "group"
- queryset = Group.objects.all() # nosemgrep: no-direct-persons-db-orm
+ # DRF needs a queryset for model/basename resolution, but every action is overridden
+ # to read via personhog-routed helpers — this queryset is never evaluated against the DB.
+ queryset = Group.objects.none()
pagination_class = None
serializer_classes = {
"find": FindGroupSerializer,
diff --git a/posthog/conftest.py b/posthog/conftest.py
index 8c9f79bf5088..cd1b16db9187 100644
--- a/posthog/conftest.py
+++ b/posthog/conftest.py
@@ -266,8 +266,9 @@ def _django_db_setup(django_db_keepdb, django_db_blocker):
if alias in settings.DATABASES:
settings.DATABASES[alias]["NAME"] = test_product_db_name
- # Drop Person-related tables from default database and all FK constraints
- # These tables will exist in the persons_db_writer database via sqlx migrations
+ # Drop Person-related tables from default database and all FK constraints.
+ # These tables exist only in the persons database, provisioned by sqlx migrations and
+ # reached via off-Django psycopg — never the ORM.
with django_db_blocker.unblock():
with connection.cursor() as cursor:
# Drop all FK constraints pointing to posthog_person, regardless of naming convention
@@ -293,8 +294,8 @@ def _django_db_setup(django_db_keepdb, django_db_blocker):
END $$;
""")
- # Drop all persons-related tables from default database
- # These will exist in the persons_db_writer database via sqlx migrations
+ # Drop all persons-related tables from default database. They exist only in the
+ # persons database (provisioned by sqlx migrations).
# Drop in correct order: dependent tables first, then referenced tables
cursor.execute("""
DROP TABLE IF EXISTS posthog_cohortpeople CASCADE;
diff --git a/posthog/models/utils.py b/posthog/models/utils.py
index 4c380f99afe5..18c23be8f78c 100644
--- a/posthog/models/utils.py
+++ b/posthog/models/utils.py
@@ -23,7 +23,6 @@ from django.db.models.constraints import BaseConstraint
from django.utils.text import slugify
from posthog.constants import MAX_SLUG_LENGTH
-from posthog.person_db_router import PERSONS_DB_MODELS
if TYPE_CHECKING:
from random import Random
@@ -484,23 +483,11 @@ class RootTeamQuerySet(models.QuerySet):
if "team_id" in kwargs:
team_id = kwargs.pop("team_id")
- # Check if this model is in the persons database
- # For persons DB models, we can't join with the Team table (cross-database)
- if self.model._meta.model_name in PERSONS_DB_MODELS:
- # Fetch the effective team_id directly from the default database
- # Cannot use subquery as it would execute against persons_db
- try:
- team = Team.objects.using("default").get(id=team_id)
- effective_team_id = team.parent_team_id if team.parent_team_id else team_id
- except Team.DoesNotExist:
- effective_team_id = team_id
- team_filter = Q(team_id=effective_team_id)
- else:
- # For non-persons DB models: use the original logic with JOIN
- parent_team_subquery = Team.objects.filter(id=team_id).values("parent_team_id")[:1]
- team_filter = Q(team_id=Subquery(parent_team_subquery)) | Q(
- team_id=team_id, team__parent_team_id__isnull=True
- )
+ # Scope to the team and, when it is an environment, its project root team.
+ parent_team_subquery = Team.objects.filter(id=team_id).values("parent_team_id")[:1]
+ team_filter = Q(team_id=Subquery(parent_team_subquery)) | Q(
+ team_id=team_id, team__parent_team_id__isnull=True
+ )
return super().filter(team_filter, *args, **kwargs)
return super().filter(*args, **kwargs)
@@ -528,28 +515,10 @@ class RootTeamMixin(models.Model):
abstract = True
def save(self, *args: Any, **kwargs: Any) -> None:
- if self._meta.model_name in PERSONS_DB_MODELS:
- return self._save_in_persons_db(*args, **kwargs)
-
if hasattr(self, "team") and self.team and hasattr(self.team, "parent_team") and self.team.parent_team: # type: ignore
self.team = self.team.parent_team # type: ignore
super().save(*args, **kwargs)
- def _save_in_persons_db(self, *args, **kwargs) -> None:
- """
- If the model is stored in persons db, referencing the foreign key will raise an error.
- Reference the actual table column instead and query `team` manually.
- """
- team_id: Optional[int] = getattr(self, "team_id", None)
- if team_id:
- from posthog.models import Team
-
- team = Team.objects.get(id=team_id)
- if hasattr(team, "parent_team") and team.parent_team:
- self.team_id = team.parent_team.id
-
- super().save(*args, **kwargs)
-
def convert_funnel_query(legacy_metric):
# Extract and simplify series
diff --git a/posthog/person_db_router.py b/posthog/person_db_router.py
index 9b26d19d8f16..b6117d4e0fb0 100644
--- a/posthog/person_db_router.py
+++ b/posthog/person_db_router.py
@@ -3,7 +3,17 @@
import threading
import contextlib
-from django.conf import settings
+from prometheus_client import Counter
+
+# A persons-DB model resolved through the Django ORM. personhog serves person/group/cohort data,
+# so this should stay at zero in production — a nonzero value means a code path still reaches a
+# persons model via the ORM, which now routes to the main database instead of the persons DB.
+# Alert on any increase; the model/operation labels point at the offending callsite.
+PERSONS_ORM_ACCESS_COUNTER = Counter(
+ "posthog_persons_orm_access_total",
+ "Persons-DB model resolved through the Django ORM (expected zero in production).",
+ labelnames=["model", "operation"],
+)
class PersonsDBORMBlockedError(RuntimeError):
@@ -13,15 +23,14 @@ class PersonsDBORMBlockedError(RuntimeError):
personhog is the sole source of truth for person/group/cohort data. The test
suite activates this block (via the personhog fake) so that any code path that
still reaches for the persons DB through the ORM fails loudly instead of
- silently reading stale/empty rows. Use the personhog helpers
+ silently reading the main database. Use the personhog helpers
(``posthog/models/person/util.py``, ``posthog/models/group_type_mapping.py``)
for production reads and ``posthog/test/persons.py`` for test data.
"""
-# Thread-local toggle. Off by default so production, migrations, management
-# commands and the e2e/demo data paths route to the persons DB as before; the
-# test fixture flips it on for the duration of each test.
+# Thread-local toggle. Off by default; the test fixture flips it on for the
+# duration of each test so a stray persons-DB ORM call surfaces immediately.
_orm_block = threading.local()
@@ -42,9 +51,8 @@ def allow_persons_orm():
"""Temporarily allow direct persons-DB ORM access while the block is active.
For maintenance paths that legitimately read/write the persons DB even when a
- test's personhog fake is active — management commands and the demo-data
- generator, which the router is designed to let "route to the persons DB as
- before". Saves and restores the previous block state so nesting is safe.
+ test's personhog fake is active. Saves and restores the previous block state so
+ nesting is safe.
"""
previously_blocked = persons_orm_blocked()
_orm_block.enabled = False
@@ -54,8 +62,8 @@ def allow_persons_orm():
_orm_block.enabled = previously_blocked
-# Set of models (lowercase) that should live in the persons_db
-# Add other models from the plan here as needed.
+# Models (lowercase model_name) whose tables are owned by the persons database.
+# personhog is the source of truth for these; the ORM must not query them.
PERSONS_DB_MODELS = {
"person",
"persondistinctid",
@@ -71,49 +79,31 @@ PERSONS_DB_MODELS = {
}
-# Database connections for persons-related operations
-# In tests, use persons_db_writer for reads to ensure transaction visibility
-# (both aliases point to same DB but are separate connections with separate transactions)
-# In production, use persons_db_reader for read scaling
-# For hobby deployments without separate persons DB, fallback to default
-def _get_persons_db_for_read():
- if settings.TEST or settings.DEBUG:
- return "persons_db_writer" if "persons_db_writer" in settings.DATABASES else "default"
- return "persons_db_reader" if "persons_db_reader" in settings.DATABASES else "default"
-
-
-def _get_persons_db_for_write():
- return "persons_db_writer" if "persons_db_writer" in settings.DATABASES else "default"
-
-
-PERSONS_DB_FOR_READ = _get_persons_db_for_read()
-PERSONS_DB_FOR_WRITE = _get_persons_db_for_write()
-
-
class PersonDBRouter:
- """
- A router to control all database operations on models in the persons database.
+ """Guards the Django ORM against touching persons-DB models.
+
+ The persons data lives behind the personhog service, not the Django ORM, so
+ this router never routes to a separate database — it returns ``None`` and lets
+ the default selection stand. It raises when a persons-DB model is queried through
+ the ORM while the block is active (the test fixture enables it), turning an
+ otherwise-silent read of the main database into a loud failure, and increments
+ ``PERSONS_ORM_ACCESS_COUNTER`` on every persons-model ORM resolution so the same
+ access is observable in production, where the block is off.
"""
- # Apps whose models can live in the persons DB. FeatureFlagHashKeyOverride
- # was historically in the `posthog` app; it moved to `feature_flags` when the
- # FF models were extracted, but the physical table still lives in persons_db.
- # Likewise CohortPeople moved to `cohorts`, keeping its posthog_cohortpeople table.
+ # Apps whose models can live in the persons DB. FeatureFlagHashKeyOverride was
+ # historically in the `posthog` app; it moved to `feature_flags` when the FF
+ # models were extracted, and CohortPeople moved to `cohorts`, but both keep
+ # their persons-DB tables.
PERSONS_APP_LABELS = {"posthog", "feature_flags", "cohorts"}
def db_for_read(self, model, **hints):
- """
- Attempts to read person models go to persons_db (writer in tests, reader in production).
- """
if self.is_persons_model(model._meta.app_label, model._meta.model_name):
+ self._record_orm_access(model, "read")
self._raise_if_blocked(model)
- return PERSONS_DB_FOR_READ
return None # Allow default db selection
def db_for_write(self, model, **hints):
- """
- Attempts to write person models go to persons_db_writer.
- """
if self.is_persons_model(model._meta.app_label, model._meta.model_name):
# Django also calls db_for_write to compute _state.db when an FK *instance*
# is assigned during Model.__init__ (e.g. ``GroupTypeMapping(team=team)``).
@@ -122,10 +112,16 @@ class PersonDBRouter:
# pass the model's own instance (save/create) or no instance (queryset writes).
instance = hints.get("instance")
if instance is None or isinstance(instance, model):
+ self._record_orm_access(model, "write")
self._raise_if_blocked(model)
- return PERSONS_DB_FOR_WRITE
return None # Allow default db selection
+ @staticmethod
+ def _record_orm_access(model, operation: str) -> None:
+ # Emit on every persons-model ORM resolution so production stray access is observable
+ # even though the block is off there (see PERSONS_ORM_ACCESS_COUNTER).
+ PERSONS_ORM_ACCESS_COUNTER.labels(model=model._meta.model_name, operation=operation).inc()
+
@staticmethod
def _raise_if_blocked(model) -> None:
if persons_orm_blocked():
@@ -136,78 +132,5 @@ class PersonDBRouter:
f"and create test data via posthog/test/persons.py."
)
- def allow_relation(self, obj1, obj2, **hints):
- """
- Allow relations if a model in PERSONS_DB_MODELS is involved.
- Relations between two models that are both in PERSONS_DB_MODELS are allowed.
- Relations between two models that are *not* in PERSONS_DB_MODELS are allowed.
- Relations between a model in PERSONS_DB_MODELS and a model not in it are DISALLOWED
- by default, as Django doesn't support cross-database relations natively.
- You might need to adjust this based on specific foreign keys (e.g., Person -> Team).
- """
- obj1_in_persons_db = obj1._meta.app_label in self.PERSONS_APP_LABELS and self.is_persons_model(
- obj1._meta.app_label, obj1._meta.model_name
- )
- obj2_in_persons_db = obj2._meta.app_label in self.PERSONS_APP_LABELS and self.is_persons_model(
- obj2._meta.app_label, obj2._meta.model_name
- )
-
- if obj1_in_persons_db and obj2_in_persons_db:
- # Both models are in persons_db, allow relation there
- return True
- elif not obj1_in_persons_db and not obj2_in_persons_db:
- # Neither model is in persons_db, allow relation on default db
- return None # Allow default behavior (usually True on 'default' db)
- else:
- # One model is in persons_db, the other is not.
- # Allow specific cross-database relationships where the FK constraint is removed (db_constraint=False)
- # Person -> Team: Person.team has db_constraint=False
- # GroupTypeMapping -> Team: GroupTypeMapping.team has db_constraint=False
- # GroupTypeMapping -> Project: GroupTypeMapping.project has db_constraint=False
- # GroupTypeMapping -> Dashboard: GroupTypeMapping.detail_dashboard has db_constraint=False
- from posthog.models import Person, Project, Team
- from posthog.models.group_type_mapping import GroupTypeMapping
-
- from products.cohorts.backend.models.cohort import Cohort, CohortPeople
- from products.dashboards.backend.models.dashboard import Dashboard
-
- # Allow any persons_db model -> Team relation
- # (Person, PersonDistinctId, Group, CohortPeople, etc. all have team FK)
- if isinstance(obj2, Team) and obj1_in_persons_db:
- return True
- if isinstance(obj1, Team) and obj2_in_persons_db:
- return True
-
- # Allow GroupTypeMapping -> Project relation
- if isinstance(obj1, GroupTypeMapping) and isinstance(obj2, Project):
- return True
- if isinstance(obj1, Project) and isinstance(obj2, GroupTypeMapping):
- return True
-
- # Allow GroupTypeMapping -> Dashboard relation
- if isinstance(obj1, GroupTypeMapping) and isinstance(obj2, Dashboard):
- return True
- if isinstance(obj1, Dashboard) and isinstance(obj2, GroupTypeMapping):
- return True
-
- # Allow Cohort -> CohortPeople relation (for cohort.people.add())
- if isinstance(obj1, Cohort) and isinstance(obj2, Person | CohortPeople):
- return True
- if isinstance(obj1, Person | CohortPeople) and isinstance(obj2, Cohort):
- return True
-
- # Disallow all other cross-database relations
- return False
-
- def allow_migrate(self, db, app_label, model_name=None, **hints):
- """
- don't run any migrations against the persons db, only against the default
- run all migrations against the default
- """
- return db != "persons_db_writer"
-
def is_persons_model(self, app_label, model_name):
- # only route posthog app models, not auth.Group (there is a name clash between posthog_group
- # and Django's auth_group. featureflaghashkeyoverride moved to the feature_flags app but the
- # physical table still lives in persons_db.
return app_label in self.PERSONS_APP_LABELS and model_name in PERSONS_DB_MODELS
diff --git a/posthog/settings/data_stores.py b/posthog/settings/data_stores.py
index 0d35d49706a2..762ea1be8b66 100644
--- a/posthog/settings/data_stores.py
+++ b/posthog/settings/data_stores.py
@@ -144,46 +144,12 @@ if direct_host:
lock_timeout_ms = os.getenv("MIGRATE_LOCK_TIMEOUT", "20000")
DATABASES["default_direct"]["OPTIONS"] = {"options": f"-c lock_timeout={lock_timeout_ms}"}
-# Add the persons_db_writer database configuration using PERSONS_DB_WRITER_URL
-# For local development, default to the persons database in the main container if no URL is provided
-persons_db_writer_url = os.getenv("PERSONS_DB_WRITER_URL")
-if not persons_db_writer_url and DEBUG and not TEST:
- # Default to local persons database in main container in development mode (but not test mode)
- # This matches the docker-compose.dev.yml configuration
- # A default is needed for generate_demo_data to properly populate the correct databases
- # with the demo data
- persons_db_writer_url = f"postgres://{PG_USER}:{PG_PASSWORD}@{PG_HOST}:{PG_PORT}/posthog_persons"
-elif not persons_db_writer_url and TEST:
- # In test mode, use a placeholder database name that will be updated by conftest
- # pytest-django adds test_ prefix which isn't known at settings import time
- # conftest.py django_db_setup fixture will update the NAME with the correct test database name
- test_persons_db = PG_DATABASE + "_persons"
- persons_db_writer_url = f"postgres://{PG_USER}:{PG_PASSWORD}@{PG_HOST}:{PG_PORT}/{test_persons_db}"
-
-if persons_db_writer_url:
- DATABASES["persons_db_writer"] = dict(
- dj_database_url.config(env="PERSONS_DB_WRITER_URL", default=persons_db_writer_url, conn_max_age=0)
- )
-
- # Fall back to the writer URL if no reader URL is set
- DATABASES["persons_db_reader"] = dict(
- dj_database_url.config(env="PERSONS_DB_READER_URL", default=persons_db_writer_url, conn_max_age=0)
- )
- if DISABLE_SERVER_SIDE_CURSORS:
- DATABASES["persons_db_writer"]["DISABLE_SERVER_SIDE_CURSORS"] = True
- DATABASES["persons_db_reader"]["DISABLE_SERVER_SIDE_CURSORS"] = True
-
- if TEST:
- # The persons DB schema is built by sqlx (rust/persons_migrations), not Django —
- # PersonDBRouter.allow_migrate blocks every Django migration on it. Without MIGRATE=False,
- # pytest-django's setup_databases still walks and records all ~1,300 Django migrations
- # against the empty persons test database on every shard (~300s of pure overhead, scaling
- # with migration count), even though the router skips the actual DDL. Skipping migrate here
- # leaves conftest.run_persons_sqlx_migrations to build the real schema.
- DATABASES["persons_db_writer"]["TEST"] = {"MIGRATE": False, "DEPENDENCIES": []}
- DATABASES["persons_db_reader"]["TEST"] = {"MIRROR": "persons_db_writer"}
-
- DATABASE_ROUTERS.insert(0, "posthog.person_db_router.PersonDBRouter")
+# The persons database is not a Django connection. Person/group/cohort data lives behind
+# the personhog service and is reached through the personhog client or off-Django psycopg
+# (posthog/persons_db.py), never the ORM. PersonDBRouter stays registered solely as a guard
+# that raises if a persons-DB model is queried through the ORM while the test block is active
+# (see posthog/person_db_router.py); it routes nothing and adds no DATABASES entry.
+DATABASE_ROUTERS.insert(0, "posthog.person_db_router.PersonDBRouter")
product_routes = load_product_db_routes(Path(__file__).resolve().parents[2])
diff --git a/posthog/test/test_person_db_router.py b/posthog/test/test_person_db_router.py
new file mode 100644
index 000000000000..d5379b4c22b0
--- /dev/null
+++ b/posthog/test/test_person_db_router.py
@@ -0,0 +1,92 @@
+import pytest
+
+from parameterized import parameterized
+from prometheus_client import REGISTRY
+
+from posthog.models import Organization
+from posthog.models.group_type_mapping import GroupTypeMapping
+from posthog.models.person import Person
+from posthog.person_db_router import (
+ PersonDBRouter,
+ PersonsDBORMBlockedError,
+ allow_persons_orm,
+ block_persons_orm,
+ unblock_persons_orm,
+)
+
+
+class TestPersonDBRouterGuard:
+ """Unit tests for the router guard. Marked persons_db_direct to skip the autouse
+ personhog fake so the block flag is controlled explicitly here, not by the fixture."""
+
+ pytestmark = pytest.mark.persons_db_direct
+
+ def setup_method(self):
+ self.router = PersonDBRouter()
+ unblock_persons_orm()
+
+ def teardown_method(self):
+ unblock_persons_orm()
+
+ @parameterized.expand([("read", "db_for_read"), ("write", "db_for_write")])
+ def test_routes_nothing_when_unblocked(self, _name, method):
+ # The router never selects a database — its only job is to guard.
+ assert getattr(self.router, method)(Person) is None
+ assert getattr(self.router, method)(Organization) is None
+
+ @parameterized.expand([("person", Person), ("group_type_mapping", GroupTypeMapping)])
+ def test_blocked_persons_model_raises(self, _name, model):
+ block_persons_orm()
+ with pytest.raises(PersonsDBORMBlockedError):
+ self.router.db_for_read(model)
+ with pytest.raises(PersonsDBORMBlockedError):
+ self.router.db_for_write(model)
+
+ def test_blocked_non_persons_model_is_allowed(self):
+ block_persons_orm()
+ assert self.router.db_for_read(Organization) is None
+ assert self.router.db_for_write(Organization) is None
+
+ def test_fk_instance_hint_does_not_trip_block(self):
+ # Django calls db_for_write with the *related* instance while resolving an FK
+ # assignment (e.g. GroupTypeMapping(team=team)); nothing is being written, so the
+ # guard must stay quiet.
+ block_persons_orm()
+ assert self.router.db_for_write(Person, instance=Organization(name="x")) is None
+
+ def test_allow_persons_orm_temporarily_unblocks(self):
+ block_persons_orm()
+ with allow_persons_orm():
+ assert self.router.db_for_read(Person) is None
+ with pytest.raises(PersonsDBORMBlockedError):
+ self.router.db_for_read(Person)
+
+ def test_records_orm_access_metric(self):
+ # The counter is the production canary — the block is off in prod, so a stray persons
+ # ORM access must still be observable. Guards against the increment being dropped.
+ labels = {"model": "person", "operation": "read"}
+ before = REGISTRY.get_sample_value("posthog_persons_orm_access_total", labels) or 0.0
+ self.router.db_for_read(Person)
+ after = REGISTRY.get_sample_value("posthog_persons_orm_access_total", labels) or 0.0
+ assert after == before + 1
+
+
+class TestPersonsORMBlockedEndToEnd:
+ """End-to-end: with the personhog fake active (the default autouse fixture), a real
+ persons-model ORM query must raise rather than silently fall through to the main DB.
+
+ This exercises the full wiring — fixture → block_persons_orm → router → is_persons_model
+ — that the unit tests above stub out. The query raises during database selection, before
+ any SQL runs.
+ """
+
+ @parameterized.expand(
+ [
+ ("person", lambda: Person.objects.filter(team_id=1).first()),
+ ("group_type_mapping", lambda: list(GroupTypeMapping.objects.filter(project_id=1))),
+ ]
+ )
+ def test_real_orm_query_raises_under_active_fake(self, _name, run_query):
+ with pytest.raises(PersonsDBORMBlockedError):
+ run_query()
diff --git a/products/feature_flags/backend/local_evaluation.py b/products/feature_flags/backend/local_evaluation.py
index 37ab0a28a224..8050379e5679 100644
--- a/products/feature_flags/backend/local_evaluation.py
+++ b/products/feature_flags/backend/local_evaluation.py
@@ -43,7 +43,6 @@ from posthog.models.group_type_mapping import (
project_has_group_types_authoritatively,
)
from posthog.models.team import Team
-from posthog.person_db_router import PERSONS_DB_FOR_READ
from posthog.storage.hypercache import HYPERCACHE_REBUILD_SKIPPED_COUNTER, HyperCache, KeyType, emit_cache_sync_metrics
from posthog.storage.hypercache_manager import HyperCacheManagementConfig
from posthog.utils import capture_exception_throttled, get_safe_cache
@@ -383,9 +382,6 @@ DATABASE_FOR_LOCAL_EVALUATION = (
else "replica"
)
-# Use centralized database routing constant
-READ_ONLY_DATABASE_FOR_PERSONS = PERSONS_DB_FOR_READ
-
flag_definitions_hypercache = HyperCache(
namespace="feature_flags",
value="flags_with_cohorts.json",