: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
chore(django): decouple person db from orm test infra (#66471)
Zach Brown719df41069d7
diff --git a/.github/workflows/ci-dagster.yml b/.github/workflows/ci-dagster.ymlindex e2709e496606..96b2cd137b72 100644--- a/.github/workflows/ci-dagster.yml+++ b/.github/workflows/ci-dagster.yml@@ -119,6 +119,7 @@ jobs:- 'posthog/git.py'- 'posthog/llm/**'- 'posthog/person_db_router.py'+ - 'posthog/persons_db.py'- 'posthog/redis.py'- 'posthog/event_usage.py'- 'posthog/products.py'diff --git a/conftest.py b/conftest.pyindex c24dafa45c42..6ba2c7cc0c70 100644--- a/conftest.py+++ b/conftest.py@@ -69,3 +69,30 @@ def _activate_personhog_fake(request):with activate_personhog_fake():yield++[email protected](autouse=True)+def _clean_persons_db_for_direct_tests(request):+ """Truncate the persons DB before each persons_db_direct test.++ These tests seed the persons DB through off-Django psycopg (posthog.test.persons), which+ commits outside Django's per-test transaction and so is NOT rolled back at teardown. Because+ team ids reset every test (the main DB rolls back), leaked rows from a prior test would bleed+ into the next one's reused team id. Truncating before the test (when no Django persons+ transaction holds locks yet) clears that carryover without risking a TRUNCATE lock hang.+ """+ if not request.node.get_closest_marker("persons_db_direct"):+ yield+ return++ from posthog.persons_db import persons_db_connection # noqa: PLC0415++ with persons_db_connection(writer=True, autocommit=True) as conn, 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 != '_persons_migrations'"+ )+ tables = [row[0] for row in cursor.fetchall()]+ if tables:+ cursor.execute(f"TRUNCATE TABLE {', '.join(tables)} RESTART IDENTITY CASCADE")+ yielddiff --git a/ee/hogai/test/test_snapshot_loader.py b/ee/hogai/test/test_snapshot_loader.pyindex ad62fef6ab46..899070c4ec49 100644--- a/ee/hogai/test/test_snapshot_loader.py+++ b/ee/hogai/test/test_snapshot_loader.py@@ -20,7 +20,7 @@ from posthog.schema import ()from posthog.hogql_queries.query_runner import get_query_runner-from posthog.models import GroupTypeMapping, Organization, PropertyDefinition, Team+from posthog.models import Organization, PropertyDefinition, Teamfrom posthog.persons_db import persons_db_connectionfrom products.warehouse_sources.backend.facade.models import DataWarehouseTable@@ -226,7 +226,11 @@ class TestSnapshotLoader(BaseTest):def test_restores_models_counts(self):_org, _user, _dataset, team = self._load_with_mocks()self.assertEqual(PropertyDefinition.objects.filter(team_id=team.id).count(), 2)- self.assertEqual(GroupTypeMapping.objects.filter(team_id=team.id).count(), 2)+ with persons_db_connection(writer=False) as conn, conn.cursor() as cursor:+ cursor.execute("SELECT count(*) FROM posthog_grouptypemapping WHERE team_id = %s", (team.id,))+ row = cursor.fetchone()+ group_type_mapping_count = row[0] if row else 0+ self.assertEqual(group_type_mapping_count, 2)self.assertEqual(DataWarehouseTable.objects.filter(team_id=team.id).count(), 2)def test_loads_team_taxonomy_data_source(self):diff --git a/posthog/conftest.py b/posthog/conftest.pyindex 60910631da81..8c9f79bf5088 100644--- a/posthog/conftest.py+++ b/posthog/conftest.py@@ -16,7 +16,6 @@ except ImportError: # fail-open: runs without tools/hogli-commands on pythonpatfrom django.conf import settingsfrom django.core.management.commands.flush import Command as FlushCommand-from django.db import connectionsfrom infi.clickhouse_orm import Database@@ -240,21 +239,17 @@ def _django_db_setup(django_db_keepdb, django_db_blocker):test_db_name = connection.settings_dict["NAME"]test_persons_db_name = test_db_name + "_persons"- # Update the persons database NAME to use the correct test database name- # The database configuration already exists from settings, we just need to update the NAME- settings.DATABASES["persons_db_writer"]["NAME"] = test_persons_db_name- settings.DATABASES["persons_db_reader"]["NAME"] = test_persons_db_name-- # Point the off-ORM persons_db util (posthog/persons_db.py) at the test persons DB.- # It reads only PERSONS_DB_{WRITER,READER}_URL from the environment, never Django- # settings, so the test database has to be exposed to it via those env vars.- _persons_db = settings.DATABASES["persons_db_writer"]- _persons_user = quote_plus(_persons_db.get("USER") or "")- _persons_password = f":{quote_plus(_persons_db['PASSWORD'])}" if _persons_db.get("PASSWORD") else ""+ # Point the off-ORM persons_db util (posthog/persons_db.py) at the test persons DB. It reads+ # only PERSONS_DB_{WRITER,READER}_URL from the environment, never Django settings. Derive the+ # URL from the DEFAULT connection's config (the persons DB lives on the same server, just a+ # different database) so this no longer depends on the persons_db Django alias.+ _default_db = connection.settings_dict+ _persons_user = quote_plus(_default_db.get("USER") or "")+ _persons_password = f":{quote_plus(_default_db['PASSWORD'])}" if _default_db.get("PASSWORD") else ""# HOST/PORT can be empty strings in Django's config (empty HOST means Unix socket);# fall back to localhost:5432 so the URL is always well-formed for psycopg.- _persons_host = _persons_db.get("HOST") or "localhost"- _persons_port = _persons_db.get("PORT") or "5432"+ _persons_host = _default_db.get("HOST") or "localhost"+ _persons_port = _default_db.get("PORT") or "5432"_persons_db_url = (f"postgres://{_persons_user}{_persons_password}@{_persons_host}:{_persons_port}/{test_persons_db_name}")@@ -364,21 +359,6 @@ def pytest_terminal_summary(terminalreporter: Any, exitstatus: int, config: Any)terminalreporter.write_line(f"[flush-lock-guard] {flush_lock_guard.reports.pop(0)}", yellow=True)-def _truncate_persons_db_tables(database: str) -> None:- 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")--def _patched_flush_handle(self, **options: Any) -> None:"""Patched Django flush command for three reasons:@@ -401,11 +381,8 @@ def _patched_flush_handle(self, **options: Any) -> None:"""database = options["database"]- if database in ("persons_db_writer", "persons_db_reader"):- flush: Callable[[], None] = partial(_truncate_persons_db_tables, database)- else:- options["allow_cascade"] = True- flush = partial(_original_flush_handle, self, **options)+ options["allow_cascade"] = True+ flush: Callable[[], None] = partial(_original_flush_handle, self, **options)flush_lock_guard.flush_with_lock_guard(database, flush)@@ -554,8 +531,8 @@ def pytest_configure(config):from django.test import TestCase, TransactionTestCase# Set default databases for Django test classes- TestCase.databases = {"default", "persons_db_writer", "persons_db_reader"}- TransactionTestCase.databases = {"default", "persons_db_writer", "persons_db_reader"}+ TestCase.databases = {"default"}+ TransactionTestCase.databases = {"default"}if not config.pluginmanager.hasplugin("posthog-junit-timings"):config.pluginmanager.register(_JUnitTimingsPlugin(), "posthog-junit-timings")diff --git a/posthog/dags/tests/conftest.py b/posthog/dags/tests/conftest.pyindex df3e32a3bfd2..36b5ef437384 100644--- a/posthog/dags/tests/conftest.py+++ b/posthog/dags/tests/conftest.py@@ -9,6 +9,10 @@ import pytestfrom posthog.test.base import reset_clickhouse_databasefrom unittest.mock import patch+from django.conf import settings++from psycopg.types.json import Jsonb+from posthog.clickhouse.cluster import ClickhouseCluster, get_cluster# Import the shared Dagster PostgreSQL fixtures so they apply to all tests@@ -18,6 +22,40 @@ from posthog.dags.tests.dagster_pg_fixtures import ( # noqa: F401_dagster_postgres_instance,_use_postgres_dagster_instance,)+from posthog.persons_db import persons_db_connection+++def refresh_person_from_persons_db(person) -> None:+ """Reload a Person instance's mutable fields from the persons DB.++ These tests run with the personhog fake off (persons_db_direct) and seed via raw+ psycopg, so the Django ORM cannot read the persons DB. This mirrors the fields+ ``refresh_from_db()`` provided to the assertions, without touching the ORM.+ """+ with persons_db_connection(writer=True) as conn, conn.cursor() as cursor:+ cursor.execute(+ "SELECT properties, version, is_identified, properties_last_updated_at, properties_last_operation "+ f"FROM {settings.PERSON_TABLE_NAME} WHERE team_id = %s AND uuid = %s",+ (person.team_id, person.uuid),+ )+ row = cursor.fetchone()+ assert row is not None, f"person {person.uuid} not found in persons DB"+ (+ person.properties,+ person.version,+ person.is_identified,+ person.properties_last_updated_at,+ person.properties_last_operation,+ ) = row+++def save_person_to_persons_db(person) -> None:+ """Persist a Person instance's properties/version to the persons DB via raw psycopg."""+ with persons_db_connection(writer=True) as conn, conn.cursor() as cursor:+ cursor.execute(+ f"UPDATE {settings.PERSON_TABLE_NAME} SET properties = %s, version = %s WHERE team_id = %s AND uuid = %s",+ (Jsonb(person.properties), person.version, person.team_id, person.uuid),+ )def _patched_get_cluster_hosts(self, client, cluster, retry_policy=None):diff --git a/posthog/dags/tests/max_ai/test_snapshot_team_data.py b/posthog/dags/tests/max_ai/test_snapshot_team_data.pyindex b2b717409e44..5c3512374cf8 100644--- a/posthog/dags/tests/max_ai/test_snapshot_team_data.py+++ b/posthog/dags/tests/max_ai/test_snapshot_team_data.py@@ -315,7 +315,7 @@ def test_snapshot_actors_property_taxonomy_can_be_skipped(@patch("products.posthog_ai.dags.snapshot_team_data.check_dump_exists")@patch("products.posthog_ai.dags.snapshot_team_data.call_query_runner")[email protected]_db(databases=["default", "persons_db_writer"])[email protected]_db(databases=["default"])def test_snapshot_actors_property_taxonomy_dumps_with_group_type_mapping(mock_call_query_runner, mock_check_dump_exists, mock_context, mock_s3, team, mock_dump):diff --git a/posthog/dags/tests/test_detach_distinct_id.py b/posthog/dags/tests/test_detach_distinct_id.pyindex 5814d32cde0c..be8bf30833c0 100644--- a/posthog/dags/tests/test_detach_distinct_id.py+++ b/posthog/dags/tests/test_detach_distinct_id.py@@ -1,4 +1,5 @@import uuid as uuid_module+import contextlibfrom uuid import UUIDimport pytest@@ -13,6 +14,7 @@ from posthog.dags.detach_distinct_id import (detach_distinct_id_job,)from posthog.kafka_client.topics import KAFKA_PERSON_DISTINCT_ID+from posthog.persons_db import persons_db_connectionPERSON_UUID = "5e00024e-cb68-59f6-821f-6150fcffc431"PERSON_PK = 42@@ -330,9 +332,9 @@ class TestDetachDistinctIdIntegration:return Team.objects.create(organization=organization, name="Detach Test Team")- @staticmethod- def _pdi_exists(conn, pdi_id: int) -> bool:- with conn.cursor() as cursor:+ @classmethod+ def _pdi_exists(cls, pdi_id: int) -> bool:+ with cls._get_persons_conn() as conn, conn.cursor() as cursor:cursor.execute("SELECT 1 FROM posthog_persondistinctid WHERE id = %s", [pdi_id])return cursor.fetchone() is not None@@ -340,9 +342,8 @@ class TestDetachDistinctIdIntegration:def person_with_two_distinct_ids(self, team):from posthog.models.utils import UUIDT- conn = self._get_persons_conn()person_uuid = UUIDT()- with conn.cursor() as cursor:+ with self._get_persons_conn() as conn, conn.cursor() as cursor:cursor.execute("INSERT INTO posthog_person (team_id, uuid, properties, is_identified, version, created_at, properties_last_updated_at, properties_last_operation) ""VALUES (%s, %s, '{}', false, 1, NOW(), '{}', '{}') RETURNING id",@@ -385,25 +386,27 @@ class TestDetachDistinctIdIntegration:}@staticmethod+ @contextlib.contextmanagerdef _get_persons_conn():- from django.db import connections-- from posthog.person_db_router import PERSONS_DB_FOR_WRITE-- return connections[PERSONS_DB_FOR_WRITE]+ # autocommit=False: the dagster job consumes this connection as the `persons_database`+ # resource and drives its own commit()/rollback() (dry runs roll back), so it must be+ # transactional rather than autocommit. The cursor-only callers commit on block exit.+ with persons_db_connection(writer=True) as conn:+ yield conn@patch("posthog.dags.detach_distinct_id.sync_execute")def test_dry_run_does_not_delete(self, mock_sync_execute, team, person_with_two_distinct_ids):person, _pdi_keep, pdi_detach = person_with_two_distinct_idsproducer = MagicMock()- result = detach_distinct_id_job.execute_in_process(- run_config=self._run_config(team.id, str(person.uuid), dry_run=True),- resources={"persons_database": self._get_persons_conn(), "kafka_producer": producer},- )+ with self._get_persons_conn() as conn:+ result = detach_distinct_id_job.execute_in_process(+ run_config=self._run_config(team.id, str(person.uuid), dry_run=True),+ resources={"persons_database": conn, "kafka_producer": producer},+ )assert result.success- assert self._pdi_exists(self._get_persons_conn(), pdi_detach.id)+ assert self._pdi_exists(pdi_detach.id)producer.produce.assert_not_called()mock_sync_execute.assert_not_called()@@ -412,18 +415,18 @@ class TestDetachDistinctIdIntegration:person, pdi_keep, pdi_detach = person_with_two_distinct_idsproducer = MagicMock()- result = detach_distinct_id_job.execute_in_process(- run_config=self._run_config(team.id, str(person.uuid), dry_run=False),- resources={"persons_database": self._get_persons_conn(), "kafka_producer": producer},- )+ with self._get_persons_conn() as conn:+ result = detach_distinct_id_job.execute_in_process(+ run_config=self._run_config(team.id, str(person.uuid), dry_run=False),+ resources={"persons_database": conn, "kafka_producer": producer},+ )assert result.success- conn = self._get_persons_conn()# PDI row deleted- assert not self._pdi_exists(conn, pdi_detach.id)+ assert not self._pdi_exists(pdi_detach.id)# Other PDI untouched- assert self._pdi_exists(conn, pdi_keep.id)+ assert self._pdi_exists(pdi_keep.id)# Kafka deletion publishedproducer.produce.assert_called_once()@@ -446,11 +449,12 @@ class TestDetachDistinctIdIntegration:wrong_uuid = str(uuid_module.uuid4())producer = MagicMock()- result = detach_distinct_id_job.execute_in_process(- run_config=self._run_config(team.id, wrong_uuid, dry_run=False),- resources={"persons_database": self._get_persons_conn(), "kafka_producer": producer},- raise_on_error=False,- )+ with self._get_persons_conn() as conn:+ result = detach_distinct_id_job.execute_in_process(+ run_config=self._run_config(team.id, wrong_uuid, dry_run=False),+ resources={"persons_database": conn, "kafka_producer": producer},+ raise_on_error=False,+ )assert not result.successproducer.produce.assert_not_called()@@ -462,9 +466,8 @@ class TestDetachDistinctIdIntegration:from posthog.models.utils import UUIDT- conn = self._get_persons_conn()person_uuid = UUIDT()- with conn.cursor() as cursor:+ with self._get_persons_conn() as conn, conn.cursor() as cursor:cursor.execute("INSERT INTO posthog_person (team_id, uuid, properties, is_identified, version, created_at, properties_last_updated_at, properties_last_operation) ""VALUES (%s, %s, '{}', false, 1, NOW(), '{}', '{}') RETURNING id",@@ -479,11 +482,12 @@ class TestDetachDistinctIdIntegration:person = SimpleNamespace(id=person_id, uuid=person_uuid, version=1)producer = MagicMock()- result = detach_distinct_id_job.execute_in_process(- run_config=self._run_config(team.id, str(person.uuid), dry_run=False),- resources={"persons_database": self._get_persons_conn(), "kafka_producer": producer},- raise_on_error=False,- )+ with self._get_persons_conn() as conn:+ result = detach_distinct_id_job.execute_in_process(+ run_config=self._run_config(team.id, str(person.uuid), dry_run=False),+ resources={"persons_database": conn, "kafka_producer": producer},+ raise_on_error=False,+ )assert not result.successproducer.produce.assert_not_called()@@ -493,11 +497,14 @@ class TestDetachDistinctIdIntegration:def test_fails_when_distinct_id_not_found(self, mock_sync_execute, team):producer = MagicMock()- result = detach_distinct_id_job.execute_in_process(- run_config=self._run_config(team.id, str(uuid_module.uuid4()), dry_run=False, distinct_id="nonexistent"),- resources={"persons_database": self._get_persons_conn(), "kafka_producer": producer},- raise_on_error=False,- )+ with self._get_persons_conn() as conn:+ result = detach_distinct_id_job.execute_in_process(+ run_config=self._run_config(+ team.id, str(uuid_module.uuid4()), dry_run=False, distinct_id="nonexistent"+ ),+ resources={"persons_database": conn, "kafka_producer": producer},+ raise_on_error=False,+ )assert not result.successproducer.produce.assert_not_called()diff --git a/posthog/dags/tests/test_person_property_reconciliation.py b/posthog/dags/tests/test_person_property_reconciliation.pyindex 72a889924ba9..28a2df263901 100644--- a/posthog/dags/tests/test_person_property_reconciliation.py+++ b/posthog/dags/tests/test_person_property_reconciliation.py@@ -38,9 +38,10 @@ from posthog.dags.person_property_reconciliation import (reconcile_with_concurrent_changes,update_person_with_version_check,)+from posthog.dags.tests.conftest import refresh_person_from_persons_db-# Exercises the persons DB directly (raw reads + ORM person creation), so it must run against the-# real persons DB rather than the personhog fake.+# Exercises the persons DB directly (raw reads and writes against the persons writer), so it must+# run against the real persons DB rather than the personhog fake.pytestmark = pytest.mark.persons_db_direct@@ -5884,13 +5885,10 @@ class TestBatchCommitsEndToEnd:def on_batch_committed(batch_num: int, batch_persons: list[dict]) -> None:batch_sizes.append(len(batch_persons))- # Use Django's database connection for persons DB (shares test transaction)- from django.db import connections+ from posthog.persons_db import persons_db_connection- from posthog.person_db_router import PERSONS_DB_FOR_WRITE-- connection = connections[PERSONS_DB_FOR_WRITE]- with connection.cursor() as cursor:+ # Non-autocommit: process_persons_in_batches expects a transactional cursor (its commit_fn drives commits).+ with persons_db_connection(writer=True) as connection, connection.cursor() as cursor:# Set up cursor settingscursor.execute("SET application_name = 'test_batch_commits'")@@ -5917,7 +5915,7 @@ class TestBatchCommitsEndToEnd:# Verify Postgres was actually updated with correct properties and metadatafor i, person in enumerate(persons):- person.refresh_from_db()+ refresh_person_from_persons_db(person)# Property value should be updatedassert person.properties["email"] == f"new_{i}@example.com", (@@ -6068,13 +6066,10 @@ class TestBatchCommitsEndToEnd:def on_batch_committed(batch_num: int, batch_persons: list[dict]) -> None:batch_sizes.append(len(batch_persons))- # Use Django's database connection for persons DB (shares test transaction)- from django.db import connections-- from posthog.person_db_router import PERSONS_DB_FOR_WRITE+ from posthog.persons_db import persons_db_connection- connection = connections[PERSONS_DB_FOR_WRITE]- with connection.cursor() as cursor:+ # Non-autocommit: process_persons_in_batches expects a transactional cursor (its commit_fn drives commits).+ with persons_db_connection(writer=True) as connection, connection.cursor() as cursor:result = process_persons_in_batches(person_property_diffs=person_property_updates,cursor=cursor,@@ -6094,7 +6089,7 @@ class TestBatchCommitsEndToEnd:# Verify existing persons were updated with correct properties and metadatafor i, person in enumerate(persons):- person.refresh_from_db()+ refresh_person_from_persons_db(person)# Property value should be updatedassert person.properties["name"] == f"new_name_{i}", (@@ -6423,15 +6418,10 @@ class TestKafkaClickHouseRoundTrip:cluster.any_host(insert_person_ch).result()- # Get a Postgres connection for the job- from django.db import connections-- from posthog.person_db_router import PERSONS_DB_FOR_WRITE-- persons_conn = connections[PERSONS_DB_FOR_WRITE]+ from posthog.persons_db import persons_db_connection- # Create real Kafka producer- with override_settings(TEST=False):+ # Create real Kafka producer. Non-autocommit: the dagster job drives commit()/rollback() on this resource.+ with persons_db_connection(writer=True) as persons_conn, override_settings(TEST=False):kafka_producer = _KafkaProducer(test=False)try:@@ -6475,7 +6465,7 @@ class TestKafkaClickHouseRoundTrip:kafka_producer.close()# Verify Postgres was updated- person.refresh_from_db()+ refresh_person_from_persons_db(person)assert person.properties["email"] == "[email protected]", (f"Postgres email not updated. Expected '[email protected]', got '{person.properties.get('email')}'")@@ -6699,13 +6689,10 @@ class TestKafkaClickHouseRoundTrip:cluster.any_host(insert_persons_ch_team2).result()# Run the Dagster job- from django.db import connections-- from posthog.person_db_router import PERSONS_DB_FOR_WRITE+ from posthog.persons_db import persons_db_connection- persons_conn = connections[PERSONS_DB_FOR_WRITE]-- with override_settings(TEST=False):+ # Non-autocommit: the dagster job drives commit()/rollback() on this resource connection.+ with persons_db_connection(writer=True) as persons_conn, override_settings(TEST=False):kafka_producer = _KafkaProducer(test=False)try:@@ -6748,7 +6735,7 @@ class TestKafkaClickHouseRoundTrip:# Verify team 1 results in Postgresfor suffix, _person_ts, _event_ts, should_be_reconciled, prop_name in test_cases_team1:person = persons_team1[suffix]- person.refresh_from_db()+ refresh_person_from_persons_db(person)if should_be_reconciled:assert person.properties[prop_name] == "new_value", (@@ -6766,7 +6753,7 @@ class TestKafkaClickHouseRoundTrip:# Verify team 2 results in Postgresfor suffix, _person_ts, _event_ts, should_be_reconciled, prop_name in test_cases_team2:person = persons_team2[suffix]- person.refresh_from_db()+ refresh_person_from_persons_db(person)if should_be_reconciled:assert person.properties[prop_name] == "new_value", (diff --git a/posthog/dags/tests/test_person_property_reconciliation_restore.py b/posthog/dags/tests/test_person_property_reconciliation_restore.pyindex 2bb882235844..8a2b2ba8cee5 100644--- a/posthog/dags/tests/test_person_property_reconciliation_restore.py+++ b/posthog/dags/tests/test_person_property_reconciliation_restore.py@@ -9,8 +9,6 @@ from datetime import UTC, datetimeimport pytest-from django.db import connections-from posthog.dags.person_property_reconciliation_restore import (compute_restore_diff,fetch_backup_entries,@@ -19,11 +17,12 @@ from posthog.dags.person_property_reconciliation_restore import (fetch_persons_by_ids,restore_person_with_version_check,)+from posthog.dags.tests.conftest import refresh_person_from_persons_db, save_person_to_persons_dbfrom posthog.models import Organization, Person, Team-from posthog.person_db_router import PERSONS_DB_FOR_WRITE+from posthog.persons_db import persons_db_connectionfrom posthog.test.persons import create_person-# Exercises the persons DB directly (raw reads against PERSONS_DB_FOR_WRITE), so it must run against+# Exercises the persons DB directly (raw reads against the persons writer), so it must run against# the real persons DB rather than the personhog fake.pytestmark = pytest.mark.persons_db_direct@@ -543,11 +542,6 @@ class TestComputeRestoreDiff:}-def get_persons_db_connection():- """Get the correct database connection for person-related tables."""- return connections[PERSONS_DB_FOR_WRITE]--@pytest.mark.django_db(transaction=True)class TestRestoreIntegration:"""Integration tests for restore functionality using real database."""@@ -556,8 +550,7 @@ class TestRestoreIntegration:def setup_backup_table(self):"""Create the backup table if it doesn't exist."""# Use persons database connection for backup table (since it references person_id)- persons_conn = get_persons_db_connection()- with persons_conn.cursor() as cursor:+ with persons_db_connection(writer=True) as persons_conn, persons_conn.cursor() as cursor:cursor.execute("""CREATE TABLE IF NOT EXISTS posthog_person_reconciliation_backup (job_id TEXT NOT NULL,@@ -605,7 +598,7 @@ class TestRestoreIntegration:"""Test fetching backup entries from database."""job_id = f"test-job-{uuid_module.uuid4()}"- with get_persons_db_connection().cursor() as cursor:+ with persons_db_connection(writer=True) as conn, conn.cursor() as cursor:create_backup_entry(cursor,job_id=job_id,@@ -638,7 +631,7 @@ class TestRestoreIntegration:version=1,)- with get_persons_db_connection().cursor() as cursor:+ with persons_db_connection(writer=True) as conn, conn.cursor() as cursor:create_backup_entry(cursor,job_id=job_id,@@ -677,7 +670,7 @@ class TestRestoreIntegration:version=1,)- with get_persons_db_connection().cursor() as cursor:+ with persons_db_connection(writer=True) as conn, conn.cursor() as cursor:# Create backup entries for both teamscreate_backup_entry(cursor,@@ -724,7 +717,7 @@ class TestRestoreIntegration:)persons.append((team.id, p))- with get_persons_db_connection().cursor() as cursor:+ with persons_db_connection(writer=True) as conn, conn.cursor() as cursor:# Create backup entriesfor team_id, person in persons:create_backup_entry(@@ -775,7 +768,7 @@ class TestRestoreIntegration:)persons[team.id].append(p)- with get_persons_db_connection().cursor() as cursor:+ with persons_db_connection(writer=True) as conn, conn.cursor() as cursor:for team_id, team_persons in persons.items():for person in team_persons:create_backup_entry(@@ -803,7 +796,7 @@ class TestRestoreIntegration:def test_fetch_person_by_id(self, team, person):"""Test fetching person by id."""- with get_persons_db_connection().cursor() as cursor:+ with persons_db_connection(writer=True) as conn, conn.cursor() as cursor:fetched = fetch_person_by_id(cursor, team.id, person.id)assert fetched is not None@@ -826,7 +819,7 @@ class TestRestoreIntegration:person_ids = [p.id for p in persons]- with get_persons_db_connection().cursor() as cursor:+ with persons_db_connection(writer=True) as conn, conn.cursor() as cursor:fetched = fetch_persons_by_ids(cursor, team.id, person_ids)assert len(fetched) == 5@@ -847,7 +840,7 @@ class TestRestoreIntegration:# Include non-existent idsperson_ids = [person.id, 99999, 99998]- with get_persons_db_connection().cursor() as cursor:+ with persons_db_connection(writer=True) as conn, conn.cursor() as cursor:fetched = fetch_persons_by_ids(cursor, team.id, person_ids)# Only the existing person should be returned@@ -860,7 +853,7 @@ class TestRestoreIntegration:"""Test full_overwrite restore overwrites current state."""job_id = f"test-job-{uuid_module.uuid4()}"- with get_persons_db_connection().cursor() as cursor:+ with persons_db_connection(writer=True) as conn, conn.cursor() as cursor:create_backup_entry(cursor,job_id=job_id,@@ -888,7 +881,7 @@ class TestRestoreIntegration:assert success is Trueassert person_data is not None- person.refresh_from_db()+ refresh_person_from_persons_db(person)assert person.properties == {"email": "[email protected]", "name": "Original"}assert person.version == 6@@ -898,9 +891,9 @@ class TestRestoreIntegration:# Set current state to match backup's "after" state for one propertyperson.properties = {"email": "[email protected]", "name": "User Changed This"}- person.save()+ save_person_to_persons_db(person)- with get_persons_db_connection().cursor() as cursor:+ with persons_db_connection(writer=True) as conn, conn.cursor() as cursor:create_backup_entry(cursor,job_id=job_id,@@ -928,7 +921,7 @@ class TestRestoreIntegration:assert success is Trueassert person_data is not None- person.refresh_from_db()+ refresh_person_from_persons_db(person)# email: current == after, so restore to beforeassert person.properties["email"] == "[email protected]"# name: current != after (user changed it), so keep current@@ -939,9 +932,9 @@ class TestRestoreIntegration:job_id = f"test-job-{uuid_module.uuid4()}"person.properties = {"email": "[email protected]", "brand_new": "added_later"}- person.save()+ save_person_to_persons_db(person)- with get_persons_db_connection().cursor() as cursor:+ with persons_db_connection(writer=True) as conn, conn.cursor() as cursor:create_backup_entry(cursor,job_id=job_id,@@ -969,7 +962,7 @@ class TestRestoreIntegration:assert success is Trueassert person_data is not None- person.refresh_from_db()+ refresh_person_from_persons_db(person)# email should be restored to originalassert person.properties["email"] == "[email protected]"# brand_new property added after backup should be preserved@@ -981,7 +974,7 @@ class TestRestoreIntegration:original_properties = dict(person.properties)original_version = person.version- with get_persons_db_connection().cursor() as cursor:+ with persons_db_connection(writer=True) as conn, conn.cursor() as cursor:create_backup_entry(cursor,job_id=job_id,@@ -1007,7 +1000,7 @@ class TestRestoreIntegration:assert success is Trueassert person_data is None # No data for Kafka in dry run- person.refresh_from_db()+ refresh_person_from_persons_db(person)assert person.properties == original_propertiesassert person.version == original_version@@ -1017,9 +1010,9 @@ class TestRestoreIntegration:# Set current to match backup's before stateperson.properties = {"email": "[email protected]"}- person.save()+ save_person_to_persons_db(person)- with get_persons_db_connection().cursor() as cursor:+ with persons_db_connection(writer=True) as conn, conn.cursor() as cursor:create_backup_entry(cursor,job_id=job_id,@@ -1053,8 +1046,7 @@ class TestRestoreJobEndToEnd:@pytest.fixture(autouse=True)def setup_backup_table(self):"""Create the backup table if it doesn't exist."""- persons_conn = get_persons_db_connection()- with persons_conn.cursor() as cursor:+ with persons_db_connection(writer=True) as persons_conn, persons_conn.cursor() as cursor:cursor.execute("""CREATE TABLE IF NOT EXISTS posthog_person_reconciliation_backup (job_id TEXT NOT NULL,@@ -1120,7 +1112,7 @@ class TestRestoreJobEndToEnd:)# Create backup entries- with get_persons_db_connection().cursor() as cursor:+ with persons_db_connection(writer=True) as conn, conn.cursor() as cursor:create_backup_entry(cursor,job_id=job_id,@@ -1144,41 +1136,39 @@ class TestRestoreJobEndToEnd:version_after=3,)- # Create a Postgres resource that returns our connection- persons_conn = get_persons_db_connection()-# Run the job- result = person_property_reconciliation_restore_from_backup.execute_in_process(- run_config={- "ops": {- "get_backup_entries_by_team": {- "config": {- "job_id": job_id,- "conflict_resolution": "full_overwrite",- "dry_run": False,- }- },- "restore_team_chunk": {- "config": {- "job_id": job_id,- "conflict_resolution": "full_overwrite",- "dry_run": False,- }- },- }- },- resources={- "cluster": cluster,- "persons_database": persons_conn,- "kafka_producer": mock_kafka_producer,- },- )+ with persons_db_connection(writer=True) as persons_conn:+ result = person_property_reconciliation_restore_from_backup.execute_in_process(+ run_config={+ "ops": {+ "get_backup_entries_by_team": {+ "config": {+ "job_id": job_id,+ "conflict_resolution": "full_overwrite",+ "dry_run": False,+ }+ },+ "restore_team_chunk": {+ "config": {+ "job_id": job_id,+ "conflict_resolution": "full_overwrite",+ "dry_run": False,+ }+ },+ }+ },+ resources={+ "cluster": cluster,+ "persons_database": persons_conn,+ "kafka_producer": mock_kafka_producer,+ },+ )assert result.success# Verify persons were restored- person1.refresh_from_db()- person2.refresh_from_db()+ refresh_person_from_persons_db(person1)+ refresh_person_from_persons_db(person2)assert person1.properties == {"email": "[email protected]", "name": "Original Name"}assert person1.version == 6@@ -1216,7 +1206,7 @@ class TestRestoreJobEndToEnd:)# Create backup entries for both- with get_persons_db_connection().cursor() as cursor:+ with persons_db_connection(writer=True) as conn, conn.cursor() as cursor:create_backup_entry(cursor,job_id=job_id,@@ -1236,42 +1226,41 @@ class TestRestoreJobEndToEnd:properties_after={"email": "[email protected]"},)- persons_conn = get_persons_db_connection()-# Run the job with team_ids filter - only restore team 1- result = person_property_reconciliation_restore_from_backup.execute_in_process(- run_config={- "ops": {- "get_backup_entries_by_team": {- "config": {- "job_id": job_id,- "team_ids": [team.id],- "conflict_resolution": "full_overwrite",- "dry_run": False,- }- },- "restore_team_chunk": {- "config": {- "job_id": job_id,- "team_ids": [team.id],- "conflict_resolution": "full_overwrite",- "dry_run": False,- }- },- }- },- resources={- "cluster": cluster,- "persons_database": persons_conn,- "kafka_producer": mock_kafka_producer,- },- )+ with persons_db_connection(writer=True) as persons_conn:+ result = person_property_reconciliation_restore_from_backup.execute_in_process(+ run_config={+ "ops": {+ "get_backup_entries_by_team": {+ "config": {+ "job_id": job_id,+ "team_ids": [team.id],+ "conflict_resolution": "full_overwrite",+ "dry_run": False,+ }+ },+ "restore_team_chunk": {+ "config": {+ "job_id": job_id,+ "team_ids": [team.id],+ "conflict_resolution": "full_overwrite",+ "dry_run": False,+ }+ },+ }+ },+ resources={+ "cluster": cluster,+ "persons_database": persons_conn,+ "kafka_producer": mock_kafka_producer,+ },+ )assert result.success# Verify only team 1 person was restored- person1.refresh_from_db()- person2.refresh_from_db()+ refresh_person_from_persons_db(person1)+ refresh_person_from_persons_db(person2)assert person1.properties == {"email": "[email protected]"}assert person2.properties == {"email": "[email protected]"} # Unchanged@@ -1293,7 +1282,7 @@ class TestRestoreJobEndToEnd:original_properties = dict(person.properties)original_version = person.version- with get_persons_db_connection().cursor() as cursor:+ with persons_db_connection(writer=True) as conn, conn.cursor() as cursor:create_backup_entry(cursor,job_id=job_id,@@ -1304,38 +1293,37 @@ class TestRestoreJobEndToEnd:properties_after={"email": "[email protected]"},)- persons_conn = get_persons_db_connection()-- result = person_property_reconciliation_restore_from_backup.execute_in_process(- run_config={- "ops": {- "get_backup_entries_by_team": {- "config": {- "job_id": job_id,- "conflict_resolution": "full_overwrite",- "dry_run": True,- }- },- "restore_team_chunk": {- "config": {- "job_id": job_id,- "conflict_resolution": "full_overwrite",- "dry_run": True,- }- },- }- },- resources={- "cluster": cluster,- "persons_database": persons_conn,- "kafka_producer": mock_kafka_producer,- },- )+ with persons_db_connection(writer=True) as persons_conn:+ result = person_property_reconciliation_restore_from_backup.execute_in_process(+ run_config={+ "ops": {+ "get_backup_entries_by_team": {+ "config": {+ "job_id": job_id,+ "conflict_resolution": "full_overwrite",+ "dry_run": True,+ }+ },+ "restore_team_chunk": {+ "config": {+ "job_id": job_id,+ "conflict_resolution": "full_overwrite",+ "dry_run": True,+ }+ },+ }+ },+ resources={+ "cluster": cluster,+ "persons_database": persons_conn,+ "kafka_producer": mock_kafka_producer,+ },+ )assert result.success# Verify person was NOT modified- person.refresh_from_db()+ refresh_person_from_persons_db(person)assert person.properties == original_propertiesassert person.version == original_version@@ -1373,7 +1361,7 @@ class TestRestoreJobEndToEnd:persons[team.id].append(person)# Create backup entries with distinct "before" data- with get_persons_db_connection().cursor() as cursor:+ with persons_db_connection(writer=True) as conn, conn.cursor() as cursor:for team in teams:t = teams.index(team)for p, person in enumerate(persons[team.id]):@@ -1398,33 +1386,32 @@ class TestRestoreJobEndToEnd:version_after=10 + p,)- persons_conn = get_persons_db_connection()-- result = person_property_reconciliation_restore_from_backup.execute_in_process(- run_config={- "ops": {- "get_backup_entries_by_team": {- "config": {- "job_id": job_id,- "conflict_resolution": "full_overwrite",- "dry_run": False,- }- },- "restore_team_chunk": {- "config": {- "job_id": job_id,- "conflict_resolution": "full_overwrite",- "dry_run": False,- }- },- }- },- resources={- "cluster": cluster,- "persons_database": persons_conn,- "kafka_producer": mock_kafka_producer,- },- )+ with persons_db_connection(writer=True) as persons_conn:+ result = person_property_reconciliation_restore_from_backup.execute_in_process(+ run_config={+ "ops": {+ "get_backup_entries_by_team": {+ "config": {+ "job_id": job_id,+ "conflict_resolution": "full_overwrite",+ "dry_run": False,+ }+ },+ "restore_team_chunk": {+ "config": {+ "job_id": job_id,+ "conflict_resolution": "full_overwrite",+ "dry_run": False,+ }+ },+ }+ },+ resources={+ "cluster": cluster,+ "persons_database": persons_conn,+ "kafka_producer": mock_kafka_producer,+ },+ )assert result.success@@ -1432,7 +1419,7 @@ class TestRestoreJobEndToEnd:for team in teams:t = teams.index(team)for p, person in enumerate(persons[team.id]):- person.refresh_from_db()+ refresh_person_from_persons_db(person)assert person.properties == {"email": f"original_t{t}_p{p}@example.com","team_marker": f"team_{t}",@@ -1471,7 +1458,7 @@ class TestRestoreJobEndToEnd:persons[team.id].append(person)# Create backup entries for all- with get_persons_db_connection().cursor() as cursor:+ with persons_db_connection(writer=True) as conn, conn.cursor() as cursor:for team in teams:t = teams.index(team)for p, person in enumerate(persons[team.id]):@@ -1485,38 +1472,37 @@ class TestRestoreJobEndToEnd:properties_after={"email": f"current_t{t}_p{p}@example.com", "status": "current"},)- persons_conn = get_persons_db_connection()-# Only restore teams 1 and 3 (indices)teams_to_restore = [teams[1].id, teams[3].id]- result = person_property_reconciliation_restore_from_backup.execute_in_process(- run_config={- "ops": {- "get_backup_entries_by_team": {- "config": {- "job_id": job_id,- "team_ids": teams_to_restore,- "conflict_resolution": "full_overwrite",- "dry_run": False,- }- },- "restore_team_chunk": {- "config": {- "job_id": job_id,- "team_ids": teams_to_restore,- "conflict_resolution": "full_overwrite",- "dry_run": False,- }- },- }- },- resources={- "cluster": cluster,- "persons_database": persons_conn,- "kafka_producer": mock_kafka_producer,- },- )+ with persons_db_connection(writer=True) as persons_conn:+ result = person_property_reconciliation_restore_from_backup.execute_in_process(+ run_config={+ "ops": {+ "get_backup_entries_by_team": {+ "config": {+ "job_id": job_id,+ "team_ids": teams_to_restore,+ "conflict_resolution": "full_overwrite",+ "dry_run": False,+ }+ },+ "restore_team_chunk": {+ "config": {+ "job_id": job_id,+ "team_ids": teams_to_restore,+ "conflict_resolution": "full_overwrite",+ "dry_run": False,+ }+ },+ }+ },+ resources={+ "cluster": cluster,+ "persons_database": persons_conn,+ "kafka_producer": mock_kafka_producer,+ },+ )assert result.success@@ -1524,7 +1510,7 @@ class TestRestoreJobEndToEnd:for t_idx in [1, 3]:team = teams[t_idx]for p, person in enumerate(persons[team.id]):- person.refresh_from_db()+ refresh_person_from_persons_db(person)assert person.properties["status"] == "restored", f"Team {t_idx} person {p} should be restored"assert person.properties["email"] == f"original_t{t_idx}_p{p}@example.com"@@ -1532,7 +1518,7 @@ class TestRestoreJobEndToEnd:for t_idx in [0, 2, 4]:team = teams[t_idx]for p, person in enumerate(persons[team.id]):- person.refresh_from_db()+ refresh_person_from_persons_db(person)assert person.properties["status"] == "current", f"Team {t_idx} person {p} should NOT be restored"assert person.properties["email"] == f"current_t{t_idx}_p{p}@example.com"@@ -1568,7 +1554,7 @@ class TestRestoreJobEndToEnd:all_persons.append(person)# Create backup entries for all- with get_persons_db_connection().cursor() as cursor:+ with persons_db_connection(writer=True) as conn, conn.cursor() as cursor:for team in teams:t = teams.index(team)for p, person in enumerate(persons[team.id]):@@ -1582,8 +1568,6 @@ class TestRestoreJobEndToEnd:properties_after={"email": f"current_t{t}_p{p}@example.com", "restored": False},)- persons_conn = get_persons_db_connection()-# Only restore specific persons: first person from each team + last person from team 0persons_to_restore = [persons[teams[0].id][0].id, # team 0, person 0@@ -1592,39 +1576,40 @@ class TestRestoreJobEndToEnd:persons[teams[2].id][0].id, # team 2, person 0]- result = person_property_reconciliation_restore_from_backup.execute_in_process(- run_config={- "ops": {- "get_backup_entries_by_team": {- "config": {- "job_id": job_id,- "person_ids": persons_to_restore,- "conflict_resolution": "full_overwrite",- "dry_run": False,- }- },- "restore_team_chunk": {- "config": {- "job_id": job_id,- "person_ids": persons_to_restore,- "conflict_resolution": "full_overwrite",- "dry_run": False,- }- },- }- },- resources={- "cluster": cluster,- "persons_database": persons_conn,- "kafka_producer": mock_kafka_producer,- },- )+ with persons_db_connection(writer=True) as persons_conn:+ result = person_property_reconciliation_restore_from_backup.execute_in_process(+ run_config={+ "ops": {+ "get_backup_entries_by_team": {+ "config": {+ "job_id": job_id,+ "person_ids": persons_to_restore,+ "conflict_resolution": "full_overwrite",+ "dry_run": False,+ }+ },+ "restore_team_chunk": {+ "config": {+ "job_id": job_id,+ "person_ids": persons_to_restore,+ "conflict_resolution": "full_overwrite",+ "dry_run": False,+ }+ },+ }+ },+ resources={+ "cluster": cluster,+ "persons_database": persons_conn,+ "kafka_producer": mock_kafka_producer,+ },+ )assert result.success# Verify only the selected persons were restoredfor person in all_persons:- person.refresh_from_db()+ refresh_person_from_persons_db(person)if person.id in persons_to_restore:assert person.properties["restored"] is True, f"Person {person.id} should be restored"else:@@ -1665,7 +1650,7 @@ class TestRestoreJobEndToEnd:persons[team.id].append(person)# Create backup entries for all- with get_persons_db_connection().cursor() as cursor:+ with persons_db_connection(writer=True) as conn, conn.cursor() as cursor:for team in teams:t = teams.index(team)for p, person in enumerate(persons[team.id]):@@ -1689,8 +1674,6 @@ class TestRestoreJobEndToEnd:},)- persons_conn = get_persons_db_connection()-# Filter to teams 0 and 2, AND persons 1 and 3 within those teams# This should restore: team0/person1, team0/person3, team2/person1, team2/person3teams_to_restore = [teams[0].id, teams[2].id]@@ -1701,35 +1684,36 @@ class TestRestoreJobEndToEnd:persons[teams[2].id][3].id,]- result = person_property_reconciliation_restore_from_backup.execute_in_process(- run_config={- "ops": {- "get_backup_entries_by_team": {- "config": {- "job_id": job_id,- "team_ids": teams_to_restore,- "person_ids": persons_to_restore,- "conflict_resolution": "full_overwrite",- "dry_run": False,- }- },- "restore_team_chunk": {- "config": {- "job_id": job_id,- "team_ids": teams_to_restore,- "person_ids": persons_to_restore,- "conflict_resolution": "full_overwrite",- "dry_run": False,- }- },- }- },- resources={- "cluster": cluster,- "persons_database": persons_conn,- "kafka_producer": mock_kafka_producer,- },- )+ with persons_db_connection(writer=True) as persons_conn:+ result = person_property_reconciliation_restore_from_backup.execute_in_process(+ run_config={+ "ops": {+ "get_backup_entries_by_team": {+ "config": {+ "job_id": job_id,+ "team_ids": teams_to_restore,+ "person_ids": persons_to_restore,+ "conflict_resolution": "full_overwrite",+ "dry_run": False,+ }+ },+ "restore_team_chunk": {+ "config": {+ "job_id": job_id,+ "team_ids": teams_to_restore,+ "person_ids": persons_to_restore,+ "conflict_resolution": "full_overwrite",+ "dry_run": False,+ }+ },+ }+ },+ resources={+ "cluster": cluster,+ "persons_database": persons_conn,+ "kafka_producer": mock_kafka_producer,+ },+ )assert result.success@@ -1744,7 +1728,7 @@ class TestRestoreJobEndToEnd:for team in teams:t = teams.index(team)for p, person in enumerate(persons[team.id]):- person.refresh_from_db()+ refresh_person_from_persons_db(person)should_restore = expected_restored.get((t, p), False)if should_restore:@@ -1789,7 +1773,7 @@ class TestRestoreJobEndToEnd:persons[team.id].append(person)# Create backup entries - "before" doesn't have new_after_backup- with get_persons_db_connection().cursor() as cursor:+ with persons_db_connection(writer=True) as conn, conn.cursor() as cursor:for team in teams:t = teams.index(team)for p, person in enumerate(persons[team.id]):@@ -1809,33 +1793,32 @@ class TestRestoreJobEndToEnd:},)- persons_conn = get_persons_db_connection()-- result = person_property_reconciliation_restore_from_backup.execute_in_process(- run_config={- "ops": {- "get_backup_entries_by_team": {- "config": {- "job_id": job_id,- "conflict_resolution": "restore_wins",- "dry_run": False,- }- },- "restore_team_chunk": {- "config": {- "job_id": job_id,- "conflict_resolution": "restore_wins",- "dry_run": False,- }- },- }- },- resources={- "cluster": cluster,- "persons_database": persons_conn,- "kafka_producer": mock_kafka_producer,- },- )+ with persons_db_connection(writer=True) as persons_conn:+ result = person_property_reconciliation_restore_from_backup.execute_in_process(+ run_config={+ "ops": {+ "get_backup_entries_by_team": {+ "config": {+ "job_id": job_id,+ "conflict_resolution": "restore_wins",+ "dry_run": False,+ }+ },+ "restore_team_chunk": {+ "config": {+ "job_id": job_id,+ "conflict_resolution": "restore_wins",+ "dry_run": False,+ }+ },+ }+ },+ resources={+ "cluster": cluster,+ "persons_database": persons_conn,+ "kafka_producer": mock_kafka_producer,+ },+ )assert result.success@@ -1845,7 +1828,7 @@ class TestRestoreJobEndToEnd:for team in teams:t = teams.index(team)for p, person in enumerate(persons[team.id]):- person.refresh_from_db()+ refresh_person_from_persons_db(person)assert person.properties == {"email": f"original_t{t}_p{p}@example.com","name": f"Original Name {t}_{p}",@@ -1883,7 +1866,7 @@ class TestRestoreJobEndToEnd:)persons[team.id].append(person)- with get_persons_db_connection().cursor() as cursor:+ with persons_db_connection(writer=True) as conn, conn.cursor() as cursor:for team in teams:t = teams.index(team)for p, person in enumerate(persons[team.id]):@@ -1897,36 +1880,35 @@ class TestRestoreJobEndToEnd:properties_after={"email": f"current_t{t}_p{p}@example.com"},)- persons_conn = get_persons_db_connection()-# Run with batch_size=2 to test pagination (3 batches: 2, 2, 1)- result = person_property_reconciliation_restore_from_backup.execute_in_process(- run_config={- "ops": {- "get_backup_entries_by_team": {- "config": {- "job_id": job_id,- "conflict_resolution": "full_overwrite",- "dry_run": False,- "backup_batch_size": 2,- }- },- "restore_team_chunk": {- "config": {- "job_id": job_id,- "conflict_resolution": "full_overwrite",- "dry_run": False,- "backup_batch_size": 2,- }- },- }- },- resources={- "cluster": cluster,- "persons_database": persons_conn,- "kafka_producer": mock_kafka_producer,- },- )+ with persons_db_connection(writer=True) as persons_conn:+ result = person_property_reconciliation_restore_from_backup.execute_in_process(+ run_config={+ "ops": {+ "get_backup_entries_by_team": {+ "config": {+ "job_id": job_id,+ "conflict_resolution": "full_overwrite",+ "dry_run": False,+ "backup_batch_size": 2,+ }+ },+ "restore_team_chunk": {+ "config": {+ "job_id": job_id,+ "conflict_resolution": "full_overwrite",+ "dry_run": False,+ "backup_batch_size": 2,+ }+ },+ }+ },+ resources={+ "cluster": cluster,+ "persons_database": persons_conn,+ "kafka_producer": mock_kafka_producer,+ },+ )assert result.success@@ -1934,7 +1916,7 @@ class TestRestoreJobEndToEnd:for team in teams:t = teams.index(team)for p, person in enumerate(persons[team.id]):- person.refresh_from_db()+ refresh_person_from_persons_db(person)assert person.properties == {"email": f"original_t{t}_p{p}@example.com","restored": True,diff --git a/posthog/demo/test/test_persons_db_sync.py b/posthog/demo/test/test_persons_db_sync.pyindex 5f65ad8549d0..028f10318e97 100644--- a/posthog/demo/test/test_persons_db_sync.py+++ b/posthog/demo/test/test_persons_db_sync.py@@ -22,7 +22,7 @@ SYNC_TEST_PROJECT_ID = 2_000_000_010SYNC_TEST_TARGET_TEAM_ID = 2_000_000_011SYNC_TEST_TARGET_PROJECT_ID = 2_000_000_011-pytestmark = pytest.mark.django_db(databases=["persons_db_writer", "persons_db_reader"])+pytestmark = pytest.mark.django_db()def _cleanup(conn: psycopg.Connection[Any]) -> None:diff --git a/posthog/hogql/database/schema/test/test_system_tables.py b/posthog/hogql/database/schema/test/test_system_tables.pyindex 95b39fa8df21..d48e1c9a2991 100644--- a/posthog/hogql/database/schema/test/test_system_tables.py+++ b/posthog/hogql/database/schema/test/test_system_tables.py@@ -19,11 +19,8 @@ from posthog.models import Group, GroupTypeMapping, GroupUsageMetric, Organizatifrom posthog.models.activity_logging.activity_log import ActivityLogfrom posthog.models.project import Projectfrom posthog.models.scoping import team_scope-from posthog.person_db_router import allow_persons_orm-from posthog.test.persons import (- create_group as _create_group_helper,- create_group_type_mapping,-)+from posthog.persons_db import persons_db_connection+from posthog.persons_seed import insert_seed_group, insert_seed_group_type_mappingfrom products.actions.backend.models.action import Actionfrom products.ai_observability.backend.models.review_queues import ReviewQueue, ReviewQueueItem@@ -360,15 +357,28 @@ def _create_feature_flag(team: Team, label: str) -> FeatureFlag:def _create_group(team: Team, label: str) -> Group:- with allow_persons_orm():- return _create_group_helper(team=team, group_key=f"group_{label}", group_type_index=0, version=0)+ # Seed straight into the persons DB (off-Django psycopg) — the federated system table reads+ # it back from there. The personhog fake stays active for the HogQL Database build, so this+ # bypasses it deliberately via the low-level insert.+ with persons_db_connection(writer=True, autocommit=True) as conn:+ group_id = insert_seed_group(+ conn, team_id=team.id, group_key=f"group_{label}", group_type_index=0, group_properties={}, version=0+ )+ group = Group(team_id=team.id, group_key=f"group_{label}", group_type_index=0, group_properties={})+ group.id = group_id+ return groupdef _create_group_type_mapping(team: Team, label: str) -> GroupTypeMapping:- with allow_persons_orm():- return create_group_type_mapping(- team=team, project=team.project, group_type=f"type_{label}", group_type_index=0+ with persons_db_connection(writer=True, autocommit=True) as conn:+ mapping_id = insert_seed_group_type_mapping(+ conn, project_id=team.project_id, team_id=team.id, group_type=f"type_{label}", group_type_index=0)+ mapping = GroupTypeMapping(+ project_id=team.project_id, team_id=team.id, group_type=f"type_{label}", group_type_index=0+ )+ mapping.id = mapping_id+ return mappingdef _create_integration(team: Team, label: str):@@ -674,12 +684,22 @@ SYSTEM_TABLE_FACTORIES = [class TestSystemTablesTeamIsolation(NonAtomicBaseTest):"""Create entities in two teams and query via ClickHouse's postgresql() function- to verify each team only sees its own data."""+ to verify each team only sees its own data.++ Group/group_type_mapping rows are seeded straight into the persons DB via psycopg (what the+ federated system table reads), while the personhog fake stays active so the HogQL Database+ build's group-type lookup resolves. setUp truncates those persons tables because the psycopg+ writes commit outside Django's per-test transaction."""CLASS_DATA_LEVEL_SETUP = Falsedef setUp(self):super().setUp()+ # The group factories commit to the persons DB outside Django's transaction, so clear them+ # here for per-test isolation (this class isn't persons_db_direct, so the autouse truncate+ # fixture doesn't run).+ with persons_db_connection(writer=True, autocommit=True) as conn, conn.cursor() as cursor:+ cursor.execute("TRUNCATE TABLE posthog_group, posthog_grouptypemapping RESTART IDENTITY CASCADE")other_org = Organization.objects.create(name="other_org")other_project = Project.objects.create(id=Team.objects.increment_id_sequence(), organization=other_org)self.other_team = Team.objects.create(id=other_project.id, project=other_project, organization=other_org)diff --git a/posthog/local_bootstrap/test_local_bootstrap.py b/posthog/local_bootstrap/test_local_bootstrap.pyindex be231946dbb1..7667139c357f 100644--- a/posthog/local_bootstrap/test_local_bootstrap.py+++ b/posthog/local_bootstrap/test_local_bootstrap.py@@ -165,7 +165,7 @@ class TestWritePersonsToPostgres: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"])+ @pytest.mark.django_db()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"diff --git a/posthog/management/commands/test/test_background_delete_model.py b/posthog/management/commands/test/test_background_delete_model.pyindex f6b573ab2724..18718c93b414 100644--- a/posthog/management/commands/test/test_background_delete_model.py+++ b/posthog/management/commands/test/test_background_delete_model.py@@ -1,14 +1,16 @@-import pytest+from uuid import uuid4+from posthog.test.base import BaseTestfrom unittest.mock import MagicMock, patchfrom django.core.management.base import CommandErrorfrom posthog.management.commands.background_delete_model import Command-from posthog.models.person.person import Person-from posthog.test.persons import create_person+from posthog.models import Tag-pytestmark = pytest.mark.persons_db_direct+# Uses a plain main-DB, team-scoped model (Tag) as the deletion target — the command is+# model-agnostic, so the specific model is incidental. (It deliberately does NOT target persons+# models: the deletion task runs against the default connection and can't reach the persons DB.)class TestBackgroundDeleteModel(BaseTest):@@ -55,24 +57,24 @@ class TestBackgroundDeleteModel(BaseTest):"""Test that valid model with team_id field starts background task"""mock_task.delay.return_value = MagicMock(id="test-task-id")- # Create some test persons- create_person(team=self.team, properties={})- create_person(team=self.team, properties={})+ # Create some records to delete+ Tag.objects.create(team=self.team, name=str(uuid4()))+ Tag.objects.create(team=self.team, name=str(uuid4()))- self.command.handle("posthog.Person", team_id=self.team.id)+ self.command.handle("posthog.Tag", team_id=self.team.id)# Verify task was calledmock_task.delay.assert_called_once_with(- model_name="posthog.Person", team_id=self.team.id, batch_size=10000, records_to_delete=2+ model_name="posthog.Tag", team_id=self.team.id, batch_size=10000, records_to_delete=2)@patch("posthog.management.commands.background_delete_model.background_delete_model_task")def test_dry_run_does_not_start_task(self, mock_task):"""Test that dry run shows info but doesn't start task"""- # Create some test persons- create_person(team=self.team, properties={})+ # Create some records to delete+ Tag.objects.create(team=self.team, name=str(uuid4()))- self.command.handle("posthog.Person", team_id=self.team.id, dry_run=True)+ self.command.handle("posthog.Tag", team_id=self.team.id, dry_run=True)# Verify task was not calledmock_task.delay.assert_not_called()@@ -107,10 +109,10 @@ class TestBackgroundDeleteModel(BaseTest):@patch("builtins.input", return_value="CANCEL")def test_confirmation_cancelled(self, mock_input, mock_task):"""Test that task is not started when confirmation is cancelled"""- # Create some test persons- create_person(team=self.team, properties={})+ # Create some records to delete+ Tag.objects.create(team=self.team, name=str(uuid4()))- self.command.handle("posthog.Person", team_id=self.team.id)+ self.command.handle("posthog.Tag", team_id=self.team.id)# Verify task was not calledmock_task.delay.assert_not_called()@@ -144,9 +146,9 @@ class TestBackgroundDeleteModel(BaseTest):def test_zero_records_exits_early(self):"""Test that command exits early when no records found"""- # Don't create any persons, so count will be 0+ # Don't create any records, so count will be 0- self.command.handle("posthog.Person", team_id=self.team.id)+ self.command.handle("posthog.Tag", team_id=self.team.id)# No need to mock task since it should never be called@@ -155,32 +157,32 @@ class TestBackgroundDeleteModel(BaseTest):with patch("posthog.management.commands.background_delete_model.background_delete_model_task") as mock_task:mock_task.delay.return_value = MagicMock(id="test-task-id")- # Create some test persons- create_person(team=self.team, properties={})- create_person(team=self.team, properties={})+ # Create some records to delete+ Tag.objects.create(team=self.team, name=str(uuid4()))+ Tag.objects.create(team=self.team, name=str(uuid4()))# Try to use a batch size larger than the limitwith patch("builtins.input", return_value="DELETE 2 RECORDS"):- self.command.handle("posthog.Person", team_id=self.team.id, batch_size=100000)+ self.command.handle("posthog.Tag", team_id=self.team.id, batch_size=100000)# Verify task was called with the limited batch sizemock_task.delay.assert_called_once_with(- model_name="posthog.Person", team_id=self.team.id, batch_size=50000, records_to_delete=2+ model_name="posthog.Tag", team_id=self.team.id, batch_size=50000, records_to_delete=2)@patch("posthog.management.commands.background_delete_model.background_delete_model_task")@patch("builtins.input", return_value="DELETE 2 RECORDS")def test_synchronous_execution(self, mock_input, mock_task):"""Test that synchronous flag runs task directly instead of using .delay()"""- # Create some test persons- create_person(team=self.team, properties={})- create_person(team=self.team, properties={})+ # Create some records to delete+ Tag.objects.create(team=self.team, name=str(uuid4()))+ Tag.objects.create(team=self.team, name=str(uuid4()))- self.command.handle("posthog.Person", team_id=self.team.id, synchronous=True)+ self.command.handle("posthog.Tag", team_id=self.team.id, synchronous=True)# Verify task was called directly (not with .delay())mock_task.assert_called_once_with(- model_name="posthog.Person", team_id=self.team.id, batch_size=10000, records_to_delete=2+ model_name="posthog.Tag", team_id=self.team.id, batch_size=10000, records_to_delete=2)# Verify .delay() was not calledmock_task.delay.assert_not_called()@@ -197,27 +199,27 @@ class TestBackgroundDeleteModel(BaseTest):team2 = Team.objects.create(organization=self.organization, name="Team 2")# Create persons across multiple teams- create_person(team=self.team, properties={}) # Team 1- create_person(team=self.team, properties={}) # Team 1- create_person(team=team2, properties={}) # Team 2- create_person(team=team2, properties={}) # Team 2- create_person(team=team2, properties={}) # Team 2+ Tag.objects.create(team=self.team, name=str(uuid4())) # Team 1+ Tag.objects.create(team=self.team, name=str(uuid4())) # Team 1+ Tag.objects.create(team=team2, name=str(uuid4())) # Team 2+ Tag.objects.create(team=team2, name=str(uuid4())) # Team 2+ Tag.objects.create(team=team2, name=str(uuid4())) # Team 2# Verify initial counts- self.assertEqual(Person.objects.filter(team=self.team).count(), 2)- self.assertEqual(Person.objects.filter(team=team2).count(), 3)+ self.assertEqual(Tag.objects.filter(team=self.team).count(), 2)+ self.assertEqual(Tag.objects.filter(team=team2).count(), 3)# Run command for team 1 only- self.command.handle("posthog.Person", team_id=self.team.id)+ self.command.handle("posthog.Tag", team_id=self.team.id)# Verify task was called with correct team_idmock_task.delay.assert_called_once_with(- model_name="posthog.Person", team_id=self.team.id, batch_size=10000, records_to_delete=2+ model_name="posthog.Tag", team_id=self.team.id, batch_size=10000, records_to_delete=2)# Verify counts haven't changed (since we're just testing the command, not the actual deletion)- self.assertEqual(Person.objects.filter(team=self.team).count(), 2)- self.assertEqual(Person.objects.filter(team=team2).count(), 3)+ self.assertEqual(Tag.objects.filter(team=self.team).count(), 2)+ self.assertEqual(Tag.objects.filter(team=team2).count(), 3)def test_max_delete_size_limit(self):"""Test that deletion is limited to max_delete_size when total count exceeds it"""diff --git a/posthog/management/commands/test/test_sync_persons_to_clickhouse.py b/posthog/management/commands/test/test_sync_persons_to_clickhouse.pyindex f9513e4c3c92..9f1deebe51ee 100644--- a/posthog/management/commands/test/test_sync_persons_to_clickhouse.py+++ b/posthog/management/commands/test/test_sync_persons_to_clickhouse.py@@ -6,6 +6,8 @@ import pytestfrom posthog.test.base import ClickhouseTestMixin, NonAtomicBaseTestfrom unittest import mock+from psycopg.types.json import Jsonb+import posthog.management.commands.sync_persons_to_clickhousefrom posthog.clickhouse.client import sync_executefrom posthog.management.commands.sync_persons_to_clickhouse import (@@ -14,17 +16,16 @@ from posthog.management.commands.sync_persons_to_clickhouse import (run_group_sync,run_person_sync,)-from posthog.models.group.group import Groupfrom posthog.models.group.sql import TRUNCATE_GROUPS_TABLE_SQLfrom posthog.models.group.util import raw_create_group_ch-from posthog.models.person.person import Person, PersonDistinctIdfrom posthog.models.person.sql import (PERSON_DISTINCT_ID2_TABLE,TRUNCATE_PERSON_DISTINCT_ID2_TABLE_SQL,TRUNCATE_PERSON_TABLE_SQL,)from posthog.models.person.util import create_person, create_person_distinct_id-from posthog.models.signals import mute_selected_signals+from posthog.persons_db import persons_db_connection+from posthog.persons_seed import insert_seed_distinct_id, insert_seed_group, insert_seed_personpytestmark = pytest.mark.persons_db_direct@@ -43,13 +44,15 @@ class TestSyncPersonsToClickHouse(NonAtomicBaseTest, ClickhouseTestMixin):sync_execute(TRUNCATE_GROUPS_TABLE_SQL)def test_persons_sync(self):- with mute_selected_signals(): # without creating/updating in clickhouse- person = Person.objects.create(+ person_uuid = uuid4()+ with persons_db_connection(writer=True, autocommit=True) as conn:+ insert_seed_person(+ conn,team_id=self.team.pk,properties={"a": 1234},is_identified=True,version=4,- uuid=uuid4(),+ uuid=person_uuid,)run_person_sync(self.team.pk, live_run=True, deletes=False)@@ -60,16 +63,18 @@ class TestSyncPersonsToClickHouse(NonAtomicBaseTest, ClickhouseTestMixin):""",{"team_id": self.team.pk},)- self.assertEqual(ch_persons, [(person.uuid, self.team.pk, '{"a": 1234}', True, 4, False)])+ self.assertEqual(ch_persons, [(person_uuid, self.team.pk, '{"a": 1234}', True, 4, False)])def test_persons_sync_with_null_version(self):- with mute_selected_signals(): # without creating/updating in clickhouse- person = Person.objects.create(+ person_uuid = uuid4()+ with persons_db_connection(writer=True, autocommit=True) as conn:+ insert_seed_person(+ conn,team_id=self.team.pk,properties={"a": 1234},is_identified=True,version=None,- uuid=uuid4(),+ uuid=person_uuid,)run_person_sync(self.team.pk, live_run=True, deletes=False)@@ -80,7 +85,7 @@ class TestSyncPersonsToClickHouse(NonAtomicBaseTest, ClickhouseTestMixin):""",{"team_id": self.team.pk},)- self.assertEqual(ch_persons, [(person.uuid, self.team.pk, '{"a": 1234}', True, 0, False)])+ self.assertEqual(ch_persons, [(person_uuid, self.team.pk, '{"a": 1234}', True, 0, False)])def test_persons_deleted(self):uuid = create_person(@@ -101,9 +106,10 @@ class TestSyncPersonsToClickHouse(NonAtomicBaseTest, ClickhouseTestMixin):self.assertEqual(ch_persons, [(UUID(uuid), self.team.pk, "{}", False, 105, True)])def test_distinct_ids_sync(self):- with mute_selected_signals(): # without creating/updating in clickhouse- person = Person.objects.create(team_id=self.team.pk, version=0, uuid=uuid4())- PersonDistinctId.objects.create(team=self.team, person=person, distinct_id="test-id", version=4)+ person_uuid = uuid4()+ with persons_db_connection(writer=True, autocommit=True) as conn:+ person_id = insert_seed_person(conn, team_id=self.team.pk, properties={}, version=0, uuid=person_uuid)+ insert_seed_distinct_id(conn, team_id=self.team.pk, person_id=person_id, distinct_id="test-id", version=4)run_distinct_id_sync(self.team.pk, live_run=True, deletes=False)@@ -113,12 +119,16 @@ class TestSyncPersonsToClickHouse(NonAtomicBaseTest, ClickhouseTestMixin):""",{"team_id": self.team.pk},)- self.assertEqual(ch_person_distinct_ids, [(person.uuid, self.team.pk, "test-id", 4, False)])+ self.assertEqual(ch_person_distinct_ids, [(person_uuid, self.team.pk, "test-id", 4, False)])def test_distinct_ids_sync_with_null_version(self):- with mute_selected_signals(): # without creating/updating in clickhouse- person = Person.objects.create(team_id=self.team.pk, version=0, uuid=uuid4())- PersonDistinctId.objects.create(team=self.team, person=person, distinct_id="test-id", version=None)+ person_uuid = uuid4()+ with persons_db_connection(writer=True, autocommit=True) as conn:+ person_id = insert_seed_person(conn, team_id=self.team.pk, properties={}, version=0, uuid=person_uuid)+ # version=None exercises the sync's NULL->0 coercion (the point of this test).+ insert_seed_distinct_id(+ conn, team_id=self.team.pk, person_id=person_id, distinct_id="test-id", version=None+ )run_distinct_id_sync(self.team.pk, live_run=True, deletes=False)@@ -128,7 +138,7 @@ class TestSyncPersonsToClickHouse(NonAtomicBaseTest, ClickhouseTestMixin):""",{"team_id": self.team.pk},)- self.assertEqual(ch_person_distinct_ids, [(person.uuid, self.team.pk, "test-id", 0, False)])+ self.assertEqual(ch_person_distinct_ids, [(person_uuid, self.team.pk, "test-id", 0, False)])def test_distinct_ids_deleted(self):uuid = uuid4()@@ -158,14 +168,16 @@ class TestSyncPersonsToClickHouse(NonAtomicBaseTest, ClickhouseTestMixin):)def test_group_sync(self, mocked_ch_call):ts = datetime.now(UTC)- Group.objects.create(- team_id=self.team.pk,- group_type_index=2,- group_key="group-key",- group_properties={"a": 1234},- created_at=ts,- version=5,- )+ with persons_db_connection(writer=True, autocommit=True) as conn:+ insert_seed_group(+ conn,+ team_id=self.team.pk,+ group_type_index=2,+ group_key="group-key",+ group_properties={"a": 1234},+ created_at=ts,+ version=5,+ )run_group_sync(self.team.pk, live_run=True)mocked_ch_call.assert_called_once()@@ -193,17 +205,22 @@ class TestSyncPersonsToClickHouse(NonAtomicBaseTest, ClickhouseTestMixin):)def test_group_sync_updates_group(self, mocked_ch_call):ts = datetime.now(UTC) - timedelta(hours=3)- group = Group.objects.create(- team_id=self.team.pk,- group_type_index=2,- group_key="group-key",- group_properties={"a": 5},- created_at=ts,- version=0,- )+ with persons_db_connection(writer=True, autocommit=True) as conn:+ group_id = insert_seed_group(+ conn,+ team_id=self.team.pk,+ group_type_index=2,+ group_key="group-key",+ group_properties={"a": 5},+ created_at=ts,+ version=0,+ )raw_create_group_ch(self.team.pk, 2, "group-key", {"a": 5}, ts)- group.group_properties = {"a": 5, "b": 3}- group.save()+ with persons_db_connection(writer=True, autocommit=True) as conn, conn.cursor() as cursor:+ cursor.execute(+ "UPDATE posthog_group SET group_properties = %s WHERE id = %s",+ (Jsonb({"a": 5, "b": 3}), group_id),+ )ts_before = datetime.now(UTC)run_group_sync(self.team.pk, live_run=True)@@ -222,7 +239,7 @@ class TestSyncPersonsToClickHouse(NonAtomicBaseTest, ClickhouseTestMixin):self.assertEqual(ch_group[2], '{"a": 5, "b": 3}')self.assertEqual(ch_group[3].strftime("%Y-%m-%d %H:%M:%S"),- group.created_at.strftime("%Y-%m-%d %H:%M:%S"),+ ts.strftime("%Y-%m-%d %H:%M:%S"),)self.assertGreaterEqual(ch_group[4].strftime("%Y-%m-%d %H:%M:%S"),@@ -243,30 +260,34 @@ class TestSyncPersonsToClickHouse(NonAtomicBaseTest, ClickhouseTestMixin):)def test_group_sync_multiple_entries(self, mocked_ch_call):ts = datetime.now(UTC)- Group.objects.create(- team_id=self.team.pk,- group_type_index=2,- group_key="group-key",- group_properties={"a": 1234},- created_at=ts,- version=5,- )- Group.objects.create(- team_id=self.team.pk,- group_type_index=2,- group_key="group-key-2",- group_properties={"a": 12345},- created_at=ts,- version=6,- )- Group.objects.create(- team_id=self.team.pk,- group_type_index=1,- group_key="group-key",- group_properties={"a": 123456},- created_at=ts,- version=7,- )+ with persons_db_connection(writer=True, autocommit=True) as conn:+ insert_seed_group(+ conn,+ team_id=self.team.pk,+ group_type_index=2,+ group_key="group-key",+ group_properties={"a": 1234},+ created_at=ts,+ version=5,+ )+ insert_seed_group(+ conn,+ team_id=self.team.pk,+ group_type_index=2,+ group_key="group-key-2",+ group_properties={"a": 12345},+ created_at=ts,+ version=6,+ )+ insert_seed_group(+ conn,+ team_id=self.team.pk,+ group_type_index=1,+ group_key="group-key",+ group_properties={"a": 123456},+ created_at=ts,+ version=7,+ )run_group_sync(self.team.pk, live_run=True)self.assertEqual(mocked_ch_call.call_count, 3)@@ -300,59 +321,68 @@ class TestSyncPersonsToClickHouse(NonAtomicBaseTest, ClickhouseTestMixin):def everything_test_run(self, live_run):# 2 persons who shouldn't be changed- person_not_changed_1 = Person.objects.create(- team_id=self.team.pk, properties={"abcdef": 1111}, version=0, uuid=uuid4()- )- create_person(- team_id=self.team.pk,- properties=person_not_changed_1.properties,- uuid=str(person_not_changed_1.uuid),- version=person_not_changed_1.version or 0,- )- person_not_changed_2 = Person.objects.create(- team_id=self.team.pk, properties={"abcdefg": 11112}, version=1, uuid=uuid4()- )- create_person(- team_id=self.team.pk,- properties=person_not_changed_2.properties,- uuid=str(person_not_changed_2.uuid),- version=person_not_changed_2.version or 0,- )+ person_not_changed_1_uuid = uuid4()+ person_not_changed_2_uuid = uuid4()+ person_should_be_created_1_uuid = uuid4()+ person_should_be_created_2_uuid = uuid4()+ person_should_update_1_uuid = uuid4()+ person_should_update_2_uuid = uuid4()+ with persons_db_connection(writer=True, autocommit=True) as conn:+ person_not_changed_1_id = insert_seed_person(+ conn, team_id=self.team.pk, properties={"abcdef": 1111}, version=0, uuid=person_not_changed_1_uuid+ )+ person_not_changed_2_id = insert_seed_person(+ conn, team_id=self.team.pk, properties={"abcdefg": 11112}, version=1, uuid=person_not_changed_2_uuid+ )- # 2 persons who should be created- with mute_selected_signals(): # without creating/updating in clickhouse- person_should_be_created_1 = Person.objects.create(+ # 2 persons who should be created+ insert_seed_person(+ conn,team_id=self.team.pk,properties={"abcde": 12553633},version=2,- uuid=uuid4(),+ uuid=person_should_be_created_1_uuid,)- person_should_be_created_2 = Person.objects.create(+ insert_seed_person(+ conn,team_id=self.team.pk,properties={"abcdeit34": 12553633},version=3,- uuid=uuid4(),+ uuid=person_should_be_created_2_uuid,)# 2 persons who have updates- person_should_update_1 = Person.objects.create(+ insert_seed_person(+ conn,team_id=self.team.pk,properties={"abcde": 12553},version=5,- uuid=uuid4(),+ uuid=person_should_update_1_uuid,)- person_should_update_2 = Person.objects.create(- team_id=self.team.pk, properties={"abc": 125}, version=7, uuid=uuid4()+ insert_seed_person(+ conn, team_id=self.team.pk, properties={"abc": 125}, version=7, uuid=person_should_update_2_uuid)create_person(- uuid=str(person_should_update_1.uuid),- team_id=person_should_update_1.team_id,+ team_id=self.team.pk,+ properties={"abcdef": 1111},+ uuid=str(person_not_changed_1_uuid),+ version=0,+ )+ create_person(+ team_id=self.team.pk,+ properties={"abcdefg": 11112},+ uuid=str(person_not_changed_2_uuid),+ version=1,+ )+ create_person(+ uuid=str(person_should_update_1_uuid),+ team_id=self.team.pk,properties={"a": 13},version=4,)create_person(- uuid=str(person_should_update_2.uuid),- team_id=person_should_update_2.team_id,+ uuid=str(person_should_update_2_uuid),+ team_id=self.team.pk,properties={"a": 1},version=6,)@@ -372,72 +402,78 @@ class TestSyncPersonsToClickHouse(NonAtomicBaseTest, ClickhouseTestMixin):)# 2 distinct id no update- PersonDistinctId.objects.create(- team=self.team,- person=person_not_changed_1,- distinct_id="distinct_id",- version=0,- )- create_person_distinct_id(- team_id=self.team.pk,- distinct_id="distinct_id",- person_id=str(person_not_changed_1.uuid),- is_deleted=False,- version=0,- )- PersonDistinctId.objects.create(- team=self.team,- person=person_not_changed_1,- distinct_id="distinct_id-9",- version=9,- )- create_person_distinct_id(- team_id=self.team.pk,- distinct_id="distinct_id-9",- person_id=str(person_not_changed_1.uuid),- is_deleted=False,- version=9,- )+ with persons_db_connection(writer=True, autocommit=True) as conn:+ insert_seed_distinct_id(+ conn,+ team_id=self.team.pk,+ person_id=person_not_changed_1_id,+ distinct_id="distinct_id",+ version=0,+ )+ insert_seed_distinct_id(+ conn,+ team_id=self.team.pk,+ person_id=person_not_changed_1_id,+ distinct_id="distinct_id-9",+ version=9,+ )- # # 2 distinct id to be created- with mute_selected_signals(): # without creating/updating in clickhouse- PersonDistinctId.objects.create(- team=self.team,- person=person_not_changed_1,+ # 2 distinct id to be created+ insert_seed_distinct_id(+ conn,+ team_id=self.team.pk,+ person_id=person_not_changed_1_id,distinct_id="distinct_id-10",version=10,)- PersonDistinctId.objects.create(- team=self.team,- person=person_not_changed_1,+ insert_seed_distinct_id(+ conn,+ team_id=self.team.pk,+ person_id=person_not_changed_1_id,distinct_id="distinct_id-11",version=11,)# 2 distinct id that need to update- PersonDistinctId.objects.create(- team=self.team,- person=person_not_changed_2,+ insert_seed_distinct_id(+ conn,+ team_id=self.team.pk,+ person_id=person_not_changed_2_id,distinct_id="distinct_id-12",version=13,)- PersonDistinctId.objects.create(- team=self.team,- person=person_not_changed_2,+ insert_seed_distinct_id(+ conn,+ team_id=self.team.pk,+ person_id=person_not_changed_2_id,distinct_id="distinct_id-14",version=15,)+ create_person_distinct_id(+ team_id=self.team.pk,+ distinct_id="distinct_id",+ person_id=str(person_not_changed_1_uuid),+ is_deleted=False,+ version=0,+ )+ create_person_distinct_id(+ team_id=self.team.pk,+ distinct_id="distinct_id-9",+ person_id=str(person_not_changed_1_uuid),+ is_deleted=False,+ version=9,+ )create_person_distinct_id(team_id=self.team.pk,distinct_id="distinct_id-12",- person_id=str(person_not_changed_1.uuid),+ person_id=str(person_not_changed_1_uuid),is_deleted=False,version=12,)create_person_distinct_id(team_id=self.team.pk,distinct_id="distinct_id-14",- person_id=str(person_not_changed_1.uuid),+ person_id=str(person_not_changed_1_uuid),is_deleted=False,version=14,)@@ -460,14 +496,16 @@ class TestSyncPersonsToClickHouse(NonAtomicBaseTest, ClickhouseTestMixin):version=18,)- Group.objects.create(- team_id=self.team.pk,- group_type_index=2,- group_key="group-key",- group_properties={"a": 1234},- created_at=datetime.now(UTC) - timedelta(hours=3),- version=5,- )+ with persons_db_connection(writer=True, autocommit=True) as conn:+ insert_seed_group(+ conn,+ team_id=self.team.pk,+ group_type_index=2,+ group_key="group-key",+ group_properties={"a": 1234},+ created_at=datetime.now(UTC) - timedelta(hours=3),+ version=5,+ )# Run the script for everythingoptions = {@@ -505,7 +543,7 @@ class TestSyncPersonsToClickHouse(NonAtomicBaseTest, ClickhouseTestMixin):ch_persons,[(- person_not_changed_1.uuid,+ person_not_changed_1_uuid,self.team.pk,'{"abcdef": 1111}',False,@@ -513,7 +551,7 @@ class TestSyncPersonsToClickHouse(NonAtomicBaseTest, ClickhouseTestMixin):False,),(- person_not_changed_2.uuid,+ person_not_changed_2_uuid,self.team.pk,'{"abcdefg": 11112}',False,@@ -521,7 +559,7 @@ class TestSyncPersonsToClickHouse(NonAtomicBaseTest, ClickhouseTestMixin):False,),(- person_should_update_1.uuid,+ person_should_update_1_uuid,self.team.pk,'{"a": 13}',False,@@ -529,7 +567,7 @@ class TestSyncPersonsToClickHouse(NonAtomicBaseTest, ClickhouseTestMixin):False,),(- person_should_update_2.uuid,+ person_should_update_2_uuid,self.team.pk,'{"a": 1}',False,@@ -557,23 +595,23 @@ class TestSyncPersonsToClickHouse(NonAtomicBaseTest, ClickhouseTestMixin):self.assertEqual(ch_person_distinct_ids,[- (person_not_changed_1.uuid, self.team.pk, "distinct_id", 0, False),+ (person_not_changed_1_uuid, self.team.pk, "distinct_id", 0, False),(- person_not_changed_1.uuid,+ person_not_changed_1_uuid,self.team.pk,"distinct_id-9",9,False,),(- person_not_changed_1.uuid,+ person_not_changed_1_uuid,self.team.pk,"distinct_id-12",12,False,),(- person_not_changed_1.uuid,+ person_not_changed_1_uuid,self.team.pk,"distinct_id-14",14,@@ -601,7 +639,7 @@ class TestSyncPersonsToClickHouse(NonAtomicBaseTest, ClickhouseTestMixin):ch_persons,[(- person_not_changed_1.uuid,+ person_not_changed_1_uuid,self.team.pk,'{"abcdef": 1111}',False,@@ -609,7 +647,7 @@ class TestSyncPersonsToClickHouse(NonAtomicBaseTest, ClickhouseTestMixin):False,),(- person_not_changed_2.uuid,+ person_not_changed_2_uuid,self.team.pk,'{"abcdefg": 11112}',False,@@ -617,7 +655,7 @@ class TestSyncPersonsToClickHouse(NonAtomicBaseTest, ClickhouseTestMixin):False,),(- person_should_be_created_1.uuid,+ person_should_be_created_1_uuid,self.team.pk,'{"abcde": 12553633}',False,@@ -625,7 +663,7 @@ class TestSyncPersonsToClickHouse(NonAtomicBaseTest, ClickhouseTestMixin):False,),(- person_should_be_created_2.uuid,+ person_should_be_created_2_uuid,self.team.pk,'{"abcdeit34": 12553633}',False,@@ -633,7 +671,7 @@ class TestSyncPersonsToClickHouse(NonAtomicBaseTest, ClickhouseTestMixin):False,),(- person_should_update_1.uuid,+ person_should_update_1_uuid,self.team.pk,'{"abcde": 12553}',False,@@ -641,7 +679,7 @@ class TestSyncPersonsToClickHouse(NonAtomicBaseTest, ClickhouseTestMixin):False,),(- person_should_update_2.uuid,+ person_should_update_2_uuid,self.team.pk,'{"abc": 125}',False,@@ -655,37 +693,37 @@ class TestSyncPersonsToClickHouse(NonAtomicBaseTest, ClickhouseTestMixin):self.assertEqual(ch_person_distinct_ids,[- (person_not_changed_1.uuid, self.team.pk, "distinct_id", 0, False),+ (person_not_changed_1_uuid, self.team.pk, "distinct_id", 0, False),(- person_not_changed_1.uuid,+ person_not_changed_1_uuid,self.team.pk,"distinct_id-9",9,False,),(- person_not_changed_1.uuid,+ person_not_changed_1_uuid,self.team.pk,"distinct_id-10",10,False,),(- person_not_changed_1.uuid,+ person_not_changed_1_uuid,self.team.pk,"distinct_id-11",11,False,),(- person_not_changed_2.uuid,+ person_not_changed_2_uuid,self.team.pk,"distinct_id-12",13,False,),(- person_not_changed_2.uuid,+ person_not_changed_2_uuid,self.team.pk,"distinct_id-14",15,diff --git a/posthog/models/test/test_person_schema.py b/posthog/models/test/test_person_schema.pyindex 4598f807579d..4a64d7bbf3fc 100644--- a/posthog/models/test/test_person_schema.py+++ b/posthog/models/test/test_person_schema.py@@ -3,15 +3,15 @@import pytestfrom django.conf import settings-from django.db import connectionsfrom django.test import TestCasefrom posthog.models.person import Person+from posthog.persons_db import persons_db_connection-def table_exists(table_name: str, database: str = "persons_db_writer") -> bool:- """Check if a table exists in the specified database."""- with connections[database].cursor() as cursor:+def table_exists(table_name: str) -> bool:+ """Check if a table exists in the persons database via off-Django psycopg."""+ with persons_db_connection(writer=True, autocommit=True) as conn, conn.cursor() as cursor:cursor.execute("""SELECT EXISTS (@@ -21,14 +21,13 @@ def table_exists(table_name: str, database: str = "persons_db_writer") -> bool:""",[table_name],)- return cursor.fetchone()[0]+ row = cursor.fetchone()+ return bool(row[0]) if row else Falseclass TestPersonSchemaConsistency(TestCase):"""Smoke test that Rust sqlx migrations ran successfully."""- databases = {"default", "persons_db_writer"}-def test_posthog_person_exists(self):"""Verify posthog_person table exists in persons_db after Rust sqlx migrations."""self.assertTrue(diff --git a/posthog/personhog_client/fake_client.py b/posthog/personhog_client/fake_client.pyindex 00036d88f40c..56f5b1185b57 100644--- a/posthog/personhog_client/fake_client.py+++ b/posthog/personhog_client/fake_client.py@@ -746,6 +746,15 @@ def get_active_fake() -> FakePersonHogClient:return _active_fake+def personhog_fake_active() -> bool:+ """Whether a personhog fake is active for the current test.++ The test seed helpers use this to choose between seeding the fake (fake active, the default)+ and writing the real persons DB via off-Django psycopg (fake off — persons_db_direct tests).+ """+ return _active_fake is not None++@contextmanagerdef activate_personhog_fake():"""Activate a FakePersonHogClient for the duration of a test.diff --git a/posthog/persons_seed.py b/posthog/persons_seed.pyindex 0a0dc8e49bf3..3a67eb9b4a62 100644--- a/posthog/persons_seed.py+++ b/posthog/persons_seed.py@@ -16,6 +16,7 @@ from __future__ import annotationsimport uuid as uuid_libimport dataclasses+from datetime import datetimefrom typing import Anyfrom django.conf import settings@@ -37,18 +38,37 @@ def insert_seed_person(properties: dict[str, Any],is_identified: bool = False,uuid: str | uuid_lib.UUID | None = None,+ version: int | None = None,+ created_at: datetime | None = None,+ last_seen_at: datetime | None = None,+ properties_last_updated_at: dict[str, Any] | None = None,+ properties_last_operation: dict[str, Any] | None = None,) -> int:"""Insert one person row and return its database id.Pass ``uuid`` when the caller needs to reference the person downstream (e.g. to- mirror it into ClickHouse); otherwise a fresh ``UUIDT`` is generated.+ mirror it into ClickHouse); otherwise a fresh ``UUIDT`` is generated. ``created_at``+ defaults to ``now()`` (matching the model's ``auto_now_add``); ``version``,+ ``last_seen_at`` and the ``properties_last_*`` maps default to NULL, mirroring+ ``Person.objects.create`` with no override."""with conn.cursor() as cursor:cursor.execute(f"INSERT INTO {settings.PERSON_TABLE_NAME} "- "(created_at, properties, is_identified, uuid, team_id) "- "VALUES (now(), %s, %s, %s, %s) RETURNING id",- (Jsonb(properties), is_identified, uuid or UUIDT(), team_id),+ "(created_at, properties, is_identified, uuid, team_id, version, last_seen_at, "+ "properties_last_updated_at, properties_last_operation) "+ "VALUES (COALESCE(%s, now()), %s, %s, %s, %s, %s, %s, %s, %s) RETURNING id",+ (+ created_at,+ Jsonb(properties),+ is_identified,+ uuid or UUIDT(),+ team_id,+ version,+ last_seen_at,+ Jsonb(properties_last_updated_at) if properties_last_updated_at is not None else None,+ Jsonb(properties_last_operation) if properties_last_operation is not None else None,+ ),)row = cursor.fetchone()assert row is not None # RETURNING always yields a row on a successful insert@@ -61,12 +81,17 @@ def insert_seed_distinct_id(team_id: int,person_id: int,distinct_id: str,+ version: int | None = 0,) -> None:- """Insert one distinct-id row linking ``distinct_id`` to ``person_id``."""+ """Insert one distinct-id row linking ``distinct_id`` to ``person_id``.++ ``version`` defaults to 0 but accepts ``None`` to write a NULL version (the column is+ nullable), mirroring ``PersonDistinctId.objects.create(version=None)``.+ """with conn.cursor() as cursor:cursor.execute(- f"INSERT INTO {PERSON_DISTINCT_ID_TABLE} (distinct_id, person_id, team_id) VALUES (%s, %s, %s)",- (distinct_id, person_id, team_id),+ f"INSERT INTO {PERSON_DISTINCT_ID_TABLE} (distinct_id, person_id, team_id, version) VALUES (%s, %s, %s, %s)",+ (distinct_id, person_id, team_id, version),)@@ -78,15 +103,60 @@ def insert_seed_group(group_type_index: int,group_properties: dict[str, Any],version: int = 0,-) -> None:- """Insert one group row. ``created_at``/``version`` are NOT NULL with no DB default."""+ created_at: datetime | None = None,+) -> int:+ """Insert one group row and return its id. ``created_at`` defaults to ``now()``; ``version`` is NOT NULL."""with conn.cursor() as cursor:cursor.execute("INSERT INTO posthog_group ""(team_id, group_key, group_type_index, group_properties, created_at, version) "- "VALUES (%s, %s, %s, %s, now(), %s)",- (team_id, group_key, group_type_index, Jsonb(group_properties), version),+ "VALUES (%s, %s, %s, %s, COALESCE(%s, now()), %s) RETURNING id",+ (team_id, group_key, group_type_index, Jsonb(group_properties), created_at, version),)+ row = cursor.fetchone()+ assert row is not None # RETURNING always yields a row on a successful insert+ return row[0]+++def insert_seed_group_type_mapping(+ conn: psycopg.Connection[Any],+ *,+ project_id: int,+ team_id: int | None,+ group_type: str,+ group_type_index: int,+ name_singular: str | None = None,+ name_plural: str | None = None,+ default_columns: list[str] | None = None,+ detail_dashboard_id: int | None = None,+ created_at: datetime | None = None,+) -> int:+ """Insert one group-type-mapping row and return its id.++ ``created_at`` is written as given (``None`` stays NULL — the model's custom ``save()`` stamps+ created_at only on insert, which this bypasses); callers pass ``now()`` for the normal case.+ """+ with conn.cursor() as cursor:+ cursor.execute(+ "INSERT INTO posthog_grouptypemapping "+ "(project_id, team_id, group_type, group_type_index, name_singular, name_plural, "+ "default_columns, detail_dashboard_id, created_at) "+ "VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s) RETURNING id",+ (+ project_id,+ team_id,+ group_type,+ group_type_index,+ name_singular,+ name_plural,+ default_columns,+ detail_dashboard_id,+ created_at,+ ),+ )+ row = cursor.fetchone()+ assert row is not None # RETURNING always yields a row on a successful insert+ return row[0]def update_seed_person(diff --git a/posthog/temporal/tests/backfill_group_type_created_at/test_activities.py b/posthog/temporal/tests/backfill_group_type_created_at/test_activities.pyindex d635541783b7..eb8304eeb1db 100644--- a/posthog/temporal/tests/backfill_group_type_created_at/test_activities.py+++ b/posthog/temporal/tests/backfill_group_type_created_at/test_activities.py@@ -7,8 +7,7 @@ from unittest.mock import patchfrom asgiref.sync import sync_to_asyncfrom posthog.models import Team-from posthog.models.group_type_mapping import GroupTypeMapping-from posthog.person_db_router import PERSONS_DB_FOR_WRITE+from posthog.persons_db import persons_db_connectionfrom posthog.temporal.backfill_group_type_created_at.activities import (_build_backfill_plan,apply_group_type_created_at_backfill,@@ -107,21 +106,22 @@ def _seed_event(team: Team, distinct_id: str, group_index: int, group_key: str,def _read_created_at(project_id: int, index: int) -> datetime | None:- return (- GroupTypeMapping.objects.using(PERSONS_DB_FOR_WRITE) # nosemgrep: no-direct-persons-db-orm- .get(project_id=project_id, group_type_index=index)- .created_at- )+ with persons_db_connection(writer=True) as conn, conn.cursor() as cursor:+ cursor.execute(+ "SELECT created_at FROM posthog_grouptypemapping WHERE project_id = %s AND group_type_index = %s",+ (project_id, index),+ )+ row = cursor.fetchone()+ return row[0] if row else None[email protected]_db(transaction=True, databases=["default", "persons_db_writer", "persons_db_reader"])[email protected]_db(transaction=True)class TestPlanGroupTypeCreatedAtBackfillIntegration:@pytest.fixture(autouse=True)def setup(self, team, activity_environment):self.team = teamself.activity_environment = activity_environmentyield- GroupTypeMapping.objects.filter(project_id=self.team.project_id).delete()@pytest.mark.asyncioasync def test_lowers_created_at_to_earliest_event(self):@@ -252,14 +252,13 @@ class TestPlanGroupTypeCreatedAtBackfillIntegration:assert datetime.fromisoformat(result["updates"][0]["new_created_at"]) == datetime(2023, 3, 1, tzinfo=UTC)[email protected]_db(transaction=True, databases=["default", "persons_db_writer", "persons_db_reader"])[email protected]_db(transaction=True)class TestApplyGroupTypeCreatedAtBackfillIntegration:@pytest.fixture(autouse=True)def setup(self, team, activity_environment):self.team = teamself.activity_environment = activity_environmentyield- GroupTypeMapping.objects.filter(project_id=self.team.project_id).delete()def _update(self, index: int, new_created_at: datetime) -> GroupTypeUpdate:return {@@ -336,8 +335,6 @@ class TestApplyGroupTypeCreatedAtBackfillIntegration:# The other project's mapping must be untouched.assert await sync_to_async(_read_created_at)(other_project_id, 0) == MAPPING_CREATED_AT- await sync_to_async(GroupTypeMapping.objects.filter(project_id=other_project_id).delete)()-@pytest.mark.asyncioasync def test_invalidates_group_types_cache(self):@sync_to_asyncdiff --git a/posthog/temporal/tests/sync_person_distinct_ids/test_activities.py b/posthog/temporal/tests/sync_person_distinct_ids/test_activities.pyindex 295ede5a61da..53125584e00f 100644--- a/posthog/temporal/tests/sync_person_distinct_ids/test_activities.py+++ b/posthog/temporal/tests/sync_person_distinct_ids/test_activities.py@@ -6,8 +6,6 @@ import pytestfrom asgiref.sync import sync_to_async-from posthog.models.person import Person, PersonDistinctId-from posthog.person_db_router import PERSONS_DB_FOR_WRITEfrom posthog.temporal.sync_person_distinct_ids.activities import (FindOrphanedPersonsInputs,FindOrphanedPersonsResult,@@ -31,6 +29,7 @@ from posthog.temporal.tests.sync_person_distinct_ids.conftest import (insert_distinct_id_to_ch,insert_person_to_ch,)+from posthog.test.persons import add_distinct_id, create_personpytestmark = pytest.mark.persons_db_direct@@ -48,12 +47,6 @@ class TestFindOrphanedPersons:yieldcleanup_ch_test_data(self.team.id, self.created_person_uuids, self.created_distinct_ids)- PersonDistinctId.objects.db_manager(PERSONS_DB_FOR_WRITE).filter(- team=self.team, distinct_id__startswith=self.prefix- ).delete()- Person.objects.db_manager(PERSONS_DB_FOR_WRITE).filter(- team=self.team, uuid__in=self.created_person_uuids- ).delete()@pytest.mark.asyncioasync def test_finds_orphaned_persons_without_distinct_ids(self):@@ -136,12 +129,6 @@ class TestLookupPgDistinctIds:yieldcleanup_ch_test_data(self.team.id, self.created_person_uuids, self.created_distinct_ids)- PersonDistinctId.objects.db_manager(PERSONS_DB_FOR_WRITE).filter(- team=self.team, distinct_id__startswith=self.prefix- ).delete()- Person.objects.db_manager(PERSONS_DB_FOR_WRITE).filter(- team=self.team, uuid__in=self.created_person_uuids- ).delete()@pytest.mark.asyncioasync def test_finds_distinct_ids_for_fixable_orphans(self):@@ -152,10 +139,8 @@ class TestLookupPgDistinctIds:@sync_to_asyncdef create_person_with_did():- person = Person.objects.db_manager(PERSONS_DB_FOR_WRITE).create(team=self.team, uuid=person_uuid)- PersonDistinctId.objects.db_manager(PERSONS_DB_FOR_WRITE).create(- team=self.team, person=person, distinct_id=distinct_id, version=0- )+ person = create_person(team=self.team, uuid=person_uuid)+ add_distinct_id(person=person, distinct_id=distinct_id, version=0)await create_person_with_did()@@ -191,10 +176,10 @@ class TestLookupPgDistinctIds:self.created_person_uuids.extend([truly_orphaned_uuid, ch_only_uuid])@sync_to_async- def create_person():- Person.objects.db_manager(PERSONS_DB_FOR_WRITE).create(team=self.team, uuid=truly_orphaned_uuid)+ def _seed():+ create_person(team=self.team, uuid=truly_orphaned_uuid)- await create_person()+ await _seed()result: LookupPgDistinctIdsResult = await self.activity_environment.run(lookup_pg_distinct_ids,@@ -224,11 +209,9 @@ class TestLookupPgDistinctIds:@sync_to_asyncdef create_person_with_dids():- person = Person.objects.db_manager(PERSONS_DB_FOR_WRITE).create(team=self.team, uuid=person_uuid)+ person = create_person(team=self.team, uuid=person_uuid)for i, distinct_id in enumerate(distinct_ids):- PersonDistinctId.objects.db_manager(PERSONS_DB_FOR_WRITE).create(- team=self.team, person=person, distinct_id=distinct_id, version=i- )+ add_distinct_id(person=person, distinct_id=distinct_id, version=i)await create_person_with_dids()@@ -466,12 +449,6 @@ class TestEndToEndOrphanCategories:yieldcleanup_ch_test_data(self.team.id, self.created_person_uuids, self.created_distinct_ids)- PersonDistinctId.objects.db_manager(PERSONS_DB_FOR_WRITE).filter(- team=self.team, distinct_id__startswith=self.prefix- ).delete()- Person.objects.db_manager(PERSONS_DB_FOR_WRITE).filter(- team=self.team, uuid__in=self.created_person_uuids- ).delete()@pytest.mark.asyncioasync def test_categorizes_all_three_orphan_types(self):@@ -488,12 +465,10 @@ class TestEndToEndOrphanCategories:@sync_to_asyncdef create_pg_data():# Fixable: Person in PG with DID- person = Person.objects.db_manager(PERSONS_DB_FOR_WRITE).create(team=self.team, uuid=fixable_uuid)- PersonDistinctId.objects.db_manager(PERSONS_DB_FOR_WRITE).create(- team=self.team, person=person, distinct_id=fixable_did, version=0- )+ person = create_person(team=self.team, uuid=fixable_uuid)+ add_distinct_id(person=person, distinct_id=fixable_did, version=0)# Truly orphaned: Person in PG, no DID- Person.objects.db_manager(PERSONS_DB_FOR_WRITE).create(team=self.team, uuid=truly_orphaned_uuid)+ create_person(team=self.team, uuid=truly_orphaned_uuid)# CH-only: No PG dataawait create_pg_data()diff --git a/posthog/temporal/tests/sync_person_distinct_ids/test_workflow.py b/posthog/temporal/tests/sync_person_distinct_ids/test_workflow.pyindex dcce474f1915..8885c037c3a9 100644--- a/posthog/temporal/tests/sync_person_distinct_ids/test_workflow.py+++ b/posthog/temporal/tests/sync_person_distinct_ids/test_workflow.py@@ -9,8 +9,8 @@ from asgiref.sync import sync_to_asyncfrom temporalio.testing import WorkflowEnvironmentfrom temporalio.worker import Worker-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 insert_seed_distinct_id, insert_seed_personfrom posthog.temporal.sync_person_distinct_ids.activities import (find_orphaned_persons,lookup_pg_distinct_ids,@@ -54,12 +54,6 @@ class TestSyncPersonDistinctIdsWorkflow:yieldcleanup_ch_test_data(self.team.id, self.created_person_uuids, self.created_distinct_ids)- PersonDistinctId.objects.db_manager(PERSONS_DB_FOR_WRITE).filter(- team=self.team, distinct_id__startswith=self.prefix- ).delete()- Person.objects.db_manager(PERSONS_DB_FOR_WRITE).filter(- team=self.team, uuid__in=self.created_person_uuids- ).delete()async def _create_test_data(self):"""Create 100 orphaned persons across all three categories."""@@ -87,26 +81,19 @@ class TestSyncPersonDistinctIdsWorkflow:insert_persons_to_ch_batch(self.team.id, self.created_person_uuids, version=0)# Create PG data for fixable and truly orphaned+ # Persons-DB rows only (no ClickHouse): the fixable persons are orphans precisely because+ # their distinct id lives in PG but not CH, so use the low-level inserts rather than the+ # create_person/add_distinct_id helpers (which also mirror into ClickHouse).@sync_to_asyncdef create_pg_data():- # Fixable: Person in PG with DID - use bulk_create for efficiency- fixable_persons = [Person(team=self.team, uuid=person_uuid) for person_uuid in self.fixable_uuids]- created_persons = Person.objects.db_manager(PERSONS_DB_FOR_WRITE).bulk_create(fixable_persons)-- # Create distinct IDs for fixable persons- distinct_id_objects = []- for i, person in enumerate(created_persons):- distinct_id = f"{self.prefix}-fixable-{i}"- distinct_id_objects.append(- PersonDistinctId(team=self.team, person=person, distinct_id=distinct_id, version=0)- )- PersonDistinctId.objects.db_manager(PERSONS_DB_FOR_WRITE).bulk_create(distinct_id_objects)-- # Truly orphaned: Person in PG, no DID - use bulk_create- truly_orphaned_persons = [- Person(team=self.team, uuid=person_uuid) for person_uuid in self.truly_orphaned_uuids- ]- Person.objects.db_manager(PERSONS_DB_FOR_WRITE).bulk_create(truly_orphaned_persons)+ with persons_db_connection(writer=True, autocommit=True) as conn:+ for i, person_uuid in enumerate(self.fixable_uuids):+ person_id = insert_seed_person(conn, team_id=self.team.id, properties={}, uuid=person_uuid)+ insert_seed_distinct_id(+ conn, team_id=self.team.id, person_id=person_id, distinct_id=f"{self.prefix}-fixable-{i}"+ )+ for person_uuid in self.truly_orphaned_uuids:+ insert_seed_person(conn, team_id=self.team.id, properties={}, uuid=person_uuid)await create_pg_data()diff --git a/posthog/test/base.py b/posthog/test/base.pyindex 5089fb6b9ef7..aa692116a5b3 100644--- a/posthog/test/base.py+++ b/posthog/test/base.py@@ -662,8 +662,7 @@ class PostHogTestCase(SimpleTestCase):# to `False` will set up test data on every test case instead.CLASS_DATA_LEVEL_SETUP = True- # Allow tests to use the persons databases (for Person/PersonDistinctId models)- databases = {"default", "persons_db_writer", "persons_db_reader"}+ databases = {"default"}# Test data definition stubsorganization: Organization = cast(Organization, None)@@ -895,25 +894,7 @@ class NonAtomicBaseTest(PostHogTestCase, ErrorResponsesMixin, TransactionTestCas# Required when models are moved between Django apps, as PostgreSQL# needs CASCADE to handle FK constraints across app boundaries.for db_name in cast(Any, self)._databases_names(include_mirrors=False):- if db_name in ("persons_db_writer", "persons_db_reader"):- # Manually truncate persons database tables- # Can't use Django's flush because it emits post_migrate signals that try to- # create contenttypes/permissions tables that don't exist in persons database- conn = connections[db_name]- 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:- call_command("flush", verbosity=0, interactive=False, database=db_name, allow_cascade=True)+ call_command("flush", verbosity=0, interactive=False, database=db_name, allow_cascade=True)class NonAtomicBaseTestKeepIdentities(PostHogTestCase, ErrorResponsesMixin, TransactionTestCase):@@ -932,23 +913,13 @@ class NonAtomicBaseTestKeepIdentities(PostHogTestCase, ErrorResponsesMixin, Tranfor db_name in cast(Any, self)._databases_names(include_mirrors=False):conn = connections[db_name]with conn.cursor() as cursor:- if db_name in ("persons_db_writer", "persons_db_reader"):- 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'- """)- else:- cursor.execute("""- SELECT tablename- FROM pg_tables- WHERE schemaname = 'public'- AND tablename NOT LIKE 'pg_%'- AND tablename NOT LIKE 'django_%'- """)+ cursor.execute("""+ SELECT tablename+ FROM pg_tables+ WHERE schemaname = 'public'+ AND tablename NOT LIKE 'pg_%'+ AND tablename NOT LIKE 'django_%'+ """)tables = [row[0] for row in cursor.fetchall()]if tables:cursor.execute(f"TRUNCATE TABLE {', '.join(tables)} CASCADE")diff --git a/posthog/test/persons.py b/posthog/test/persons.pyindex f454efca39e7..d309829e2036 100644--- a/posthog/test/persons.py+++ b/posthog/test/persons.py@@ -28,7 +28,13 @@ from posthog.models.person.util import (create_person_distinct_id as _ch_create_person_distinct_id,)from posthog.models.utils import UUIDT-from posthog.person_db_router import persons_orm_blocked+from posthog.persons_db import persons_db_connection+from posthog.persons_seed import (+ insert_seed_distinct_id,+ insert_seed_group,+ insert_seed_group_type_mapping,+ insert_seed_person,+)if TYPE_CHECKING:import uuid@@ -285,8 +291,8 @@ def create_person(*, team: Team | None = None, distinct_ids: list[str] | None =dids = [str(d) for d in (distinct_ids or [])]- if not persons_orm_blocked():- return _create_person_in_orm(create_kwargs, dids)+ if _get_active_fake() is None:+ return _create_person_in_persons_db(create_kwargs, dids)person = _build_person(create_kwargs)person._distinct_ids = list(dids)@@ -295,13 +301,34 @@ def create_person(*, team: Team | None = None, distinct_ids: list[str] | None =return person-def _create_person_in_orm(create_kwargs: dict[str, Any], dids: list[str]) -> Person:- """Write a real persons-DB person + distinct ids (for fake-off / excluded tests)."""- if not create_kwargs.get("uuid"):- create_kwargs["uuid"] = UUIDT()- person = Person.objects.create(**create_kwargs)- for distinct_id in dids:- PersonDistinctId.objects.create(team_id=person.team_id, person=person, distinct_id=distinct_id, version=0)+def _create_person_in_persons_db(create_kwargs: dict[str, Any], dids: list[str]) -> Person:+ """Write a real persons-DB person + distinct ids via off-Django psycopg (fake-off / excluded tests).++ Builds the Person instance to resolve the same field defaults Person.objects.create would+ (uuid, created_at, version), then inserts directly so this path needs no Django persons connection.+ """+ person = Person(**create_kwargs)+ if not person.uuid:+ person.uuid = UUIDT()+ person.created_at = person.created_at or now()++ with persons_db_connection(writer=True, autocommit=True) as conn:+ person.id = insert_seed_person(+ conn,+ team_id=person.team_id,+ properties=person.properties or {},+ is_identified=person.is_identified,+ uuid=person.uuid,+ version=person.version,+ created_at=person.created_at,+ last_seen_at=person.last_seen_at,+ properties_last_updated_at=person.properties_last_updated_at,+ properties_last_operation=person.properties_last_operation,+ )+ for distinct_id in dids:+ insert_seed_distinct_id(conn, team_id=person.team_id, person_id=person.id, distinct_id=distinct_id)++ person._state.adding = Falseperson._distinct_ids = list(dids)_ch_sync_person(person, dids)return person@@ -359,10 +386,12 @@ def add_distinct_id(*, person: Person, distinct_id: str, version: int = 0) -> Peif existing_distinct_ids is not None and distinct_id not in existing_distinct_ids:existing_distinct_ids.append(distinct_id)- if not persons_orm_blocked():- return PersonDistinctId.objects.create(- team_id=person.team_id, person=person, distinct_id=str(distinct_id), version=version- )+ if _get_active_fake() is None:+ with persons_db_connection(writer=True, autocommit=True) as conn:+ insert_seed_distinct_id(+ conn, team_id=person.team_id, person_id=person.pk, distinct_id=str(distinct_id), version=version+ )+ return PersonDistinctId(team_id=person.team_id, person=person, distinct_id=str(distinct_id), version=version)_seed_distinct_id_into_fake(person.team_id, person.pk, distinct_id, version=version)return PersonDistinctId(team_id=person.team_id, person=person, distinct_id=distinct_id, version=version)@@ -447,8 +476,22 @@ def create_group(*, team: Team | None = None, group_type_index: int, group_key:if team is not None:create_kwargs["team"] = team- if not persons_orm_blocked():- return Group.objects.create(**create_kwargs)+ if _get_active_fake() is None:+ group = Group(**create_kwargs)+ group.created_at = group.created_at or now()+ group.version = group.version or 0+ with persons_db_connection(writer=True, autocommit=True) as conn:+ group.id = insert_seed_group(+ conn,+ team_id=group.team_id,+ group_key=group.group_key,+ group_type_index=group.group_type_index,+ group_properties=group.group_properties or {},+ version=group.version,+ created_at=group.created_at,+ )+ group._state.adding = False+ return groupgroup = Group(**create_kwargs)group.id = _next_synthetic_pk()@@ -477,8 +520,25 @@ def create_group_type_mapping(*, team: Team | None = None, **kwargs: Any) -> Groif team is not None:kwargs["team"] = team- if not persons_orm_blocked():- return GroupTypeMapping.objects.create(**kwargs)+ if _get_active_fake() is None:+ mapping = GroupTypeMapping(**kwargs)+ if mapping.created_at is None:+ mapping.created_at = now()+ with persons_db_connection(writer=True, autocommit=True) as conn:+ mapping.id = insert_seed_group_type_mapping(+ conn,+ project_id=mapping.project_id,+ team_id=mapping.team_id,+ group_type=mapping.group_type,+ group_type_index=mapping.group_type_index,+ name_singular=mapping.name_singular,+ name_plural=mapping.name_plural,+ default_columns=list(mapping.default_columns) if mapping.default_columns is not None else None,+ detail_dashboard_id=mapping.detail_dashboard_id,+ created_at=mapping.created_at,+ )+ mapping._state.adding = False+ return mappingmapping = GroupTypeMapping(**kwargs)mapping.id = _next_synthetic_pk()diff --git a/posthog/test/test_persons_db.py b/posthog/test/test_persons_db.pyindex c3e7c9038e9e..49caf53bf76d 100644--- a/posthog/test/test_persons_db.py+++ b/posthog/test/test_persons_db.py@@ -28,7 +28,7 @@ class TestPersonsDbUrl:assert persons_db_url(writer=False) == LOCAL_DEV_PERSONS_DB_URL[email protected]_db(databases=["persons_db_writer", "persons_db_reader"])[email protected]_db()def test_sync_connection_targets_persons_db():with persons_db_connection() as conn, conn.cursor() as cursor:cursor.execute("SELECT current_database()")@@ -37,14 +37,14 @@ def test_sync_connection_targets_persons_db():assert row[0].endswith("_persons")[email protected]_db(databases=["persons_db_writer", "persons_db_reader"])[email protected]_db()def test_sync_reader_connection_works():with persons_db_connection(writer=False) as conn, conn.cursor() as cursor:cursor.execute("SELECT 1")assert cursor.fetchone() == (1,)[email protected]_db(databases=["persons_db_writer", "persons_db_reader"])[email protected]_db()async def test_async_connection_targets_persons_db():async with persons_db_aconnection() as conn, conn.cursor() as cursor:await cursor.execute("SELECT current_database()")diff --git a/posthog/test/test_persons_seed.py b/posthog/test/test_persons_seed.pyindex d82c8f5ef325..6afecf197129 100644--- a/posthog/test/test_persons_seed.py+++ b/posthog/test/test_persons_seed.py@@ -14,7 +14,7 @@ from posthog.persons_seed import insert_seed_distinct_id, insert_seed_person, up# test cleans up its own rows to avoid leaking into the shared persons test database.SEED_TEST_TEAM_ID = 2_000_000_001-pytestmark = pytest.mark.django_db(databases=["persons_db_writer", "persons_db_reader"])+pytestmark = pytest.mark.django_db()def _cleanup(conn: psycopg.Connection[Any]) -> None:diff --git a/posthog/test/test_utils.py b/posthog/test/test_utils.pyindex 79a10954194f..e23b7f80d7be 100644--- a/posthog/test/test_utils.py+++ b/posthog/test/test_utils.py@@ -855,21 +855,20 @@ class TestFlatten(TestCase):def create_group_type_mapping_without_created_at(**kwargs) -> "GroupTypeMapping":- from posthog.person_db_router import PERSONS_DB_FOR_WRITE, persons_orm_blocked # noqa: PLC0415+ from posthog.personhog_client.fake_client import personhog_fake_active # noqa: PLC0415from posthog.test.persons import _seed_group_type_mapping_into_fake, create_group_type_mapping # noqa: PLC0415instance = create_group_type_mapping(**kwargs)instance.created_at = None# Mirror create_group_type_mapping's own branch: when the fake is off (persons-DB-direct tests),- # it wrote a real row whose GroupTypeMapping.save() auto-stamped created_at=now(). Null the- # column with a direct UPDATE (which skips that auto-stamp) so the persons DB genuinely holds- # a null created_at — making this helper's name true to form for the fake-off path too.- if not persons_orm_blocked():- from posthog.models.group_type_mapping import GroupTypeMapping # noqa: PLC0415-- GroupTypeMapping.objects.using(PERSONS_DB_FOR_WRITE).filter( # nosemgrep: no-direct-persons-db-orm- pk=instance.pk- ).update(created_at=None)+ # it wrote a real row whose created_at defaulted to now(). Null the column with a direct UPDATE+ # over off-Django psycopg so the persons DB genuinely holds a null created_at — making this+ # helper's name true to form for the fake-off path too.+ if not personhog_fake_active():+ from posthog.persons_db import persons_db_connection # noqa: PLC0415++ with persons_db_connection(writer=True, autocommit=True) as conn, conn.cursor() as cursor:+ cursor.execute("UPDATE posthog_grouptypemapping SET created_at = NULL WHERE id = %s", (instance.pk,))_seed_group_type_mapping_into_fake(instance)return instancediff --git a/products/agent_platform/backend/tests/test_approvals_api.py b/products/agent_platform/backend/tests/test_approvals_api.pyindex b718f50d6e99..3f6fb1fd286a 100644--- a/products/agent_platform/backend/tests/test_approvals_api.py+++ b/products/agent_platform/backend/tests/test_approvals_api.py@@ -36,8 +36,6 @@ from ..models import AgentApplicationclass TestApprovalEndpointsAuth(APIBaseTest):databases = {"default",- "persons_db_writer",- "persons_db_reader","agent_platform_db_writer","agent_platform_db_reader",}diff --git a/products/agent_platform/backend/tests/test_cron_fire.py b/products/agent_platform/backend/tests/test_cron_fire.pyindex 4871b45d868e..c218df06f539 100644--- a/products/agent_platform/backend/tests/test_cron_fire.py+++ b/products/agent_platform/backend/tests/test_cron_fire.py@@ -19,8 +19,6 @@ from ..models import AgentApplication, AgentRevisionclass TestCronFireAction(APIBaseTest):databases = {"default",- "persons_db_writer",- "persons_db_reader","agent_platform_db_writer","agent_platform_db_reader",}diff --git a/products/agent_platform/backend/tests/test_env_keys.py b/products/agent_platform/backend/tests/test_env_keys.pyindex 9cd738f215a8..503986d5b249 100644--- a/products/agent_platform/backend/tests/test_env_keys.py+++ b/products/agent_platform/backend/tests/test_env_keys.py@@ -21,8 +21,6 @@ from ..models import AgentApplication, AgentRevisionclass TestAgentRevisionEnvKeys(APIBaseTest):databases = {"default",- "persons_db_writer",- "persons_db_reader","agent_platform_db_writer","agent_platform_db_reader",}diff --git a/products/agent_platform/backend/tests/test_fleet_stats.py b/products/agent_platform/backend/tests/test_fleet_stats.pyindex 57b8be6324c8..391cb3c4b430 100644--- a/products/agent_platform/backend/tests/test_fleet_stats.py+++ b/products/agent_platform/backend/tests/test_fleet_stats.py@@ -21,8 +21,6 @@ from ..presentation.views import AgentApplicationViewSet, AgentFleetViewSetclass TestAgentApplicationStats(APIBaseTest):databases = {"default",- "persons_db_writer",- "persons_db_reader","agent_platform_db_writer","agent_platform_db_reader",}@@ -77,8 +75,6 @@ class TestAgentApplicationStats(APIBaseTest):class TestAgentFleetViewSet(APIBaseTest):databases = {"default",- "persons_db_writer",- "persons_db_reader","agent_platform_db_writer","agent_platform_db_reader",}diff --git a/products/agent_platform/backend/tests/test_freeze_skill_refs.py b/products/agent_platform/backend/tests/test_freeze_skill_refs.pyindex 05fdc6869796..a284403504f9 100644--- a/products/agent_platform/backend/tests/test_freeze_skill_refs.py+++ b/products/agent_platform/backend/tests/test_freeze_skill_refs.py@@ -18,8 +18,6 @@ from ..models import AgentApplication, AgentRevisionclass TestFreezeResolvesSkillRefs(APIBaseTest):databases = {"default",- "persons_db_writer",- "persons_db_reader","agent_platform_db_writer","agent_platform_db_reader",}diff --git a/products/agent_platform/backend/tests/test_memory_authz.py b/products/agent_platform/backend/tests/test_memory_authz.pyindex 4067cfac8c14..b772e1763875 100644--- a/products/agent_platform/backend/tests/test_memory_authz.py+++ b/products/agent_platform/backend/tests/test_memory_authz.py@@ -22,8 +22,6 @@ from ..models import AgentApplicationclass TestMemoryViewSetAuthz(APIBaseTest):databases = {"default",- "persons_db_writer",- "persons_db_reader","agent_platform_db_writer","agent_platform_db_reader",}diff --git a/products/agent_platform/backend/tests/test_models_catalog.py b/products/agent_platform/backend/tests/test_models_catalog.pyindex 43388833f998..d186d14eff03 100644--- a/products/agent_platform/backend/tests/test_models_catalog.py+++ b/products/agent_platform/backend/tests/test_models_catalog.py@@ -19,8 +19,6 @@ from ..presentation.views import AgentApplicationViewSetclass TestAgentApplicationModels(APIBaseTest):databases = {"default",- "persons_db_writer",- "persons_db_reader","agent_platform_db_writer","agent_platform_db_reader",}diff --git a/products/agent_platform/backend/tests/test_posthog_identity_provisioning.py b/products/agent_platform/backend/tests/test_posthog_identity_provisioning.pyindex e8a2a2394766..99532b27c773 100644--- a/products/agent_platform/backend/tests/test_posthog_identity_provisioning.py+++ b/products/agent_platform/backend/tests/test_posthog_identity_provisioning.py@@ -29,8 +29,6 @@ POSTHOG_SPEC = {class TestPostHogIdentityProvisioning(APIBaseTest):databases = {"default",- "persons_db_writer",- "persons_db_reader","agent_platform_db_writer","agent_platform_db_reader",}diff --git a/products/agent_platform/backend/tests/test_preview_proxy.py b/products/agent_platform/backend/tests/test_preview_proxy.pyindex 0760e0d9b3bd..c4847e37e372 100644--- a/products/agent_platform/backend/tests/test_preview_proxy.py+++ b/products/agent_platform/backend/tests/test_preview_proxy.py@@ -48,8 +48,6 @@ def _base_spec() -> dict[str, Any]:class TestPreviewProxyScope(APIBaseTest):databases = {"default",- "persons_db_writer",- "persons_db_reader","agent_platform_db_writer","agent_platform_db_reader",}@@ -72,8 +70,6 @@ class TestPreviewProxyScope(APIBaseTest):class TestPreviewProxyRendering(APIBaseTest):databases = {"default",- "persons_db_writer",- "persons_db_reader","agent_platform_db_writer","agent_platform_db_reader",}@@ -124,8 +120,6 @@ class TestPreviewProxyCrossAppRejection(APIBaseTest):databases = {"default",- "persons_db_writer",- "persons_db_reader","agent_platform_db_writer","agent_platform_db_reader",}diff --git a/products/agent_platform/backend/tests/test_preview_token.py b/products/agent_platform/backend/tests/test_preview_token.pyindex 3eefe41f156e..83291a126808 100644--- a/products/agent_platform/backend/tests/test_preview_token.py+++ b/products/agent_platform/backend/tests/test_preview_token.py@@ -60,8 +60,6 @@ def _base_spec(triggers: list[dict[str, Any]] | None = None, modes: list[str] |class TestPreviewTokenResponse(APIBaseTest):databases = {"default",- "persons_db_writer",- "persons_db_reader","agent_platform_db_writer","agent_platform_db_reader",}@@ -222,8 +220,6 @@ class TestPreviewTokenDomainMode(APIBaseTest):databases = {"default",- "persons_db_writer",- "persons_db_reader","agent_platform_db_writer","agent_platform_db_reader",}@@ -278,8 +274,6 @@ class TestSlackUrlSerializer(APIBaseTest):databases = {"default",- "persons_db_writer",- "persons_db_reader","agent_platform_db_writer","agent_platform_db_reader",}@@ -322,8 +316,6 @@ class TestPreviewTokenMintPost(APIBaseTest):databases = {"default",- "persons_db_writer",- "persons_db_reader","agent_platform_db_writer","agent_platform_db_reader",}@@ -386,8 +378,6 @@ class TestPreviewTokenScopeMapping(APIBaseTest):databases = {"default",- "persons_db_writer",- "persons_db_reader","agent_platform_db_writer","agent_platform_db_reader",}diff --git a/products/agent_platform/backend/tests/test_promote_archive.py b/products/agent_platform/backend/tests/test_promote_archive.pyindex cba00560b136..6bd088e0e1fd 100644--- a/products/agent_platform/backend/tests/test_promote_archive.py+++ b/products/agent_platform/backend/tests/test_promote_archive.py@@ -22,8 +22,6 @@ from ..models import AgentApplication, AgentIdentityCredential, AgentRevision, Aclass TestPromoteArchive(APIBaseTest):databases = {"default",- "persons_db_writer",- "persons_db_reader","agent_platform_db_writer","agent_platform_db_reader",}diff --git a/products/agent_platform/backend/tests/test_revision_create.py b/products/agent_platform/backend/tests/test_revision_create.pyindex 65c142db8148..bbdddfa00894 100644--- a/products/agent_platform/backend/tests/test_revision_create.py+++ b/products/agent_platform/backend/tests/test_revision_create.py@@ -22,8 +22,6 @@ _SPEC = {"models": {"mode": "manual", "models": [{"model": "anthropic/claude-haiclass TestRevisionCreateBundleUri(APIBaseTest):databases = {"default",- "persons_db_writer",- "persons_db_reader","agent_platform_db_writer","agent_platform_db_reader",}diff --git a/products/agent_platform/backend/tests/test_revisions_slug_lookup.py b/products/agent_platform/backend/tests/test_revisions_slug_lookup.pyindex ebd7a1a19111..706cb44d319f 100644--- a/products/agent_platform/backend/tests/test_revisions_slug_lookup.py+++ b/products/agent_platform/backend/tests/test_revisions_slug_lookup.py@@ -25,8 +25,6 @@ from ..models import AgentApplication, AgentRevisionclass TestRevisionsSlugLookup(APIBaseTest):databases = {"default",- "persons_db_writer",- "persons_db_reader","agent_platform_db_writer","agent_platform_db_reader",}diff --git a/products/agent_platform/backend/tests/test_session_logs.py b/products/agent_platform/backend/tests/test_session_logs.pyindex 4d7989355234..bc1e4b27ed3a 100644--- a/products/agent_platform/backend/tests/test_session_logs.py+++ b/products/agent_platform/backend/tests/test_session_logs.py@@ -53,8 +53,6 @@ def _insert_log(class TestSessionLogs(ClickhouseTestMixin, APIBaseTest):databases = {"default",- "persons_db_writer",- "persons_db_reader","agent_platform_db_writer","agent_platform_db_reader",}diff --git a/products/agent_platform/backend/tests/test_slug_validation.py b/products/agent_platform/backend/tests/test_slug_validation.pyindex e0ba3e8672ec..763f97eea6d5 100644--- a/products/agent_platform/backend/tests/test_slug_validation.py+++ b/products/agent_platform/backend/tests/test_slug_validation.py@@ -17,8 +17,6 @@ from ..models import AgentApplication, AgentRevision_DBS = {"default",- "persons_db_writer",- "persons_db_reader","agent_platform_db_writer","agent_platform_db_reader",}