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): more person orm decoupling (#66406)

Zach Brown6f03ddefe849
diff --git a/posthog/hogql/database/postgres_table.py b/posthog/hogql/database/postgres_table.py
index 1054ce44e7e8..172b6497af4a 100644
--- a/posthog/hogql/database/postgres_table.py
+++ b/posthog/hogql/database/postgres_table.py
@@ -1,14 +1,17 @@
from functools import cache
-from typing import Optional
+from typing import Optional, cast
from django.conf import settings
+from psycopg.conninfo import conninfo_to_dict
+
from posthog.hogql.base import Expr
from posthog.hogql.context import HogQLContext
from posthog.hogql.database.models import FunctionCallTable
from posthog.hogql.escape_sql import escape_hogql_identifier
from posthog.person_db_router import PERSONS_DB_MODELS
+from posthog.persons_db import persons_db_url
from posthog.scopes import APIScopeObject
@@ -38,22 +41,30 @@ def build_function_call(postgres_table_name: str, context: Optional[HogQLContext
table = add_param(postgres_table_name)
if settings.DEBUG or settings.TEST:
- databases = settings.DATABASES
- # Determine which database to use based on table name
+ address = add_param("db:5432") # docker container for postgres from clickhouse
+
# Extract model name from postgres table name (e.g., "posthog_group" -> "group")
model_name = postgres_table_name.replace("posthog_", "")
- db_name = "persons_db_writer" if model_name in PERSONS_DB_MODELS else "default"
- database = databases[db_name]
-
- address = add_param("db:5432") # docker container for postgres from clickhouse
- from django.db import connections
-
- actual_db_name = connections[db_name].settings_dict[
- "NAME"
- ] # during tests, django uses test-prefixed db name rather than the configured NAME
- db = add_param(actual_db_name)
- user = add_param(database["USER"])
- password = add_param(database["PASSWORD"])
+ if model_name in PERSONS_DB_MODELS:
+ # The persons DB is not a Django-managed connection. Source its credentials from the
+ # off-ORM URL (posthog/persons_db.py), which conftest points at the test-prefixed
+ # persons DB under tests — mirroring the test DB name Django would have resolved.
+ # Index directly (not .get with a default): a missing critical field should raise a
+ # clear KeyError here rather than pass blank credentials that surface as an opaque
+ # ClickHouse connection error at query time.
+ conninfo = cast(dict[str, str], conninfo_to_dict(persons_db_url(writer=True)))
+ db = add_param(conninfo["dbname"])
+ user = add_param(conninfo["user"])
+ password = add_param(conninfo["password"])
+ else:
+ from django.db import connections
+
+ database = settings.DATABASES["default"]
+ # during tests, django uses test-prefixed db name rather than the configured NAME
+ actual_db_name = connections["default"].settings_dict["NAME"]
+ db = add_param(actual_db_name)
+ user = add_param(database["USER"])
+ password = add_param(database["PASSWORD"])
else:
host_var = settings.CLICKHOUSE_HOGQL_RDSPROXY_READ_HOST
port_var = settings.CLICKHOUSE_HOGQL_RDSPROXY_READ_PORT
diff --git a/posthog/hogql/database/test/test_postgres_table.py b/posthog/hogql/database/test/test_postgres_table.py
index c562b7041f3c..e8f6fe12a999 100644
--- a/posthog/hogql/database/test/test_postgres_table.py
+++ b/posthog/hogql/database/test/test_postgres_table.py
@@ -21,7 +21,7 @@ from posthog.hogql.database.models import (
StringJSONDatabaseField,
TableNode,
)
-from posthog.hogql.database.postgres_table import PostgresTable
+from posthog.hogql.database.postgres_table import PostgresTable, build_function_call
from posthog.hogql.database.schema.system import SystemTables
from posthog.hogql.parser import parse_expr, parse_select
from posthog.hogql.printer import prepare_and_print_ast
@@ -154,6 +154,19 @@ class TestPostgresTable(BaseTest):
def _select(self, query: str, dialect: Literal["hogql", "clickhouse"] = "clickhouse") -> str:
return prepare_and_print_ast(parse_select(query), self.context, dialect=dialect)[0]
+ def test_persons_model_table_resolves_to_persons_db(self):
+ # In DEBUG/TEST, persons-model system tables (e.g. system.groups) build a federated
+ # postgresql(...) call pointing at the persons database — sourced off-ORM from
+ # PERSONS_DB_WRITER_URL — while main-DB tables resolve to the default database. The
+ # persons test DB name carries the "_persons" suffix, which discriminates the two.
+ persons_ctx = HogQLContext(team_id=self.team.pk)
+ build_function_call("posthog_group", persons_ctx)
+ assert any(str(v).endswith("_persons") for v in persons_ctx.values.values())
+
+ default_ctx = HogQLContext(team_id=self.team.pk)
+ build_function_call("posthog_dashboard", default_ctx)
+ assert not any(str(v).endswith("_persons") for v in default_ctx.values.values())
+
def test_select(self):
self._init_database()
self.assertEqual(
diff --git a/posthog/local_bootstrap/importer.py b/posthog/local_bootstrap/importer.py
index 46869c4d7462..85666123593d 100644
--- a/posthog/local_bootstrap/importer.py
+++ b/posthog/local_bootstrap/importer.py
@@ -8,7 +8,10 @@ from dataclasses import dataclass, field
from datetime import UTC, datetime
from typing import Any
+from django.conf import settings
+
from dateutil.parser import isoparse
+from psycopg.types.json import Jsonb
from posthog.clickhouse.client import sync_execute
from posthog.clickhouse.query_tagging import Feature, Product, tags_context
@@ -21,12 +24,17 @@ from posthog.local_bootstrap.config import (
TableResult,
)
from posthog.local_bootstrap.source import iter_table_rows
-from posthog.models import Organization, OrganizationMembership, Person, PersonDistinctId, Team, User
+from posthog.models import Organization, OrganizationMembership, Team, User
from posthog.models.event.sql import EVENTS_DATA_TABLE
+from posthog.persons_db import persons_db_connection
+from posthog.persons_seed import PERSON_DISTINCT_ID_TABLE
ZERO_UUID = "00000000-0000-0000-0000-000000000000"
ZERO_DT = datetime(1970, 1, 1)
+# Batch size for the persons-DB inserts (mirrors the prior bulk_create batch_size).
+_PG_WRITE_BATCH = 1000
+
# Columns we write directly into sharded_events (mirrors INSERT_EVENT_SQL minus computed columns).
_EVENT_COLUMNS = [
"uuid",
@@ -265,41 +273,54 @@ def _accumulate_persons(
return persons
-def _write_persons_to_postgres(team: Team, persons: dict[str, _PersonAccumulator]) -> list[Person]:
- person_objs: list[Person] = []
- desired_created_at: list[datetime] = []
+def _write_persons_to_postgres(team_id: int, persons: dict[str, _PersonAccumulator]) -> None:
+ if not persons:
+ return
+
+ # (uuid, properties, version, created_at) per person. created_at is written directly here,
+ # unlike the auto_now_add ORM path which had to restamp it after the fact.
+ person_rows: list[tuple[uuid.UUID, Jsonb, int, datetime]] = []
for person_id, entry in persons.items():
try:
properties = json.loads(entry.properties)
except (json.JSONDecodeError, TypeError):
properties = {}
- person_objs.append(
- Person( # nosemgrep: no-direct-persons-db-orm
- team=team,
- uuid=uuid.UUID(person_id),
- properties=properties,
- is_identified=True,
- version=entry.version,
+ person_rows.append((uuid.UUID(person_id), Jsonb(properties), entry.version, entry.created_at))
+
+ with persons_db_connection(writer=True, autocommit=True) as conn, conn.cursor() as cursor:
+ # Map each canonical UUID to its generated id so distinct IDs can reference person_id.
+ id_by_uuid: dict[str, int] = {}
+ for i in range(0, len(person_rows), _PG_WRITE_BATCH):
+ person_batch = person_rows[i : i + _PG_WRITE_BATCH]
+ person_placeholders = ", ".join(["(%s, %s, %s, %s, %s, true)"] * len(person_batch))
+ person_params = [
+ value
+ for person_uuid, properties, version, created_at in person_batch
+ for value in (team_id, person_uuid, properties, version, created_at)
+ ]
+ cursor.execute(
+ f"INSERT INTO {settings.PERSON_TABLE_NAME} "
+ f"(team_id, uuid, properties, version, created_at, is_identified) VALUES {person_placeholders} "
+ "RETURNING id, uuid",
+ person_params,
)
- )
- desired_created_at.append(entry.created_at)
-
- # created_at is auto_now_add, so bulk_create stamps "now"; restore the dump's value afterwards.
- Person.objects.bulk_create(person_objs, batch_size=1000) # nosemgrep: no-direct-persons-db-orm
- for person, created_at in zip(person_objs, desired_created_at):
- person.created_at = created_at
- Person.objects.bulk_update(person_objs, ["created_at"], batch_size=1000) # nosemgrep: no-direct-persons-db-orm
-
- distinct_objs: list[PersonDistinctId] = []
- for person, entry in zip(person_objs, persons.values()):
- for distinct_id, version in entry.distinct_ids.items():
- distinct_objs.append(
- PersonDistinctId( # nosemgrep: no-direct-persons-db-orm
- team=team, person=person, distinct_id=distinct_id, version=version
- )
+ for person_pk, person_uuid in cursor.fetchall():
+ id_by_uuid[str(person_uuid)] = person_pk
+
+ distinct_rows: list[tuple[str, int, int, int]] = [
+ (distinct_id, id_by_uuid[str(uuid.UUID(person_id))], team_id, version)
+ for person_id, entry in persons.items()
+ for distinct_id, version in entry.distinct_ids.items()
+ ]
+ for i in range(0, len(distinct_rows), _PG_WRITE_BATCH):
+ distinct_batch = distinct_rows[i : i + _PG_WRITE_BATCH]
+ distinct_placeholders = ", ".join(["(%s, %s, %s, %s)"] * len(distinct_batch))
+ distinct_params = [value for row in distinct_batch for value in row]
+ cursor.execute(
+ f"INSERT INTO {PERSON_DISTINCT_ID_TABLE} (distinct_id, person_id, team_id, version) "
+ f"VALUES {distinct_placeholders}",
+ distinct_params,
)
- PersonDistinctId.objects.bulk_create(distinct_objs, batch_size=1000) # nosemgrep: no-direct-persons-db-orm
- return person_objs
def _write_persons_to_clickhouse(team: Team, persons: dict[str, _PersonAccumulator]) -> None:
@@ -351,7 +372,7 @@ def import_persons(
accumulated = _accumulate_persons(config, files, batch_size, progress)
live = {pid: entry for pid, entry in accumulated.items() if not entry.is_deleted}
- _write_persons_to_postgres(team, live)
+ _write_persons_to_postgres(team.id, live)
_write_persons_to_clickhouse(team, live)
distinct_ids = sum(len(entry.distinct_ids) for entry in live.values())
diff --git a/posthog/local_bootstrap/test_local_bootstrap.py b/posthog/local_bootstrap/test_local_bootstrap.py
index 9dfc98a98761..be231946dbb1 100644
--- a/posthog/local_bootstrap/test_local_bootstrap.py
+++ b/posthog/local_bootstrap/test_local_bootstrap.py
@@ -2,11 +2,21 @@ from datetime import UTC, datetime
import pytest
+from django.conf import settings
+
from parameterized import parameterized
from posthog.local_bootstrap.config import BootstrapConfig, BootstrapConfigError, S3Location, TableImportConfig
-from posthog.local_bootstrap.importer import ZERO_UUID, Progress, _accumulate_persons, _event_row_to_ch
+from posthog.local_bootstrap.importer import (
+ ZERO_UUID,
+ Progress,
+ _accumulate_persons,
+ _event_row_to_ch,
+ _PersonAccumulator,
+ _write_persons_to_postgres,
+)
from posthog.local_bootstrap.source import _matches_format
+from posthog.persons_db import persons_db_connection
def _events_config() -> TableImportConfig:
@@ -141,3 +151,66 @@ class TestAccumulatePersons:
rows = [{"person_id": pid, "distinct_id": "d1", "properties": "{}", "created_at": 1_704_067_200}]
persons = self._run(monkeypatch, rows)
assert persons[pid].created_at == datetime(2024, 1, 1, tzinfo=UTC)
+
+
+class TestWritePersonsToPostgres:
+ # Writes go through a raw psycopg connection that commits outside Django's test
+ # transaction, so the test cleans up its own rows in the shared persons test database.
+ TEAM_ID = 2_000_000_002
+
+ def _cleanup(self) -> None:
+ # Own autocommit connection: the DELETEs must commit even when the caller is unwinding a
+ # failed assertion, otherwise the seeded rows leak and the next run hits a unique violation.
+ with persons_db_connection(writer=True, autocommit=True) as conn, conn.cursor() as cursor:
+ cursor.execute("DELETE FROM posthog_persondistinctid WHERE team_id = %s", (self.TEAM_ID,))
+ cursor.execute(f"DELETE FROM {settings.PERSON_TABLE_NAME} WHERE team_id = %s", (self.TEAM_ID,))
+
+ @pytest.mark.django_db(databases=["persons_db_writer", "persons_db_reader"])
+ def test_writes_persons_and_links_distinct_ids_to_the_right_person(self):
+ uuid_with_dids = "11111111-1111-1111-1111-111111111111"
+ uuid_without_dids = "22222222-2222-2222-2222-222222222222"
+ persons = {
+ uuid_with_dids: _PersonAccumulator(
+ properties='{"email": "[email protected]"}',
+ version=7,
+ created_at=datetime(2024, 1, 1, tzinfo=UTC),
+ is_deleted=False,
+ distinct_ids={"da1": 0, "da2": 3},
+ ),
+ uuid_without_dids: _PersonAccumulator(
+ properties="{}",
+ version=0,
+ created_at=datetime(2024, 1, 1, tzinfo=UTC),
+ is_deleted=False,
+ distinct_ids={},
+ ),
+ }
+
+ self._cleanup() # clear any rows a prior failed run may have left behind
+ try:
+ _write_persons_to_postgres(self.TEAM_ID, persons)
+
+ with persons_db_connection(writer=False) as conn, conn.cursor() as cursor:
+ cursor.execute(
+ f"SELECT uuid, properties, version, is_identified FROM {settings.PERSON_TABLE_NAME} "
+ "WHERE team_id = %s",
+ (self.TEAM_ID,),
+ )
+ by_uuid = {str(uuid): (props, version, identified) for uuid, props, version, identified in cursor}
+
+ cursor.execute(
+ "SELECT pdi.distinct_id, pdi.version, p.uuid "
+ f"FROM posthog_persondistinctid pdi JOIN {settings.PERSON_TABLE_NAME} p ON p.id = pdi.person_id "
+ "WHERE pdi.team_id = %s",
+ (self.TEAM_ID,),
+ )
+ dids = {did: (version, str(owner)) for did, version, owner in cursor}
+
+ # Both persons land, JSON properties are parsed, is_identified is set.
+ assert set(by_uuid) == {uuid_with_dids, uuid_without_dids}
+ assert by_uuid[uuid_with_dids] == ({"email": "[email protected]"}, 7, True)
+
+ # Distinct IDs attach to the right person (the uuid->id mapping) with their versions.
+ assert dids == {"da1": (0, uuid_with_dids), "da2": (3, uuid_with_dids)}
+ finally:
+ self._cleanup()
diff --git a/posthog/management/commands/setup_orphan_test_data.py b/posthog/management/commands/setup_orphan_test_data.py
index a09984c62fd2..bb8594387eec 100644
--- a/posthog/management/commands/setup_orphan_test_data.py
+++ b/posthog/management/commands/setup_orphan_test_data.py
@@ -14,12 +14,13 @@ Usage:
import uuid
+from django.conf import settings
from django.core.management.base import BaseCommand
from posthog.clickhouse.client.execute import sync_execute
from posthog.models import Team
-from posthog.models.person import Person, PersonDistinctId
-from posthog.person_db_router import PERSONS_DB_FOR_WRITE
+from posthog.persons_db import persons_db_connection
+from posthog.persons_seed import PERSON_DISTINCT_ID_TABLE, insert_seed_distinct_id, insert_seed_person
class Command(BaseCommand):
@@ -98,49 +99,48 @@ class Command(BaseCommand):
created_persons: list[tuple[str, str, str | None]] = []
- # 1. Fixable orphans: Person in CH + PG, DID only in PG
- self.stdout.write(self.style.WARNING("\n[Fixable Orphans]"))
- for i in range(fixable_count):
- person_uuid = str(uuid.uuid4())
- distinct_id = f"{prefix}-fixable-{i}-{person_uuid[:8]}"
-
- # Create person in PostgreSQL with distinct ID
- person = Person.objects.db_manager(PERSONS_DB_FOR_WRITE).create( # nosemgrep: no-direct-persons-db-orm
- team=team,
- uuid=person_uuid,
- properties={"test_type": "fixable", "index": i},
- )
- PersonDistinctId.objects.db_manager(PERSONS_DB_FOR_WRITE).create( # nosemgrep: no-direct-persons-db-orm
- team=team,
- person=person,
- distinct_id=distinct_id,
- version=0,
- )
-
- # Create person in ClickHouse WITHOUT distinct ID
- self._insert_person_to_ch(team.id, person_uuid, version=0)
- # Deliberately NOT inserting distinct_id to CH
-
- created_persons.append(("fixable", person_uuid, distinct_id))
- self.stdout.write(f" Created: {person_uuid[:8]}... -> {distinct_id}")
-
- # 2. Truly orphaned: Person in CH + PG, no DID anywhere
- self.stdout.write(self.style.WARNING("\n[Truly Orphaned]"))
- for i in range(truly_orphaned_count):
- person_uuid = str(uuid.uuid4())
-
- # Create person in PostgreSQL WITHOUT distinct ID
- Person.objects.db_manager(PERSONS_DB_FOR_WRITE).create( # nosemgrep: no-direct-persons-db-orm
- team=team,
- uuid=person_uuid,
- properties={"test_type": "truly_orphaned", "index": i},
- )
-
- # Create person in ClickHouse WITHOUT distinct ID
- self._insert_person_to_ch(team.id, person_uuid, version=0)
-
- created_persons.append(("truly_orphaned", person_uuid, None))
- self.stdout.write(f" Created: {person_uuid[:8]}... (no DID)")
+ # autocommit so each seeded row lands immediately, matching the prior per-create ORM behavior.
+ with persons_db_connection(writer=True, autocommit=True) as conn:
+ # 1. Fixable orphans: Person in CH + PG, DID only in PG
+ self.stdout.write(self.style.WARNING("\n[Fixable Orphans]"))
+ for i in range(fixable_count):
+ person_uuid = str(uuid.uuid4())
+ distinct_id = f"{prefix}-fixable-{i}-{person_uuid[:8]}"
+
+ # Create person in PostgreSQL with distinct ID
+ person_id = insert_seed_person(
+ conn,
+ team_id=team.id,
+ properties={"test_type": "fixable", "index": i},
+ uuid=person_uuid,
+ )
+ insert_seed_distinct_id(conn, team_id=team.id, person_id=person_id, distinct_id=distinct_id)
+
+ # Create person in ClickHouse WITHOUT distinct ID
+ self._insert_person_to_ch(team.id, person_uuid, version=0)
+ # Deliberately NOT inserting distinct_id to CH
+
+ created_persons.append(("fixable", person_uuid, distinct_id))
+ self.stdout.write(f" Created: {person_uuid[:8]}... -> {distinct_id}")
+
+ # 2. Truly orphaned: Person in CH + PG, no DID anywhere
+ self.stdout.write(self.style.WARNING("\n[Truly Orphaned]"))
+ for i in range(truly_orphaned_count):
+ person_uuid = str(uuid.uuid4())
+
+ # Create person in PostgreSQL WITHOUT distinct ID
+ insert_seed_person(
+ conn,
+ team_id=team.id,
+ properties={"test_type": "truly_orphaned", "index": i},
+ uuid=person_uuid,
+ )
+
+ # Create person in ClickHouse WITHOUT distinct ID
+ self._insert_person_to_ch(team.id, person_uuid, version=0)
+
+ created_persons.append(("truly_orphaned", person_uuid, None))
+ self.stdout.write(f" Created: {person_uuid[:8]}... (no DID)")
# 3. CH-only orphans: Person only in CH, not in PG
self.stdout.write(self.style.WARNING("\n[CH-Only Orphans]"))
@@ -167,26 +167,33 @@ class Command(BaseCommand):
def cleanup_test_data(self, team: Team, prefix: str):
self.stdout.write(f"\nCleaning up test data for team {team.id} with prefix '{prefix}'...")
- # Find test persons in PostgreSQL by properties
- pg_persons = Person.objects.db_manager(PERSONS_DB_FOR_WRITE).filter( # nosemgrep: no-direct-persons-db-orm
- team=team,
- properties__test_type__in=["fixable", "truly_orphaned"],
- )
- pg_uuids = list(pg_persons.values_list("uuid", flat=True))
+ # Escape LIKE wildcards so the prefix matches literally, mirroring Django's __startswith.
+ like_prefix = prefix.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") + "%"
- # Delete from PostgreSQL
- deleted_dids = (
- PersonDistinctId.objects.db_manager(PERSONS_DB_FOR_WRITE) # nosemgrep: no-direct-persons-db-orm
- .filter(
- team=team,
- distinct_id__startswith=prefix,
+ with persons_db_connection(writer=True, autocommit=True) as conn, conn.cursor() as cursor:
+ # Find test persons by their seeded test_type property.
+ cursor.execute(
+ f"SELECT uuid FROM {settings.PERSON_TABLE_NAME} "
+ "WHERE team_id = %s AND properties->>'test_type' IN ('fixable', 'truly_orphaned')",
+ (team.id,),
)
- .delete()
- )
- deleted_persons = pg_persons.delete()
+ pg_uuids = [str(row[0]) for row in cursor.fetchall()]
+
+ cursor.execute(
+ f"DELETE FROM {PERSON_DISTINCT_ID_TABLE} WHERE team_id = %s AND distinct_id LIKE %s",
+ (team.id, like_prefix),
+ )
+ deleted_dids = cursor.rowcount
+
+ cursor.execute(
+ f"DELETE FROM {settings.PERSON_TABLE_NAME} "
+ "WHERE team_id = %s AND properties->>'test_type' IN ('fixable', 'truly_orphaned')",
+ (team.id,),
+ )
+ deleted_persons = cursor.rowcount
- self.stdout.write(f" Deleted {deleted_persons[0]} persons from PostgreSQL")
- self.stdout.write(f" Deleted {deleted_dids[0]} distinct IDs from PostgreSQL")
+ self.stdout.write(f" Deleted {deleted_persons} persons from PostgreSQL")
+ self.stdout.write(f" Deleted {deleted_dids} distinct IDs from PostgreSQL")
# Mark as deleted in ClickHouse (we can't truly delete, but can mark is_deleted=1)
if pg_uuids: