: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
fix(api): backfill non-array test_account_filters rows (#58375)
Jovan Sakovicd52dbe3b380c
diff --git a/posthog/migrations/1185_fix_non_list_test_account_filters.py b/posthog/migrations/1185_fix_non_list_test_account_filters.pynew file mode 100644index 000000000000..ca5de2c8df7a--- /dev/null+++ b/posthog/migrations/1185_fix_non_list_test_account_filters.py@@ -0,0 +1,84 @@+# Generated by Django 5.2.13 on 2026-05-26++import json++from django.db import migrations+from django.db.models import CharField, F, Func++import structlog++logger = structlog.get_logger(__name__)++BULK_BATCH_SIZE = 500+++def _coerce_to_filter_list(value: object) -> list:+ if isinstance(value, list):+ return value+ if isinstance(value, str):+ # The most common corruption is a JSON-encoded list passed as a string; keep its contents.+ try:+ parsed = json.loads(value)+ except (TypeError, ValueError):+ return []+ if isinstance(parsed, list):+ return parsed+ return []+++def fix_non_list_test_account_filters(apps, schema_editor):+ """Reconcile Team.test_account_filters rows that aren't a JSON array.++ test_account_filters is a free-form JSONField and, before request-time+ validation rejected non-list values, some rows were written with a+ JSON-encoded string (e.g. via the project-settings-update MCP tool). A+ non-array value crashes the project settings page and every query that+ iterates team.test_account_filters, so the stored rows must be fixed.++ Where the stored value is a JSON string that itself parses to a list we+ keep that list; anything else is reset to []. The pre-migration value is+ recoverable from the ActivityLog rows the team/project update endpoints+ write. The filter is pushed to Postgres (jsonb_typeof) so this only touches+ the handful of affected rows - in practice a tiny set - which keeps it safe+ to run inside the default migration transaction.+ """+ Team = apps.get_model("posthog", "Team")++ bad_teams = (+ Team.objects.annotate(+ _taf_type=Func(F("test_account_filters"), function="jsonb_typeof", output_field=CharField())+ )+ .exclude(_taf_type="array")+ .only("id", "test_account_filters")+ )++ batch: list = []+ fixed = 0+ for team in bad_teams.iterator(chunk_size=BULK_BATCH_SIZE):+ team.test_account_filters = _coerce_to_filter_list(team.test_account_filters)+ batch.append(team)+ if len(batch) >= BULK_BATCH_SIZE:+ Team.objects.bulk_update(batch, ["test_account_filters"])+ fixed += len(batch)+ batch = []+ if batch:+ Team.objects.bulk_update(batch, ["test_account_filters"])+ fixed += len(batch)++ if fixed:+ logger.info("fixed_non_list_test_account_filters", count=fixed)+++class Migration(migrations.Migration):+ dependencies = [+ ("posthog", "1184_migrate_product_analytics_models"),+ ]++ operations = [+ migrations.RunPython(+ fix_non_list_test_account_filters,+ # Not reversible: rolling back would re-introduce non-array values, and the+ # pre-migration value is recoverable from ActivityLog if ever needed.+ migrations.RunPython.noop,+ ),+ ]diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txtindex 4282e86c14b1..fd0c44b6e724 100644--- a/posthog/migrations/max_migration.txt+++ b/posthog/migrations/max_migration.txt@@ -1 +1 @@-1184_migrate_product_analytics_models+1185_fix_non_list_test_account_filtersdiff --git a/posthog/test/test_migration_1185.py b/posthog/test/test_migration_1185.pynew file mode 100644index 000000000000..7f00aa8b3ba6--- /dev/null+++ b/posthog/test/test_migration_1185.py@@ -0,0 +1,82 @@+from typing import Any++import pytest+from posthog.test.base import TestMigrations++from parameterized import parameterized++pytestmark = pytest.mark.skip("old migrations slow overall test run down")+++class FixNonListTestAccountFiltersMigrationTest(TestMigrations):+ migrate_from = "1184_migrate_product_analytics_models"+ migrate_to = "1185_fix_non_list_test_account_filters"++ CLASS_DATA_LEVEL_SETUP = False++ def setUpBeforeMigration(self, apps: Any) -> None:+ Organization = apps.get_model("posthog", "Organization")+ Project = apps.get_model("posthog", "Project")+ Team = apps.get_model("posthog", "Team")++ self.organization = Organization.objects.create(name="Test Organization")+ self.project = Project.objects.create(organization=self.organization, name="Test Project", id=1_000_001)+ self.Team = Team++ # JSONField encodes whatever Python value we pass via json.dumps, so a Python str+ # becomes a JSON string in the column - the exact corruption we are repairing.+ self.teams = {+ "stringified_array": self._create_team(+ "stringified_array",+ test_account_filters='[{"key":"$browser","value":"Chrome","operator":"exact"}]',+ ),+ "stringified_non_array": self._create_team(+ "stringified_non_array",+ test_account_filters="not even an array",+ ),+ "object": self._create_team(+ "object",+ test_account_filters={"key": "$browser", "value": "Chrome"},+ ),+ "json_null": self._create_team(+ "json_null",+ test_account_filters=None,+ ),+ "already_array": self._create_team(+ "already_array",+ test_account_filters=[{"key": "email", "value": "@posthog.com", "operator": "icontains"}],+ ),+ }++ def _create_team(self, name: str, test_account_filters: Any) -> Any:+ return self.Team.objects.create(+ organization=self.organization,+ project=self.project,+ name=name,+ test_account_filters=test_account_filters,+ )++ @parameterized.expand(+ [+ # Stringified JSON array - the meaningful recovery, preserve the parsed contents.+ (+ "stringified_array",+ [{"key": "$browser", "value": "Chrome", "operator": "exact"}],+ ),+ # Stringified non-array - cannot recover, reset to [].+ ("stringified_non_array", []),+ # JSON object - reset to [].+ ("object", []),+ # JSON null - reset to [].+ ("json_null", []),+ # Already a valid array - left untouched.+ (+ "already_array",+ [{"key": "email", "value": "@posthog.com", "operator": "icontains"}],+ ),+ ]+ )+ def test_test_account_filters_normalized(self, team_key: str, expected: list) -> None:+ team = self.teams[team_key]+ team.refresh_from_db()+ self.assertEqual(team.test_account_filters, expected)