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.

perf(warehouse-sources): index running jobs and cap the facade job list (#92706)

Daniel RCe193706f15a4
diff --git a/products/warehouse_sources/backend/facade/api.py b/products/warehouse_sources/backend/facade/api.py
index 1e1ace76f01c..f5ffb408fe9a 100644
--- a/products/warehouse_sources/backend/facade/api.py
+++ b/products/warehouse_sources/backend/facade/api.py
@@ -575,11 +575,21 @@ def soft_delete_tables(team_id: int, names: Collection[str]) -> int:
return deleted
-def list_jobs_for_source(source_id: UUID, team_id: int) -> list[contracts.ExternalDataJob]:
+MAX_JOBS_PER_SOURCE = 100
+
+
+def list_jobs_for_source(
+ source_id: UUID, team_id: int, limit: int = MAX_JOBS_PER_SOURCE
+) -> list[contracts.ExternalDataJob]:
+ """The source's newest jobs, most recent first, at most `MAX_JOBS_PER_SOURCE` of them.
+
+ The cap is not optional in effect: a busy source runs millions of jobs, so an unbounded
+ read here would scan and sort that whole history to serve one caller.
+ """
qs = (
_ExternalDataJob.objects.select_related("schema", "pipeline")
.filter(team_id=team_id, pipeline_id=source_id)
- .order_by("-created_at")
+ .order_by("-created_at")[: min(max(limit, 1), MAX_JOBS_PER_SOURCE)]
)
return [_to_job(j) for j in qs]
diff --git a/products/warehouse_sources/backend/migrations/0167_externaldatajob_running_idx.py b/products/warehouse_sources/backend/migrations/0167_externaldatajob_running_idx.py
new file mode 100644
index 000000000000..fc0696f85587
--- /dev/null
+++ b/products/warehouse_sources/backend/migrations/0167_externaldatajob_running_idx.py
@@ -0,0 +1,23 @@
+from django.db import migrations, models
+from django.db.models import Q
+
+from posthog.migration_helpers import SafeAddIndexConcurrently
+
+
+class Migration(migrations.Migration):
+ # Concurrent index builds cannot run inside a transaction. Lives in its own
+ # migration per PostHog policy (don't mix CONCURRENTLY operations with regular DDL).
+ atomic = False
+
+ dependencies = [("warehouse_sources", "0166_externaldatajob_detach_created_by")]
+
+ operations = [
+ SafeAddIndexConcurrently(
+ model_name="externaldatajob",
+ index=models.Index(
+ fields=["created_at"],
+ condition=Q(status="Running"),
+ name="idx_extdatajob_running",
+ ),
+ ),
+ ]
diff --git a/products/warehouse_sources/backend/migrations/max_migration.txt b/products/warehouse_sources/backend/migrations/max_migration.txt
index 895245918fe9..6844fa5205dd 100644
--- a/products/warehouse_sources/backend/migrations/max_migration.txt
+++ b/products/warehouse_sources/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0166_externaldatajob_detach_created_by
+0167_externaldatajob_running_idx
diff --git a/products/warehouse_sources/backend/models/external_data_job.py b/products/warehouse_sources/backend/models/external_data_job.py
index 9708f7e784b4..356434373c96 100644
--- a/products/warehouse_sources/backend/models/external_data_job.py
+++ b/products/warehouse_sources/backend/models/external_data_job.py
@@ -3,7 +3,7 @@ from uuid import UUID
from django.conf import settings
from django.db import models
-from django.db.models import F, Func, IntegerField, OuterRef, Prefetch, Subquery, Value
+from django.db.models import F, Func, IntegerField, OuterRef, Prefetch, Q, Subquery, Value
from django.db.models.functions import Greatest
from posthog.models.utils import CreatedMetaFields, UpdatedMetaFields, UUIDTModel, sane_repr
@@ -82,6 +82,15 @@ class ExternalDataJob(CreatedMetaFields, UpdatedMetaFields, UUIDTModel):
fields=["pipeline", "status", "finished_at"],
name="idx_extdatajob_pipe_stat_fin",
),
+ # Serves the sweeps that look for live runs (sweep_stopped_schema_syncs, the CDC
+ # orphan sweep, teardown, repair): status equality with a created_at range and no
+ # team or pipeline to narrow on first. Running is a fraction of a percent of the
+ # table, so the partial index holds only live rows instead of the whole history.
+ models.Index(
+ fields=["created_at"],
+ condition=Q(status=ExternalDataJobStatus.RUNNING),
+ name="idx_extdatajob_running",
+ ),
]
def folder_path(self) -> str:
diff --git a/products/warehouse_sources/backend/tests/test_facade.py b/products/warehouse_sources/backend/tests/test_facade.py
index ed12ae7f5185..a577a8baf5c1 100644
--- a/products/warehouse_sources/backend/tests/test_facade.py
+++ b/products/warehouse_sources/backend/tests/test_facade.py
@@ -1,7 +1,10 @@
import uuid
+from datetime import timedelta
from posthog.test.base import BaseTest
+from django.utils import timezone
+
from parameterized import parameterized
from posthog.constants import AvailableFeature
@@ -277,6 +280,37 @@ class TestWarehouseSourcesFacade(BaseTest):
assert results[0].source_type == "Postgres"
assert results[0].source_prefix == "stripe_"
+ @parameterized.expand(
+ [
+ ("within_the_limit", 2, 2),
+ ("above_the_cap", api.MAX_JOBS_PER_SOURCE + 1, api.MAX_JOBS_PER_SOURCE),
+ ("zero", 0, 1),
+ ]
+ )
+ def test_list_jobs_for_source_returns_the_newest_within_the_limit(
+ self, _name: str, limit: int, expected_count: int
+ ) -> None:
+ total = api.MAX_JOBS_PER_SOURCE + 1
+ jobs = ExternalDataJob.objects.bulk_create(
+ ExternalDataJob(
+ team_id=self.team.pk,
+ pipeline=self.source,
+ schema=self.schema,
+ status="Completed",
+ schema_snapshot={},
+ rows_synced=n,
+ )
+ for n in range(1, total + 1)
+ )
+ base = timezone.now() - timedelta(days=1)
+ for job in jobs:
+ job.created_at = base + timedelta(seconds=job.rows_synced or 0)
+ ExternalDataJob.objects.bulk_update(jobs, ["created_at"])
+
+ results = api.list_jobs_for_source(self.source.id, self.team.pk, limit=limit)
+
+ assert [r.rows_synced for r in results] == list(range(total, total - expected_count, -1))
+
def test_facade_enforces_team_isolation(self) -> None:
other_team = Team.objects.create(organization=self.organization, name="other")
with self.assertRaises(ExternalDataSource.DoesNotExist):