: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): migrate dev seed commands to raw sql (#65909)
Zach Brown87dbc3767ab5
diff --git a/posthog/management/commands/export_distinct_ids.py b/posthog/management/commands/export_distinct_ids.pyindex 72fe8b67777c..24fafd185ea8 100644--- a/posthog/management/commands/export_distinct_ids.py+++ b/posthog/management/commands/export_distinct_ids.py@@ -1,8 +1,10 @@import random+from django.conf import settingsfrom django.core.management.base import BaseCommand-from posthog.models import Person, PersonDistinctId, Team+from posthog.models import Team+from posthog.persons_db import persons_db_connectionclass Command(BaseCommand):@@ -64,19 +66,27 @@ class Command(BaseCommand):self.stdout.write(self.style.SUCCESS(f"Exporting distinct IDs for team: {team.name}"))- # Build the query- distinct_ids_query = PersonDistinctId.objects.filter(team=team) # nosemgrep: no-direct-persons-db-orm-+ # Build the distinct-id query, joining to the person table only when filtering on+ # person attributes (identified / demo).+ conditions = ["pdi.team_id = %s"]if identified_only:- distinct_ids_query = distinct_ids_query.filter(person__is_identified=True)+ conditions.append("p.is_identified = true")self.stdout.write("Filtering for identified persons only")-if demo_only:- distinct_ids_query = distinct_ids_query.filter(person__properties__is_demo=True)+ conditions.append("p.properties @> '{\"is_demo\": true}'::jsonb")self.stdout.write("Filtering for demo persons only")- # Get distinct IDs- distinct_ids = list(distinct_ids_query.values_list("distinct_id", flat=True))+ person_join = (+ f"JOIN {settings.PERSON_TABLE_NAME} p ON p.team_id = pdi.team_id AND p.id = pdi.person_id"+ if (identified_only or demo_only)+ else ""+ )+ query = (+ f"SELECT pdi.distinct_id FROM posthog_persondistinctid pdi {person_join} WHERE {' AND '.join(conditions)}"+ )+ with persons_db_connection(writer=False) as conn, conn.cursor() as cursor:+ cursor.execute(query, [team.id])+ distinct_ids = [row[0] for row in cursor.fetchall()]if not distinct_ids:self.stdout.write(self.style.WARNING("No distinct IDs found matching the criteria!"))@@ -126,13 +136,17 @@ class Command(BaseCommand):self.stdout.write(self.style.ERROR(f"Error writing to file: {e}"))# Also show some stats- total_persons = Person.objects.filter(team=team).count() # nosemgrep: no-direct-persons-db-orm- identified_persons = Person.objects.filter( # nosemgrep: no-direct-persons-db-orm- team=team, is_identified=True- ).count() # nosemgrep: no-direct-persons-db-orm- demo_persons = Person.objects.filter( # nosemgrep: no-direct-persons-db-orm- team=team, properties__is_demo=True- ).count() # nosemgrep: no-direct-persons-db-orm+ with persons_db_connection(writer=False) as conn, conn.cursor() as cursor:+ cursor.execute(+ f"SELECT count(*), "+ "count(*) FILTER (WHERE is_identified), "+ "count(*) FILTER (WHERE properties @> '{\"is_demo\": true}'::jsonb) "+ f"FROM {settings.PERSON_TABLE_NAME} WHERE team_id = %s",+ [team.id],+ )+ stats_row = cursor.fetchone()+ assert stats_row is not None+ total_persons, identified_persons, demo_persons = stats_rowself.stdout.write(f"\nTeam statistics:")self.stdout.write(f" Total persons: {total_persons}")diff --git a/posthog/management/commands/generate_persons.py b/posthog/management/commands/generate_persons.pyindex acdeb57c4c52..c06087a489c2 100644--- a/posthog/management/commands/generate_persons.py+++ b/posthog/management/commands/generate_persons.py@@ -2,10 +2,11 @@ import randomfrom typing import Anyfrom django.core.management.base import BaseCommand-from django.db import router, transaction-from posthog.models import Person, PersonDistinctId, Team+from posthog.models import Teamfrom posthog.models.utils import UUIDT+from posthog.persons_db import persons_db_connection+from posthog.persons_seed import insert_seed_distinct_id, insert_seed_personclass Command(BaseCommand):@@ -62,28 +63,20 @@ class Command(BaseCommand):self.stdout.write(self.style.SUCCESS(f"Generating {count} persons for team: {team.name}"))- # Generate persons- # Use the correct database for Person writes (handles persons_db_writer routing in production)- db_alias = router.db_for_write(Person) or "default"+ # Generate persons through a direct persons-DB connection (off the Django ORM).+ # The connection commits when the block exits, before the ClickHouse sync reads them back.persons_created = 0- with transaction.atomic(using=db_alias):+ with persons_db_connection(writer=True) as conn:for i in range(count):person_data = self._generate_person_data(i, identified_ratio)- # Create person in Django only- person = Person.objects.create( # nosemgrep: no-direct-persons-db-orm- team=team,+ person_id = insert_seed_person(+ conn,+ team_id=team.id,properties=person_data["properties"],is_identified=person_data["is_identified"],)-- # Create distinct ID- distinct_id = str(UUIDT())- PersonDistinctId.objects.create( # nosemgrep: no-direct-persons-db-orm- team=team,- person=person,- distinct_id=distinct_id,- )+ insert_seed_distinct_id(conn, team_id=team.id, person_id=person_id, distinct_id=str(UUIDT()))persons_created += 1@@ -856,14 +849,16 @@ class Command(BaseCommand):event_types = ["pageview", "click", "form_submit", "signup", "purchase", "download"]pages = ["/", "/pricing", "/features", "/about", "/contact", "/blog", "/docs"]- events_created = 0- for _i in range(min(person_count, 50)): # Limit events to avoid overwhelming- person = Person.objects.filter(team=team).order_by("?").first() # nosemgrep: no-direct-persons-db-orm- if not person:- continue-- distinct_id = person.distinct_ids[0] if person.distinct_ids else str(UUIDT())+ # Attach demo events to a random sample of the team's distinct_ids.+ with persons_db_connection(writer=False) as conn, conn.cursor() as cursor:+ cursor.execute(+ "SELECT distinct_id FROM posthog_persondistinctid WHERE team_id = %s ORDER BY random() LIMIT %s",+ (team.id, min(person_count, 50)),+ )+ distinct_ids = [row[0] for row in cursor.fetchall()]+ events_created = 0+ for distinct_id in distinct_ids:# Generate 1-5 events per personfor _j in range(random.randint(1, 5)):event_type = random.choice(event_types)diff --git a/posthog/management/commands/generate_random_product_tours.py b/posthog/management/commands/generate_random_product_tours.pyindex d06b6724c71b..24af74fb2e9f 100644--- a/posthog/management/commands/generate_random_product_tours.py+++ b/posthog/management/commands/generate_random_product_tours.py@@ -15,7 +15,7 @@ from posthog.clickhouse.client import sync_executefrom posthog.constants import PRODUCT_TOUR_TARGETING_FLAG_PREFIXfrom posthog.models import Team, Userfrom posthog.models.event.sql import BULK_INSERT_EVENT_SQL-from posthog.models.person.person import Person, PersonDistinctId+from posthog.persons_seed import PersonData, fetch_recent_persons_with_distinct_idfrom products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.product_tours.backend.models import ProductTour@@ -88,16 +88,6 @@ TOUR_TEMPLATES: list[dict[str, Any]] = []-class PersonData:- """Holds person data for event generation."""-- def __init__(self, distinct_id: str, person_uuid: str, properties: dict, created_at: Any):- self.distinct_id = distinct_id- self.person_uuid = person_uuid- self.properties = properties- self.created_at = created_at--class Command(BaseCommand):help = "Generate random product tours for development purposes"@@ -142,35 +132,6 @@ class Command(BaseCommand):tour.internal_targeting_flag = flagtour.save(update_fields=["internal_targeting_flag"])- def get_real_persons(self, team: Team, limit: int = 50) -> list[PersonData]:- """Fetch real persons from the database."""- persons_data: list[PersonData] = []-- persons = (- Person.objects.filter(team_id=team.id) # nosemgrep: no-direct-persons-db-orm- .prefetch_related("persondistinctid_set")- .order_by("-created_at")[:limit]- )-- for person in persons:- distinct_ids = PersonDistinctId.objects.filter( # nosemgrep: no-direct-persons-db-orm- person=person, team_id=team.id- ).values_list( # nosemgrep: no-direct-persons-db-orm- "distinct_id", flat=True- )-- if distinct_ids:- persons_data.append(- PersonData(- distinct_id=distinct_ids[0],- person_uuid=str(person.uuid),- properties=person.properties or {},- created_at=person.created_at,- )- )-- return persons_data-def add_arguments(self, parser):parser.add_argument("count", type=int, help="Number of product tours to generate")parser.add_argument("--team-id", type=int, help="Team ID to create tours for")@@ -491,7 +452,7 @@ class Command(BaseCommand):# Fetch real persons if events are requestedpersons_data: list[PersonData] = []if num_events > 0:- persons_data = self.get_real_persons(team, limit=100)+ persons_data = fetch_recent_persons_with_distinct_id(team.id, limit=100)if persons_data:self.stdout.write(self.style.SUCCESS(f"Found {len(persons_data)} persons in the database to use for events")diff --git a/posthog/management/commands/generate_random_surveys.py b/posthog/management/commands/generate_random_surveys.pyindex 84952898d558..9a8103ba8dfc 100644--- a/posthog/management/commands/generate_random_surveys.py+++ b/posthog/management/commands/generate_random_surveys.py@@ -11,7 +11,7 @@ from django.utils import timezonefrom posthog.clickhouse.client import sync_executefrom posthog.models import Team, Userfrom posthog.models.event.sql import BULK_INSERT_EVENT_SQL-from posthog.models.person.person import Person, PersonDistinctId+from posthog.persons_seed import PersonData, fetch_recent_persons_with_distinct_idfrom posthog.settings.data_stores import CLICKHOUSE_CLUSTERfrom products.surveys.backend.models import Survey@@ -244,16 +244,6 @@ LLM_NEGATIVE_FEEDBACK = []-class PersonData:- """Holds person data for event generation."""-- def __init__(self, distinct_id: str, person_uuid: str, properties: dict, created_at: Any):- self.distinct_id = distinct_id- self.person_uuid = person_uuid- self.properties = properties- self.created_at = created_at--class Command(BaseCommand):help = "Generate random surveys for development purposes"@@ -271,37 +261,6 @@ class Command(BaseCommand):result = sync_execute(query, {"team_id": team.id, "limit": limit})return [row[0] for row in result if row[0]]- def get_real_persons(self, team: Team, limit: int = 50) -> list[PersonData]:- """Fetch real persons from the database that were created by demo data generation."""- persons_data: list[PersonData] = []-- # Query persons with their distinct IDs- persons = (- Person.objects.filter(team_id=team.id) # nosemgrep: no-direct-persons-db-orm- .prefetch_related("persondistinctid_set")- .order_by("-created_at")[:limit]- )-- for person in persons:- distinct_ids = PersonDistinctId.objects.filter( # nosemgrep: no-direct-persons-db-orm- person=person, team_id=team.id- ).values_list( # nosemgrep: no-direct-persons-db-orm- "distinct_id", flat=True- )-- if distinct_ids:- # Use the first distinct_id for the person- persons_data.append(- PersonData(- distinct_id=distinct_ids[0],- person_uuid=str(person.uuid),- properties=person.properties or {},- created_at=person.created_at,- )- )-- return persons_data-def add_arguments(self, parser):parser.add_argument("count",@@ -1146,7 +1105,7 @@ class Command(BaseCommand):# Fetch real persons from the database if responses are requestedpersons_data: list[PersonData] = []if num_responses > 0:- persons_data = self.get_real_persons(team, limit=100)+ persons_data = fetch_recent_persons_with_distinct_id(team.id, limit=100)if persons_data:self.stdout.write(self.style.SUCCESS(f"Found {len(persons_data)} persons in the database to use for responses")diff --git a/posthog/persons_seed.py b/posthog/persons_seed.pynew file mode 100644index 000000000000..0a0dc8e49bf3--- /dev/null+++ b/posthog/persons_seed.py@@ -0,0 +1,138 @@+"""Direct persons-database reads and writes for local dev and seed management commands.++These helpers read, insert, and update persons/groups straight in the persons database via+a raw psycopg connection (see :mod:`posthog.persons_db`), bypassing the Django ORM so the+persons database can be dropped from Django's ``DATABASES``. They exist only for development+and seed tooling that needs to fabricate or read persons locally — production person+creation flows through ingestion and the personhog service, which has no create RPC by+design.++``created_at`` and ``uuid`` are ``NOT NULL`` with no database default (the ORM fills them+application-side), so the inserts set them explicitly; ``team_id`` is required (and in+production routes the row to the correct hash partition of the persons table).+"""++from __future__ import annotations++import uuid as uuid_lib+import dataclasses+from typing import Any++from django.conf import settings++import psycopg+from psycopg.types.json import Jsonb++from posthog.models.utils import UUIDT+from posthog.persons_db import persons_db_connection++# Not configurable like the person table; the model uses Django's default db_table.+PERSON_DISTINCT_ID_TABLE = "posthog_persondistinctid"+++def insert_seed_person(+ conn: psycopg.Connection[Any],+ *,+ team_id: int,+ properties: dict[str, Any],+ is_identified: bool = False,+ uuid: str | uuid_lib.UUID | 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.+ """+ 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),+ )+ row = cursor.fetchone()+ assert row is not None # RETURNING always yields a row on a successful insert+ return row[0]+++def insert_seed_distinct_id(+ conn: psycopg.Connection[Any],+ *,+ team_id: int,+ person_id: int,+ distinct_id: str,+) -> None:+ """Insert one distinct-id row linking ``distinct_id`` to ``person_id``."""+ 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),+ )+++def insert_seed_group(+ conn: psycopg.Connection[Any],+ *,+ team_id: int,+ group_key: str,+ 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."""+ 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),+ )+++def update_seed_person(+ conn: psycopg.Connection[Any],+ *,+ team_id: int,+ uuid: str | uuid_lib.UUID,+ properties: dict[str, Any],+ is_identified: bool,+) -> None:+ """Overwrite ``properties`` and ``is_identified`` for an existing person."""+ with conn.cursor() as cursor:+ cursor.execute(+ f"UPDATE {settings.PERSON_TABLE_NAME} "+ "SET properties = %s, is_identified = %s WHERE team_id = %s AND uuid = %s",+ (Jsonb(properties), is_identified, team_id, uuid),+ )+++class PersonData:+ """A person fetched from the persons database for dev/seed event generation."""++ distinct_id: str+ person_uuid: str+ properties: dict[str, Any]+ created_at: Any+++def fetch_recent_persons_with_distinct_id(team_id: int, *, limit: int = 50) -> list[PersonData]:+ """Return up to ``limit`` most-recently-created persons that have a distinct ID.++ Each person is paired with one of its distinct IDs; the inner lateral join drops+ persons without one, so the result may be shorter than ``limit``.+ """+ query = (+ "SELECT p.uuid, p.properties, p.created_at, pdi.distinct_id "+ f"FROM (SELECT id, uuid, properties, created_at FROM {settings.PERSON_TABLE_NAME} "+ "WHERE team_id = %(team_id)s ORDER BY created_at DESC LIMIT %(limit)s) p "+ "JOIN LATERAL (SELECT distinct_id FROM posthog_persondistinctid "+ "WHERE team_id = %(team_id)s AND person_id = p.id LIMIT 1) pdi ON true"+ )+ with persons_db_connection(writer=False) as conn, conn.cursor() as cursor:+ cursor.execute(query, {"team_id": team_id, "limit": limit})+ rows = cursor.fetchall()+ return [+ PersonData(person_uuid=str(row[0]), properties=row[1] or {}, created_at=row[2], distinct_id=row[3])+ for row in rows+ ]diff --git a/posthog/test/test_persons_seed.py b/posthog/test/test_persons_seed.pynew file mode 100644index 000000000000..d82c8f5ef325--- /dev/null+++ b/posthog/test/test_persons_seed.py@@ -0,0 +1,83 @@+from typing import Any++import pytest++from django.conf import settings++import psycopg++from posthog.persons_db import persons_db_connection+from posthog.persons_seed import insert_seed_distinct_id, insert_seed_person, update_seed_person++# Sentinel team id used only by these tests. The seed helpers write through a raw+# psycopg connection that commits independently of Django's test transaction, so each+# 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"])+++def _cleanup(conn: psycopg.Connection[Any]) -> None:+ with conn.cursor() as cursor:+ cursor.execute("DELETE FROM posthog_persondistinctid WHERE team_id = %s", (SEED_TEST_TEAM_ID,))+ cursor.execute(f"DELETE FROM {settings.PERSON_TABLE_NAME} WHERE team_id = %s", (SEED_TEST_TEAM_ID,))+++class TestPersonsSeedHelpers:+ def test_insert_person_persists_fields_and_sets_required_columns(self):+ with persons_db_connection(writer=True) as conn:+ try:+ person_id = insert_seed_person(+ conn, team_id=SEED_TEST_TEAM_ID, properties={"email": "[email protected]"}, is_identified=True+ )+ with conn.cursor() as cursor:+ cursor.execute(+ f"SELECT properties, is_identified, uuid, created_at FROM {settings.PERSON_TABLE_NAME} WHERE id = %s",+ (person_id,),+ )+ row = cursor.fetchone()+ assert row is not None+ assert row[0] == {"email": "[email protected]"}+ assert row[1] is True+ assert row[2] is not None # uuid filled (NOT NULL, no DB default)+ assert row[3] is not None # created_at filled (NOT NULL, no DB default)+ finally:+ _cleanup(conn)++ def test_insert_distinct_id_links_to_person(self):+ with persons_db_connection(writer=True) as conn:+ try:+ person_id = insert_seed_person(conn, team_id=SEED_TEST_TEAM_ID, properties={})+ insert_seed_distinct_id(conn, team_id=SEED_TEST_TEAM_ID, person_id=person_id, distinct_id="seed-did")+ with conn.cursor() as cursor:+ cursor.execute(+ "SELECT person_id FROM posthog_persondistinctid WHERE team_id = %s AND distinct_id = %s",+ (SEED_TEST_TEAM_ID, "seed-did"),+ )+ row = cursor.fetchone()+ assert row is not None+ assert row[0] == person_id+ finally:+ _cleanup(conn)++ def test_update_person_overwrites_properties_and_identified(self):+ with persons_db_connection(writer=True) as conn:+ try:+ person_uuid = "00000000-0000-0000-0000-000000000abc"+ insert_seed_person(+ conn, team_id=SEED_TEST_TEAM_ID, properties={"v": 1}, is_identified=False, uuid=person_uuid+ )+ update_seed_person(+ conn, team_id=SEED_TEST_TEAM_ID, uuid=person_uuid, properties={"v": 2}, is_identified=True+ )+ with conn.cursor() as cursor:+ cursor.execute(+ f"SELECT properties, is_identified FROM {settings.PERSON_TABLE_NAME} WHERE team_id = %s AND uuid = %s",+ (SEED_TEST_TEAM_ID, person_uuid),+ )+ row = cursor.fetchone()+ assert row is not None+ assert row[0] == {"v": 2}+ assert row[1] is True+ finally:+ _cleanup(conn)diff --git a/products/customer_analytics/backend/management/commands/seed_customer_analytics_accounts.py b/products/customer_analytics/backend/management/commands/seed_customer_analytics_accounts.pyindex c17baeaeef55..4787259eb020 100644--- a/products/customer_analytics/backend/management/commands/seed_customer_analytics_accounts.py+++ b/products/customer_analytics/backend/management/commands/seed_customer_analytics_accounts.py@@ -24,8 +24,9 @@ from uuid import uuid4from django.core.management.base import BaseCommand, CommandErrorfrom django.db import transaction-from posthog.models import Group, OrganizationMembership, Team, User+from posthog.models import OrganizationMembership, Team, Userfrom posthog.models.scoping import team_scope+from posthog.persons_db import persons_db_connectionfrom products.customer_analytics.backend.models.account import Account, AccountAssignment, AccountPropertiesfrom products.customer_analytics.backend.models.team_customer_analytics_config import TeamCustomerAnalyticsConfig@@ -97,14 +98,13 @@ class Command(BaseCommand):raise CommandError(f"Team {team_id} does not exist.")def _read_account_groups(self, team: Team, limit: int | None) -> list[tuple[str, dict[str, Any]]]:- rows = [- (group_key, props or {})- for group_key, props in Group.objects.filter( # nosemgrep: no-direct-persons-db-orm- team_id=team.pk, group_type_index=ACCOUNT_GROUP_TYPE_INDEX- )- .order_by("group_key")- .values_list("group_key", "group_properties")- ]+ query = (+ "SELECT group_key, group_properties FROM posthog_group "+ "WHERE team_id = %(team_id)s AND group_type_index = %(gti)s ORDER BY group_key"+ )+ with persons_db_connection(writer=False) as conn, conn.cursor() as cursor:+ cursor.execute(query, {"team_id": team.pk, "gti": ACCOUNT_GROUP_TYPE_INDEX})+ rows = [(group_key, props or {}) for group_key, props in cursor.fetchall()]return rows[:limit] if limit is not None else rowsdef _set_config(self, team: Team) -> None:diff --git a/products/customer_analytics/backend/management/commands/test/test_seed_customer_analytics_accounts.py b/products/customer_analytics/backend/management/commands/test/test_seed_customer_analytics_accounts.pyindex 3e3a50530e20..d073a9e8a1f0 100644--- a/products/customer_analytics/backend/management/commands/test/test_seed_customer_analytics_accounts.py+++ b/products/customer_analytics/backend/management/commands/test/test_seed_customer_analytics_accounts.py@@ -5,7 +5,9 @@ from posthog.test.base import BaseTestfrom django.core.management import call_commandfrom django.core.management.base import CommandError-from posthog.models import Group, OrganizationMembership, User+from posthog.models import OrganizationMembership, User+from posthog.persons_db import persons_db_connection+from posthog.persons_seed import insert_seed_groupfrom products.customer_analytics.backend.models.account import Accountfrom products.customer_analytics.backend.models.team_customer_analytics_config import TeamCustomerAnalyticsConfig@@ -13,14 +15,24 @@ from products.notebooks.backend.models import Notebook, ResourceNotebookclass TestSeedCustomerAnalyticsAccounts(BaseTest):+ def tearDown(self):+ # _make_group commits rows outside the test transaction, so remove them here to+ # avoid leaking into other tests that share the persons database.+ with persons_db_connection(writer=True) as conn, conn.cursor() as cursor:+ cursor.execute("DELETE FROM posthog_group WHERE team_id = %s", (self.team.pk,))+ super().tearDown()+def _make_group(self, group_key: str, name: str) -> None:- Group.objects.create(- team_id=self.team.pk,- group_key=group_key,- group_type_index=0,- group_properties={"name": name, "industry": "tech", "team_size": 3},- version=0,- )+ # The command reads groups via a raw persons-DB connection, so fixtures must be+ # committed — a Django ORM create would be invisible across the connection boundary.+ with persons_db_connection(writer=True) as conn:+ insert_seed_group(+ conn,+ team_id=self.team.pk,+ group_key=group_key,+ group_type_index=0,+ group_properties={"name": name, "industry": "tech", "team_size": 3},+ )def _run(self, **kwargs) -> str:out = StringIO()diff --git a/products/mcp_analytics/backend/management/commands/seed_mcp_sessions.py b/products/mcp_analytics/backend/management/commands/seed_mcp_sessions.pyindex 54c9afeed32b..fcdc301092c7 100644--- a/products/mcp_analytics/backend/management/commands/seed_mcp_sessions.py+++ b/products/mcp_analytics/backend/management/commands/seed_mcp_sessions.py@@ -8,12 +8,13 @@ from django.core.management.base import BaseCommand, CommandParserfrom posthog.clickhouse.client import sync_executefrom posthog.models.event.sql import EVENTS_DATA_TABLEfrom posthog.models.event.util import create_event-from posthog.models.person import Person, PersonDistinctIdfrom posthog.models.person.util import create_person, create_person_distinct_id, get_person_by_distinct_idfrom posthog.models.scoping import team_scopefrom posthog.models.team.team import Team-from posthog.models.utils import uuid7+from posthog.models.utils import UUIDT, uuid7from posthog.personhog_client.caller_tag import personhog_caller_tag+from posthog.persons_db import persons_db_connection+from posthog.persons_seed import insert_seed_distinct_id, insert_seed_person, update_seed_personfrom products.mcp_analytics.backend.models import MCPSession@@ -221,19 +222,27 @@ class Command(BaseCommand):team_id=team.id, distinct_id=distinct_id, distinct_id_limit=0)if existing_person:- person = existing_person+ person_uuid = str(existing_person.uuid)if properties:- person.properties = properties- person.is_identified = is_identified- person.save(update_fields=["properties", "is_identified"])+ with persons_db_connection(writer=True) as conn:+ update_seed_person(+ conn,+ team_id=team.id,+ uuid=person_uuid,+ properties=properties,+ is_identified=is_identified,+ )else:- person = Person.objects.create( # nosemgrep: no-direct-persons-db-orm- team=team, properties=properties, is_identified=is_identified- )- PersonDistinctId.objects.create( # nosemgrep: no-direct-persons-db-orm- team=team, distinct_id=distinct_id, person=person- )- person_uuid = str(person.uuid)+ person_uuid = str(UUIDT())+ with persons_db_connection(writer=True) as conn:+ person_id = insert_seed_person(+ conn,+ team_id=team.id,+ properties=properties,+ is_identified=is_identified,+ uuid=person_uuid,+ )+ insert_seed_distinct_id(conn, team_id=team.id, person_id=person_id, distinct_id=distinct_id)create_person(team_id=team.id,uuid=person_uuid,