:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(signals): stop the scout profile scanning whole warehouse job histories (#103294)
posthog[bot]a23e5a3f8634
diff --git a/products/signals/backend/scout_harness/profile/builders.py b/products/signals/backend/scout_harness/profile/builders.pyindex e0f8f5ed7ff2..a16fda14c5a1 100644--- a/products/signals/backend/scout_harness/profile/builders.py+++ b/products/signals/backend/scout_harness/profile/builders.py@@ -30,7 +30,7 @@ import loggingfrom datetime import timedeltafrom typing import Any-from django.db.models import Count, F, Max, OuterRef, Q, Subquery+from django.db.models import Count, F, Max, Qfrom django.utils import timezonefrom posthog.hogql import ast@@ -65,8 +65,7 @@ from products.signals.backend.scout_harness.config_registry import live_scout_skfrom products.signals.backend.scout_harness.profile.schema import Inventoryfrom products.signals.backend.scout_harness.team_limits import withheld_skills_for_teamfrom products.surveys.backend.models import Survey-from products.warehouse_sources.backend.facade.models import ExternalDataSchema, ExternalDataSource-from products.warehouse_sources.backend.facade.types import ExternalDataJobStatus+from products.warehouse_sources.backend.facade import api as warehouse_sourcesfrom products.workflows.backend.models.hog_flow.hog_flow import HogFlowlogger = logging.getLogger(__name__)@@ -239,32 +238,16 @@ def _external_data_sources(team: Team) -> list[dict[str, Any]]:semantics of the `external-data-sources-list` API so a scout can spot a dead source fromthe profile alone without a follow-up list call."""- # Newest schema-level error across the source's non-deleted schemas. Ordered by most- # recently updated so a scout sees the freshest failure, matching the list API's intent.- latest_error = Subquery(- ExternalDataSchema.objects.filter(source_id=OuterRef("pk"), deleted=False, latest_error__isnull=False)- .order_by("-updated_at")- .values("latest_error")[:1]- )- rows = (- ExternalDataSource.objects.filter(team=team, deleted=False)- .annotate(- last_run_at=Max("jobs__created_at", filter=Q(jobs__status=ExternalDataJobStatus.COMPLETED)),- latest_error=latest_error,- )- .order_by("source_type", "id")- .values("source_type", "status", "prefix", "created_at", "last_run_at", "latest_error")- )return [{- "source_type": row["source_type"],- "status": row["status"],- "prefix": row["prefix"] or "",- "created_at": row["created_at"].isoformat() if row.get("created_at") else None,- "last_run_at": row["last_run_at"].isoformat() if row.get("last_run_at") else None,- "latest_error": row.get("latest_error"),+ "source_type": source.source_type,+ "status": source.status,+ "prefix": source.prefix or "",+ "created_at": source.created_at.isoformat(),+ "last_run_at": source.last_run_at.isoformat() if source.last_run_at else None,+ "latest_error": source.latest_error,}- for row in rows+ for source in warehouse_sources.list_source_health(team.pk)]diff --git a/products/warehouse_sources/backend/facade/api.py b/products/warehouse_sources/backend/facade/api.pyindex a99e02090d21..233afbeaf96b 100644--- a/products/warehouse_sources/backend/facade/api.py+++ b/products/warehouse_sources/backend/facade/api.py@@ -22,7 +22,7 @@ from collections.abc import Collectionfrom typing import TYPE_CHECKINGfrom uuid import UUID-from django.db.models import Prefetch, QuerySet+from django.db.models import OuterRef, Prefetch, QuerySet, Subquery# Source-agnostic storage contract for user-uploaded files — shared with the upload endpoint.from products.warehouse_sources.backend.file_uploads import (@@ -38,7 +38,10 @@ from products.warehouse_sources.backend.file_uploads import (from products.warehouse_sources.backend.models.column_statistics import (WarehouseColumnStatistics as _WarehouseColumnStatistics,)-from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob as _ExternalDataJob+from products.warehouse_sources.backend.models.external_data_job import (+ ExternalDataJob as _ExternalDataJob,+ latest_completed_job_subquery,+)from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema as _ExternalDataSchemafrom products.warehouse_sources.backend.models.external_data_source import ExternalDataSource as _ExternalDataSourcefrom products.warehouse_sources.backend.models.table import DataWarehouseTable as _DataWarehouseTable@@ -68,6 +71,7 @@ __all__ = [# capability functions"get_source","list_sources",+ "list_source_health","list_revenue_sources","list_revenue_source_settings","get_schema",@@ -257,6 +261,31 @@ def list_sources(return [_to_source(s) for s in qs]+def list_source_health(team_id: int) -> list[contracts.ExternalDataSourceHealth]:+ """Live sources with the timestamp of their newest completed run and their newest schema error.++ One correlated probe per source for each of the two lookups, so the cost tracks the number+ of sources rather than the length of the team's job history.+ """+ # Newest schema-level error across the source's non-deleted schemas. Ordered by most+ # recently updated so a consumer sees the freshest failure.+ latest_error = Subquery(+ _ExternalDataSchema.objects.filter(source_id=OuterRef("pk"), deleted=False, latest_error__isnull=False)+ .order_by("-updated_at")+ .values("latest_error")[:1]+ )+ rows = (+ _ExternalDataSource.objects.filter(team_id=team_id, deleted=False)+ .annotate(+ last_run_at=latest_completed_job_subquery(team_id, "created_at"),+ latest_error=latest_error,+ )+ .order_by("source_type", "id")+ .values("source_type", "status", "prefix", "created_at", "last_run_at", "latest_error")+ )+ return [contracts.ExternalDataSourceHealth(**row) for row in rows]++def _revenue_source_queryset(team_id: int,*,diff --git a/products/warehouse_sources/backend/facade/contracts.py b/products/warehouse_sources/backend/facade/contracts.pyindex dd0676841049..b621afaa0b0d 100644--- a/products/warehouse_sources/backend/facade/contracts.py+++ b/products/warehouse_sources/backend/facade/contracts.py@@ -85,6 +85,22 @@ class ExternalDataSource:direct_engine: str | None+@dataclass(frozen=True)+class ExternalDataSourceHealth:+ """A source's sync health: how it is configured, plus its newest completed run and error.++ `status` alone conflates "sync in progress" with "never succeeded", so a consumer needs+ `last_run_at` to tell a healthy source from one that has never synced.+ """++ source_type: str+ status: str | None+ prefix: str | None+ created_at: datetime+ last_run_at: datetime | None+ latest_error: str | None++# --- Schema ---diff --git a/products/warehouse_sources/backend/models/external_data_job.py b/products/warehouse_sources/backend/models/external_data_job.pyindex a97b7b5745c5..e88328fa11bd 100644--- a/products/warehouse_sources/backend/models/external_data_job.py+++ b/products/warehouse_sources/backend/models/external_data_job.py@@ -93,6 +93,24 @@ def get_external_data_job(job_id: UUID) -> ExternalDataJob:).get(pk=job_id)+def latest_completed_job_subquery(team_id: int, field: str) -> Subquery:+ """One field of each source's newest completed job, correlated on the source row.++ Annotate this on a queryset of `ExternalDataSource`. It costs one probe of+ `idx_extdatajob_latest_run` per source, because the filter matches that index's leading+ columns and the ordering matches its trailing one.++ Do not replace it with `Max("jobs__created_at", filter=...)`. Django compiles that aggregate+ to a LEFT OUTER JOIN onto the job table plus a GROUP BY, so Postgres reads and sorts every+ completed job the team has ever run to produce one timestamp per source.+ """+ return Subquery(+ ExternalDataJob.objects.filter(pipeline=OuterRef("pk"), team_id=team_id, status=ExternalDataJobStatus.COMPLETED)+ .order_by("-created_at")+ .values(field)[:1]+ )++def latest_completed_job_prefetch(team_id: int, lookup: str, to_attr: str, source_ids: Collection[UUID | str] | None = None) -> Prefetch:@@ -109,15 +127,7 @@ def latest_completed_job_prefetch(sources = ExternalDataSource.objects.filter(team_id=team_id).exclude(deleted=True)if source_ids is not None:sources = sources.filter(id__in=source_ids)- latest_job_ids = sources.values(- latest_job_id=Subquery(- ExternalDataJob.objects.filter(- pipeline=OuterRef("pk"), team_id=team_id, status=ExternalDataJobStatus.COMPLETED- )- .order_by("-created_at")- .values("id")[:1]- )- )+ latest_job_ids = sources.values(latest_job_id=latest_completed_job_subquery(team_id, "id"))return Prefetch(lookup, queryset=ExternalDataJob.objects.filter(id__in=latest_job_ids), to_attr=to_attr)diff --git a/products/warehouse_sources/backend/tests/test_facade.py b/products/warehouse_sources/backend/tests/test_facade.pyindex f9f5157a5653..ed12ae7f5185 100644--- a/products/warehouse_sources/backend/tests/test_facade.py+++ b/products/warehouse_sources/backend/tests/test_facade.py@@ -70,6 +70,19 @@ class TestWarehouseSourcesFacade(BaseTest):assert deleted.id not in {s.id for s in api.list_sources(self.team.pk)}assert deleted.id in {s.id for s in api.list_sources(self.team.pk, include_deleted=True)}+ def test_list_source_health_reports_the_newest_completed_run(self) -> None:+ ExternalDataJob.objects.create(team_id=self.team.pk, pipeline=self.source, status="Completed")+ newest = ExternalDataJob.objects.create(team_id=self.team.pk, pipeline=self.source, status="Completed")+ ExternalDataJob.objects.create(team_id=self.team.pk, pipeline=self.source, status="Running")+ self.schema.latest_error = "permission denied for table users"+ self.schema.save()++ results = api.list_source_health(self.team.pk)++ assert [r.source_type for r in results] == ["Postgres"]+ assert results[0].last_run_at == newest.created_at+ assert results[0].latest_error == "permission denied for table users"+def test_list_revenue_sources_maps_settings_schemas_and_tables(self) -> None:other_source = ExternalDataSource.objects.create(team_id=self.team.pk,