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(endpoints): restore materialized serving on v2 (#84276)

Kyle Swank82c7cfe408fb
diff --git a/products/data_modeling/backend/facade/api.py b/products/data_modeling/backend/facade/api.py
index 1082274a3da9..394076b21bc6 100644
--- a/products/data_modeling/backend/facade/api.py
+++ b/products/data_modeling/backend/facade/api.py
@@ -30,6 +30,8 @@ _LAZY = {
"get_saved_query_summary": "logic.saved_query_reads",
"saved_query_names": "logic.saved_query_reads",
"saved_query_materialized_at": "logic.saved_query_freshness",
+ "latest_saved_query_materialization_job": "logic.saved_query_freshness",
+ "is_materialization_fresh": "logic.saved_query_freshness",
"start_node_materialization": "logic.node_materialization",
"delete_dag_schedules": "logic.schedule_reconcile",
"delete_team_data_modeling_schedules": "logic.schedule_reconcile",
diff --git a/products/data_modeling/backend/logic/saved_query_freshness.py b/products/data_modeling/backend/logic/saved_query_freshness.py
index 73e6ef8c08f0..ad41f1273fa4 100644
--- a/products/data_modeling/backend/logic/saved_query_freshness.py
+++ b/products/data_modeling/backend/logic/saved_query_freshness.py
@@ -5,7 +5,9 @@ django.setup() without pulling the materialization dispatch stack (and its circu
import back into products.endpoints).
"""
-from datetime import datetime
+from datetime import datetime, timedelta
+
+from django.utils import timezone
from products.data_modeling.backend.models import DataModelingJob, DataModelingJobEngine, DataModelingJobStatus
from products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery
@@ -17,8 +19,11 @@ def saved_query_materialized_at(saved_query: DataWarehouseSavedQuery) -> datetim
The v2 DAG records success on DataModelingJob but never writes saved_query.last_run_at, so
read freshness from the newest Completed clickhouse job and fall back to the frozen v1 field.
"""
+ prefetched_jobs = getattr(saved_query, "prefetched_latest_completed_jobs", None)
job_last_run_at = (
- DataModelingJob.objects.filter(
+ (prefetched_jobs[0].last_run_at if prefetched_jobs else None)
+ if prefetched_jobs is not None
+ else DataModelingJob.objects.filter(
team_id=saved_query.team_id,
saved_query_id=saved_query.id,
status=DataModelingJobStatus.COMPLETED,
@@ -30,3 +35,28 @@ def saved_query_materialized_at(saved_query: DataWarehouseSavedQuery) -> datetim
)
candidates = [ts for ts in (job_last_run_at, saved_query.last_run_at) if ts is not None]
return max(candidates) if candidates else None
+
+
+def latest_saved_query_materialization_job(saved_query: DataWarehouseSavedQuery) -> DataModelingJob | None:
+ """Return the latest ClickHouse materialization attempt recorded by the v2 workflow."""
+ prefetched_jobs = getattr(saved_query, "prefetched_latest_jobs", None)
+ if prefetched_jobs is not None:
+ return prefetched_jobs[0] if prefetched_jobs else None
+ return (
+ DataModelingJob.objects.filter(
+ team_id=saved_query.team_id,
+ saved_query_id=saved_query.id,
+ engine=DataModelingJobEngine.CLICKHOUSE,
+ )
+ .order_by("-last_run_at")
+ .first()
+ )
+
+
+def is_materialization_fresh(materialized_at: datetime | None, freshness_seconds: int | None) -> bool:
+ """Whether a successful materialization is still within its serving window."""
+ if materialized_at is None:
+ return False
+ if not freshness_seconds:
+ return True
+ return timezone.now() < materialized_at + timedelta(seconds=freshness_seconds)
diff --git a/products/endpoints/backend/logic/crud.py b/products/endpoints/backend/logic/crud.py
index f6648aa53b2c..571bb9c00dc9 100644
--- a/products/endpoints/backend/logic/crud.py
+++ b/products/endpoints/backend/logic/crud.py
@@ -112,7 +112,7 @@ class EndpointCrudService:
current_version=1,
derived_from_insight=data.derived_from_insight,
)
- EndpointVersion.objects.create(
+ version = EndpointVersion.objects.create(
endpoint=endpoint,
team=self.team,
version=1,
@@ -127,6 +127,13 @@ class EndpointCrudService:
created_by=self.user,
columns=columns,
)
+ if data.is_materialized is True:
+ self.materialization.enable_materialization(
+ endpoint,
+ version,
+ version.data_freshness_seconds,
+ bucket_overrides=data.bucket_overrides,
+ )
apply_tags(endpoint, data.tags)
@@ -151,7 +158,7 @@ class EndpointCrudService:
return endpoint
- except ValidationError:
+ except (APIException, ValidationError):
raise
except Exception as e:
capture_exception(
diff --git a/products/endpoints/backend/logic/execution.py b/products/endpoints/backend/logic/execution.py
index 34773fc90453..b979cf987856 100644
--- a/products/endpoints/backend/logic/execution.py
+++ b/products/endpoints/backend/logic/execution.py
@@ -67,8 +67,7 @@ from posthog.permissions import is_authenticated_via_project_secret_api_key
from posthog.schema_migrations.upgrade import upgrade
from posthog.synthetic_user import SyntheticUser
-from products.data_modeling.backend.facade.api import saved_query_materialized_at
-from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery
+from products.data_modeling.backend.facade.api import is_materialization_fresh, saved_query_materialized_at
from products.data_warehouse.backend.facade.api import trigger_saved_query_schedule
from products.endpoints.backend.exceptions import EndpointAtCapacity, EndpointQueryTooExpensive
from products.endpoints.backend.insight_transformers import MaterializedSeriesMismatchError
@@ -368,19 +367,13 @@ class EndpointExecutionService(PydanticModelMixin):
if not version.is_materialized or not version.saved_query:
return False
- saved_query = version.saved_query
- if saved_query.status != DataWarehouseSavedQuery.Status.COMPLETED:
- return False
-
- if not saved_query.table:
+ if not version.saved_query.table or materialized_at is None:
return False
# Check if materialized data is stale. Keyed on the version's freshness target, not
# saved_query.sync_frequency_interval — the v2 schedule migration nulls that field.
- if materialized_at and version.data_freshness_seconds:
- next_refresh_due = materialized_at + timedelta(seconds=version.data_freshness_seconds)
- if timezone.now() >= next_refresh_due:
- return False
+ if not is_materialization_fresh(materialized_at, version.data_freshness_seconds):
+ return False
# 'direct' mode explicitly bypasses materialization to run the original query
if data.refresh == EndpointRefreshMode.DIRECT:
diff --git a/products/endpoints/backend/logic/materialization.py b/products/endpoints/backend/logic/materialization.py
index 4b877a5821f9..783147d39b34 100644
--- a/products/endpoints/backend/logic/materialization.py
+++ b/products/endpoints/backend/logic/materialization.py
@@ -32,6 +32,8 @@ from products.data_modeling.backend.facade.api import (
UnsatisfiableFrequencyError,
UnsupportedFrequencyTargetError,
delete_node_from_dag,
+ is_materialization_fresh,
+ latest_saved_query_materialization_job,
saved_query_materialized_at,
sync_saved_query_to_dag,
)
@@ -90,14 +92,29 @@ ELIGIBILITY_CHECK_FAILED_REASON = (
def build_materialization_info(version: EndpointVersion, endpoint_name: str | None = None) -> dict:
"""Build the materialization status dict for a version."""
if version.saved_query:
- # v2 never writes saved_query.last_run_at; derive freshness from DataModelingJob.
- materialized_at = saved_query_materialized_at(version.saved_query)
+ latest_job = latest_saved_query_materialization_job(version.saved_query)
+ materialization_status = latest_job.status if latest_job else version.saved_query.status
+ materialization_error = latest_job.error if latest_job else version.saved_query.latest_error
+ if latest_job and latest_job.status == DataWarehouseSavedQuery.Status.COMPLETED:
+ materialized_at = max(
+ timestamp
+ for timestamp in (latest_job.last_run_at, version.saved_query.last_run_at)
+ if timestamp is not None
+ )
+ else:
+ # A failed or running attempt may follow a successful build that remains serveable.
+ materialized_at = saved_query_materialized_at(version.saved_query)
result = {
- "status": version.saved_query.status or "Unknown",
+ "enabled": bool(version.saved_query.is_materialized),
+ "ready": bool(
+ version.saved_query.table_id
+ and is_materialization_fresh(materialized_at, version.data_freshness_seconds)
+ ),
+ "status": materialization_status or "Unknown",
"can_materialize": True,
"last_materialized_at": materialized_at.isoformat() if materialized_at else None,
- "error": (version.saved_query.latest_error or "")
- if version.saved_query.status != DataWarehouseSavedQuery.Status.COMPLETED
+ "error": (materialization_error or "")
+ if materialization_status != DataWarehouseSavedQuery.Status.COMPLETED
else "",
"saved_query_id": str(version.saved_query.id),
}
@@ -108,6 +125,8 @@ def build_materialization_info(version: EndpointVersion, endpoint_name: str | No
capture_exception(e, {"endpoint_version_id": str(version.id), "team_id": version.endpoint.team_id})
can_mat, reason = False, ELIGIBILITY_CHECK_FAILED_REASON
result = {
+ "enabled": False,
+ "ready": False,
"can_materialize": can_mat,
"reason": reason if not can_mat else None,
}
diff --git a/products/endpoints/backend/presentation/serializers.py b/products/endpoints/backend/presentation/serializers.py
index 9294b1266296..7f19fb7fdef0 100644
--- a/products/endpoints/backend/presentation/serializers.py
+++ b/products/endpoints/backend/presentation/serializers.py
@@ -93,6 +93,12 @@ class EndpointMaterializationSerializer(serializers.Serializer):
name = serializers.CharField(
help_text="URL-safe endpoint name.",
)
+ enabled = serializers.BooleanField(
+ help_text="Whether materialization is enabled for this endpoint version.",
+ )
+ ready = serializers.BooleanField(
+ help_text="Whether a successful materialization is available to serve.",
+ )
status = serializers.CharField(
required=False,
help_text="Current materialization status (e.g. 'Completed', 'Running').",
diff --git a/products/endpoints/backend/presentation/views/api.py b/products/endpoints/backend/presentation/views/api.py
index 6894c2d6f95a..3ac60b64dca7 100644
--- a/products/endpoints/backend/presentation/views/api.py
+++ b/products/endpoints/backend/presentation/views/api.py
@@ -46,7 +46,7 @@ from posthog.auth import ProjectSecretAPIKeyAuthentication
from posthog.clickhouse.query_tagging import Product
from posthog.event_usage import report_user_action
from posthog.exceptions_capture import capture_exception
-from posthog.models import User
+from posthog.models import TaggedItem, User
from posthog.permissions import (
APIScopePermission,
TeamMemberAccessPermission,
@@ -57,6 +57,7 @@ from posthog.schema_migrations.upgrade import upgrade
from products.access_control.backend.facade.user_access_control import access_level_satisfied_for_resource
from products.access_control.backend.presentation.access_control import AccessControlViewSetMixin
+from products.data_modeling.backend.facade.models import DataModelingJob
from products.endpoints.backend.facade.api import (
REWRITE_CONTRACT,
EndpointCrudService,
@@ -274,21 +275,35 @@ class EndpointViewSet(
return sorted(endpoint.tagged_items.values_list("tag__name", flat=True))
@staticmethod
- def _with_serialization_prefetches(queryset):
+ def _with_materialization_job_prefetches(queryset):
+ latest_jobs = DataModelingJob.objects.filter(engine=DataModelingJob.Engine.CLICKHOUSE).order_by("-last_run_at")
+ latest_completed_jobs = latest_jobs.filter(status=DataModelingJob.Status.COMPLETED)
+ return queryset.select_related("saved_query").prefetch_related(
+ Prefetch("saved_query__datamodelingjob_set", queryset=latest_jobs[:1], to_attr="prefetched_latest_jobs"),
+ Prefetch(
+ "saved_query__datamodelingjob_set",
+ queryset=latest_completed_jobs[:1],
+ to_attr="prefetched_latest_completed_jobs",
+ ),
+ )
+
+ @classmethod
+ def _with_serialization_prefetches(cls, queryset):
"""Tags are prefetched by TaggedItemViewSetMixin.filter_queryset; repeating them here
raises a lookup conflict.
Only the current version is fetched, and the history is counted in the database, so an
endpoint with a long version history costs the same as a fresh one.
"""
+ current_versions = cls._with_materialization_job_prefetches(
+ EndpointVersion.objects.filter(version=F("endpoint__current_version"))
+ )
return (
queryset.select_related("created_by")
.prefetch_related(
Prefetch(
"versions",
- queryset=EndpointVersion.objects.filter(version=F("endpoint__current_version")).select_related(
- "saved_query"
- ),
+ queryset=current_versions,
to_attr="prefetched_current_versions",
),
)
@@ -330,6 +345,12 @@ class EndpointViewSet(
endpoint = obj
version = self._current_version(endpoint)
+ versions_count = (
+ obj.endpoint_versions_count
+ if isinstance(obj, EndpointVersion) and hasattr(obj, "endpoint_versions_count")
+ else self._versions_count(endpoint)
+ )
+
url = None
ui_url = None
if request:
@@ -353,7 +374,7 @@ class EndpointViewSet(
"is_materialized": version.is_materialized,
"current_version": endpoint.current_version,
"current_version_id": str(version.id),
- "versions_count": self._versions_count(endpoint),
+ "versions_count": versions_count,
"derived_from_insight": endpoint.derived_from_insight,
"last_executed_at": endpoint.last_executed_at.isoformat() if endpoint.last_executed_at else None,
"materialization": build_materialization_info(version),
@@ -611,7 +632,19 @@ class EndpointViewSet(
Returns versions in descending order (latest first).
"""
endpoint = self._get_endpoint_with_object_access(name)
- versions_qs = endpoint.versions.all()
+ versions_qs = (
+ self._with_materialization_job_prefetches(endpoint.versions.all())
+ .select_related("endpoint", "endpoint__created_by", "created_by")
+ .prefetch_related(
+ Prefetch(
+ "endpoint__tagged_items",
+ queryset=TaggedItem.objects.select_related("tag"),
+ to_attr="prefetched_tags",
+ )
+ )
+ .annotate(endpoint_versions_count=Count("endpoint__versions", distinct=True))
+ .order_by("-version")
+ )
page = self.paginate_queryset(versions_qs)
if page is not None:
results = [self._serialize(v) for v in page]
diff --git a/products/endpoints/backend/tests/test_endpoint.py b/products/endpoints/backend/tests/test_endpoint.py
index 647bac451649..9e72abe8f461 100644
--- a/products/endpoints/backend/tests/test_endpoint.py
+++ b/products/endpoints/backend/tests/test_endpoint.py
@@ -1,4 +1,4 @@
-from datetime import datetime
+from datetime import datetime, timedelta
from typing import Any
from freezegun import freeze_time
@@ -7,6 +7,7 @@ from unittest import TestCase, mock
from django.db import connection
from django.test.utils import CaptureQueriesContext
+from django.utils import timezone
from parameterized import parameterized
from rest_framework import status
@@ -19,9 +20,11 @@ from posthog.models.team import Team
from posthog.models.user import User
from posthog.models.utils import generate_random_token_personal, hash_key_value
+from products.data_modeling.backend.facade.models import DataModelingJob, DataWarehouseSavedQuery
from products.endpoints.backend.models import Endpoint, EndpointVersion
from products.endpoints.backend.tests.conftest import create_endpoint_with_version
from products.product_analytics.backend.facade.models import InsightVariable
+from products.warehouse_sources.backend.facade.models import DataWarehouseTable
class TestEndpoint(ClickhouseTestMixin, APIBaseTest):
@@ -1896,8 +1899,9 @@ class TestEndpointListResilienceAndQueryCount(ClickhouseTestMixin, APIBaseTest):
def _create_endpoints(self, count: int) -> None:
for i in range(count):
+ endpoint_name = f"list_perf_{count}_{i}"
endpoint = create_endpoint_with_version(
- name=f"list_perf_{i}",
+ name=endpoint_name,
team=self.team,
query={
"kind": "HogQLQuery",
@@ -1906,7 +1910,33 @@ class TestEndpointListResilienceAndQueryCount(ClickhouseTestMixin, APIBaseTest):
},
created_by=self.user,
)
- endpoint.versions.update(columns=[{"name": "c", "type": "integer"}])
+ saved_query = DataWarehouseSavedQuery.objects.create(
+ team=self.team,
+ name=endpoint_name,
+ query=endpoint.get_version().query,
+ is_materialized=True,
+ table=DataWarehouseTable.objects.create(
+ team=self.team,
+ name=endpoint_name,
+ format=DataWarehouseTable.TableFormat.Parquet,
+ url_pattern=f"s3://test-bucket/{endpoint_name}",
+ ),
+ )
+ endpoint.versions.update(columns=[{"name": "c", "type": "integer"}], saved_query=saved_query)
+ DataModelingJob.objects.create(
+ team=self.team,
+ saved_query=saved_query,
+ status=DataModelingJob.Status.COMPLETED,
+ engine=DataModelingJob.Engine.CLICKHOUSE,
+ last_run_at=timezone.now() - timedelta(minutes=5),
+ )
+ DataModelingJob.objects.create(
+ team=self.team,
+ saved_query=saved_query,
+ status=DataModelingJob.Status.RUNNING,
+ engine=DataModelingJob.Engine.CLICKHOUSE,
+ last_run_at=timezone.now(),
+ )
def _list_query_count(self, endpoint_count: int) -> int:
Endpoint.objects.all().delete()
@@ -1925,6 +1955,61 @@ class TestEndpointListResilienceAndQueryCount(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(few, many, f"listing 8 endpoints cost {many} queries vs {few} for 2, so something N+1s")
+ def _versions_query_count(self, version_count: int) -> int:
+ Endpoint.objects.all().delete()
+ endpoint = create_endpoint_with_version(
+ name=f"versions_perf_{version_count}",
+ team=self.team,
+ query={"kind": "HogQLQuery", "query": "SELECT 1"},
+ created_by=self.user,
+ )
+ first_version = endpoint.get_version()
+ for version_number in range(1, version_count + 1):
+ version = (
+ first_version
+ if version_number == 1
+ else EndpointVersion.objects.create(
+ endpoint=endpoint,
+ team=self.team,
+ version=version_number,
+ query={"kind": "HogQLQuery", "query": f"SELECT {version_number}"},
+ created_by=self.user,
+ columns=[{"name": "result", "type": "integer"}],
+ )
+ )
+ saved_query = DataWarehouseSavedQuery.objects.create(
+ team=self.team,
+ name=f"versions_perf_{version_count}_v{version_number}",
+ query=version.query,
+ is_materialized=True,
+ )
+ version.saved_query = saved_query
+ version.columns = [{"name": "result", "type": "integer"}]
+ version.save(update_fields=["saved_query", "columns", "updated_at"])
+ DataModelingJob.objects.create(
+ team=self.team,
+ saved_query=saved_query,
+ status=DataModelingJob.Status.COMPLETED,
+ engine=DataModelingJob.Engine.CLICKHOUSE,
+ last_run_at=timezone.now(),
+ )
+
+ endpoint.current_version = version_count
+ endpoint.save(update_fields=["current_version", "updated_at"])
+ url = f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/versions/"
+ self.client.get(url)
+ with CaptureQueriesContext(connection) as ctx:
+ response = self.client.get(url)
+ self.assertEqual(status.HTTP_200_OK, response.status_code, response.content)
+ self.assertEqual(version_count, len(response.json()["results"]))
+ return len(ctx.captured_queries)
+
+ def test_versions_query_count_does_not_grow_with_version_count(self):
+ few = self._versions_query_count(2)
+ many = self._versions_query_count(8)
+
+ self.assertEqual(few, many, f"listing 8 versions cost {many} queries vs {few} for 2, so something N+1s")
+
def test_list_reports_the_latest_version_and_the_full_history_count(self):
endpoint = create_endpoint_with_version(
name="versioned",
@@ -1948,7 +2033,13 @@ class TestEndpointListResilienceAndQueryCount(ClickhouseTestMixin, APIBaseTest):
self.assertEqual("SELECT 3", result["query"]["query"])
def test_list_survives_an_endpoint_whose_eligibility_check_raises(self):
- self._create_endpoints(2)
+ for i in range(2):
+ create_endpoint_with_version(
+ name=f"eligibility_error_{i}",
+ team=self.team,
+ query={"kind": "HogQLQuery", "query": "SELECT 1"},
+ created_by=self.user,
+ )
with mock.patch.object(EndpointVersion, "can_materialize", side_effect=RuntimeError("boom")):
response = self.client.get(f"/api/environments/{self.team.id}/endpoints/")
diff --git a/products/endpoints/backend/tests/test_endpoint_execution.py b/products/endpoints/backend/tests/test_endpoint_execution.py
index eedcff54521d..d9ca63002eee 100644
--- a/products/endpoints/backend/tests/test_endpoint_execution.py
+++ b/products/endpoints/backend/tests/test_endpoint_execution.py
@@ -2398,6 +2398,7 @@ class TestEndpointExecution(ClickhouseTestMixin, APIBaseTest):
saved_query = version.saved_query
saved_query.sync_frequency_interval = None # migration cleanup nulls this on v2 teams
saved_query.last_run_at = timezone.now() - timedelta(days=3)
+ saved_query.status = None
saved_query.save()
DataModelingJob.objects.create(
team=self.team,
diff --git a/products/endpoints/backend/tests/test_endpoint_materialization.py b/products/endpoints/backend/tests/test_endpoint_materialization.py
index f429ea3fdc21..b50ff60d7d0a 100644
--- a/products/endpoints/backend/tests/test_endpoint_materialization.py
+++ b/products/endpoints/backend/tests/test_endpoint_materialization.py
@@ -13,6 +13,7 @@ import pytest_asyncio
from asgiref.sync import sync_to_async
from parameterized import parameterized
from rest_framework import status
+from rest_framework.exceptions import APIException
from rest_framework.response import Response
from posthog.schema import RetentionQuery
@@ -130,6 +131,45 @@ class TestEndpointMaterialization(ClickhouseTestMixin, APIBaseTest):
"DataWarehouseModelPath should be created for the saved_query",
)
+ def test_create_with_materialization_enabled_schedules_saved_query(self):
+ response = self.client.post(
+ f"/api/environments/{self.team.id}/endpoints/",
+ {
+ "name": "materialized-on-create",
+ "query": self.sample_hogql_query,
+ "is_materialized": True,
+ "data_freshness_seconds": 86400,
+ },
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.json())
+ self.assertTrue(response.json()["materialization"]["enabled"])
+ self.assertFalse(response.json()["materialization"]["ready"])
+ version = EndpointVersion.objects.get(endpoint__team=self.team, endpoint__name="materialized-on-create")
+ self.assertIsNotNone(version.saved_query_id)
+ assert version.saved_query is not None
+ self.assertTrue(version.saved_query.is_materialized)
+
+ def test_create_scheduler_failure_returns_server_error_and_rolls_back(self):
+ with mock.patch.object(
+ EndpointMaterializationService,
+ "enable_materialization",
+ side_effect=APIException("scheduler unavailable"),
+ ):
+ response = self.client.post(
+ f"/api/environments/{self.team.id}/endpoints/",
+ {
+ "name": "materialization-scheduler-failure",
+ "query": self.sample_hogql_query,
+ "is_materialized": True,
+ },
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_500_INTERNAL_SERVER_ERROR)
+ self.assertFalse(EndpointVersion.objects.filter(endpoint__name="materialization-scheduler-failure").exists())
+
def test_unsatisfiable_freshness_rolls_back_the_whole_enable(self):
# if scheduling rejects the chosen freshness (finer than an upstream source can deliver),
# the enable must unwind completely — no dangling saved query, version link, or DAG node
@@ -1013,15 +1053,22 @@ class TestEndpointMaterialization(ClickhouseTestMixin, APIBaseTest):
def test_materialization_status_derives_last_materialized_at_from_jobs(self):
"""v2 DAG runs record success on DataModelingJob without touching saved_query.last_run_at;
the status payload must report the real materialization time, not the frozen v1 field."""
- job_time = timezone.now() - timedelta(minutes=5)
+ job_time = timezone.now() - timedelta(days=2)
saved_query = DataWarehouseSavedQuery.objects.create(
team=self.team,
name="status_freshness_endpoint",
query=self.sample_hogql_query,
is_materialized=True,
- status=DataWarehouseSavedQuery.Status.COMPLETED,
+ status=None,
last_run_at=timezone.now() - timedelta(days=3),
)
+ saved_query.table = DataWarehouseTable.objects.create(
+ team=self.team,
+ name="status_freshness_endpoint",
+ format=DataWarehouseTable.TableFormat.Parquet,
+ url_pattern="s3://test-bucket/status-freshness",
+ )
+ saved_query.save(update_fields=["table"])
endpoint = create_endpoint_with_version(
name="status_freshness_endpoint",
team=self.team,
@@ -1046,6 +1093,66 @@ class TestEndpointMaterialization(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.json()["last_materialized_at"], job_time.isoformat())
+ self.assertEqual(response.json()["status"], DataModelingJob.Status.COMPLETED)
+ self.assertTrue(response.json()["enabled"])
+ self.assertFalse(response.json()["ready"])
+
+ @parameterized.expand(
+ [
+ (DataModelingJob.Status.RUNNING, None),
+ (DataModelingJob.Status.FAILED, "refresh failed"),
+ ]
+ )
+ def test_materialization_status_reports_latest_attempt_and_retains_fresh_build(self, job_status, error):
+ completed_at = timezone.now() - timedelta(minutes=5)
+ saved_query = DataWarehouseSavedQuery.objects.create(
+ team=self.team,
+ name=f"status-{job_status.lower()}",
+ query=self.sample_hogql_query,
+ is_materialized=True,
+ )
+ saved_query.table = DataWarehouseTable.objects.create(
+ team=self.team,
+ name=f"status_{job_status.lower()}",
+ format=DataWarehouseTable.TableFormat.Parquet,
+ url_pattern=f"s3://test-bucket/{job_status.lower()}",
+ )
+ saved_query.save(update_fields=["table"])
+ endpoint = create_endpoint_with_version(
+ name=f"status-{job_status.lower()}",
+ team=self.team,
+ query=self.sample_hogql_query,
+ created_by=self.user,
+ data_freshness_seconds=3600,
+ )
+ version = endpoint.versions.first()
+ version.saved_query = saved_query
+ version.save(update_fields=["saved_query"])
+ DataModelingJob.objects.create(
+ team=self.team,
+ saved_query=saved_query,
+ status=DataModelingJob.Status.COMPLETED,
+ engine=DataModelingJob.Engine.CLICKHOUSE,
+ last_run_at=completed_at,
+ )
+ DataModelingJob.objects.create(
+ team=self.team,
+ saved_query=saved_query,
+ status=job_status,
+ engine=DataModelingJob.Engine.CLICKHOUSE,
+ error=error,
+ last_run_at=timezone.now(),
+ )
+
+ response = self.client.get(
+ f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/materialization_status/"
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json()["status"], job_status)
+ self.assertEqual(response.json()["error"], error or "")
+ self.assertEqual(response.json()["last_materialized_at"], completed_at.isoformat())
+ self.assertTrue(response.json()["ready"])
def test_force_mode_uses_materialized_table(self):
"""Test that 'force' mode on a materialized endpoint still uses the materialized table (not inline)."""
diff --git a/products/endpoints/frontend/generated/api.schemas.ts b/products/endpoints/frontend/generated/api.schemas.ts
index 395cc1f99c3e..6867adbcc978 100644
--- a/products/endpoints/frontend/generated/api.schemas.ts
+++ b/products/endpoints/frontend/generated/api.schemas.ts
@@ -70,6 +70,10 @@ export interface UserBasicApi {
export interface EndpointMaterializationApi {
/** URL-safe endpoint name. */
name: string
+ /** Whether materialization is enabled for this endpoint version. */
+ enabled: boolean
+ /** Whether a successful materialization is available to serve. */
+ ready: boolean
/** Current materialization status (e.g. 'Completed', 'Running'). */
status?: string
/** Whether this endpoint query can be materialized. */
diff --git a/products/endpoints/mcp/tools.yaml b/products/endpoints/mcp/tools.yaml
index c70696ba13c5..85a6050a1740 100644
--- a/products/endpoints/mcp/tools.yaml
+++ b/products/endpoints/mcp/tools.yaml
@@ -22,8 +22,8 @@ tools:
title: Create endpoint
description: >
Create a new API endpoint from a HogQL or insight query. The name must be URL-safe (letters, numbers,
- hyphens, underscores, starts with a letter, max 128 chars). Materialization is auto-enabled if the query is
- eligible.
+ hyphens, underscores, starts with a letter, max 128 chars). Set is_materialized to true to materialize an
+ eligible query.
include_params:
- name
- query
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index bd2768c8d289..f96ae04058f8 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -3018,7 +3018,7 @@
}
},
"endpoint-create": {
- "description": "Create a new API endpoint from a HogQL or insight query. The name must be URL-safe (letters, numbers, hyphens, underscores, starts with a letter, max 128 chars). Materialization is auto-enabled if the query is eligible.",
+ "description": "Create a new API endpoint from a HogQL or insight query. The name must be URL-safe (letters, numbers, hyphens, underscores, starts with a letter, max 128 chars). Set is_materialized to true to materialize an eligible query.",
"category": "Endpoints",
"feature": "endpoints",
"summary": "Create endpoint",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index e8ad9a8f2010..7df57ba11182 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -3047,7 +3047,7 @@
}
},
"endpoint-create": {
- "description": "Create a new API endpoint from a HogQL or insight query. The name must be URL-safe (letters, numbers, hyphens, underscores, starts with a letter, max 128 chars). Materialization is auto-enabled if the query is eligible.",
+ "description": "Create a new API endpoint from a HogQL or insight query. The name must be URL-safe (letters, numbers, hyphens, underscores, starts with a letter, max 128 chars). Set is_materialized to true to materialize an eligible query.",
"category": "Endpoints",
"feature": "endpoints",
"summary": "Create endpoint",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 90b65e03db7e..5230a2e86971 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -29710,6 +29710,10 @@ export namespace Schemas {
export interface EndpointMaterialization {
/** URL-safe endpoint name. */
name: string;
+ /** Whether materialization is enabled for this endpoint version. */
+ enabled: boolean;
+ /** Whether a successful materialization is available to serve. */
+ ready: boolean;
/** Current materialization status (e.g. 'Completed', 'Running'). */
status?: string;
/** Whether this endpoint query can be materialized. */