:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(endpoints): revert stale materializations on DAG-scheduled teams (#93424)
Jovan Sakovic500765f74c4c
diff --git a/products/endpoints/backend/logic/execution.py b/products/endpoints/backend/logic/execution.pyindex b979cf987856..60fa78ab0a01 100644--- a/products/endpoints/backend/logic/execution.py+++ b/products/endpoints/backend/logic/execution.py@@ -604,6 +604,7 @@ class EndpointExecutionService(PydanticModelMixin):error_label = type(e).__name__raisefinally:+ self._track_last_executed(endpoint, version_obj)if execution_status is not None:_duration = time.monotonic() - _start_timeENDPOINT_EXECUTION_DURATION_SECONDS.labels(@@ -641,7 +642,6 @@ class EndpointExecutionService(PydanticModelMixin):version=version_obj.version,),)- self._track_last_executed(endpoint, version_obj)self._maybe_shadow_ducklake(endpoint,diff --git a/products/endpoints/backend/tasks/tasks.py b/products/endpoints/backend/tasks/tasks.pyindex 3a6b2cf7d611..51143ba968b3 100644--- a/products/endpoints/backend/tasks/tasks.py+++ b/products/endpoints/backend/tasks/tasks.py@@ -1,6 +1,7 @@from datetime import timedeltafrom typing import Any+from django.db.models import Exists, OuterRef, Qfrom django.utils import timezonefrom celery import shared_task@@ -9,6 +10,7 @@ from structlog import get_loggerfrom posthog.celery_queues import CeleryQueuefrom posthog.scoping_audit import skip_team_scope_audit+from products.data_modeling.backend.facade.models import DataModelingJob, DataModelingJobStatusfrom products.endpoints.backend.logic.ducklake_shadow import run_ducklake_shadow_comparisonfrom products.endpoints.backend.metrics import ENDPOINT_MATERIALIZATION_EVENT_TOTALfrom products.endpoints.backend.models import EndpointVersion@@ -58,9 +60,9 @@ def deactivate_stale_materializations() -> None:This task finds endpoint versions where:1. The version has an active materialization (saved_query.is_materialized = True)- 2. The materialization has run in the past 24h (saved_query.last_run_at within 24h)+ 2. The materialization has run in the past 24h (a completed job, or saved_query.last_run_at)3. The materialization was enabled at least 30 days ago (saved_query.created_at)- 4. The endpoint was last executed over 30 days ago (via API key)+ 4. The version was last executed over 30 days ago (via API key)For matching versions, the materialization is reverted to save resources."""@@ -68,13 +70,24 @@ def deactivate_stale_materializations() -> None:twenty_four_hours_ago = now - timedelta(hours=24)stale_threshold = now - timedelta(days=STALE_THRESHOLD_DAYS)+ recent_job = DataModelingJob.objects.filter(+ saved_query_id=OuterRef("saved_query_id"),+ status=DataModelingJobStatus.COMPLETED,+ last_run_at__gte=twenty_four_hours_ago,+ )+ ran_recently = Q(saved_query__last_run_at__gte=twenty_four_hours_ago) | Q(Exists(recent_job))++ version_stale = Q(last_executed_at__lt=stale_threshold) | Q(+ last_executed_at__isnull=True, endpoint__last_executed_at__lt=stale_threshold+ )+stale_versions = EndpointVersion.objects.filter(+ ran_recently,+ version_stale,saved_query__isnull=False,saved_query__is_materialized=True,- saved_query__last_run_at__gte=twenty_four_hours_ago,saved_query__deleted=False,saved_query__created_at__lte=stale_threshold,- endpoint__last_executed_at__lt=stale_threshold,endpoint__deleted=False,).select_related("saved_query", "endpoint")diff --git a/products/endpoints/backend/tests/test_deactivate_stale_materializations.py b/products/endpoints/backend/tests/test_deactivate_stale_materializations.pyindex e620cd52ade3..3e91cb6b2be6 100644--- a/products/endpoints/backend/tests/test_deactivate_stale_materializations.py+++ b/products/endpoints/backend/tests/test_deactivate_stale_materializations.py@@ -6,7 +6,7 @@ from unittest import mockfrom django.utils import timezone-from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery+from products.data_modeling.backend.facade.models import DataModelingJob, DataWarehouseSavedQueryfrom products.endpoints.backend.models import Endpoint, EndpointVersionfrom products.endpoints.backend.tasks.tasks import (STALE_THRESHOLD_DAYS,@@ -228,6 +228,69 @@ class TestDeactivateStaleMaterializationsTask(BaseTest):version.refresh_from_db()assert version.saved_query is None+ @mock.patch("products.endpoints.backend.tasks.tasks._deactivate_version_materialization")+ def test_selects_stale_version_whose_saved_query_last_run_at_is_never_written(self, mock_deactivate):+ now = timezone.now()+ _, version = self._create_materialized_endpoint(+ name="v2_scheduled",+ last_run_at=now - timedelta(days=40),+ last_executed_at=now - timedelta(days=45),+ materialization_created_at=now - timedelta(days=45),+ )+ DataModelingJob.objects.create(+ team=self.team,+ saved_query=version.saved_query,+ status=DataModelingJob.Status.COMPLETED,+ last_run_at=now - timedelta(hours=1),+ )++ deactivate_stale_materializations()++ mock_deactivate.assert_called_once()+ assert mock_deactivate.call_args[0][0].id == version.id++ @mock.patch("products.endpoints.backend.tasks.tasks._deactivate_version_materialization")+ def test_deactivates_superseded_version_of_an_active_endpoint(self, mock_deactivate):+ now = timezone.now()+ endpoint, old_version = self._create_materialized_endpoint(+ name="active_endpoint",+ last_executed_at=now - timedelta(days=5),+ materialization_created_at=now - timedelta(days=45),+ )+ EndpointVersion.objects.filter(id=old_version.id).update(last_executed_at=now - timedelta(days=45))++ current_saved_query = DataWarehouseSavedQuery.objects.create(+ team=self.team,+ name="active_endpoint_v2",+ query=self.sample_hogql_query,+ is_materialized=True,+ last_run_at=now,+ origin=DataWarehouseSavedQuery.Origin.ENDPOINT,+ table=DataWarehouseTable.objects.create(+ team=self.team,+ name="active_endpoint_v2_table",+ format=DataWarehouseTable.TableFormat.Parquet,+ url_pattern="s3://test-bucket/active_endpoint_v2_table",+ ),+ )+ DataWarehouseSavedQuery.objects.filter(id=current_saved_query.id).update(created_at=now - timedelta(days=40))+ current_version = EndpointVersion.objects.create(+ endpoint=endpoint,+ version=2,+ query=self.sample_hogql_query,+ created_by=self.user,+ saved_query=current_saved_query,+ last_executed_at=now - timedelta(days=5),+ )+ endpoint.current_version = 2+ endpoint.save(update_fields=["current_version"])++ deactivate_stale_materializations()++ deactivated_ids = {call.args[0].id for call in mock_deactivate.call_args_list}+ assert deactivated_ids == {old_version.id}+ assert current_version.id not in deactivated_ids+class TestDeactivateEndpointMaterialization(BaseTest):def setUp(self):diff --git a/products/endpoints/backend/tests/test_endpoint.py b/products/endpoints/backend/tests/test_endpoint.pyindex d6b559c44076..7ac3f680afb8 100644--- a/products/endpoints/backend/tests/test_endpoint.py+++ b/products/endpoints/backend/tests/test_endpoint.py@@ -14,6 +14,7 @@ from rest_framework import statusfrom posthog.schema import EndpointLastExecutionTimesRequest+from posthog.exceptions import ClickHouseQueryTimeOutfrom posthog.models.activity_logging.activity_log import ActivityLogfrom posthog.models.personal_api_key import PersonalAPIKeyfrom posthog.models.team import Team@@ -857,6 +858,30 @@ class TestEndpoint(ClickhouseTestMixin, APIBaseTest):self.assertIsNotNone(endpoint.last_executed_at)self.assertIsNotNone(version.last_executed_at)+ def test_api_key_run_that_times_out_still_stamps_last_executed_at(self):+ create_endpoint_with_version(+ name="slow_query",+ team=self.team,+ query={"kind": "HogQLQuery", "query": "SELECT 1"},+ created_by=self.user,+ is_active=True,+ )++ with mock.patch(+ "products.endpoints.backend.logic.execution.process_query_model",+ side_effect=ClickHouseQueryTimeOut(),+ ):+ response = self.client.get(+ f"/api/environments/{self.team.id}/endpoints/slow_query/run/",+ headers={"authorization": f"Bearer {self.api_key}"},+ )+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.json())++ endpoint = Endpoint.objects.get(name="slow_query", team=self.team)+ version = EndpointVersion.objects.get(endpoint=endpoint, version=1)+ self.assertIsNotNone(endpoint.last_executed_at)+ self.assertIsNotNone(version.last_executed_at)+def test_last_execution_times_is_endpoint_level_only(self):"""last_execution_times returns endpoint-level rows only — per-version data is not exposed."""endpoint = create_endpoint_with_version(