Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

chore(django): move eval code off orm (#66220)

Zach Browne5806c546db8
diff --git a/ee/hogai/eval/data_setup.py b/ee/hogai/eval/data_setup.py
index 64c0f5131d79..a1b6c165aed2 100644
--- a/ee/hogai/eval/data_setup.py
+++ b/ee/hogai/eval/data_setup.py
@@ -17,10 +17,11 @@ from posthog.clickhouse.client import sync_execute
from posthog.demo.matrix.manager import MatrixManager
from posthog.demo.matrix.taxonomy_inference import infer_taxonomy_for_team
from posthog.demo.products.hedgebox.matrix import HedgeboxMatrix
-from posthog.models import GroupTypeMapping, Organization, OrganizationMembership, Team, User
+from posthog.models import Organization, OrganizationMembership, Team, User
from posthog.models.event.sql import COPY_EVENTS_BETWEEN_TEAMS
from posthog.models.group.sql import COPY_GROUPS_BETWEEN_TEAMS
from posthog.models.person.sql import COPY_PERSON_DISTINCT_ID2S_BETWEEN_TEAMS, COPY_PERSONS_BETWEEN_TEAMS
+from posthog.persons_db import persons_db_connection
from products.dashboards.backend.models import Dashboard, DashboardTile
from products.posthog_ai.backend.models.assistant import CoreMemory
@@ -180,15 +181,17 @@ def copy_demo_data_to_new_team(
sync_execute(COPY_EVENTS_BETWEEN_TEAMS, copy_params)
sync_execute(COPY_GROUPS_BETWEEN_TEAMS, copy_params)
- GroupTypeMapping.objects.filter(project_id=team.project_id).delete() # nosemgrep: no-direct-persons-db-orm
- GroupTypeMapping.objects.bulk_create( # nosemgrep: no-direct-persons-db-orm
- GroupTypeMapping(team_id=team.id, project_id=team.project_id, **record)
- for record in GroupTypeMapping.objects.filter( # nosemgrep: no-direct-persons-db-orm
- project_id=master_team.project_id
- ).values( # nosemgrep: no-direct-persons-db-orm
- "group_type", "group_type_index", "name_singular", "name_plural"
+ # Copy the master team's group type mappings onto the isolated eval team, writing through the
+ # off-ORM persons connection so the persons DB stays decoupled from Django.
+ with persons_db_connection(writer=True) as conn, conn.cursor() as cursor:
+ cursor.execute("DELETE FROM posthog_grouptypemapping WHERE project_id = %s", [team.project_id])
+ cursor.execute(
+ "INSERT INTO posthog_grouptypemapping "
+ "(team_id, project_id, group_type, group_type_index, name_singular, name_plural) "
+ "SELECT %s, %s, group_type, group_type_index, name_singular, name_plural "
+ "FROM posthog_grouptypemapping WHERE project_id = %s",
+ [team.id, team.project_id, master_team.project_id],
)
- )
MatrixManager._sync_postgres_with_clickhouse_data(master_team_id, team.id)
diff --git a/ee/hogai/eval/offline/snapshot_loader.py b/ee/hogai/eval/offline/snapshot_loader.py
index bedf39a5b94d..5f933e40d806 100644
--- a/ee/hogai/eval/offline/snapshot_loader.py
+++ b/ee/hogai/eval/offline/snapshot_loader.py
@@ -13,7 +13,8 @@ from dagster_pipes import PipesContext
from fastavro import reader
from pydantic_avro import AvroBase
-from posthog.models import GroupTypeMapping, Organization, Project, PropertyDefinition, Team, User
+from posthog.models import Organization, Project, PropertyDefinition, Team, User
+from posthog.persons_db import persons_db_aconnection
from products.warehouse_sources.backend.facade.models import DataWarehouseTable
@@ -138,12 +139,23 @@ class SnapshotLoader:
async def _load_group_type_mappings(self, buffer: BytesIO, *, team: Team, project: Project):
snapshot = list(self._parse_snapshot_to_schema(GroupTypeMappingSnapshot, buffer))
- group_type_mappings = GroupTypeMappingSnapshot.deserialize_for_team(
- snapshot, team_id=team.id, project_id=project.id
+ group_type_mappings = list(
+ GroupTypeMappingSnapshot.deserialize_for_team(snapshot, team_id=team.id, project_id=project.id)
)
- return await GroupTypeMapping.objects.abulk_create( # nosemgrep: no-direct-persons-db-orm
- group_type_mappings, batch_size=500
- ) # nosemgrep: no-direct-persons-db-orm
+ if not group_type_mappings:
+ return []
+ # Written through the off-ORM persons connection so the persons DB stays decoupled from Django.
+ async with persons_db_aconnection(writer=True) as conn, conn.cursor() as cursor:
+ await cursor.executemany(
+ "INSERT INTO posthog_grouptypemapping "
+ "(team_id, project_id, group_type, group_type_index, name_singular, name_plural) "
+ "VALUES (%s, %s, %s, %s, %s, %s)",
+ [
+ (m.team_id, m.project_id, m.group_type, m.group_type_index, m.name_singular, m.name_plural)
+ for m in group_type_mappings
+ ],
+ )
+ return group_type_mappings
async def _load_data_warehouse_tables(self, buffer: BytesIO, *, team: Team, project: Project):
snapshot = list(self._parse_snapshot_to_schema(DataWarehouseTableSnapshot, buffer))
diff --git a/ee/hogai/test/test_snapshot_loader.py b/ee/hogai/test/test_snapshot_loader.py
index f2e93366c80e..f673f47c4285 100644
--- a/ee/hogai/test/test_snapshot_loader.py
+++ b/ee/hogai/test/test_snapshot_loader.py
@@ -20,6 +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.persons_db import persons_db_connection
from products.warehouse_sources.backend.facade.models import DataWarehouseTable
@@ -44,19 +45,33 @@ from ee.hogai.eval.schema import (
class TestSnapshotLoader(BaseTest):
+ # Team ids this class loads snapshots for. Keep in sync with the ids passed to _extras() (asserted there).
+ LOADED_TEAM_IDS = (9990, 99990)
+
+ def _clear_loaded_group_type_mappings(self):
+ # _load_group_type_mappings commits GTM rows through the off-ORM persons connection (outside the
+ # test transaction), so they don't roll back. Clear them scoped to this class's teams — in setUp
+ # to recover from a prior run that left rows, and in tearDown so they can't bleed into later tests
+ # sharing the persons DB.
+ with persons_db_connection(writer=True, autocommit=True) as conn, conn.cursor() as cursor:
+ cursor.execute("DELETE FROM posthog_grouptypemapping WHERE team_id = ANY(%s)", [list(self.LOADED_TEAM_IDS)])
+
def setUp(self):
super().setUp()
+ self._clear_loaded_group_type_mappings()
TEAM_TAXONOMY_QUERY_DATA_SOURCE.clear()
EVENT_TAXONOMY_QUERY_DATA_SOURCE.clear()
ACTORS_PROPERTY_TAXONOMY_QUERY_DATA_SOURCE.clear()
def tearDown(self):
+ self._clear_loaded_group_type_mappings()
TEAM_TAXONOMY_QUERY_DATA_SOURCE.clear()
EVENT_TAXONOMY_QUERY_DATA_SOURCE.clear()
ACTORS_PROPERTY_TAXONOMY_QUERY_DATA_SOURCE.clear()
super().tearDown()
def _extras(self, team_id: int) -> dict[str, Any]:
+ assert team_id in self.LOADED_TEAM_IDS, "Add new test team ids to LOADED_TEAM_IDS so cleanup stays scoped"
return {
"aws_endpoint_url": "http://localhost:9000",
"aws_bucket_name": "evals",