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.

fix(data-warehouse): read view state from the newest run (#94345)

Jovan Sakovic620340336f87
diff --git a/posthog/temporal/data_modeling/activities/succeed_materialization.py b/posthog/temporal/data_modeling/activities/succeed_materialization.py
index a8d8563b44fa..31528309faba 100644
--- a/posthog/temporal/data_modeling/activities/succeed_materialization.py
+++ b/posthog/temporal/data_modeling/activities/succeed_materialization.py
@@ -14,6 +14,7 @@ from products.data_modeling.backend.facade.models import (
DataModelingJob,
DataModelingJobEngine,
DataModelingJobStatus,
+ DataWarehouseSavedQuery,
Node,
)
@@ -121,6 +122,7 @@ def _succeed_node_and_data_modeling_job(
job.last_run_at = dt.datetime.now(dt.UTC)
job.error = None
job.save()
+ _clear_modified_marker(job)
return SucceedNodeAndJobOutcome(
node=node,
@@ -130,6 +132,19 @@ def _succeed_node_and_data_modeling_job(
)
+def _clear_modified_marker(job: DataModelingJob) -> None:
+ # The API stamps `Modified` on a query edit. A serving run that started after the last save has
+ # consumed that edit, so the marker must go. `updated_at` moves on every save, which is why the
+ # comparison happens here, at run time, and not when the view is read.
+ if job.engine == DataModelingJobEngine.DUCKGRES or job.saved_query_id is None:
+ return
+ DataWarehouseSavedQuery.objects.filter(
+ id=job.saved_query_id,
+ status=DataWarehouseSavedQuery.Status.MODIFIED,
+ updated_at__lte=job.created_at,
+ ).update(status=None)
+
+
@activity.defn
async def succeed_materialization_activity(inputs: SucceedMaterializationInputs) -> SucceedMaterializationResult:
bind_contextvars(team_id=inputs.team_id)
diff --git a/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py b/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py
index 446882b3703d..c86d5beb777c 100644
--- a/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py
+++ b/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py
@@ -1,4 +1,5 @@
import asyncio
+import datetime as dt
import contextlib
from collections.abc import AsyncIterator, Callable, Collection, Iterable
from dataclasses import replace
@@ -853,6 +854,30 @@ class TestSucceedMaterializationActivity:
assert is_node_suspended(anode, DataModelingJobEngine.CLICKHOUSE) is False
assert is_node_suspended(anode, DataModelingJobEngine.DUCKGRES) is True
+ @pytest.mark.parametrize("edited_after_the_run_started", [False, True])
+ async def test_success_clears_modified_only_when_the_run_started_after_the_edit(
+ self, activity_environment, ateam, anode, ajob, adag, asaved_query, edited_after_the_run_started
+ ):
+ # The API stamps Modified on a query edit; a run that started after the edit consumes it,
+ # while an edit landing mid-run must survive until the next run.
+ edited_at = ajob.created_at + dt.timedelta(minutes=1 if edited_after_the_run_started else -1)
+ await database_sync_to_async(DataWarehouseSavedQuery.objects.filter(id=asaved_query.id).update)(
+ status=DataWarehouseSavedQuery.Status.MODIFIED, updated_at=edited_at
+ )
+ inputs = SucceedMaterializationInputs(
+ team_id=ateam.pk,
+ node_id=str(anode.id),
+ dag_id=str(adag.id),
+ job_id=str(ajob.id),
+ row_count=1,
+ duration_seconds=1.0,
+ )
+ await activity_environment.run(succeed_materialization_activity, inputs)
+
+ await database_sync_to_async(asaved_query.refresh_from_db)()
+ expected = DataWarehouseSavedQuery.Status.MODIFIED if edited_after_the_run_started else None
+ assert asaved_query.status == expected
+
async def test_flags_enrichment_needed_when_hash_missing(self, activity_environment, ateam, anode, ajob, adag):
# A view with no stored enrichment hash (never enriched) must signal the workflow to enrich.
inputs = SucceedMaterializationInputs(
@@ -883,6 +908,29 @@ class TestSucceedMaterializationActivity:
result = await activity_environment.run(succeed_materialization_activity, inputs)
assert result.enrichment_needed is False
+ async def test_flags_enrichment_needed_once_the_table_is_linked(
+ self, activity_environment, ateam, anode, ajob, adag, asaved_query
+ ):
+ # The definition-only pass stored an unsampled hash. The first run links the table before this
+ # activity runs, while its own job is still Running, and that alone must flip the hash.
+ await database_sync_to_async(DataWarehouseSavedQuery.objects.filter(id=asaved_query.id).update)(
+ semantic_enrichment_hash=compute_enrichment_hash(asaved_query)
+ )
+ table = await database_sync_to_async(DataWarehouseTable.objects.create)(
+ team=ateam, name="test_model", format="Delta"
+ )
+ await database_sync_to_async(DataWarehouseSavedQuery.objects.filter(id=asaved_query.id).update)(table=table)
+ inputs = SucceedMaterializationInputs(
+ team_id=ateam.pk,
+ node_id=str(anode.id),
+ dag_id=str(adag.id),
+ job_id=str(ajob.id),
+ row_count=1,
+ duration_seconds=1.0,
+ )
+ result = await activity_environment.run(succeed_materialization_activity, inputs)
+ assert result.enrichment_needed is True
+
class TestPrepareQueryableTableActivity:
async def test_creates_warehouse_table_from_saved_query(self, activity_environment, ateam, asaved_query, ajob):
diff --git a/products/data_modeling/backend/logic/enrich_view_semantics.py b/products/data_modeling/backend/logic/enrich_view_semantics.py
index a674ff520fca..1c82e115b0fa 100644
--- a/products/data_modeling/backend/logic/enrich_view_semantics.py
+++ b/products/data_modeling/backend/logic/enrich_view_semantics.py
@@ -87,9 +87,16 @@ def _view_columns(saved_query: DataWarehouseSavedQuery) -> list[dict[str, Any]]:
return result
+def _has_sampleable_rows(saved_query: DataWarehouseSavedQuery) -> bool:
+ """The prepare step links the table before the succeed activity asks this, while the run's job is
+ still Running, so the link is the one fact that is true on the first success. It is also a column,
+ which keeps the save-signal path free of queries."""
+ return saved_query.table_id is not None
+
+
def compute_enrichment_hash(saved_query: DataWarehouseSavedQuery) -> str:
"""Fingerprint the inputs that would change the descriptions: query text, column set, and whether a
- row sample is available. The `sample_bit` flips once the view is first materialized (table + last run),
+ row sample is available. The `sample_bit` flips once the view is first materialized (a backing table is linked),
so descriptions upgrade exactly once with real row data rather than staying at the definition-only pass.
"""
query = saved_query.query or {}
@@ -97,7 +104,7 @@ def compute_enrichment_hash(saved_query: DataWarehouseSavedQuery) -> str:
column_pairs = sorted(
(name, _clickhouse_type(column_meta)) for name, column_meta in (saved_query.columns or {}).items()
)
- sample_bit = "sampled" if (saved_query.table_id and saved_query.last_run_at) else "unsampled"
+ sample_bit = "sampled" if _has_sampleable_rows(saved_query) else "unsampled"
payload = json.dumps([query_str, column_pairs, sample_bit], sort_keys=True)
return hashlib.sha256(payload.encode("utf-8")).hexdigest()
@@ -369,7 +376,7 @@ def enrich_view_semantics_sync(team_id: int, saved_query_id: str) -> dict[str, A
business_context = get_team_business_context(team)
lineage = _gather_lineage(team, saved_query, query_str)
# Only sample a materialized view — running the raw view query for an unmaterialized one is unbounded.
- row_sample = _get_row_sample(saved_query) if (saved_query.table_id and saved_query.last_run_at) else []
+ row_sample = _get_row_sample(saved_query) if _has_sampleable_rows(saved_query) else []
prompt = build_bounded_view_enrichment_prompt(
view_name=saved_query.name,
query_definition=query_str,
diff --git a/products/data_modeling/backend/logic/saved_query_reads.py b/products/data_modeling/backend/logic/saved_query_reads.py
index 3c2cf0d3dddd..b52e69e4dbdc 100644
--- a/products/data_modeling/backend/logic/saved_query_reads.py
+++ b/products/data_modeling/backend/logic/saved_query_reads.py
@@ -8,6 +8,7 @@ from django.conf import settings
from ..facade.contracts import SavedQuerySummary
from ..models.datawarehouse_saved_query import DataWarehouseSavedQuery
from ..models.node import Node
+from .saved_query_freshness import saved_query_materialized_at
def _clickhouse_type(entry: object) -> str | None:
@@ -51,7 +52,7 @@ def get_saved_query_summary(team_id: int, saved_query_id: UUID | str) -> SavedQu
id=str(saved_query.id),
team_id=saved_query.team_id,
name=saved_query.name,
- last_run_at=saved_query.last_run_at,
+ last_run_at=saved_query_materialized_at(saved_query),
)
diff --git a/products/data_modeling/backend/migrations/0033_alter_datawarehousesavedquery_status.py b/products/data_modeling/backend/migrations/0033_alter_datawarehousesavedquery_status.py
new file mode 100644
index 000000000000..a0eda0c0a6d8
--- /dev/null
+++ b/products/data_modeling/backend/migrations/0033_alter_datawarehousesavedquery_status.py
@@ -0,0 +1,27 @@
+# Generated by Django 5.2.17 on 2026-09-03 15:20
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [("data_modeling", "0032_datawarehousesavedquery_dwsavedquery_team_live_name")]
+
+ operations = [
+ migrations.AlterField(
+ model_name="datawarehousesavedquery",
+ name="status",
+ field=models.CharField(
+ choices=[
+ ("Cancelled", "Cancelled"),
+ ("Modified", "Modified"),
+ ("Completed", "Completed"),
+ ("Failed", "Failed"),
+ ("Running", "Running"),
+ ("Skipped", "Skipped"),
+ ],
+ help_text="The status of when this SavedQuery last ran.",
+ max_length=64,
+ null=True,
+ ),
+ ),
+ ]
diff --git a/products/data_modeling/backend/migrations/max_migration.txt b/products/data_modeling/backend/migrations/max_migration.txt
index 57f6099077f1..0d8b6aa291fa 100644
--- a/products/data_modeling/backend/migrations/max_migration.txt
+++ b/products/data_modeling/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0032_datawarehousesavedquery_dwsavedquery_team_live_name
+0033_alter_datawarehousesavedquery_status
diff --git a/products/data_modeling/backend/models/datawarehouse_saved_query.py b/products/data_modeling/backend/models/datawarehouse_saved_query.py
index e8419bdd12b8..51e33d6330bd 100644
--- a/products/data_modeling/backend/models/datawarehouse_saved_query.py
+++ b/products/data_modeling/backend/models/datawarehouse_saved_query.py
@@ -86,6 +86,7 @@ class DataWarehouseSavedQuery(CreatedMetaFields, UUIDTModel, UpdatedMetaFields,
COMPLETED = "Completed"
FAILED = "Failed"
RUNNING = "Running"
+ SKIPPED = "Skipped"
class Origin(models.TextChoices):
"""Possible origin of this SavedQuery"""
diff --git a/products/data_modeling/backend/tests/test_enrich_view_semantics.py b/products/data_modeling/backend/tests/test_enrich_view_semantics.py
index ea5183ee8cd2..e5dfa532a1f1 100644
--- a/products/data_modeling/backend/tests/test_enrich_view_semantics.py
+++ b/products/data_modeling/backend/tests/test_enrich_view_semantics.py
@@ -4,8 +4,6 @@ from typing import Any
import pytest
from unittest.mock import patch
-from django.utils import timezone
-
from parameterized import parameterized
from posthog.models import Organization, Team
@@ -259,15 +257,17 @@ class TestBuildViewEnrichmentPrompt:
class TestComputeEnrichmentHash:
- def test_sample_bit_changes_hash_after_materialization(self):
- # The first successful materialization (table + last_run_at) must register as a change so the view
- # re-enriches once with real row data.
+ def test_sample_bit_flips_when_a_table_is_linked(self, django_assert_num_queries):
+ # The first successful materialization links the table; that must register as a change so the
+ # view re-enriches once with real row data. The hash also runs from the save signal, so it must
+ # read nothing but the row it was given.
team = _team()
sq = _saved_query(team, columns=_columns("amount"))
- unsampled = compute_enrichment_hash(sq)
- sq.table_id = uuid.uuid4()
- sq.last_run_at = timezone.now()
- assert compute_enrichment_hash(sq) != unsampled
+ with django_assert_num_queries(0):
+ unsampled = compute_enrichment_hash(sq)
+ sq.table_id = uuid.uuid4()
+ sampled = compute_enrichment_hash(sq)
+ assert sampled != unsampled
class TestMaybeDispatchEnrichment:
diff --git a/products/data_warehouse/backend/presentation/views/data_warehouse.py b/products/data_warehouse/backend/presentation/views/data_warehouse.py
index 6189ac187ba0..e05d2ab5a186 100644
--- a/products/data_warehouse/backend/presentation/views/data_warehouse.py
+++ b/products/data_warehouse/backend/presentation/views/data_warehouse.py
@@ -3,7 +3,7 @@ from typing import cast
from zoneinfo import ZoneInfo
from django.db import connection
-from django.db.models import Count, Q, Sum
+from django.db.models import Count, OuterRef, Q, Subquery, Sum
from django.db.models.functions import TruncDate, TruncHour
import structlog
@@ -32,7 +32,7 @@ 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_modeling.backend.facade.models import DataModelingJob, DataModelingJobEngine, DataWarehouseSavedQuery
from products.data_quality.backend.presentation.serializers import DataQualityGateConfigSerializer
from products.data_quality.backend.presentation.views import data_quality_gate_response
from products.data_warehouse.backend.facade.api import get_managed_warehouse_data_status, get_source_schema_statuses
@@ -659,13 +659,22 @@ class DataWarehouseViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
try:
results = []
- # Get failed materializations from DataWarehouseSavedQuery
- # Only show views that are actively materialized but failing
- failed_materializations = DataWarehouseSavedQuery.objects.filter(
- team_id=self.team_id,
- deleted=False,
- is_materialized=True,
- status=DataWarehouseSavedQuery.Status.FAILED,
+ # A view is failing when its newest run failed. The duckgres shadow shares the saved query
+ # and finalizes after the serving run, so it is excluded from the verdict.
+ serving_run = (
+ DataModelingJob.objects.filter(saved_query_id=OuterRef("id"))
+ .exclude(engine=DataModelingJobEngine.DUCKGRES)
+ .order_by("-last_run_at")
+ )
+ failed_materializations = (
+ DataWarehouseSavedQuery.objects.exclude(deleted=True)
+ .filter(team_id=self.team_id, is_materialized=True)
+ .annotate(
+ latest_run_status=Subquery(serving_run.values("status")[:1]),
+ latest_run_error=Subquery(serving_run.values("error")[:1]),
+ latest_run_at=Subquery(serving_run.values("last_run_at")[:1]),
+ )
+ .filter(latest_run_status=DataModelingJob.Status.FAILED)
)
for query in failed_materializations:
@@ -675,8 +684,8 @@ class DataWarehouseViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
"name": query.name,
"type": "materialized_view",
"status": "failed",
- "error": query.latest_error,
- "failed_at": query.last_run_at.isoformat() if query.last_run_at else None,
+ "error": query.latest_run_error,
+ "failed_at": query.latest_run_at.isoformat() if query.latest_run_at else None,
"url": f"/data-warehouse/view/{query.id}",
}
)
diff --git a/products/data_warehouse/backend/presentation/views/saved_query.py b/products/data_warehouse/backend/presentation/views/saved_query.py
index 551358edf8d9..b75db156f63d 100644
--- a/products/data_warehouse/backend/presentation/views/saved_query.py
+++ b/products/data_warehouse/backend/presentation/views/saved_query.py
@@ -53,6 +53,7 @@ from products.access_control.backend.presentation.access_control import (
from products.data_modeling.backend.facade.api import MAX_LOOKBACK_SECONDS, get_incremental_config
from products.data_modeling.backend.facade.models import (
DataModelingJob,
+ DataModelingJobEngine,
DataWarehouseSavedQuery,
DataWarehouseSavedQueryColumnAnnotation,
Edge,
@@ -452,16 +453,46 @@ class DataWarehouseSavedQuerySerializerMixin:
This mixin is intended to be used with serializers.ModelSerializer subclasses.
"""
+ def _serving_run(self, view: DataWarehouseSavedQuery) -> DataModelingJob | None:
+ """The newest materialization run that serves this view, or None if it has never run.
+
+ Prefers the prefetched job so a list of views costs one query. Falls back to a lookup for
+ the detail route, which has no prefetch.
+ """
+ try:
+ jobs = view.jobs # type: ignore[attr-defined]
+ return jobs[0] if jobs else None
+ except AttributeError:
+ return (
+ DataModelingJob.objects.filter(saved_query_id=view.id)
+ .exclude(engine=DataModelingJobEngine.DUCKGRES)
+ .order_by("-last_run_at")
+ .first()
+ )
+
@extend_schema_field(serializers.DateTimeField(allow_null=True))
def get_last_run_at(self, view: DataWarehouseSavedQuery) -> datetime | None:
- try:
- jobs = view.jobs # type: ignore
- if len(jobs) > 0:
- return jobs[0].last_run_at
- except Exception:
- pass
+ run = self._serving_run(view)
+ return run.last_run_at if run is not None else view.last_run_at
+
+ @extend_schema_field(serializers.ChoiceField(choices=DataWarehouseSavedQuery.Status.choices, allow_null=True))
+ def get_status(self, view: DataWarehouseSavedQuery) -> str | None:
+ run = self._serving_run(view)
+ if run is None:
+ return view.status
+ # Modified means "edited and not materialized since", which no run can express. A run that
+ # happened after the edit answers it, so the column only wins while the edit is the newer fact.
+ edited_since_the_run = (
+ view.status == DataWarehouseSavedQuery.Status.MODIFIED
+ and view.updated_at is not None
+ and view.updated_at > run.last_run_at
+ )
+ return view.status if edited_since_the_run else run.status
- return view.last_run_at
+ @extend_schema_field(serializers.CharField(allow_null=True))
+ def get_latest_error(self, view: DataWarehouseSavedQuery) -> str | None:
+ run = self._serving_run(view)
+ return run.error if run is not None else view.latest_error
@extend_schema_field(serializers.CharField(allow_null=True))
def get_sync_frequency(self, schema: DataWarehouseSavedQuery):
@@ -541,6 +572,8 @@ class DataWarehouseSavedQueryMinimalSerializer(
read_only=True, help_text=SYNC_FREQUENCY_MANAGED_BY_DAG_HELP_TEXT
)
last_run_at = serializers.SerializerMethodField(read_only=True)
+ status = serializers.SerializerMethodField(read_only=True)
+ latest_error = serializers.SerializerMethodField(read_only=True)
managed_viewset_kind = serializers.SerializerMethodField(read_only=True)
folder_id = serializers.UUIDField(source="folder.id", read_only=True, allow_null=True)
folder_name = serializers.CharField(source="folder.name", read_only=True, allow_null=True)
@@ -687,6 +720,8 @@ class DataWarehouseSavedQuerySerializer(
sync_frequency_bounds = serializers.SerializerMethodField(read_only=True, help_text=SYNC_FREQUENCY_BOUNDS_HELP_TEXT)
latest_history_id = serializers.SerializerMethodField(read_only=True)
last_run_at = serializers.SerializerMethodField(read_only=True)
+ status = serializers.SerializerMethodField(read_only=True)
+ latest_error = serializers.SerializerMethodField(read_only=True)
managed_viewset_kind = serializers.SerializerMethodField(read_only=True)
suspended = serializers.SerializerMethodField(read_only=True)
folder_id = TeamScopedPrimaryKeyRelatedField(
@@ -1541,7 +1576,11 @@ class DataWarehouseSavedQueryViewSet(TeamAndOrgViewSetMixin, AccessControlViewSe
"managed_viewset",
"column_annotations",
Prefetch(
- "datamodelingjob_set", queryset=DataModelingJob.objects.order_by("-last_run_at")[:1], to_attr="jobs"
+ "datamodelingjob_set",
+ queryset=DataModelingJob.objects.exclude(engine=DataModelingJobEngine.DUCKGRES).order_by(
+ "-last_run_at"
+ )[:1],
+ to_attr="jobs",
),
)
.exclude(deleted=True)
diff --git a/products/data_warehouse/backend/tests/api/test_data_warehouse.py b/products/data_warehouse/backend/tests/api/test_data_warehouse.py
index 98c083f14b9a..17542dca6c7b 100644
--- a/products/data_warehouse/backend/tests/api/test_data_warehouse.py
+++ b/products/data_warehouse/backend/tests/api/test_data_warehouse.py
@@ -12,7 +12,7 @@ from rest_framework.response import Response
from products.dashboards.backend.models.dashboard import Dashboard
from products.dashboards.backend.models.dashboard_tile import DashboardTile
-from products.data_modeling.backend.facade.models import DataModelingJob
+from products.data_modeling.backend.facade.models import DataModelingJob, DataModelingJobEngine, DataWarehouseSavedQuery
from products.data_warehouse.backend.models.team_data_warehouse_config import TeamDataWarehouseConfig
from products.warehouse_sources.backend.facade.models import (
DataWarehouseTable,
@@ -733,3 +733,69 @@ class TestDataHealthIssuesPersonalAPIKey(APIBaseTest):
value = self.create_personal_api_key_with_scopes(scopes)
response = self._get(value)
assert response.status_code == status.HTTP_403_FORBIDDEN, response.json()
+
+
+class TestDataHealthIssuesReadsTheNewestRun(APIBaseTest):
+ """What the failing-materializations panel reports.
+
+ The panel used to read `status` and `latest_error` on the saved query. Both are written only by
+ the retired v1 workflow, so on a converted team they hold whatever v1 last left there, or nothing
+ at all. The newest materialization run is the live signal.
+ """
+
+ def _view(self, name: str, **frozen) -> DataWarehouseSavedQuery:
+ return DataWarehouseSavedQuery.objects.create(
+ team=self.team,
+ name=name,
+ query={"kind": "HogQLQuery", "query": "SELECT 1 AS one"},
+ created_by=self.user,
+ is_materialized=True,
+ **frozen,
+ )
+
+ def _run(self, view, statuss, *, error=None, engine=DataModelingJobEngine.CLICKHOUSE, minutes_ago=0):
+ return DataModelingJob.objects.create(
+ team=self.team,
+ saved_query=view,
+ status=statuss,
+ error=error,
+ engine=engine,
+ rows_materialized=0,
+ last_run_at=timezone.now() - timedelta(minutes=minutes_ago),
+ )
+
+ def _reported(self) -> dict[str, dict]:
+ response = self.client.get(f"/api/projects/{self.team.id}/data_warehouse/data_health_issues/")
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ return {r["name"]: r for r in response.json()["results"] if r["type"] == "materialized_view"}
+
+ def test_a_view_whose_newest_run_failed_is_reported_with_that_error(self):
+ view = self._view("orders", status=None, latest_error=None)
+ self._run(view, DataModelingJob.Status.FAILED, error="Memory limit exceeded")
+
+ reported = self._reported()
+
+ assert "orders" in reported
+ assert reported["orders"]["error"] == "Memory limit exceeded"
+
+ def test_a_view_that_recovered_is_not_reported_from_its_frozen_columns(self):
+ view = self._view("orders", status="Failed", latest_error="Ancient v1 error")
+ self._run(view, DataModelingJob.Status.FAILED, error="Ancient v1 error", minutes_ago=60)
+ self._run(view, DataModelingJob.Status.COMPLETED, minutes_ago=1)
+
+ assert "orders" not in self._reported()
+
+ def test_a_duckgres_shadow_success_does_not_stand_in_for_the_serving_run(self):
+ view = self._view("orders")
+ self._run(view, DataModelingJob.Status.FAILED, error="Serving run failed", minutes_ago=10)
+ self._run(view, DataModelingJob.Status.COMPLETED, engine=DataModelingJobEngine.DUCKGRES, minutes_ago=1)
+
+ reported = self._reported()
+
+ assert "orders" in reported
+ assert reported["orders"]["error"] == "Serving run failed"
+
+ def test_a_view_that_has_never_run_is_not_reported(self):
+ self._view("orders", status="Failed", latest_error="Ancient v1 error")
+
+ assert "orders" not in self._reported()
diff --git a/products/data_warehouse/backend/tests/api/test_saved_query.py b/products/data_warehouse/backend/tests/api/test_saved_query.py
index c05628dcec8e..fdec4f5e07db 100644
--- a/products/data_warehouse/backend/tests/api/test_saved_query.py
+++ b/products/data_warehouse/backend/tests/api/test_saved_query.py
@@ -11,6 +11,7 @@ from django.core.exceptions import ValidationError
from django.db import connection
from django.test import SimpleTestCase
from django.test.utils import CaptureQueriesContext
+from django.utils import timezone
from parameterized import parameterized
@@ -22,6 +23,7 @@ from products.data_modeling.backend.facade.modeling import DataWarehouseModelPat
from products.data_modeling.backend.facade.models import (
DAG,
DataModelingJob,
+ DataModelingJobEngine,
DataWarehouseManagedViewSet,
DataWarehouseSavedQuery,
DataWarehouseSavedQueryColumnAnnotation,
@@ -2660,3 +2662,103 @@ class TestSavedQueryDescription(APIBaseTest):
results = self.client.get(self._base()).json()["results"]
described = {v["name"]: v.get("description") for v in results}
assert described["described_view"] == "Listed description."
+
+
+class TestSavedQueryStateComesFromTheServingRun(APIBaseTest):
+ """The serializer reports run state from the newest serving run, not the frozen v1 columns."""
+
+ def _view(self, name: str, **column_state) -> DataWarehouseSavedQuery:
+ return DataWarehouseSavedQuery.objects.create(
+ team=self.team,
+ name=name,
+ query={"kind": "HogQLQuery", "query": "SELECT 1 AS a"},
+ created_by=self.user,
+ **column_state,
+ )
+
+ def _run(self, view, status, *, minutes_ago=1, error=None, engine=None):
+ return DataModelingJob.objects.create(
+ team=self.team,
+ saved_query=view,
+ status=status,
+ error=error,
+ engine=engine or DataModelingJobEngine.CLICKHOUSE,
+ last_run_at=timezone.now() - timedelta(minutes=minutes_ago),
+ )
+
+ def _detail(self, view) -> dict:
+ response = self.client.get(f"/api/environments/{self.team.id}/warehouse_saved_queries/{view.id}/")
+ self.assertEqual(response.status_code, 200, response.content)
+ return response.json()
+
+ def _from_list(self, view) -> dict:
+ response = self.client.get(f"/api/environments/{self.team.id}/warehouse_saved_queries/")
+ self.assertEqual(response.status_code, 200, response.content)
+ return next(row for row in response.json()["results"] if row["id"] == str(view.id))
+
+ def _edited_after_its_run(self, view) -> None:
+ # update() skips auto_now, which is the only way to place the edit after the run
+ DataWarehouseSavedQuery.objects.filter(id=view.id).update(updated_at=timezone.now())
+
+ def test_the_newest_run_reports_the_failure_the_frozen_columns_never_saw(self):
+ view = self._view("blank_columns")
+ self._run(view, DataModelingJob.Status.FAILED, error="Query exceeded timeout limit")
+
+ body = self._detail(view)
+
+ self.assertEqual(body["status"], "Failed")
+ self.assertEqual(body["latest_error"], "Query exceeded timeout limit")
+
+ def test_a_view_that_recovered_stops_reporting_its_old_failure(self):
+ view = self._view(
+ "recovered",
+ status=DataWarehouseSavedQuery.Status.FAILED,
+ latest_error="months ago, under v1",
+ )
+ self._run(view, DataModelingJob.Status.FAILED, minutes_ago=90, error="months ago, under v1")
+ self._run(view, DataModelingJob.Status.COMPLETED, minutes_ago=5)
+
+ body = self._detail(view)
+
+ self.assertEqual(body["status"], "Completed")
+ self.assertIsNone(body["latest_error"])
+
+ def test_a_duckgres_shadow_does_not_stand_in_for_the_serving_run(self):
+ view = self._view("shadowed")
+ self._run(view, DataModelingJob.Status.FAILED, minutes_ago=30, error="the real failure")
+ self._run(view, DataModelingJob.Status.COMPLETED, minutes_ago=1, engine=DataModelingJobEngine.DUCKGRES)
+
+ body = self._detail(view)
+
+ self.assertEqual(body["status"], "Failed")
+ self.assertEqual(body["latest_error"], "the real failure")
+
+ def test_modified_survives_while_the_edit_is_newer_than_the_run(self):
+ view = self._view("edited_since", status=DataWarehouseSavedQuery.Status.MODIFIED)
+ self._run(view, DataModelingJob.Status.COMPLETED, minutes_ago=10)
+ self._edited_after_its_run(view)
+
+ self.assertEqual(self._detail(view)["status"], "Modified")
+
+ def test_modified_is_answered_by_a_run_that_happened_after_the_edit(self):
+ view = self._view("materialized_since", status=DataWarehouseSavedQuery.Status.MODIFIED)
+ self._edited_after_its_run(view)
+ self._run(view, DataModelingJob.Status.COMPLETED, minutes_ago=0)
+
+ self.assertEqual(self._detail(view)["status"], "Completed")
+
+ def test_modified_survives_when_the_view_has_never_run(self):
+ view = self._view("never_ran", status=DataWarehouseSavedQuery.Status.MODIFIED)
+
+ self.assertEqual(self._detail(view)["status"], "Modified")
+
+ def test_the_list_route_agrees_with_the_detail_route(self):
+ # the two read through different halves of _serving_run: prefetch on list, lookup on detail
+ view = self._view("both_routes", status=DataWarehouseSavedQuery.Status.FAILED, latest_error="stale")
+ self._run(view, DataModelingJob.Status.COMPLETED, minutes_ago=2)
+
+ detail, listed = self._detail(view), self._from_list(view)
+
+ self.assertEqual(detail["status"], listed["status"])
+ self.assertEqual(detail["latest_error"], listed["latest_error"])
+ self.assertEqual(listed["status"], "Completed")
diff --git a/products/data_warehouse/frontend/generated/api.schemas.ts b/products/data_warehouse/frontend/generated/api.schemas.ts
index 403e41a6ed0b..274ecdba87c9 100644
--- a/products/data_warehouse/frontend/generated/api.schemas.ts
+++ b/products/data_warehouse/frontend/generated/api.schemas.ts
@@ -1112,6 +1112,7 @@ export interface PatchedDataWarehouseExpressionApi {
* * `Completed` - Completed
* * `Failed` - Failed
* * `Running` - Running
+ * * `Skipped` - Skipped
*/
export type DataWarehouseSavedQueryStatusEnumApi =
(typeof DataWarehouseSavedQueryStatusEnumApi)[keyof typeof DataWarehouseSavedQueryStatusEnumApi]
@@ -1122,6 +1123,7 @@ export const DataWarehouseSavedQueryStatusEnumApi = {
Completed: 'Completed',
Failed: 'Failed',
Running: 'Running',
+ Skipped: 'Skipped',
} as const
/**
@@ -1157,13 +1159,6 @@ export interface DataWarehouseSavedQueryMinimalApi {
/** True when this team's DAG owns the materialization cadence through a single schedule, so `sync_frequency` cannot be set per view and writes to it are rejected. False when per-node DAG schedules are in use or the team is on the v1 backend. False does not on its own mean the cadence is writable: a view belonging to a managed viewset rejects every update regardless, which `managed_viewset_kind` reports. */
readonly sync_frequency_managed_by_dag: boolean
readonly columns: readonly DataWarehouseSavedQueryMinimalApiColumnsItem[]
- /** The status of when this SavedQuery last ran.
- *
- * * `Cancelled` - Cancelled
- * * `Modified` - Modified
- * * `Completed` - Completed
- * * `Failed` - Failed
- * * `Running` - Running */
readonly status: DataWarehouseSavedQueryStatusEnumApi | null
/** @nullable */
readonly last_run_at: string | null
@@ -1478,13 +1473,6 @@ export interface DataWarehouseSavedQueryApi {
/** Which cadences this view can actually be set to, and what withholds the rest. Computed from the view's data modeling lineage: upstream source sync frequencies set a floor, downstream cadences set a ceiling. Read-only, and present on retrieve, create and update responses only. */
readonly sync_frequency_bounds: SyncFrequencyBoundsApi
readonly columns: readonly DataWarehouseSavedQueryApiColumnsItem[]
- /** The status of when this SavedQuery last ran.
- *
- * * `Cancelled` - Cancelled
- * * `Modified` - Modified
- * * `Completed` - Completed
- * * `Failed` - Failed
- * * `Running` - Running */
readonly status: DataWarehouseSavedQueryStatusEnumApi | null
/** @nullable */
readonly last_run_at: string | null
@@ -1609,13 +1597,6 @@ export interface PatchedDataWarehouseSavedQueryApi {
/** Which cadences this view can actually be set to, and what withholds the rest. Computed from the view's data modeling lineage: upstream source sync frequencies set a floor, downstream cadences set a ceiling. Read-only, and present on retrieve, create and update responses only. */
readonly sync_frequency_bounds?: SyncFrequencyBoundsApi
readonly columns?: readonly PatchedDataWarehouseSavedQueryApiColumnsItem[]
- /** The status of when this SavedQuery last ran.
- *
- * * `Cancelled` - Cancelled
- * * `Modified` - Modified
- * * `Completed` - Completed
- * * `Failed` - Failed
- * * `Running` - Running */
readonly status?: DataWarehouseSavedQueryStatusEnumApi | null
/** @nullable */
readonly last_run_at?: string | null
diff --git a/products/endpoints/backend/insight_transformers.py b/products/endpoints/backend/insight_transformers.py
index bdb959156482..6549af0a2bae 100644
--- a/products/endpoints/backend/insight_transformers.py
+++ b/products/endpoints/backend/insight_transformers.py
@@ -49,7 +49,7 @@ def transform_materialized_insight_response(
result: The result.data dict from _execute_query_and_respond(). Modified in-place.
original_query: The original insight query definition (TrendsQuery, etc.)
team: The team for query runner context.
- now: Pin date range to this timestamp (e.g., saved_query.last_run_at) instead of datetime.now().
+ now: Pin date range to the materialization time instead of datetime.now().
"""
query_kind = original_query.get("kind")
diff --git a/products/endpoints/backend/logic/execution.py b/products/endpoints/backend/logic/execution.py
index c842bafe1d58..3ec5c017f9ec 100644
--- a/products/endpoints/backend/logic/execution.py
+++ b/products/endpoints/backend/logic/execution.py
@@ -855,7 +855,7 @@ class EndpointExecutionService(PydanticModelMixin):
strategy.clean_response_sentinels(result.data)
try:
- strategy.transform_materialized_response(result.data, saved_query)
+ strategy.transform_materialized_response(result.data, saved_query, materialized_at)
except MaterializedSeriesMismatchError:
# Series drift: query was likely edited after materialization. Trigger a refresh
# so future materialized reads succeed; the caller serves this request inline.
diff --git a/products/endpoints/backend/logic/strategies.py b/products/endpoints/backend/logic/strategies.py
index fa9f5e2a4e22..09b1c7f0f056 100644
--- a/products/endpoints/backend/logic/strategies.py
+++ b/products/endpoints/backend/logic/strategies.py
@@ -14,6 +14,7 @@ stay kind-agnostic.
import abc
import dataclasses
+from datetime import datetime
from functools import cached_property
from typing import TYPE_CHECKING, ClassVar, Optional
@@ -373,7 +374,9 @@ class EndpointQueryStrategy(abc.ABC):
"""
@abc.abstractmethod
- def transform_materialized_response(self, response_data: dict, saved_query: "DataWarehouseSavedQuery") -> None:
+ def transform_materialized_response(
+ self, response_data: dict, saved_query: "DataWarehouseSavedQuery", materialized_at: datetime | None
+ ) -> None:
"""Re-shape a materialized read into the inline response format."""
@abc.abstractmethod
@@ -511,7 +514,9 @@ class HogQLEndpointStrategy(EndpointQueryStrategy):
return select_query, original_limit
- def transform_materialized_response(self, response_data: dict, saved_query: "DataWarehouseSavedQuery") -> None:
+ def transform_materialized_response(
+ self, response_data: dict, saved_query: "DataWarehouseSavedQuery", materialized_at: datetime | None
+ ) -> None:
"""HogQL materialized rows are flat and returned as-is — no re-shaping needed."""
return None
@@ -691,7 +696,9 @@ class InsightEndpointStrategy(EndpointQueryStrategy):
add_where_condition(select_query, condition)
return None
- def transform_materialized_response(self, response_data: dict, saved_query: "DataWarehouseSavedQuery") -> None:
+ def transform_materialized_response(
+ self, response_data: dict, saved_query: "DataWarehouseSavedQuery", materialized_at: datetime | None
+ ) -> None:
"""Re-shape flat materialized rows into the inline insight response format.
Raises MaterializedSeriesMismatchError on series drift (query edited after
@@ -703,7 +710,7 @@ class InsightEndpointStrategy(EndpointQueryStrategy):
response_data,
self.query,
self.team,
- now=saved_query.last_run_at,
+ now=materialized_at,
)
def clean_response_sentinels(self, response_data: dict) -> None:
diff --git a/products/endpoints/backend/rate_limit.py b/products/endpoints/backend/rate_limit.py
index c1ce99be5b45..59eb912b3515 100644
--- a/products/endpoints/backend/rate_limit.py
+++ b/products/endpoints/backend/rate_limit.py
@@ -97,18 +97,21 @@ def _check_and_cache_materialization_status(team_id: int, endpoint_name: str, ve
Returns True if the targeted endpoint version (current when version is None) is ready
for materialized execution.
"""
+ from products.data_modeling.backend.facade.api import latest_saved_query_materialization_job
from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery
from products.endpoints.backend.models import Endpoint, EndpointVersion
try:
endpoint = Endpoint.objects.get(team_id=team_id, name=endpoint_name, is_active=True, deleted=False)
endpoint_version = endpoint.get_version(version)
-
- is_ready = (
- endpoint_version.is_materialized
- and endpoint_version.saved_query is not None
- and endpoint_version.saved_query.status == DataWarehouseSavedQuery.Status.COMPLETED
- )
+ saved_query = endpoint_version.saved_query
+
+ is_ready = False
+ if endpoint_version.is_materialized and saved_query is not None:
+ # The v2 workflow records runs on DataModelingJob and never writes saved_query.status.
+ latest_job = latest_saved_query_materialization_job(saved_query)
+ status = latest_job.status if latest_job is not None else saved_query.status
+ is_ready = status == DataWarehouseSavedQuery.Status.COMPLETED
set_endpoint_materialization_ready(team_id, endpoint_name, is_ready, version=version)
return is_ready
diff --git a/products/endpoints/backend/tests/test_endpoint_execution.py b/products/endpoints/backend/tests/test_endpoint_execution.py
index 6bc1161d19b3..ebdd4c216119 100644
--- a/products/endpoints/backend/tests/test_endpoint_execution.py
+++ b/products/endpoints/backend/tests/test_endpoint_execution.py
@@ -2473,6 +2473,42 @@ class TestEndpointExecution(ClickhouseTestMixin, APIBaseTest):
# data_freshness_seconds=86400, materialized ~5 min ago -> ~86100s remaining
self.assertGreater(cache_ttl, 80000, f"cache TTL clamped ({cache_ttl}s): freshness read from frozen timestamp")
+ def test_materialized_response_transform_receives_the_job_materialization_time(self):
+ from products.endpoints.backend.logic.strategies import HogQLEndpointStrategy
+
+ endpoint = self._make_fresh_materialized_endpoint(
+ "v2-transform-now", {"kind": "HogQLQuery", "query": "select 1 as n"}
+ )
+ saved_query = endpoint.versions.first().saved_query
+ saved_query.sync_frequency_interval = None
+ saved_query.last_run_at = None
+ saved_query.status = None
+ saved_query.save()
+ materialized_at = timezone.now() - timedelta(minutes=5)
+ DataModelingJob.objects.create(
+ team=self.team,
+ saved_query=saved_query,
+ status=DataModelingJob.Status.COMPLETED,
+ engine=DataModelingJob.Engine.CLICKHOUSE,
+ last_run_at=materialized_at,
+ )
+
+ flat_response = Response({"results": [[1]], "columns": ["n"]})
+ with (
+ mock.patch.object(EndpointExecutionService, "_execute_query_and_respond", return_value=flat_response),
+ mock.patch.object(
+ HogQLEndpointStrategy, "transform_materialized_response", autospec=True
+ ) as mock_transform,
+ ):
+ response = self.client.post(
+ f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/run/", {}, format="json"
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ mock_transform.assert_called_once()
+ _strategy, _data, _saved_query, passed_at = mock_transform.call_args.args
+ self.assertEqual(passed_at, materialized_at)
+
@parameterized.expand(
[
("refresh_starts", None),
diff --git a/products/endpoints/backend/tests/test_rate_limit.py b/products/endpoints/backend/tests/test_rate_limit.py
index e5c5187f507d..b581db1e1e9a 100644
--- a/products/endpoints/backend/tests/test_rate_limit.py
+++ b/products/endpoints/backend/tests/test_rate_limit.py
@@ -3,10 +3,11 @@ from unittest.mock import MagicMock, patch
from django.core.cache import cache
from django.test import TestCase
+from django.utils import timezone
from parameterized import parameterized
-from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery
+from products.data_modeling.backend.facade.models import DataModelingJob, DataWarehouseSavedQuery
from products.endpoints.backend.models import Endpoint
from products.endpoints.backend.presentation.throttles import (
EndpointBurstThrottle,
@@ -138,6 +139,56 @@ class TestCheckAndCacheMaterializationStatus(APIBaseTest):
self.assertEqual(result, expected_ready)
self.assertEqual(is_endpoint_materialization_ready(self.team.id, f"endpoint_{status}"), expected_ready)
+ @parameterized.expand(
+ [
+ (DataModelingJob.Status.COMPLETED, DataModelingJob.Engine.CLICKHOUSE, True),
+ (DataModelingJob.Status.FAILED, DataModelingJob.Engine.CLICKHOUSE, False),
+ (DataModelingJob.Status.COMPLETED, DataModelingJob.Engine.DUCKGRES, False),
+ ]
+ )
+ def test_readiness_derives_from_newest_clickhouse_job(self, job_status, engine, expected_ready):
+ from products.endpoints.backend.models import EndpointVersion
+
+ name = f"job_{job_status}_{engine}".lower()
+ saved_query = DataWarehouseSavedQuery.objects.create(
+ name=f"query_{name}",
+ team=self.team,
+ query={"kind": "HogQLQuery", "query": "SELECT 1"},
+ is_materialized=True,
+ status=None,
+ origin=DataWarehouseSavedQuery.Origin.ENDPOINT,
+ )
+ saved_query.table = DataWarehouseTable.objects.create(
+ team=self.team,
+ name=f"table_{name}",
+ format=DataWarehouseTable.TableFormat.Parquet,
+ url_pattern=f"s3://test-bucket/table_{name}",
+ )
+ saved_query.save()
+ DataModelingJob.objects.create(
+ team=self.team,
+ saved_query=saved_query,
+ status=job_status,
+ engine=engine,
+ last_run_at=timezone.now(),
+ )
+ endpoint = Endpoint.objects.create(
+ name=f"endpoint_{name}",
+ team=self.team,
+ created_by=self.user,
+ is_active=True,
+ current_version=1,
+ )
+ EndpointVersion.objects.create(
+ endpoint=endpoint,
+ version=1,
+ query={"kind": "HogQLQuery", "query": "SELECT 1"},
+ created_by=self.user,
+ saved_query=saved_query,
+ )
+
+ self.assertEqual(_check_and_cache_materialization_status(self.team.id, f"endpoint_{name}"), expected_ready)
+
def _create_endpoint_with_materialized_v1_and_inline_v2(self, name="versioned_endpoint"):
from products.endpoints.backend.models import EndpointVersion
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 1a0d8402cc1d..87597379e797 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -22793,6 +22793,7 @@ export namespace Schemas {
* * `Completed` - Completed
* * `Failed` - Failed
* * `Running` - Running
+ * * `Skipped` - Skipped
*/
export type DataWarehouseSavedQueryStatusEnum = typeof DataWarehouseSavedQueryStatusEnum[keyof typeof DataWarehouseSavedQueryStatusEnum];
@@ -22803,6 +22804,7 @@ export namespace Schemas {
Completed: 'Completed',
Failed: 'Failed',
Running: 'Running',
+ Skipped: 'Skipped',
} as const;
/**
@@ -22863,13 +22865,6 @@ export namespace Schemas {
/** Which cadences this view can actually be set to, and what withholds the rest. Computed from the view's data modeling lineage: upstream source sync frequencies set a floor, downstream cadences set a ceiling. Read-only, and present on retrieve, create and update responses only. */
readonly sync_frequency_bounds: SyncFrequencyBounds;
readonly columns: readonly DataWarehouseSavedQueryColumnsItem[];
- /** The status of when this SavedQuery last ran.
- *
- * * `Cancelled` - Cancelled
- * * `Modified` - Modified
- * * `Completed` - Completed
- * * `Failed` - Failed
- * * `Running` - Running */
readonly status: DataWarehouseSavedQueryStatusEnum | null;
/** @nullable */
readonly last_run_at: string | null;
@@ -23031,13 +23026,6 @@ export namespace Schemas {
/** True when this team's DAG owns the materialization cadence through a single schedule, so `sync_frequency` cannot be set per view and writes to it are rejected. False when per-node DAG schedules are in use or the team is on the v1 backend. False does not on its own mean the cadence is writable: a view belonging to a managed viewset rejects every update regardless, which `managed_viewset_kind` reports. */
readonly sync_frequency_managed_by_dag: boolean;
readonly columns: readonly DataWarehouseSavedQueryMinimalColumnsItem[];
- /** The status of when this SavedQuery last ran.
- *
- * * `Cancelled` - Cancelled
- * * `Modified` - Modified
- * * `Completed` - Completed
- * * `Failed` - Failed
- * * `Running` - Running */
readonly status: DataWarehouseSavedQueryStatusEnum | null;
/** @nullable */
readonly last_run_at: string | null;
@@ -62463,13 +62451,6 @@ export namespace Schemas {
/** Which cadences this view can actually be set to, and what withholds the rest. Computed from the view's data modeling lineage: upstream source sync frequencies set a floor, downstream cadences set a ceiling. Read-only, and present on retrieve, create and update responses only. */
readonly sync_frequency_bounds?: SyncFrequencyBounds;
readonly columns?: readonly PatchedDataWarehouseSavedQueryColumnsItem[];
- /** The status of when this SavedQuery last ran.
- *
- * * `Cancelled` - Cancelled
- * * `Modified` - Modified
- * * `Completed` - Completed
- * * `Failed` - Failed
- * * `Running` - Running */
readonly status?: DataWarehouseSavedQueryStatusEnum | null;
/** @nullable */
readonly last_run_at?: string | null;