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.

chore(migrations): enforce idempotent concurrent index migrations (#59096)

Sandy Spicer8394827e9be2
diff --git a/docs/published/handbook/engineering/safe-django-migrations.md b/docs/published/handbook/engineering/safe-django-migrations.md
index f2033b148927..61afb589534f 100644
--- a/docs/published/handbook/engineering/safe-django-migrations.md
+++ b/docs/published/handbook/engineering/safe-django-migrations.md
@@ -289,51 +289,111 @@ class Migration(migrations.Migration):
- **Blocks all writes:** No data can be written during index creation
- **Deployment timeout:** Migration might exceed timeout limits
-### Safe Approach: Concurrent Index Creation
-
-**Recommended: Use Django's built-in concurrent operations (PostgreSQL only):**
+### Why `AddIndexConcurrently` Is Not Enough
+
+Do not use `AddIndexConcurrently` / `RemoveIndexConcurrently` directly.
+They are non-blocking, but they are **not idempotent**:
+Django emits a bare `CREATE INDEX CONCURRENTLY` (or `DROP INDEX CONCURRENTLY`)
+with no `IF NOT EXISTS` / `IF EXISTS`, and there is no hook to disable
+`lock_timeout` or `statement_timeout` for the build.
+
+Deploy runs migrations under a `lock_timeout`, and `bin/migrate` re-runs the
+**entire** migration on failure with exponential backoff.
+`CREATE INDEX CONCURRENTLY` is non-transactional and runs with `atomic = False`,
+so if the build is cancelled (a single transient `lock_timeout` while another
+session holds a conflicting lock is enough; OOM, deploy timeout, statement_timeout,
+SIGTERM and PG restarts can do the same) PostgreSQL leaves an **invalid** index
+behind with nothing to roll it back.
+The next retry then re-issues the same bare statement and fails with
+`relation "..." already exists` (or `index "..." does not exist` for drops).
+The migration is now stuck and blocks all deploys until someone drops or
+`REINDEX`es the invalid index by hand.
+
+`IF NOT EXISTS` alone is **not enough** either. PG's `IF NOT EXISTS` is
+name-level, not state-level — it skips when an index with that name exists,
+regardless of whether it is valid (`indisvalid = false`). A bare retry under
+`IF NOT EXISTS` will silently no-op past an invalid leftover and mark the
+migration applied while the index does nothing.
+
+This is enforced: `ConcurrentIndexIdempotencyPolicy` in the migration risk
+analyzer blocks any migration that uses `AddIndexConcurrently`,
+`RemoveIndexConcurrently`, or a raw `RunSQL` concurrent index without
+`IF [NOT] EXISTS`.
+
+### Safe Approach: `CreateIndexConcurrently` Helper (Recommended)
+
+The `posthog.migration_helpers.CreateIndexConcurrently` helper handles the
+full safe pattern: disables `lock_timeout` and `statement_timeout` on the
+migration connection, looks the target index up in `pg_index`, drops it if
+it was left in an invalid state by a prior interrupted build, then runs
+`CREATE INDEX CONCURRENTLY IF NOT EXISTS`.
+
+Wrap it in `SeparateDatabaseAndState` so Django model state still tracks the
+index (keeps `makemigrations --check` and the ORM correct):
```python
-from django.contrib.postgres.operations import AddIndexConcurrently
from django.db import migrations, models
+from posthog.migration_helpers import CreateIndexConcurrently
+
+
class Migration(migrations.Migration):
atomic = False # Required for CONCURRENTLY
operations = [
- AddIndexConcurrently(
- model_name='mymodel',
- index=models.Index(fields=['field_name'], name='mymodel_field_idx'),
+ migrations.SeparateDatabaseAndState(
+ state_operations=[
+ migrations.AddIndex(
+ model_name="mymodel",
+ index=models.Index(fields=["field_name"], name="mymodel_field_idx"),
+ ),
+ ],
+ database_operations=[
+ CreateIndexConcurrently(
+ index_name="mymodel_field_idx",
+ table_name="mymodel",
+ columns="(field_name)",
+ ),
+ ],
),
]
```
-**If you need `IF NOT EXISTS` for idempotency, use RunSQL:**
+Dropping an index uses the mirror helper, `DropIndexConcurrently`, with
+`RemoveIndex` in `state_operations`.
-```python
-from django.db import migrations
+### Fallback: Raw `RunSQL` + `lock_timeout = 0` + `IF NOT EXISTS`
-class Migration(migrations.Migration):
- atomic = False # Required for CONCURRENTLY
+For exotic cases the helper doesn't cover (partitioned tables, custom
+operator classes the helper hasn't grown a knob for yet, etc.), raw `RunSQL`
+is still accepted by the policy as long as it includes `IF [NOT] EXISTS`:
- operations = [
- migrations.RunSQL(
- sql="""
- CREATE INDEX CONCURRENTLY IF NOT EXISTS mymodel_field_idx
- ON mymodel (field_name)
- """,
- reverse_sql="DROP INDEX CONCURRENTLY IF EXISTS mymodel_field_idx",
- ),
- ]
+```python
+migrations.RunSQL(
+ sql="""
+ SET lock_timeout = 0;
+ SET statement_timeout = 0;
+ CREATE INDEX CONCURRENTLY IF NOT EXISTS mymodel_field_idx
+ ON mymodel (field_name);
+ """,
+ reverse_sql="DROP INDEX CONCURRENTLY IF EXISTS mymodel_field_idx;",
+)
```
+This form is strictly weaker than the helper: it does not detect or clean up
+an `indisvalid = false` leftover. If a prior deploy was interrupted by
+anything other than `lock_timeout`, manual `REINDEX INDEX CONCURRENTLY` or
+`DROP INDEX CONCURRENTLY IF EXISTS` is needed before re-running. Prefer the
+helper.
+
### Key Points
-- **Use `AddIndexConcurrently` for existing large tables** - it handles the SQL correctly
-- `AddIndexConcurrently` does not support `IF NOT EXISTS` - use `RunSQL` if you need idempotency
-- Set `atomic = False` in the migration (required for all CONCURRENTLY operations)
-- Concurrent index creation is slower but doesn't block writes
-- Use `RemoveIndexConcurrently` to drop indexes safely
+- **Never use `AddIndexConcurrently` / `RemoveIndexConcurrently` directly** — they are non-idempotent and the CI policy blocks them
+- **Prefer `CreateIndexConcurrently` / `DropIndexConcurrently` from `posthog.migration_helpers`** — it disables both timeouts and recovers from invalid leftover indexes
+- Raw `RunSQL` with `SET lock_timeout = 0; SET statement_timeout = 0; CREATE INDEX CONCURRENTLY IF NOT EXISTS ...` is acceptable as a fallback but does not recover from invalid leftovers
+- Wrap in `SeparateDatabaseAndState` so Django model state still tracks the index
+- Set `atomic = False` (required for all `CONCURRENTLY` operations)
+- If a prior deploy already left an invalid index (the helper would catch this on next run, but the fallback won't), clean it up with `REINDEX INDEX CONCURRENTLY` or `DROP INDEX CONCURRENTLY IF EXISTS` before re-running
## Adding Constraints
@@ -597,21 +657,37 @@ class Migration(migrations.Migration):
PostgreSQL's `CONCURRENTLY` operations cannot run inside transactions. Use `atomic=False` **only** when required.
```python
+from posthog.migration_helpers import CreateIndexConcurrently
+
+
class Migration(migrations.Migration):
atomic = False # Required for CONCURRENTLY
operations = [
- AddIndexConcurrently(
- model_name="mymodel",
- index=models.Index(fields=["field_name"], name="mymodel_field_idx"),
+ migrations.SeparateDatabaseAndState(
+ state_operations=[
+ migrations.AddIndex(
+ model_name="mymodel",
+ index=models.Index(fields=["field_name"], name="mymodel_field_idx"),
+ ),
+ ],
+ database_operations=[
+ CreateIndexConcurrently(
+ index_name="mymodel_field_idx",
+ table_name="mymodel",
+ columns="(field_name)",
+ ),
+ ],
),
]
```
+See [Adding Indexes](#adding-indexes) for why the bare `AddIndexConcurrently` form is unsafe and what the helper does under the hood.
+
**When to use `atomic=False`:**
-- `CREATE INDEX CONCURRENTLY` (required - `AddIndexConcurrently` needs this)
-- `DROP INDEX CONCURRENTLY` (required - `RemoveIndexConcurrently` needs this)
+- `CREATE INDEX CONCURRENTLY` (required — use `CreateIndexConcurrently`, not `AddIndexConcurrently`)
+- `DROP INDEX CONCURRENTLY` (required — use `DropIndexConcurrently`, not `RemoveIndexConcurrently`)
- `REINDEX CONCURRENTLY` (required)
**When NOT to use `atomic=False`:**
diff --git a/posthog/management/commands/test_migrations_are_safe.py b/posthog/management/commands/test_migrations_are_safe.py
index 69a649f40c87..85d4d2037139 100644
--- a/posthog/management/commands/test_migrations_are_safe.py
+++ b/posthog/management/commands/test_migrations_are_safe.py
@@ -135,9 +135,9 @@ def validate_migration_sql(sql) -> bool:
):
print(
f"\n\n\033[91mFound a CREATE INDEX command that isn't run CONCURRENTLY. This locks tables which causes downtime. "
- "See https://github.com/PostHog/posthog/blob/master/docs/published/safe-django-migrations.md for guidance."
- "If adding the index by itself, please use `AddIndexConcurrently()` of `django.contrib.postgres.operations` instead. "
- "See https://docs.djangoproject.com/en/4.2/ref/contrib/postgres/operations/#concurrent-index-operations.\n"
+ "Use a RunSQL `SET lock_timeout = 0; CREATE INDEX CONCURRENTLY IF NOT EXISTS ...` wrapped in SeparateDatabaseAndState "
+ "(not AddIndexConcurrently, which is non-idempotent and blocked by ConcurrentIndexIdempotencyPolicy). "
+ "See https://github.com/PostHog/posthog/blob/master/docs/published/handbook/engineering/safe-django-migrations.md#adding-indexes\n"
f"Source: `{operation_sql}`"
)
return True
diff --git a/posthog/management/migration_analysis/operations.py b/posthog/management/migration_analysis/operations.py
index 8bd1151abc3d..b8d4e0f89b9e 100644
--- a/posthog/management/migration_analysis/operations.py
+++ b/posthog/management/migration_analysis/operations.py
@@ -383,18 +383,38 @@ class AddIndexAnalyzer(OperationAnalyzer):
class AddIndexConcurrentlyAnalyzer(OperationAnalyzer):
- """Analyzer for AddIndexConcurrently - always safe as it's designed for non-locking index creation."""
+ """Analyzer for AddIndexConcurrently.
+
+ Non-blocking, but NOT idempotent: it emits a bare CREATE INDEX CONCURRENTLY
+ with no IF NOT EXISTS and no way to disable lock_timeout. Under the deploy
+ retry loop a single lock_timeout cancellation leaves an invalid index and
+ every retry then fails with "relation already exists". ConcurrentIndexIdempotencyPolicy
+ blocks this; the score here keeps the per-operation report consistent.
+ """
operation_type = "AddIndexConcurrently"
- default_score = 0
+ default_score = 2
def analyze(self, op) -> OperationRisk:
model_name = getattr(op, "model_name", None)
return OperationRisk(
type=self.operation_type,
- score=0,
- reason="Concurrent index creation is safe (non-blocking)",
+ score=2,
+ reason="AddIndexConcurrently is non-idempotent (bare CREATE INDEX CONCURRENTLY, no lock_timeout control)",
details={"model": model_name},
+ guidance=f"""Don't use AddIndexConcurrently. It emits CREATE INDEX CONCURRENTLY with no IF NOT EXISTS and cannot set lock_timeout, so a single lock-timeout cancellation during deploy leaves an invalid index and every bin/migrate retry then fails with "relation already exists".
+
+Use RunSQL wrapped in SeparateDatabaseAndState:
+
+ migrations.SeparateDatabaseAndState(
+ state_operations=[migrations.AddIndex(...)],
+ database_operations=[migrations.RunSQL(
+ sql="SET lock_timeout = 0; CREATE INDEX CONCURRENTLY IF NOT EXISTS my_idx ON my_table (col);",
+ reverse_sql="DROP INDEX CONCURRENTLY IF EXISTS my_idx;",
+ )],
+ )
+
+[See the migration safety guide]({SAFE_MIGRATIONS_DOCS_URL}#adding-indexes)""",
)
@@ -462,13 +482,14 @@ class RunSQLAnalyzer(OperationAnalyzer):
score=1,
reason="CREATE INDEX CONCURRENTLY is safe (non-blocking)",
details={"sql": sql},
+ guidance="Also prefix with `SET lock_timeout = 0;` so the deploy lock_timeout can't cancel the build and leave an invalid index that defeats IF NOT EXISTS on retry.",
)
return OperationRisk(
type=self.operation_type,
score=2,
reason="CREATE INDEX CONCURRENTLY is safe (non-blocking)",
details={"sql": sql},
- guidance="Add IF NOT EXISTS for idempotency: CREATE INDEX CONCURRENTLY IF NOT EXISTS",
+ guidance='Make this idempotent and uncancellable: `SET lock_timeout = 0; CREATE INDEX CONCURRENTLY IF NOT EXISTS ...`. Without IF NOT EXISTS, a cancelled build leaves an invalid index and every bin/migrate retry fails with "relation already exists".',
)
elif "DROP" in sql and "INDEX" in sql:
if "IF EXISTS" in sql:
@@ -847,17 +868,36 @@ class RemoveIndexAnalyzer(OperationAnalyzer):
class RemoveIndexConcurrentlyAnalyzer(OperationAnalyzer):
- """Analyzer for RemoveIndexConcurrently - safe non-blocking index removal."""
+ """Analyzer for RemoveIndexConcurrently.
+
+ Non-blocking, but NOT idempotent: emits a bare DROP INDEX CONCURRENTLY with
+ no IF EXISTS. After a partial failure the retry loop fails with "index does
+ not exist". ConcurrentIndexIdempotencyPolicy blocks this; the score here
+ keeps the per-operation report consistent.
+ """
operation_type = "RemoveIndexConcurrently"
- default_score = 0
+ default_score = 2
def analyze(self, op) -> OperationRisk:
return OperationRisk(
type=self.operation_type,
- score=0,
- reason="Concurrent index removal is safe (non-blocking)",
+ score=2,
+ reason="RemoveIndexConcurrently is non-idempotent (bare DROP INDEX CONCURRENTLY, no IF EXISTS)",
details={"model": op.model_name if hasattr(op, "model_name") else "unknown"},
+ guidance=f"""Don't use RemoveIndexConcurrently. It emits DROP INDEX CONCURRENTLY with no IF EXISTS, so after a partial failure every bin/migrate retry fails with "index does not exist".
+
+Use RunSQL wrapped in SeparateDatabaseAndState:
+
+ migrations.SeparateDatabaseAndState(
+ state_operations=[migrations.RemoveIndex(...)],
+ database_operations=[migrations.RunSQL(
+ sql="DROP INDEX CONCURRENTLY IF EXISTS my_idx;",
+ reverse_sql="SET lock_timeout = 0; CREATE INDEX CONCURRENTLY IF NOT EXISTS my_idx ON my_table (col);",
+ )],
+ )
+
+[See the migration safety guide]({SAFE_MIGRATIONS_DOCS_URL}#adding-indexes)""",
)
diff --git a/posthog/management/migration_analysis/policies.py b/posthog/management/migration_analysis/policies.py
index 6a3f3888f214..ac89f29112d0 100644
--- a/posthog/management/migration_analysis/policies.py
+++ b/posthog/management/migration_analysis/policies.py
@@ -4,6 +4,7 @@ These are team coding guidelines, not database safety issues.
Policies enforce architectural decisions and coding standards.
"""
+import re
from abc import ABC, abstractmethod
# Apps owned by PostHog where policies are enforced
@@ -109,6 +110,9 @@ class AtomicFalsePolicy(MigrationPolicy):
CONCURRENT_OP_TYPES = {
"AddIndexConcurrently",
"RemoveIndexConcurrently",
+ # PostHog helpers (see posthog/migration_helpers/concurrent_index.py)
+ "CreateIndexConcurrently",
+ "DropIndexConcurrently",
}
def check_operation(self, op) -> list[str]:
@@ -242,8 +246,164 @@ class AtomicFalsePolicy(MigrationPolicy):
return False
+class ConcurrentIndexIdempotencyPolicy(MigrationPolicy):
+ """
+ Policy: concurrent index operations must be idempotent.
+
+ Rationale:
+ - bin/migrate re-runs the ENTIRE migration on failure, with exponential
+ backoff, up to MIGRATE_MAX_RETRIES times.
+ - CREATE/DROP INDEX CONCURRENTLY is non-transactional and runs with
+ atomic=False, so a cancelled or interrupted build leaves an INVALID
+ index behind - there is no transaction to roll it back.
+ - Django's AddIndexConcurrently / RemoveIndexConcurrently emit a bare
+ CREATE/DROP INDEX CONCURRENTLY with no IF [NOT] EXISTS and give no way
+ to disable lock_timeout. Deploy runs under a lock_timeout, so a single
+ transient cancellation leaves an invalid index, and every subsequent
+ retry then fails with "relation already exists" (or "does not exist"
+ for drops). The migration is stuck and blocks deploys until the invalid
+ index is cleaned up by hand.
+ - The safe pattern is RunSQL with `SET lock_timeout = 0;` plus
+ `CREATE INDEX CONCURRENTLY IF NOT EXISTS` (and the matching
+ `DROP INDEX CONCURRENTLY IF EXISTS` reverse), wrapped in
+ SeparateDatabaseAndState so Django model state still tracks the index.
+ lock_timeout = 0 stops the build from being cancelled in the first
+ place; IF NOT EXISTS makes the retry idempotent if it is.
+ """
+
+ DJANGO_CONCURRENT_OPS = {"AddIndexConcurrently", "RemoveIndexConcurrently"}
+
+ # The PostHog helpers in posthog/migration_helpers/concurrent_index.py
+ # encode the idempotency guarantees this policy enforces (indisvalid
+ # recovery + IF [NOT] EXISTS + timeout disabling) at the operation
+ # level, so they are explicitly exempt from the static SQL check.
+ POSTHOG_SAFE_HELPER_OPS = {"CreateIndexConcurrently", "DropIndexConcurrently"}
+
+ GUIDANCE = (
+ "Use posthog.migration_helpers.CreateIndexConcurrently (or DropIndexConcurrently),\n"
+ "wrapped in SeparateDatabaseAndState so Django model state still tracks the index:\n"
+ "\n"
+ " from posthog.migration_helpers import CreateIndexConcurrently\n"
+ "\n"
+ " migrations.SeparateDatabaseAndState(\n"
+ " state_operations=[migrations.AddIndex(...)],\n"
+ " database_operations=[CreateIndexConcurrently(\n"
+ ' index_name="my_idx",\n'
+ ' table_name="my_table",\n'
+ ' columns="(col)",\n'
+ " )],\n"
+ " )\n"
+ "\n"
+ "The helper disables lock_timeout and statement_timeout, drops any invalid leftover\n"
+ "index (recovering from a prior interrupted build), then runs CREATE INDEX\n"
+ "CONCURRENTLY IF NOT EXISTS. Raw RunSQL with `SET lock_timeout = 0;\n"
+ "CREATE INDEX CONCURRENTLY IF NOT EXISTS ...` is still accepted as a fallback for\n"
+ "exotic cases, but the helper is the recommended form.\n"
+ "\n"
+ "See https://github.com/PostHog/posthog/blob/master/docs/published/handbook/engineering/safe-django-migrations.md#adding-indexes"
+ )
+
+ def check_operation(self, op) -> list[str]:
+ return [] # Checked at migration level
+
+ def check_migration(self, migration) -> list[str]:
+ if not is_posthog_app(migration.app_label, migration):
+ return []
+
+ violations = []
+ for op in self._iter_executed_operations(migration):
+ violations.extend(self._check_single_operation(op))
+ return violations
+
+ def _iter_executed_operations(self, migration):
+ """Yield operations that emit SQL, descending recursively into
+ SeparateDatabaseAndState.database_operations.
+
+ SDAS can legally nest (a database_operations entry can itself be a
+ SeparateDatabaseAndState); a non-recursive descent would silently skip
+ the inner ops and reopen the incident class. state_operations never
+ touch the database, so they are not descended.
+ """
+ yield from self._descend(migration.operations)
+
+ def _descend(self, ops):
+ for op in ops or []:
+ if op.__class__.__name__ == "SeparateDatabaseAndState":
+ yield from self._descend(getattr(op, "database_operations", []) or [])
+ else:
+ yield op
+
+ def _check_single_operation(self, op) -> list[str]:
+ op_type = op.__class__.__name__
+
+ if op_type in self.POSTHOG_SAFE_HELPER_OPS:
+ # The helpers handle indisvalid recovery + IF [NOT] EXISTS +
+ # timeout disabling internally. Trust the type, skip the SQL
+ # check (which would false-positive on the helper's display SQL).
+ return []
+
+ if op_type in self.DJANGO_CONCURRENT_OPS:
+ return [
+ f"❌ BLOCKED: {op_type} emits a non-idempotent CREATE/DROP INDEX CONCURRENTLY "
+ "and cannot disable lock_timeout. A single transient lock_timeout cancellation "
+ "during deploy leaves an INVALID index; bin/migrate then re-runs the migration "
+ 'and every retry fails with "relation already exists" - a stuck migration that '
+ f"blocks deploys.\n{self.GUIDANCE}"
+ ]
+
+ if op_type == "RunSQL":
+ return self._check_runsql(op)
+
+ return []
+
+ def _check_runsql(self, op) -> list[str]:
+ # Both forward `sql` and `reverse_sql` flow through bin/migrate's retry
+ # loop (rollbacks rerun on failure too), so a non-idempotent reverse
+ # reopens the same stuck-migration class as a non-idempotent forward.
+ violations = []
+ violations.extend(self._check_sql(getattr(op, "sql", ""), "sql"))
+ violations.extend(self._check_sql(getattr(op, "reverse_sql", ""), "reverse_sql"))
+ return violations
+
+ # Match the specific concurrent-index statement, not the whole RunSQL blob.
+ # Substring checks (`"IF NOT EXISTS" in sql`) false-negative when an unrelated
+ # statement in the same RunSQL legitimately uses IF [NOT] EXISTS (e.g.
+ # `CREATE TABLE IF NOT EXISTS ...; CREATE INDEX CONCURRENTLY idx ...`).
+ _BARE_CREATE_INDEX_CONCURRENTLY = re.compile(
+ r"CREATE\s+(?:UNIQUE\s+)?INDEX\s+CONCURRENTLY\b(?!\s+IF\s+NOT\s+EXISTS\b)",
+ re.IGNORECASE,
+ )
+ _BARE_DROP_INDEX_CONCURRENTLY = re.compile(
+ r"DROP\s+INDEX\s+CONCURRENTLY\b(?!\s+IF\s+EXISTS\b)",
+ re.IGNORECASE,
+ )
+
+ def _check_sql(self, sql, attr_name: str) -> list[str]:
+ sql = str(sql)
+ # Strip /* */, -- and # comments so keywords inside comments don't match
+ sql = re.sub(r"/\*.*?\*/", "", sql, flags=re.S)
+ sql = re.sub(r"--[^\n]*", "", sql)
+ sql = re.sub(r"#[^\n]*", "", sql)
+
+ violations = []
+ if self._BARE_CREATE_INDEX_CONCURRENTLY.search(sql):
+ violations.append(
+ f"❌ BLOCKED: RunSQL {attr_name} CREATE INDEX CONCURRENTLY is missing IF NOT EXISTS, "
+ "so it is non-idempotent. A cancelled build leaves an INVALID index and every "
+ f'bin/migrate retry then fails with "relation already exists".\n{self.GUIDANCE}'
+ )
+ if self._BARE_DROP_INDEX_CONCURRENTLY.search(sql):
+ violations.append(
+ f"❌ BLOCKED: RunSQL {attr_name} DROP INDEX CONCURRENTLY is missing IF EXISTS, "
+ "so it is non-idempotent. After a partial failure every bin/migrate retry then "
+ f'fails with "index does not exist".\n{self.GUIDANCE}'
+ )
+ return violations
+
+
# Registry of all PostHog policies
POSTHOG_POLICIES = [
UUIDPrimaryKeyPolicy(),
AtomicFalsePolicy(),
+ ConcurrentIndexIdempotencyPolicy(),
]
diff --git a/posthog/management/migration_analysis/test/test_risk_analyzer.py b/posthog/management/migration_analysis/test/test_risk_analyzer.py
index 527449ec096a..f5039a236cf1 100644
--- a/posthog/management/migration_analysis/test/test_risk_analyzer.py
+++ b/posthog/management/migration_analysis/test/test_risk_analyzer.py
@@ -2,8 +2,11 @@ from unittest.mock import MagicMock
from django.db import migrations, models
+from parameterized import parameterized
+
from posthog.management.migration_analysis.analyzer import RiskAnalyzer
from posthog.management.migration_analysis.models import RiskLevel
+from posthog.management.migration_analysis.policies import ConcurrentIndexIdempotencyPolicy
def create_mock_operation(op_class, **kwargs):
@@ -1656,7 +1659,11 @@ class TestAtomicFalsePolicy:
assert any("atomic=False" in v for v in migration_risk.policy_violations)
def test_atomic_false_with_add_index_concurrently_ok(self):
- """atomic=False with AddIndexConcurrently is correct - no warning"""
+ """AtomicFalsePolicy does not flag AddIndexConcurrently with atomic=False.
+
+ Idempotency of AddIndexConcurrently is a separate concern enforced by
+ ConcurrentIndexIdempotencyPolicy (see TestConcurrentIndexIdempotencyPolicy).
+ """
mock_migration = MagicMock()
mock_migration.atomic = False
mock_migration.app_label = "posthog"
@@ -1669,10 +1676,12 @@ class TestAtomicFalsePolicy:
migration_risk = self.analyzer.analyze_migration(mock_migration, "posthog/migrations/0001_test.py")
- # Should not have atomic-related warnings
+ # AtomicFalsePolicy is satisfied (concurrent op with atomic=False)
assert not any("atomic=False" in v for v in migration_risk.policy_violations)
# Should recognize the operation (not "Unknown")
assert not any("Unknown" in r.reason for r in migration_risk.operations)
+ # ConcurrentIndexIdempotencyPolicy still blocks the non-idempotent op
+ assert any("non-idempotent" in v for v in migration_risk.policy_violations)
def test_atomic_true_with_concurrent_blocked(self):
"""CONCURRENTLY without atomic=False should be BLOCKED (will fail at runtime)"""
@@ -1692,7 +1701,11 @@ class TestAtomicFalsePolicy:
assert any("atomic=False" in v for v in migration_risk.policy_violations)
def test_atomic_false_with_runsql_concurrently_ok(self):
- """atomic=False with RunSQL CONCURRENTLY is correct - no warning"""
+ """AtomicFalsePolicy does not flag RunSQL CONCURRENTLY with atomic=False.
+
+ This SQL is missing IF NOT EXISTS, so ConcurrentIndexIdempotencyPolicy
+ blocks it separately (see TestConcurrentIndexIdempotencyPolicy).
+ """
mock_migration = MagicMock()
mock_migration.atomic = False
mock_migration.app_label = "posthog"
@@ -1703,8 +1716,10 @@ class TestAtomicFalsePolicy:
migration_risk = self.analyzer.analyze_migration(mock_migration, "posthog/migrations/0001_test.py")
- # Should not have atomic-related warnings
+ # AtomicFalsePolicy is satisfied (concurrent op with atomic=False)
assert not any("atomic=False" in v for v in migration_risk.policy_violations)
+ # ConcurrentIndexIdempotencyPolicy blocks the missing IF NOT EXISTS
+ assert any("non-idempotent" in v for v in migration_risk.policy_violations)
def test_atomic_true_with_runsql_concurrently_blocked(self):
"""RunSQL with CONCURRENTLY without atomic=False should be BLOCKED"""
@@ -1816,3 +1831,236 @@ class TestAtomicFalsePolicy:
# Product app should trigger policy checks - atomic=False without CONCURRENTLY warns
assert any("atomic=False" in v for v in migration_risk.policy_violations)
+
+ @parameterized.expand(["CreateIndexConcurrently", "DropIndexConcurrently"])
+ def test_posthog_helpers_recognized_as_concurrent(self, op_name):
+ """The PostHog helpers must register as concurrent ops in
+ CONCURRENT_OP_TYPES, otherwise atomic=False migrations using them
+ would trip the `atomic=False without CONCURRENTLY` warning.
+ """
+ mock_migration = MagicMock()
+ mock_migration.atomic = False
+ mock_migration.app_label = "posthog"
+ mock_migration.name = "0001_test"
+
+ # Plain MagicMock (no spec=) — spec= on a Django operation class
+ # would cause `__class__.__name__ = ...` to mutate the real class
+ # name globally and bleed across tests.
+ op = MagicMock()
+ op.__class__.__name__ = op_name
+ op.sql = 'CREATE INDEX CONCURRENTLY IF NOT EXISTS "idx" ON "t" (c)'
+ op.reverse_sql = 'DROP INDEX CONCURRENTLY IF EXISTS "idx"'
+ mock_migration.operations = [op]
+
+ migration_risk = self.analyzer.analyze_migration(mock_migration, "posthog/migrations/0001_test.py")
+ assert not any("atomic=False" in v for v in migration_risk.policy_violations)
+
+
+class TestConcurrentIndexIdempotencyPolicy:
+ """ConcurrentIndexIdempotencyPolicy blocks non-idempotent concurrent index ops.
+
+ Regression coverage for the deploy-blocking failure where a transient
+ lock_timeout cancellation of a bare CREATE INDEX CONCURRENTLY left an
+ invalid index and every bin/migrate retry then failed with
+ "relation already exists".
+ """
+
+ def setup_method(self):
+ self.analyzer = RiskAnalyzer()
+
+ def _analyze(self, operations, atomic=False, app_label="posthog"):
+ mock_migration = MagicMock()
+ mock_migration.atomic = atomic
+ mock_migration.app_label = app_label
+ mock_migration.name = "0001_test"
+ mock_migration.operations = operations
+ return self.analyzer.analyze_migration(mock_migration, f"{app_label}/migrations/0001_test.py")
+
+ @parameterized.expand(["AddIndexConcurrently", "RemoveIndexConcurrently"])
+ def test_django_concurrent_op_blocked(self, op_name):
+ op = MagicMock()
+ op.__class__.__name__ = op_name
+ risk = self._analyze([op])
+ assert risk.level == RiskLevel.BLOCKED
+ assert any(op_name in v and "non-idempotent" in v for v in risk.policy_violations)
+
+ @parameterized.expand(
+ [
+ ("create_no_if_not_exists", "CREATE INDEX CONCURRENTLY idx_foo ON t (c);"),
+ ("drop_no_if_exists", "DROP INDEX CONCURRENTLY idx_foo;"),
+ ]
+ )
+ def test_runsql_non_idempotent_concurrent_index_blocked(self, _name, sql):
+ op = create_mock_operation(migrations.RunSQL, sql=sql)
+ risk = self._analyze([op])
+ assert risk.level == RiskLevel.BLOCKED
+ assert any("non-idempotent" in v for v in risk.policy_violations)
+
+ @parameterized.expand(
+ [
+ ("create_idempotent", "SET lock_timeout = 0; CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_foo ON t (c);"),
+ ("drop_idempotent", "DROP INDEX CONCURRENTLY IF EXISTS idx_foo;"),
+ ("reindex", "REINDEX INDEX CONCURRENTLY idx_foo;"),
+ ]
+ )
+ def test_runsql_safe_concurrent_index_not_flagged(self, _name, sql):
+ op = create_mock_operation(migrations.RunSQL, sql=sql)
+ risk = self._analyze([op])
+ assert not any("non-idempotent" in v for v in risk.policy_violations)
+
+ def test_safe_pattern_in_separate_database_and_state_not_flagged(self):
+ state_op = create_mock_operation(migrations.AddIndex, model_name="mymodel", index=MagicMock())
+ db_op = create_mock_operation(
+ migrations.RunSQL,
+ sql="SET lock_timeout = 0; CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_foo ON mymodel (c);",
+ )
+ sep = create_mock_operation(
+ migrations.SeparateDatabaseAndState, state_operations=[state_op], database_operations=[db_op]
+ )
+ risk = self._analyze([sep])
+ assert not any("non-idempotent" in v for v in risk.policy_violations)
+
+ def test_non_idempotent_runsql_inside_separate_database_and_state_blocked(self):
+ db_op = create_mock_operation(migrations.RunSQL, sql="CREATE INDEX CONCURRENTLY idx_foo ON mymodel (c);")
+ sep = create_mock_operation(
+ migrations.SeparateDatabaseAndState, state_operations=[], database_operations=[db_op]
+ )
+ risk = self._analyze([sep])
+ assert risk.level == RiskLevel.BLOCKED
+ assert any("non-idempotent" in v for v in risk.policy_violations)
+
+ def test_third_party_app_not_checked(self):
+ op = MagicMock()
+ op.__class__.__name__ = "AddIndexConcurrently"
+ risk = self._analyze([op], app_label="some_third_party_app")
+ assert not any("non-idempotent" in v for v in risk.policy_violations)
+
+ def test_non_idempotent_reverse_sql_blocked(self):
+ """Forward SQL is idempotent but reverse_sql is bare DROP. Rollback runs through the same retry loop, so a non-idempotent reverse re-opens the stuck-migration class."""
+ op = create_mock_operation(
+ migrations.RunSQL,
+ sql="SET lock_timeout = 0; CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_foo ON t (c);",
+ reverse_sql="DROP INDEX CONCURRENTLY idx_foo;",
+ )
+ risk = self._analyze([op])
+ assert risk.level == RiskLevel.BLOCKED
+ assert any("non-idempotent" in v and "reverse_sql" in v for v in risk.policy_violations)
+
+ def test_non_idempotent_runsql_inside_nested_separate_database_and_state_blocked(self):
+ """SeparateDatabaseAndState can nest; descent must reach inner ops at any depth."""
+ inner_db_op = create_mock_operation(migrations.RunSQL, sql="CREATE INDEX CONCURRENTLY idx_foo ON mymodel (c);")
+ inner_sep = create_mock_operation(
+ migrations.SeparateDatabaseAndState, state_operations=[], database_operations=[inner_db_op]
+ )
+ outer_sep = create_mock_operation(
+ migrations.SeparateDatabaseAndState, state_operations=[], database_operations=[inner_sep]
+ )
+ risk = self._analyze([outer_sep])
+ assert risk.level == RiskLevel.BLOCKED
+ assert any("non-idempotent" in v for v in risk.policy_violations)
+
+ def test_policy_in_isolation_catches_nested_sdas(self):
+ """Calling the policy directly proves it stands on its own, independent of sibling policies firing on the same migration."""
+ inner_db_op = create_mock_operation(migrations.RunSQL, sql="CREATE INDEX CONCURRENTLY idx_foo ON mymodel (c);")
+ inner_sep = create_mock_operation(
+ migrations.SeparateDatabaseAndState, state_operations=[], database_operations=[inner_db_op]
+ )
+ outer_sep = create_mock_operation(
+ migrations.SeparateDatabaseAndState, state_operations=[], database_operations=[inner_sep]
+ )
+ mock_migration = MagicMock()
+ mock_migration.app_label = "posthog"
+ mock_migration.operations = [outer_sep]
+
+ violations = ConcurrentIndexIdempotencyPolicy().check_migration(mock_migration)
+
+ assert any("non-idempotent" in v for v in violations)
+
+ @parameterized.expand(
+ [
+ (
+ "create_table_if_not_exists_hides_bare_create_index",
+ "CREATE TABLE IF NOT EXISTS some_table (a int); CREATE INDEX CONCURRENTLY idx_foo ON t (c);",
+ ),
+ (
+ "drop_table_if_exists_hides_bare_drop_index",
+ "DROP TABLE IF EXISTS old_table; DROP INDEX CONCURRENTLY idx_foo;",
+ ),
+ (
+ "block_comment_if_not_exists_hides_bare_create_index",
+ "/* IF NOT EXISTS */ CREATE INDEX CONCURRENTLY idx_foo ON t (c);",
+ ),
+ (
+ "list_form_mixed_create_table_and_bare_index",
+ [
+ "CREATE TABLE IF NOT EXISTS some_table (a int);",
+ "CREATE INDEX CONCURRENTLY idx_foo ON t (c);",
+ ],
+ ),
+ (
+ "bare_create_unique_index_concurrently",
+ "CREATE UNIQUE INDEX CONCURRENTLY idx_foo ON t (c);",
+ ),
+ ]
+ )
+ def test_substring_collision_no_longer_hides_bare_concurrent_index(self, _name, sql):
+ """Regression: a substring check `"IF NOT EXISTS" in sql` matched unrelated statements
+ in the same RunSQL blob and silently allowed a bare CREATE/DROP INDEX CONCURRENTLY through.
+ Per-statement regex catches the bare index op even when the blob also contains a legitimate
+ `CREATE TABLE IF NOT EXISTS` / `DROP TABLE IF EXISTS` / block comment / list-form sibling.
+ """
+ op = create_mock_operation(migrations.RunSQL, sql=sql)
+ risk = self._analyze([op])
+ assert risk.level == RiskLevel.BLOCKED
+ assert any("non-idempotent" in v for v in risk.policy_violations)
+
+ @parameterized.expand(
+ [
+ (
+ "create_unique_index_with_if_not_exists",
+ "CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS idx_foo ON t (c);",
+ ),
+ (
+ "create_table_if_not_exists_alongside_safe_concurrent_index",
+ "CREATE TABLE IF NOT EXISTS some_table (a int);"
+ " CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_foo ON t (c);",
+ ),
+ (
+ "comment_only_mention_of_bare_concurrently",
+ "-- old form was: CREATE INDEX CONCURRENTLY idx_foo ON t (c);\n"
+ "CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_foo ON t (c);",
+ ),
+ ]
+ )
+ def test_per_statement_regex_does_not_overreach(self, _name, sql):
+ """Don't false-positive on safe SQL that happens to contain a non-CONCURRENTLY DDL or
+ the bare keyword sequence inside a comment.
+ """
+ op = create_mock_operation(migrations.RunSQL, sql=sql)
+ risk = self._analyze([op])
+ assert not any("non-idempotent" in v for v in risk.policy_violations)
+
+ @parameterized.expand(
+ [
+ ("CreateIndexConcurrently",),
+ ("DropIndexConcurrently",),
+ ]
+ )
+ def test_posthog_helper_ops_pass_through(self, op_name):
+ """The PostHog migration helpers encode the idempotency guarantee internally
+ (indisvalid recovery + IF [NOT] EXISTS + timeout disabling), so the static
+ check must not flag them — even though they inherit from RunSQL and their
+ display SQL contains a CONCURRENTLY index statement.
+
+ Plain MagicMock (no spec=) — spec= on a Django operation class would
+ cause `__class__.__name__ = ...` to mutate the real class name globally
+ and bleed across tests.
+ """
+ op = MagicMock()
+ op.__class__.__name__ = op_name
+ # Mirror what the real helpers stash on `sql` for sqlmigrate display:
+ op.sql = 'CREATE INDEX CONCURRENTLY IF NOT EXISTS "idx" ON "t" (c)'
+ op.reverse_sql = 'DROP INDEX CONCURRENTLY IF EXISTS "idx"'
+ risk = self._analyze([op])
+ assert not any("non-idempotent" in v for v in risk.policy_violations)
+ assert risk.level != RiskLevel.BLOCKED
diff --git a/posthog/migration_helpers/__init__.py b/posthog/migration_helpers/__init__.py
new file mode 100644
index 000000000000..03fa20c767df
--- /dev/null
+++ b/posthog/migration_helpers/__init__.py
@@ -0,0 +1,3 @@
+from posthog.migration_helpers.concurrent_index import CreateIndexConcurrently, DropIndexConcurrently
+
+__all__ = ["CreateIndexConcurrently", "DropIndexConcurrently"]
diff --git a/posthog/migration_helpers/concurrent_index.py b/posthog/migration_helpers/concurrent_index.py
new file mode 100644
index 000000000000..d4cacb4ed7dc
--- /dev/null
+++ b/posthog/migration_helpers/concurrent_index.py
@@ -0,0 +1,271 @@
+"""Idempotent CREATE/DROP INDEX CONCURRENTLY operations for Django migrations.
+
+The Django built-ins (`AddIndexConcurrently`, `RemoveIndexConcurrently`) emit
+bare `CREATE/DROP INDEX CONCURRENTLY` with no `IF [NOT] EXISTS`, and there is
+no hook to disable `lock_timeout` / `statement_timeout`. Under bin/migrate's
+exponential-backoff retry loop, a single transient timeout cancellation
+leaves an INVALID index in pg_class and every subsequent retry then fails
+with "relation already exists". Adding `IF NOT EXISTS` is only a partial
+fix — it skips on name collision but does not detect that the leftover
+index is invalid (indisvalid = false), so the migration is marked applied
+while the index quietly does nothing.
+
+These helpers implement the same recovery pattern GitLab uses in
+`add_concurrent_index` / `remove_concurrent_index`:
+
+1. Disable `lock_timeout` and `statement_timeout` on this connection so
+ deploy-time timeouts can't cancel the build.
+2. Look the index up in pg_class/pg_index. If it exists with
+ indisvalid = false, DROP it first — recovering from a prior interrupted
+ build, and emitting a structured log line so the recovery is visible
+ in the deploy log (otherwise the auto-recovery would silently mask
+ repeated cancellations).
+3. Run the CREATE/DROP statement with IF [NOT] EXISTS so retries are safe.
+
+Wrap in SeparateDatabaseAndState so Django state still tracks the index:
+
+ migrations.SeparateDatabaseAndState(
+ state_operations=[migrations.AddIndex(...)],
+ database_operations=[CreateIndexConcurrently(
+ index_name="my_idx",
+ table_name="my_table",
+ columns="(col_a, col_b)",
+ )],
+ )
+
+The Migration class still needs `atomic = False`.
+"""
+
+from django.db import migrations
+
+import structlog
+
+logger = structlog.get_logger(__name__)
+
+
+def _build_create_sql(
+ *,
+ index_name: str,
+ table_name: str,
+ columns: str,
+ unique: bool,
+ using: str,
+ where: str,
+) -> str:
+ unique_kw = "UNIQUE " if unique else ""
+ using_kw = f" USING {using}" if using else ""
+ where_kw = f" {where}" if where else ""
+ return (
+ f'CREATE {unique_kw}INDEX CONCURRENTLY IF NOT EXISTS "{index_name}" '
+ f'ON "{table_name}"{using_kw} {columns}{where_kw}'
+ )
+
+
+def _build_drop_sql(index_name: str) -> str:
+ return f'DROP INDEX CONCURRENTLY IF EXISTS "{index_name}"'
+
+
+class _ConcurrentIndexOp(migrations.RunSQL):
+ """Shared machinery for CREATE/DROP INDEX CONCURRENTLY.
+
+ Inherits from RunSQL so sqlmigrate / introspection still show meaningful
+ SQL; the real apply path is overridden in `database_forwards` /
+ `database_backwards`.
+ """
+
+ reversible = True
+
+ # Set by subclass __init__; read by deconstruct() (so squashmigrations /
+ # the migration writer can rebuild the op) and describe().
+ index_name: str
+ table_name: str
+ columns: str
+ unique: bool
+ using: str
+ where: str
+
+ def deconstruct(self) -> tuple[str, list[object], dict[str, str | bool]]:
+ # RunSQL.deconstruct() emits sql=/reverse_sql= kwargs, which this op's
+ # keyword-only __init__ rejects — so squashmigrations / the migration
+ # writer would fail to rebuild it. Emit the real constructor kwargs.
+ kwargs: dict[str, str | bool] = {
+ "index_name": self.index_name,
+ "table_name": self.table_name,
+ "columns": self.columns,
+ }
+ if self.unique:
+ kwargs["unique"] = True
+ if self.using:
+ kwargs["using"] = self.using
+ if self.where:
+ kwargs["where"] = self.where
+ return (self.__class__.__qualname__, [], kwargs)
+
+ @staticmethod
+ def _disable_timeouts(schema_editor) -> None:
+ schema_editor.execute("SET lock_timeout = 0")
+ schema_editor.execute("SET statement_timeout = 0")
+
+ def _drop_if_invalid(self, schema_editor, index_name: str) -> None:
+ """If `index_name` exists but is invalid, drop it.
+
+ Recovers from a prior CONCURRENTLY build that was cancelled
+ mid-flight (OOM, pod kill, lock_timeout, statement_timeout, etc.).
+ Postgres leaves the row in pg_class with indisvalid = false; a
+ plain `CREATE INDEX CONCURRENTLY IF NOT EXISTS` would silently
+ skip and leave the invalid index in place.
+
+ The recovery is intentionally noisy: a log line plus a migration
+ stdout message, both tagged with the index name. Without this,
+ the auto-recovery would mask repeated cancellations of the same
+ index and we would never know a table has chronic lock contention
+ or memory pressure during builds.
+ """
+ with schema_editor.connection.cursor() as cursor:
+ cursor.execute(
+ """
+ SELECT 1
+ FROM pg_class c
+ JOIN pg_index i ON c.oid = i.indexrelid
+ WHERE c.relname = %s AND NOT i.indisvalid
+ """,
+ [index_name],
+ )
+ if cursor.fetchone() is None:
+ return
+ logger.warning(
+ "concurrent_index_recovering_from_invalid_leftover",
+ index_name=index_name,
+ operation=type(self).__name__,
+ )
+ # Mirror to migration stdout so it shows up in bin/migrate log,
+ # not just the application log stream.
+ print( # noqa: T201
+ f"[{type(self).__name__}] index {index_name!r} was left in an "
+ "invalid state by a prior interrupted build; dropping and "
+ "rebuilding it. If this fires repeatedly for the same index, "
+ "investigate why the prior build was cancelled."
+ )
+ schema_editor.execute(_build_drop_sql(index_name))
+
+
+class CreateIndexConcurrently(_ConcurrentIndexOp):
+ """Idempotent CREATE INDEX CONCURRENTLY with invalid-index recovery.
+
+ Arguments:
+ index_name: name of the index to create. Required (used for the
+ indisvalid check and the IF NOT EXISTS guard).
+ table_name: target table.
+ columns: column expression(s) including the surrounding parens,
+ e.g. `"(team_id, slot_index)"` or `"(lower(email))"`.
+ unique: emit `CREATE UNIQUE INDEX CONCURRENTLY`.
+ using: index method, e.g. `"gin"`. Default is btree.
+ where: partial-index predicate, including the `WHERE` keyword,
+ e.g. `"WHERE deleted_at IS NULL"`. Empty by default.
+ """
+
+ def __init__(
+ self,
+ *,
+ index_name: str,
+ table_name: str,
+ columns: str,
+ unique: bool = False,
+ using: str = "",
+ where: str = "",
+ ) -> None:
+ # All constructor args survive on the instance: index_name/table_name
+ # are read by `_drop_if_invalid` / `describe`, and every arg is needed
+ # by `deconstruct` so squashmigrations can rebuild the op.
+ self.index_name = index_name
+ self.table_name = table_name
+ self.columns = columns
+ self.unique = unique
+ self.using = using
+ self.where = where
+ super().__init__(
+ sql=_build_create_sql(
+ index_name=index_name,
+ table_name=table_name,
+ columns=columns,
+ unique=unique,
+ using=using,
+ where=where,
+ ),
+ reverse_sql=_build_drop_sql(index_name),
+ )
+
+ def database_forwards(self, app_label, schema_editor, from_state, to_state) -> None:
+ self._disable_timeouts(schema_editor)
+ self._drop_if_invalid(schema_editor, self.index_name)
+ schema_editor.execute(self.sql)
+
+ def database_backwards(self, app_label, schema_editor, from_state, to_state) -> None:
+ self._disable_timeouts(schema_editor)
+ schema_editor.execute(self.reverse_sql)
+
+ def describe(self) -> str:
+ return f"Concurrently create index {self.index_name} on {self.table_name}"
+
+
+class DropIndexConcurrently(_ConcurrentIndexOp):
+ """Idempotent DROP INDEX CONCURRENTLY.
+
+ The forward direction has no invalid-leftover failure mode to recover
+ from (DROP either succeeds or the index is missing). The reverse,
+ however, is a CREATE INDEX CONCURRENTLY and needs the full recovery
+ path — the same arguments as `CreateIndexConcurrently` (columns,
+ unique, using, where) are required so the reverse can rebuild the
+ same index shape.
+
+ Arguments:
+ index_name: name of the index to drop.
+ table_name: target table (used for the reverse CREATE).
+ columns: column expression(s) including parens (used for the
+ reverse CREATE).
+ unique / using / where: as in `CreateIndexConcurrently` (used for
+ the reverse CREATE).
+ """
+
+ def __init__(
+ self,
+ *,
+ index_name: str,
+ table_name: str,
+ columns: str,
+ unique: bool = False,
+ using: str = "",
+ where: str = "",
+ ) -> None:
+ # All constructor args survive on the instance: index_name/table_name
+ # are read by `_drop_if_invalid` (on rollback) / `describe`, and every
+ # arg is needed by `deconstruct` so squashmigrations can rebuild the op.
+ self.index_name = index_name
+ self.table_name = table_name
+ self.columns = columns
+ self.unique = unique
+ self.using = using
+ self.where = where
+ super().__init__(
+ sql=_build_drop_sql(index_name),
+ reverse_sql=_build_create_sql(
+ index_name=index_name,
+ table_name=table_name,
+ columns=columns,
+ unique=unique,
+ using=using,
+ where=where,
+ ),
+ )
+
+ def database_forwards(self, app_label, schema_editor, from_state, to_state) -> None:
+ self._disable_timeouts(schema_editor)
+ schema_editor.execute(self.sql)
+
+ def database_backwards(self, app_label, schema_editor, from_state, to_state) -> None:
+ self._disable_timeouts(schema_editor)
+ self._drop_if_invalid(schema_editor, self.index_name)
+ schema_editor.execute(self.reverse_sql)
+
+ def describe(self) -> str:
+ return f"Concurrently drop index {self.index_name} on {self.table_name}"
diff --git a/posthog/migration_helpers/test_concurrent_index.py b/posthog/migration_helpers/test_concurrent_index.py
new file mode 100644
index 000000000000..169174f17154
--- /dev/null
+++ b/posthog/migration_helpers/test_concurrent_index.py
@@ -0,0 +1,221 @@
+"""Functional tests for CreateIndexConcurrently / DropIndexConcurrently.
+
+Each test creates and drops a real table inside the standard test database
+so we can poke pg_index.indisvalid directly and assert the helper's
+recovery path. The table name is unique per test run to avoid colliding
+with anything else in the schema.
+"""
+
+import uuid
+
+import pytest
+
+from django.db import connection, migrations
+
+from posthog.migration_helpers import CreateIndexConcurrently, DropIndexConcurrently
+
+
+def temp_table():
+ """Create a one-off table and drop it on teardown."""
+ name = f"test_cic_{uuid.uuid4().hex[:8]}"
+ with connection.cursor() as cursor:
+ cursor.execute(f'CREATE TABLE "{name}" (id serial primary key, col int)')
+ try:
+ yield name
+ finally:
+ with connection.cursor() as cursor:
+ cursor.execute(f'DROP TABLE IF EXISTS "{name}"')
+
+
+def _apply(op):
+ """Run a migration op forwards against the real connection."""
+ schema_editor = connection.schema_editor(atomic=False)
+ schema_editor.__enter__()
+ try:
+ op.database_forwards("posthog", schema_editor, from_state=None, to_state=None)
+ finally:
+ schema_editor.__exit__(None, None, None)
+
+
+def _index_exists(index_name: str) -> bool:
+ with connection.cursor() as cursor:
+ cursor.execute("SELECT 1 FROM pg_class WHERE relname = %s", [index_name])
+ return cursor.fetchone() is not None
+
+
+def _index_is_valid(index_name: str) -> bool:
+ with connection.cursor() as cursor:
+ cursor.execute(
+ """
+ SELECT i.indisvalid
+ FROM pg_class c
+ JOIN pg_index i ON c.oid = i.indexrelid
+ WHERE c.relname = %s
+ """,
+ [index_name],
+ )
+ row = cursor.fetchone()
+ return bool(row and row[0])
+
+
[email protected]_db(transaction=True)
+def test_create_index_concurrently_creates_index(temp_table):
+ idx_name = f"{temp_table}_col_idx"
+ op = CreateIndexConcurrently(index_name=idx_name, table_name=temp_table, columns="(col)")
+
+ _apply(op)
+
+ assert _index_exists(idx_name)
+ assert _index_is_valid(idx_name)
+
+
[email protected]_db(transaction=True)
+def test_create_index_concurrently_is_idempotent(temp_table):
+ """Second apply must not raise — IF NOT EXISTS skips the existing valid index."""
+ idx_name = f"{temp_table}_col_idx"
+ op = CreateIndexConcurrently(index_name=idx_name, table_name=temp_table, columns="(col)")
+
+ _apply(op)
+ _apply(op)
+
+ assert _index_is_valid(idx_name)
+
+
[email protected]_db(transaction=True)
+def test_create_index_concurrently_recovers_from_invalid_leftover(temp_table, capsys):
+ """Plant an invalid index, then run the helper; it should drop and rebuild.
+
+ Also asserts the recovery is *noisy* — the auto-recovery would otherwise
+ mask repeated cancellations of the same index, so a stdout breadcrumb is
+ a hard requirement, not nice-to-have.
+ """
+ idx_name = f"{temp_table}_col_idx"
+
+ # Fake an interrupted CONCURRENTLY build by inserting an invalid index row.
+ # Postgres only lets you do this via CREATE INDEX with a deliberately
+ # poisoned predicate that fails after the catalog row is laid down — the
+ # cleanest portable way is to mark a freshly-built index invalid by hand.
+ with connection.cursor() as cursor:
+ cursor.execute(f'CREATE INDEX "{idx_name}" ON "{temp_table}" (col)')
+ cursor.execute(
+ """
+ UPDATE pg_index SET indisvalid = false
+ WHERE indexrelid = (SELECT oid FROM pg_class WHERE relname = %s)
+ """,
+ [idx_name],
+ )
+
+ assert _index_exists(idx_name)
+ assert not _index_is_valid(idx_name)
+
+ op = CreateIndexConcurrently(index_name=idx_name, table_name=temp_table, columns="(col)")
+ _apply(op)
+
+ assert _index_exists(idx_name)
+ assert _index_is_valid(idx_name)
+
+ captured = capsys.readouterr()
+ assert "invalid state by a prior interrupted build" in captured.out
+ assert idx_name in captured.out
+
+
[email protected]_db(transaction=True)
+def test_no_recovery_breadcrumb_when_no_invalid_leftover(temp_table, capsys):
+ """Conversely, a clean first-time apply must NOT print the recovery
+ breadcrumb. We only want noise when something was actually recovered.
+ """
+ idx_name = f"{temp_table}_col_idx"
+ op = CreateIndexConcurrently(index_name=idx_name, table_name=temp_table, columns="(col)")
+ _apply(op)
+
+ captured = capsys.readouterr()
+ assert "invalid state by a prior interrupted build" not in captured.out
+
+
[email protected]_db(transaction=True)
+def test_create_index_concurrently_unique_partial_with_using(temp_table):
+ idx_name = f"{temp_table}_uniq_idx"
+ op = CreateIndexConcurrently(
+ index_name=idx_name,
+ table_name=temp_table,
+ columns="(col)",
+ unique=True,
+ using="btree",
+ where="WHERE col IS NOT NULL",
+ )
+
+ _apply(op)
+
+ assert _index_is_valid(idx_name)
+ with connection.cursor() as cursor:
+ cursor.execute(
+ "SELECT indexdef FROM pg_indexes WHERE indexname = %s",
+ [idx_name],
+ )
+ indexdef = cursor.fetchone()[0]
+ assert "UNIQUE" in indexdef
+ assert "WHERE" in indexdef
+
+
[email protected]_db(transaction=True)
+def test_drop_index_concurrently_removes_index(temp_table):
+ idx_name = f"{temp_table}_col_idx"
+ with connection.cursor() as cursor:
+ cursor.execute(f'CREATE INDEX "{idx_name}" ON "{temp_table}" (col)')
+ assert _index_exists(idx_name)
+
+ op = DropIndexConcurrently(index_name=idx_name, table_name=temp_table, columns="(col)")
+ _apply(op)
+
+ assert not _index_exists(idx_name)
+
+
[email protected]_db(transaction=True)
+def test_drop_index_concurrently_is_idempotent(temp_table):
+ """Running drop when the index is already gone must not raise."""
+ idx_name = f"{temp_table}_col_idx"
+ op = DropIndexConcurrently(index_name=idx_name, table_name=temp_table, columns="(col)")
+
+ _apply(op) # nothing to drop the first time
+ _apply(op) # still nothing the second time
+
+ assert not _index_exists(idx_name)
+
+
[email protected]_db(transaction=True)
+def test_subclasses_runsql_for_introspection_compatibility():
+ """Subclasses must remain RunSQL so makemigrations / sqlmigrate continue to work."""
+ op = CreateIndexConcurrently(index_name="x", table_name="y", columns="(z)")
+ assert isinstance(op, migrations.RunSQL)
+ # RunSQL types sql/reverse_sql as str | Sequence | None; the helper always
+ # builds plain strings, so narrow before the membership checks.
+ assert isinstance(op.sql, str)
+ assert isinstance(op.reverse_sql, str)
+ assert "CREATE INDEX CONCURRENTLY" in op.sql
+ assert "IF NOT EXISTS" in op.sql
+ assert "DROP INDEX CONCURRENTLY" in op.reverse_sql
+ assert "IF EXISTS" in op.reverse_sql
+
+
[email protected]("op_cls", [CreateIndexConcurrently, DropIndexConcurrently])
+ "extra_kwargs",
+ [
+ {},
+ {"unique": True, "using": "btree", "where": "WHERE col_a IS NOT NULL"},
+ ],
+)
+def test_deconstruct_round_trips(op_cls, extra_kwargs):
+ # RunSQL.deconstruct() emits sql=/reverse_sql=, which the helper __init__
+ # rejects; the override must emit kwargs that rebuild an equivalent op so
+ # squashmigrations / the migration writer work.
+ op = op_cls(index_name="my_idx", table_name="my_table", columns="(col_a)", **extra_kwargs)
+
+ name, args, kwargs = op.deconstruct()
+
+ assert name == op_cls.__name__
+ assert args == []
+ rebuilt = op_cls(**kwargs)
+ assert rebuilt.sql == op.sql
+ assert rebuilt.reverse_sql == op.reverse_sql