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): allow turning off ineligible materializations (#110181)

Jovan Sakovic34dff06a80e6
diff --git a/products/endpoints/backend/logic/materialization.py b/products/endpoints/backend/logic/materialization.py
index d480411668dd..f5bf6b162bf2 100644
--- a/products/endpoints/backend/logic/materialization.py
+++ b/products/endpoints/backend/logic/materialization.py
@@ -180,18 +180,12 @@ class EndpointMaterializationService:
clear_endpoint_materialization_cache(self.team.pk, endpoint.name, versions=[version.version])
ENDPOINT_MATERIALIZATION_EVENT_TOTAL.labels(action="enable", status="success").inc()
if version.saved_query:
- log_activity(
- organization_id=self.team.organization_id,
- team_id=self.team.pk,
- user=self.user,
- was_impersonated=is_impersonated(self.request),
- item_id=str(version.saved_query.id),
- scope="DataWarehouseSavedQuery",
- activity="materialization_enabled",
- detail=Detail(
- name=version.saved_query.name,
- context=EndpointContext(version=version.version),
- ),
+ self._log_materialization_activity(
+ endpoint,
+ version,
+ "materialization_enabled",
+ saved_query_id=str(version.saved_query.id),
+ saved_query_name=version.saved_query.name,
)
except ValidationError:
ENDPOINT_MATERIALIZATION_EVENT_TOTAL.labels(action="enable", status="validation_error").inc()
@@ -375,22 +369,42 @@ class EndpointMaterializationService:
ENDPOINT_MATERIALIZATION_EVENT_TOTAL.labels(action="disable", status="error").inc()
raise
ENDPOINT_MATERIALIZATION_EVENT_TOTAL.labels(action="disable", status="success").inc()
+ self._log_materialization_activity(
+ endpoint,
+ version,
+ "materialization_disabled",
+ saved_query_id=saved_query_id,
+ saved_query_name=saved_query_name,
+ )
+ # Clears this version's throttle-readiness key plus the "current" key (the disabled
+ # version may be the current one) — the next request lazily re-checks the DB.
+ clear_endpoint_materialization_cache(self.team.pk, endpoint.name, versions=[version.version])
+
+ def _log_materialization_activity(
+ self,
+ endpoint: Endpoint,
+ version: EndpointVersion,
+ activity: str,
+ *,
+ saved_query_id: str,
+ saved_query_name: str,
+ ) -> None:
+ # Two rows: the model's history reads the saved query, the endpoint's history reads the
+ # endpoint. A read-time join can't replace this, since disabling unlinks the saved query.
+ for item_id, scope, name in (
+ (saved_query_id, "DataWarehouseSavedQuery", saved_query_name),
+ (str(endpoint.id), "EndpointVersion", endpoint.name),
+ ):
log_activity(
organization_id=self.team.organization_id,
team_id=self.team.pk,
user=self.user,
was_impersonated=is_impersonated(self.request),
- item_id=saved_query_id,
- scope="DataWarehouseSavedQuery",
- activity="materialization_disabled",
- detail=Detail(
- name=saved_query_name,
- context=EndpointContext(version=version.version),
- ),
+ item_id=item_id,
+ scope=scope,
+ activity=activity,
+ detail=Detail(name=name, context=EndpointContext(version=version.version)),
)
- # Clears this version's throttle-readiness key plus the "current" key (the disabled
- # version may be the current one) — the next request lazily re-checks the DB.
- clear_endpoint_materialization_cache(self.team.pk, endpoint.name, versions=[version.version])
def preview(
self,
diff --git a/products/endpoints/backend/tests/test_endpoint_materialization.py b/products/endpoints/backend/tests/test_endpoint_materialization.py
index 1be9a478bcd6..6ad48160b015 100644
--- a/products/endpoints/backend/tests/test_endpoint_materialization.py
+++ b/products/endpoints/backend/tests/test_endpoint_materialization.py
@@ -20,6 +20,7 @@ from rest_framework.response import Response
from posthog.hogql.errors import QueryError
from posthog.constants import RETENTION_FIRST_EVER_OCCURRENCE, TREND_FILTER_TYPE_EVENTS
+from posthog.models.activity_logging.activity_log import ActivityLog
from posthog.models.team.extensions import get_or_create_team_extension
from posthog.models.team.team_revenue_analytics_config import TeamRevenueAnalyticsConfig
from posthog.sync import database_sync_to_async
@@ -416,6 +417,17 @@ class TestEndpointMaterialization(ClickhouseTestMixin, APIBaseTest):
saved_query = DataWarehouseSavedQuery.objects.get(id=saved_query_id)
self.assertTrue(saved_query.deleted)
+ # The endpoint's history tab filters on the endpoint id, so both toggles must be logged there too.
+ endpoint_history = ActivityLog.objects.filter(
+ team_id=self.team.id, scope__in=["Endpoint", "EndpointVersion"], item_id=str(endpoint.id)
+ ).values_list("activity", flat=True)
+ self.assertIn("materialization_enabled", endpoint_history)
+ self.assertIn("materialization_disabled", endpoint_history)
+ model_history = ActivityLog.objects.filter(
+ team_id=self.team.id, scope="DataWarehouseSavedQuery", item_id=str(saved_query_id)
+ ).values_list("activity", flat=True)
+ self.assertIn("materialization_disabled", model_history)
+
def test_cannot_materialize_query_with_invalid_variables(self):
"""Test that queries with invalid variable metadata cannot be materialized."""
endpoint = create_endpoint_with_version(
diff --git a/products/endpoints/frontend/activityDescriber.tsx b/products/endpoints/frontend/activityDescriber.tsx
index 7956cb8a8e6b..66c2a61e3025 100644
--- a/products/endpoints/frontend/activityDescriber.tsx
+++ b/products/endpoints/frontend/activityDescriber.tsx
@@ -102,6 +102,29 @@ export function endpointActivityDescriber(logItem: ActivityLogItem, asNotificati
}
}
+ if (
+ (logItem.activity === 'materialization_enabled' || logItem.activity === 'materialization_disabled') &&
+ version !== undefined
+ ) {
+ const verb = logItem.activity === 'materialization_enabled' ? 'Turned on' : 'Turned off'
+ return {
+ summary: activityLogSummary(
+ logItem,
+ <>
+ {verb} materialization for <VersionLink name={endpointName} version={version} />
+ </>,
+ <EndpointLink name={endpointName} />
+ ),
+ description: (
+ <>
+ <ActivityLogUserName logItem={logItem} /> {verb.toLowerCase()} materialization for{' '}
+ <VersionLink name={endpointName} version={version} /> of endpoint{' '}
+ <EndpointLink name={endpointName} />.
+ </>
+ ),
+ }
+ }
+
if (logItem.activity === 'updated') {
return {
summary: activityLogSummary(logItem, 'Updated the endpoint', <EndpointLink name={endpointName} />),
diff --git a/products/endpoints/frontend/endpoint-tabs/EndpointConfiguration.tsx b/products/endpoints/frontend/endpoint-tabs/EndpointConfiguration.tsx
index 9ceac1426a83..6b24580391f0 100644
--- a/products/endpoints/frontend/endpoint-tabs/EndpointConfiguration.tsx
+++ b/products/endpoints/frontend/endpoint-tabs/EndpointConfiguration.tsx
@@ -369,6 +369,9 @@ function MaterializationContent(): JSX.Element {
const cannotMaterializeReason =
materializationPreview?.reason ?? freshMaterialization?.reason ?? endpoint.materialization?.reason ?? null
const isMaterialized = effectiveIsMaterialized || effectiveMaterializationStatus?.toLowerCase() === 'running'
+ // Eligibility gates turning materialization on. A version materialized before its query became
+ // ineligible still needs the switch, or there is no way to turn it off.
+ const showMaterializationSwitch = canMaterialize || baseIsMaterialized
const handleToggleMaterialization = (): void => {
setIsMaterialized(!isMaterialized)
@@ -392,11 +395,13 @@ function MaterializationContent(): JSX.Element {
</p>
{!canMaterialize && cannotMaterializeReason && (
- <div className="flex flex-col gap-4 items-start">
+ <div className="flex flex-col gap-4 items-start mb-4">
<LemonBanner type="warning" hideIcon={false} className="w-full">
<div className="flex flex-col gap-1">
<span className="font-semibold">
- This endpoint can't be materialized yet, so every execution runs the full query.
+ {baseIsMaterialized
+ ? "This endpoint is materialized, but its query isn't supported for materialization anymore. You can turn materialization off. To turn it back on, change the query first."
+ : "This endpoint can't be materialized yet, so every execution runs the full query."}
</span>
<span className="font-normal">Reason: {cannotMaterializeReason}</span>
</div>
@@ -420,7 +425,7 @@ function MaterializationContent(): JSX.Element {
</div>
)}
- {canMaterialize && (
+ {showMaterializationSwitch && (
<div className="flex flex-col gap-4">
<AccessControlAction
resourceType={AccessControlResourceType.Endpoint}