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(data-warehouse): add managed warehouse data status endpoint (#70571)

Eric Duong59e40fa33fba
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yaml
index 281bb63792d3..6d83dd9d73c0 100644
--- a/.semgrep/rules/security/idor-team-scoped-models.yaml
+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml
@@ -187,6 +187,7 @@ rules:
|LLMProviderKey
|LLMSkill
|LLMTraceSummary
+ |ManagedWarehouseBackfillPartition
|MarketingAnalyticsGoalMapping
|MessageCategory
|MessageRecipientPreference
@@ -478,6 +479,7 @@ rules:
|LLMProviderKey
|LLMSkill
|LLMTraceSummary
+ |ManagedWarehouseBackfillPartition
|MarketingAnalyticsGoalMapping
|MessageCategory
|MessageRecipientPreference
diff --git a/posthog/dags/events_backfill_to_duckling.py b/posthog/dags/events_backfill_to_duckling.py
index 7172172d6d26..0b01e7969c1b 100644
--- a/posthog/dags/events_backfill_to_duckling.py
+++ b/posthog/dags/events_backfill_to_duckling.py
@@ -41,6 +41,7 @@ from contextlib import closing
from datetime import date, datetime, timedelta
from typing import Any, Literal
+from django.db import DatabaseError
from django.utils import timezone
import psycopg
@@ -50,6 +51,7 @@ from clickhouse_driver.errors import Error as ClickHouseError
from dagster import (
AssetExecutionContext,
Config,
+ DagsterRun,
DagsterRunStatus,
DefaultSensorStatus,
DynamicPartitionsDefinition,
@@ -73,6 +75,16 @@ from posthog.ducklake.client import make_duckgres_conninfo
from posthog.ducklake.common import DUCKGRES_BUCKET_REGION, _get_org_id_for_team, get_duckgres_server_for_organization
from posthog.ducklake.models import DuckgresServerTeam
+from products.data_warehouse.backend.facade.backfill_status import (
+ BackfillOutcome,
+ historical_backfill_months,
+ record_backfill_finished,
+ record_backfill_outcome,
+ record_backfill_started,
+ stale_running_partitions,
+)
+from products.data_warehouse.backend.facade.models import ManagedWarehouseBackfillPartition
+
logger = structlog.get_logger(__name__)
# Catalog alias used by every duckgres connection. Duckgres auto-attaches the
@@ -691,6 +703,58 @@ EXPECTED_DUCKLAKE_PERSONS_COLUMNS = {
duckling_events_partitions_def = DynamicPartitionsDefinition(name="duckling_events_backfill")
duckling_persons_partitions_def = DynamicPartitionsDefinition(name="duckling_persons_backfill")
+
+# The recording API itself lives in the product (logic.backfill_status) and knows nothing about
+# Dagster. This adapter is the boundary: it translates Dagster's run vocabulary into ours, so a
+# different scheduler only has to supply its own translation.
+def _outcome_from_run_status(run_status: DagsterRunStatus) -> BackfillOutcome:
+ if run_status == DagsterRunStatus.SUCCESS:
+ return BackfillOutcome.SUCCEEDED
+ if run_status in (DagsterRunStatus.FAILURE, DagsterRunStatus.CANCELED):
+ return BackfillOutcome.FAILED
+ return BackfillOutcome.RUNNING
+
+
+def _stale_run_outcome(run: DagsterRun | None) -> BackfillOutcome | None:
+ """How to resolve a row stuck in RUNNING, given its scheduler run — None means leave it alone.
+
+ Only a run's own process may declare it finished while it is still in flight, so a live (or
+ queued) run is never touched. A vanished run resolves to FAILED: there is no proof the data
+ landed, and re-running a partition is safe while trusting a ghost run is not.
+ """
+ if run is None:
+ return BackfillOutcome.FAILED
+ outcome = _outcome_from_run_status(run.status)
+ return None if outcome is BackfillOutcome.RUNNING else outcome
+
+
+# Bounds the run-storage lookups a single sensor tick spends resolving crashed runs.
+STALE_RUNNING_REPAIR_LIMIT = 25
+
+
+def _repair_stale_running_statuses(context: SensorEvaluationContext, dataset: str) -> None:
+ """Resolve status rows whose recording process died before writing a terminal state.
+
+ record_backfill_started/finished bracket the run in-process, so an OOM or pod eviction in
+ between leaves the row RUNNING forever — and the UI reporting "backfilling" indefinitely.
+ Each tick asks Dagster what actually happened to the oldest sufficiently stale RUNNING rows.
+ """
+ for row in stale_running_partitions(dataset=dataset, limit=STALE_RUNNING_REPAIR_LIMIT):
+ run = context.instance.get_run_by_id(row.run_id)
+ outcome = _stale_run_outcome(run)
+ if outcome is None:
+ continue
+ record_backfill_finished(
+ team_id=row.team_id,
+ dataset=dataset,
+ partition_key=row.partition_key,
+ run_id=row.run_id,
+ failure_reason=(
+ None if outcome is BackfillOutcome.SUCCEEDED else "RunLost" if run is None else "RunDidNotComplete"
+ ),
+ )
+
+
# SQL for creating the events table in DuckLake if it doesn't exist
# Uses TIMESTAMPTZ because ClickHouse exports DateTime64 as TIMESTAMP WITH TIME ZONE in Parquet.
EVENTS_TABLE_DDL = """
@@ -2298,6 +2362,39 @@ def register_persons_files_with_duckling(
tags={"owner": JobOwners.TEAM_MANAGED_WAREHOUSE.value, **EVENTS_CONCURRENCY_TAG},
)
def duckling_events_backfill(context: AssetExecutionContext, config: DucklingBackfillConfig) -> None:
+ team_id, _ = parse_partition_key_dates(context.partition_key)
+ if config.dry_run:
+ _run_duckling_events_backfill(context, config)
+ return
+
+ run_id = context.run.run_id
+ record_backfill_started(
+ team_id=team_id,
+ dataset=ManagedWarehouseBackfillPartition.Dataset.EVENTS,
+ partition_key=context.partition_key,
+ run_id=run_id,
+ )
+ try:
+ _run_duckling_events_backfill(context, config)
+ except Exception as error:
+ record_backfill_finished(
+ team_id=team_id,
+ dataset=ManagedWarehouseBackfillPartition.Dataset.EVENTS,
+ partition_key=context.partition_key,
+ run_id=run_id,
+ error=error,
+ )
+ raise
+
+ record_backfill_finished(
+ team_id=team_id,
+ dataset=ManagedWarehouseBackfillPartition.Dataset.EVENTS,
+ partition_key=context.partition_key,
+ run_id=run_id,
+ )
+
+
+def _run_duckling_events_backfill(context: AssetExecutionContext, config: DucklingBackfillConfig) -> None:
"""Backfill events from ClickHouse to a customer's duckling.
Supports both daily (YYYY-MM-DD) and monthly (YYYY-MM) partition keys.
@@ -2468,6 +2565,42 @@ def duckling_events_backfill(context: AssetExecutionContext, config: DucklingBac
tags={"owner": JobOwners.TEAM_MANAGED_WAREHOUSE.value, **PERSONS_CONCURRENCY_TAG},
)
def duckling_persons_backfill(context: AssetExecutionContext, config: DucklingBackfillConfig) -> None:
+ partition_key = context.partition_key
+ team_id = (
+ int(partition_key) if is_full_export_partition(partition_key) else parse_partition_key_dates(partition_key)[0]
+ )
+ if config.dry_run:
+ _run_duckling_persons_backfill(context, config)
+ return
+
+ run_id = context.run.run_id
+ record_backfill_started(
+ team_id=team_id,
+ dataset=ManagedWarehouseBackfillPartition.Dataset.PERSONS,
+ partition_key=partition_key,
+ run_id=run_id,
+ )
+ try:
+ _run_duckling_persons_backfill(context, config)
+ except Exception as error:
+ record_backfill_finished(
+ team_id=team_id,
+ dataset=ManagedWarehouseBackfillPartition.Dataset.PERSONS,
+ partition_key=partition_key,
+ run_id=run_id,
+ error=error,
+ )
+ raise
+
+ record_backfill_finished(
+ team_id=team_id,
+ dataset=ManagedWarehouseBackfillPartition.Dataset.PERSONS,
+ partition_key=partition_key,
+ run_id=run_id,
+ )
+
+
+def _run_duckling_persons_backfill(context: AssetExecutionContext, config: DucklingBackfillConfig) -> None:
"""Backfill persons from ClickHouse to a customer's duckling.
Supports two partition formats with different export strategies:
@@ -2868,6 +3001,9 @@ EVENTS_BACKFILL_MAX_PARTITIONS_PER_TICK = 100
# Cap on per-team earliest-event ClickHouse lookups per tick. This is the only expensive
# sensor op; it runs once per team ever, then the result is cached on the model row.
EVENTS_BACKFILL_MAX_EARLIEST_LOOKUPS_PER_TICK = 5
+# Existing installations predate the durable UI projection. Reconcile a bounded
+# number of historical partitions per tick so the sensor stays within its budget.
+EVENTS_BACKFILL_STATUS_RECONCILE_LIMIT = 25
# Stored in DuckgresServerTeam.earliest_event_date for a team with no events, so the sensor
# caches "nothing to backfill" instead of re-querying every tick. Far enough in the future
# that the generated months range is always empty.
@@ -2878,21 +3014,66 @@ _NO_HISTORY_SENTINEL = date(9999, 12, 31)
_FULL_BACKFILL_RUN_TAG = {"duckling_backfill_type": "full"}
-def get_months_in_range(start_date: date, end_date: date) -> list[str]:
- """Generate list of month strings (YYYY-MM) between start and end dates."""
- months = []
- current = date(start_date.year, start_date.month, 1)
- end_month = date(end_date.year, end_date.month, 1)
+def _reconcile_events_backfill_statuses(context: SensorEvaluationContext, partition_keys: list[str]) -> None:
+ """Backfill the status projection for partitions that ran before it existed.
- while current <= end_month:
- months.append(current.strftime("%Y-%m"))
- # Move to next month
- if current.month == 12:
- current = date(current.year + 1, 1, 1)
- else:
- current = date(current.year, current.month + 1, 1)
+ TEMPORARY BRIDGE — the only part of this instrumentation that can't move off Dagster: it
+ reconstructs status by reading Dagster's own run storage. Everything else records status as
+ the run happens, through the scheduler-agnostic API in logic.backfill_status.
- return months
+ Delete this (and its persons counterpart in the full-backfill sensor) once every live
+ partition has a row, which happens within a few ticks of deploy. Until then, a scheduler
+ migration would have to drop it rather than port it.
+ """
+ if not partition_keys:
+ return
+
+ team_ids = {int(partition_key.split("_", 1)[0]) for partition_key in partition_keys}
+ try:
+ projected = set(
+ ManagedWarehouseBackfillPartition.objects.unscoped()
+ # team_id == environment_id for these rows; filtering on team_id hits the unique
+ # constraint's index, which leads with team.
+ .filter(
+ team_id__in=team_ids,
+ dataset=ManagedWarehouseBackfillPartition.Dataset.EVENTS,
+ )
+ .values_list("partition_key", flat=True)
+ )
+ except DatabaseError:
+ logger.exception("managed_warehouse_backfill_status_reconciliation_failed")
+ return
+
+ unprojected = [partition_key for partition_key in partition_keys if partition_key not in projected]
+ for partition_key in unprojected[:EVENTS_BACKFILL_STATUS_RECONCILE_LIMIT]:
+ runs = context.instance.get_runs(
+ filters=RunsFilter(
+ job_name="duckling_events_backfill_job",
+ tags={"dagster/partition": partition_key},
+ ),
+ limit=1,
+ )
+ if not runs:
+ # A registered partition with no findable run offers no evidence its data ever
+ # landed (dropped run request, wiped run storage). Project it failed — re-running a
+ # partition is safe — rather than leaving it to occupy this budget on every tick.
+ record_backfill_outcome(
+ team_id=int(partition_key.split("_", 1)[0]),
+ dataset=ManagedWarehouseBackfillPartition.Dataset.EVENTS,
+ partition_key=partition_key,
+ run_id="unknown",
+ outcome=BackfillOutcome.FAILED,
+ failure_reason="RunNotFound",
+ )
+ continue
+ latest_run = runs[0]
+ record_backfill_outcome(
+ team_id=int(partition_key.split("_", 1)[0]),
+ dataset=ManagedWarehouseBackfillPartition.Dataset.EVENTS,
+ partition_key=partition_key,
+ run_id=latest_run.run_id,
+ outcome=_outcome_from_run_status(latest_run.status),
+ )
@sensor(
@@ -2935,7 +3116,8 @@ def duckling_events_full_backfill_sensor(
# re-registers exactly the days the daily runs are handling, racing them under DuckLake's
# per-table OCC (that conflict is why the current-month monthly partition goes red while the
# daily partitions succeed).
- last_month_end = timezone.now().date().replace(day=1) - timedelta(days=1)
+ today = timezone.now().date()
+ last_month_end = today.replace(day=1) - timedelta(days=1)
backfills = list(DuckgresServerTeam.objects.filter(backfill_enabled=True).order_by("team_id"))
if not backfills:
@@ -2962,6 +3144,7 @@ def duckling_events_full_backfill_sensor(
# 2. Per-team remaining months (oldest first), skipping already-registered partitions.
existing = set(context.instance.get_dynamic_partitions("duckling_events_backfill"))
per_team_remaining: list[list[str]] = []
+ existing_historical_partitions: list[str] = []
for bf in backfills:
earliest = bf.earliest_event_date
if earliest is None or earliest > last_month_end:
@@ -2969,11 +3152,15 @@ def duckling_events_full_backfill_sensor(
# in the current month — no complete month to full-backfill (the daily sensor owns
# the current month), so skip it.
continue
- keys = [f"{bf.team_id}_{m}" for m in get_months_in_range(earliest, last_month_end)]
+ keys = [f"{bf.team_id}_{m}" for m in historical_backfill_months(earliest, today=today)]
+ existing_historical_partitions.extend(key for key in keys if key in existing)
remaining = [k for k in keys if k not in existing]
if remaining:
per_team_remaining.append(remaining)
+ _reconcile_events_backfill_statuses(context, existing_historical_partitions)
+ _repair_stale_running_statuses(context, ManagedWarehouseBackfillPartition.Dataset.EVENTS)
+
# 3. Round-robin interleave by month index: round r takes each team's r-th remaining
# month, so the queue order is team0-m0, team1-m0, ..., team0-m1, ... — fair under FIFO.
candidates: list[str] = []
@@ -3164,6 +3351,22 @@ def duckling_persons_full_backfill_sensor(
# Check existing partitions
existing_partitions = set(context.instance.get_dynamic_partitions("duckling_persons_backfill"))
+ try:
+ projected_persons_partitions = set(
+ ManagedWarehouseBackfillPartition.objects.unscoped()
+ # team_id == environment_id for these rows; filtering on team_id hits the unique
+ # constraint's index, which leads with team.
+ .filter(
+ team_id__in=[backfill.team_id for backfill in backfills],
+ dataset=ManagedWarehouseBackfillPartition.Dataset.PERSONS,
+ )
+ .values_list("partition_key", flat=True)
+ )
+ except DatabaseError:
+ logger.exception("managed_warehouse_backfill_status_reconciliation_failed")
+ projected_persons_partitions = existing_partitions
+
+ _repair_stale_running_statuses(context, ManagedWarehouseBackfillPartition.Dataset.PERSONS)
new_partitions: list[str] = []
run_requests: list[RunRequest] = []
@@ -3197,6 +3400,14 @@ def duckling_persons_full_backfill_sensor(
)
if runs:
latest_run = runs[0]
+ if partition_key not in projected_persons_partitions:
+ record_backfill_outcome(
+ team_id=team_id,
+ dataset=ManagedWarehouseBackfillPartition.Dataset.PERSONS,
+ partition_key=partition_key,
+ run_id=latest_run.run_id,
+ outcome=_outcome_from_run_status(latest_run.status),
+ )
# Only retry if failed - skip if in progress or succeeded
if latest_run.status == DagsterRunStatus.FAILURE:
run_requests.append(
@@ -3216,6 +3427,17 @@ def duckling_persons_full_backfill_sensor(
DagsterRunStatus.QUEUED,
):
context.log.debug(f"Skipping team_id={team_id} - run in progress")
+ elif partition_key not in projected_persons_partitions:
+ # Registered partition with no findable run: no evidence the data ever landed,
+ # so project it failed rather than re-checking it every tick forever.
+ record_backfill_outcome(
+ team_id=team_id,
+ dataset=ManagedWarehouseBackfillPartition.Dataset.PERSONS,
+ partition_key=partition_key,
+ run_id="unknown",
+ outcome=BackfillOutcome.FAILED,
+ failure_reason="RunNotFound",
+ )
if new_partitions:
context.log.info(f"Creating {len(new_partitions)} full persons backfill partitions")
diff --git a/posthog/dags/test_events_backfill_to_duckling.py b/posthog/dags/test_events_backfill_to_duckling.py
index f90c37addd3c..fbedc0e8a3c9 100644
--- a/posthog/dags/test_events_backfill_to_duckling.py
+++ b/posthog/dags/test_events_backfill_to_duckling.py
@@ -42,6 +42,7 @@ from posthog.dags.events_backfill_to_duckling import (
_resolve_duckling_target,
_resolve_table_names,
_set_table_partitioning,
+ _stale_run_outcome,
_validate_identifier,
delete_events_partition_data,
duckling_events_backfill_job,
@@ -51,7 +52,6 @@ from posthog.dags.events_backfill_to_duckling import (
export_events_to_duckling_s3,
export_persons_full_to_duckling_s3,
export_persons_to_duckling_s3,
- get_months_in_range,
get_s3_url_for_clickhouse,
is_full_export_partition,
parse_partition_key,
@@ -61,6 +61,8 @@ from posthog.dags.events_backfill_to_duckling import (
table_exists,
)
+from products.data_warehouse.backend.facade.backfill_status import BackfillOutcome, get_months_in_range
+
@pytest.fixture(autouse=True)
def _disable_ducklake_file_partition_value_fixup_by_default():
@@ -673,6 +675,7 @@ class TestFullBackfillSensorEarliestDate:
@patch("posthog.dags.events_backfill_to_duckling.get_earliest_event_date_for_team")
@patch("posthog.dags.events_backfill_to_duckling.DuckgresServerTeam")
@patch("posthog.dags.events_backfill_to_duckling.timezone")
+ @patch("posthog.dags.events_backfill_to_duckling.stale_running_partitions", new=MagicMock(return_value=[]))
def test_earliest_date_clamped(
self,
_name,
@@ -709,6 +712,7 @@ class TestFullBackfillSensorEarliestDate:
@patch("posthog.dags.events_backfill_to_duckling.get_earliest_event_date_for_team")
@patch("posthog.dags.events_backfill_to_duckling.DuckgresServerTeam")
@patch("posthog.dags.events_backfill_to_duckling.timezone")
+ @patch("posthog.dags.events_backfill_to_duckling.stale_running_partitions", new=MagicMock(return_value=[]))
def test_no_events_returns_empty(self, mock_tz, mock_backfill_cls, mock_get_earliest):
from dagster import DagsterInstance, SensorResult, build_sensor_context
@@ -749,10 +753,14 @@ class TestFullBackfillSensorEarliestDate:
with (
patch("posthog.dags.events_backfill_to_duckling.timezone") as mock_tz,
patch("posthog.dags.events_backfill_to_duckling.DuckgresServerTeam") as mock_cls,
+ patch("posthog.dags.events_backfill_to_duckling.ManagedWarehouseBackfillPartition") as mock_projection,
+ patch("posthog.dags.events_backfill_to_duckling.record_backfill_outcome"),
+ patch("posthog.dags.events_backfill_to_duckling.stale_running_partitions", return_value=[]),
patch("posthog.dags.events_backfill_to_duckling.get_earliest_event_date_for_team") as mock_ge,
):
mock_tz.now.return_value = now
mock_cls.objects.filter.return_value.order_by.return_value = backfills
+ mock_projection.objects.unscoped.return_value.filter.return_value.values_list.return_value = []
if isinstance(get_earliest, list):
mock_ge.side_effect = get_earliest
else:
@@ -864,6 +872,7 @@ class TestFullBackfillSensorEarliestDate:
with (
patch("posthog.dags.events_backfill_to_duckling.timezone") as mock_tz,
patch("posthog.dags.events_backfill_to_duckling.DuckgresServerTeam") as mock_cls,
+ patch("posthog.dags.events_backfill_to_duckling.stale_running_partitions", return_value=[]),
patch("posthog.dags.events_backfill_to_duckling.get_earliest_event_date_for_team"),
):
mock_tz.now.return_value = datetime(2020, 2, 10, 12, 0, 0)
@@ -877,6 +886,30 @@ class TestFullBackfillSensorEarliestDate:
assert runs_filter.tags == {"duckling_backfill_type": "full"}
+class TestStaleRunOutcome:
+ # A stuck-RUNNING row may only be resolved from a run that provably ended — resolving a live
+ # or queued run would overwrite the terminal state its own process is about to write.
+ @parameterized.expand(
+ [
+ ("lost_run", None, BackfillOutcome.FAILED),
+ ("succeeded", "SUCCESS", BackfillOutcome.SUCCEEDED),
+ ("failed", "FAILURE", BackfillOutcome.FAILED),
+ ("canceled", "CANCELED", BackfillOutcome.FAILED),
+ ("still_running", "STARTED", None),
+ ("queued", "QUEUED", None),
+ ]
+ )
+ def test_resolves_only_provably_ended_runs(self, _name, status_name, expected):
+ from dagster import DagsterRunStatus
+
+ run = None
+ if status_name is not None:
+ run = MagicMock()
+ run.status = DagsterRunStatus[status_name]
+
+ assert _stale_run_outcome(run) == expected
+
+
class TestDailyBackfillSensor:
@staticmethod
def _team(team_id: int):
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index 8b4456777840..e5a142d3205a 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -598,6 +598,15 @@ SPECTACULAR_SETTINGS = {
# BulkUpdateTagsRequest and its UUID subclass, so the shared enum can't be component-prefixed
# unambiguously and auto-resolves to a hash name. Pin it to a stable name.
"BulkUpdateTagsActionEnum": ["add", "remove", "set"],
+ "ManagedWarehouseReadinessStateEnum": [
+ "not_configured",
+ "waiting",
+ "backfilling",
+ "catching_up",
+ "up_to_date",
+ "needs_attention",
+ "unknown",
+ ],
# Full signal taxonomy on the report `signals` endpoint; the source-config serializer's
# subset enums keep their own auto-resolved names.
"SignalSourceProduct": "products.signals.backend.enums.SIGNAL_SOURCE_PRODUCT_VALUES",
diff --git a/products/data_warehouse/backend/facade/api.py b/products/data_warehouse/backend/facade/api.py
index 87db67cdead4..6600e36b57c0 100644
--- a/products/data_warehouse/backend/facade/api.py
+++ b/products/data_warehouse/backend/facade/api.py
@@ -58,6 +58,7 @@ _LAZY = {
"reconcile_webhook_events": "logic.external_data_source.webhooks",
"WebhookConsumerConfig": "logic.webhook_consumer.config",
"WebhookS3Sink": "logic.webhook_consumer.consumer",
+ "get_managed_warehouse_data_status": "logic.managed_warehouse_data_status",
"get_mysql_source_location": "mysql_helpers",
"reconcile_mysql_schemas": "mysql_helpers",
"reproject_direct_mysql_table": "mysql_helpers",
diff --git a/products/data_warehouse/backend/facade/backfill_status.py b/products/data_warehouse/backend/facade/backfill_status.py
new file mode 100644
index 000000000000..089718b5aaab
--- /dev/null
+++ b/products/data_warehouse/backend/facade/backfill_status.py
@@ -0,0 +1,26 @@
+"""
+Backfill-status wiring for data_warehouse.
+
+The managed-warehouse backfill jobs run in core's Dagster code location, so the scheduler-agnostic
+status recording API (logic.backfill_status) crosses the product boundary through this facade.
+"""
+
+from products.data_warehouse.backend.logic.backfill_status import (
+ BackfillOutcome,
+ get_months_in_range,
+ historical_backfill_months,
+ record_backfill_finished,
+ record_backfill_outcome,
+ record_backfill_started,
+ stale_running_partitions,
+)
+
+__all__ = [
+ "BackfillOutcome",
+ "get_months_in_range",
+ "historical_backfill_months",
+ "record_backfill_finished",
+ "record_backfill_outcome",
+ "record_backfill_started",
+ "stale_running_partitions",
+]
diff --git a/products/data_warehouse/backend/facade/models.py b/products/data_warehouse/backend/facade/models.py
index 55748730a852..10332a0452ca 100644
--- a/products/data_warehouse/backend/facade/models.py
+++ b/products/data_warehouse/backend/facade/models.py
@@ -4,7 +4,10 @@ Model-class wiring for data_warehouse.
Light re-export of the data_warehouse model class(es) consumed cross-product.
"""
+from products.data_warehouse.backend.models.managed_warehouse_backfill_partition import (
+ ManagedWarehouseBackfillPartition,
+)
from products.data_warehouse.backend.models.revenue_analytics_config import ExternalDataSourceRevenueAnalyticsConfig
from products.data_warehouse.backend.models.team_data_warehouse_config import TeamDataWarehouseConfig
-__all__ = ["ExternalDataSourceRevenueAnalyticsConfig", "TeamDataWarehouseConfig"]
+__all__ = ["ExternalDataSourceRevenueAnalyticsConfig", "ManagedWarehouseBackfillPartition", "TeamDataWarehouseConfig"]
diff --git a/products/data_warehouse/backend/logic/backfill_status.py b/products/data_warehouse/backend/logic/backfill_status.py
new file mode 100644
index 000000000000..920742bf54c9
--- /dev/null
+++ b/products/data_warehouse/backend/logic/backfill_status.py
@@ -0,0 +1,223 @@
+from __future__ import annotations
+
+import re
+from dataclasses import dataclass
+from datetime import date, timedelta
+from enum import StrEnum
+
+from django.db import DatabaseError
+from django.utils import timezone
+
+import structlog
+
+from products.data_warehouse.backend.models import ManagedWarehouseBackfillPartition
+
+logger = structlog.get_logger(__name__)
+
+Granularity = ManagedWarehouseBackfillPartition.Granularity
+LifecycleState = ManagedWarehouseBackfillPartition.LifecycleState
+
+# Partition key shapes. These are PostHog's convention for naming a unit of backfill work, not
+# any one scheduler's: `1_2026-05` (a historical month), `1_2026-05-04` (a day), `1` (persons'
+# whole history in one run). This module is the only place that decodes them.
+_FULL_KEY = re.compile(r"^\d+$")
+_MONTH_KEY = re.compile(r"^\d+_(?P<year>\d{4})-(?P<month>\d{2})$")
+_DAY_KEY = re.compile(r"^\d+_(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})$")
+
+# How long a row may sit in RUNNING before the repair sweep asks the scheduler whether its run
+# is actually still alive. Only a cost gate — a run that legitimately outlives it is left alone.
+STALE_RUNNING_AGE = timedelta(hours=1)
+
+
+class BackfillOutcome(StrEnum):
+ """How a backfill run ended, in terms the product understands.
+
+ Schedulers report completion in their own vocabulary (Dagster has DagsterRunStatus, the next
+ one will have something else). Callers map into this enum at the boundary so nothing below
+ this line depends on which scheduler runs the job.
+ """
+
+ RUNNING = "running"
+ SUCCEEDED = "succeeded"
+ FAILED = "failed"
+
+
+@dataclass(frozen=True)
+class PartitionDescriptor:
+ granularity: str
+ period_start: date | None
+
+
+def describe_partition_key(partition_key: str) -> PartitionDescriptor:
+ """Decode a partition key into the period it covers. Raises ValueError on an unknown shape."""
+ if _FULL_KEY.fullmatch(partition_key):
+ return PartitionDescriptor(granularity=Granularity.FULL, period_start=None)
+
+ day = _DAY_KEY.fullmatch(partition_key)
+ if day:
+ return PartitionDescriptor(
+ granularity=Granularity.DAY,
+ period_start=date(int(day["year"]), int(day["month"]), int(day["day"])),
+ )
+
+ month = _MONTH_KEY.fullmatch(partition_key)
+ if month:
+ return PartitionDescriptor(
+ granularity=Granularity.MONTH,
+ period_start=date(int(month["year"]), int(month["month"]), 1),
+ )
+
+ raise ValueError(f"Unrecognized backfill partition key: {partition_key!r}")
+
+
+def get_months_in_range(start_date: date, end_date: date) -> list[str]:
+ """Generate list of month strings (YYYY-MM) between start and end dates."""
+ months = []
+ current = date(start_date.year, start_date.month, 1)
+ end_month = date(end_date.year, end_date.month, 1)
+
+ while current <= end_month:
+ months.append(current.strftime("%Y-%m"))
+ # Move to next month
+ if current.month == 12:
+ current = date(current.year + 1, 1, 1)
+ else:
+ current = date(current.year, current.month + 1, 1)
+
+ return months
+
+
+def historical_backfill_months(earliest_event_date: date, *, today: date | None = None) -> list[str]:
+ """Complete months the events backfill is expected to cover.
+
+ The current, in-progress month belongs to the daily backfill, so history stops at the end of
+ last month. Both the scheduler (which enqueues these months) and the readiness endpoint (which
+ counts them) call this, so the numerator and the denominator can't drift apart.
+ """
+ today = today or timezone.now().date()
+ last_complete_month = today.replace(day=1) - timedelta(days=1)
+ if earliest_event_date > last_complete_month:
+ return []
+ return get_months_in_range(earliest_event_date, last_complete_month)
+
+
+def record_backfill_started(*, team_id: int, dataset: str, partition_key: str, run_id: str) -> None:
+ """Record that a partition is being backfilled. Safe to call again for a retry of the same partition."""
+ try:
+ descriptor = describe_partition_key(partition_key)
+ ManagedWarehouseBackfillPartition.objects.for_team(team_id).update_or_create(
+ environment_id=team_id,
+ dataset=dataset,
+ partition_key=partition_key,
+ defaults={
+ "team_id": team_id,
+ "granularity": descriptor.granularity,
+ "period_start": descriptor.period_start,
+ "lifecycle_state": LifecycleState.RUNNING,
+ "run_id": run_id,
+ "started_at": timezone.now(),
+ "completed_at": None,
+ "last_error": None,
+ },
+ )
+ except (DatabaseError, ValueError):
+ # Status is a projection for the UI: never fail the backfill itself over it.
+ logger.exception(
+ "managed_warehouse_backfill_status_write_failed",
+ team_id=team_id,
+ dataset=dataset,
+ partition_key=partition_key,
+ )
+
+
+def record_backfill_finished(
+ *,
+ team_id: int,
+ dataset: str,
+ partition_key: str,
+ run_id: str,
+ error: Exception | None = None,
+ failure_reason: str | None = None,
+) -> None:
+ """Record that a partition finished, successfully or not.
+
+ Pass `error` when the recording process caught the failure itself; pass `failure_reason`
+ when the failure is known only second-hand (a repaired crash, a lost run).
+ """
+ _finish(
+ team_id=team_id,
+ dataset=dataset,
+ partition_key=partition_key,
+ run_id=run_id,
+ failure_reason=type(error).__name__[:128] if error is not None else failure_reason,
+ )
+
+
+def record_backfill_outcome(
+ *,
+ team_id: int,
+ dataset: str,
+ partition_key: str,
+ run_id: str,
+ outcome: BackfillOutcome,
+ failure_reason: str = "RunDidNotComplete",
+) -> None:
+ """Project a run this process never saw onto the partition row.
+
+ Used when reconstructing status from a scheduler's own run history, where all we know is how
+ the run ended.
+ """
+ record_backfill_started(team_id=team_id, dataset=dataset, partition_key=partition_key, run_id=run_id)
+ if outcome is BackfillOutcome.SUCCEEDED:
+ _finish(team_id=team_id, dataset=dataset, partition_key=partition_key, run_id=run_id, failure_reason=None)
+ elif outcome is BackfillOutcome.FAILED:
+ _finish(
+ team_id=team_id,
+ dataset=dataset,
+ partition_key=partition_key,
+ run_id=run_id,
+ failure_reason=failure_reason,
+ )
+
+
+def stale_running_partitions(*, dataset: str, limit: int) -> list[ManagedWarehouseBackfillPartition]:
+ """Rows stuck in RUNNING long enough that the recording process may have died mid-run.
+
+ A process killed between record_backfill_started and record_backfill_finished (OOM, pod
+ eviction) never writes its terminal state, so without repair the row reports "backfilling"
+ forever. The scheduler resolves these against its own run records; the age gate only avoids
+ churning on rows whose run is plausibly still in flight.
+ """
+ cutoff = timezone.now() - STALE_RUNNING_AGE
+ try:
+ return list(
+ # unscoped: repair sweeps all teams from a scheduler context, not one tenant.
+ ManagedWarehouseBackfillPartition.objects.unscoped()
+ .filter(dataset=dataset, lifecycle_state=LifecycleState.RUNNING, updated_at__lt=cutoff)
+ .order_by("updated_at")[:limit]
+ )
+ except DatabaseError:
+ logger.exception("managed_warehouse_backfill_stale_running_query_failed", dataset=dataset)
+ return []
+
+
+def _finish(*, team_id: int, dataset: str, partition_key: str, run_id: str, failure_reason: str | None) -> None:
+ updates: dict[str, object] = {
+ "run_id": run_id,
+ "completed_at": timezone.now(),
+ "lifecycle_state": LifecycleState.COMPLETED if failure_reason is None else LifecycleState.FAILED,
+ "last_error": failure_reason,
+ }
+ try:
+ ManagedWarehouseBackfillPartition.objects.for_team(team_id).filter(
+ environment_id=team_id,
+ dataset=dataset,
+ partition_key=partition_key,
+ ).update(**updates)
+ except DatabaseError:
+ logger.exception(
+ "managed_warehouse_backfill_status_write_failed",
+ team_id=team_id,
+ dataset=dataset,
+ partition_key=partition_key,
+ )
diff --git a/products/data_warehouse/backend/logic/managed_warehouse_data_status.py b/products/data_warehouse/backend/logic/managed_warehouse_data_status.py
new file mode 100644
index 000000000000..851b35263c4a
--- /dev/null
+++ b/products/data_warehouse/backend/logic/managed_warehouse_data_status.py
@@ -0,0 +1,396 @@
+from __future__ import annotations
+
+from datetime import datetime, timedelta
+from typing import Literal, TypedDict
+
+from django.db import DatabaseError
+from django.db.models import Count, Exists, Max, Min, OuterRef, Q, Subquery
+from django.utils import timezone
+
+import structlog
+
+from posthog.ducklake.models import DuckgresServerTeam, DuckgresSinkSchemaState
+
+from products.data_warehouse.backend.logic.backfill_status import historical_backfill_months
+from products.data_warehouse.backend.models import ManagedWarehouseBackfillPartition
+from 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",
+]
+
+QUEUE_RETENTION_DAYS = 14
+PERSISTENT_BACKFILL_FAILURES = 3
+READINESS_PRIORITY: tuple[ReadinessState, ...] = (
+ "needs_attention",
+ "backfilling",
+ "catching_up",
+ "waiting",
+ "unknown",
+ "up_to_date",
+)
+
+
+class DatasetStatus(TypedDict):
+ dataset: Literal["events", "persons"]
+ readiness_state: ReadinessState
+ detail: str
+ completed_partitions: int
+ total_partitions: int | None
+ current_partition: str | None
+ last_updated_at: datetime | None
+
+
+class SourceTableStatus(TypedDict):
+ schema_id: str
+ source_id: str
+ source_name: str
+ source_type: str
+ table_name: str
+ readiness_state: ReadinessState
+ detail: str
+ completed_chunks: int
+ total_chunks: int | None
+ pending_batches: int | None
+ oldest_pending_at: datetime | None
+ last_applied_at: datetime | None
+ last_synced_at: datetime | None
+
+
+class SourcesStatus(TypedDict):
+ readiness_state: ReadinessState
+ detail: str
+ tables: list[SourceTableStatus]
+
+
+class ManagedWarehouseDataStatus(TypedDict):
+ overall_readiness_state: ReadinessState
+ events: DatasetStatus
+ persons: DatasetStatus
+ sources: SourcesStatus
+ 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
+
+ # Same helper the scheduler enqueues from, so this denominator always matches what actually runs.
+ return len(historical_backfill_months(backfill.earliest_event_date))
+
+
+def dataset_status(
+ *,
+ dataset: Literal["events", "persons"],
+ backfill: DuckgresServerTeam | None,
+ partitions: list[ManagedWarehouseBackfillPartition],
+) -> DatasetStatus:
+ if backfill is None or not backfill.backfill_enabled:
+ return {
+ "dataset": dataset,
+ "readiness_state": "not_configured",
+ "detail": "Warehouse backfill is not enabled for this project. Enable it from the Settings tab.",
+ "completed_partitions": 0,
+ "total_partitions": None,
+ "current_partition": None,
+ "last_updated_at": None,
+ }
+
+ relevant_partitions = partitions
+ # History is per-month for events and a single full export for persons. Both are read off the
+ # granularity column rather than the key's spelling, so a scheduler that names its partitions
+ # differently can't silently change what these numbers mean.
+ if dataset == "events":
+ historical_granularity = ManagedWarehouseBackfillPartition.Granularity.MONTH
+ total_partitions = _event_historical_partition_count(backfill)
+ else:
+ historical_granularity = ManagedWarehouseBackfillPartition.Granularity.FULL
+ total_partitions = 1
+
+ historical_partitions = [row for row in partitions if row.granularity == historical_granularity]
+ completed_partitions = sum(
+ row.lifecycle_state == ManagedWarehouseBackfillPartition.LifecycleState.COMPLETED
+ for row in historical_partitions
+ )
+
+ failed = next(
+ (
+ row
+ for row in relevant_partitions
+ if row.lifecycle_state == ManagedWarehouseBackfillPartition.LifecycleState.FAILED
+ ),
+ None,
+ )
+ running = next(
+ (
+ row
+ for row in relevant_partitions
+ if row.lifecycle_state == ManagedWarehouseBackfillPartition.LifecycleState.RUNNING
+ ),
+ None,
+ )
+ last_updated_at = max((row.updated_at for row in relevant_partitions), default=None)
+
+ if failed is not None:
+ readiness_state: ReadinessState = "needs_attention"
+ detail = "A backfill partition failed. Retry the failed warehouse backfill run."
+ current_partition = failed.partition_key
+ elif running is not None:
+ readiness_state = "backfilling"
+ detail = "Historical data is being copied into the warehouse."
+ current_partition = running.partition_key
+ elif total_partitions is None:
+ readiness_state = "waiting"
+ detail = "Preparing the historical data range."
+ current_partition = None
+ elif completed_partitions < total_partitions:
+ readiness_state = "backfilling" if completed_partitions else "waiting"
+ detail = f"{completed_partitions} of {total_partitions} historical partitions are complete."
+ current_partition = None
+ else:
+ readiness_state = "up_to_date"
+ detail = "Historical data is loaded and daily updates are enabled."
+ current_partition = None
+
+ return {
+ "dataset": dataset,
+ "readiness_state": readiness_state,
+ "detail": detail,
+ "completed_partitions": completed_partitions,
+ "total_partitions": total_partitions,
+ "current_partition": current_partition,
+ "last_updated_at": last_updated_at,
+ }
+
+
+def _queue_tail_statuses(team_id: int, schema_ids: list[str]) -> dict[str, QueueTailStatus] | None:
+ if not schema_ids:
+ return {}
+
+ 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]:
+ if (
+ state.state == DuckgresSinkSchemaState.State.NEEDS_RESYNC
+ or state.consecutive_failures >= PERSISTENT_BACKFILL_FAILURES
+ ):
+ return "needs_attention", "This table needs a fresh warehouse copy before imports can continue."
+ if state.state == DuckgresSinkSchemaState.State.PENDING_BACKFILL:
+ return "waiting", "Waiting to copy existing rows into the warehouse."
+ if state.state == DuckgresSinkSchemaState.State.BACKFILLING:
+ 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."
+
+
+def _sources_status(team_id: int) -> SourcesStatus:
+ states = list(DuckgresSinkSchemaState.objects.filter(team_id=team_id).order_by("schema_id"))
+ if not states:
+ return {
+ "readiness_state": "not_configured",
+ "detail": "No imported source tables are configured for this warehouse.",
+ "tables": [],
+ }
+
+ schema_by_id = {
+ str(schema.id): schema
+ for schema in ExternalDataSchema.objects.filter(
+ team_id=team_id,
+ id__in=[state.schema_id for state in states],
+ should_sync=True,
+ deleted=False,
+ source__deleted=False,
+ ).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 None
+
+ tables: 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 None
+ readiness_state, detail = source_table_readiness(state, queue_status, queue_available)
+ tables.append(
+ {
+ "schema_id": schema_id,
+ "source_id": str(schema.source_id),
+ "source_name": schema.source.prefix or schema.source.source_type,
+ "source_type": schema.source.source_type,
+ "table_name": schema.name,
+ "readiness_state": readiness_state,
+ "detail": detail,
+ "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_synced_at": schema.last_synced_at,
+ }
+ )
+
+ if not tables:
+ return {
+ "readiness_state": "not_configured",
+ "detail": "No imported source tables are configured for this warehouse.",
+ "tables": [],
+ }
+
+ tables = sort_source_tables(tables)
+ readiness_state = _roll_up_state([table["readiness_state"] for table in tables])
+ details: dict[ReadinessState, str] = {
+ "needs_attention": "One or more imported tables need attention.",
+ "backfilling": "Existing rows are being copied for one or more imported tables.",
+ "catching_up": "Recent imports are still being applied to the warehouse.",
+ "waiting": "One or more imported tables are waiting to start.",
+ "unknown": "Some live import statuses are temporarily unavailable.",
+ "up_to_date": "All imported source tables are up to date.",
+ "not_configured": "No imported source tables are configured for this warehouse.",
+ }
+ return {"readiness_state": readiness_state, "detail": details[readiness_state], "tables": tables}
+
+
+def sort_source_tables(tables: list[SourceTableStatus]) -> list[SourceTableStatus]:
+ """Most severe first, then alphabetically by source and table.
+
+ A team can import dozens of tables and the UI paginates at 20, so the one table that has
+ stalled has to land on the first page. Ordering by schema_id (a UUID) scattered it.
+ """
+ severity = {state: rank for rank, state in enumerate(READINESS_PRIORITY)}
+ return sorted(
+ tables,
+ key=lambda table: (
+ severity.get(table["readiness_state"], len(severity)),
+ table["source_name"].lower(),
+ table["table_name"].lower(),
+ ),
+ )
+
+
+def _roll_up_state(states: list[ReadinessState]) -> ReadinessState:
+ for candidate in READINESS_PRIORITY:
+ if candidate in states:
+ return candidate
+ return "not_configured"
+
+
+def get_managed_warehouse_data_status(team_id: int) -> ManagedWarehouseDataStatus:
+ backfill = DuckgresServerTeam.objects.filter(team_id=team_id).first()
+ partitions = list(
+ ManagedWarehouseBackfillPartition.objects.for_team(team_id)
+ .filter(environment_id=team_id)
+ .order_by("-updated_at")
+ )
+ events = dataset_status(
+ dataset="events",
+ backfill=backfill,
+ partitions=[row for row in partitions if row.dataset == ManagedWarehouseBackfillPartition.Dataset.EVENTS],
+ )
+ persons = dataset_status(
+ dataset="persons",
+ backfill=backfill,
+ partitions=[row for row in partitions if row.dataset == ManagedWarehouseBackfillPartition.Dataset.PERSONS],
+ )
+ sources = _sources_status(team_id)
+ return {
+ "overall_readiness_state": _roll_up_state(
+ [events["readiness_state"], persons["readiness_state"], sources["readiness_state"]]
+ ),
+ "events": events,
+ "persons": persons,
+ "sources": sources,
+ "generated_at": timezone.now(),
+ }
diff --git a/products/data_warehouse/backend/migrations/0057_managed_warehouse_backfill_partition.py b/products/data_warehouse/backend/migrations/0057_managed_warehouse_backfill_partition.py
new file mode 100644
index 000000000000..24c07c0b848f
--- /dev/null
+++ b/products/data_warehouse/backend/migrations/0057_managed_warehouse_backfill_partition.py
@@ -0,0 +1,80 @@
+# Generated by Django 5.2.14 on 2026-07-13 21:30
+
+import django.db.models.deletion
+from django.db import migrations, models
+
+import posthog.models.utils
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("data_warehouse", "0056_remove_data_modeling_models"),
+ ("posthog", "1252_datadeletionrequest_property_removal_marker"),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="ManagedWarehouseBackfillPartition",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.models.utils.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ ("environment_id", models.BigIntegerField()),
+ (
+ "dataset",
+ models.CharField(
+ choices=[("events", "Events"), ("persons", "Persons")],
+ max_length=16,
+ ),
+ ),
+ ("partition_key", models.CharField(max_length=128)),
+ (
+ "granularity",
+ models.CharField(
+ choices=[("day", "Day"), ("month", "Month"), ("full", "Full")],
+ max_length=8,
+ ),
+ ),
+ ("period_start", models.DateField(blank=True, null=True)),
+ (
+ "lifecycle_state",
+ models.CharField(
+ choices=[
+ ("running", "Running"),
+ ("completed", "Completed"),
+ ("failed", "Failed"),
+ ],
+ max_length=16,
+ ),
+ ),
+ ("run_id", models.CharField(max_length=64)),
+ ("started_at", models.DateTimeField()),
+ ("completed_at", models.DateTimeField(blank=True, null=True)),
+ ("last_error", models.CharField(blank=True, max_length=128, null=True)),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ("updated_at", models.DateTimeField(auto_now=True)),
+ (
+ "team",
+ models.ForeignKey(
+ db_constraint=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ to="posthog.team",
+ ),
+ ),
+ ],
+ options={
+ "constraints": [
+ models.UniqueConstraint(
+ fields=("team", "environment_id", "dataset", "partition_key"),
+ name="unique_managed_warehouse_backfill_partition",
+ )
+ ],
+ },
+ ),
+ ]
diff --git a/products/data_warehouse/backend/migrations/max_migration.txt b/products/data_warehouse/backend/migrations/max_migration.txt
index 56a3ce44d20b..8e260d1f6a7d 100644
--- a/products/data_warehouse/backend/migrations/max_migration.txt
+++ b/products/data_warehouse/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0056_remove_data_modeling_models
+0057_managed_warehouse_backfill_partition
diff --git a/products/data_warehouse/backend/models/__init__.py b/products/data_warehouse/backend/models/__init__.py
index b2a6ceeb1640..a8cde285b7b1 100644
--- a/products/data_warehouse/backend/models/__init__.py
+++ b/products/data_warehouse/backend/models/__init__.py
@@ -1,7 +1,9 @@
+from .managed_warehouse_backfill_partition import ManagedWarehouseBackfillPartition
from .revenue_analytics_config import ExternalDataSourceRevenueAnalyticsConfig
from .team_data_warehouse_config import TeamDataWarehouseConfig
__all__ = [
"ExternalDataSourceRevenueAnalyticsConfig",
+ "ManagedWarehouseBackfillPartition",
"TeamDataWarehouseConfig",
]
diff --git a/products/data_warehouse/backend/models/managed_warehouse_backfill_partition.py b/products/data_warehouse/backend/models/managed_warehouse_backfill_partition.py
new file mode 100644
index 000000000000..3467ba81dee1
--- /dev/null
+++ b/products/data_warehouse/backend/models/managed_warehouse_backfill_partition.py
@@ -0,0 +1,50 @@
+from django.db import models
+
+from posthog.models.scoping.root_mixin import TeamScopedRootMixin
+from posthog.models.utils import UUIDModel
+
+
+class ManagedWarehouseBackfillPartition(TeamScopedRootMixin, UUIDModel):
+ class Dataset(models.TextChoices):
+ EVENTS = "events", "Events"
+ PERSONS = "persons", "Persons"
+
+ class Granularity(models.TextChoices):
+ DAY = "day", "Day"
+ MONTH = "month", "Month"
+ FULL = "full", "Full"
+
+ class LifecycleState(models.TextChoices):
+ RUNNING = "running", "Running"
+ COMPLETED = "completed", "Completed"
+ FAILED = "failed", "Failed"
+
+ # team is the canonical tenant boundary; environment_id preserves the exact
+ # project because sibling environments share a team scope.
+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False)
+ environment_id = models.BigIntegerField()
+ dataset = models.CharField(max_length=16, choices=Dataset.choices)
+ # partition_key is whatever the scheduler calls this unit of work — opaque here, and only
+ # decoded in one place (logic.backfill_status.describe_partition_key). granularity and
+ # period_start carry the meaning, so readers never re-parse the key and a scheduler that
+ # spells keys differently doesn't silently change what the readiness numbers mean.
+ partition_key = models.CharField(max_length=128)
+ granularity = models.CharField(max_length=8, choices=Granularity.choices)
+ # Null for a FULL partition, which covers all of history rather than one period.
+ period_start = models.DateField(null=True, blank=True)
+ lifecycle_state = models.CharField(max_length=16, choices=LifecycleState.choices)
+ # Free-form scheduler run identifier (a Dagster run id today), kept only for debugging.
+ run_id = models.CharField(max_length=64)
+ started_at = models.DateTimeField()
+ completed_at = models.DateTimeField(null=True, blank=True)
+ last_error = models.CharField(max_length=128, null=True, blank=True)
+ created_at = models.DateTimeField(auto_now_add=True)
+ updated_at = models.DateTimeField(auto_now=True)
+
+ class Meta:
+ constraints = [
+ models.UniqueConstraint(
+ fields=["team", "environment_id", "dataset", "partition_key"],
+ name="unique_managed_warehouse_backfill_partition",
+ )
+ ]
diff --git a/products/data_warehouse/backend/presentation/managed_warehouse_data_status.py b/products/data_warehouse/backend/presentation/managed_warehouse_data_status.py
new file mode 100644
index 000000000000..45dd9885514a
--- /dev/null
+++ b/products/data_warehouse/backend/presentation/managed_warehouse_data_status.py
@@ -0,0 +1,81 @@
+from rest_framework import serializers
+
+READINESS_STATE_CHOICES = [
+ "not_configured",
+ "waiting",
+ "backfilling",
+ "catching_up",
+ "up_to_date",
+ "needs_attention",
+ "unknown",
+]
+
+
+class ManagedWarehouseDatasetStatusSerializer(serializers.Serializer):
+ dataset = serializers.ChoiceField(
+ choices=["events", "persons"], help_text="Warehouse dataset represented by this status."
+ )
+ readiness_state = serializers.ChoiceField(
+ choices=READINESS_STATE_CHOICES, help_text="User-facing readiness state for this dataset."
+ )
+ detail = serializers.CharField(help_text="Human-readable explanation of the current readiness state.")
+ completed_partitions = serializers.IntegerField(
+ help_text="Number of historical backfill partitions completed successfully."
+ )
+ total_partitions = serializers.IntegerField(
+ allow_null=True, help_text="Expected historical partitions, or null while the range is being calculated."
+ )
+ current_partition = serializers.CharField(
+ allow_null=True, help_text="Partition currently running or requiring attention, when applicable."
+ )
+ last_updated_at = serializers.DateTimeField(
+ allow_null=True, help_text="When the durable backfill status last changed."
+ )
+
+
+class ManagedWarehouseSourceTableStatusSerializer(serializers.Serializer):
+ schema_id = serializers.UUIDField(help_text="Imported source schema identifier.")
+ source_id = serializers.UUIDField(help_text="Imported source connection identifier.")
+ source_name = serializers.CharField(help_text="Display name for the imported source connection.")
+ source_type = serializers.CharField(help_text="Type of the imported source connection.")
+ table_name = serializers.CharField(help_text="Imported table name.")
+ readiness_state = serializers.ChoiceField(
+ choices=READINESS_STATE_CHOICES, help_text="User-facing warehouse readiness state for this table."
+ )
+ detail = serializers.CharField(help_text="Human-readable explanation of the table's readiness state.")
+ completed_chunks = serializers.IntegerField(help_text="Backfill chunks already copied into the warehouse.")
+ 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."
+ )
+ last_synced_at = serializers.DateTimeField(
+ allow_null=True, help_text="When PostHog most recently completed the upstream source import."
+ )
+
+
+class ManagedWarehouseSourcesStatusSerializer(serializers.Serializer):
+ readiness_state = serializers.ChoiceField(
+ choices=READINESS_STATE_CHOICES, help_text="Rolled-up readiness state for imported source tables."
+ )
+ detail = serializers.CharField(help_text="Human-readable explanation of imported source readiness.")
+ tables = ManagedWarehouseSourceTableStatusSerializer(
+ many=True, help_text="Per-table source backfill and live import application statuses."
+ )
+
+
+class ManagedWarehouseDataStatusResponseSerializer(serializers.Serializer):
+ overall_readiness_state = serializers.ChoiceField(
+ choices=READINESS_STATE_CHOICES, help_text="Highest-priority readiness state across all warehouse datasets."
+ )
+ events = ManagedWarehouseDatasetStatusSerializer(help_text="Events backfill readiness.")
+ persons = ManagedWarehouseDatasetStatusSerializer(help_text="Persons backfill readiness.")
+ sources = ManagedWarehouseSourcesStatusSerializer(help_text="Imported source table readiness.")
+ generated_at = serializers.DateTimeField(help_text="When this status snapshot was generated.")
diff --git a/products/data_warehouse/backend/presentation/views/data_warehouse.py b/products/data_warehouse/backend/presentation/views/data_warehouse.py
index 79328687bf9a..3b9315694df7 100644
--- a/products/data_warehouse/backend/presentation/views/data_warehouse.py
+++ b/products/data_warehouse/backend/presentation/views/data_warehouse.py
@@ -31,7 +31,11 @@ from posthog.utils import convert_property_value, flatten
from products.batch_exports.backend.facade.models import BatchExportRun
from products.cdp.backend.facade.models import HogFunction, HogFunctionState, HogFunctionType
from products.data_modeling.backend.facade.models import DataModelingJob, DataWarehouseSavedQuery
+from products.data_warehouse.backend.facade.api import get_managed_warehouse_data_status
from products.data_warehouse.backend.facade.models import TeamDataWarehouseConfig
+from products.data_warehouse.backend.presentation.managed_warehouse_data_status import (
+ ManagedWarehouseDataStatusResponseSerializer,
+)
from products.data_warehouse.backend.presentation.views import managed_warehouse
from products.warehouse_sources.backend.facade.hogql import get_view_or_table_by_name
from products.warehouse_sources.backend.facade.models import ExternalDataJob, ExternalDataSchema, ExternalDataSource
@@ -997,6 +1001,17 @@ class DataWarehouseViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
resp.data.update(managed_warehouse.team_backfill_state(self.team_id))
return resp
+ @extend_schema(responses={200: ManagedWarehouseDataStatusResponseSerializer})
+ @action(
+ methods=["GET"],
+ detail=False,
+ url_path="managed-warehouse-data-status",
+ required_scopes=["warehouse_view:read", "external_data_source:read"],
+ )
+ def managed_warehouse_data_status(self, request: Request, **kwargs) -> Response:
+ """Get events, persons, and imported source readiness for the managed warehouse."""
+ return Response(get_managed_warehouse_data_status(self.team_id))
+
@extend_schema(
responses={
200: inline_serializer(
diff --git a/products/data_warehouse/backend/tests/test_backfill_status.py b/products/data_warehouse/backend/tests/test_backfill_status.py
new file mode 100644
index 000000000000..3a3dcb3a8eb0
--- /dev/null
+++ b/products/data_warehouse/backend/tests/test_backfill_status.py
@@ -0,0 +1,54 @@
+from datetime import date
+
+import pytest
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from products.data_warehouse.backend.logic.backfill_status import describe_partition_key, historical_backfill_months
+from products.data_warehouse.backend.models import ManagedWarehouseBackfillPartition
+
+Granularity = ManagedWarehouseBackfillPartition.Granularity
+
+
+class TestDescribePartitionKey(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("historical_month", "1_2026-05", Granularity.MONTH, date(2026, 5, 1)),
+ ("single_day", "1_2026-05-04", Granularity.DAY, date(2026, 5, 4)),
+ ("persons_full_export", "42", Granularity.FULL, None),
+ ("multi_digit_team", "123456_2026-11", Granularity.MONTH, date(2026, 11, 1)),
+ ]
+ )
+ def test_decodes_the_period_a_key_covers(
+ self, _name: str, partition_key: str, expected_granularity: str, expected_period_start: date | None
+ ) -> None:
+ descriptor = describe_partition_key(partition_key)
+
+ assert descriptor.granularity == expected_granularity
+ assert descriptor.period_start == expected_period_start
+
+ @parameterized.expand(
+ [
+ ("no_period", "1_2026"),
+ ("not_a_key", "team-one"),
+ ("impossible_date", "1_2026-13-01"),
+ ("empty", ""),
+ ]
+ )
+ def test_rejects_a_key_it_cannot_decode(self, _name: str, partition_key: str) -> None:
+ with pytest.raises(ValueError):
+ describe_partition_key(partition_key)
+
+
+class TestHistoricalBackfillMonths(SimpleTestCase):
+ def test_stops_at_the_last_complete_month(self) -> None:
+ # The current month belongs to the daily backfill, so history must exclude it — counting it
+ # would leave the UI permanently one partition short of complete.
+ months = historical_backfill_months(date(2026, 3, 14), today=date(2026, 7, 13))
+
+ assert months == ["2026-03", "2026-04", "2026-05", "2026-06"]
+
+ def test_is_empty_when_the_first_event_is_this_month(self) -> None:
+ assert historical_backfill_months(date(2026, 7, 2), today=date(2026, 7, 13)) == []
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.py
new file mode 100644
index 000000000000..511b799b90d7
--- /dev/null
+++ b/products/data_warehouse/backend/tests/test_managed_warehouse_data_status.py
@@ -0,0 +1,213 @@
+from datetime import UTC, date, datetime
+from uuid import uuid4
+
+from freezegun import freeze_time
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from posthog.ducklake.models import DuckgresServerTeam, DuckgresSinkSchemaState
+
+from products.data_warehouse.backend.logic.managed_warehouse_data_status import (
+ QueueTailStatus,
+ ReadinessState,
+ SourceTableStatus,
+ dataset_status,
+ sort_source_tables,
+ source_table_readiness,
+)
+from products.data_warehouse.backend.models import ManagedWarehouseBackfillPartition
+
+Granularity = ManagedWarehouseBackfillPartition.Granularity
+LifecycleState = ManagedWarehouseBackfillPartition.LifecycleState
+
+
+class TestSourceTableReadiness(SimpleTestCase):
+ @parameterized.expand(
+ [
+ (
+ "persistent_failure_overrides_pending_batches",
+ 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,
+ 0,
+ {"pending_batches": 2, "oldest_pending_at": None, "last_applied_at": None},
+ True,
+ "catching_up",
+ ),
+ (
+ "primed_schema_without_pending_batches_is_up_to_date",
+ DuckgresSinkSchemaState.State.PRIMED,
+ 0,
+ {"pending_batches": 0, "oldest_pending_at": None, "last_applied_at": None},
+ True,
+ "up_to_date",
+ ),
+ (
+ "queue_outage_does_not_report_up_to_date",
+ DuckgresSinkSchemaState.State.PRIMED,
+ 0,
+ None,
+ False,
+ "unknown",
+ ),
+ ]
+ )
+ def test_state_precedence(
+ self,
+ _name: str,
+ lifecycle_state: str,
+ consecutive_failures: int,
+ queue_status: QueueTailStatus | None,
+ queue_available: bool,
+ expected_readiness: ReadinessState,
+ ) -> None:
+ state = DuckgresSinkSchemaState(
+ team_id=1,
+ schema_id=uuid4(),
+ state=lifecycle_state,
+ consecutive_failures=consecutive_failures,
+ )
+
+ readiness, _ = source_table_readiness(state, queue_status, queue_available)
+
+ assert readiness == expected_readiness
+
+
+@freeze_time("2026-07-13")
+class TestDatasetStatus(SimpleTestCase):
+ def _partition(
+ self,
+ *,
+ partition_key: str,
+ granularity: str,
+ lifecycle_state: str = LifecycleState.COMPLETED,
+ dataset: str = "events",
+ ) -> ManagedWarehouseBackfillPartition:
+ return ManagedWarehouseBackfillPartition(
+ team_id=1,
+ environment_id=1,
+ dataset=dataset,
+ partition_key=partition_key,
+ granularity=granularity,
+ lifecycle_state=lifecycle_state,
+ run_id="run",
+ started_at=datetime(2026, 7, 12, tzinfo=UTC),
+ updated_at=datetime(2026, 7, 12, tzinfo=UTC),
+ )
+
+ def _backfill(self, earliest_event_date: date | None = date(2026, 3, 14)) -> DuckgresServerTeam:
+ return DuckgresServerTeam(team_id=1, backfill_enabled=True, earliest_event_date=earliest_event_date)
+
+ def test_daily_partitions_do_not_count_toward_historical_progress(self) -> None:
+ # Daily runs land constantly once a team is live. Counting them as historical progress would
+ # push completed past total and report a half-copied warehouse as up to date.
+ partitions = [
+ self._partition(partition_key="1_2026-03", granularity=Granularity.MONTH),
+ self._partition(partition_key="1_2026-04", granularity=Granularity.MONTH),
+ self._partition(partition_key="1_2026-07-11", granularity=Granularity.DAY),
+ self._partition(partition_key="1_2026-07-12", granularity=Granularity.DAY),
+ ]
+
+ status = dataset_status(dataset="events", backfill=self._backfill(), partitions=partitions)
+
+ # March through June is the historical range on 2026-07-13; only two months are done.
+ assert status["completed_partitions"] == 2
+ assert status["total_partitions"] == 4
+ assert status["readiness_state"] == "backfilling"
+
+ def test_events_are_up_to_date_once_every_historical_month_completes(self) -> None:
+ partitions = [
+ self._partition(partition_key=f"1_2026-0{month}", granularity=Granularity.MONTH) for month in (3, 4, 5, 6)
+ ]
+
+ status = dataset_status(dataset="events", backfill=self._backfill(), partitions=partitions)
+
+ assert status["readiness_state"] == "up_to_date"
+ assert status["completed_partitions"] == 4
+
+ def test_persons_history_is_a_single_full_export(self) -> None:
+ partitions = [self._partition(partition_key="1", granularity=Granularity.FULL, dataset="persons")]
+
+ status = dataset_status(dataset="persons", backfill=self._backfill(), partitions=partitions)
+
+ assert status["total_partitions"] == 1
+ assert status["readiness_state"] == "up_to_date"
+
+ def test_failed_partition_needs_attention_and_names_itself(self) -> None:
+ partitions = [
+ self._partition(partition_key="1_2026-03", granularity=Granularity.MONTH),
+ self._partition(
+ partition_key="1_2026-04", granularity=Granularity.MONTH, lifecycle_state=LifecycleState.FAILED
+ ),
+ ]
+
+ status = dataset_status(dataset="events", backfill=self._backfill(), partitions=partitions)
+
+ assert status["readiness_state"] == "needs_attention"
+ assert status["current_partition"] == "1_2026-04"
+
+ def test_unknown_history_range_is_still_waiting(self) -> None:
+ # The scheduler caches earliest_event_date on first sight; until then there is no denominator.
+ status = dataset_status(dataset="events", backfill=self._backfill(earliest_event_date=None), partitions=[])
+
+ assert status["readiness_state"] == "waiting"
+ assert status["total_partitions"] is None
+
+
+class TestSortSourceTables(SimpleTestCase):
+ def _table(self, *, source_name: str, table_name: str, readiness_state: ReadinessState) -> SourceTableStatus:
+ return {
+ "schema_id": str(uuid4()),
+ "source_id": str(uuid4()),
+ "source_name": source_name,
+ "source_type": source_name,
+ "table_name": table_name,
+ "readiness_state": readiness_state,
+ "detail": "",
+ "completed_chunks": 0,
+ "total_chunks": None,
+ "pending_batches": None,
+ "oldest_pending_at": None,
+ "last_applied_at": None,
+ "last_synced_at": None,
+ }
+
+ def test_a_stalled_table_among_dozens_lands_on_the_first_page(self) -> None:
+ # The table paginates at 20 rows. A team importing dozens of tables would otherwise have the
+ # one that needs attention scattered anywhere by schema_id (a UUID), with no way to find it.
+ tables = [
+ self._table(source_name="Stripe", table_name=f"table_{i}", readiness_state="up_to_date") for i in range(30)
+ ]
+ tables.insert(25, self._table(source_name="Hubspot", table_name="contacts", readiness_state="needs_attention"))
+
+ ordered = sort_source_tables(tables)
+
+ assert ordered[0]["readiness_state"] == "needs_attention"
+ assert ordered[0]["table_name"] == "contacts"
+
+ def test_orders_by_severity_then_name(self) -> None:
+ tables = [
+ self._table(source_name="Zendesk", table_name="tickets", readiness_state="up_to_date"),
+ self._table(source_name="Stripe", table_name="charges", readiness_state="catching_up"),
+ self._table(source_name="Hubspot", table_name="deals", readiness_state="needs_attention"),
+ self._table(source_name="Amplitude", table_name="events", readiness_state="catching_up"),
+ self._table(source_name="Salesforce", table_name="accounts", readiness_state="up_to_date"),
+ ]
+
+ ordered = [(table["source_name"], table["readiness_state"]) for table in sort_source_tables(tables)]
+
+ assert ordered == [
+ ("Hubspot", "needs_attention"),
+ ("Amplitude", "catching_up"),
+ ("Stripe", "catching_up"),
+ ("Salesforce", "up_to_date"),
+ ("Zendesk", "up_to_date"),
+ ]
diff --git a/products/data_warehouse/frontend/generated/api.schemas.ts b/products/data_warehouse/frontend/generated/api.schemas.ts
index 8ffd54c1d7f5..57d8b513d69f 100644
--- a/products/data_warehouse/frontend/generated/api.schemas.ts
+++ b/products/data_warehouse/frontend/generated/api.schemas.ts
@@ -84,6 +84,166 @@ export interface EnableWarehouseBackfillResponseApi {
table_suffix: string
}
+/**
+ * * `not_configured` - not_configured
+ * * `waiting` - waiting
+ * * `backfilling` - backfilling
+ * * `catching_up` - catching_up
+ * * `up_to_date` - up_to_date
+ * * `needs_attention` - needs_attention
+ * * `unknown` - unknown
+ */
+export type ManagedWarehouseReadinessStateEnumApi =
+ (typeof ManagedWarehouseReadinessStateEnumApi)[keyof typeof ManagedWarehouseReadinessStateEnumApi]
+
+export const ManagedWarehouseReadinessStateEnumApi = {
+ NotConfigured: 'not_configured',
+ Waiting: 'waiting',
+ Backfilling: 'backfilling',
+ CatchingUp: 'catching_up',
+ UpToDate: 'up_to_date',
+ NeedsAttention: 'needs_attention',
+ Unknown: 'unknown',
+} as const
+
+/**
+ * * `events` - events
+ * * `persons` - persons
+ */
+export type DatasetEnumApi = (typeof DatasetEnumApi)[keyof typeof DatasetEnumApi]
+
+export const DatasetEnumApi = {
+ Events: 'events',
+ Persons: 'persons',
+} as const
+
+export interface ManagedWarehouseDatasetStatusApi {
+ /** Warehouse dataset represented by this status.
+ *
+ * * `events` - events
+ * * `persons` - persons */
+ dataset: DatasetEnumApi
+ /** User-facing readiness state for this dataset.
+ *
+ * * `not_configured` - not_configured
+ * * `waiting` - waiting
+ * * `backfilling` - backfilling
+ * * `catching_up` - catching_up
+ * * `up_to_date` - up_to_date
+ * * `needs_attention` - needs_attention
+ * * `unknown` - unknown */
+ readiness_state: ManagedWarehouseReadinessStateEnumApi
+ /** Human-readable explanation of the current readiness state. */
+ detail: string
+ /** Number of historical backfill partitions completed successfully. */
+ completed_partitions: number
+ /**
+ * Expected historical partitions, or null while the range is being calculated.
+ * @nullable
+ */
+ total_partitions: number | null
+ /**
+ * Partition currently running or requiring attention, when applicable.
+ * @nullable
+ */
+ current_partition: string | null
+ /**
+ * When the durable backfill status last changed.
+ * @nullable
+ */
+ last_updated_at: string | null
+}
+
+export interface ManagedWarehouseSourceTableStatusApi {
+ /** Imported source schema identifier. */
+ schema_id: string
+ /** Imported source connection identifier. */
+ source_id: string
+ /** Display name for the imported source connection. */
+ source_name: string
+ /** Type of the imported source connection. */
+ source_type: string
+ /** Imported table name. */
+ table_name: string
+ /** User-facing warehouse readiness state for this table.
+ *
+ * * `not_configured` - not_configured
+ * * `waiting` - waiting
+ * * `backfilling` - backfilling
+ * * `catching_up` - catching_up
+ * * `up_to_date` - up_to_date
+ * * `needs_attention` - needs_attention
+ * * `unknown` - unknown */
+ readiness_state: ManagedWarehouseReadinessStateEnumApi
+ /** Human-readable explanation of the table's readiness state. */
+ detail: string
+ /** Backfill chunks already copied into the warehouse. */
+ completed_chunks: number
+ /**
+ * Total backfill chunks, or null before the copy plan is ready.
+ * @nullable
+ */
+ 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.
+ * @nullable
+ */
+ last_applied_at: string | null
+ /**
+ * When PostHog most recently completed the upstream source import.
+ * @nullable
+ */
+ last_synced_at: string | null
+}
+
+export interface ManagedWarehouseSourcesStatusApi {
+ /** Rolled-up readiness state for imported source tables.
+ *
+ * * `not_configured` - not_configured
+ * * `waiting` - waiting
+ * * `backfilling` - backfilling
+ * * `catching_up` - catching_up
+ * * `up_to_date` - up_to_date
+ * * `needs_attention` - needs_attention
+ * * `unknown` - unknown */
+ readiness_state: ManagedWarehouseReadinessStateEnumApi
+ /** Human-readable explanation of imported source readiness. */
+ detail: string
+ /** Per-table source backfill and live import application statuses. */
+ tables: ManagedWarehouseSourceTableStatusApi[]
+}
+
+export interface ManagedWarehouseDataStatusResponseApi {
+ /** Highest-priority readiness state across all warehouse datasets.
+ *
+ * * `not_configured` - not_configured
+ * * `waiting` - waiting
+ * * `backfilling` - backfilling
+ * * `catching_up` - catching_up
+ * * `up_to_date` - up_to_date
+ * * `needs_attention` - needs_attention
+ * * `unknown` - unknown */
+ overall_readiness_state: ManagedWarehouseReadinessStateEnumApi
+ /** Events backfill readiness. */
+ events: ManagedWarehouseDatasetStatusApi
+ /** Persons backfill readiness. */
+ persons: ManagedWarehouseDatasetStatusApi
+ /** Imported source table readiness. */
+ sources: ManagedWarehouseSourcesStatusApi
+ /** When this status snapshot was generated. */
+ generated_at: string
+}
+
export interface ProvisionWarehouseRequestApi {
/** Name for the new database */
database_name: string
diff --git a/products/data_warehouse/frontend/generated/api.ts b/products/data_warehouse/frontend/generated/api.ts
index ae08dbd3fd5e..f924d0970528 100644
--- a/products/data_warehouse/frontend/generated/api.ts
+++ b/products/data_warehouse/frontend/generated/api.ts
@@ -25,6 +25,7 @@ import type {
FixHogqlListParams,
InsightVariableApi,
InsightVariablesListParams,
+ ManagedWarehouseDataStatusResponseApi,
PaginatedDataModelingJobListApi,
PaginatedDataWarehouseModelPathListApi,
PaginatedDataWarehouseSavedQueryColumnAnnotationListApi,
@@ -328,6 +329,26 @@ export const dataWarehouseJobStatsRetrieve = async (projectId: string, options?:
})
}
+export const getDataWarehouseManagedWarehouseDataStatusRetrieveUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/data_warehouse/managed-warehouse-data-status/`
+}
+
+/**
+ * Get events, persons, and imported source readiness for the managed warehouse.
+ */
+export const dataWarehouseManagedWarehouseDataStatusRetrieve = async (
+ projectId: string,
+ options?: RequestInit
+): Promise<ManagedWarehouseDataStatusResponseApi> => {
+ return apiMutator<ManagedWarehouseDataStatusResponseApi>(
+ getDataWarehouseManagedWarehouseDataStatusRetrieveUrl(projectId),
+ {
+ ...options,
+ method: 'GET',
+ }
+ )
+}
+
export const getDataWarehousePropertyValuesRetrieveUrl = (projectId: string) => {
return `/api/projects/${projectId}/data_warehouse/property_values/`
}
diff --git a/products/data_warehouse/mcp/tools.yaml b/products/data_warehouse/mcp/tools.yaml
index 436175b19302..3853c0a706b9 100644
--- a/products/data_warehouse/mcp/tools.yaml
+++ b/products/data_warehouse/mcp/tools.yaml
@@ -45,6 +45,9 @@ tools:
data-warehouse-job-stats-retrieve:
operation: data_warehouse_job_stats_retrieve
enabled: false
+ data-warehouse-managed-warehouse-data-status-retrieve:
+ operation: data_warehouse_managed_warehouse_data_status_retrieve
+ enabled: false
data-warehouse-property-values-retrieve:
operation: data_warehouse_property_values_retrieve
enabled: false
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 22b5a941c11c..a0f7f5e289c8 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -18959,6 +18959,18 @@ export namespace Schemas {
readonly team: number;
}
+ /**
+ * * `events` - events
+ * * `persons` - persons
+ */
+ export type DatasetEnum = typeof DatasetEnum[keyof typeof DatasetEnum];
+
+
+ export const DatasetEnum = {
+ Events: 'events',
+ Persons: 'persons',
+ } as const;
+
export interface DatasetItem {
readonly id: string;
dataset: string;
@@ -33228,6 +33240,155 @@ export namespace Schemas {
readonly duration_ms: number | null;
}
+ /**
+ * * `not_configured` - not_configured
+ * * `waiting` - waiting
+ * * `backfilling` - backfilling
+ * * `catching_up` - catching_up
+ * * `up_to_date` - up_to_date
+ * * `needs_attention` - needs_attention
+ * * `unknown` - unknown
+ */
+ export type ManagedWarehouseReadinessStateEnum = typeof ManagedWarehouseReadinessStateEnum[keyof typeof ManagedWarehouseReadinessStateEnum];
+
+
+ export const ManagedWarehouseReadinessStateEnum = {
+ NotConfigured: 'not_configured',
+ Waiting: 'waiting',
+ Backfilling: 'backfilling',
+ CatchingUp: 'catching_up',
+ UpToDate: 'up_to_date',
+ NeedsAttention: 'needs_attention',
+ Unknown: 'unknown',
+ } as const;
+
+ export interface ManagedWarehouseDatasetStatus {
+ /** Warehouse dataset represented by this status.
+ *
+ * * `events` - events
+ * * `persons` - persons */
+ dataset: DatasetEnum;
+ /** User-facing readiness state for this dataset.
+ *
+ * * `not_configured` - not_configured
+ * * `waiting` - waiting
+ * * `backfilling` - backfilling
+ * * `catching_up` - catching_up
+ * * `up_to_date` - up_to_date
+ * * `needs_attention` - needs_attention
+ * * `unknown` - unknown */
+ readiness_state: ManagedWarehouseReadinessStateEnum;
+ /** Human-readable explanation of the current readiness state. */
+ detail: string;
+ /** Number of historical backfill partitions completed successfully. */
+ completed_partitions: number;
+ /**
+ * Expected historical partitions, or null while the range is being calculated.
+ * @nullable
+ */
+ total_partitions: number | null;
+ /**
+ * Partition currently running or requiring attention, when applicable.
+ * @nullable
+ */
+ current_partition: string | null;
+ /**
+ * When the durable backfill status last changed.
+ * @nullable
+ */
+ last_updated_at: string | null;
+ }
+
+ export interface ManagedWarehouseSourceTableStatus {
+ /** Imported source schema identifier. */
+ schema_id: string;
+ /** Imported source connection identifier. */
+ source_id: string;
+ /** Display name for the imported source connection. */
+ source_name: string;
+ /** Type of the imported source connection. */
+ source_type: string;
+ /** Imported table name. */
+ table_name: string;
+ /** User-facing warehouse readiness state for this table.
+ *
+ * * `not_configured` - not_configured
+ * * `waiting` - waiting
+ * * `backfilling` - backfilling
+ * * `catching_up` - catching_up
+ * * `up_to_date` - up_to_date
+ * * `needs_attention` - needs_attention
+ * * `unknown` - unknown */
+ readiness_state: ManagedWarehouseReadinessStateEnum;
+ /** Human-readable explanation of the table's readiness state. */
+ detail: string;
+ /** Backfill chunks already copied into the warehouse. */
+ completed_chunks: number;
+ /**
+ * Total backfill chunks, or null before the copy plan is ready.
+ * @nullable
+ */
+ 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.
+ * @nullable
+ */
+ last_applied_at: string | null;
+ /**
+ * When PostHog most recently completed the upstream source import.
+ * @nullable
+ */
+ last_synced_at: string | null;
+ }
+
+ export interface ManagedWarehouseSourcesStatus {
+ /** Rolled-up readiness state for imported source tables.
+ *
+ * * `not_configured` - not_configured
+ * * `waiting` - waiting
+ * * `backfilling` - backfilling
+ * * `catching_up` - catching_up
+ * * `up_to_date` - up_to_date
+ * * `needs_attention` - needs_attention
+ * * `unknown` - unknown */
+ readiness_state: ManagedWarehouseReadinessStateEnum;
+ /** Human-readable explanation of imported source readiness. */
+ detail: string;
+ /** Per-table source backfill and live import application statuses. */
+ tables: ManagedWarehouseSourceTableStatus[];
+ }
+
+ export interface ManagedWarehouseDataStatusResponse {
+ /** Highest-priority readiness state across all warehouse datasets.
+ *
+ * * `not_configured` - not_configured
+ * * `waiting` - waiting
+ * * `backfilling` - backfilling
+ * * `catching_up` - catching_up
+ * * `up_to_date` - up_to_date
+ * * `needs_attention` - needs_attention
+ * * `unknown` - unknown */
+ overall_readiness_state: ManagedWarehouseReadinessStateEnum;
+ /** Events backfill readiness. */
+ events: ManagedWarehouseDatasetStatus;
+ /** Persons backfill readiness. */
+ persons: ManagedWarehouseDatasetStatus;
+ /** Imported source table readiness. */
+ sources: ManagedWarehouseSourcesStatus;
+ /** When this status snapshot was generated. */
+ generated_at: string;
+ }
+
export interface MarkToleratedInput {
/** UUID of the changed snapshot to mark as a known tolerated alternate. Future runs that produce the same alternate hash for this identifier will not be flagged as changes. */
snapshot_id: string;
diff --git a/tach.toml b/tach.toml
index f70a2d93ecff..bbd2c72227db 100644
--- a/tach.toml
+++ b/tach.toml
@@ -276,6 +276,7 @@ depends_on = [
"products.cdp",
"products.data_modeling",
"products.revenue_analytics", "products.warehouse_sources", "products.data_tools", "products.batch_exports",
+ "products.warehouse_sources_queue",
]
layer = "modules"