: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(migrations): read the domain idp config field under either name (#101626)
posthog[bot]99a0f7a090cd
diff --git a/ee/migrations/0058_backfill_scim_provisioned_user_config.py b/ee/migrations/0058_backfill_scim_provisioned_user_config.pyindex ec42d814d60e..033a73f80521 100644--- a/ee/migrations/0058_backfill_scim_provisioned_user_config.py+++ b/ee/migrations/0058_backfill_scim_provisioned_user_config.py@@ -10,23 +10,25 @@ logger = structlog.get_logger(__name__)CHUNK_SIZE = 1000-def _ids_to_leave_on_their_domain_key(pending: Any) -> list[Any]:+def _domain_config_field(OrganizationDomain: Any) -> str:+ # posthog.1316 renames this field to `_identity_provider_config` in migration state. This+ # backfill can run on either side of that rename, and no ordering edge can say which: 1316 and+ # this migration sit inside the two squashes, so an edge between them closes a cycle between+ # the squashes themselves.+ names = {field.name for field in OrganizationDomain._meta.get_fields()}+ return "identity_provider_config" if "identity_provider_config" in names else "_identity_provider_config"+++def _ids_to_leave_on_their_domain_key(pending: Any, config_path: str) -> list[Any]:# One user provisioned through two domains of one config holds two records for what is now a# single tenant. Keep the oldest on the config and leave the rest on their domain key, so the# unique constraint added in 0060 holds without this dropping anyone's record.- duplicate_groups = (- pending.values("user_id", "organization_domain__identity_provider_config")- .annotate(rows=Count("id"))- .filter(rows__gt=1)- )+ duplicate_groups = pending.values("user_id", config_path).annotate(rows=Count("id")).filter(rows__gt=1)skipped: list[Any] = []for group in duplicate_groups:group_ids = list(- pending.filter(- user_id=group["user_id"],- organization_domain__identity_provider_config=group["organization_domain__identity_provider_config"],- )+ pending.filter(user_id=group["user_id"], **{config_path: group[config_path]}).order_by("created_at", "id").values_list("id", flat=True))@@ -34,7 +36,7 @@ def _ids_to_leave_on_their_domain_key(pending: Any) -> list[Any]:logger.warning("scim_provisioned_user_duplicate_for_identity_provider_config",scim_provisioned_user_id=str(row_id),- identity_provider_config_id=str(group["organization_domain__identity_provider_config"]),+ identity_provider_config_id=str(group[config_path]),)skipped.extend(group_ids[1:])return skipped@@ -52,16 +54,19 @@ def backfill_scim_provisioned_user_config(apps: Any, schema_editor: Any) -> NoneOrganizationDomain = apps.get_model("posthog", "OrganizationDomain")db_alias = schema_editor.connection.alias+ config_field = _domain_config_field(OrganizationDomain)+ config_path = f"organization_domain__{config_field}"+pending = SCIMProvisionedUser.objects.using(db_alias).filter(identity_provider_config__isnull=True,- organization_domain__identity_provider_config__isnull=False,+ **{f"{config_path}__isnull": False},)- claimable = pending.exclude(id__in=_ids_to_leave_on_their_domain_key(pending))+ claimable = pending.exclude(id__in=_ids_to_leave_on_their_domain_key(pending, config_path))config_of_domain = Subquery(OrganizationDomain.objects.using(db_alias).filter(pk=OuterRef("organization_domain_id"))- .values("identity_provider_config_id")[:1]+ .values(f"{config_field}_id")[:1])# Walking the primary key keeps the scan forward-only and each statement small.@@ -84,11 +89,6 @@ def backfill_scim_provisioned_user_config(apps: Any, schema_editor: Any) -> Noneclass Migration(migrations.Migration):dependencies = [("ee", "0057_scim_records_identity_provider_config_indexes")]- # This backfill reads OrganizationDomain.identity_provider_config, which posthog.1316 renames in- # migration state. Without this edge the planner is free to apply 1316 first, and the backfill- # then fails on a fresh database with an unsupported-lookup FieldError.- run_before = []-operations = [migrations.RunPython(backfill_scim_provisioned_user_config,diff --git a/ee/migrations/test/test_migration_0058.py b/ee/migrations/test/test_migration_0058.pynew file mode 100644index 000000000000..154c100ead4c--- /dev/null+++ b/ee/migrations/test/test_migration_0058.py@@ -0,0 +1,68 @@+import importlib++from posthog.test.base import BaseTest++from django.apps import apps as current_apps+from django.db.migrations.loader import MigrationLoader+from django.db.migrations.operations.fields import RenameField++from parameterized import parameterized++from posthog.models.identity_provider_config import IdentityProviderConfig+from posthog.models.organization_domain import OrganizationDomain+from posthog.models.user import User++from ee.models.scim_provisioned_user import SCIMProvisionedUser++migration_module = importlib.import_module("ee.migrations.0058_backfill_scim_provisioned_user_config")+backfill_scim_provisioned_user_config = migration_module.backfill_scim_provisioned_user_config+++class FakeSchemaEditor:+ class connection:+ alias = "default"+++def apps_before_the_rename():+ # posthog.1316 renames the field, and the squashes leave this backfill free to run on either+ # side of it. The current state with that one rename undone is the other side.+ state = MigrationLoader(connection=None).project_state()+ RenameField("organizationdomain", "_identity_provider_config", "identity_provider_config").state_forwards(+ "posthog", state+ )+ return state.apps+++class TestBackfillScimProvisionedUserConfig(BaseTest):+ def _domain(self, domain: str, config: IdentityProviderConfig) -> OrganizationDomain:+ return OrganizationDomain.objects.create(+ organization=self.organization, domain=domain, _identity_provider_config=config+ )++ def _record(self, user: User, domain: OrganizationDomain) -> SCIMProvisionedUser:+ return SCIMProvisionedUser.objects.create(+ user=user,+ organization_domain=domain,+ identity_provider=SCIMProvisionedUser.IdentityProvider.OKTA,+ username=user.email,+ )++ @parameterized.expand([("before_the_rename",), ("after_the_rename",)])+ def test_claims_records_keyed_on_a_domain(self, case):+ config = IdentityProviderConfig.objects.create(organization=self.organization, scim_enabled=True)+ first_domain = self._domain("one.example.com", config)+ second_domain = self._domain("two.example.com", config)++ claimable = self._record(self.user, first_domain)+ duplicate_user = User.objects.create_and_join(self.organization, "[email protected]", None)+ oldest_of_the_duplicates = self._record(duplicate_user, first_domain)+ newest_of_the_duplicates = self._record(duplicate_user, second_domain)++ apps = apps_before_the_rename() if case == "before_the_rename" else current_apps+ backfill_scim_provisioned_user_config(apps, FakeSchemaEditor())++ for record in (claimable, oldest_of_the_duplicates, newest_of_the_duplicates):+ record.refresh_from_db()+ assert claimable.identity_provider_config_id == config.id+ assert oldest_of_the_duplicates.identity_provider_config_id == config.id+ assert newest_of_the_duplicates.identity_provider_config_id is Nonediff --git a/posthog/test/repo_invariants/test_migration_run_before.py b/posthog/test/repo_invariants/test_migration_run_before.pynew file mode 100644index 000000000000..ee3ff3a813fd--- /dev/null+++ b/posthog/test/repo_invariants/test_migration_run_before.py@@ -0,0 +1,23 @@+"""A migration that declares `run_before` must name a target.++`run_before = []` is the same as not declaring the attribute, so it is always a leftover: a+migration that needs an ordering edge silently loses it, and the comment above the line keeps+telling the reader the edge is there. Django reports nothing, and the planner is then free to+apply the two migrations in either order.+"""++from django.db.migrations.loader import MigrationLoader+++def test_declared_run_before_names_a_target() -> None:+ loader = MigrationLoader(connection=None, load=False)+ loader.load_disk()+ offenders = sorted(+ f"{app}.{name}"+ for (app, name), migration in loader.disk_migrations.items()+ if "run_before" in type(migration).__dict__ and not migration.run_before+ )+ assert not offenders, (+ "These migrations declare an empty run_before. Name the migration this one must run "+ "before, or delete the attribute.\n " + "\n ".join(offenders)+ )