: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(data-warehouse): report warehouse import status from sink apply events (#71309)
Eric Duong7febd1da04f2
diff --git a/frontend/src/scenes/data-warehouse/scene/OverviewTab.tsx b/frontend/src/scenes/data-warehouse/scene/OverviewTab.tsxindex 788818896226..ad667dc9ff40 100644--- a/frontend/src/scenes/data-warehouse/scene/OverviewTab.tsx+++ b/frontend/src/scenes/data-warehouse/scene/OverviewTab.tsx@@ -110,13 +110,6 @@ export function OverviewTab(): JSX.Element {render: (_, source) => `${source.backfilled_schemas} / ${source.total_schemas}`,sorter: (a, b) => a.backfilled_schemas / a.total_schemas - b.backfilled_schemas / b.total_schemas,},- {- title: 'Pending imports',- dataIndex: 'pending_batches',- render: (pendingBatches) =>- typeof pendingBatches === 'number' ? pendingBatches.toLocaleString() : 'Unavailable',- sorter: (a, b) => (a.pending_batches ?? -1) - (b.pending_batches ?? -1),- },{title: 'Last source import',dataIndex: 'last_synced_at',@@ -124,6 +117,13 @@ export function OverviewTab(): JSX.Element {typeof lastSyncedAt === 'string' ? humanFriendlyDetailedTime(lastSyncedAt) : 'Not synced yet',sorter: (a, b) => new Date(a.last_synced_at ?? 0).getTime() - new Date(b.last_synced_at ?? 0).getTime(),},+ {+ title: 'Applied to warehouse',+ dataIndex: 'last_applied_at',+ render: (lastAppliedAt) =>+ typeof lastAppliedAt === 'string' ? humanFriendlyDetailedTime(lastAppliedAt) : 'Not recorded yet',+ sorter: (a, b) => new Date(a.last_applied_at ?? 0).getTime() - new Date(b.last_applied_at ?? 0).getTime(),+ },]if (managedWarehouseDataStatusLoading && !managedWarehouseDataStatus) {diff --git a/frontend/src/scenes/data-warehouse/scene/managedWarehouseDataStatusLogic.ts b/frontend/src/scenes/data-warehouse/scene/managedWarehouseDataStatusLogic.tsindex 1a0b22449a49..ec8a3b48a6be 100644--- a/frontend/src/scenes/data-warehouse/scene/managedWarehouseDataStatusLogic.ts+++ b/frontend/src/scenes/data-warehouse/scene/managedWarehouseDataStatusLogic.ts@@ -11,7 +11,7 @@ import type {const ACTIVE_REFRESH_INTERVAL_MS = 15_000const STABLE_REFRESH_INTERVAL_MS = 60_000-const ACTIVE_STATES: ManagedWarehouseReadinessStateEnumApi[] = ['waiting', 'backfilling', 'catching_up']+const ACTIVE_STATES: ManagedWarehouseReadinessStateEnumApi[] = ['waiting', 'backfilling']// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface managedWarehouseDataStatusLogicValues {diff --git a/frontend/src/scenes/data-warehouse/scene/warehouseStatusDisplay.tsx b/frontend/src/scenes/data-warehouse/scene/warehouseStatusDisplay.tsxindex 9fca891ca6bc..134bf2ff9625 100644--- a/frontend/src/scenes/data-warehouse/scene/warehouseStatusDisplay.tsx+++ b/frontend/src/scenes/data-warehouse/scene/warehouseStatusDisplay.tsx@@ -14,10 +14,8 @@ export const STATUS_LABELS: Record<ManagedWarehouseReadinessStateEnumApi, stringnot_configured: 'Not configured',waiting: 'Waiting',backfilling: 'Backfilling',- catching_up: 'Catching up',up_to_date: 'Up to date',needs_attention: 'Needs attention',- unknown: 'Status unavailable',sync_paused: 'Sync paused',}@@ -25,10 +23,8 @@ export const STATUS_TAG_TYPES: Record<ManagedWarehouseReadinessStateEnumApi, Lemnot_configured: 'muted',waiting: 'warning',backfilling: 'primary',- catching_up: 'primary',up_to_date: 'success',needs_attention: 'danger',- unknown: 'muted',sync_paused: 'default',}@@ -36,12 +32,10 @@ export const STATUS_TAG_TYPES: Record<ManagedWarehouseReadinessStateEnumApi, Lemexport const STATUS_SEVERITY: Record<ManagedWarehouseReadinessStateEnumApi, number> = {needs_attention: 0,backfilling: 1,- catching_up: 2,- waiting: 3,- unknown: 4,- sync_paused: 5,- up_to_date: 6,- not_configured: 7,+ waiting: 2,+ sync_paused: 3,+ up_to_date: 4,+ not_configured: 5,}export function StatusTag({ readinessState }: { readinessState: ManagedWarehouseReadinessStateEnumApi }): JSX.Element {@@ -73,14 +67,6 @@ export const sourceSchemaColumns: LemonTableColumns<ManagedWarehouseSourceTableSrender: (_, table) =>table.total_chunks ? `${table.completed_chunks} / ${table.total_chunks} chunks` : 'No active backfill',},- {- title: 'Pending imports',- dataIndex: 'pending_batches',- render: (pendingBatches) =>- typeof pendingBatches === 'number' ? pendingBatches.toLocaleString() : 'Unavailable',- // Unavailable counts sort last rather than as zero, which would read as "nothing pending".- sorter: (a, b) => (a.pending_batches ?? -1) - (b.pending_batches ?? -1),- },{title: 'Last source import',dataIndex: 'last_synced_at',@@ -88,4 +74,11 @@ export const sourceSchemaColumns: LemonTableColumns<ManagedWarehouseSourceTableStypeof lastSyncedAt === 'string' ? humanFriendlyDetailedTime(lastSyncedAt) : 'Not synced yet',sorter: (a, b) => new Date(a.last_synced_at ?? 0).getTime() - new Date(b.last_synced_at ?? 0).getTime(),},+ {+ title: 'Applied to warehouse',+ dataIndex: 'last_applied_at',+ render: (lastAppliedAt) =>+ typeof lastAppliedAt === 'string' ? humanFriendlyDetailedTime(lastAppliedAt) : 'Not recorded yet',+ sorter: (a, b) => new Date(a.last_applied_at ?? 0).getTime() - new Date(b.last_applied_at ?? 0).getTime(),+ },]diff --git a/posthog/ducklake/models.py b/posthog/ducklake/models.pyindex 7d5cec7473b2..516ccc6361d8 100644--- a/posthog/ducklake/models.py+++ b/posthog/ducklake/models.py@@ -176,6 +176,13 @@ class DuckgresSinkSchemaState(CreatedMetaFields, UpdatedMetaFields, UUIDModel):db_constraint=False,)+ # When the sink last applied a live (non-backfill) imported batch to duckgres for this+ # schema, stamped by the sink at apply time. The web tier reads it from the main DB so+ # the Data ops UI can report import activity without querying the warehouse-sources+ # queue DB (which it has no access to). NULL = no live apply recorded since this field+ # shipped. It's an event timestamp, not a liveness signal — history, never "stale".+ queue_last_applied_at = models.DateTimeField(null=True, blank=True)+class Meta:db_table = "posthog_duckgressinkschemastate"verbose_name = "Duckgres sink schema state"diff --git a/posthog/migrations/1258_duckgressinkschemastate_queue_last_applied_at.py b/posthog/migrations/1258_duckgressinkschemastate_queue_last_applied_at.pynew file mode 100644index 000000000000..d7a6cb470c39--- /dev/null+++ b/posthog/migrations/1258_duckgressinkschemastate_queue_last_applied_at.py@@ -0,0 +1,15 @@+# Generated by Django 5.2.14 on 2026-07-15 22:31++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [("posthog", "1257_datadeletionrequest_approved_automatically_and_more")]++ operations = [+ migrations.AddField(+ model_name="duckgressinkschemastate",+ name="queue_last_applied_at",+ field=models.DateTimeField(blank=True, null=True),+ ),+ ]diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txtindex 1f9d749e4cec..1b7bef7b2072 100644--- a/posthog/migrations/max_migration.txt+++ b/posthog/migrations/max_migration.txt@@ -1 +1 @@-1257_datadeletionrequest_approved_automatically_and_more+1258_duckgressinkschemastate_queue_last_applied_atdiff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex 5b02bf579e5b..3bfe51683f6d 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -624,10 +624,8 @@ SPECTACULAR_SETTINGS = {"not_configured","waiting","backfilling",- "catching_up","up_to_date","needs_attention",- "unknown","sync_paused",],# Full signal taxonomy on the report `signals` endpoint; the source-config serializer'sdiff --git a/products/data_warehouse/backend/logic/managed_warehouse_data_status.py b/products/data_warehouse/backend/logic/managed_warehouse_data_status.pyindex 947d32d4e408..793967fe6024 100644--- a/products/data_warehouse/backend/logic/managed_warehouse_data_status.py+++ b/products/data_warehouse/backend/logic/managed_warehouse_data_status.py@@ -1,39 +1,25 @@from __future__ import annotations-from datetime import datetime, timedelta+from datetime import datetimefrom typing import Literal, TypedDict-from django.db import DatabaseError-from django.db.models import Count, Exists, Max, Min, OuterRef, Q, Subqueryfrom django.utils import timezone-import structlog-from posthog.ducklake.models import DuckgresServerTeam, DuckgresSinkSchemaStatefrom products.data_warehouse.backend.logic.backfill_status import historical_backfill_monthsfrom products.data_warehouse.backend.models import ManagedWarehouseBackfillPartitionfrom products.warehouse_sources.backend.facade.models import ExternalDataSchema-from products.warehouse_sources_queue.backend.models import (- SourceBatch,- SourceBatchDuckgresApply,- SourceBatchDuckgresStatus,-)--logger = structlog.get_logger(__name__)ReadinessState = Literal["not_configured","waiting","backfilling",- "catching_up","up_to_date","needs_attention",- "unknown","sync_paused",]-QUEUE_RETENTION_DAYS = 14PERSISTENT_BACKFILL_FAILURES = 3# sync_paused ranks below every active-work or failure state (those are still worth surfacing even# on a paused schema's source) but above up_to_date: a source with some schemas paused shouldn't@@ -41,9 +27,7 @@ PERSISTENT_BACKFILL_FAILURES = 3READINESS_PRIORITY: tuple[ReadinessState, ...] = ("needs_attention","backfilling",- "catching_up","waiting",- "unknown","sync_paused","up_to_date",)@@ -72,8 +56,8 @@ class SourceTableStatus(TypedDict):backfilled: boolcompleted_chunks: inttotal_chunks: int | None- pending_batches: int | None- oldest_pending_at: datetime | None+ # When the sink last applied a live imported batch to the warehouse — an event+ # timestamp stamped by the sink at apply time, not a derived liveness signal.last_applied_at: datetime | Nonelast_synced_at: datetime | None@@ -86,7 +70,7 @@ class SourceSummary(TypedDict):detail: strtotal_schemas: intbackfilled_schemas: int- pending_batches: int | None+ last_applied_at: datetime | Nonelast_synced_at: datetime | None@@ -104,12 +88,6 @@ class ManagedWarehouseDataStatus(TypedDict):generated_at: datetime-class QueueTailStatus(TypedDict):- pending_batches: int- oldest_pending_at: datetime | None- last_applied_at: datetime | None--def _event_historical_partition_count(backfill: DuckgresServerTeam) -> int | None:if backfill.earliest_event_date is None:return None@@ -202,78 +180,14 @@ def dataset_status(}-def _queue_tail_statuses(team_id: int, schema_ids: list[str]) -> dict[str, QueueTailStatus] | None:- if not schema_ids:- return {}+def source_table_readiness(state: DuckgresSinkSchemaState) -> tuple[ReadinessState, str]:+ """Readiness derived purely from events the sink jobs recorded at the time of the work.- try:- queue_cutoff = timezone.now() - timedelta(days=QUEUE_RETENTION_DAYS)- latest_duckgres_state = Subquery(- SourceBatchDuckgresStatus.objects.filter(- batch_id=OuterRef("pk"),- created_at__gte=queue_cutoff - timedelta(days=QUEUE_RETENTION_DAYS),- )- .order_by("-created_at", "-id")- .values("job_state")[:1]- )- has_apply = Exists(- SourceBatchDuckgresApply.objects.for_team(team_id).filter(- schema_id=OuterRef("schema_id"),- run_uuid=OuterRef("run_uuid"),- batch_index=OuterRef("batch_index"),- )- )- pending_rows = (- SourceBatch.objects.filter(- team_id=team_id,- schema_id__in=schema_ids,- latest_state=SourceBatch.LatestState.SUCCEEDED,- is_final_batch=False,- created_at__gte=queue_cutoff,- )- .annotate(latest_duckgres_state=latest_duckgres_state, has_apply=has_apply)- .filter(has_apply=False)- .filter(- Q(latest_duckgres_state__isnull=True)- | Q(- latest_duckgres_state__in=[- SourceBatchDuckgresStatus.State.EXECUTING,- SourceBatchDuckgresStatus.State.WAITING_RETRY,- ]- )- )- .values("schema_id")- .annotate(pending_batches=Count("id"), oldest_pending_at=Min("created_at"))- )- applied_rows = (- SourceBatchDuckgresApply.objects.for_team(team_id)- .filter(schema_id__in=schema_ids, created_at__gte=queue_cutoff)- .values("schema_id")- .annotate(last_applied_at=Max("created_at"))- )- statuses: dict[str, QueueTailStatus] = {- schema_id: {- "pending_batches": 0,- "oldest_pending_at": None,- "last_applied_at": None,- }- for schema_id in schema_ids- }- for row in pending_rows:- schema_id = str(row["schema_id"])- statuses[schema_id]["pending_batches"] = int(row["pending_batches"])- statuses[schema_id]["oldest_pending_at"] = row["oldest_pending_at"]- for row in applied_rows:- statuses[str(row["schema_id"])]["last_applied_at"] = row["last_applied_at"]- return statuses- except DatabaseError:- logger.exception("managed_warehouse_queue_status_unavailable", team_id=team_id)- return None---def source_table_readiness(- state: DuckgresSinkSchemaState, queue_status: QueueTailStatus | None, queue_available: bool-) -> tuple[ReadinessState, str]:+ There is deliberately no liveness inference here (no pending counts, no staleness+ windows): the backfill lifecycle fields are written by the planner/backfill jobs, and+ the last live apply is stamped by the sink at apply time — the UI reports what ran+ and when, nothing more.+ """if (state.state == DuckgresSinkSchemaState.State.NEEDS_RESYNCor state.consecutive_failures >= PERSISTENT_BACKFILL_FAILURES@@ -285,13 +199,7 @@ def source_table_readiness(if state.chunk_count:return "backfilling", f"Copied {state.chunks_applied} of {state.chunk_count} backfill chunks."return "backfilling", "Existing rows are being copied into the warehouse."- if not queue_available:- return "unknown", "Live import status is temporarily unavailable."- if queue_status and queue_status["pending_batches"] > 0:- count = queue_status["pending_batches"]- suffix = "batch" if count == 1 else "batches"- return "catching_up", f"Applying {count} imported {suffix} to the warehouse."- return "up_to_date", "Imported data is up to date."+ return "up_to_date", "New imports are applied to the warehouse as they arrive."def _schema_table_statuses(team_id: int, *, source_id: str | None = None) -> list[SourceTableStatus]:@@ -322,17 +230,13 @@ def _schema_table_statuses(team_id: int, *, source_id: str | None = None) -> lisstr(schema.id): schema for schema in ExternalDataSchema.objects.filter(**schema_filter).select_related("source")}visible_states = [state for state in states if str(state.schema_id) in schema_by_id]- schema_ids = [str(state.schema_id) for state in visible_states]- queue_statuses = _queue_tail_statuses(team_id, schema_ids)- queue_available = queue_statuses is not Nonetables: list[SourceTableStatus] = []for state in visible_states:schema_id = str(state.schema_id)schema = schema_by_id[schema_id]- queue_status = queue_statuses.get(schema_id) if queue_statuses is not None else Noneif schema.should_sync:- readiness_state, detail = source_table_readiness(state, queue_status, queue_available)+ readiness_state, detail = source_table_readiness(state)else:# Paused wins over whatever the sink state says: a stale failure streak from before# the pause isn't actionable while nothing is actively importing for this table.@@ -352,9 +256,7 @@ def _schema_table_statuses(team_id: int, *, source_id: str | None = None) -> lis"backfilled": state.state == DuckgresSinkSchemaState.State.PRIMED,"completed_chunks": state.chunks_applied,"total_chunks": state.chunk_count,- "pending_batches": queue_status["pending_batches"] if queue_status is not None else None,- "oldest_pending_at": queue_status["oldest_pending_at"] if queue_status is not None else None,- "last_applied_at": queue_status["last_applied_at"] if queue_status is not None else None,+ "last_applied_at": state.queue_last_applied_at,"last_synced_at": schema.last_synced_at,})@@ -369,11 +271,9 @@ def get_source_schema_statuses(team_id: int, source_id: str) -> list[SourceTable_SOURCE_SUMMARY_DETAILS: dict[ReadinessState, str] = {"needs_attention": "One or more schemas need attention.","backfilling": "Historical rows are being copied for one or more schemas.",- "catching_up": "Recent imports are still being applied for one or more schemas.","waiting": "One or more schemas are waiting to start.",- "unknown": "Live import status is temporarily unavailable for one or more schemas.","sync_paused": "Sync is paused for one or more schemas.",- "up_to_date": "All schemas are up to date.",+ "up_to_date": "New imports are applied to the warehouse as they arrive.","not_configured": "No schemas are configured for this source.",}@@ -386,10 +286,8 @@ def _rollup_sources(tables: list[SourceTableStatus]) -> list[SourceSummary]:summaries: list[SourceSummary] = []for source_id, rows in grouped.items():readiness_state = _roll_up_state([row["readiness_state"] for row in rows])- # pending_batches is uniformly None (queue check failed) or uniformly an int across a- # team's rows, since _queue_tail_statuses either fails for all schemas or none.- pending_batches = (- None if rows[0]["pending_batches"] is None else sum(row["pending_batches"] or 0 for row in rows)+ last_applied_at = max(+ (row["last_applied_at"] for row in rows if row["last_applied_at"] is not None), default=None)last_synced_at = max((row["last_synced_at"] for row in rows if row["last_synced_at"] is not None), default=None)summaries.append(@@ -401,7 +299,7 @@ def _rollup_sources(tables: list[SourceTableStatus]) -> list[SourceSummary]:"detail": _SOURCE_SUMMARY_DETAILS[readiness_state],"total_schemas": len(rows),"backfilled_schemas": sum(1 for row in rows if row["backfilled"]),- "pending_batches": pending_batches,+ "last_applied_at": last_applied_at,"last_synced_at": last_synced_at,})@@ -448,9 +346,7 @@ def _sources_status(team_id: int) -> SourcesStatus:details: dict[ReadinessState, str] = {"needs_attention": "One or more imported sources need attention.","backfilling": "Existing rows are being copied for one or more imported sources.",- "catching_up": "Recent imports are still being applied to the warehouse.","waiting": "One or more imported sources are waiting to start.",- "unknown": "Some live import statuses are temporarily unavailable.","sync_paused": "Sync is paused for one or more imported sources.","up_to_date": "All imported sources are up to date.","not_configured": "No imported source tables are configured for this warehouse.",diff --git a/products/data_warehouse/backend/presentation/managed_warehouse_data_status.py b/products/data_warehouse/backend/presentation/managed_warehouse_data_status.pyindex 8eb839360435..e17444d8ecf3 100644--- a/products/data_warehouse/backend/presentation/managed_warehouse_data_status.py+++ b/products/data_warehouse/backend/presentation/managed_warehouse_data_status.py@@ -4,10 +4,8 @@ READINESS_STATE_CHOICES = ["not_configured","waiting","backfilling",- "catching_up","up_to_date","needs_attention",- "unknown","sync_paused",]@@ -51,14 +49,10 @@ class ManagedWarehouseSourceTableStatusSerializer(serializers.Serializer):total_chunks = serializers.IntegerField(allow_null=True, help_text="Total backfill chunks, or null before the copy plan is ready.")- pending_batches = serializers.IntegerField(- allow_null=True, help_text="Imported batches waiting to be applied, or null when queue status is unavailable."- )- oldest_pending_at = serializers.DateTimeField(- allow_null=True, help_text="Creation time of the oldest unapplied imported batch."- )last_applied_at = serializers.DateTimeField(- allow_null=True, help_text="When an imported batch was most recently applied to the warehouse."+ allow_null=True,+ help_text="When an imported batch was most recently applied to the warehouse, or null if no apply "+ "has been recorded for this table.",)last_synced_at = serializers.DateTimeField(allow_null=True, help_text="When PostHog most recently completed the upstream source import."@@ -77,9 +71,10 @@ class ManagedWarehouseSourceSummarySerializer(serializers.Serializer):backfilled_schemas = serializers.IntegerField(help_text="Number of schemas whose one-time historical copy into the warehouse has completed.")- pending_batches = serializers.IntegerField(+ last_applied_at = serializers.DateTimeField(allow_null=True,- help_text="Imported batches waiting to be applied across this source's schemas, or null when queue status is unavailable.",+ help_text="Most recent time an imported batch was applied to the warehouse across this source's "+ "schemas, or null if no apply has been recorded.",)last_synced_at = serializers.DateTimeField(allow_null=True, help_text="Most recent upstream source import completion across this source's schemas."diff --git a/products/data_warehouse/backend/tests/test_managed_warehouse_data_status.py b/products/data_warehouse/backend/tests/test_managed_warehouse_data_status.pyindex c42df65a4d83..ef7098fcbbd9 100644--- a/products/data_warehouse/backend/tests/test_managed_warehouse_data_status.py+++ b/products/data_warehouse/backend/tests/test_managed_warehouse_data_status.py@@ -11,7 +11,6 @@ from posthog.ducklake.models import DuckgresServerTeam, DuckgresSinkSchemaStatefrom posthog.models import Organization, Teamfrom products.data_warehouse.backend.logic.managed_warehouse_data_status import (- QueueTailStatus,ReadinessState,SourceTableStatus,_rollup_sources,@@ -31,36 +30,28 @@ class TestSourceTableReadiness(SimpleTestCase):@parameterized.expand([(- "persistent_failure_overrides_pending_batches",+ "persistent_failure_streak_needs_attention_even_mid_backfill",DuckgresSinkSchemaState.State.BACKFILLING,3,- {"pending_batches": 4, "oldest_pending_at": None, "last_applied_at": None},- True,"needs_attention",),(- "primed_schema_with_pending_batches_is_catching_up",- DuckgresSinkSchemaState.State.PRIMED,+ "pending_backfill_is_waiting",+ DuckgresSinkSchemaState.State.PENDING_BACKFILL,0,- {"pending_batches": 2, "oldest_pending_at": None, "last_applied_at": None},- True,- "catching_up",+ "waiting",),(- "primed_schema_without_pending_batches_is_up_to_date",- DuckgresSinkSchemaState.State.PRIMED,+ "backfilling_reports_backfilling",+ DuckgresSinkSchemaState.State.BACKFILLING,0,- {"pending_batches": 0, "oldest_pending_at": None, "last_applied_at": None},- True,- "up_to_date",+ "backfilling",),(- "queue_outage_does_not_report_up_to_date",+ "primed_schema_is_up_to_date",DuckgresSinkSchemaState.State.PRIMED,0,- None,- False,- "unknown",+ "up_to_date",),])@@ -69,8 +60,6 @@ class TestSourceTableReadiness(SimpleTestCase):_name: str,lifecycle_state: str,consecutive_failures: int,- queue_status: QueueTailStatus | None,- queue_available: bool,expected_readiness: ReadinessState,) -> None:state = DuckgresSinkSchemaState(@@ -80,7 +69,7 @@ class TestSourceTableReadiness(SimpleTestCase):consecutive_failures=consecutive_failures,)- readiness, _ = source_table_readiness(state, queue_status, queue_available)+ readiness, _ = source_table_readiness(state)assert readiness == expected_readiness@@ -173,7 +162,7 @@ def _table(readiness_state: ReadinessState,source_id: str | None = None,backfilled: bool = True,- pending_batches: int | None = None,+ last_applied_at: datetime | None = None,last_synced_at: datetime | None = None,) -> SourceTableStatus:return {@@ -187,9 +176,7 @@ def _table("backfilled": backfilled,"completed_chunks": 0,"total_chunks": None,- "pending_batches": pending_batches,- "oldest_pending_at": None,- "last_applied_at": None,+ "last_applied_at": last_applied_at,"last_synced_at": last_synced_at,}@@ -211,9 +198,9 @@ class TestSortSourceTables(SimpleTestCase):def test_orders_by_severity_then_name(self) -> None:tables = [_table(source_name="Zendesk", table_name="tickets", readiness_state="up_to_date"),- _table(source_name="Stripe", table_name="charges", readiness_state="catching_up"),+ _table(source_name="Stripe", table_name="charges", readiness_state="backfilling"),_table(source_name="Hubspot", table_name="deals", readiness_state="needs_attention"),- _table(source_name="Amplitude", table_name="events", readiness_state="catching_up"),+ _table(source_name="Amplitude", table_name="events", readiness_state="backfilling"),_table(source_name="Salesforce", table_name="accounts", readiness_state="up_to_date"),]@@ -221,18 +208,18 @@ class TestSortSourceTables(SimpleTestCase):assert ordered == [("Hubspot", "needs_attention"),- ("Amplitude", "catching_up"),- ("Stripe", "catching_up"),+ ("Amplitude", "backfilling"),+ ("Stripe", "backfilling"),("Salesforce", "up_to_date"),("Zendesk", "up_to_date"),]class TestRollupSources(SimpleTestCase):- def test_counts_backfilled_schemas_independent_of_live_catch_up_state(self) -> None:- # A schema can be fully backfilled but still "catching_up" on live imports. The rollup's- # backfilled count must track the one-time historical copy, not the live readiness label,- # or a source with a slow live queue would undercount how much history actually landed.+ def test_counts_backfilled_schemas_independent_of_readiness_label(self) -> None:+ # A schema can be fully backfilled while a sibling is still copying. The rollup's+ # backfilled count must track the one-time historical copy, not the readiness label,+ # or a source with one slow schema would undercount how much history actually landed.stripe_id = str(uuid4())tables = [_table(@@ -246,7 +233,7 @@ class TestRollupSources(SimpleTestCase):source_id=stripe_id,source_name="Stripe",table_name="customers",- readiness_state="catching_up",+ readiness_state="up_to_date",backfilled=True,),_table(@@ -262,8 +249,8 @@ class TestRollupSources(SimpleTestCase):assert summary["total_schemas"] == 3assert summary["backfilled_schemas"] == 2- # catching_up outranks waiting in READINESS_PRIORITY, so it wins the rollup.- assert summary["readiness_state"] == "catching_up"+ # waiting outranks up_to_date in READINESS_PRIORITY, so it wins the rollup.+ assert summary["readiness_state"] == "waiting"def test_groups_by_source_not_by_table(self) -> None:stripe_id, postgres_id = str(uuid4()), str(uuid4())@@ -281,55 +268,9 @@ class TestRollupSources(SimpleTestCase):# needs_attention outranks up_to_date, so Postgres sorts first despite the alphabet.assert [s["source_name"] for s in summaries] == ["Postgres", "Stripe"]- def test_pending_batches_null_propagates_rather_than_undercounting(self) -> None:- # If the live queue check failed, reporting a partial sum (or zero) would read as "caught- # up" when the real answer is "unknown" — null must survive the aggregation.- source_id = str(uuid4())- tables = [- _table(- source_id=source_id,- source_name="Stripe",- table_name="charges",- readiness_state="unknown",- pending_batches=None,- ),- _table(- source_id=source_id,- source_name="Stripe",- table_name="customers",- readiness_state="unknown",- pending_batches=None,- ),- ]-- [summary] = _rollup_sources(tables)-- assert summary["pending_batches"] is None-- def test_pending_batches_sums_across_schemas_when_queue_is_available(self) -> None:- source_id = str(uuid4())- tables = [- _table(- source_id=source_id,- source_name="Stripe",- table_name="charges",- readiness_state="catching_up",- pending_batches=3,- ),- _table(- source_id=source_id,- source_name="Stripe",- table_name="customers",- readiness_state="up_to_date",- pending_batches=0,- ),- ]-- [summary] = _rollup_sources(tables)-- assert summary["pending_batches"] == 3-- def test_last_synced_at_is_the_most_recent_across_schemas(self) -> None:+ def test_timestamps_roll_up_to_the_most_recent_across_schemas(self) -> None:+ # Both event timestamps summarize a source as "the latest time this happened anywhere in+ # it"; a min (or a None clobbering the max) would misreport an active source as stale.source_id = str(uuid4())older = datetime(2026, 6, 1, tzinfo=UTC)newer = datetime(2026, 7, 1, tzinfo=UTC)@@ -340,6 +281,7 @@ class TestRollupSources(SimpleTestCase):table_name="charges",readiness_state="up_to_date",last_synced_at=older,+ last_applied_at=newer,),_table(source_id=source_id,@@ -347,6 +289,7 @@ class TestRollupSources(SimpleTestCase):table_name="customers",readiness_state="up_to_date",last_synced_at=newer,+ last_applied_at=older,),_table(source_id=source_id,@@ -354,12 +297,14 @@ class TestRollupSources(SimpleTestCase):table_name="invoices",readiness_state="waiting",last_synced_at=None,+ last_applied_at=None,),][summary] = _rollup_sources(tables)assert summary["last_synced_at"] == newer+ assert summary["last_applied_at"] == newerdef test_a_paused_schema_outranks_up_to_date_but_not_a_real_problem(self) -> None:# A source where some schemas aren't being kept current at all shouldn't read as fully@@ -399,8 +344,9 @@ class TestRollupSources(SimpleTestCase):class TestGetSourceSchemaStatuses(TestCase):- # The queue-tail lookup reads SourceBatch, which lives in its own database.- databases = {"default", "warehouse_sources_queue_db_writer"}+ # The read side reports only what the sink jobs stamped onto the (main-DB) sink-state rows,+ # so it must not touch the warehouse-sources queue DB at all — leaving it out of `databases`+ # turns any accidentally re-introduced queue query into a test failure.def test_scopes_to_the_requested_source_only(self) -> None:# The modal fetches one source's schemas on click; a filter bug here would leak every@@ -455,3 +401,25 @@ class TestGetSourceSchemaStatuses(TestCase):result = get_source_schema_statuses(team.id, str(source.id))assert result == []++ def test_reports_the_last_apply_the_sink_stamped(self) -> None:+ # The row surfaces exactly what the sink recorded at apply time — the incident regression+ # was deriving this live from a database the web tier can't reach; now a primed schema+ # must read up_to_date and pass the stamped timestamp through untouched.+ team = Team.objects.create(organization=Organization.objects.create(name="org"), name="t")+ source = ExternalDataSource.objects.create(+ team=team, source_id="a", connection_id="ca", source_type="Stripe", status="Running"+ )+ schema = ExternalDataSchema.objects.create(team=team, name="charges", source=source)+ applied_at = datetime(2026, 7, 14, 12, 0, tzinfo=UTC)+ DuckgresSinkSchemaState.objects.create(+ team=team,+ schema_id=schema.id,+ state=DuckgresSinkSchemaState.State.PRIMED,+ queue_last_applied_at=applied_at,+ )++ [result] = get_source_schema_statuses(team.id, str(source.id))++ assert result["readiness_state"] == "up_to_date"+ assert result["last_applied_at"] == applied_atdiff --git a/products/data_warehouse/frontend/generated/api.schemas.ts b/products/data_warehouse/frontend/generated/api.schemas.tsindex 0bb679e9d1ac..642f01fb243c 100644--- a/products/data_warehouse/frontend/generated/api.schemas.ts+++ b/products/data_warehouse/frontend/generated/api.schemas.ts@@ -88,10 +88,8 @@ export interface EnableWarehouseBackfillResponseApi {* * `not_configured` - not_configured* * `waiting` - waiting* * `backfilling` - backfilling- * * `catching_up` - catching_up* * `up_to_date` - up_to_date* * `needs_attention` - needs_attention- * * `unknown` - unknown* * `sync_paused` - sync_paused*/export type ManagedWarehouseReadinessStateEnumApi =@@ -101,10 +99,8 @@ export const ManagedWarehouseReadinessStateEnumApi = {NotConfigured: 'not_configured',Waiting: 'waiting',Backfilling: 'backfilling',- CatchingUp: 'catching_up',UpToDate: 'up_to_date',NeedsAttention: 'needs_attention',- Unknown: 'unknown',SyncPaused: 'sync_paused',} as const@@ -130,10 +126,8 @@ export interface ManagedWarehouseDatasetStatusApi {* * `not_configured` - not_configured* * `waiting` - waiting* * `backfilling` - backfilling- * * `catching_up` - catching_up* * `up_to_date` - up_to_date* * `needs_attention` - needs_attention- * * `unknown` - unknown* * `sync_paused` - sync_paused */readiness_state: ManagedWarehouseReadinessStateEnumApi/** Human-readable explanation of the current readiness state. */@@ -169,10 +163,8 @@ export interface ManagedWarehouseSourceSummaryApi {* * `not_configured` - not_configured* * `waiting` - waiting* * `backfilling` - backfilling- * * `catching_up` - catching_up* * `up_to_date` - up_to_date* * `needs_attention` - needs_attention- * * `unknown` - unknown* * `sync_paused` - sync_paused */readiness_state: ManagedWarehouseReadinessStateEnumApi/** Human-readable explanation of this source's readiness state. */@@ -182,10 +174,10 @@ export interface ManagedWarehouseSourceSummaryApi {/** Number of schemas whose one-time historical copy into the warehouse has completed. */backfilled_schemas: number/**- * Imported batches waiting to be applied across this source's schemas, or null when queue status is unavailable.+ * Most recent time an imported batch was applied to the warehouse across this source's schemas, or null if no apply has been recorded.* @nullable*/- pending_batches: number | null+ last_applied_at: string | null/*** Most recent upstream source import completion across this source's schemas.* @nullable@@ -199,10 +191,8 @@ export interface ManagedWarehouseSourcesStatusApi {* * `not_configured` - not_configured* * `waiting` - waiting* * `backfilling` - backfilling- * * `catching_up` - catching_up* * `up_to_date` - up_to_date* * `needs_attention` - needs_attention- * * `unknown` - unknown* * `sync_paused` - sync_paused */readiness_state: ManagedWarehouseReadinessStateEnumApi/** Human-readable explanation of imported source readiness. */@@ -217,10 +207,8 @@ export interface ManagedWarehouseDataStatusResponseApi {* * `not_configured` - not_configured* * `waiting` - waiting* * `backfilling` - backfilling- * * `catching_up` - catching_up* * `up_to_date` - up_to_date* * `needs_attention` - needs_attention- * * `unknown` - unknown* * `sync_paused` - sync_paused */overall_readiness_state: ManagedWarehouseReadinessStateEnumApi/** Events backfill readiness. */@@ -249,10 +237,8 @@ export interface ManagedWarehouseSourceTableStatusApi {* * `not_configured` - not_configured* * `waiting` - waiting* * `backfilling` - backfilling- * * `catching_up` - catching_up* * `up_to_date` - up_to_date* * `needs_attention` - needs_attention- * * `unknown` - unknown* * `sync_paused` - sync_paused */readiness_state: ManagedWarehouseReadinessStateEnumApi/** Human-readable explanation of the table's readiness state. */@@ -267,17 +253,7 @@ export interface ManagedWarehouseSourceTableStatusApi {*/total_chunks: number | null/**- * Imported batches waiting to be applied, or null when queue status is unavailable.- * @nullable- */- pending_batches: number | null- /**- * Creation time of the oldest unapplied imported batch.- * @nullable- */- oldest_pending_at: string | null- /**- * When an imported batch was most recently applied to the warehouse.+ * When an imported batch was most recently applied to the warehouse, or null if no apply has been recorded for this table.* @nullable*/last_applied_at: string | nulldiff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/consumer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/consumer.pyindex 4987ca73f6bb..beb9690e34d1 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/consumer.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/consumer.py@@ -5,12 +5,16 @@ from collections.abc import Callablefrom datetime import datetimefrom typing import Any+from django.db import close_old_connections+from django.utils import timezone+import psycopgimport structlogfrom asgiref.sync import sync_to_asyncfrom prometheus_client import Gaugefrom posthog.exceptions_capture import capture_exception+from posthog.models import DuckgresSinkSchemaStatefrom products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.batch_consumer import (MAX_ATTEMPTS,@@ -52,6 +56,18 @@ logger = structlog.get_logger(__name__)DuckgresConsumerConfig = BatchConsumerConfig++def _record_live_batch_applied(schema_id: str) -> None:+ """Stamp the main-DB sink-state row with the time of this live apply.++ This is what the Data ops Overview tab reports as "last applied to warehouse" —+ an event stamped at the moment the work happens, so the web tier never has to+ query the warehouse-sources queue DB (which it has no credentials for).+ """+ close_old_connections()+ DuckgresSinkSchemaState.objects.filter(schema_id=schema_id).update(queue_last_applied_at=timezone.now())++# How often the fetch path refreshes the enabled-team set and runs the# supersede sweep + backlog gauges (the poll loop itself runs every ~2s).ENABLEMENT_REFRESH_SECONDS = 60.0@@ -428,8 +444,18 @@ class DuckgresBatchConsumerAdapter:*,batch: PendingBatch,) -> None:- if not batch.is_final_batch:- await DuckgresBatchQueue.mark_applied(conn, batch=batch)+ if batch.is_final_batch:+ return+ await DuckgresBatchQueue.mark_applied(conn, batch=batch)+ if is_backfill_metadata(batch.metadata):+ return+ try:+ await sync_to_async(_record_live_batch_applied, thread_sensitive=False)(batch.schema_id)+ except Exception as e:+ # The batch is already applied and marked; a failed stamp only leaves the+ # Data ops display timestamp behind until the next live apply.+ logger.exception("duckgres_live_apply_stamp_failed", schema_id=batch.schema_id)+ capture_exception(e)def is_retryable_error(self, err: Exception) -> bool:return not isinstance(err, PermanentBatchApplyError)diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_consumer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_consumer.pyindex aad7873575ac..b59828cfa148 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_consumer.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_consumer.py@@ -1,4 +1,5 @@import time+import uuidfrom contextlib import contextmanagerfrom typing import Any@@ -6,6 +7,9 @@ import pytestfrom unittest.mock import AsyncMock, MagicMock, patchimport psycopg+from asgiref.sync import async_to_sync++from posthog.models import DuckgresSinkSchemaState, Organization, Teamfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.batch_consumer import (OwnershipLostError,@@ -748,3 +752,54 @@ class TestPermanentApplyErrors:mock_fail.assert_called_once()mock_diverged.assert_not_called()+++# transaction=True: the stamp helper runs via sync_to_async in a separate thread and calls+# close_old_connections, so the row must be committed for that thread to see it.[email protected]_db(transaction=True)+class TestLiveApplyStamp:+ def _sink_state(self) -> DuckgresSinkSchemaState:+ team = Team.objects.create(organization=Organization.objects.create(name="org"), name="t")+ return DuckgresSinkSchemaState.objects.create(+ team=team, schema_id=uuid.uuid4(), state=DuckgresSinkSchemaState.State.PRIMED+ )++ def test_live_apply_stamps_the_sink_state_row(self) -> None:+ # This stamp is the only thing the Data ops Overview tab has for "last applied to+ # warehouse" — if the hook stops writing it, the UI silently freezes in time.+ state = self._sink_state()+ adapter = DuckgresBatchConsumerAdapter()+ batch = _make_batch(schema_id=str(state.schema_id))++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.mark_applied",+ new=AsyncMock(),+ ) as mock_mark_applied:+ async_to_sync(adapter.after_batch_processed)(_make_healthy_conn(), batch=batch)++ mock_mark_applied.assert_awaited_once()+ state.refresh_from_db()+ assert state.queue_last_applied_at is not None++ @pytest.mark.parametrize(+ "overrides",+ [+ {"metadata": {"duckgres_backfill": True, "chunk_paths": ["s3://b/f"], "chunk_count": 1}},+ {"is_final_batch": True},+ ],+ )+ def test_backfill_and_final_batches_do_not_stamp(self, overrides: dict[str, Any]) -> None:+ # Backfill chunks report through the chunk counters, and final markers apply nothing;+ # stamping either would misreport historical or zero-work processing as a live import.+ state = self._sink_state()+ adapter = DuckgresBatchConsumerAdapter()+ batch = _make_batch(schema_id=str(state.schema_id), **overrides)++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.mark_applied",+ new=AsyncMock(),+ ):+ async_to_sync(adapter.after_batch_processed)(_make_healthy_conn(), batch=batch)++ state.refresh_from_db()+ assert state.queue_last_applied_at is Nonediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 2f22fdc6fb78..f4527d82f99b 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -35180,10 +35180,8 @@ export namespace Schemas {* * `not_configured` - not_configured* * `waiting` - waiting* * `backfilling` - backfilling- * * `catching_up` - catching_up* * `up_to_date` - up_to_date* * `needs_attention` - needs_attention- * * `unknown` - unknown* * `sync_paused` - sync_paused*/export type ManagedWarehouseReadinessStateEnum = typeof ManagedWarehouseReadinessStateEnum[keyof typeof ManagedWarehouseReadinessStateEnum];@@ -35193,10 +35191,8 @@ export namespace Schemas {NotConfigured: 'not_configured',Waiting: 'waiting',Backfilling: 'backfilling',- CatchingUp: 'catching_up',UpToDate: 'up_to_date',NeedsAttention: 'needs_attention',- Unknown: 'unknown',SyncPaused: 'sync_paused',} as const;@@ -35211,10 +35207,8 @@ export namespace Schemas {* * `not_configured` - not_configured* * `waiting` - waiting* * `backfilling` - backfilling- * * `catching_up` - catching_up* * `up_to_date` - up_to_date* * `needs_attention` - needs_attention- * * `unknown` - unknown* * `sync_paused` - sync_paused */readiness_state: ManagedWarehouseReadinessStateEnum;/** Human-readable explanation of the current readiness state. */@@ -35250,10 +35244,8 @@ export namespace Schemas {* * `not_configured` - not_configured* * `waiting` - waiting* * `backfilling` - backfilling- * * `catching_up` - catching_up* * `up_to_date` - up_to_date* * `needs_attention` - needs_attention- * * `unknown` - unknown* * `sync_paused` - sync_paused */readiness_state: ManagedWarehouseReadinessStateEnum;/** Human-readable explanation of this source's readiness state. */@@ -35263,10 +35255,10 @@ export namespace Schemas {/** Number of schemas whose one-time historical copy into the warehouse has completed. */backfilled_schemas: number;/**- * Imported batches waiting to be applied across this source's schemas, or null when queue status is unavailable.+ * Most recent time an imported batch was applied to the warehouse across this source's schemas, or null if no apply has been recorded.* @nullable*/- pending_batches: number | null;+ last_applied_at: string | null;/*** Most recent upstream source import completion across this source's schemas.* @nullable@@ -35280,10 +35272,8 @@ export namespace Schemas {* * `not_configured` - not_configured* * `waiting` - waiting* * `backfilling` - backfilling- * * `catching_up` - catching_up* * `up_to_date` - up_to_date* * `needs_attention` - needs_attention- * * `unknown` - unknown* * `sync_paused` - sync_paused */readiness_state: ManagedWarehouseReadinessStateEnum;/** Human-readable explanation of imported source readiness. */@@ -35298,10 +35288,8 @@ export namespace Schemas {* * `not_configured` - not_configured* * `waiting` - waiting* * `backfilling` - backfilling- * * `catching_up` - catching_up* * `up_to_date` - up_to_date* * `needs_attention` - needs_attention- * * `unknown` - unknown* * `sync_paused` - sync_paused */overall_readiness_state: ManagedWarehouseReadinessStateEnum;/** Events backfill readiness. */@@ -35330,10 +35318,8 @@ export namespace Schemas {* * `not_configured` - not_configured* * `waiting` - waiting* * `backfilling` - backfilling- * * `catching_up` - catching_up* * `up_to_date` - up_to_date* * `needs_attention` - needs_attention- * * `unknown` - unknown* * `sync_paused` - sync_paused */readiness_state: ManagedWarehouseReadinessStateEnum;/** Human-readable explanation of the table's readiness state. */@@ -35348,17 +35334,7 @@ export namespace Schemas {*/total_chunks: number | null;/**- * Imported batches waiting to be applied, or null when queue status is unavailable.- * @nullable- */- pending_batches: number | null;- /**- * Creation time of the oldest unapplied imported batch.- * @nullable- */- oldest_pending_at: string | null;- /**- * When an imported batch was most recently applied to the warehouse.+ * When an imported batch was most recently applied to the warehouse, or null if no apply has been recorded for this table.* @nullable*/last_applied_at: string | null;