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.

fix(persons): refuse persons-database models in background_delete_model (#112934)

Eli Reisman811c71bd66d0
diff --git a/posthog/management/commands/background_delete_model.py b/posthog/management/commands/background_delete_model.py
index e7172622d20e..440b258b6209 100644
--- a/posthog/management/commands/background_delete_model.py
+++ b/posthog/management/commands/background_delete_model.py
@@ -5,7 +5,7 @@ from django.core.management.base import BaseCommand, CommandError
import structlog
-from posthog.tasks.tasks import background_delete_model_task
+from posthog.tasks.tasks import background_delete_model_task, ensure_not_persons_db_model
logger = structlog.get_logger(__name__)
logger.setLevel(logging.INFO)
@@ -15,7 +15,7 @@ class Command(BaseCommand):
help = "Start a background deletion task for a model with team_id field"
def add_arguments(self, parser):
- parser.add_argument("model_name", type=str, help="Django model name (e.g., 'posthog.Person', 'posthog.Event')")
+ parser.add_argument("model_name", type=str, help="Django model name (e.g., 'posthog.Tag')")
parser.add_argument("--team-id", type=int, required=True, help="Team ID to filter records for deletion")
parser.add_argument(
"--batch-size", type=int, default=10000, help="Number of rows to delete per batch (default: 10000)"
@@ -56,6 +56,11 @@ class Command(BaseCommand):
except LookupError as e:
raise CommandError(f"Model not found: {e}")
+ try:
+ ensure_not_persons_db_model(model)
+ except ValueError as e:
+ raise CommandError(str(e))
+
# Check if model has team_id field
team_field = None
if "team_id" in [field.name for field in model._meta.get_fields()]:
diff --git a/posthog/management/commands/test/test_background_delete_model.py b/posthog/management/commands/test/test_background_delete_model.py
index 18718c93b414..4862d47b7a0d 100644
--- a/posthog/management/commands/test/test_background_delete_model.py
+++ b/posthog/management/commands/test/test_background_delete_model.py
@@ -5,12 +5,15 @@ from unittest.mock import MagicMock, patch
from django.core.management.base import CommandError
+from parameterized import parameterized
+
from posthog.management.commands.background_delete_model import Command
from posthog.models import Tag
+from posthog.tasks.tasks import background_delete_model_task
# 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.)
+# model-agnostic, so the specific model is incidental. (Persons-database models are refused, so
+# these tests cannot use them.)
class TestBackgroundDeleteModel(BaseTest):
@@ -51,6 +54,22 @@ class TestBackgroundDeleteModel(BaseTest):
self.assertIn("does not have a team_id or team field", str(context.exception))
+ @parameterized.expand(
+ [("posthog.Person",), ("posthog.PersonDistinctId",), ("feature_flags.FeatureFlagHashKeyOverride",)]
+ )
+ @patch("posthog.management.commands.background_delete_model.background_delete_model_task")
+ def test_refuses_persons_db_models(self, model_name, mock_task):
+ with self.assertRaises(CommandError) as context:
+ self.command.handle(model_name, team_id=self.team.id)
+
+ self.assertIn("lives in the persons database", str(context.exception))
+ mock_task.assert_not_called()
+ mock_task.delay.assert_not_called()
+
+ def test_task_refuses_persons_db_model(self):
+ with self.assertRaisesRegex(ValueError, "lives in the persons database"):
+ background_delete_model_task("posthog.Person", team_id=self.team.id)
+
@patch("posthog.management.commands.background_delete_model.background_delete_model_task")
@patch("builtins.input", return_value="DELETE 2 RECORDS")
def test_valid_model_with_team_id_field(self, mock_input, mock_task):
diff --git a/posthog/tasks/tasks.py b/posthog/tasks/tasks.py
index dc43ec75948f..22618f3d430e 100644
--- a/posthog/tasks/tasks.py
+++ b/posthog/tasks/tasks.py
@@ -9,6 +9,7 @@ from uuid import UUID
from django.conf import settings
from django.db import OperationalError, ProgrammingError, connection
+from django.db.models import Model
from django.utils import timezone
import requests
@@ -30,6 +31,7 @@ from posthog.exceptions import ClickHouseAtCapacity, QueryRanConcurrently
from posthog.exceptions_capture import capture_exception
from posthog.metrics import pushed_metrics_registry
from posthog.models.event.new_events_schema import events_read_table, use_new_events_schema
+from posthog.person_db_router import PersonDBRouter
from posthog.ph_client import get_regional_ph_client
from posthog.redis import get_client
from posthog.scoping_audit import skip_team_scope_audit
@@ -1117,6 +1119,15 @@ def send_org_usage_reports() -> None:
send_all_org_usage_reports.delay()
+def ensure_not_persons_db_model(model: type[Model]) -> None:
+ # Hobby keeps persons-database tables in the main database, where a raw delete would skip personhog
+ # and leave the ClickHouse rows live.
+ if PersonDBRouter().is_persons_model(model._meta.app_label, model._meta.model_name):
+ raise ValueError(
+ f"{model._meta.label} lives in the persons database. Use the person, group or team delete flows instead."
+ )
+
+
@shared_task(ignore_result=True, queue=CeleryQueue.LONG_RUNNING.value)
def background_delete_model_task(
model_name: str, team_id: int, batch_size: int = 10000, records_to_delete: int | None = None
@@ -1143,6 +1154,7 @@ def background_delete_model_task(
# Parse model name
app_label, model_label = model_name.split(".")
model = apps.get_model(app_label, model_label)
+ ensure_not_persons_db_model(model)
# Determine team field name
team_field = "team_id" if hasattr(model, "team_id") else "team"