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.

feat(devex): add migration helpers for indexes and constraints (#64207)

Julian Bez5720674c6593
diff --git a/.agents/skills/django-migrations/SKILL.md b/.agents/skills/django-migrations/SKILL.md
index 3a30873b418f..c79b17e382b3 100644
--- a/.agents/skills/django-migrations/SKILL.md
+++ b/.agents/skills/django-migrations/SKILL.md
@@ -22,6 +22,16 @@ If the task is a ClickHouse migration, use `clickhouse-migrations` instead.
3. **Apply safety rules** from `safe-django-migrations.md` — the doc covers multi-phase rollouts, `SeparateDatabaseAndState`, concurrent operations, idempotency, and all risky patterns in detail.
4. **Validate**: `./manage.py sqlmigrate <app> <migration_number>`, run tests, confirm linear migration sequence.
+## Use the migration helpers
+
+`posthog.migration_helpers` has drop-in operations for the risky-but-common cases. Reach for these first; they track Django state, disable timeouts, and are idempotent under `bin/migrate` retries:
+
+- **Add/drop an index** → `SafeAddIndexConcurrently` / `SafeRemoveIndexConcurrently` (`model_name` + `models.Index`). Never use Django's `AddIndexConcurrently` — CI blocks it.
+- **Add a CHECK constraint** → `AddConstraintNotValid` then `ValidateConstraint` in a later migration (or same migration with `atomic = False`).
+- **Index expressed only as raw SQL** (no Django `Index`) → `CreateIndexConcurrently` / `DropIndexConcurrently` wrapped in `SeparateDatabaseAndState`.
+
+All concurrent-index ops require `atomic = False`.
+
## Hot table hazard
`posthog_team`, `posthog_user`, `posthog_organization`, and `posthog_project` are read on virtually every request. Any `ALTER TABLE` on them — including a plain nullable `AddField`, which is "safe" everywhere else — needs an `ACCESS EXCLUSIVE` lock, and while that lock request waits behind in-flight queries, every later query on the table queues behind it. Even a metadata-only `ADD COLUMN` can stall site-wide traffic in waves (one per `bin/migrate` retry) until the ALTER wins the lock race. This has caused production 5xx incidents.
@@ -29,7 +39,7 @@ If the task is a ClickHouse migration, use `clickhouse-migrations` instead.
Before writing a migration that touches one of these models:
- For `Team`: put domain-specific fields on a Team extension model instead — `posthog/models/team/README.md`. That's a `CREATE TABLE`, no lock on `posthog_team`.
-- `CREATE INDEX CONCURRENTLY` (via `CreateIndexConcurrently`) is fine — `SHARE UPDATE EXCLUSIVE` doesn't block reads or writes.
+- `CREATE INDEX CONCURRENTLY` (via `SafeAddIndexConcurrently`) is fine — `SHARE UPDATE EXCLUSIVE` doesn't block reads or writes.
- If the field genuinely belongs on the hot table (core identity, cross-product settings, SDK config), the `HotTableAlterPolicy` analyzer blocks the migration in CI until `<app_label>.<migration_name>` is added to `posthog/management/migration_analysis/hot_table_acknowledged_migrations.txt`. That acknowledgment also means coordinating the deploy with infra for a low-traffic window.
## Cross-language `NOT NULL` hazard
diff --git a/docs/published/handbook/engineering/safe-django-migrations.md b/docs/published/handbook/engineering/safe-django-migrations.md
index 664fddf0dfea..1a7ce9c9364b 100644
--- a/docs/published/handbook/engineering/safe-django-migrations.md
+++ b/docs/published/handbook/engineering/safe-django-migrations.md
@@ -34,7 +34,7 @@ This is not theoretical: a plain nullable `AddField` on `Team` — exactly what
For `Team`, most new fields shouldn't be on the table at all. Domain-specific fields belong on a **Team extension model** (see `posthog/models/team/README.md`) — that's a `CREATE TABLE`, which takes no lock on `posthog_team` whatsoever.
-`CREATE INDEX CONCURRENTLY` (via `CreateIndexConcurrently`, see [Adding Indexes](#adding-indexes)) is also fine: it only takes `SHARE UPDATE EXCLUSIVE`, which doesn't block reads or writes.
+`CREATE INDEX CONCURRENTLY` (via `SafeAddIndexConcurrently`, see [Adding Indexes](#adding-indexes)) is also fine: it only takes `SHARE UPDATE EXCLUSIVE`, which doesn't block reads or writes.
### If You Genuinely Must Alter a Hot Table
@@ -343,16 +343,37 @@ analyzer blocks any migration that uses `AddIndexConcurrently`,
`RemoveIndexConcurrently`, or a raw `RunSQL` concurrent index without
`IF [NOT] EXISTS`.
-### Safe Approach: `CreateIndexConcurrently` Helper (Recommended)
+### Safe Approach: `SafeAddIndexConcurrently` 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`.
+**Adding an index? Use `SafeAddIndexConcurrently`.**
+It takes a `model_name` + Django `Index` (like Django's `AddIndexConcurrently`), tracks state itself — no `SeparateDatabaseAndState`, no re-spelling the index as raw SQL — and adds the safety the bare Django op lacks: disables `lock_timeout`/`statement_timeout`, skips an already-valid index, and rebuilds an `indisvalid = false` leftover from an interrupted build.
-Wrap it in `SeparateDatabaseAndState` so Django model state still tracks the
-index (keeps `makemigrations --check` and the ORM correct):
+```python
+from django.db import migrations, models
+
+from posthog.migration_helpers import SafeAddIndexConcurrently
+
+
+class Migration(migrations.Migration):
+ atomic = False # Required for CONCURRENTLY
+
+ operations = [
+ SafeAddIndexConcurrently(
+ model_name="mymodel",
+ index=models.Index(fields=["field_name"], name="mymodel_field_idx"),
+ ),
+ ]
+```
+
+Dropping an index uses the mirror helper, `SafeRemoveIndexConcurrently`
+(`model_name` + index `name`).
+
+### Raw-SQL variant: `CreateIndexConcurrently` / `DropIndexConcurrently`
+
+When the index doesn't map cleanly to a Django `Index` (e.g. an expression
+the ORM can't model), use the raw-SQL helpers. They subclass `RunSQL`, which
+doesn't touch Django state, so they must be wrapped in
+`SeparateDatabaseAndState` with a matching `AddIndex` / `RemoveIndex`:
```python
from django.db import migrations, models
@@ -382,9 +403,6 @@ class Migration(migrations.Migration):
]
```
-Dropping an index uses the mirror helper, `DropIndexConcurrently`, with
-`RemoveIndex` in `state_operations`.
-
### Fallback: Raw `RunSQL` + `lock_timeout = 0` + `IF NOT EXISTS`
For exotic cases the helper doesn't cover (partitioned tables, custom
@@ -412,9 +430,9 @@ helper.
### Key Points
- **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
+- **Prefer `SafeAddIndexConcurrently` / `SafeRemoveIndexConcurrently` from `posthog.migration_helpers`** — they take a `model_name` + Index, track Django state themselves (no `SeparateDatabaseAndState`), disable both timeouts, and recover from invalid leftover indexes
+- Use the raw-SQL `CreateIndexConcurrently` / `DropIndexConcurrently` (wrapped in `SeparateDatabaseAndState`) only when the index doesn't map to a Django `Index`
+- Raw `RunSQL` with `SET lock_timeout = 0; SET statement_timeout = 0; CREATE INDEX CONCURRENTLY IF NOT EXISTS ...` is acceptable as a last-resort fallback but does not recover from invalid leftovers
- 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
@@ -431,44 +449,45 @@ helper.
### Safe Approach: NOT VALID Pattern
-Add constraints in two phases - add without validation, then validate separately.
+Add CHECK constraints in two phases — add without validation, then validate separately — using the `posthog.migration_helpers` helpers.
+They take a `model_name` + Django constraint (so Django builds the SQL and tracks model state, no `SeparateDatabaseAndState` and no hand-written SQL), and both phases are idempotent under `bin/migrate` retries (the add skips if the constraint exists, the validate skips if it's already validated).
-**Example: CHECK Constraint**
-
-**Step 1: Add constraint with NOT VALID**
+**Step 1: Add the constraint with NOT VALID** — brief lock, no table scan, enforces new/changed rows only.
```python
+from django.db import migrations, models
+from django.db.models import Q
+
+from posthog.migration_helpers import AddConstraintNotValid
+
+
class Migration(migrations.Migration):
operations = [
- migrations.RunSQL(
- sql="""
- ALTER TABLE mymodel
- ADD CONSTRAINT mymodel_field_check
- CHECK (field_value > 0)
- NOT VALID
- """,
- reverse_sql="ALTER TABLE mymodel DROP CONSTRAINT mymodel_field_check",
+ AddConstraintNotValid(
+ model_name="mymodel",
+ constraint=models.CheckConstraint(condition=Q(field_value__gt=0), name="mymodel_field_check"),
),
]
```
-This adds the constraint but only validates NEW rows (instant operation).
-
-**Step 2: Validate constraint in separate migration**
+**Step 2: Validate the constraint in a separate migration** — scans existing rows under `SHARE UPDATE EXCLUSIVE` (allows normal reads/writes).
```python
+from django.db import migrations
+
+from posthog.migration_helpers import ValidateConstraint
+
+
class Migration(migrations.Migration):
operations = [
- migrations.RunSQL(
- sql="ALTER TABLE mymodel VALIDATE CONSTRAINT mymodel_field_check",
- reverse_sql=migrations.RunSQL.noop,
- ),
+ ValidateConstraint(model_name="mymodel", name="mymodel_field_check"),
]
```
-Deploy this separately. Validation scans the table but uses `SHARE UPDATE EXCLUSIVE` lock which allows normal reads and writes but blocks other schema changes on that table.
+Keep the two phases in **separate migrations** (so the add's brief `ACCESS EXCLUSIVE` lock isn't held through the validate scan), or in the same migration with `atomic = False`.
+If validation fails, Django marks the migration unapplied — clean the offending rows and re-run.
-**Note:** This pattern applies to `FOREIGN KEY` constraints on existing columns. New nullable FK columns don't need it - the column starts empty, so there's nothing to validate.
+**Note:** The same NOT VALID / VALIDATE pattern applies to `FOREIGN KEY` constraints on existing columns; there's no helper for that yet, so hand-write the `RunSQL` (`ADD CONSTRAINT ... FOREIGN KEY ... NOT VALID` then `VALIDATE CONSTRAINT`). New nullable FK columns don't need it — the column starts empty, so there's nothing to validate.
### Key Points
diff --git a/posthog/management/migration_analysis/analyzer.py b/posthog/management/migration_analysis/analyzer.py
index 9f15cfdd8743..baa37cc931f5 100644
--- a/posthog/management/migration_analysis/analyzer.py
+++ b/posthog/management/migration_analysis/analyzer.py
@@ -3,6 +3,7 @@
from posthog.management.migration_analysis.models import MigrationRisk, OperationRisk
from posthog.management.migration_analysis.operations import (
AddConstraintAnalyzer,
+ AddConstraintNotValidAnalyzer,
AddFieldAnalyzer,
AddIndexAnalyzer,
AddIndexConcurrentlyAnalyzer,
@@ -10,8 +11,10 @@ from posthog.management.migration_analysis.operations import (
AlterIndexTogetherAnalyzer,
AlterModelTableAnalyzer,
AlterUniqueTogetherAnalyzer,
+ CreateIndexConcurrentlyAnalyzer,
CreateModelAnalyzer,
DeleteModelAnalyzer,
+ DropIndexConcurrentlyAnalyzer,
RemoveFieldAnalyzer,
RemoveIndexAnalyzer,
RemoveIndexConcurrentlyAnalyzer,
@@ -19,7 +22,10 @@ from posthog.management.migration_analysis.operations import (
RenameModelAnalyzer,
RunPythonAnalyzer,
RunSQLAnalyzer,
+ SafeAddIndexConcurrentlyAnalyzer,
+ SafeRemoveIndexConcurrentlyAnalyzer,
SeparateDatabaseAndStateAnalyzer,
+ ValidateConstraintAnalyzer,
is_unmanaged_model,
)
from posthog.management.migration_analysis.policies import POSTHOG_POLICIES
@@ -55,6 +61,13 @@ class RiskAnalyzer:
"AlterIndexTogether": AlterIndexTogetherAnalyzer(),
"RemoveIndex": RemoveIndexAnalyzer(),
"RemoveIndexConcurrently": RemoveIndexConcurrentlyAnalyzer(),
+ # PostHog migration helpers (posthog/migration_helpers/concurrent_index.py)
+ "CreateIndexConcurrently": CreateIndexConcurrentlyAnalyzer(),
+ "DropIndexConcurrently": DropIndexConcurrentlyAnalyzer(),
+ "SafeAddIndexConcurrently": SafeAddIndexConcurrentlyAnalyzer(),
+ "SafeRemoveIndexConcurrently": SafeRemoveIndexConcurrentlyAnalyzer(),
+ "AddConstraintNotValid": AddConstraintNotValidAnalyzer(),
+ "ValidateConstraint": ValidateConstraintAnalyzer(),
"SeparateDatabaseAndState": SeparateDatabaseAndStateAnalyzer(),
}
diff --git a/posthog/management/migration_analysis/operations.py b/posthog/management/migration_analysis/operations.py
index b8d4e0f89b9e..617e8c502cd8 100644
--- a/posthog/management/migration_analysis/operations.py
+++ b/posthog/management/migration_analysis/operations.py
@@ -429,9 +429,11 @@ class AddConstraintAnalyzer(OperationAnalyzer):
score=3,
reason="Adding constraint may lock table (use NOT VALID pattern)",
details={"model": model_name},
- guidance=f"""Add constraints in 2 phases without locking:
-1. Add constraint with NOT VALID (instant, validates new rows only)
-2. Validate constraint in separate migration (scans table with non-blocking lock)
+ guidance=f"""Add constraints in 2 phases without locking, using the PostHog helpers:
+1. AddConstraintNotValid (instant, validates new rows only, no table scan)
+2. ValidateConstraint in a separate migration (scans table with non-blocking lock)
+
+ from posthog.migration_helpers import AddConstraintNotValid, ValidateConstraint
[See the migration safety guide]({SAFE_MIGRATIONS_DOCS_URL}#adding-constraints)""",
)
@@ -901,6 +903,90 @@ Use RunSQL wrapped in SeparateDatabaseAndState:
)
+class _SafeConcurrentIndexAnalyzer(OperationAnalyzer):
+ """Base for the PostHog concurrent-index helpers.
+
+ All four (the raw-SQL CreateIndexConcurrently / DropIndexConcurrently and
+ the state-aware SafeAddIndexConcurrently / SafeRemoveIndexConcurrently)
+ encode the guarantees ConcurrentIndexIdempotencyPolicy enforces - timeout
+ disabling, invalid-leftover recovery, and skip-if-already-applied - so they
+ are safe by construction. Scoring them SAFE (vs the default "unknown
+ operation" needs-review fallback) keeps the per-operation report honest
+ about the recommended path.
+ """
+
+ default_score = 1
+ safe_reason = "PostHog concurrent-index helper: idempotent (timeout disabling + invalid-leftover recovery)"
+
+ @staticmethod
+ def _index_name(op) -> str | None:
+ index = getattr(op, "index", None)
+ return getattr(index, "name", None) or getattr(op, "index_name", None) or getattr(op, "name", None)
+
+ def analyze(self, op) -> OperationRisk:
+ return OperationRisk(
+ type=self.operation_type,
+ score=self.default_score,
+ reason=self.safe_reason,
+ details={"model": getattr(op, "model_name", None), "index": self._index_name(op)},
+ )
+
+
+class CreateIndexConcurrentlyAnalyzer(_SafeConcurrentIndexAnalyzer):
+ operation_type = "CreateIndexConcurrently"
+
+
+class DropIndexConcurrentlyAnalyzer(_SafeConcurrentIndexAnalyzer):
+ operation_type = "DropIndexConcurrently"
+
+
+class SafeAddIndexConcurrentlyAnalyzer(_SafeConcurrentIndexAnalyzer):
+ operation_type = "SafeAddIndexConcurrently"
+
+
+class SafeRemoveIndexConcurrentlyAnalyzer(_SafeConcurrentIndexAnalyzer):
+ operation_type = "SafeRemoveIndexConcurrently"
+
+
+class AddConstraintNotValidAnalyzer(OperationAnalyzer):
+ """Phase 1 of the NOT VALID pattern - mirrors the score the RunSQL analyzer
+ gives a hand-written `ADD CONSTRAINT ... NOT VALID` (safe: brief lock, no
+ table scan). Follow up with ValidateConstraint.
+ """
+
+ operation_type = "AddConstraintNotValid"
+ default_score = 1
+
+ def analyze(self, op) -> OperationRisk:
+ constraint = getattr(op, "constraint", None)
+ return OperationRisk(
+ type=self.operation_type,
+ score=1,
+ reason="ADD CONSTRAINT ... NOT VALID is safe (validates new rows only, no table scan)",
+ details={"model": getattr(op, "model_name", None), "constraint": getattr(constraint, "name", None)},
+ guidance="Follow up with ValidateConstraint in a later migration to check existing rows.",
+ )
+
+
+class ValidateConstraintAnalyzer(OperationAnalyzer):
+ """Phase 2 of the NOT VALID pattern - mirrors the score the RunSQL analyzer
+ gives a hand-written `VALIDATE CONSTRAINT` (slow on large tables but
+ non-blocking: SHARE UPDATE EXCLUSIVE allows reads and writes).
+ """
+
+ operation_type = "ValidateConstraint"
+ default_score = 2
+
+ def analyze(self, op) -> OperationRisk:
+ return OperationRisk(
+ type=self.operation_type,
+ score=2,
+ reason="VALIDATE CONSTRAINT can be slow but non-blocking (allows reads/writes)",
+ details={"model": getattr(op, "model_name", None), "constraint": getattr(op, "name", None)},
+ guidance="Long-running on large tables but uses SHARE UPDATE EXCLUSIVE lock (allows normal operations).",
+ )
+
+
class SeparateDatabaseAndStateAnalyzer(OperationAnalyzer):
operation_type = "SeparateDatabaseAndState"
default_score = 0
diff --git a/posthog/management/migration_analysis/policies.py b/posthog/management/migration_analysis/policies.py
index cab7571c897b..b19ba64ec105 100644
--- a/posthog/management/migration_analysis/policies.py
+++ b/posthog/management/migration_analysis/policies.py
@@ -114,6 +114,8 @@ class AtomicFalsePolicy(MigrationPolicy):
# PostHog helpers (see posthog/migration_helpers/concurrent_index.py)
"CreateIndexConcurrently",
"DropIndexConcurrently",
+ "SafeAddIndexConcurrently",
+ "SafeRemoveIndexConcurrently",
}
def check_operation(self, op) -> list[str]:
@@ -278,28 +280,31 @@ class ConcurrentIndexIdempotencyPolicy(MigrationPolicy):
# 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"}
+ POSTHOG_SAFE_HELPER_OPS = {
+ "CreateIndexConcurrently",
+ "DropIndexConcurrently",
+ "SafeAddIndexConcurrently",
+ "SafeRemoveIndexConcurrently",
+ }
GUIDANCE = (
- "Use posthog.migration_helpers.CreateIndexConcurrently (or DropIndexConcurrently),\n"
- "wrapped in SeparateDatabaseAndState so Django model state still tracks the index:\n"
+ "Use posthog.migration_helpers.SafeAddIndexConcurrently (or\n"
+ "SafeRemoveIndexConcurrently). It takes a model_name + Index like Django's\n"
+ "AddIndexConcurrently, tracks Django state itself (no SeparateDatabaseAndState),\n"
+ "disables lock_timeout/statement_timeout, skips if a valid index already exists,\n"
+ "and rebuilds an invalid leftover from a prior interrupted build:\n"
"\n"
- " from posthog.migration_helpers import CreateIndexConcurrently\n"
+ " from posthog.migration_helpers import SafeAddIndexConcurrently\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"
+ " SafeAddIndexConcurrently(\n"
+ ' model_name="mymodel",\n'
+ ' index=models.Index(fields=["field_name"], name="my_idx"),\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"
+ "If the index doesn't map to a Django Index, use CreateIndexConcurrently\n"
+ "(raw SQL) wrapped in SeparateDatabaseAndState with a matching AddIndex. Raw\n"
+ "RunSQL with `SET lock_timeout = 0; CREATE INDEX CONCURRENTLY IF NOT EXISTS ...`\n"
+ "is still accepted as a last-resort fallback.\n"
"\n"
"See https://github.com/PostHog/posthog/blob/master/docs/published/handbook/engineering/safe-django-migrations.md#adding-indexes"
)
@@ -436,6 +441,10 @@ class HotTableAlterPolicy(MigrationPolicy):
"RemoveConstraint",
"AddIndex",
"RemoveIndex",
+ # ADD CONSTRAINT ... NOT VALID still takes a brief ACCESS EXCLUSIVE lock,
+ # so the helper is gated like a plain AddConstraint. (ValidateConstraint
+ # is not listed - VALIDATE takes only SHARE UPDATE EXCLUSIVE.)
+ "AddConstraintNotValid",
}
# Op types that carry the target model in `name`
MODEL_LEVEL_OPS = {
diff --git a/posthog/management/migration_analysis/test/test_risk_analyzer.py b/posthog/management/migration_analysis/test/test_risk_analyzer.py
index eb716bbf02cb..53a4befc16c7 100644
--- a/posthog/management/migration_analysis/test/test_risk_analyzer.py
+++ b/posthog/management/migration_analysis/test/test_risk_analyzer.py
@@ -7,6 +7,12 @@ 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, HotTableAlterPolicy
+from posthog.migration_helpers import (
+ AddConstraintNotValid,
+ SafeAddIndexConcurrently,
+ SafeRemoveIndexConcurrently,
+ ValidateConstraint,
+)
def create_mock_operation(op_class, **kwargs):
@@ -484,6 +490,27 @@ class TestRunSQLOperations:
assert risk.level == RiskLevel.NEEDS_REVIEW
assert "validate" in risk.reason.lower()
+ def test_add_constraint_not_valid_helper_scores_safe(self):
+ """The helper scores like the hand-written ADD CONSTRAINT ... NOT VALID (safe)."""
+ op = AddConstraintNotValid(
+ model_name="dashboard",
+ constraint=models.CheckConstraint(condition=models.Q(amount__gte=0), name="dash_amount_chk"),
+ )
+
+ risk = self.analyzer.analyze_operation(op)
+
+ assert risk.score == 1
+ assert risk.level == RiskLevel.SAFE
+
+ def test_validate_constraint_helper_scores_needs_review(self):
+ """The helper scores like the hand-written VALIDATE CONSTRAINT (slow, non-blocking)."""
+ op = ValidateConstraint(model_name="dashboard", name="dash_amount_chk")
+
+ risk = self.analyzer.analyze_operation(op)
+
+ assert risk.score == 2
+ assert risk.level == RiskLevel.NEEDS_REVIEW
+
def test_run_sql_drop_constraint(self):
"""Test DROP CONSTRAINT - fast but needs deployment safety review (score 2)."""
op = create_mock_operation(
@@ -1832,7 +1859,14 @@ 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"])
+ @parameterized.expand(
+ [
+ "CreateIndexConcurrently",
+ "DropIndexConcurrently",
+ "SafeAddIndexConcurrently",
+ "SafeRemoveIndexConcurrently",
+ ]
+ )
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
@@ -2065,6 +2099,22 @@ class TestConcurrentIndexIdempotencyPolicy:
assert not any("non-idempotent" in v for v in risk.policy_violations)
assert risk.level != RiskLevel.BLOCKED
+ @parameterized.expand(
+ [
+ (SafeAddIndexConcurrently(model_name="dashboard", index=models.Index(fields=["name"], name="idx")),),
+ (SafeRemoveIndexConcurrently(model_name="dashboard", name="idx"),),
+ ]
+ )
+ def test_safe_state_aware_helpers_score_safe(self, op):
+ """The state-aware helpers track state themselves and are idempotent by
+ construction, so they score SAFE and are never flagged — no
+ SeparateDatabaseAndState or raw display SQL required.
+ """
+ risk = self._analyze([op])
+ assert risk.level == RiskLevel.SAFE
+ assert not any("non-idempotent" in v for v in risk.policy_violations)
+ assert not any("atomic=False" in v for v in risk.policy_violations)
+
class TestHotTableAlterPolicy:
"""HotTableAlterPolicy blocks unacknowledged DDL on tables read on every request.
@@ -2185,6 +2235,13 @@ class TestHotTableAlterPolicy:
risk = self._analyze([op])
assert not any("ACCESS EXCLUSIVE" in v for v in risk.policy_violations)
+ def test_validate_constraint_on_hot_model_not_flagged(self):
+ """VALIDATE CONSTRAINT takes only SHARE UPDATE EXCLUSIVE, so the helper is
+ not gated even on a hot table (unlike its AddConstraintNotValid sibling)."""
+ op = create_mock_operation(ValidateConstraint, model_name="team", name="team_some_check")
+ risk = self._analyze([op])
+ assert not any("ACCESS EXCLUSIVE" in v for v in risk.policy_violations)
+
def test_alter_model_options_on_hot_model_not_flagged(self):
op = MagicMock()
op.__class__.__name__ = "AlterModelOptions"
diff --git a/posthog/migration_helpers/__init__.py b/posthog/migration_helpers/__init__.py
index 03fa20c767df..8d9cbda05d2d 100644
--- a/posthog/migration_helpers/__init__.py
+++ b/posthog/migration_helpers/__init__.py
@@ -1,3 +1,16 @@
-from posthog.migration_helpers.concurrent_index import CreateIndexConcurrently, DropIndexConcurrently
+from posthog.migration_helpers.concurrent_index import (
+ CreateIndexConcurrently,
+ DropIndexConcurrently,
+ SafeAddIndexConcurrently,
+ SafeRemoveIndexConcurrently,
+)
+from posthog.migration_helpers.not_valid_constraint import AddConstraintNotValid, ValidateConstraint
-__all__ = ["CreateIndexConcurrently", "DropIndexConcurrently"]
+__all__ = [
+ "AddConstraintNotValid",
+ "CreateIndexConcurrently",
+ "DropIndexConcurrently",
+ "SafeAddIndexConcurrently",
+ "SafeRemoveIndexConcurrently",
+ "ValidateConstraint",
+]
diff --git a/posthog/migration_helpers/concurrent_index.py b/posthog/migration_helpers/concurrent_index.py
index d4cacb4ed7dc..65a90c7058a0 100644
--- a/posthog/migration_helpers/concurrent_index.py
+++ b/posthog/migration_helpers/concurrent_index.py
@@ -20,9 +20,29 @@ These helpers implement the same recovery pattern GitLab uses in
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:
+3. Run the CREATE/DROP statement so retries are safe.
+
+There are two flavors:
+
+`SafeAddIndexConcurrently` / `SafeRemoveIndexConcurrently` (preferred) take a
+`model_name` + Django `Index`, exactly like Django's own
+`AddIndexConcurrently` / `RemoveIndexConcurrently`. They track Django state
+themselves, so there is no `SeparateDatabaseAndState` wrapper and no
+re-specifying the index as raw SQL:
+
+ operations = [
+ SafeAddIndexConcurrently(
+ model_name="mymodel",
+ index=models.Index(fields=["team", "-created_at"], name="my_idx"),
+ ),
+ ]
+
+`CreateIndexConcurrently` / `DropIndexConcurrently` take the raw index SQL
+(`index_name`, `table_name`, `columns`). They subclass `RunSQL`, which does
+not touch Django state, so they must be wrapped in `SeparateDatabaseAndState`
+with a matching `AddIndex` / `RemoveIndex`. Reach for these only when the
+index doesn't map cleanly to a Django `Index` (e.g. an expression the ORM
+can't model):
migrations.SeparateDatabaseAndState(
state_operations=[migrations.AddIndex(...)],
@@ -36,6 +56,7 @@ Wrap in SeparateDatabaseAndState so Django state still tracks the index:
The Migration class still needs `atomic = False`.
"""
+from django.contrib.postgres.operations import AddIndexConcurrently, RemoveIndexConcurrently
from django.db import migrations
import structlog
@@ -43,6 +64,58 @@ import structlog
logger = structlog.get_logger(__name__)
+def _disable_timeouts(schema_editor) -> None:
+ schema_editor.execute("SET lock_timeout = 0")
+ schema_editor.execute("SET statement_timeout = 0")
+
+
+def _index_validity(schema_editor, index_name: str) -> str | None:
+ """None if no index of this name exists, else "valid" or "invalid" (indisvalid)."""
+ with schema_editor.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()
+ if row is None:
+ return None
+ return "valid" if row[0] else "invalid"
+
+
+def _log_and_drop_invalid_index(schema_editor, index_name: str, op_name: str) -> None:
+ """Drop an index left invalid by a prior interrupted CONCURRENTLY build.
+
+ The caller has already established (via `_index_validity`) that the index
+ is invalid - Postgres left the row in pg_class with indisvalid = false after
+ a build was cancelled mid-flight (OOM, pod kill, lock_timeout, etc.), and a
+ plain `CREATE INDEX CONCURRENTLY IF NOT EXISTS` would silently skip past it.
+
+ 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.
+ """
+ logger.warning(
+ "concurrent_index_recovering_from_invalid_leftover",
+ index_name=index_name,
+ operation=op_name,
+ )
+ # Mirror to migration stdout so it shows up in bin/migrate log,
+ # not just the application log stream.
+ print( # noqa: T201
+ f"[{op_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))
+
+
def _build_create_sql(
*,
index_name: str,
@@ -101,53 +174,6 @@ class _ConcurrentIndexOp(migrations.RunSQL):
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.
@@ -175,8 +201,8 @@ class CreateIndexConcurrently(_ConcurrentIndexOp):
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.
+ # are read by `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
@@ -196,12 +222,13 @@ class CreateIndexConcurrently(_ConcurrentIndexOp):
)
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)
+ _disable_timeouts(schema_editor)
+ if _index_validity(schema_editor, self.index_name) == "invalid":
+ _log_and_drop_invalid_index(schema_editor, self.index_name, type(self).__name__)
+ schema_editor.execute(self.sql) # CREATE ... IF NOT EXISTS
def database_backwards(self, app_label, schema_editor, from_state, to_state) -> None:
- self._disable_timeouts(schema_editor)
+ _disable_timeouts(schema_editor)
schema_editor.execute(self.reverse_sql)
def describe(self) -> str:
@@ -238,8 +265,8 @@ class DropIndexConcurrently(_ConcurrentIndexOp):
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.
+ # are read on rollback / by `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
@@ -259,13 +286,103 @@ class DropIndexConcurrently(_ConcurrentIndexOp):
)
def database_forwards(self, app_label, schema_editor, from_state, to_state) -> None:
- self._disable_timeouts(schema_editor)
+ _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)
+ _disable_timeouts(schema_editor)
+ if _index_validity(schema_editor, self.index_name) == "invalid":
+ _log_and_drop_invalid_index(schema_editor, self.index_name, type(self).__name__)
+ schema_editor.execute(self.reverse_sql) # CREATE ... IF NOT EXISTS
def describe(self) -> str:
return f"Concurrently drop index {self.index_name} on {self.table_name}"
+
+
+class SafeAddIndexConcurrently(AddIndexConcurrently):
+ """State-aware CREATE INDEX CONCURRENTLY with invalid-index recovery.
+
+ The model-aware counterpart to `CreateIndexConcurrently`: pass the same
+ `model_name` + `Index` you would give Django's `AddIndexConcurrently`, and
+ this op tracks Django state itself (no `SeparateDatabaseAndState` wrapper,
+ no re-specifying the columns as raw SQL) while adding the safety the bare
+ Django op lacks:
+
+ - disables lock_timeout / statement_timeout so a deploy-time timeout can't
+ cancel the build,
+ - skips when a valid index of that name already exists (idempotent retry),
+ - drops and rebuilds an indisvalid = false leftover from a prior
+ interrupted build, logging a breadcrumb so the recovery is visible.
+
+ Prefer this for the common case. Drop down to `CreateIndexConcurrently`
+ only when the index doesn't map to a Django `Index`.
+
+ operations = [
+ SafeAddIndexConcurrently(
+ model_name="mymodel",
+ index=models.Index(fields=["team", "-created_at"], name="my_idx"),
+ ),
+ ]
+
+ The Migration class still needs `atomic = False`.
+ """
+
+ def database_forwards(self, app_label, schema_editor, from_state, to_state) -> None:
+ self._ensure_not_in_transaction(schema_editor)
+ model = to_state.apps.get_model(app_label, self.model_name)
+ if not self.allow_migrate_model(schema_editor.connection.alias, model):
+ return
+ _disable_timeouts(schema_editor)
+ validity = _index_validity(schema_editor, self.index.name)
+ if validity == "valid":
+ return # already built; a bin/migrate retry is a no-op
+ if validity == "invalid":
+ _log_and_drop_invalid_index(schema_editor, self.index.name, type(self).__name__)
+ schema_editor.add_index(model, self.index, concurrently=True)
+
+ def database_backwards(self, app_label, schema_editor, from_state, to_state) -> None:
+ self._ensure_not_in_transaction(schema_editor)
+ model = from_state.apps.get_model(app_label, self.model_name)
+ if not self.allow_migrate_model(schema_editor.connection.alias, model):
+ return
+ _disable_timeouts(schema_editor)
+ if _index_validity(schema_editor, self.index.name) is None:
+ return # already dropped; a bin/migrate retry is a no-op
+ schema_editor.remove_index(model, self.index, concurrently=True)
+
+
+class SafeRemoveIndexConcurrently(RemoveIndexConcurrently):
+ """State-aware DROP INDEX CONCURRENTLY, the reverse of `SafeAddIndexConcurrently`.
+
+ Pass `model_name` + the index name, like Django's `RemoveIndexConcurrently`.
+ Forward drops the index (skipping if already gone); reverse rebuilds it with
+ the same timeout-disabling + invalid-leftover recovery as
+ `SafeAddIndexConcurrently`. The Migration class still needs `atomic = False`.
+ """
+
+ def database_forwards(self, app_label, schema_editor, from_state, to_state) -> None:
+ self._ensure_not_in_transaction(schema_editor)
+ model = from_state.apps.get_model(app_label, self.model_name)
+ if not self.allow_migrate_model(schema_editor.connection.alias, model):
+ return
+ _disable_timeouts(schema_editor)
+ if _index_validity(schema_editor, self.name) is None:
+ return # already dropped; a bin/migrate retry is a no-op
+ from_model_state = from_state.models[app_label, self.model_name_lower]
+ index = from_model_state.get_index_by_name(self.name)
+ schema_editor.remove_index(model, index, concurrently=True)
+
+ def database_backwards(self, app_label, schema_editor, from_state, to_state) -> None:
+ self._ensure_not_in_transaction(schema_editor)
+ model = to_state.apps.get_model(app_label, self.model_name)
+ if not self.allow_migrate_model(schema_editor.connection.alias, model):
+ return
+ _disable_timeouts(schema_editor)
+ validity = _index_validity(schema_editor, self.name)
+ if validity == "valid":
+ return # already rebuilt; a bin/migrate retry is a no-op
+ if validity == "invalid":
+ _log_and_drop_invalid_index(schema_editor, self.name, type(self).__name__)
+ to_model_state = to_state.models[app_label, self.model_name_lower]
+ index = to_model_state.get_index_by_name(self.name)
+ schema_editor.add_index(model, index, concurrently=True)
diff --git a/posthog/migration_helpers/not_valid_constraint.py b/posthog/migration_helpers/not_valid_constraint.py
new file mode 100644
index 000000000000..5196b09270be
--- /dev/null
+++ b/posthog/migration_helpers/not_valid_constraint.py
@@ -0,0 +1,164 @@
+"""Two-phase CHECK constraint helpers: add NOT VALID, then VALIDATE separately.
+
+Adding a constraint the normal way (Django's `AddConstraint` ->
+`ALTER TABLE ... ADD CONSTRAINT ... CHECK (...)`) validates every existing row
+while holding an ACCESS EXCLUSIVE lock. On a large or hot table that blocks all
+traffic for the duration of the scan. Postgres lets you split this in two:
+
+1. `ADD CONSTRAINT ... NOT VALID` records the constraint and enforces it for
+ new/changed rows. Takes only a brief ACCESS EXCLUSIVE lock; no table scan.
+2. `VALIDATE CONSTRAINT` scans existing rows under SHARE UPDATE EXCLUSIVE, which
+ does not block reads or writes.
+
+`AddConstraintNotValid` does phase 1 (and tracks Django state like
+`AddConstraint`, so `makemigrations --check` stays correct). `ValidateConstraint`
+does phase 2.
+
+Put them in SEPARATE migrations (validate after the add has deployed), or in the
+same migration with `atomic = False` - never the same atomic migration, or the
+ADD's ACCESS EXCLUSIVE lock is held through the VALIDATE scan and you've gained
+nothing:
+
+ # 0005_add_amount_check.py
+ operations = [
+ AddConstraintNotValid(
+ model_name="mymodel",
+ constraint=models.CheckConstraint(condition=Q(amount__gte=0), name="mymodel_amount_gte_0"),
+ ),
+ ]
+
+ # 0006_validate_amount_check.py
+ operations = [
+ ValidateConstraint(model_name="mymodel", name="mymodel_amount_gte_0"),
+ ]
+
+The VALIDATE phase disables lock_timeout / statement_timeout first (like the
+concurrent index helpers): otherwise a deploy-time statement_timeout would kill
+the scan mid-flight on a large table and every bin/migrate retry would do the
+same. VALIDATE only takes SHARE UPDATE EXCLUSIVE, so waiting for the lock doesn't
+block traffic. The ADD phase deliberately does NOT touch the timeouts: it's a
+brief metadata-only ALTER under ACCESS EXCLUSIVE, so it should fail fast on lock
+contention (the default lock_timeout) instead of queuing the lock behind in-flight
+queries and stalling the table.
+
+Both phases are idempotent (bin/migrate re-runs the whole migration on failure):
+the add skips if the constraint already exists, the validate skips if it is
+already validated.
+"""
+
+from django.db import migrations
+from django.db.migrations.operations.base import Operation
+from django.db.models import CheckConstraint
+
+import structlog
+
+from posthog.migration_helpers.concurrent_index import _disable_timeouts
+
+logger = structlog.get_logger(__name__)
+
+
+def _constraint_validity(schema_editor, table_name: str, constraint_name: str) -> bool | None:
+ """None if the constraint doesn't exist, else its convalidated flag."""
+ with schema_editor.connection.cursor() as cursor:
+ cursor.execute(
+ """
+ SELECT c.convalidated
+ FROM pg_constraint c
+ JOIN pg_class t ON c.conrelid = t.oid
+ WHERE c.conname = %s AND t.relname = %s
+ """,
+ [constraint_name, table_name],
+ )
+ row = cursor.fetchone()
+ return None if row is None else bool(row[0])
+
+
+class AddConstraintNotValid(migrations.AddConstraint):
+ """Phase 1: add a CHECK constraint with NOT VALID (no table scan).
+
+ Same arguments as Django's `AddConstraint` (model_name + constraint), but
+ emits `ADD CONSTRAINT ... NOT VALID` so existing rows aren't scanned under an
+ ACCESS EXCLUSIVE lock. Follow up with `ValidateConstraint` in a separate
+ migration. CHECK constraints only - NOT VALID doesn't apply to UNIQUE
+ constraints (build a unique index with `SafeAddIndexConcurrently` instead).
+ """
+
+ # django-stubs doesn't expose these AddConstraint instance attributes, so
+ # declare them for mypy (set by AddConstraint.__init__).
+ model_name: str
+ constraint: CheckConstraint
+
+ def __init__(self, model_name, constraint) -> None:
+ if not isinstance(constraint, CheckConstraint):
+ raise ValueError(
+ "AddConstraintNotValid only supports CheckConstraint - NOT VALID does not apply to "
+ "other constraint types. For a unique constraint, build a unique index with "
+ "SafeAddIndexConcurrently."
+ )
+ super().__init__(model_name, constraint)
+
+ def database_forwards(self, app_label, schema_editor, from_state, to_state) -> None:
+ model = to_state.apps.get_model(app_label, self.model_name)
+ if not self.allow_migrate_model(schema_editor.connection.alias, model):
+ return
+ # No timeout disabling here: NOT VALID is a brief metadata-only ALTER (no
+ # table scan), so it should keep the default lock_timeout and fail fast on
+ # lock contention rather than queue an ACCESS EXCLUSIVE lock behind in-flight
+ # queries. A bin/migrate retry re-attempts once the lock is free.
+ if _constraint_validity(schema_editor, model._meta.db_table, self.constraint.name) is not None:
+ return # already added; a bin/migrate retry is a no-op
+ schema_editor.execute(f"{self.constraint.create_sql(model, schema_editor)} NOT VALID")
+
+ def database_backwards(self, app_label, schema_editor, from_state, to_state) -> None:
+ model = from_state.apps.get_model(app_label, self.model_name)
+ if not self.allow_migrate_model(schema_editor.connection.alias, model):
+ return
+ table = schema_editor.quote_name(model._meta.db_table)
+ name = schema_editor.quote_name(self.constraint.name)
+ schema_editor.execute(f"ALTER TABLE {table} DROP CONSTRAINT IF EXISTS {name}")
+
+ def describe(self) -> str:
+ return f"Add CHECK constraint {self.constraint.name} on {self.model_name} (NOT VALID)"
+
+
+class ValidateConstraint(Operation):
+ """Phase 2: VALIDATE a constraint previously added with NOT VALID.
+
+ Scans existing rows under SHARE UPDATE EXCLUSIVE (doesn't block reads or
+ writes). Pure database operation - the constraint is already in Django state
+ from the `AddConstraintNotValid` in an earlier migration, so this changes no
+ state. Idempotent: skips if the constraint is already validated.
+ """
+
+ reversible = True
+
+ def __init__(self, model_name: str, name: str) -> None:
+ self.model_name = model_name
+ self.name = name
+
+ def state_forwards(self, app_label, state) -> None:
+ pass # the constraint is already tracked by the earlier AddConstraintNotValid
+
+ def database_forwards(self, app_label, schema_editor, from_state, to_state) -> None:
+ model = to_state.apps.get_model(app_label, self.model_name)
+ if not self.allow_migrate_model(schema_editor.connection.alias, model):
+ return
+ _disable_timeouts(schema_editor) # statement_timeout must not kill the VALIDATE scan mid-flight
+ if _constraint_validity(schema_editor, model._meta.db_table, self.name):
+ return # already validated; a bin/migrate retry is a no-op
+ table = schema_editor.quote_name(model._meta.db_table)
+ name = schema_editor.quote_name(self.name)
+ schema_editor.execute(f"ALTER TABLE {table} VALIDATE CONSTRAINT {name}")
+
+ def database_backwards(self, app_label, schema_editor, from_state, to_state) -> None:
+ pass # validation isn't reversible; the constraint itself is dropped by the add op's reverse
+
+ def deconstruct(self) -> tuple[str, list[object], dict[str, str]]:
+ return (self.__class__.__qualname__, [], {"model_name": self.model_name, "name": self.name})
+
+ def describe(self) -> str:
+ return f"Validate constraint {self.name} on {self.model_name}"
+
+ @property
+ def migration_name_fragment(self) -> str:
+ return f"validate_{self.name}"
diff --git a/posthog/migration_helpers/test_concurrent_index.py b/posthog/migration_helpers/test_concurrent_index.py
index 169174f17154..cbee9db77f58 100644
--- a/posthog/migration_helpers/test_concurrent_index.py
+++ b/posthog/migration_helpers/test_concurrent_index.py
@@ -1,4 +1,4 @@
-"""Functional tests for CreateIndexConcurrently / DropIndexConcurrently.
+"""Functional tests for the concurrent-index helpers.
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
@@ -10,9 +10,15 @@ import uuid
import pytest
-from django.db import connection, migrations
+from django.db import connection, migrations, models
+from django.db.migrations.state import ModelState, ProjectState
-from posthog.migration_helpers import CreateIndexConcurrently, DropIndexConcurrently
+from posthog.migration_helpers import (
+ CreateIndexConcurrently,
+ DropIndexConcurrently,
+ SafeAddIndexConcurrently,
+ SafeRemoveIndexConcurrently,
+)
@pytest.fixture
@@ -219,3 +225,218 @@ def test_deconstruct_round_trips(op_cls, extra_kwargs):
rebuilt = op_cls(**kwargs)
assert rebuilt.sql == op.sql
assert rebuilt.reverse_sql == op.reverse_sql
+
+
+# --- State-aware helpers: SafeAddIndexConcurrently / SafeRemoveIndexConcurrently ---
+
+MODEL_NAME = "TempSciModel"
+MODEL_NAME_LOWER = "tempscimodel"
+
+
+def temp_model():
+ """A one-off table plus a ProjectState model pointing at it.
+
+ The state-aware ops resolve the model + index from migration state
+ (unlike the raw-SQL helpers), so the test has to hand them a real state.
+ """
+ table = f"test_sci_{uuid.uuid4().hex[:8]}"
+ with connection.cursor() as cursor:
+ cursor.execute(f'CREATE TABLE "{table}" (id serial primary key, col int)')
+ state = ProjectState()
+ state.add_model(
+ ModelState(
+ app_label="posthog",
+ name=MODEL_NAME,
+ fields=[
+ ("id", models.AutoField(primary_key=True)),
+ ("col", models.IntegerField(null=True)),
+ ],
+ options={"db_table": table},
+ )
+ )
+ try:
+ yield table, state
+ finally:
+ with connection.cursor() as cursor:
+ cursor.execute(f'DROP TABLE IF EXISTS "{table}"')
+
+
+def _apply_forwards(op, state):
+ schema_editor = connection.schema_editor(atomic=False)
+ schema_editor.__enter__()
+ try:
+ op.database_forwards("posthog", schema_editor, from_state=state, to_state=state)
+ finally:
+ schema_editor.__exit__(None, None, None)
+
+
+def _apply_backwards(op, state):
+ schema_editor = connection.schema_editor(atomic=False)
+ schema_editor.__enter__()
+ try:
+ op.database_backwards("posthog", schema_editor, from_state=state, to_state=state)
+ finally:
+ schema_editor.__exit__(None, None, None)
+
+
+def test_safe_add_index_tracks_state_without_separate_database_and_state():
+ """The whole point of the state-aware helper: state_forwards updates Django
+ model state on its own, so no SeparateDatabaseAndState wrapper is needed.
+ """
+ state = ProjectState()
+ state.add_model(
+ ModelState(
+ app_label="posthog",
+ name=MODEL_NAME,
+ fields=[("id", models.AutoField(primary_key=True)), ("col", models.IntegerField(null=True))],
+ )
+ )
+ index = models.Index(fields=["col"], name="state_tracking_idx")
+ op = SafeAddIndexConcurrently(model_name=MODEL_NAME, index=index)
+
+ new_state = state.clone()
+ op.state_forwards("posthog", new_state)
+
+ assert new_state.models["posthog", MODEL_NAME_LOWER].get_index_by_name("state_tracking_idx") == index
+
+
[email protected]_db(transaction=True)
+def test_safe_add_index_concurrently_creates_index(temp_model):
+ table, state = temp_model
+ idx_name = f"{table}_col_idx"
+ op = SafeAddIndexConcurrently(model_name=MODEL_NAME, index=models.Index(fields=["col"], name=idx_name))
+
+ _apply_forwards(op, state)
+
+ assert _index_exists(idx_name)
+ assert _index_is_valid(idx_name)
+
+
[email protected]_db(transaction=True)
+def test_safe_add_index_concurrently_is_idempotent(temp_model):
+ """Second apply skips on the already-valid index instead of raising."""
+ table, state = temp_model
+ idx_name = f"{table}_col_idx"
+ op = SafeAddIndexConcurrently(model_name=MODEL_NAME, index=models.Index(fields=["col"], name=idx_name))
+
+ _apply_forwards(op, state)
+ _apply_forwards(op, state)
+
+ assert _index_is_valid(idx_name)
+
+
[email protected]_db(transaction=True)
+def test_safe_add_index_concurrently_recovers_from_invalid_leftover(temp_model, capsys):
+ table, state = temp_model
+ idx_name = f"{table}_col_idx"
+ with connection.cursor() as cursor:
+ cursor.execute(f'CREATE INDEX "{idx_name}" ON "{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 = SafeAddIndexConcurrently(model_name=MODEL_NAME, index=models.Index(fields=["col"], name=idx_name))
+ _apply_forwards(op, state)
+
+ 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_safe_add_index_concurrently_partial_descending(temp_model):
+ """Delegating to schema_editor.add_index covers index shapes the raw-SQL
+ helper would force you to hand-translate (ordering, partial predicate).
+ """
+ table, state = temp_model
+ idx_name = f"{table}_partial_idx"
+ op = SafeAddIndexConcurrently(
+ model_name=MODEL_NAME,
+ index=models.Index(fields=["-col"], name=idx_name, condition=models.Q(col__isnull=False)),
+ )
+
+ _apply_forwards(op, state)
+
+ 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 "DESC" in indexdef
+ assert "WHERE" in indexdef
+
+
[email protected]_db(transaction=True)
+def test_safe_add_index_concurrently_reverse_drops_index(temp_model):
+ table, state = temp_model
+ idx_name = f"{table}_col_idx"
+ op = SafeAddIndexConcurrently(model_name=MODEL_NAME, index=models.Index(fields=["col"], name=idx_name))
+
+ _apply_forwards(op, state)
+ assert _index_exists(idx_name)
+
+ _apply_backwards(op, state)
+ assert not _index_exists(idx_name)
+
+ _apply_backwards(op, state) # idempotent: nothing left to drop
+ assert not _index_exists(idx_name)
+
+
[email protected]_db(transaction=True)
+def test_safe_remove_index_concurrently_removes_index(temp_model):
+ table, state = temp_model
+ idx_name = f"{table}_col_idx"
+ # Register the index in state (so RemoveIndex can resolve it), then build it.
+ add = SafeAddIndexConcurrently(model_name=MODEL_NAME, index=models.Index(fields=["col"], name=idx_name))
+ add.state_forwards("posthog", state)
+ _apply_forwards(add, state)
+ assert _index_exists(idx_name)
+
+ remove = SafeRemoveIndexConcurrently(model_name=MODEL_NAME, name=idx_name)
+ _apply_forwards(remove, state)
+ assert not _index_exists(idx_name)
+
+ _apply_forwards(remove, state) # idempotent: already gone
+ assert not _index_exists(idx_name)
+
+
[email protected]_db(transaction=True)
+def test_safe_remove_index_concurrently_reverse_recreates(temp_model):
+ table, state = temp_model
+ idx_name = f"{table}_col_idx"
+ add = SafeAddIndexConcurrently(model_name=MODEL_NAME, index=models.Index(fields=["col"], name=idx_name))
+ add.state_forwards("posthog", state)
+ _apply_forwards(add, state)
+
+ remove = SafeRemoveIndexConcurrently(model_name=MODEL_NAME, name=idx_name)
+ _apply_forwards(remove, state)
+ assert not _index_exists(idx_name)
+
+ _apply_backwards(remove, state) # reverse of a drop rebuilds the index
+ assert _index_is_valid(idx_name)
+
+
+ "op",
+ [
+ SafeAddIndexConcurrently(model_name=MODEL_NAME, index=models.Index(fields=["col"], name="i")),
+ SafeRemoveIndexConcurrently(model_name=MODEL_NAME, name="i"),
+ ],
+)
+def test_safe_ops_deconstruct_round_trips(op):
+ """Unlike the RunSQL-based helpers, these inherit Django's deconstruct;
+ confirm it emits the model_name/index kwargs the migration writer needs.
+ """
+ name, args, kwargs = op.deconstruct()
+
+ assert name == type(op).__name__
+ assert args == []
+ rebuilt = type(op)(**kwargs)
+ assert rebuilt.deconstruct() == op.deconstruct()
diff --git a/posthog/migration_helpers/test_not_valid_constraint.py b/posthog/migration_helpers/test_not_valid_constraint.py
new file mode 100644
index 000000000000..d21d1c937c05
--- /dev/null
+++ b/posthog/migration_helpers/test_not_valid_constraint.py
@@ -0,0 +1,270 @@
+"""Functional tests for AddConstraintNotValid / ValidateConstraint.
+
+Each test creates and drops a real table inside the standard test database so
+we can poke pg_constraint.convalidated directly and exercise the two-phase
+NOT VALID -> VALIDATE flow against live Postgres.
+"""
+
+import uuid
+
+import pytest
+
+from django.db import connection, models
+from django.db.migrations.state import ModelState, ProjectState
+from django.db.models import Q
+from django.db.utils import IntegrityError
+
+from posthog.migration_helpers import AddConstraintNotValid, ValidateConstraint
+
+MODEL_NAME = "TmpCheckModel"
+MODEL_NAME_LOWER = "tmpcheckmodel"
+
+
+def temp_model():
+ """A one-off table plus a ProjectState model pointing at it."""
+ table = f"test_nvc_{uuid.uuid4().hex[:8]}"
+ with connection.cursor() as cursor:
+ cursor.execute(f'CREATE TABLE "{table}" (id serial primary key, amount int)')
+ state = ProjectState()
+ state.add_model(
+ ModelState(
+ app_label="posthog",
+ name=MODEL_NAME,
+ fields=[
+ ("id", models.AutoField(primary_key=True)),
+ ("amount", models.IntegerField(null=True)),
+ ],
+ options={"db_table": table},
+ )
+ )
+ try:
+ yield table, state
+ finally:
+ with connection.cursor() as cursor:
+ cursor.execute(f'DROP TABLE IF EXISTS "{table}"')
+
+
+def _apply_forwards(op, state):
+ schema_editor = connection.schema_editor(atomic=False)
+ schema_editor.__enter__()
+ try:
+ op.database_forwards("posthog", schema_editor, from_state=state, to_state=state)
+ finally:
+ schema_editor.__exit__(None, None, None)
+
+
+def _apply_backwards(op, state):
+ schema_editor = connection.schema_editor(atomic=False)
+ schema_editor.__enter__()
+ try:
+ op.database_backwards("posthog", schema_editor, from_state=state, to_state=state)
+ finally:
+ schema_editor.__exit__(None, None, None)
+
+
+def _convalidated(constraint_name):
+ """None if the constraint is absent, else its convalidated flag."""
+ with connection.cursor() as cursor:
+ cursor.execute("SELECT convalidated FROM pg_constraint WHERE conname = %s", [constraint_name])
+ row = cursor.fetchone()
+ return None if row is None else bool(row[0])
+
+
+def _insert(table, amount):
+ with connection.cursor() as cursor:
+ cursor.execute(f'INSERT INTO "{table}" (amount) VALUES (%s)', [amount])
+
+
+def _check(name):
+ return models.CheckConstraint(condition=Q(amount__gte=0), name=name)
+
+
+def test_add_constraint_not_valid_rejects_non_check_constraint():
+ with pytest.raises(ValueError, match="only supports CheckConstraint"):
+ AddConstraintNotValid(model_name=MODEL_NAME, constraint=models.UniqueConstraint(fields=["amount"], name="u"))
+
+
+def test_add_constraint_not_valid_tracks_state_without_separate_database_and_state():
+ """state_forwards updates Django model state on its own (no SeparateDatabaseAndState)."""
+ state = ProjectState()
+ state.add_model(
+ ModelState(
+ app_label="posthog",
+ name=MODEL_NAME,
+ fields=[("id", models.AutoField(primary_key=True)), ("amount", models.IntegerField(null=True))],
+ )
+ )
+ constraint = _check("state_tracking_chk")
+ op = AddConstraintNotValid(model_name=MODEL_NAME, constraint=constraint)
+
+ new_state = state.clone()
+ op.state_forwards("posthog", new_state)
+
+ constraints = new_state.models["posthog", MODEL_NAME_LOWER].options["constraints"]
+ assert any(c.name == "state_tracking_chk" for c in constraints)
+
+
[email protected]_db(transaction=True)
+def test_add_constraint_not_valid_creates_unvalidated_constraint(temp_model):
+ table, state = temp_model
+ name = f"{table}_amount_chk"
+ op = AddConstraintNotValid(model_name=MODEL_NAME, constraint=_check(name))
+
+ _apply_forwards(op, state)
+
+ assert _convalidated(name) is False # present but not validated
+
+
[email protected]_db(transaction=True)
+def test_add_constraint_not_valid_skips_existing_rows_but_enforces_new_rows(temp_model):
+ """The point of NOT VALID: existing violations are tolerated, new ones aren't."""
+ table, state = temp_model
+ name = f"{table}_amount_chk"
+ _insert(table, -5) # pre-existing violation
+
+ op = AddConstraintNotValid(model_name=MODEL_NAME, constraint=_check(name))
+ _apply_forwards(op, state) # succeeds despite the violating row (no scan)
+
+ with pytest.raises(IntegrityError):
+ _insert(table, -1) # new violation is rejected
+
+
[email protected]_db(transaction=True)
+def test_add_constraint_not_valid_is_idempotent(temp_model):
+ table, state = temp_model
+ name = f"{table}_amount_chk"
+ op = AddConstraintNotValid(model_name=MODEL_NAME, constraint=_check(name))
+
+ _apply_forwards(op, state)
+ _apply_forwards(op, state)
+
+ assert _convalidated(name) is False
+
+
[email protected]_db(transaction=True)
+def test_add_constraint_not_valid_reverse_drops(temp_model):
+ table, state = temp_model
+ name = f"{table}_amount_chk"
+ op = AddConstraintNotValid(model_name=MODEL_NAME, constraint=_check(name))
+
+ _apply_forwards(op, state)
+ assert _convalidated(name) is False
+
+ _apply_backwards(op, state)
+ assert _convalidated(name) is None
+
+ _apply_backwards(op, state) # idempotent: DROP CONSTRAINT IF EXISTS
+ assert _convalidated(name) is None
+
+
[email protected]_db(transaction=True)
+def test_validate_constraint_marks_constraint_valid(temp_model):
+ table, state = temp_model
+ name = f"{table}_amount_chk"
+ _insert(table, 5) # clean data
+ _apply_forwards(AddConstraintNotValid(model_name=MODEL_NAME, constraint=_check(name)), state)
+ assert _convalidated(name) is False
+
+ _apply_forwards(ValidateConstraint(model_name=MODEL_NAME, name=name), state)
+
+ assert _convalidated(name) is True
+
+
[email protected]_db(transaction=True)
+def test_validate_constraint_is_idempotent(temp_model):
+ table, state = temp_model
+ name = f"{table}_amount_chk"
+ _apply_forwards(AddConstraintNotValid(model_name=MODEL_NAME, constraint=_check(name)), state)
+ validate = ValidateConstraint(model_name=MODEL_NAME, name=name)
+
+ _apply_forwards(validate, state)
+ _apply_forwards(validate, state) # already validated -> skipped
+
+ assert _convalidated(name) is True
+
+
[email protected]_db(transaction=True)
+def test_validate_constraint_fails_on_existing_violation(temp_model):
+ table, state = temp_model
+ name = f"{table}_amount_chk"
+ _insert(table, -5) # existing violation
+ _apply_forwards(AddConstraintNotValid(model_name=MODEL_NAME, constraint=_check(name)), state)
+
+ with pytest.raises(IntegrityError):
+ _apply_forwards(ValidateConstraint(model_name=MODEL_NAME, name=name), state)
+
+ assert _convalidated(name) is False # stays unvalidated, can retry after cleanup
+
+
[email protected]_db(transaction=True)
+def test_validate_constraint_reverse_is_noop(temp_model):
+ table, state = temp_model
+ name = f"{table}_amount_chk"
+ _apply_forwards(AddConstraintNotValid(model_name=MODEL_NAME, constraint=_check(name)), state)
+ validate = ValidateConstraint(model_name=MODEL_NAME, name=name)
+ _apply_forwards(validate, state)
+
+ _apply_backwards(validate, state) # validation isn't reversible
+
+ assert _convalidated(name) is True # constraint untouched by the reverse
+
+
+def _collected_forward_sql(op):
+ """Run op.database_forwards in collect_sql mode and return the emitted SQL.
+
+ collect_sql records statements instead of running them; the constraint is
+ absent, so the validity probe returns None and the op proceeds to emit DDL.
+ """
+ state = ProjectState()
+ state.add_model(
+ ModelState(
+ app_label="posthog",
+ name=MODEL_NAME,
+ fields=[("id", models.AutoField(primary_key=True)), ("amount", models.IntegerField(null=True))],
+ )
+ )
+ schema_editor = connection.schema_editor(atomic=False, collect_sql=True)
+ schema_editor.__enter__()
+ try:
+ op.database_forwards("posthog", schema_editor, from_state=state, to_state=state)
+ finally:
+ schema_editor.__exit__(None, None, None)
+ return "\n".join(schema_editor.collected_sql)
+
+
+def test_validate_constraint_disables_timeouts():
+ """VALIDATE scans the whole table under SHARE UPDATE EXCLUSIVE (no traffic
+ block), so statement_timeout must be disabled or the scan is killed mid-flight
+ and every bin/migrate retry repeats."""
+ collected = _collected_forward_sql(ValidateConstraint(model_name=MODEL_NAME, name="tchk"))
+ assert "SET lock_timeout = 0" in collected
+ assert "SET statement_timeout = 0" in collected
+
+
+def test_add_constraint_not_valid_keeps_lock_timeout():
+ """NOT VALID is a brief metadata-only ALTER under ACCESS EXCLUSIVE, so it must
+ keep the default lock_timeout and fail fast on contention rather than queue the
+ lock behind in-flight queries and stall the table."""
+ collected = _collected_forward_sql(AddConstraintNotValid(model_name=MODEL_NAME, constraint=_check("tchk")))
+ assert "SET lock_timeout = 0" not in collected
+ assert "SET statement_timeout = 0" not in collected
+ assert "ADD CONSTRAINT" in collected.upper() # the op still emitted its DDL
+
+
+ "op",
+ [
+ AddConstraintNotValid(model_name=MODEL_NAME, constraint=_check("c")),
+ ValidateConstraint(model_name=MODEL_NAME, name="c"),
+ ],
+)
+def test_deconstruct_round_trips(op):
+ name, args, kwargs = op.deconstruct()
+
+ assert name == type(op).__name__
+ assert args == []
+ rebuilt = type(op)(**kwargs)
+ assert rebuilt.deconstruct() == op.deconstruct()