: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(warehouse-sources): derive source health status from schema states (#114260)
posthog[bot]fa7eddfeccd1
diff --git a/products/signals/backend/scout_harness/profile/builders.py b/products/signals/backend/scout_harness/profile/builders.pyindex 7645e8f79a80..e1760be556e5 100644--- a/products/signals/backend/scout_harness/profile/builders.py+++ b/products/signals/backend/scout_harness/profile/builders.py@@ -75,7 +75,7 @@ logger = logging.getLogger(__name__)# (or restructuring an existing one) without bumping the version would silently mix old# and new shapes in the cache. A redaction change bumps it too, so rows built before the# redaction stop being served.-INVENTORY_SOURCE_VERSION = "v14"+INVENTORY_SOURCE_VERSION = "v15"# Top-events ClickHouse query bounds. 7d is short enough to spot recent bursts and long# enough to stabilize counts on low-traffic teams; 50 covers the long tail withoutdiff --git a/products/warehouse_sources/backend/facade/api.py b/products/warehouse_sources/backend/facade/api.pyindex a16f64a3fc9e..14156c73525b 100644--- a/products/warehouse_sources/backend/facade/api.py+++ b/products/warehouse_sources/backend/facade/api.py@@ -18,11 +18,12 @@ exception is ``soft_delete_tables``: consumers may not iterate the model to call``soft_delete()`` themselves, so the facade does it for them."""+from collections import defaultdictfrom collections.abc import Collectionfrom typing import TYPE_CHECKINGfrom uuid import UUID-from django.db.models import OuterRef, Prefetch, QuerySet, Subquery+from django.db.models import OuterRef, Prefetch, Q, QuerySet, Subquery# Source-agnostic storage contract for user-uploaded files — shared with the upload endpoint.from products.warehouse_sources.backend.file_uploads import (@@ -64,6 +65,7 @@ from products.warehouse_sources.backend.models.util import (validate_source_prefix,validate_warehouse_table_url_pattern,)+from products.warehouse_sources.backend.source_status import effective_source_statusfrom products.warehouse_sources.backend.types import ExternalDataSourceTypefrom . import contracts@@ -93,6 +95,7 @@ __all__ = ["list_column_statistics","get_sync_alert_context",# framework-free helper transforms+ "effective_source_status","clickhouse_columns_to_dwh_columns","motherduck_columns_to_dwh_columns","trino_columns_to_dwh_columns",@@ -271,7 +274,9 @@ def list_sources(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.+ """Live sources with their effective status, newest completed run and newest schema error.++ The status rolls up the source's active schemas the same way the source list does.One correlated probe per source for each of the two lookups, so the cost tracks the numberof sources rather than the length of the team's job history.@@ -290,9 +295,26 @@ def list_source_health(team_id: int) -> list[contracts.ExternalDataSourceHealth]latest_error=latest_error,).order_by("source_type", "id")- .values("source_type", "status", "prefix", "created_at", "last_run_at", "latest_error")+ .values("id", "source_type", "status", "prefix", "created_at", "last_run_at", "latest_error"))- return [contracts.ExternalDataSourceHealth(**row) for row in rows]+ active_schemas_by_source: defaultdict[UUID, list[_ExternalDataSchema]] = defaultdict(list)+ for schema in (+ _ExternalDataSchema.objects.filter(team_id=team_id, deleted=False, source__deleted=False)+ .filter(Q(should_sync=True) | Q(latest_error__isnull=False))+ .only("source_id", "status", "should_sync")+ ):+ active_schemas_by_source[schema.source_id].append(schema)+ return [+ contracts.ExternalDataSourceHealth(+ source_type=row["source_type"],+ status=effective_source_status(active_schemas_by_source[row["id"]], fallback=row["status"]),+ prefix=row["prefix"],+ created_at=row["created_at"],+ last_run_at=row["last_run_at"],+ latest_error=row["latest_error"],+ )+ for row in rows+ ]def _revenue_source_queryset(diff --git a/products/warehouse_sources/backend/presentation/views/external_data_source/source_setup.py b/products/warehouse_sources/backend/presentation/views/external_data_source/source_setup.pyindex f10d0235adf6..720f68df1af8 100644--- a/products/warehouse_sources/backend/presentation/views/external_data_source/source_setup.py+++ b/products/warehouse_sources/backend/presentation/views/external_data_source/source_setup.py@@ -37,7 +37,7 @@ from products.data_warehouse.backend.facade.api import (is_any_external_data_schema_paused,is_custom_source_ai_builder_enabled_for_team,)-from products.warehouse_sources.backend.facade.api import validate_source_prefix+from products.warehouse_sources.backend.facade.api import effective_source_status, validate_source_prefixfrom products.warehouse_sources.backend.facade.models import (DataWarehouseTable,ExternalDataJob,@@ -320,36 +320,7 @@ class ExternalDataSourceSerializers(UserAccessControlSerializerMixin, serializerreturn list(instance.schemas.exclude(deleted=True).filter(Q(should_sync=True) | Q(latest_error__isnull=False)))def get_status(self, instance: ExternalDataSource) -> str:- active_schemas: list[ExternalDataSchema] = self._active_schemas(instance)- # Negative statuses should ignore schemas the user has disabled — those can linger in- # active_schemas via the latest_error prefetch but shouldn't drag the source into a failed state.- syncing_schemas = [schema for schema in active_schemas if schema.should_sync]- any_failures = any(schema.status == ExternalDataSchema.Status.FAILED for schema in syncing_schemas)- any_billing_limits_reached = any(- schema.status == ExternalDataSchema.Status.BILLING_LIMIT_REACHED for schema in syncing_schemas- )- any_billing_limits_too_low = any(- schema.status == ExternalDataSchema.Status.BILLING_LIMIT_TOO_LOW for schema in syncing_schemas- )- any_paused = any(schema.status == ExternalDataSchema.Status.PAUSED for schema in active_schemas)- any_running = any(schema.status == ExternalDataSchema.Status.RUNNING for schema in active_schemas)- any_completed = any(schema.status == ExternalDataSchema.Status.COMPLETED for schema in active_schemas)-- if any_failures:- return ExternalDataSchema.Status.FAILED- elif any_billing_limits_reached:- return "Billing limits"- elif any_billing_limits_too_low:- return "Billing limits too low"- elif any_paused:- return ExternalDataSchema.Status.PAUSED- elif any_running:- return ExternalDataSchema.Status.RUNNING- elif any_completed:- return ExternalDataSchema.Status.COMPLETED- else:- # Fallback during migration phase of going from source -> schema as the source of truth for syncs- return instance.status+ return effective_source_status(self._active_schemas(instance), fallback=instance.status)@extend_schema_field(serializers.CharField(allow_null=True))def get_latest_error(self, instance: ExternalDataSource):diff --git a/products/warehouse_sources/backend/source_status.py b/products/warehouse_sources/backend/source_status.pynew file mode 100644index 000000000000..160996d21a0e--- /dev/null+++ b/products/warehouse_sources/backend/source_status.py@@ -0,0 +1,48 @@+"""Effective sync status of a source, derived from the states of its schemas.++The stored `ExternalDataSource.status` column is not kept current as schemas sync, so a source+whose schemas all completed can still read `Running`. Every reader that reports a source's+status uses `effective_source_status`, so the source list, the source detail and the scout+project profile agree about the same source.+"""++from collections.abc import Iterable+from typing import Protocol++from products.warehouse_sources.backend.facade.types import ExternalDataSchemaStatus++BILLING_LIMITS_STATUS = "Billing limits"+BILLING_LIMITS_TOO_LOW_STATUS = "Billing limits too low"+++class SchemaSyncState(Protocol):+ @property+ def status(self) -> str | None: ...++ @property+ def should_sync(self) -> bool: ...+++def effective_source_status(active_schemas: Iterable[SchemaSyncState], *, fallback: str) -> str:+ """Roll the states of a source's active schemas up into one source status.++ `active_schemas` are the non-deleted schemas that sync or carry an error. Only a schema that+ still syncs can make the source fail: a disabled schema can keep an old error. `fallback` is+ the stored source status, used only when no schema has a known state.+ """+ schemas = list(active_schemas)+ syncing = [schema for schema in schemas if schema.should_sync]++ if any(schema.status == ExternalDataSchemaStatus.FAILED for schema in syncing):+ return ExternalDataSchemaStatus.FAILED+ if any(schema.status == ExternalDataSchemaStatus.BILLING_LIMIT_REACHED for schema in syncing):+ return BILLING_LIMITS_STATUS+ if any(schema.status == ExternalDataSchemaStatus.BILLING_LIMIT_TOO_LOW for schema in syncing):+ return BILLING_LIMITS_TOO_LOW_STATUS+ if any(schema.status == ExternalDataSchemaStatus.PAUSED for schema in schemas):+ return ExternalDataSchemaStatus.PAUSED+ if any(schema.status == ExternalDataSchemaStatus.RUNNING for schema in schemas):+ return ExternalDataSchemaStatus.RUNNING+ if any(schema.status == ExternalDataSchemaStatus.COMPLETED for schema in schemas):+ return ExternalDataSchemaStatus.COMPLETED+ return fallbackdiff --git a/products/warehouse_sources/backend/tests/test_facade.py b/products/warehouse_sources/backend/tests/test_facade.pyindex 915d55352dfc..1140c447d5df 100644--- a/products/warehouse_sources/backend/tests/test_facade.py+++ b/products/warehouse_sources/backend/tests/test_facade.py@@ -20,6 +20,9 @@ from products.warehouse_sources.backend.models.external_data_job import Externalfrom products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchemafrom products.warehouse_sources.backend.models.external_data_source import ExternalDataSourcefrom products.warehouse_sources.backend.models.table import DataWarehouseTable+from products.warehouse_sources.backend.presentation.views.external_data_source.source_setup import (+ ExternalDataSourceSerializers,+)class TestWarehouseSourcesFacade(BaseTest):@@ -87,6 +90,61 @@ class TestWarehouseSourcesFacade(BaseTest):assert results[0].last_run_at == newest.created_atassert results[0].latest_error == "permission denied for table users"+ @parameterized.expand(+ [+ ("all_completed", [(ExternalDataSchema.Status.COMPLETED, True)], "Completed"),+ (+ "one_running",+ [(ExternalDataSchema.Status.COMPLETED, True), (ExternalDataSchema.Status.RUNNING, True)],+ "Running",+ ),+ (+ "one_failed",+ [(ExternalDataSchema.Status.COMPLETED, True), (ExternalDataSchema.Status.FAILED, True)],+ "Failed",+ ),+ (+ "failed_but_disabled",+ [(ExternalDataSchema.Status.COMPLETED, True), (ExternalDataSchema.Status.FAILED, False)],+ "Completed",+ ),+ (+ "billing_limit_reached",+ [(ExternalDataSchema.Status.COMPLETED, True), (ExternalDataSchema.Status.BILLING_LIMIT_REACHED, True)],+ "Billing limits",+ ),+ (+ "one_paused",+ [(ExternalDataSchema.Status.COMPLETED, True), (ExternalDataSchema.Status.PAUSED, True)],+ "Paused",+ ),+ ("no_schema_state", [(None, True)], "Running"),+ ]+ )+ def test_list_source_health_status_matches_source_list(+ self, _name: str, schema_states: list[tuple[str | None, bool]], expected: str+ ) -> None:+ self.source.status = "Running"+ self.source.save()+ self.schema.delete()+ for index, (status, should_sync) in enumerate(schema_states):+ ExternalDataSchema.objects.create(+ team_id=self.team.pk,+ source=self.source,+ name=f"schema_{index}",+ should_sync=should_sync,+ status=status,+ latest_error=None if should_sync else "old error",+ )++ [health] = api.list_source_health(self.team.pk)+ serializer_status = ExternalDataSourceSerializers(context={"get_team": lambda: self.team}).get_status(+ self.source+ )++ assert health.status == expected+ assert serializer_status == expected+def test_list_revenue_sources_maps_settings_schemas_and_tables(self) -> None:other_source = ExternalDataSource.objects.create(team_id=self.team.pk,