: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
perf(auth): add functional index for stripped-alias email lookups (#80298)
Yasen387e2384051a
diff --git a/posthog/migrations/1298_user_stripped_alias_index.py b/posthog/migrations/1298_user_stripped_alias_index.pynew file mode 100644index 000000000000..ffee673ebbb5--- /dev/null+++ b/posthog/migrations/1298_user_stripped_alias_index.py@@ -0,0 +1,40 @@+import django.db.models.functions.text+from django.db import migrations, models++from posthog.migration_helpers import SafeAddIndexConcurrently+++class Migration(migrations.Migration):+ """+ posthog_user is a hot table read on virtually every request, so a plain `AddIndex` (which+ takes an ACCESS EXCLUSIVE lock to build) risks stalling site-wide traffic. SafeAddIndexConcurrently+ builds it with CREATE INDEX CONCURRENTLY (SHARE UPDATE EXCLUSIVE, doesn't block reads/writes),+ tracking Django state the same way AddIndex would.++ The index is not yet used by any query in this migration — EmailValidationHelper.user_exists_with_stripped_alias+ still filters via iexact/istartswith/iendswith. A follow-up change rewrites that lookup to filter+ on this same expression, turning its full-table scan into an index scan. Landing the index first,+ on its own, lets it finish building before that lookup starts relying on it.+ """++ atomic = False++ dependencies = [+ ("auth", "0012_alter_user_first_name_max_length"),+ ("posthog", "1297_add_instagram_integration_kind"),+ ]++ operations = [+ SafeAddIndexConcurrently(+ model_name="user",+ index=models.Index(+ models.Func(+ django.db.models.functions.text.Lower("email"),+ models.Value("\\+[^@]*@"),+ models.Value("@"),+ function="regexp_replace",+ ),+ name="user_stripped_alias_idx",+ ),+ ),+ ]diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txtindex 6a06ee7a3e31..cfed6ad50b9e 100644--- a/posthog/migrations/max_migration.txt+++ b/posthog/migrations/max_migration.txt@@ -1 +1 @@-1297_add_instagram_integration_kind+1298_user_stripped_alias_indexdiff --git a/posthog/models/user.py b/posthog/models/user.pyindex 4b9f141cf940..49dae2c946d1 100644--- a/posthog/models/user.py+++ b/posthog/models/user.py@@ -5,6 +5,8 @@ from typing import TYPE_CHECKING, Any, NoReturn, Optional, TypedDict, castfrom django.contrib.auth.models import AbstractUser, BaseUserManagerfrom django.core.management.base import CommandErrorfrom django.db import models, transaction+from django.db.models import Func, Value+from django.db.models.functions import Lowerfrom django.db.models.signals import pre_savefrom django.dispatch import receiverfrom django.utils.translation import gettext_lazy as _@@ -326,6 +328,16 @@ class User(AbstractUser, UUIDTClassicModel, ModelActivityMixin): # type: ignore# we never drop columns to avoid failures during rolling deploys.temporary_token = deprecate_field(models.CharField(max_length=200, null=True, blank=True, unique=True))+ class Meta:+ verbose_name = _("user")+ verbose_name_plural = _("users")+ indexes = [+ models.Index(+ Func(Lower("email"), Value(r"\+[^@]*@"), Value("@"), function="regexp_replace"),+ name="user_stripped_alias_idx",+ ),+ ]+# Remove unused attributes from `AbstractUser`username = cast(Any, None)diff --git a/posthog/test/test_migration_1296.py b/posthog/test/test_migration_1296.pyindex 5627c3b16efb..3502a6a74618 100644--- a/posthog/test/test_migration_1296.py+++ b/posthog/test/test_migration_1296.py@@ -1,14 +1,16 @@from datetime import timedeltafrom typing import Any-from posthog.test.base import TestMigrations+from posthog.test.base import NonAtomicTestMigrationsfrom django.utils import timezonefrom parameterized import parameterized-class BackfillCimdVerificationTokenUrlMigrationTest(TestMigrations):+# Non-atomic because rewinding to `migrate_from` unapplies every later migration, and those include+# `atomic = False` ones whose CONCURRENTLY index operations Postgres refuses inside a transaction.+class BackfillCimdVerificationTokenUrlMigrationTest(NonAtomicTestMigrations):migrate_from = "1295_cimdverificationtoken_cimd_url"migrate_to = "1296_backfill_cimd_verification_token_url"