: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(admin): disallow child model count to hit persons db (#65324)
Nick Beste9ae385c76c7
diff --git a/posthog/admin/admins/organization_admin.py b/posthog/admin/admins/organization_admin.pyindex 5144a95dbe8c..224cbfb4172b 100644--- a/posthog/admin/admins/organization_admin.py+++ b/posthog/admin/admins/organization_admin.py@@ -20,29 +20,20 @@ from posthog.admin.inlines.project_inline import ProjectInlinefrom posthog.admin.inlines.team_inline import TeamInlinefrom posthog.admin.paginators.no_count_paginator import NoCountPaginatorfrom posthog.models.organization import Organization+from posthog.person_db_router import PERSONS_DB_MODELS-# Registry of models to count for bulk-delete report.+# Registry of default-db models to count for bulk-delete report.# Format: (model_import_path, filter_field, display_name)# This mirrors delete_bulky_postgres_data() in posthog/models/team/util.py# When bulk-delete changes, update this list accordingly.-# Note: CohortPeople and BatchExport require special handling (see below)+# Note: BatchExport requires special handling (see below)BULK_DELETE_MODEL_REGISTRY: tuple[tuple[str, str, str], ...] = (("products.early_access_features.backend.models.EarlyAccessFeature", "team_id", "Early Access Features"),- ("posthog.models.person.PersonDistinctId", "team_id", "Person Distinct IDs"),- ("posthog.models.person.PersonlessDistinctId", "team_id", "Personless Distinct IDs"),("products.error_tracking.backend.models.ErrorTrackingIssueFingerprintV2","team_id","Error Tracking Fingerprints",),- (- "products.feature_flags.backend.models.feature_flag.FeatureFlagHashKeyOverride",- "team_id",- "Feature Flag Overrides",- ),- ("posthog.models.group.group.Group", "team_id", "Groups"),- ("posthog.models.group_type_mapping.GroupTypeMapping", "team_id", "Group Type Mappings"),- ("posthog.models.person.Person", "team_id", "Persons"),("products.product_analytics.backend.models.insight_caching_state.InsightCachingState","team_id",@@ -50,13 +41,24 @@ BULK_DELETE_MODEL_REGISTRY: tuple[tuple[str, str, str], ...] = (),)+# Subset of persons-db models that are part of the bulk-delete path.+# Maps model_name (lowercase, matching person_db_router.PERSONS_DB_MODELS) to display name.+BULK_DELETE_PERSONS_DB_MODELS: dict[str, str] = {+ "cohortpeople": "Cohort People",+ "featureflaghashkeyoverride": "Feature Flag Overrides",+ "group": "Groups",+ "grouptypemapping": "Group Type Mappings",+ "person": "Persons",+ "persondistinctid": "Person Distinct IDs",+ "personlessdistinctid": "Personless Distinct IDs",+}+def get_model_counts_for_organization(organization: Organization) -> list[dict]:"""Returns counts of all bulk-delete models for teams in this organization.+ Models in the persons database are listed but not counted."""- from products.cohorts.backend.models.cohort import Cohort, CohortPeople-team_ids = list(organization.teams.values_list("id", flat=True))if not team_ids:return []@@ -83,32 +85,6 @@ def get_model_counts_for_organization(organization: Organization) -> list[dict]:})- # CohortPeople is in persons_db, Cohort is in default db - can't do cross-db JOIN- # Must first get cohort_ids from default db, then count CohortPeople by cohort_id- try:- cohort_ids = list(Cohort.objects.filter(team_id__in=team_ids).values_list("id", flat=True))- cohort_people_count = (- # nosemgrep: no-direct-persons-db-orm- CohortPeople.objects.filter(cohort_id__in=cohort_ids).count()- if cohort_ids- else 0 # nosemgrep: no-direct-persons-db-orm- ) # nosemgrep: no-direct-persons-db-orm- results.append(- {- "name": "Cohort People",- "count": cohort_people_count,- "model": CohortPeople._meta.label,- }- )- except Exception as e:- results.append(- {- "name": "Cohort People",- "count": f"Error: {e}",- "model": "products.cohorts.backend.models.CohortPeople",- }- )-# BatchExport requires deleted=False filter to match delete_batch_exports() behaviortry:from products.batch_exports.backend.models.batch_export import BatchExport@@ -130,6 +106,17 @@ def get_model_counts_for_organization(organization: Organization) -> list[dict]:})+ for model_name, display_name in BULK_DELETE_PERSONS_DB_MODELS.items():+ if model_name not in PERSONS_DB_MODELS:+ raise ValueError(f"{model_name} is listed in BULK_DELETE_PERSONS_DB_MODELS but not in PERSONS_DB_MODELS")+ results.append(+ {+ "name": display_name,+ "count": None,+ "persons_db": True,+ }+ )+return sorted(results, key=lambda x: x["name"])@@ -436,6 +423,7 @@ class OrganizationAdmin(admin.ModelAdmin):organization = Organization.objects.get(id=organization_id)counts = get_model_counts_for_organization(organization)total = sum(c["count"] for c in counts if isinstance(c["count"], int))+ has_persons_db_models = any(c.get("persons_db") for c in counts)return render(request,@@ -444,6 +432,7 @@ class OrganizationAdmin(admin.ModelAdmin):"organization": organization,"counts": counts,"total": total,+ "has_persons_db_models": has_persons_db_models,},)diff --git a/posthog/templates/admin/organization/model_counts.html b/posthog/templates/admin/organization/model_counts.htmlindex 25bf43b4d81c..4eb56fac3dfb 100644--- a/posthog/templates/admin/organization/model_counts.html+++ b/posthog/templates/admin/organization/model_counts.html@@ -18,7 +18,9 @@<tr><td style="padding: 10px; border: 1px solid #ddd;">{{ item.name }}</td><td style="text-align: right; padding: 10px; border: 1px solid #ddd;">- {% if item.count is not None %}+ {% if item.persons_db %}+ <em style="color: #888;">Persons database — count unavailable</em>+ {% elif item.count is not None %}{{ item.count|default:0 }}{% else %}-@@ -29,12 +31,19 @@</tbody><tfoot><tr style="background: #f5f5f5; font-weight: bold;">- <td style="padding: 10px; border: 1px solid #ddd;">Total Records</td>+ <td style="padding: 10px; border: 1px solid #ddd;">Total Records (default database only)</td><td style="text-align: right; padding: 10px; border: 1px solid #ddd;">{{ total|default:0 }}</td></tr></tfoot></table>+{% if has_persons_db_models %}+<p style="color: #888; font-style: italic;">+ Some models live in the persons database and cannot be counted from this admin view.+ These models will still be deleted as part of organization deletion.+</p>+{% endif %}+<p style="margin-top: 20px;"><a href="{% url 'admin:posthog_organization_change' organization.id %}">← Back to Organization</a></p>