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(data-warehouse): index sourcebatch.job_id (#83156)

estefaniae4ecd05534e0
diff --git a/posthog/management/migration_analysis/atomic_false_acknowledged_migrations.txt b/posthog/management/migration_analysis/atomic_false_acknowledged_migrations.txt
index 61135cc4f630..75e50e0c798d 100644
--- a/posthog/management/migration_analysis/atomic_false_acknowledged_migrations.txt
+++ b/posthog/management/migration_analysis/atomic_false_acknowledged_migrations.txt
@@ -21,3 +21,4 @@ tasks.0092_backfill_task_last_activity_at
# Does run CONCURRENTLY, one index per sourcebatch partition, but from RunPython
# (the partition list is only known at runtime), which the type-based check can't see.
warehouse_sources_queue.0008_sourcebatch_superseded
+warehouse_sources_queue.0009_sourcebatch_job_id_idx
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_jobs_db.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_jobs_db.py
index 3cf27330d61e..21fc8f232c47 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_jobs_db.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_jobs_db.py
@@ -103,6 +103,7 @@ def _ensure_tables(conn: psycopg.Connection[Any]) -> None:
CREATE INDEX IF NOT EXISTS sb_failed_changed_idx ON {BATCH_TABLE} (state_changed_at)
WHERE latest_state = 'failed'
""")
+ conn.execute(f"CREATE INDEX IF NOT EXISTS sb_job_id_idx ON {BATCH_TABLE} (job_id)")
conn.execute(f"""
CREATE TABLE IF NOT EXISTS {STATUS_TABLE} (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
@@ -1528,6 +1529,23 @@ class TestClaimGates:
await conn.execute("SET enable_seqscan = on")
assert "sb_claimable_idx" in plan
+ @pytest.mark.asyncio
+ async def test_job_scoped_queries_use_the_job_id_index(self, conn):
+ # supersede_other_runs runs on every fresh run's first batch; without this
+ # index each call seq-scans every retained partition.
+ await _insert_batch(conn)
+ await conn.execute("SET enable_seqscan = off")
+ try:
+ cur = await conn.execute(
+ f"EXPLAIN (FORMAT TEXT) SELECT count(*) FROM {BATCH_TABLE} b "
+ "WHERE b.created_at > now() - interval '14 days' AND b.job_id = %s",
+ ["job-1"],
+ )
+ plan = "\n".join(row[0] for row in await cur.fetchall())
+ finally:
+ await conn.execute("SET enable_seqscan = on")
+ assert "sb_job_id_idx" in plan
+
@pytest.mark.django_db(transaction=True)
class TestGetClaimableBatchCount:
diff --git a/products/warehouse_sources_queue/backend/migrations/0009_sourcebatch_job_id_idx.py b/products/warehouse_sources_queue/backend/migrations/0009_sourcebatch_job_id_idx.py
new file mode 100644
index 000000000000..0bcf164eb47c
--- /dev/null
+++ b/products/warehouse_sources_queue/backend/migrations/0009_sourcebatch_job_id_idx.py
@@ -0,0 +1,137 @@
+from django.db import migrations, models
+
+import structlog
+
+from posthog.dataclasses import frozen
+
+logger = structlog.get_logger(__name__)
+
+INDEX_NAME = "sb_job_id_idx"
+_INDEX_COLUMNS = "(job_id)"
+
+# ON ONLY creates the parent index as metadata alone, leaving it invalid until
+# every partition has a matching index attached. Building those per partition
+# with CONCURRENTLY is the only way to add this index without locking writes out
+# of the batch table for the length of the build (0008's pattern): CONCURRENTLY
+# is not supported on a partitioned parent, and a plain build there recurses
+# into every partition under a lock that blocks the claim path. This index is
+# unpartial, so the build touches every retained row.
+_PARENT_INDEX_SQL = f"""
+DO $$
+BEGIN
+ IF to_regclass('public.sourcebatch') IS NOT NULL THEN
+ SET LOCAL lock_timeout = '5s';
+ CREATE INDEX IF NOT EXISTS {INDEX_NAME}
+ ON ONLY sourcebatch {_INDEX_COLUMNS};
+ END IF;
+END
+$$;
+"""
+
+_PARTITIONS_SQL = """
+ SELECT c.relname
+ FROM pg_inherits i
+ JOIN pg_class c ON c.oid = i.inhrelid
+ WHERE i.inhparent = 'public.sourcebatch'::regclass
+ ORDER BY c.relname
+"""
+
+# indisvalid is false while a CONCURRENTLY build is unfinished or was cancelled;
+# the pg_inherits probe says whether the child index is already attached to the
+# parent, which is what makes the whole loop re-runnable under bin/migrate retries.
+_INDEX_STATE_SQL = """
+ SELECT i.indisvalid, EXISTS (SELECT 1 FROM pg_inherits pi WHERE pi.inhrelid = c.oid)
+ FROM pg_class c
+ JOIN pg_index i ON i.indexrelid = c.oid
+ WHERE c.relname = %s
+"""
+
+
+def _sourcebatch_exists(schema_editor) -> bool:
+ with schema_editor.connection.cursor() as cursor:
+ cursor.execute("SELECT to_regclass('public.sourcebatch') IS NOT NULL")
+ row = cursor.fetchone()
+ return bool(row and row[0])
+
+
+def _partitions(schema_editor) -> list[str]:
+ with schema_editor.connection.cursor() as cursor:
+ cursor.execute(_PARTITIONS_SQL)
+ return [row[0] for row in cursor.fetchall()]
+
+
+@frozen
+class _IndexState:
+ valid: bool
+ attached: bool
+
+
+def _index_state(schema_editor, index_name: str) -> _IndexState:
+ with schema_editor.connection.cursor() as cursor:
+ cursor.execute(_INDEX_STATE_SQL, [index_name])
+ row = cursor.fetchone()
+ if row is None:
+ return _IndexState(valid=False, attached=False)
+ return _IndexState(valid=bool(row[0]), attached=bool(row[1]))
+
+
+def _disable_timeouts(schema_editor) -> None:
+ # A cancelled CONCURRENTLY build leaves an invalid index that IF NOT EXISTS
+ # would skip past on every retry, so these builds must not be interruptible.
+ schema_editor.execute("SET lock_timeout = 0")
+ schema_editor.execute("SET statement_timeout = 0")
+
+
+def _forward(apps, schema_editor):
+ schema_editor.execute(_PARENT_INDEX_SQL)
+ if not _sourcebatch_exists(schema_editor):
+ return
+
+ _disable_timeouts(schema_editor)
+ for partition in _partitions(schema_editor):
+ index_name = f"{partition}_{INDEX_NAME}"
+ state = _index_state(schema_editor, index_name)
+ if state.attached:
+ continue
+ if not state.valid:
+ # Either absent, or an invalid leftover from an interrupted build.
+ schema_editor.execute(f'DROP INDEX CONCURRENTLY IF EXISTS "{index_name}"')
+ logger.info("sourcebatch_partition_index_build", partition=partition, index_name=index_name)
+ schema_editor.execute(
+ f'CREATE INDEX CONCURRENTLY IF NOT EXISTS "{index_name}" ON "{partition}" {_INDEX_COLUMNS}'
+ )
+ # Attaching the last partition is what flips the parent index to valid.
+ schema_editor.execute(f'ALTER INDEX {INDEX_NAME} ATTACH PARTITION "{index_name}"')
+
+
+def _reverse(apps, schema_editor):
+ if _sourcebatch_exists(schema_editor):
+ _disable_timeouts(schema_editor)
+ # Dropping the parent takes every attached child with it; the loop then
+ # clears children a partial forward run created but never attached.
+ schema_editor.execute(f"DROP INDEX IF EXISTS {INDEX_NAME}")
+ for partition in _partitions(schema_editor):
+ schema_editor.execute(f'DROP INDEX CONCURRENTLY IF EXISTS "{partition}_{INDEX_NAME}"')
+
+
+class Migration(migrations.Migration):
+ # CREATE INDEX CONCURRENTLY cannot run inside a transaction block.
+ atomic = False
+
+ dependencies = [
+ ("warehouse_sources_queue", "0008_sourcebatch_superseded"),
+ ]
+
+ operations = [
+ migrations.SeparateDatabaseAndState(
+ state_operations=[
+ migrations.AddIndex(
+ model_name="sourcebatch",
+ index=models.Index(fields=["job_id"], name="sb_job_id_idx"),
+ ),
+ ],
+ database_operations=[
+ migrations.RunPython(_forward, _reverse),
+ ],
+ ),
+ ]
diff --git a/products/warehouse_sources_queue/backend/migrations/max_migration.txt b/products/warehouse_sources_queue/backend/migrations/max_migration.txt
index 27a9b040337f..c20d00388cb0 100644
--- a/products/warehouse_sources_queue/backend/migrations/max_migration.txt
+++ b/products/warehouse_sources_queue/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0008_sourcebatch_superseded
+0009_sourcebatch_job_id_idx
diff --git a/products/warehouse_sources_queue/backend/models.py b/products/warehouse_sources_queue/backend/models.py
index 021e9d11412c..f5b73afcaf88 100644
--- a/products/warehouse_sources_queue/backend/models.py
+++ b/products/warehouse_sources_queue/backend/models.py
@@ -71,6 +71,10 @@ class SourceBatch(UUIDModel):
models.Index(fields=["team_id", "schema_id"], name="sb_team_schema_idx"),
models.Index(fields=["run_uuid"], name="sb_run_uuid_idx"),
models.Index(fields=["run_uuid", "batch_index"], name="sb_run_uuid_bi_idx"),
+ # Serves the job-scoped scans (supersede_other_runs on every fresh run's
+ # first batch, lock-takeover activity summary, orphan reconcile counts),
+ # which otherwise seq-scan every retained partition per call.
+ models.Index(fields=["job_id"], name="sb_job_id_idx"),
models.Index(
fields=["team_id", "created_at", "batch_index"],
name="sb_claimable_idx",