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): keep the endpoints workload tag off the inline fallback (#116678)

Thiago Salvatorefbc40d93d3f0
diff --git a/products/endpoints/backend/logic/execution.py b/products/endpoints/backend/logic/execution.py
index 2f4fa9d01673..af7e5c9dcbd8 100644
--- a/products/endpoints/backend/logic/execution.py
+++ b/products/endpoints/backend/logic/execution.py
@@ -53,6 +53,7 @@ from posthog.clickhouse.query_tagging import (
get_query_tag_value,
is_api_key_access_method,
tag_queries,
+ tags_context,
)
from posthog.errors import ExposedCHQueryError
from posthog.event_usage import get_request_analytics_properties, report_user_action
@@ -801,46 +802,33 @@ class EndpointExecutionService(PydanticModelMixin):
"endpoint_materialized": True,
"endpoint_materialized_at": materialized_at.isoformat() if materialized_at else None,
}
- tag_queries(
+ with tags_context(
workload=Workload.ENDPOINTS,
warehouse_query=True,
endpoint_version=version.version,
- )
-
- # Compute dynamic cache TTL: time remaining until data_freshness window expires
- cache_ttl = None
- if materialized_at and version.data_freshness_seconds:
- remaining = (
- materialized_at + timedelta(seconds=version.data_freshness_seconds) - timezone.now()
- ).total_seconds()
- if remaining <= 0:
- logger.warning(
- "endpoint_materialization_behind_sla",
- endpoint_name=endpoint.name,
- team_id=self.team.pk,
- data_freshness_seconds=version.data_freshness_seconds,
- last_run_at=materialized_at.isoformat(),
- remaining_seconds=remaining,
- )
- tag_queries(endpoint_materialization_behind=True)
- cache_ttl = max(1, int(remaining)) # at least 1 second to enable caching
+ ):
+ # Compute dynamic cache TTL: time remaining until data_freshness window expires
+ cache_ttl = None
+ if materialized_at and version.data_freshness_seconds:
+ remaining = (
+ materialized_at + timedelta(seconds=version.data_freshness_seconds) - timezone.now()
+ ).total_seconds()
+ if remaining <= 0:
+ logger.warning(
+ "endpoint_materialization_behind_sla",
+ endpoint_name=endpoint.name,
+ team_id=self.team.pk,
+ data_freshness_seconds=version.data_freshness_seconds,
+ last_run_at=materialized_at.isoformat(),
+ remaining_seconds=remaining,
+ )
+ tag_queries(endpoint_materialization_behind=True)
+ cache_ttl = max(1, int(remaining)) # at least 1 second to enable caching
- result = self._execute_query_and_respond(
- query_request_data,
- data.client_query_id,
- cache_age_seconds=cache_ttl,
- extra_result_fields=extra_fields,
- debug=debug,
- headers=deprecation_headers,
- pagination=pagination,
- limit_context=strategy.materialized_limit_context,
- )
-
- if self._is_cache_stale(result, materialized_at):
- query_request_data["refresh"] = RefreshType.FORCE_BLOCKING
result = self._execute_query_and_respond(
query_request_data,
data.client_query_id,
+ cache_age_seconds=cache_ttl,
extra_result_fields=extra_fields,
debug=debug,
headers=deprecation_headers,
@@ -848,6 +836,18 @@ class EndpointExecutionService(PydanticModelMixin):
limit_context=strategy.materialized_limit_context,
)
+ if self._is_cache_stale(result, materialized_at):
+ query_request_data["refresh"] = RefreshType.FORCE_BLOCKING
+ result = self._execute_query_and_respond(
+ query_request_data,
+ data.client_query_id,
+ extra_result_fields=extra_fields,
+ debug=debug,
+ headers=deprecation_headers,
+ pagination=pagination,
+ limit_context=strategy.materialized_limit_context,
+ )
+
if isinstance(result.data, dict):
strategy.clean_response_sentinels(result.data)
diff --git a/products/endpoints/backend/tests/test_endpoint_execution.py b/products/endpoints/backend/tests/test_endpoint_execution.py
index deb1f660c372..7baf1dd0613e 100644
--- a/products/endpoints/backend/tests/test_endpoint_execution.py
+++ b/products/endpoints/backend/tests/test_endpoint_execution.py
@@ -16,6 +16,8 @@ from posthog.schema import EventsNode, TrendsQuery
from posthog.hogql.constants import LimitContext
from posthog.hogql.errors import ExposedHogQLError
+from posthog.clickhouse.client.connection import Workload
+from posthog.clickhouse.query_tagging import get_query_tags
from posthog.errors import CHQueryErrorNoCommonType
from posthog.exceptions import APIQueriesBudgetExceeded, ClickHouseAtCapacity
@@ -2522,10 +2524,18 @@ class TestEndpointExecution(ClickhouseTestMixin, APIBaseTest):
)
inline_response = Response({"results": [[1]], "columns": ["count()"]})
+ outcomes: list[Response | Exception] = [RuntimeError("materialized table exploded"), inline_response]
+ workloads_seen: list[str | None] = []
+
+ def run_query(*args, **kwargs) -> Response:
+ workloads_seen.append(get_query_tags().workload)
+ outcome = outcomes.pop(0)
+ if isinstance(outcome, Exception):
+ raise outcome
+ return outcome
+
with mock.patch.object(
- EndpointExecutionService,
- "_execute_query_and_respond",
- side_effect=[RuntimeError("materialized table exploded"), inline_response],
+ EndpointExecutionService, "_execute_query_and_respond", side_effect=run_query
) as mock_exec:
response = self.client.post(
f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/run/", {}, format="json"
@@ -2533,6 +2543,10 @@ class TestEndpointExecution(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(mock_exec.call_count, 2, "expected materialized attempt then inline fallback")
+ self.assertEqual(workloads_seen[0], Workload.ENDPOINTS)
+ self.assertNotEqual(
+ workloads_seen[1], Workload.ENDPOINTS, "the inline fallback must not run on the endpoints cluster"
+ )
def test_materialized_cache_ttl_derived_from_modeling_jobs(self):
"""v2 DAG runs record success in DataModelingJob but never write saved_query.last_run_at.