: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): stop reporting a quiet schema as a stalled schedule (#104706)
posthog[bot]d2a0c9b18a70
diff --git a/products/data_warehouse/backend/sync_status.py b/products/data_warehouse/backend/sync_status.pyindex aa1d39732b58..d450960e406f 100644--- a/products/data_warehouse/backend/sync_status.py+++ b/products/data_warehouse/backend/sync_status.py@@ -32,39 +32,10 @@ _BILLING_LIMIT_REASONS: dict[str, str] = {}-def _last_run_at(schema: ExternalDataSchema) -> datetime | None:- """When a sync last ran to completion, whether or not it moved any rows.-- `last_synced_at` alone answers a narrower question. It is the signals watermark- (`partition_field > last_synced_at`) as well as a display value, so the v3 pipeline- deliberately leaves it where it is when a run extracts nothing — advancing it would- narrow the next run's signal window past rows that arrive late. Such a run stamps only- `last_full_run_at`, so a schema whose source is simply quiet reads here as having run.-- Both are consulted because neither covers every path on its own: a fast return writes- `last_synced_at` and not `last_full_run_at`, and a v3 zero-batch run does the reverse.- """- stamped: datetime | None = None- raw = schema.last_full_run_at- if raw is not None:- try:- parsed = datetime.fromisoformat(raw)- except (TypeError, ValueError):- parsed = None- # A naive stamp cannot be compared against `now`, and guessing its zone would- # invent freshness. Mirrors `_fast_return_eligible`, which rejects one outright.- if parsed is not None and parsed.tzinfo is not None:- stamped = parsed-- synced = ensure_utc(schema.last_synced_at) if schema.last_synced_at is not None else None- candidates = [value for value in (synced, stamped) if value is not None]- return max(candidates) if candidates else None--def _is_stale(schema: ExternalDataSchema, now: datetime) -> bool:"""Stale once the last sync run is older than 2x the cadence; unknown cadence or never-run is not stale."""interval = schema.sync_frequency_interval- last_run = _last_run_at(schema)+ last_run = schema.last_run_atif interval is None or last_run is None:return Falsereturn (now - last_run) > interval * STALE_RUNNING_MULTIPLIERdiff --git a/products/warehouse_sources/backend/models/external_data_schema.py b/products/warehouse_sources/backend/models/external_data_schema.pyindex 202e26effb6f..2f3d48ea9123 100644--- a/products/warehouse_sources/backend/models/external_data_schema.py+++ b/products/warehouse_sources/backend/models/external_data_schema.py@@ -503,6 +503,31 @@ class ExternalDataSchema(ModelActivityMixin, CreatedMetaFields, UpdatedMetaFieldreturn None+ @property+ def last_full_run(self) -> datetime | None:+ """Parsed `last_full_run_at`, or None when it does not parse or has no zone.++ Picking a zone for a naive stamp would invent freshness the schema may not have.+ """+ raw = self.last_full_run_at+ if raw is None:+ return None+ try:+ stamped = datetime.fromisoformat(raw)+ except (TypeError, ValueError):+ return None+ return stamped if stamped.tzinfo is not None else None++ @property+ def last_run_at(self) -> datetime | None:+ """When a sync last ran, whether or not it moved any rows.++ A run that extracts nothing advances only `last_full_run_at`, because `last_synced_at` is+ also the signals watermark. A fast return does the reverse, so neither stamp is enough alone.+ """+ stamps = [stamp for stamp in (self.last_synced_at, self.last_full_run) if stamp is not None]+ return max(stamps) if stamps else None+@propertydef incremental_field_lookback_seconds(self) -> int | None:if self.sync_type_config:diff --git a/products/warehouse_sources/backend/stalled_schedules.py b/products/warehouse_sources/backend/stalled_schedules.pyindex 1971d8182232..de00416432ed 100644--- a/products/warehouse_sources/backend/stalled_schedules.py+++ b/products/warehouse_sources/backend/stalled_schedules.py@@ -17,8 +17,9 @@ periodic sweep that reports them and the management command that repairs them.from datetime import timedelta-from django.db.models import DateTimeField, DurationField, ExpressionWrapper, F, QuerySet, Value-from django.db.models.functions import Coalesce, Greatest+from django.db.models import Case, DateTimeField, DurationField, ExpressionWrapper, F, QuerySet, Value, When+from django.db.models.fields.json import KeyTextTransform+from django.db.models.functions import Cast, Coalesce, Greatestfrom django.utils import timezoneimport structlog@@ -53,6 +54,11 @@ SELF_REPORTING_STATUSES = (ExternalDataSchema.Status.PAUSED,)+# `last_full_run_at` is free-form JSON. Postgres raises on a cast it cannot parse and reads a naive+# stamp in the session zone, so only an ISO stamp with an offset is cast, as in+# `ExternalDataSchema.last_full_run`.+_AWARE_ISO_TIMESTAMP = r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?([+-]\d{2}:\d{2}|Z)$"+# Replaces the stale Running status on a repaired schema. The row keeps a visible record of the# gap, and the schema's own next tick clears it.REPAIRED_SCHEMA_ERROR = (@@ -133,12 +139,25 @@ def stalled_schema_queryset(missed_intervals: int = DEFAULT_MISSED_INTERVALS,min_stall: timedelta = DEFAULT_MIN_STALL,) -> QuerySet[ExternalDataSchema]:- """Schemas whose last successful sync is older than their own cadence allows.+ """Schemas whose last run is older than their own cadence allows.The window scales with `sync_frequency_interval` because a fixed one cannot serve both afive-minute schema and a daily one. A daily schema therefore needs days of silence toqualify, which is the cost of not flagging every schema that merely ran slowly.++ The window runs from the later of `last_synced_at` and `last_full_run_at`, because a run+ that imports nothing advances only the second (see `ExternalDataSchema.last_run_at`)."""+ # NULL for a missing or unusable stamp. Postgres GREATEST skips NULLs, so `latest_run_at` then+ # falls back to `last_synced_at`.+ last_full_run = Case(+ When(+ sync_type_config__last_full_run_at__regex=_AWARE_ISO_TIMESTAMP,+ then=Cast(KeyTextTransform("last_full_run_at", "sync_type_config"), DateTimeField()),+ ),+ default=None,+ output_field=DateTimeField(),+ )stall_window = ExpressionWrapper(Greatest(Coalesce(F("sync_frequency_interval"), Value(FALLBACK_SYNC_INTERVAL)) * missed_intervals,@@ -166,9 +185,10 @@ def stalled_schema_queryset(# key evaluates to SQL NULL, and `.exclude()` compiles to `NOT (...)` — NOT NULL is NULL,# not TRUE, so Postgres drops the row from the result entirely instead of keeping it.# That silently wipes out every schema without the key, not just the ones carrying it.+ .annotate(latest_run_at=Greatest(F("last_synced_at"), last_full_run, output_field=DateTimeField())).annotate(stalled_after=ExpressionWrapper(- F("last_synced_at") + stall_window,+ F("latest_run_at") + stall_window,output_field=DateTimeField(),))@@ -190,7 +210,7 @@ def find_stalled_schemas(if source_type is not None:queryset = queryset.filter(source__source_type__iexact=source_type)- queryset = queryset.select_related("source").order_by("last_synced_at")+ queryset = queryset.select_related("source").order_by("latest_run_at")if limit is not None:queryset = queryset[:limit]@@ -210,10 +230,6 @@ def find_stalled_schemas(now = timezone.now()stalled = []for schema in schemas:- # The queryset already excludes a null stamp. The check is here because the column is- # nullable, so the subtraction below has no other way to know.- if schema.last_synced_at is None:- continue# Streaming CDC and cdc_halted are excluded here rather than in the queryset (see the# comment there): a paused per-schema schedule is streaming CDC's steady state, and# cdc_halted exists precisely to keep everything else off the schedule until repair_cdc@@ -232,7 +248,7 @@ def find_stalled_schemas(source_id=str(schema.source_id),source_type=schema.source.source_type,kind="stuck_job" if schema.id in schemas_with_running_jobs else "no_runs",- stalled_for=now - schema.last_synced_at,+ stalled_for=now - schema.latest_run_at, # type: ignore[attr-defined]cdc_ingest_mode=(schema.source.job_inputs or {}).get("cdc_ingest_mode", "legacy"),admin_paused=bool((schema.sync_type_config or {}).get("admin_unpause_schedule_after_run")),has_sync_interval=schema.sync_frequency_interval is not None,diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/pipeline.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/pipeline.pyindex 46e5d946c685..754e02be223b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/pipeline.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/pipeline.py@@ -603,7 +603,7 @@ class PipelineV3(Generic[ResumableData]):async def _stamp_full_run(self) -> None:"""Record that this run took the full extraction path, for the fast-return valve.- Writes only `last_full_run_at`, which `_fast_return_eligible` is the sole reader of.+ Writes only `last_full_run_at`.`last_synced_at` is deliberately left alone: it feeds data freshness, the schemas UI andthe signals watermark (`partition_field > last_synced_at`), so moving it on a run thatloaded nothing would narrow the next run's signal window.diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/create_job_model.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/create_job_model.pyindex 8fe61a780b4b..8f77d09d362d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/create_job_model.py+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/create_job_model.py@@ -279,14 +279,8 @@ def _fast_return_eligible(if data_quality_checks_needed_for(team_id, schema.table_id):return False- last_full_run_at = schema.last_full_run_at- if last_full_run_at is None:- return False- try:- stamped = dt.datetime.fromisoformat(last_full_run_at)- except (TypeError, ValueError):- return False- if stamped.tzinfo is None:+ stamped = schema.last_full_run+ if stamped is None:return Falsereturn dt.datetime.now(dt.UTC) - stamped < FAST_RETURN_FULL_RUN_INTERVALdiff --git a/products/warehouse_sources/backend/tests/test_stalled_schedules.py b/products/warehouse_sources/backend/tests/test_stalled_schedules.pyindex f593268942e6..c911b131e867 100644--- a/products/warehouse_sources/backend/tests/test_stalled_schedules.py+++ b/products/warehouse_sources/backend/tests/test_stalled_schedules.py@@ -107,6 +107,37 @@ class TestStalledSchedules(BaseTest):assert str(schema.id) not in found+ def test_a_schema_whose_runs_found_nothing_to_import_is_not_stalled(self) -> None:+ self._schema(+ synced_ago=timedelta(days=5),+ sync_type_config={"last_full_run_at": (timezone.now() - timedelta(hours=1)).isoformat()},+ )+ stalled = self._schema(synced_ago=timedelta(days=4))++ assert [s.schema_id for s in find_stalled_schemas(limit=1)] == [str(stalled.id)]++ def test_a_schema_whose_runs_also_stopped_is_still_stalled(self) -> None:+ schema = self._schema(+ synced_ago=timedelta(days=5),+ sync_type_config={"last_full_run_at": (timezone.now() - timedelta(days=4)).isoformat()},+ )++ stalled = [s for s in find_stalled_schemas() if s.schema_id == str(schema.id)]++ assert len(stalled) == 1+ assert timedelta(days=4) <= stalled[0].stalled_for < timedelta(days=5)++ @parameterized.expand(+ [+ ("unparseable", "whenever"),+ ("naive", (timezone.now() - timedelta(hours=1)).replace(tzinfo=None).isoformat()),+ ]+ )+ def test_an_unusable_run_stamp_falls_back_to_the_sync_stamp(self, _name: str, stamp: str) -> None:+ schema = self._schema(synced_ago=timedelta(days=5), sync_type_config={"last_full_run_at": stamp})++ assert str(schema.id) in {s.schema_id for s in find_stalled_schemas()}+def test_a_schema_with_a_running_job_is_a_wedged_run_not_a_stalled_schedule(self) -> None:schema = self._schema(synced_ago=timedelta(days=5))ExternalDataJob.objects.create(