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(signals): surface last_run_at and latest_error on scout profile sources (#68645)

posthog[bot]e8aebb1dc2d2
diff --git a/products/signals/backend/scout_harness/profile/builders.py b/products/signals/backend/scout_harness/profile/builders.py
index 83adec4bf22e..6c483981b51d 100644
--- a/products/signals/backend/scout_harness/profile/builders.py
+++ b/products/signals/backend/scout_harness/profile/builders.py
@@ -29,7 +29,7 @@ import logging
from datetime import timedelta
from typing import Any
-from django.db.models import Count, F, Max, Q
+from django.db.models import Count, F, Max, OuterRef, Q, Subquery
from django.utils import timezone
from posthog.hogql import ast
@@ -61,7 +61,7 @@ from products.notebooks.backend.facade import api as notebooks
from products.signals.backend.models import SignalReport, SignalSourceConfig
from products.signals.backend.scout_harness.profile.schema import Inventory
from products.surveys.backend.models import Survey
-from products.warehouse_sources.backend.facade.models import ExternalDataSource
+from products.warehouse_sources.backend.facade.models import ExternalDataJob, ExternalDataSchema, ExternalDataSource
from products.workflows.backend.models.hog_flow.hog_flow import HogFlow
logger = logging.getLogger(__name__)
@@ -217,12 +217,30 @@ def _external_data_sources(team: Team) -> list[dict[str, Any]]:
"""Connected warehouse sources (Stripe, Postgres, BigQuery, etc.).
Excludes soft-deleted rows. `status` and `prefix` give the agent enough context to
- spot a stuck or recently-added source without exposing credentials.
+ spot a recently-added source without exposing credentials. `last_run_at` and
+ `latest_error` are what let a scout tell a healthy source apart from one stuck in
+ `Running`: source-level `status` conflates "sync in progress" with "never succeeded",
+ so a source that has never completed a sync reads as `Running` just like a healthy one.
+ `last_run_at` is the timestamp of the most recent completed sync job (null = never
+ synced); `latest_error` surfaces the newest schema-level error, if any. Both mirror the
+ semantics of the `external-data-sources-list` API so a scout can spot a dead source from
+ the 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=ExternalDataJob.Status.COMPLETED)),
+ latest_error=latest_error,
+ )
.order_by("source_type", "id")
- .values("source_type", "status", "prefix", "created_at")
+ .values("source_type", "status", "prefix", "created_at", "last_run_at", "latest_error")
)
return [
{
@@ -230,6 +248,8 @@ def _external_data_sources(team: Team) -> list[dict[str, Any]]:
"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"),
}
for row in rows
]
diff --git a/products/signals/backend/scout_harness/profile/schema.py b/products/signals/backend/scout_harness/profile/schema.py
index 976ac59d092c..266b71b198f2 100644
--- a/products/signals/backend/scout_harness/profile/schema.py
+++ b/products/signals/backend/scout_harness/profile/schema.py
@@ -50,6 +50,10 @@ class ExternalDataSourceEntry(_Section):
status: str
prefix: str
created_at: str | None
+ # `last_run_at` (most recent completed sync) and `latest_error` disambiguate a source stuck
+ # in `Running` that has never synced from a healthy one — `status` alone conflates them.
+ last_run_at: str | None
+ latest_error: str | None
class SignalSourceConfigEntry(_Section):
diff --git a/products/signals/backend/scout_harness/serializers.py b/products/signals/backend/scout_harness/serializers.py
index 069f04346e2f..ad57bb39dc94 100644
--- a/products/signals/backend/scout_harness/serializers.py
+++ b/products/signals/backend/scout_harness/serializers.py
@@ -823,6 +823,18 @@ class ExternalDataSourceEntrySerializer(serializers.Serializer):
allow_null=True,
help_text="ISO-8601 timestamp the source was connected.",
)
+ last_run_at = serializers.CharField(
+ allow_null=True,
+ help_text=(
+ "ISO-8601 timestamp of the most recent completed sync job, or null if this source has "
+ "never completed a sync. Use this to tell a healthy source apart from one stuck in "
+ "`Running` that has imported zero rows — `status` alone conflates the two."
+ ),
+ )
+ latest_error = serializers.CharField(
+ allow_null=True,
+ help_text="Newest schema-level sync error for this source, or null if no schema is erroring.",
+ )
class SignalSourceConfigEntrySerializer(serializers.Serializer):
diff --git a/products/signals/backend/test/test_scout_harness_profile.py b/products/signals/backend/test/test_scout_harness_profile.py
index 8e5b787e8df5..02ae8f8fc6f5 100644
--- a/products/signals/backend/test/test_scout_harness_profile.py
+++ b/products/signals/backend/test/test_scout_harness_profile.py
@@ -67,7 +67,7 @@ from products.signals.backend.scout_harness.tools.profile import (
get_project_profile,
)
from products.surveys.backend.models import Survey
-from products.warehouse_sources.backend.facade.models import ExternalDataSource
+from products.warehouse_sources.backend.facade.models import ExternalDataJob, ExternalDataSchema, ExternalDataSource
from products.workflows.backend.models.hog_flow.hog_flow import HogFlow
@@ -177,6 +177,30 @@ class TestExternalDataSources(BaseTest):
assert result[0]["status"] == "Failed"
assert result[0]["prefix"] == "pg_"
+ def test_last_run_at_none_when_never_completed_a_sync(self) -> None:
+ # A source stuck in `Running` that has never completed a sync must read as `last_run_at=None`
+ # so a scout can tell it apart from a healthy source — `status` alone conflates the two. Only
+ # a `Completed` job counts; a `Running` job present here must not populate `last_run_at`.
+ source = ExternalDataSource.objects.create(
+ team=self.team, source_type="BigQuery", status="Running", prefix="bq_"
+ )
+ ExternalDataJob.objects.create(team=self.team, pipeline=source, status=ExternalDataJob.Status.RUNNING)
+ result = _external_data_sources(self.team)
+ assert result[0]["last_run_at"] is None
+ assert result[0]["latest_error"] is None
+
+ def test_surfaces_last_run_at_and_latest_error(self) -> None:
+ source = ExternalDataSource.objects.create(
+ team=self.team, source_type="Stripe", status="Completed", prefix="stripe_"
+ )
+ job = ExternalDataJob.objects.create(team=self.team, pipeline=source, status=ExternalDataJob.Status.COMPLETED)
+ ExternalDataSchema.objects.create(
+ team=self.team, source=source, name="charges", latest_error="permission denied for table charges"
+ )
+ result = _external_data_sources(self.team)
+ assert result[0]["last_run_at"] == job.created_at.isoformat()
+ assert result[0]["latest_error"] == "permission denied for table charges"
+
class TestSignalSourceConfigs(BaseTest):
def test_splits_enabled_and_disabled(self) -> None:
diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.ts
index 203c34070c64..24b9b82ffa4d 100644
--- a/products/signals/frontend/generated/api.schemas.ts
+++ b/products/signals/frontend/generated/api.schemas.ts
@@ -1046,6 +1046,16 @@ export interface ExternalDataSourceEntryApi {
* @nullable
*/
created_at: string | null
+ /**
+ * ISO-8601 timestamp of the most recent completed sync job, or null if this source has never completed a sync. Use this to tell a healthy source apart from one stuck in `Running` that has imported zero rows — `status` alone conflates the two.
+ * @nullable
+ */
+ last_run_at: string | null
+ /**
+ * Newest schema-level sync error for this source, or null if no schema is erroring.
+ * @nullable
+ */
+ latest_error: string | null
}
/**
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 7c25cda51384..9731472829ff 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -24048,6 +24048,16 @@ export namespace Schemas {
* @nullable
*/
created_at: string | null;
+ /**
+ * ISO-8601 timestamp of the most recent completed sync job, or null if this source has never completed a sync. Use this to tell a healthy source apart from one stuck in `Running` that has imported zero rows — `status` alone conflates the two.
+ * @nullable
+ */
+ last_run_at: string | null;
+ /**
+ * Newest schema-level sync error for this source, or null if no schema is erroring.
+ * @nullable
+ */
+ latest_error: string | null;
}
export interface ExternalDataSourceRevenueAnalyticsConfig {