: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
chore(endpoints): refactor Endpoints and make easier to work with (#62705)
Jovan Sakovicc28cea67a192
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex e20a4b394a45..f33893624654 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -16161,6 +16161,49 @@},"type": "object"},+ "EndpointBreakdownLimitExceededSignalExtra": {+ "additionalProperties": false,+ "properties": {+ "breakdown_limit": {+ "type": "number"+ },+ "endpoint_name": {+ "type": "string"+ }+ },+ "required": ["endpoint_name", "breakdown_limit"],+ "type": "object"+ },+ "EndpointBreakdownLimitExceededSignalInput": {+ "additionalProperties": false,+ "properties": {+ "description": {+ "type": "string"+ },+ "extra": {+ "$ref": "#/definitions/EndpointBreakdownLimitExceededSignalExtra"+ },+ "remediation": {+ "$ref": "#/definitions/SignalRemediation"+ },+ "source_id": {+ "type": "string"+ },+ "source_product": {+ "const": "endpoints",+ "type": "string"+ },+ "source_type": {+ "const": "endpoint_breakdown_limit_exceeded",+ "type": "string"+ },+ "weight": {+ "type": "number"+ }+ },+ "required": ["description", "extra", "source_id", "source_product", "source_type", "weight"],+ "type": "object"+ },"EndpointExecutionFailedSignalExtra": {"additionalProperties": false,"properties": {@@ -40208,6 +40251,9 @@{"$ref": "#/definitions/EndpointExecutionFailedSignalInput"},+ {+ "$ref": "#/definitions/EndpointBreakdownLimitExceededSignalInput"+ },{"$ref": "#/definitions/PgAnalyzeIssueSignalInput"},@@ -40321,6 +40367,7 @@"issue_reopened","issue_spiking","endpoint_execution_failed",+ "endpoint_breakdown_limit_exceeded","cross_source_issue","alert_state_change","health_issue"diff --git a/frontend/src/queries/schema/schema-signals.ts b/frontend/src/queries/schema/schema-signals.tsindex da3984065d03..b28a93fb2199 100644--- a/frontend/src/queries/schema/schema-signals.ts+++ b/frontend/src/queries/schema/schema-signals.ts@@ -28,6 +28,7 @@ export enum SignalSourceType {ISSUE_REOPENED = 'issue_reopened',ISSUE_SPIKING = 'issue_spiking',ENDPOINT_EXECUTION_FAILED = 'endpoint_execution_failed',+ ENDPOINT_BREAKDOWN_LIMIT_EXCEEDED = 'endpoint_breakdown_limit_exceeded',CROSS_SOURCE_ISSUE = 'cross_source_issue',ALERT_STATE_CHANGE = 'alert_state_change',HEALTH_ISSUE = 'health_issue',@@ -300,6 +301,19 @@ export interface EndpointExecutionFailedSignalInput extends SignalInputBase {extra: EndpointExecutionFailedSignalExtra}+// Endpoint breakdown limit exceeded — the 'Other' bucket appeared in results++export interface EndpointBreakdownLimitExceededSignalExtra extends SignalExtraBase {+ endpoint_name: string+ breakdown_limit: number+}++export interface EndpointBreakdownLimitExceededSignalInput extends SignalInputBase {+ source_type: 'endpoint_breakdown_limit_exceeded'+ source_product: 'endpoints'+ extra: EndpointBreakdownLimitExceededSignalExtra+}+// Signals scout — cross-source findings emitted by the headless Signals scout harness.export interface SignalsScoutEvidenceEntry {@@ -426,6 +440,7 @@ export type SignalInput =| ConversationsTicketSignalInput| ErrorTrackingSignalInput| EndpointExecutionFailedSignalInput+ | EndpointBreakdownLimitExceededSignalInput| PgAnalyzeIssueSignalInput| SignalsScoutSignalInput| LogsAlertStateChangeSignalInputdiff --git a/posthog/schema.py b/posthog/schema.pyindex 1975f95adec8..09208968450f 100644--- a/posthog/schema.py+++ b/posthog/schema.py@@ -1036,6 +1036,14 @@ class EmptyPropertyFilter(BaseModel):type: Literal["empty"] = "empty"+class EndpointBreakdownLimitExceededSignalExtra(BaseModel):+ model_config = ConfigDict(+ extra="forbid",+ )+ breakdown_limit: float+ endpoint_name: str++class EndpointExecutionFailedSignalExtra(BaseModel):model_config = ConfigDict(extra="forbid",@@ -4543,6 +4551,19 @@ class EmbeddingDistance(BaseModel):result: EmbeddingRecord+class EndpointBreakdownLimitExceededSignalInput(BaseModel):+ model_config = ConfigDict(+ extra="forbid",+ )+ description: str+ extra: EndpointBreakdownLimitExceededSignalExtra+ remediation: SignalRemediation | None = None+ source_id: str+ source_product: Literal["endpoints"] = "endpoints"+ source_type: Literal["endpoint_breakdown_limit_exceeded"] = "endpoint_breakdown_limit_exceeded"+ weight: float++class EndpointExecutionFailedSignalInput(BaseModel):model_config = ConfigDict(extra="forbid",@@ -6670,6 +6691,7 @@ class SignalInput(| ConversationsTicketSignalInput| ErrorTrackingSignalInput| EndpointExecutionFailedSignalInput+ | EndpointBreakdownLimitExceededSignalInput| PgAnalyzeIssueSignalInput| SignalsScoutSignalInput| LogsAlertStateChangeSignalInput@@ -6686,6 +6708,7 @@ class SignalInput(| ConversationsTicketSignalInput| ErrorTrackingSignalInput| EndpointExecutionFailedSignalInput+ | EndpointBreakdownLimitExceededSignalInput| PgAnalyzeIssueSignalInput| SignalsScoutSignalInput| LogsAlertStateChangeSignalInputdiff --git a/posthog/schema_enums.py b/posthog/schema_enums.pyindex 403df6380c86..7dc4727559c0 100644--- a/posthog/schema_enums.py+++ b/posthog/schema_enums.py@@ -2958,6 +2958,7 @@ class SignalSourceType(StrEnum):ISSUE_REOPENED = "issue_reopened"ISSUE_SPIKING = "issue_spiking"ENDPOINT_EXECUTION_FAILED = "endpoint_execution_failed"+ ENDPOINT_BREAKDOWN_LIMIT_EXCEEDED = "endpoint_breakdown_limit_exceeded"CROSS_SOURCE_ISSUE = "cross_source_issue"ALERT_STATE_CHANGE = "alert_state_change"HEALTH_ISSUE = "health_issue"diff --git a/posthog/temporal/data_modeling/activities/materialize_view.py b/posthog/temporal/data_modeling/activities/materialize_view.pyindex 7cbd529fcc8c..ab2a77dee69c 100644--- a/posthog/temporal/data_modeling/activities/materialize_view.py+++ b/posthog/temporal/data_modeling/activities/materialize_view.py@@ -35,7 +35,7 @@ from products.data_modeling.backend.models.data_modeling_job import DataModelingfrom products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQueryfrom products.data_modeling.backend.models.modeling import bounded_resolver_factory_for_viewfrom products.data_warehouse.backend.s3 import ensure_bucket_exists, get_s3_client-from products.endpoints.backend.services.endpoint_materialization_service import prepare_executable_query+from products.endpoints.backend.services.materialization import prepare_executable_queryLOGGER = get_logger(__name__)diff --git a/posthog/temporal/data_modeling/activities/materialize_view_duckgres.py b/posthog/temporal/data_modeling/activities/materialize_view_duckgres.pyindex 2804327db702..9dd8d32d3931 100644--- a/posthog/temporal/data_modeling/activities/materialize_view_duckgres.py+++ b/posthog/temporal/data_modeling/activities/materialize_view_duckgres.py@@ -16,7 +16,7 @@ from posthog.temporal.common.logger import get_loggerfrom products.data_modeling.backend.models import Node, NodeTypefrom products.data_modeling.backend.models.data_modeling_job import DataModelingJob, DataModelingJobStatusfrom products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery-from products.endpoints.backend.services.endpoint_materialization_service import prepare_executable_query+from products.endpoints.backend.services.materialization import prepare_executable_queryLOGGER = get_logger(__name__)diff --git a/posthog/temporal/data_modeling/run_workflow.py b/posthog/temporal/data_modeling/run_workflow.pyindex 62ba13e853c1..f6a2cd545f98 100644--- a/posthog/temporal/data_modeling/run_workflow.py+++ b/posthog/temporal/data_modeling/run_workflow.py@@ -72,8 +72,8 @@ from products.data_modeling.backend.models.modeling import DataWarehouseModelPatfrom products.data_warehouse.backend.data_load.create_table import create_table_from_saved_queryfrom products.data_warehouse.backend.data_load.saved_query_service import a_pause_saved_query_schedulefrom products.data_warehouse.backend.s3 import ensure_bucket_exists, get_s3_client-from products.endpoints.backend.rate_limit import set_endpoint_materialization_ready-from products.endpoints.backend.services.endpoint_materialization_service import prepare_executable_query+from products.endpoints.backend.rate_limit import update_materialization_ready_for_saved_query+from products.endpoints.backend.services.materialization import prepare_executable_queryfrom products.warehouse_sources.backend.models.table import DataWarehouseTableLOGGER = get_logger(__name__)@@ -1596,7 +1596,7 @@ async def update_saved_query_status(if saved_query.origin == DataWarehouseSavedQuery.Origin.ENDPOINT:is_ready = status == DataWarehouseSavedQuery.Status.COMPLETED- await database_sync_to_async(set_endpoint_materialization_ready)(team_id, saved_query.name, is_ready)+ await database_sync_to_async(update_materialization_ready_for_saved_query)(team_id, saved_query, is_ready)@dataclasses.dataclassdiff --git a/products/endpoints/backend/api.py b/products/endpoints/backend/api.pyindex f8d6bd1c795c..13eff1d64b50 100644--- a/products/endpoints/backend/api.py+++ b/products/endpoints/backend/api.py@@ -1,90 +1,47 @@+"""HTTP layer for the Endpoints product.++The viewset is intentionally thin: authentication/permissions, request parsing,+and response serialization. Business logic lives in ``backend/services``:++- ``services.crud``: create/update/destroy orchestration + activity logging+- ``services.execution``: the /run path (materialized / inline / DuckLake)+- ``services.materialization``: enable/disable/preview materialization+- ``services.strategies``: HogQL vs insight query behavior+- ``services.validation``: request payload validation+"""+import re-import time-import uuid-import builtinsimport dataclasses-from collections.abc import Iterator-from datetime import timedelta-from typing import Any, Optional, Union, castfrom django.shortcuts import get_object_or_404-from django.utils import timezone-import structlog-import posthoganalytics-from asgiref.sync import async_to_sync-from dateutil.parser import isoparsefrom django_filters.rest_framework import DjangoFilterBackendfrom drf_spectacular.utils import OpenApiParameter, extend_schema_view-from loginas.utils import is_impersonated_session-from pydantic import (- BaseModel,- ValidationError as PydanticValidationError,-)+from pydantic import ValidationError as PydanticValidationErrorfrom rest_framework import serializers, status, viewsets-from rest_framework.exceptions import PermissionDenied, Throttled, ValidationError+from rest_framework.exceptions import PermissionDenied, ValidationErrorfrom rest_framework.permissions import IsAuthenticatedfrom rest_framework.request import Requestfrom rest_framework.response import Responsefrom posthog.schema import (- DashboardFilter,EndpointLastExecutionTimesRequest,- EndpointRefreshMode,EndpointRequest,EndpointRunRequest,- HogQLQuery,- HogQLQueryModifiers,- HogQLVariable,- PropertyOperator,- QueryRequest,QueryStatus,QueryStatusResponse,- RefreshType,)-from posthog.hogql import ast-from posthog.hogql.context import HogQLContext-from posthog.hogql.errors import ExposedHogQLError, QueryError, ResolutionError-from posthog.hogql.parser import parse_expr, parse_select-from posthog.hogql.printer import to_printed_hogql-from posthog.hogql.printer.hogql import HogQLPrinter-from posthog.hogql.printer.utils import print_prepared_ast-from posthog.hogql.visitor import CloningVisitor-from posthog.api.documentation import extend_schemafrom posthog.api.log_entries import LogEntryMixinfrom posthog.api.mixins import PydanticModelMixin, ValidatedRequest, validated_request-from posthog.api.query import _process_query_requestfrom posthog.api.routing import TeamAndOrgViewSetMixin-from posthog.api.services.query import process_query_modelfrom posthog.api.shared import UserBasicSerializer-from posthog.api.tagged_item import TaggedItemViewSetMixin, cleanup_orphan_tags, set_tags_on_object+from posthog.api.tagged_item import TaggedItemViewSetMixinfrom posthog.api.utils import actionfrom posthog.auth import ProjectSecretAPIKeyAuthentication-from posthog.clickhouse.client.connection import Workload-from posthog.clickhouse.client.limit import ConcurrencyLimitExceeded-from posthog.clickhouse.query_tagging import (- Feature,- Product,- get_query_tag_value,- is_api_key_access_method,- tag_queries,-)-from posthog.ducklake.common import get_duckgres_server_for_organization-from posthog.errors import ExposedCHQueryError-from posthog.event_usage import get_request_analytics_properties, report_user_action+from posthog.clickhouse.query_tagging import Productfrom posthog.exceptions_capture import capture_exception-from posthog.hogql_queries.insights.utils.breakdowns import BREAKDOWN_NULL_STRING_LABEL, BREAKDOWN_OTHER_STRING_LABEL-from posthog.hogql_queries.query_runner import BLOCKING_EXECUTION_MODES-from posthog.models import User-from posthog.models.activity_logging.activity_log import (- ActivityContextBase,- Change,- Detail,- changes_between,- log_activity,-)from posthog.permissions import (APIScopePermission,TeamMemberAccessPermission,@@ -93,42 +50,9 @@ from posthog.permissions import (from posthog.rbac.access_control_api_mixin import AccessControlViewSetMixinfrom posthog.rbac.user_access_control import access_level_satisfied_for_resourcefrom posthog.schema_migrations.upgrade import upgrade-from posthog.synthetic_user import SyntheticUser-from posthog.types import InsightQueryNode--from products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery-from products.data_modeling.backend.services.saved_query_dag_sync import delete_node_from_dag, sync_saved_query_to_dag-from products.data_warehouse.backend.data_load.saved_query_service import trigger_saved_query_schedule-from products.endpoints.backend.insight_transformers import (- MaterializedSeriesMismatchError,- transform_materialized_insight_response,-)-from products.endpoints.backend.logs import ENDPOINTS_LOG_SOURCE, build_execution_message, log_endpoint_execution-from products.endpoints.backend.materialization import (- ENDPOINT_BREAKDOWN_LIMIT,- SUPPORTED_BUCKET_FUNCTIONS,- VariablePlaceholderFinder,- _extract_aggregate_name,- analyze_variables_for_materialization,- build_endpoint_hogql,- convert_insight_query_to_hogql,- get_reaggregation,- prepare_insight_query_for_endpoint,- transform_query_for_materialization,- transform_select_for_materialized_table,-)-from products.endpoints.backend.metrics import (- ENDPOINT_CACHE_RESULT_TOTAL,- ENDPOINT_CONCURRENCY_REJECTED_TOTAL,- ENDPOINT_DUCKLAKE_FALLBACK_TOTAL,- ENDPOINT_EXECUTION_DURATION_SECONDS,- ENDPOINT_EXECUTION_TOTAL,- ENDPOINT_HOGQL_RESULT_ROWS,- ENDPOINT_MATERIALIZATION_EVENT_TOTAL,- ENDPOINT_MATERIALIZED_FRESHNESS_RATIO,- ENDPOINT_VALIDATION_ERROR_TOTAL,- query_kind_label,-)++from products.endpoints.backend.constants import ENDPOINT_NAME_REGEX+from products.endpoints.backend.logs import ENDPOINTS_LOG_SOURCEfrom products.endpoints.backend.models import Endpoint, EndpointVersionfrom products.endpoints.backend.openapi import generate_openapi_specfrom products.endpoints.backend.rate_limit import (@@ -136,7 +60,6 @@ from products.endpoints.backend.rate_limit import (EndpointProjectSecretApiKeyTeamBurstThrottle,EndpointProjectSecretApiKeyTeamSustainedThrottle,EndpointSustainedThrottle,- clear_endpoint_materialization_cache,)from products.endpoints.backend.serializers import (EndpointMaterializationSerializer,@@ -145,251 +68,17 @@ from products.endpoints.backend.serializers import (EndpointRunResponseSerializer,EndpointVersionResponseSerializer,)-from products.product_analytics.backend.models.insight_variable import InsightVariable-from products.warehouse_sources.backend.models.external_data_schema import sync_frequency_to_sync_frequency_interval--from common.hogvm.python.utils import HogVMException--DATA_FRESHNESS_BUCKETS: dict[int, str] = {- 900: "15min",- 1800: "30min",- 3600: "1hour",- 21600: "6hour",- 43200: "12hour",- 86400: "24hour",- 604800: "7day",-}-VALID_DATA_FRESHNESS_SECONDS: frozenset[int] = frozenset(DATA_FRESHNESS_BUCKETS)-DEFAULT_DATA_FRESHNESS_SECONDS = 86400--ENDPOINT_NAME_REGEX = r"^[a-zA-Z][a-zA-Z0-9_-]{0,127}$"--logger = structlog.get_logger(__name__)---def _emit_endpoint_failure_signal(- team,- endpoint: "Endpoint",- exc: BaseException,- *,- materialized: bool,- version: int | None = None,- saved_query_id: Union[str, uuid.UUID, None] = None,- query_kind: str | None = None,- executed_sql: str | None = None,- saved_query_status: str | None = None,- saved_query_last_run_at: str | None = None,- saved_query_columns: dict | None = None,- endpoint_columns: list | None = None,-) -> None:- """Fire a Signal when an endpoint execution fails, so the AI can reason about it later.-- Fails silently — signal emission must never mask the underlying error.- """- from products.signals.backend.facade.api import emit_signal-- try:- error_class = type(exc).__name__- error_msg = str(exc)- version_str = f" v{version}" if version else ""-- if materialized:- execution_mode = "materialized"- context = (- f"The materialized table (saved_query_id={saved_query_id}) may be stale, missing, or have a schema mismatch. "- f"Check whether the materialization refresh completed successfully and whether the underlying query still produces valid columns."- )- if saved_query_status:- context += f"\nSaved query status: {saved_query_status}"- if saved_query_last_run_at:- context += f", last materialized at: {saved_query_last_run_at}"- if saved_query_columns:- context += f"\nMaterialized table columns: {saved_query_columns}"- if endpoint_columns:- context += f"\nEndpoint version columns: {endpoint_columns}"- else:- execution_mode = "inline"- context = (- f"The query is executed on-demand against live data. "- f"Common causes: invalid HogQL syntax, missing or renamed properties, query timeout, or incompatible variable overrides."- )-- parts = [- f"Endpoint '{endpoint.name}'{version_str} failed during {execution_mode} execution.",- f"Error: {error_class}: {error_msg}",- ]- if query_kind:- parts.append(f"Query kind: {query_kind}")- if executed_sql:- parts.append(f"Executed HogQL: {executed_sql}")- parts.append(context)- parts.append(f"Endpoint path: {endpoint.endpoint_path}")- description = "\n".join(parts)-- async_to_sync(emit_signal)(- team=team,- source_product="endpoints",- source_type="endpoint_execution_failed",- source_id=f"{team.id}:{endpoint.name}",- description=description,- weight=0.5,- extra={- "endpoint_name": endpoint.name,- "endpoint_version": version,- "materialized": materialized,- "saved_query_id": str(saved_query_id) if saved_query_id else None,- "error_class": error_class,- "error_message": error_msg,- },- )- except Exception:- logger.exception("Failed to emit endpoint failure signal", endpoint_name=endpoint.name)---def _add_where_condition(select_query: ast.SelectQuery, condition: ast.Expr) -> None:- """Append a condition to select_query.where with AND."""- if select_query.where:- select_query.where = ast.And(exprs=[select_query.where, condition])- else:- select_query.where = condition---def _get_single_breakdown_property(breakdown_filter: dict) -> str | None:- """Extract the breakdown property name from either legacy or new format.-- Legacy: {"breakdown": "$browser", "breakdown_type": "event"}- New: {"breakdowns": [{"property": "$browser", "type": "event"}]}- """- breakdown = breakdown_filter.get("breakdown")- if breakdown:- return breakdown-- breakdowns = breakdown_filter.get("breakdowns") or []- if len(breakdowns) == 1:- return breakdowns[0].get("property")-- return None---def _iter_breakdowns(breakdown_filter: dict) -> Iterator[tuple[str, str]]:- """Yield (property_name, property_type) from legacy or new breakdown format."""- breakdown = breakdown_filter.get("breakdown")- if breakdown:- yield (breakdown, breakdown_filter.get("breakdown_type", "event"))- return- for b in breakdown_filter.get("breakdowns") or []:- prop = b.get("property")- if prop:- yield (prop, b.get("type", "event"))---def _get_breakdown_properties(breakdown_filter: dict) -> list[str]:- """Extract all breakdown property names from either legacy or new format."""- return [name for name, _ in _iter_breakdowns(breakdown_filter)]---def _get_breakdown_column_indices(breakdown_filter: dict) -> dict[str, int]:- """Map breakdown property names to their 1-based index in the breakdown_value array.-- Single breakdown: {"$browser": 0} (0 means use the whole array, not an index)- Multiple breakdowns: {"$browser": 1, "$os": 2}- """- props = _get_breakdown_properties(breakdown_filter)- if len(props) <= 1:- return {props[0]: 0} if props else {}- return {prop: i + 1 for i, prop in enumerate(props)}---def _get_breakdown_infos(breakdown_filter: dict) -> list[tuple[str, str]]:- """Extract all breakdown property name and type pairs.-- Returns list of (property_name, property_type) tuples.- """- return list(_iter_breakdowns(breakdown_filter))---def _endpoint_refresh_mode_to_refresh_type(- mode: EndpointRefreshMode | None,-) -> RefreshType:- """- Map EndpointRefreshMode to RefreshType.-- - cache -> blocking- - force/direct -> force_blocking (materialization bypass handled in _should_use_materialized_table)- """- if mode is None or mode == EndpointRefreshMode.CACHE:- return RefreshType.BLOCKING- return RefreshType.FORCE_BLOCKING--[email protected](frozen=True)-class EndpointContext(ActivityContextBase):- id: Optional[int] = None- version: Optional[int] = None--[email protected](frozen=True)-class EndpointPagination:- limit: int- offset: int- ceiling: int | None-- def apply_to(self, select_query: ast.SelectQuery) -> None:- """Set LIMIT and OFFSET on an AST SelectQuery for pagination."""- if self.ceiling is not None and self.offset >= self.ceiling:- select_query.limit = ast.Constant(value=0)- select_query.offset = ast.Constant(value=0)- else:- remaining = (self.ceiling - self.offset) if self.ceiling is not None else None- effective_limit = min(self.limit, remaining) if remaining is not None else self.limit- select_query.limit = ast.Constant(value=effective_limit + 1)- if self.offset > 0:- select_query.offset = ast.Constant(value=self.offset)-- def process_results(self, result: dict) -> None:- """Trim the extra row and annotate the result dict with pagination metadata."""- rows = result.get("results", [])- has_more = len(rows) > self.limit- if has_more:- result["results"] = rows[: self.limit]- if self.ceiling is not None and self.offset + len(result["results"]) >= self.ceiling:- has_more = False- result["hasMore"] = has_more- result["limit"] = self.limit- result["offset"] = self.offset---class _PlaceholderPreservingPrinter(HogQLPrinter):- """HogQL printer that preserves {placeholder} syntax instead of raising on unresolved placeholders."""-- def visit_placeholder(self, node: ast.Placeholder) -> str:- if node.field is None:- raise QueryError("You can not use placeholders here")- return f"{{{node.field}}}"---def _cant_materialize_response(reason: str) -> Response:- return Response(- {- "can_materialize": False,- "reason": reason,- "transformed_query": None,- "execution_query": None,- "range_pairs": [],- "aggregates": [],- }- )---def _validate_bucket_overrides(bucket_overrides: dict[str, str] | None) -> None:- """Raise ValidationError if any bucket override value is not in SUPPORTED_BUCKET_FUNCTIONS."""- if not bucket_overrides:- return-- invalid = {k: v for k, v in bucket_overrides.items() if v not in SUPPORTED_BUCKET_FUNCTIONS}- if invalid:- valid_options = list(SUPPORTED_BUCKET_FUNCTIONS.keys())- raise ValidationError(f"Invalid bucket override values: {invalid}. Valid options: {valid_options}")+from products.endpoints.backend.services.crud import EndpointCrudService+from products.endpoints.backend.services.execution import EndpointExecutionService+from products.endpoints.backend.services.materialization import (+ EndpointMaterializationService,+ build_materialization_info,+)+from products.endpoints.backend.services.validation import (+ validate_bucket_overrides,+ validate_endpoint_request,+ validate_update_request,+)class MaterializationPreviewRequestSerializer(serializers.Serializer):@@ -402,18 +91,6 @@ class MaterializationPreviewRequestSerializer(serializers.Serializer):)-class _RunRejected(Exception):- """Internal control-flow signal: a run request was rejected during validation.-- Carries the 4xx Response to return to the caller. Caught in `run()`, where the rejection is- logged once — alongside DRF ValidationErrors — so every rejected run surfaces in the logs.- """-- def __init__(self, response: Response):- self.response = response- super().__init__()--@extend_schema_view(partial_update=extend_schema(request=EndpointRequestSerializer,@@ -431,7 +108,6 @@ class EndpointViewSet():authentication_classes = [ProjectSecretAPIKeyAuthentication]psak_allowed_actions = ["run"]- # NOTE: Do we need to override the scopes for the "create"scope_object = "endpoint"# Read endpoint execution logs from the `log_entries` table keyed by this source.log_source = ENDPOINTS_LOG_SOURCE@@ -482,6 +158,10 @@ class EndpointViewSet(return [permission() for permission in (IsAuthenticated, APIScopePermission, TeamMemberAccessPermission)]raise NotImplementedError()+ # ------------------------------------------------------------------+ # Access control helpers+ # ------------------------------------------------------------------+def _get_endpoint_with_object_access(self, name: str | None) -> Endpoint:"""Fetch a team-scoped endpoint by name and enforce object-level access controls.@@ -500,15 +180,17 @@ class EndpointViewSet(defaults so a restrictive project default doesn't break the public execution API. Creatorsand org admins always pass (specific_access_level_for_object returns the highest level)."""- # PSAK scopes are project-wide within their resource type and deliberately ignore- # object-level access controls — the key's team binding and `endpoint:read` scope are- # the whole authorization story (see posthog/scopes.py).+ # PSAK scopes are project-wide and deliberately bypass object-level access controls.if is_authenticated_via_project_secret_api_key(self.request):returnspecific_level = self.user_access_control.specific_access_level_for_object(endpoint)if specific_level is not None and not access_level_satisfied_for_resource("endpoint", specific_level, "viewer"):raise PermissionDenied("You do not have access to this endpoint.")+ # ------------------------------------------------------------------+ # Request parsing helpers+ # ------------------------------------------------------------------+def _parse_version_param(self, request: Request) -> int | None:"""Parse version number from request body or query params.@@ -531,57 +213,49 @@ class EndpointViewSet(return None+ @staticmethod+ def _parse_int_param(+ body_value: int | None, query_param: str | None, name: str, min_value: int | None = None+ ) -> tuple[int | None, Response | None]:+ """Parse an integer from the request body or query params. Returns (value, error_response)."""+ value = body_value+ if value is None and query_param is not None:+ try:+ value = int(query_param)+ if min_value is not None and value < min_value:+ raise ValueError()+ except (ValueError, TypeError):+ return None, Response(+ {"error": f"Invalid {name} parameter: {query_param}"},+ status=status.HTTP_400_BAD_REQUEST,+ )+ elif value is not None and min_value is not None and value < min_value:+ return None, Response(+ {"error": f"Invalid {name} parameter: {value}"},+ status=status.HTTP_400_BAD_REQUEST,+ )+ return value, None++ def _resolve_version_param(self, request: Request, endpoint: Endpoint) -> EndpointVersion | Response:+ """Resolve the ?version=N param to a version, or a 404 Response if it doesn't exist."""+ version_number = self._parse_version_param(request)+ if version_number is None:+ return endpoint.get_version()+ try:+ return endpoint.get_version(version_number)+ except EndpointVersion.DoesNotExist:+ return Response({"error": f"Version {version_number} not found"}, status=status.HTTP_404_NOT_FOUND)++ # ------------------------------------------------------------------+ # Serialization+ # ------------------------------------------------------------------+def _get_tag_names(self, endpoint: Endpoint) -> list[str]:"""Read tag names from the prefetched cache or from the DB if not prefetched."""if hasattr(endpoint, "prefetched_tags"):return sorted({ti.tag.name for ti in endpoint.prefetched_tags})return sorted(endpoint.tagged_items.values_list("tag__name", flat=True))- def _apply_tags(self, endpoint: Endpoint, tags: list[str] | None) -> None:- """Replace the endpoint's tags. No-op when tags is None (field omitted)."""- if tags is None:- return- # `prefetched_tags` is a dynamic attribute populated by the TaggedItem prefetch / set_tags_on_object;- # it's not declared on the Endpoint model.- endpoint.prefetched_tags = set_tags_on_object(tags, endpoint) # type: ignore[attr-defined]- cleanup_orphan_tags(endpoint.team_id)-- @extend_schema(exclude=True)- @action(methods=["POST"], detail=False)- def bulk_update_tags(self, request: Request, *args, **kwargs) -> Response:- # The inherited TaggedItemViewSetMixin.bulk_update_tags assumes integer PKs (its- # BulkUpdateTagsRequestSerializer validates ids as IntegerField). Endpoint uses- # UUID PKs, so the action is unusable. Return 405 until the mixin gains UUID support.- return Response(- {"detail": "Bulk tag updates are not supported for endpoints."},- status=status.HTTP_405_METHOD_NOT_ALLOWED,- )-- def _build_materialization_info(self, version: EndpointVersion, endpoint_name: str | None = None) -> dict:- """Build materialization status dict for a version."""- if version.saved_query:- result = {- "status": version.saved_query.status or "Unknown",- "can_materialize": True,- "last_materialized_at": (- version.saved_query.last_run_at.isoformat() if version.saved_query.last_run_at else None- ),- "error": (version.saved_query.latest_error or "")- if version.saved_query.status != DataWarehouseSavedQuery.Status.COMPLETED- else "",- "saved_query_id": str(version.saved_query.id),- }- else:- can_mat, reason = version.can_materialize()- result = {- "can_materialize": can_mat,- "reason": reason if not can_mat else None,- }-- if endpoint_name is not None:- result["name"] = endpoint_name- return result-def _serialize(self,obj: Endpoint | EndpointVersion,@@ -624,7 +298,7 @@ class EndpointViewSet("versions_count": endpoint.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": self._build_materialization_info(version),+ "materialization": build_materialization_info(version),"bucket_overrides": version.bucket_overrides,"columns": version.get_columns() if version else [],"tags": self._get_tag_names(endpoint),@@ -642,6 +316,10 @@ class EndpointViewSet(return result+ # ------------------------------------------------------------------+ # CRUD actions+ # ------------------------------------------------------------------+@extend_schema(responses={200: EndpointResponseSerializer(many=True)},description="List all endpoints for the team.",@@ -681,176 +359,6 @@ class EndpointViewSet(capture_exception(e, {"endpoint_name": endpoint.name, "team_id": self.team_id})raise ValidationError("Failed to retrieve endpoint.")- def _validate_data_freshness(self, data_freshness_seconds: int | None) -> None:- """Validate data_freshness_seconds is one of the allowed bucket values."""- if data_freshness_seconds is None:- return- if data_freshness_seconds not in VALID_DATA_FRESHNESS_SECONDS:- allowed = sorted(VALID_DATA_FRESHNESS_SECONDS)- raise ValidationError(- {- "data_freshness_seconds": (- f"Data freshness must be one of: {allowed} seconds "- "(15 minutes, 30 minutes, 1 hour, 6 hours, 12 hours, 24 hours, 7 days)."- )- }- )-- def _validate_hogql_query(self, query: HogQLQuery) -> None:- """Validate that a HogQL query can be parsed and the variables are valid."""- try:- ast_node = parse_select(query.query)- except ExposedHogQLError as e:- raise ValidationError({"query": f"Invalid HogQL query: {e}"}) from e- except ResolutionError as e:- capture_exception(e)- raise ValidationError({"query": "Invalid HogQL query: unable to resolve table or field references."})- except Exception as e:- capture_exception(e)- raise ValidationError({"query": "Unknown error occurred parsing the query."})-- self._validate_variable_placeholders(ast_node, query.variables or {})-- def _sync_hogql_query_variables(self, query: HogQLQuery) -> None:- """Sync query variable definitions with the placeholders used in the query string."""- try:- ast_node = parse_select(query.query)- except Exception:- # Validation runs separately and will surface parse errors.- return-- finder = VariablePlaceholderFinder()- finder.visit(ast_node)-- placeholder_names = {str(p.chain[1]) for p in finder.variable_placeholders if p.chain and len(p.chain) > 1}- if not placeholder_names:- query.variables = None- return-- existing_variables = query.variables or {}- existing_variable_ids: list[str] = []- for variable in existing_variables.values():- if not variable.variableId:- continue- try:- uuid.UUID(variable.variableId)- except ValueError:- continue- existing_variable_ids.append(variable.variableId)-- team_variables = InsightVariable.objects.filter(team=self.team, id__in=existing_variable_ids)- team_variables_by_id = {str(variable.id): variable for variable in team_variables}-- synced_variables: dict[str, HogQLVariable] = {}- existing_code_names: set[str] = set()-- for variable_id, variable in existing_variables.items():- if variable.code_name and variable.code_name in placeholder_names:- if variable.value is None and variable.isNull is not True:- team_variable = team_variables_by_id.get(variable.variableId)- if team_variable:- variable.value = team_variable.default_value- variable.isNull = team_variable.default_value is None- synced_variables[variable_id] = variable- existing_code_names.add(variable.code_name)-- missing_code_names = placeholder_names - existing_code_names- if missing_code_names:- missing_variables = InsightVariable.objects.filter(team=self.team, code_name__in=missing_code_names)-- for variable in missing_variables:- if not variable.code_name:- continue- synced_variables[str(variable.id)] = HogQLVariable(- variableId=str(variable.id),- code_name=variable.code_name,- value=variable.default_value,- isNull=variable.default_value is None,- )-- query.variables = synced_variables or None-- def _validate_variable_placeholders(self, node: ast.AST, variables: Optional[dict[str, HogQLVariable]]) -> None:- """Validate that every {variables.X} placeholder in the query has a matching variable definition."""- finder = VariablePlaceholderFinder()- finder.visit(node)-- if not finder.variable_placeholders:- return-- placeholder_names = {str(p.chain[1]) for p in finder.variable_placeholders if p.chain and len(p.chain) > 1}-- defined_code_names: set[str] = set()- if variables:- defined_code_names = {v.code_name for v in variables.values() if v.code_name}- variable_ids = set(variables.keys())-- undefined: list[str] = sorted(placeholder_names - defined_code_names)- if undefined:- raise ValidationError(- {- "query": f"Query references undefined variable(s): {', '.join(undefined)}. "- "See https://posthog.com/docs/endpoints/variables for detail."- }- )-- if variable_ids:- valid_uuids: set[str] = set()- invalid_uuids: set[str] = set()- invalid_ids: set[str] = set()- for vid in variable_ids:- try:- uuid.UUID(vid)- valid_uuids.add(vid)- except ValueError:- invalid_uuids.add(vid)-- if invalid_uuids:- raise ValidationError(- {"query": f"Variable ID(s) not valid UUIDs: {', '.join(sorted(invalid_uuids))}. "}- )-- if valid_uuids:- existing_ids = {- str(id)- for id in InsightVariable.objects.filter(team=self.team, id__in=valid_uuids).values_list(- "id", flat=True- )- }- invalid_ids = valid_uuids - existing_ids-- if invalid_ids:- raise ValidationError(- {- "query": f"Variable ID(s) not found: {', '.join(sorted(invalid_ids))}. "- "Make sure the variables exist in https://app.posthog.com/data-management/variables."- }- )-- def validate_request(self, data: EndpointRequest, strict: bool = True) -> None:- query = data.query- if not query and strict:- raise ValidationError({"query": "This field is required."})-- name = data.name- if not name:- if name is not None or strict:- raise ValidationError({"name": "This field is required."})- return- if not isinstance(name, str) or not re.fullmatch(ENDPOINT_NAME_REGEX, name):- raise ValidationError(- {- "name": f"Invalid name '{name}'. Must start with a letter, contain only alphanumeric characters, "- "hyphens, or underscores, and be between 1 and 128 characters long."- }- )-- if query and isinstance(query, HogQLQuery) and query.query:- self._sync_hogql_query_variables(query)- self._validate_hogql_query(query)-- self._validate_data_freshness(data.data_freshness_seconds)-@extend_schema(request=EndpointRequestSerializer,responses={201: EndpointResponseSerializer},@@ -860,99 +368,14 @@ class EndpointViewSet("""Create a new endpoint."""upgraded_query = upgrade(request.data)data = self.get_model(upgraded_query, EndpointRequest)- self.validate_request(data, strict=True)-- if Endpoint.objects.filter(team=self.team, name=data.name, deleted=False).exists():- raise ValidationError({"name": "An endpoint with this name already exists for this team."})+ validate_endpoint_request(data, self.team, strict=True)- try:- query_dict = cast(Union[HogQLQuery, InsightQueryNode], data.query).model_dump()- endpoint = Endpoint.objects.create(- team=self.team,- created_by=cast(User, request.user),- name=cast(str, data.name), # verified in validate_request- is_active=data.is_active if data.is_active is not None else True,- current_version=1,- derived_from_insight=data.derived_from_insight,- )-- try:- columns: list[dict] | None = EndpointVersion.extract_columns(query_dict, team_id=self.team.pk)- except Exception:- columns = None- EndpointVersion.objects.create(- endpoint=endpoint,- team=self.team,- version=1,- query=query_dict,- description=data.description or "",- data_freshness_seconds=(- data.data_freshness_seconds- if data.data_freshness_seconds is not None- else DEFAULT_DATA_FRESHNESS_SECONDS- ),- created_by=cast(User, request.user),- columns=columns,- )-- self._apply_tags(endpoint, data.tags)-- log_activity(- organization_id=self.organization.id,- team_id=self.team.id,- user=cast(User, request.user),- was_impersonated=is_impersonated_session(request),- item_id=str(endpoint.id),- scope="Endpoint",- activity="created",- detail=Detail(name=endpoint.name),- )+ endpoint = EndpointCrudService(self.team, request).create(data)- report_user_action(- user=cast(User, request.user),- event="endpoint created",- properties={- "endpoint_id": str(endpoint.id),- "endpoint_name": endpoint.name,- "query_kind": query_dict.get("kind") if isinstance(query_dict, dict) else None,- },- team=self.team,- request=request,- )-- return Response(- self._serialize(endpoint, request),- status=status.HTTP_201_CREATED,- )-- except Exception as e:- capture_exception(- e,- {- "product": Product.ENDPOINTS,- "team_id": self.team_id,- "endpoint_name": data.name,- },- )- raise ValidationError("Failed to create endpoint.")-- def validate_update_request(- self,- data: EndpointRequest,- endpoint: Endpoint | None = None,- strict: bool = True,- ) -> None:- self._validate_data_freshness(data.data_freshness_seconds)-- # Determine final states after this request (for validation)- will_be_active = data.is_active if data.is_active is not None else (endpoint.is_active if endpoint else True)-- if not will_be_active and data.is_materialized is True:- raise ValidationError({"is_materialized": "Cannot enable materialization on inactive endpoint."})-- if data.query and isinstance(data.query, HogQLQuery) and data.query.query:- self._sync_hogql_query_variables(data.query)- self._validate_hogql_query(data.query)+ return Response(+ self._serialize(endpoint, request),+ status=status.HTTP_201_CREATED,+ )@extend_schema(request=EndpointRequestSerializer,@@ -969,7 +392,6 @@ class EndpointViewSet(# Enforce object-level RBAC: a user with global editor scope can still be restricted# from a specific endpoint via per-object access controls.endpoint = self._get_endpoint_with_object_access(name)- endpoint_before_update = Endpoint.objects.get(pk=endpoint.id)upgraded_query = upgrade(request.data)data = self.get_model(upgraded_query, EndpointRequest)@@ -979,1371 +401,49 @@ class EndpointViewSet(self.destroy(request, name=name)return Response({"success": True}, status=status.HTTP_200_OK)- self.validate_update_request(data, endpoint=endpoint, strict=False)+ validate_update_request(data, self.team, endpoint=endpoint)version_number = self._parse_version_param(request)- target_version_override = None- if version_number is not None:- try:- target_version_override = endpoint.get_version(version_number)- except EndpointVersion.DoesNotExist:- raise ValidationError({"version": f"Version {version_number} not found for this endpoint."})- if data.query is not None:- raise ValidationError(- {- "query": "Cannot change query when targeting a specific version. Query changes create a new version."- }- )-- try:- current_version = endpoint.get_version()- target_version = target_version_override or current_version-- version_before_update = EndpointVersion.objects.get(pk=target_version.pk) if target_version else None- version_was_created = False- query_changed = False- new_query_dict = None- if data.query is not None:- new_query_dict = data.query.model_dump()- query_changed = endpoint.has_query_changed(new_query_dict)-- # Deactivates the whole endpoint - we deactivate a version later if requested- if data.is_active is not None and target_version_override is None:- endpoint.is_active = data.is_active- endpoint.save()-- final_is_active = data.is_active if data.is_active is not None else endpoint.is_active- was_materialized = current_version.saved_query_id is not None-- # Step 1: Handle deactivation (disables materialization, prevents any materialization operations)- if not final_is_active and was_materialized:- self._disable_materialization(endpoint, request, current_version)-- # Step 2: Handle query changes and versioning (independent of active/materialization state)- old_bucket_overrides: dict[str, str] | None = None- if query_changed and new_query_dict is not None:- if was_materialized:- old_bucket_overrides = current_version.bucket_overrides-- new_version = endpoint.create_new_version(query=new_query_dict, user=cast(User, request.user))- version_was_created = True- current_version = new_version- target_version = new_version-- # Step 3: Update version-level fields on target version- if target_version:- update_fields = []- if data.description is not None:- target_version.description = data.description- update_fields.append("description")- if "data_freshness_seconds" in request.data:- target_version.data_freshness_seconds = (- data.data_freshness_seconds- if data.data_freshness_seconds is not None- else DEFAULT_DATA_FRESHNESS_SECONDS- )- update_fields.append("data_freshness_seconds")- # When targeting a specific version, is_active updates the version- if data.is_active is not None and target_version_override is not None:- target_version.is_active = data.is_active- update_fields.append("is_active")- if update_fields:- update_fields.append("updated_at")- target_version.save(update_fields=update_fields)-- # Step 4: Handle materialization state (only if endpoint should be active)- stored_bucket_overrides = target_version.bucket_overrides if target_version else None- materialization_error: str | None = None- if final_is_active and target_version:- # When targeting a specific version, check that version's materialization state- # Otherwise use was_materialized (state before this update) to support materialization transfer- if target_version_override is not None:- check_was_materialized = target_version.saved_query_id is not None- else:- check_was_materialized = was_materialized-- should_enable = data.is_materialized is True or (- data.is_materialized is None and check_was_materialized- )- should_disable = data.is_materialized is False-- if should_enable:- bucket_overrides = request.data.get("bucket_overrides")- if bucket_overrides is None and version_was_created:- bucket_overrides = old_bucket_overrides- _validate_bucket_overrides(bucket_overrides)- try:- self._enable_materialization(- endpoint,- target_version.data_freshness_seconds,- request,- target_version,- bucket_overrides=bucket_overrides,- )- # Trigger immediate refresh when bucket_overrides changed- if (- bucket_overrides is not None- and bucket_overrides != stored_bucket_overrides- and target_version.saved_query is not None- ):- try:- trigger_saved_query_schedule(target_version.saved_query)- except Exception:- logger.warning(- "failed_to_trigger_materialization_refresh",- team_id=self.team_id,- saved_query_id=str(target_version.saved_query_id),- )- except Exception as e:- if version_was_created:- # The new version was already committed — don't fail the whole update.- # Materialization can be retried via a subsequent update.- materialization_error = str(e)- logger.exception(- "Materialization failed after version creation",- endpoint_name=endpoint.name,- version=target_version.version,- )- capture_exception(- e,- {- "product": Product.ENDPOINTS,- "team_id": self.team_id,- "endpoint_name": endpoint.name,- "version": target_version.version,- },- )- else:- raise- elif should_disable:- self._disable_materialization(endpoint, request, target_version)-- self._apply_tags(endpoint, data.tags)-- endpoint_changes = changes_between("Endpoint", previous=endpoint_before_update, current=endpoint)- if endpoint_changes:- # endpoint-level activity- log_activity(- organization_id=self.organization.id,- team_id=self.team.id,- user=cast(User, request.user),- was_impersonated=is_impersonated_session(request),- item_id=str(endpoint.id),- scope="Endpoint",- activity="updated",- detail=Detail(name=endpoint.name, changes=endpoint_changes),- )+ outcome = EndpointCrudService(self.team, request).update(endpoint, data, request.data, version_number)- # TODO: Should these go to finally: ?- # version-level activity- if version_was_created:- query_change = Change(- type="EndpointVersion",- action="changed",- field="query",- before=version_before_update.query if version_before_update else None,- after=target_version.query,- )- log_activity(- organization_id=self.organization.id,- team_id=self.team.id,- user=cast(User, request.user),- was_impersonated=is_impersonated_session(request),- item_id=str(endpoint.id),- scope="Endpoint",- activity="version_created",- detail=Detail(- name=endpoint.name,- changes=[query_change],- context=EndpointContext(version=target_version.version),- ),- )- elif target_version and version_before_update:- version_changes = changes_between(- "EndpointVersion", previous=version_before_update, current=target_version- )-- if version_changes:- log_activity(- organization_id=self.organization.id,- team_id=self.team.id,- user=cast(User, request.user),- was_impersonated=is_impersonated_session(request),- item_id=str(endpoint.id),- scope="EndpointVersion",- activity="version_updated",- detail=Detail(- name=endpoint.name,- changes=version_changes,- context=EndpointContext(version=target_version.version),- ),- )-- # When targeting a specific version, return version data; otherwise return endpoint data- if target_version_override is not None:- result = self._serialize(target_version)- else:- result = self._serialize(endpoint, request)-- if materialization_error:- result["materialization_error"] = materialization_error-- return Response(result)-- except ValidationError:- raise- except Exception as e:- current_version = endpoint.get_version()- capture_exception(- e,- {- "product": Product.ENDPOINTS,- "team_id": self.team_id,- "endpoint_id": endpoint.id,- "saved_query_id": current_version.saved_query.id if current_version.saved_query else None,- },- )- raise ValidationError("Failed to update endpoint.")-- def _enable_materialization(- self,- endpoint: Endpoint,- data_freshness_seconds: int,- request: Request,- version: EndpointVersion | None = None,- bucket_overrides: dict[str, str] | None = None,- ) -> None:- """Enable materialization for an endpoint version.-- If version is not specified, uses the current version.- Each version gets its own saved_query with naming: {endpoint_name}_v{version}- """- try:- self._enable_materialization_inner(endpoint, data_freshness_seconds, request, version, bucket_overrides)- ENDPOINT_MATERIALIZATION_EVENT_TOTAL.labels(action="enable", status="success").inc()- target_version = version or endpoint.get_version()- if target_version and target_version.saved_query:- log_activity(- organization_id=self.organization.id,- team_id=self.team.id,- user=cast(User, request.user),- was_impersonated=is_impersonated_session(request),- item_id=str(target_version.saved_query.id),- scope="DataWarehouseSavedQuery",- activity="materialization_enabled",- detail=Detail(- name=target_version.saved_query.name,- context=EndpointContext(version=target_version.version),- ),- )- except ValidationError:- ENDPOINT_MATERIALIZATION_EVENT_TOTAL.labels(action="enable", status="validation_error").inc()- raise- except Exception:- ENDPOINT_MATERIALIZATION_EVENT_TOTAL.labels(action="enable", status="error").inc()- raise ValidationError("Failed to enable materialization.")-- def _enable_materialization_inner(- self,- endpoint: Endpoint,- data_freshness_seconds: int,- request: Request,- version: EndpointVersion | None = None,- bucket_overrides: dict[str, str] | None = None,- ) -> None:- version = version or endpoint.get_version()-- can_mat, reason = version.can_materialize()- if not can_mat:- raise ValidationError(f"Cannot materialize endpoint. Reason: {reason}")-- # Per-version naming allows independent materialization for each version- saved_query_name = f"{endpoint.name}_v{version.version}"- saved_query = DataWarehouseSavedQuery.objects.filter(- name=saved_query_name, team=self.team, deleted=False- ).first()- if saved_query is None:- saved_query = DataWarehouseSavedQuery(- name=saved_query_name,- team=self.team,- origin=DataWarehouseSavedQuery.Origin.ENDPOINT,- )-- hogql_query = build_endpoint_hogql(version.query, self.team, bucket_overrides=bucket_overrides)-- saved_query.query = hogql_query- saved_query.external_tables = saved_query.s3_tables- saved_query.is_materialized = True- saved_query.sync_frequency_interval = sync_frequency_to_sync_frequency_interval(- DATA_FRESHNESS_BUCKETS[data_freshness_seconds]- )-- saved_query.save()-- version.saved_query = saved_query- version.bucket_overrides = bucket_overrides- version.save(update_fields=["saved_query", "bucket_overrides", "updated_at"])-- saved_query.schedule_materialization()-- try:- sync_saved_query_to_dag(saved_query)- except Exception as e:- logger.exception(- "Failed to sync endpoint node to DAG",- endpoint_name=endpoint.name,- saved_query_id=version.saved_query.id if version and version.saved_query else None,- )- capture_exception(- e,- {- "product": Product.ENDPOINTS,- "team_id": self.team_id,- "endpoint_name": endpoint.name,- "saved_query_id": version.saved_query.id if version and version.saved_query else None,- },- )+ # When targeting a specific version, return version data; otherwise return endpoint data+ if outcome.version_targeted and outcome.target_version is not None:+ result = self._serialize(outcome.target_version)+ else:+ result = self._serialize(outcome.endpoint, request)- def _disable_materialization(- self, endpoint: Endpoint, request: Request, version: EndpointVersion | None = None- ) -> None:- """Disable materialization for an endpoint version.+ if outcome.materialization_error:+ result["materialization_error"] = outcome.materialization_error- If version is not specified, uses the current version.- """- version = version or endpoint.get_version()- if version:- if version.saved_query:- saved_query_id = str(version.saved_query.id)- saved_query_name = version.saved_query.name- try:- delete_node_from_dag(version.saved_query)- except Exception as e:- logger.exception(- "Failed to remove endpoint node from DAG",- endpoint_name=endpoint.name,- saved_query_id=version.saved_query.id if version and version.saved_query else None,- )- capture_exception(- e,- {- "product": Product.ENDPOINTS,- "team_id": self.team_id,- "endpoint_name": endpoint.name,- "saved_query_id": version.saved_query.id if version and version.saved_query else None,- },- )- try:- version.disable_materialization()- except Exception:- ENDPOINT_MATERIALIZATION_EVENT_TOTAL.labels(action="disable", status="error").inc()- raise- ENDPOINT_MATERIALIZATION_EVENT_TOTAL.labels(action="disable", status="success").inc()- log_activity(- organization_id=self.organization.id,- team_id=self.team.id,- user=cast(User, request.user),- was_impersonated=is_impersonated_session(request),- item_id=saved_query_id,- scope="DataWarehouseSavedQuery",- activity="materialization_disabled",- detail=Detail(- name=saved_query_name,- context=EndpointContext(version=version.version),- ),- )- clear_endpoint_materialization_cache(self.team_id, endpoint.name)+ return Response(result)def destroy(self, request: Request, name=None, *args, **kwargs) -> Response:"""Delete an endpoint and clean up materialized query."""endpoint = self._get_endpoint_with_object_access(name)- endpoint_id = str(endpoint.id)- endpoint_name = endpoint.name-- for version in endpoint.versions.filter(saved_query__isnull=False):- try:- if version.saved_query:- delete_node_from_dag(version.saved_query)- except Exception as e:- logger.exception(- "Failed to remove endpoint node from DAG on destroy",- endpoint_name=endpoint.name,- saved_query_id=version.saved_query.id if version.saved_query else None,- )- capture_exception(- e,- {- "product": Product.ENDPOINTS,- "team_id": self.team_id,- "endpoint_name": endpoint.name,- "saved_query_id": version.saved_query.id if version and version.saved_query else None,- },- )-- endpoint.soft_delete()- clear_endpoint_materialization_cache(self.team_id, endpoint.name)- log_activity(- organization_id=self.organization.id,- team_id=self.team.id,- user=cast(User, request.user),- was_impersonated=is_impersonated_session(request),- item_id=endpoint_id,- scope="Endpoint",- activity="deleted",- detail=Detail(name=endpoint_name),- )+ EndpointCrudService(self.team, request).destroy(endpoint)return Response(status=status.HTTP_204_NO_CONTENT)- def _should_use_materialized_table(- self, endpoint: Endpoint, data: EndpointRunRequest, version: EndpointVersion | None = None- ) -> bool:- """- Decide whether to use materialized table or inline execution.-- Returns False if:- - Not materialized- - Materialization incomplete/failed- - Materialized data is stale (older than sync frequency)- - User overrides present (variables, query)- - 'direct' mode requested (explicitly bypass materialization)- """- version = version or endpoint.get_version()- if not version.is_materialized or not version.saved_query:- return False-- saved_query = version.saved_query- if saved_query.status not in ["Completed"]:- return False-- if not saved_query.table:- return False-- # Check if materialized data is stale- if saved_query.last_run_at and saved_query.sync_frequency_interval:- next_refresh_due = saved_query.last_run_at + saved_query.sync_frequency_interval- if timezone.now() >= next_refresh_due:- return False-- # 'direct' mode explicitly bypasses materialization to run the original query- if data.refresh == EndpointRefreshMode.DIRECT:- return False-- # Check if variables are valid for materialized execution- if data.variables:- query = version.query- query_kind = query.get("kind")-- if query_kind == "HogQLQuery":- # HogQL: check if request variables are a subset of materialized variables- materialized_vars = self._get_materialized_variables(version)- if not materialized_vars:- return False-- materialized_codes = {v.code_name for v in materialized_vars}- request_var_codes = set(data.variables.keys())- if not request_var_codes.issubset(materialized_codes):- return False- else:- # Materialized insight: only breakdown properties allowed- breakdown_filter = query.get("breakdownFilter") or {}- allowed_props = set(_get_breakdown_properties(breakdown_filter))- if not allowed_props:- return False-- request_var_codes = set(data.variables.keys())- if not request_var_codes.issubset(allowed_props):- return False-- return True-- def _get_materialized_variables(self, version: EndpointVersion) -> builtins.list:- """Return the materializable variable infos for an endpoint query."""- query = version.query- if not query or not query.get("variables"):- return []-- try:- can_materialize, _, variable_infos = analyze_variables_for_materialization(- query, bucket_overrides=version.bucket_overrides- )- return variable_infos if can_materialize else []- except Exception:- logger.debug("Failed to analyze variables for materialization", exc_info=True)- return []-- def _parse_original_hogql_query(self, query: dict) -> tuple[builtins.list | None, int | None, bool]:- """Parse the original HogQL query and extract SELECT columns, LIMIT, and GROUP BY presence.-- Returns (materialized_columns, limit, has_group_by) where columns/limit may be None.- materialized_columns is a list of MaterializedColumn with re-aggregation metadata.- """- query_str = query.get("query")- if not query_str:- return None, None, False-- try:- parsed = parse_select(query_str)- if isinstance(parsed, ast.SelectQuery):- columns = (- transform_select_for_materialized_table(list(parsed.select), self.team) if parsed.select else None- )- limit = parsed.limit.value if isinstance(parsed.limit, ast.Constant) else None- has_group_by = bool(parsed.group_by)- return columns, limit, has_group_by- except Exception:- logger.debug("Failed to parse original HogQL query", exc_info=True)-- return None, None, False-- # Query types that support user-configurable breakdown filtering- BREAKDOWN_SUPPORTED_QUERY_TYPES = {"TrendsQuery", "RetentionQuery"}-- def _get_allowed_variables(self, query: dict, is_materialized: bool) -> set[str]:- """Get the set of allowed variable names for this endpoint."""- query_kind = query.get("kind")-- if query_kind == "HogQLQuery":- # HogQL: allowed variables are code_names from query["variables"]- variables = query.get("variables", {})- return {v.get("code_name") for v in variables.values() if v.get("code_name")} if variables else set()-- # Insight queries- allowed: set[str] = set()-- # Only allow breakdown properties for query types that support it- if query_kind in self.BREAKDOWN_SUPPORTED_QUERY_TYPES:- breakdown_filter = query.get("breakdownFilter") or {}- allowed.update(_get_breakdown_properties(breakdown_filter))-- if not is_materialized:- # Non-materialized also allows date_from/date_to via filters_override- allowed.update({"date_from", "date_to"})-- return allowed-- def _get_required_variables_for_materialized(self, query: dict, version: EndpointVersion) -> set[str]:- """Get the required variable names for a materialized endpoint.-- SECURITY: This prevents data leakage by ensuring that materialized endpoints- with variables cannot be called without providing all variable values.- """- query_kind = query.get("kind")-- if query_kind == "HogQLQuery":- materialized_vars = self._get_materialized_variables(version)- return {v.code_name for v in materialized_vars}-- # Insight queries: all breakdown properties are required- if query_kind in self.BREAKDOWN_SUPPORTED_QUERY_TYPES:- breakdown_filter = query.get("breakdownFilter") or {}- return set(_get_breakdown_properties(breakdown_filter))-- return set()-- def _apply_where_filter(- self,- select_query: ast.SelectQuery,- column: str,- value: str,- op: ast.CompareOperationOp = ast.CompareOperationOp.Eq,- value_wrapper_fns: builtins.list[str] | None = None,- bucket_fn: str | None = None,- ) -> None:- """Add a comparison filter to WHERE clause.-- When bucket_fn is set (range variables), wrap the filter value with the- bucket function so the comparison matches the bucketed column values.- """- right_expr: ast.Expr = ast.Constant(value=value)- for fn in reversed(value_wrapper_fns or []):- right_expr = ast.Call(name=fn, args=[right_expr])- if bucket_fn:- right_expr = ast.Call(name=bucket_fn, args=[ast.Call(name="toDateTime", args=[right_expr])])- condition = ast.CompareOperation(- left=ast.Field(chain=[column]),- op=op,- right=right_expr,- )- _add_where_condition(select_query, condition)-- def _build_breakdown_filter_condition(- self, query_kind: str | None, value: str, array_index: int = 0- ) -> ast.Expr | None:- """Build the appropriate WHERE condition for breakdown filtering based on query type.-- Different insight types store breakdowns in different columns:- - TrendsQuery, RetentionQuery: `breakdown_value` Array column- - LifecycleQuery: No breakdown support-- array_index controls how to access the breakdown column:- - 0: single breakdown — use has() on the full array- - 1+: multiple breakdowns — use equality on breakdown_value[N]- """- if query_kind not in ("TrendsQuery", "RetentionQuery"):- logger.warning(- "Query type does not support breakdown filtering",- query_kind=query_kind,- )- return None-- if array_index > 0:- return ast.CompareOperation(- left=ast.ArrayAccess(- array=ast.Field(chain=["breakdown_value"]),- property=ast.Constant(value=array_index),- ),- op=ast.CompareOperationOp.Eq,- right=ast.Constant(value=value),- )-- return ast.Call(- name="has",- args=[ast.Field(chain=["breakdown_value"]), ast.Constant(value=value)],- )-- def _execute_query_and_respond(- self,- query_request_data: dict,- client_query_id: str | None,- request: Request,- variables_override: builtins.list[HogQLVariable] | None = None,- cache_age_seconds: int | None = None,- extra_result_fields: dict | None = None,- debug: bool = False,- headers: dict[str, str] | None = None,- pagination: EndpointPagination | None = None,- ) -> Response:- """Shared query execution logic."""- merged_data = self.get_model(query_request_data, QueryRequest)-- logger.debug(merged_data)- query, client_query_id, execution_mode = _process_query_request(- merged_data, self.team, client_query_id, request.user- )- self._tag_client_query_id(client_query_id)- endpoint_feature = (- Feature.ENDPOINT_EXECUTION if get_query_tag_value("access_method") else Feature.ENDPOINT_PLAYGROUND- )- tag_queries(product=Product.ENDPOINTS, feature=endpoint_feature)-- if execution_mode not in BLOCKING_EXECUTION_MODES:- raise ValidationError({"refresh": f"Only sync modes are supported, got: {execution_mode}"})-- result = process_query_model(- self.team,- query,- variables_override=variables_override,- execution_mode=execution_mode,- query_id=client_query_id,- user=cast(User, request.user),- is_query_service=is_api_key_access_method(get_query_tag_value("access_method")),- cache_age_seconds=cache_age_seconds,- analytics_props=get_request_analytics_properties(request),- )-- if isinstance(result, BaseModel):- result = result.model_dump(by_alias=True)-- if isinstance(result, dict) and extra_result_fields:- result.update(extra_result_fields)-- if not debug:- debug_fields_to_remove = [- "calculation_trigger",- "cache_key",- "explain",- "modifiers",- "resolved_date_range",- "timings",- "hogql",- ]-- for field in debug_fields_to_remove:- result.pop(field, None)-- if pagination and "results" in result:- pagination.process_results(result)- elif "results" in result:- result["hasMore"] = False-- _clean_breakdown_sentinels(result)-- if "results" in result:- results_value = result.pop("results")- result = {"results": results_value, **result}-- response_status = (- status.HTTP_202_ACCEPTED- if result.get("query_status") and result["query_status"].get("complete") is False- else status.HTTP_200_OK- )- return Response(result, status=response_status, headers=headers)-- def _is_cache_stale(self, result: Response, saved_query) -> bool:- """Check if cached result is older than the materialization."""- if not isinstance(result.data, dict) or not result.data.get("is_cached"):- return False-- last_refresh = result.data.get("last_refresh")- if not last_refresh or not saved_query.last_run_at:- return False-- if isinstance(last_refresh, str):- last_refresh = isoparse(last_refresh)-- return last_refresh < saved_query.last_run_at-- def _build_materialized_select_query(- self,- table_name: str,- version: EndpointVersion,- variable_infos: builtins.list | None = None,- ) -> tuple[ast.SelectQuery, int | None]:- """Build the base SELECT query against a materialized table.-- Wraps aggregate columns with their reaggregate_fn (e.g. sum("count()"))- when needed to preserve SQL semantics. This happens in two cases:-- 1. Range variables (bucket_fn != None): multiple materialized rows must- be collapsed back into one aggregate per group.- 2. No GROUP BY + all-aggregate SELECT: without wrapping, an empty WHERE- match returns 0 rows instead of the expected 1-row identity result- (count→0, sum→0, min/max→type default). Wrapping restores the implicit- single-group aggregate that SQL guarantees.-- Non-aggregate columns (GROUP BY dimensions) are passed through as-is and- added to the GROUP BY clause.-- Returns (select_query, original_limit) — caller is responsible for pagination.- Used by both execution and preview paths.- """- query = version.query- query_kind = query.get("kind")-- select_columns: list[ast.Expr] = [ast.Field(chain=["*"])]- group_by_columns: list[ast.Expr] = []- original_limit: int | None = None-- if query_kind == "HogQLQuery":- original_select, original_limit, has_group_by = self._parse_original_hogql_query(query)- mat_vars = variable_infos if variable_infos is not None else self._get_materialized_variables(version)- if mat_vars and original_select:- has_range_vars = any(v.bucket_fn is not None for v in mat_vars)- all_aggregates = all(col.is_aggregate and col.reaggregate_fn for col in original_select)- needs_reaggregation = has_range_vars or (not has_group_by and all_aggregates)-- if needs_reaggregation:- reagg_select: list[ast.Expr] = []- for col in original_select:- if col.is_aggregate and col.reaggregate_fn:- reagg_select.append(ast.Call(name=col.reaggregate_fn, args=[col.expr]))- else:- reagg_select.append(col.expr)- if not col.is_aggregate:- group_by_columns.append(col.expr)- select_columns = reagg_select- else:- select_columns = [col.expr for col in original_select]-- select_query = ast.SelectQuery(- select=select_columns,- select_from=ast.JoinExpr(table=ast.Field(chain=[table_name])),- )-- if group_by_columns:- select_query.group_by = [CloningVisitor().visit(c) for c in group_by_columns]-- if original_limit is not None:- select_query.limit = ast.Constant(value=original_limit)-- return select_query, original_limit-- def _execute_materialized_endpoint(- self,- endpoint: Endpoint,- data: EndpointRunRequest,- request: Request,- version: EndpointVersion | None = None,- debug: bool = False,- limit: int | None = None,- offset: int | None = None,- ) -> Response:- """Execute against a materialized table in S3."""- materialized_hogql_query = None- query_kind = None- try:- version = version or endpoint.get_version()- if not version.saved_query:- raise ValidationError("No materialized query found for this endpoint")- saved_query = version.saved_query-- query = version.query- query_kind = query.get("kind")-- select_query, original_limit = self._build_materialized_select_query(- table_name=saved_query.name,- version=version,- )-- pagination: EndpointPagination | None = None-- # Only paginate flat-row HogQL results. Insight types get transformed- # into nested structures where flat-row LIMIT/OFFSET is meaningless.- if limit is not None and query_kind == "HogQLQuery":- pagination = EndpointPagination(limit=limit, offset=offset or 0, ceiling=original_limit)- pagination.apply_to(select_query)-- deprecation_headers: dict[str, str] | None = None-- # For insight endpoints: filters_override takes precedence over variables (backwards compat)- if query_kind != "HogQLQuery" and data.filters_override is not None:- deprecation_headers = {- "X-PostHog-Warn": "filters_override is deprecated. Use variables instead: https://posthog.com/docs/api/endpoints"- }- # Extract breakdown filter from properties- if data.filters_override.properties:- for prop in data.filters_override.properties:- if hasattr(prop, "key") and hasattr(prop, "value") and prop.value is not None:- # Convert value to string for breakdown filter- value = prop.value[0] if isinstance(prop.value, list) else prop.value- condition = self._build_breakdown_filter_condition(query_kind, str(value))- if condition:- _add_where_condition(select_query, condition)- # filters_override is deprecated — only the first property is used- break- elif data.variables:- if query_kind == "HogQLQuery":- # HogQL: filter by all materialized variable columns- materialized_vars = self._get_materialized_variables(version)- for mat_var in materialized_vars:- var_value = data.variables.get(mat_var.code_name)- if var_value is not None:- self._apply_where_filter(- select_query,- mat_var.code_name,- var_value,- op=mat_var.operator,- value_wrapper_fns=mat_var.value_wrapper_fns,- bucket_fn=mat_var.bucket_fn,- )- else:- # Insight: filter by breakdown property names- breakdown_filter = query.get("breakdownFilter") or {}- index_mapping = _get_breakdown_column_indices(breakdown_filter)-- for breakdown_prop, array_index in index_mapping.items():- if breakdown_prop in data.variables:- condition = self._build_breakdown_filter_condition(- query_kind, data.variables[breakdown_prop], array_index=array_index- )- if condition:- _add_where_condition(select_query, condition)-- materialized_hogql_query = HogQLQuery(- query=select_query.to_hogql(),- modifiers=HogQLQueryModifiers(useMaterializedViews=True),- )-- refresh_type = _endpoint_refresh_mode_to_refresh_type(data.refresh)-- query_request_data = {- "client_query_id": data.client_query_id,- "name": f"{endpoint.name}_materialized",- "refresh": refresh_type,- "query": materialized_hogql_query.model_dump(),- }-- extra_fields = {- "endpoint_materialized": True,- "endpoint_materialized_at": saved_query.last_run_at.isoformat() if saved_query.last_run_at else None,- }- tag_queries(- workload=Workload.ENDPOINTS,- warehouse_query=True,- endpoint_version=version.version if version else None,- )-- # Compute dynamic cache TTL: time remaining until data_freshness window expires- cache_ttl = None- if saved_query.last_run_at and version.data_freshness_seconds:- remaining = (- saved_query.last_run_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_id,- data_freshness_seconds=version.data_freshness_seconds,- last_run_at=saved_query.last_run_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,- request,- cache_age_seconds=cache_ttl,- extra_result_fields=extra_fields,- debug=debug,- headers=deprecation_headers,- pagination=pagination,- )-- if self._is_cache_stale(result, saved_query):- query_request_data["refresh"] = RefreshType.FORCE_BLOCKING- result = self._execute_query_and_respond(- query_request_data,- data.client_query_id,- request,- extra_result_fields=extra_fields,- debug=debug,- headers=deprecation_headers,- pagination=pagination,- )-- INSIGHT_TRANSFORM_TYPES = {"TrendsQuery", "LifecycleQuery", "RetentionQuery"}- if query_kind in INSIGHT_TRANSFORM_TYPES:- try:- transform_materialized_insight_response(- result.data,- query,- self.team,- now=saved_query.last_run_at,- )- except MaterializedSeriesMismatchError:- # Series drift: query was likely edited after materialization. Trigger a refresh- # so the next request succeeds, but fail this one loudly rather than- # returning wrong-labeled data.- logger.warning(- "Materialized endpoint series mismatch, triggering re-materialization",- endpoint_name=endpoint.name,- saved_query_id=saved_query.id,- )- trigger_saved_query_schedule(saved_query)- raise-- # Freshness relative to the configured target: >1.0 means behind SLA.- # Absolute age is meaningless across endpoints with different frequencies.- if saved_query.last_run_at and version and version.data_freshness_seconds:- age_seconds = max((timezone.now() - saved_query.last_run_at).total_seconds(), 0.0)- ENDPOINT_MATERIALIZED_FRESHNESS_RATIO.observe(age_seconds / version.data_freshness_seconds)-- return result- except Exception as e:- logger.exception(- "Materialized endpoint execution failed",- endpoint_name=endpoint.name,- saved_query_id=saved_query.id if saved_query else None,- saved_query_status=saved_query.status if saved_query else None,- )- capture_exception(- e,- {- "product": Product.ENDPOINTS,- "team_id": self.team_id,- "endpoint_name": endpoint.name,- "materialized": True,- "saved_query_id": saved_query.id if saved_query else None,- },- )- _emit_endpoint_failure_signal(- self.team,- endpoint,- e,- materialized=True,- version=version.version if version else None,- saved_query_id=saved_query.id if saved_query else None,- query_kind=query_kind,- executed_sql=materialized_hogql_query.query if materialized_hogql_query else None,- saved_query_status=saved_query.status if saved_query else None,- saved_query_last_run_at=(- saved_query.last_run_at.isoformat() if saved_query and saved_query.last_run_at else None- ),- saved_query_columns=saved_query.columns if saved_query else None,- endpoint_columns=version.columns if version else None,- )- raise-- @staticmethod- def _parse_int_param(- body_value: int | None, query_param: str | None, name: str, min_value: int | None = None- ) -> int | None:- """Parse an integer from the request body or query params. Raises `_RunRejected` if invalid."""- value = body_value- if value is None and query_param is not None:- try:- value = int(query_param)- if min_value is not None and value < min_value:- raise ValueError()- except (ValueError, TypeError):- raise _RunRejected(- Response({"error": f"Invalid {name} parameter: {query_param}"}, status=status.HTTP_400_BAD_REQUEST)- )- elif value is not None and min_value is not None and value < min_value:- raise _RunRejected(- Response({"error": f"Invalid {name} parameter: {value}"}, status=status.HTTP_400_BAD_REQUEST)- )- return value-- def _apply_pagination_to_query(self, query: dict, limit: int, offset: int) -> tuple[dict, EndpointPagination]:- """Apply pagination to a HogQL query. Returns (modified_query, pagination).-- Parses the HogQL AST, applies LIMIT/OFFSET, and reprints using a- placeholder-preserving printer so unresolved {variables.*} survive.- """- query_kind = query.get("kind")-- if query_kind == "HogQLQuery":- query_sql = query.get("query", "")- parsed = parse_select(query_sql)- if not isinstance(parsed, ast.SelectQuery):- raise ValidationError(- "Pagination is not supported for UNION queries. Wrap the UNION in a subquery: SELECT * FROM (... UNION ALL ...) LIMIT n"- )-- ceiling = parsed.limit.value if isinstance(parsed.limit, ast.Constant) else None- pagination = EndpointPagination(limit=limit, offset=offset, ceiling=ceiling)-- pagination.apply_to(parsed)-- ctx = HogQLContext(enable_select_queries=True, limit_top_select=False)- query = query.copy()- query["query"] = _PlaceholderPreservingPrinter(context=ctx).visit(parsed)- return query, pagination-- raise ValidationError({"limit": f"Limit/offset parameters are only supported for HogQLQuery, not {query_kind}"})-- def _parse_variables(- self, query: dict[str, dict], variables: dict[str, str]- ) -> builtins.list[HogQLVariable] | None:- query_variables = query.get("variables", None)- if not query_variables:- return None-- variables_override = []- for request_variable_code_name, request_variable_value in variables.items():- variable_id = None- for query_variable_id, query_variable_value in query_variables.items():- if query_variable_value.get("code_name", None) == request_variable_code_name:- variable_id = query_variable_id-- if variable_id is None:- raise ValidationError({"variables": f"Variable '{request_variable_code_name}' not found in query"})-- variables_override.append(- HogQLVariable(- variableId=variable_id,- code_name=request_variable_code_name,- value=request_variable_value,- isNull=True if request_variable_value is None else None,- )- )- return variables_override-- def _variables_to_filters(- self,- variables: dict[str, str],- breakdown_infos: builtins.list[tuple[str, str]] | None = None,- ):- """Convert insight magic variables to DashboardFilter.-- Args:- variables: Dict of variable name -> value from the request- breakdown_infos: List of (property_name, property_type) for breakdown filtering- """-- date_from = variables.get("date_from")- date_to = variables.get("date_to")-- properties: list[dict] = []- for prop_name, prop_type in breakdown_infos or []:- if prop_name not in variables:- continue- value = variables[prop_name]- # Any failure to build a filter for a breakdown variable must error the- # request — silently skipping would return unfiltered data, which is a- # data-leak (same principle that gates materialized endpoints on having- # all variables present).- try:- if prop_type == "hogql":- # HogQLPropertyFilter.key is a full HogQL predicate and doesn't accept- # `operator` (HogQLPropertyFilter has extra="forbid"), so build a- # `<expr> = <value>` (or `isNull(<expr>)`) predicate to filter with.- key_expr = parse_expr(prop_name)- predicate_expr: ast.Expr- if value == "":- predicate_expr = ast.Call(name="isNull", args=[key_expr])- else:- predicate_expr = ast.CompareOperation(- left=key_expr,- op=ast.CompareOperationOp.Eq,- right=ast.Constant(value=value),- )- properties.append({"key": predicate_expr.to_hogql(), "type": "hogql"})- continue- if value == "":- # Empty string means "null/unset" — match events where the property is missing.- # This keeps inline execution consistent with the materialized path,- # where null breakdown values are stored as '' in S3.- properties.append(- {- "key": prop_name,- "type": prop_type if prop_type else "event",- "operator": PropertyOperator.IS_NOT_SET,- }- )- else:- properties.append(- {- "key": prop_name,- "value": value,- "type": prop_type if prop_type else "event",- "operator": PropertyOperator.EXACT,- }- )- except Exception as e:- capture_exception(- e,- {- "product": Product.ENDPOINTS,- "team_id": self.team_id,- "endpoint_name": self.kwargs.get("name"),- "prop_name": prop_name,- "prop_type": prop_type,- },- )- raise ValidationError(- {"variables": f"Could not apply filter for breakdown variable '{prop_name}'"}- ) from e-- if not date_from and not date_to and not properties:- return None-- return DashboardFilter(date_from=date_from, date_to=date_to, properties=properties)-- def _should_use_ducklake(self, endpoint: Endpoint, version: EndpointVersion | None) -> bool:- if version is None or version.query.get("kind") != "HogQLQuery":- return False-- ff_result = posthoganalytics.feature_enabled(- "endpoints-ducklake-execution",- str(self.team.uuid),- groups={- "organization": str(self.team.organization_id),- "project": str(self.team.id),- },- group_properties={- "organization": {"id": str(self.team.organization_id)},- "project": {"id": str(self.team.id)},- },- only_evaluate_locally=True,- send_feature_flag_events=False,- )- logger.info("Ducklake FF evaluation", endpoint_name=endpoint.name, ff_result=ff_result)- if not ff_result:- return False-- server = get_duckgres_server_for_organization(str(self.team.organization_id))- if server is None:- logger.info("Ducklake skip: no duckgres server", endpoint_name=endpoint.name, team_id=self.team_id)- return server is not None-- def _execute_ducklake_endpoint(- self,- endpoint: Endpoint,- query: dict,- debug: bool = False,- ) -> Response:- from posthog.ducklake.client import execute_ducklake_query-- try:- result = execute_ducklake_query(- self.team_id,- query=HogQLQuery(query=query["query"]),- organization_id=str(self.team.organization_id),- )- response_data: dict = {- "results": result.results,- "columns": result.columns,- "types": result.types,- "hasMore": False,- "backend": "ducklake",- }- if debug:- response_data["query"] = query.get("query")- response_data["hogql"] = result.hogql- response_data["ducklake_sql"] = result.sql- return Response(response_data, status=status.HTTP_200_OK)- except Exception as e:- logger.exception(- "DuckLake endpoint execution failed",- endpoint_name=endpoint.name,- )- capture_exception(- e,- {- "product": Product.ENDPOINTS,- "team_id": self.team_id,- "ducklake": True,- "endpoint_name": endpoint.name,- },- )- raise-- def _execute_inline_endpoint(- self,- endpoint: Endpoint,- data: EndpointRunRequest,- request: Request,- query: dict,- version: EndpointVersion | None = None,- debug: bool = False,- limit: int | None = None,- offset: int | None = None,- ) -> Response:- """Execute query directly against ClickHouse."""- try:- query = prepare_insight_query_for_endpoint(query)-- pagination: EndpointPagination | None = None- if limit is not None:- query, pagination = self._apply_pagination_to_query(query, limit, offset or 0)-- refresh_type = _endpoint_refresh_mode_to_refresh_type(data.refresh)- query_kind = query.get("kind")-- variables_override = None- filters_override = None- deprecation_headers: dict[str, str] | None = None-- # For insight endpoints: filters_override takes precedence over variables (backwards compat)- if query_kind != "HogQLQuery" and data.filters_override is not None:- filters_override = data.filters_override- deprecation_headers = {- "X-PostHog-Warn": "filters_override is deprecated. Use variables instead: https://posthog.com/docs/api/endpoints"- }- elif data.variables:- if query_kind == "HogQLQuery":- variables_override = self._parse_variables(query, data.variables)- else:- breakdown_filter = query.get("breakdownFilter") or {}- breakdown_infos = _get_breakdown_infos(breakdown_filter)- filters_override = self._variables_to_filters(data.variables, breakdown_infos=breakdown_infos)-- query_request_data = {- "client_query_id": data.client_query_id,- "filters_override": filters_override.model_dump() if filters_override else None,- "name": endpoint.name,- "refresh": refresh_type,- "query": query,- }-- cache_age = version.data_freshness_seconds if version else None- tag_queries(endpoint_version=version.version if version else None)-- return self._execute_query_and_respond(- query_request_data,- data.client_query_id,- request,- variables_override=variables_override,- cache_age_seconds=cache_age,- debug=debug,- headers=deprecation_headers,- pagination=pagination,- )-- except Exception as e:- self.handle_column_ch_error(e)- logger.exception(- "Inline endpoint execution failed",- endpoint_name=endpoint.name,- )- capture_exception(- e,- {- "product": Product.ENDPOINTS,- "team_id": self.team_id,- "materialized": False,- "endpoint_name": endpoint.name,- },- )- _emit_endpoint_failure_signal(- self.team,- endpoint,- e,- materialized=False,- version=version.version if version else None,- query_kind=query_kind,- executed_sql=query.get("query") if query_kind == "HogQLQuery" else None,- endpoint_columns=version.columns if version else None,- )- raise-- def _log_rejected_run(self, endpoint: Endpoint, reason: str) -> None:- """Record a rejected run request as a failed execution so it surfaces in the endpoint logs.-- Request validation runs before the execution block, so a rejected request would otherwise- never appear in the logs. Each rejection gets its own execution id.- """- log_endpoint_execution(- team_id=self.team_id,- endpoint_id=str(endpoint.id),- instance_id=str(uuid.uuid4()),- level="ERROR",- message=f"Endpoint execution failed · invalid request · {reason}",- )-- def _resolve_version(- self, endpoint: Endpoint, version_number: int | None, name: str | None- ) -> EndpointVersion | None:- """Return the requested version, or None when no specific version was asked for and none exist.-- Raises `_RunRejected` (404) only when a specific `version_number` was requested but not found —- matching the original behavior where an unspecified version falls through to the inline path.- """- try:- return endpoint.get_version(version_number)- except EndpointVersion.DoesNotExist:- if version_number is not None:- raise _RunRejected(- Response(- {- "error": f"Version {version_number} not found for endpoint '{name}'",- "current_version": endpoint.current_version,- },- status=status.HTTP_404_NOT_FOUND,- )- )- return None-- @staticmethod- def _format_validation_detail(detail: Any) -> str:- """Flatten a DRF ValidationError detail (str | list | dict, possibly nested) into one line."""- if isinstance(detail, dict):- return "; ".join(- f"{field}: {EndpointViewSet._format_validation_detail(messages)}" for field, messages in detail.items()- )- if isinstance(detail, list):- return "; ".join(EndpointViewSet._format_validation_detail(item) for item in detail)- return str(detail)+ # ------------------------------------------------------------------+ # Execution+ # ------------------------------------------------------------------@staticmethoddef _parse_run_request(request: Request) -> EndpointRunRequest:- """Parse and validate the run request body into a clean, field-level 400 on failure.-- Raises a DRF ValidationError so the caller never sees pydantic's raw error dump. Rejection- logging is handled centrally in `run()`.- """+ """Parse the run body into field-level errors instead of pydantic's raw error dump."""try:return EndpointRunRequest.model_validate(request.data)except PydanticValidationError as exc:field_errors = {".".join(str(part) for part in error["loc"]) or "body": error["msg"] for error in exc.errors()}- raise ValidationError(field_errors)+ raise ValidationError(field_errors) from exc++ @staticmethod+ def _rejection_reason(response: Response) -> str:+ data = response.data+ if isinstance(data, dict):+ return str(data.get("error", data))+ return str(data)@extend_schema(request=EndpointRunRequest,@@ -2355,284 +455,50 @@ class EndpointViewSet("""Execute endpoint with optional parameters."""endpoint = get_object_or_404(Endpoint, team=self.team, name=name, is_active=True, deleted=False)self._enforce_object_level_access(endpoint)-- # All run-request validation lives in one place so every rejection — whether it raises a DRF- # ValidationError or returns a 4xx Response — is logged exactly once before we bail out.+ service = EndpointExecutionService(self.team, request)try:data = self._parse_run_request(request)-- report_user_action(- user=cast("User | SyntheticUser", request.user),- event="endpoint executed",- properties={- "endpoint_id": str(endpoint.id),- "endpoint_name": endpoint.name,- "has_filters_override": bool(data.filters_override),- "has_variables": bool(data.variables),- "has_limit": data.limit is not None,- "has_offset": data.offset is not None,- "refresh_mode": data.refresh.value if data.refresh else None,- "auth_method": "project_secret_api_key"- if is_authenticated_via_project_secret_api_key(request)- else "user",- },- team=self.team,- request=request,- )-- version_number = self._parse_int_param(data.version, request.query_params.get("version"), "version")- limit = self._parse_int_param(data.limit, request.query_params.get("limit"), "limit", min_value=1)- offset = self._parse_int_param(data.offset, request.query_params.get("offset"), "offset", min_value=0)-- if offset is not None and limit is None:- raise _RunRejected(- Response({"error": "offset requires limit to be set"}, status=status.HTTP_400_BAD_REQUEST)- )-- version_obj = self._resolve_version(endpoint, version_number, name)-- self.validate_run_request(data, endpoint, version_obj)-- if offset is not None and version_obj and version_obj.query.get("kind") != "HogQLQuery":- raise _RunRejected(- Response(- {"error": "offset is only supported for HogQL endpoints"}, status=status.HTTP_400_BAD_REQUEST- )- )except ValidationError as exc:- self._log_rejected_run(endpoint, self._format_validation_detail(exc.detail))+ service.log_rejected_run(endpoint, service.format_validation_detail(exc.detail))raise- except _RunRejected as rejected:- data_ = rejected.response.data- reason = data_.get("error", data_) if isinstance(data_, dict) else data_- self._log_rejected_run(endpoint, str(reason))- return rejected.response-- # Check if we should use materialization for this version- use_materialized = self._should_use_materialized_table(endpoint, data, version_obj)-- debug = data.debug or False- execution_type = "materialized" if use_materialized else "inline"- query_kind_metric = query_kind_label(version_obj.query if version_obj else None)- execution_status: str | None = None- execution_id = str(uuid.uuid4())- cache_outcome: str | None = None- result_row_count: int | None = None- error_label: str | None = None- _start_time = time.monotonic()- _duration = 0.0+ version_number, err = self._parse_int_param(data.version, request.query_params.get("version"), "version")+ if err:+ service.log_rejected_run(endpoint, self._rejection_reason(err))+ return err+ limit, err = self._parse_int_param(data.limit, request.query_params.get("limit"), "limit", min_value=1)+ if err:+ service.log_rejected_run(endpoint, self._rejection_reason(err))+ return err+ offset, err = self._parse_int_param(data.offset, request.query_params.get("offset"), "offset", min_value=0)+ if err:+ service.log_rejected_run(endpoint, self._rejection_reason(err))+ return err++ if offset is not None and limit is None:+ response = Response(+ {"error": "offset requires limit to be set"},+ status=status.HTTP_400_BAD_REQUEST,+ )+ service.log_rejected_run(endpoint, self._rejection_reason(response))+ return response++ version_obj = Nonetry:- if use_materialized:- result = self._execute_materialized_endpoint(- endpoint, data, request, version=version_obj, debug=debug, limit=limit, offset=offset- )- else:- # Use version's query- if not version_obj:- return Response(- {"error": "No version found for this endpoint"},- status=status.HTTP_404_NOT_FOUND,- )- query_to_use = version_obj.query.copy()-- use_ducklake = self._should_use_ducklake(endpoint, version_obj)- if use_ducklake:- try:- result = self._execute_ducklake_endpoint(endpoint, query_to_use, debug=debug)- execution_type = "ducklake"- except Exception:- logger.warning(- "DuckLake execution failed, falling back to inline",- endpoint_name=endpoint.name,- )- ENDPOINT_DUCKLAKE_FALLBACK_TOTAL.inc()- execution_type = "ducklake_fallback"- result = self._execute_inline_endpoint(- endpoint,- data,- request,- query_to_use,- version=version_obj,- debug=debug,- limit=limit,- offset=offset,- )- else:- result = self._execute_inline_endpoint(- endpoint,- data,- request,- query_to_use,- version=version_obj,- debug=debug,- limit=limit,- offset=offset,- )- execution_status = "success"- except (ExposedHogQLError, ExposedCHQueryError) as e:- execution_status = "user_error"- error_label = getattr(e, "code_name", None) or type(e).__name__- logger.exception(- "Endpoint execution failed",- endpoint_name=endpoint.name,- code_name=getattr(e, "code_name", None),- )- raise ValidationError("Query execution failed.", getattr(e, "code_name", None))- except HogVMException:- execution_status = "user_error"- error_label = "HogVMException"- logger.exception(- "Endpoint execution failed (HogVM)",- endpoint_name=endpoint.name,- )- raise ValidationError("Query execution failed: HogQL virtual machine error")- except ResolutionError:- execution_status = "user_error"- error_label = "ResolutionError"- logger.exception(- "Endpoint resolution failed",- endpoint_name=endpoint.name,- )- raise ValidationError("Query resolution failed: unable to resolve table or field references.")- except ConcurrencyLimitExceeded:- ENDPOINT_CONCURRENCY_REJECTED_TOTAL.labels(team_id=str(self.team_id)).inc()- raise Throttled(detail="Too many concurrent requests. Please try again later.")- except Exception as e:- execution_status = "error"- error_label = type(e).__name__- raise- finally:- if execution_status is not None:- _duration = time.monotonic() - _start_time- ENDPOINT_EXECUTION_DURATION_SECONDS.labels(- execution_type=execution_type, query_kind=query_kind_metric- ).observe(_duration)- ENDPOINT_EXECUTION_TOTAL.labels(- execution_type=execution_type, query_kind=query_kind_metric, status=execution_status- ).inc()- if execution_status in ("error", "user_error"):- log_endpoint_execution(- team_id=self.team_id,- endpoint_id=str(endpoint.id),- instance_id=execution_id,- level="ERROR",- message=build_execution_message(- succeeded=False,- execution_type=execution_type,- version=version_obj.version if version_obj else None,- error=error_label,- ),+ version_obj = endpoint.get_version(version_number)+ except EndpointVersion.DoesNotExist:+ if version_number is not None:+ response = Response(+ {+ "error": f"Version {version_number} not found for endpoint '{name}'",+ "current_version": endpoint.current_version,+ },+ status=status.HTTP_404_NOT_FOUND,)+ service.log_rejected_run(endpoint, self._rejection_reason(response))+ return response- try:- if isinstance(result.data, dict):- # DuckLake bypasses the query result cache entirely — don't claim hit/miss for it.- if execution_type != "ducklake":- cache_outcome = "hit" if bool(result.data.get("is_cached")) else "miss"- ENDPOINT_CACHE_RESULT_TOTAL.labels(- execution_type=execution_type, query_kind=query_kind_metric, outcome=cache_outcome- ).inc()-- results_value = result.data.get("results")- if isinstance(results_value, list):- result_row_count = len(results_value)- if query_kind_metric == "hogql":- ENDPOINT_HOGQL_RESULT_ROWS.labels(execution_type=execution_type).observe(result_row_count)- except Exception:- logger.debug("Failed to record endpoint result metrics", exc_info=True)-- log_endpoint_execution(- team_id=self.team_id,- endpoint_id=str(endpoint.id),- instance_id=execution_id,- level="INFO",- message=build_execution_message(- succeeded=True,- execution_type=execution_type,- cache_outcome=cache_outcome,- duration_ms=round(_duration * 1000),- rows=result_row_count,- version=version_obj.version if version_obj else None,- ),- )-- if is_api_key_access_method(get_query_tag_value("access_method")):- now = timezone.now()- throttle = timedelta(minutes=30)- if endpoint.last_executed_at is None or (now - endpoint.last_executed_at > throttle):- endpoint.last_executed_at = now- endpoint.save(update_fields=["last_executed_at"])- if version_obj is not None and (- version_obj.last_executed_at is None or (now - version_obj.last_executed_at > throttle)- ):- version_obj.last_executed_at = now- version_obj.save(update_fields=["last_executed_at"])-- if isinstance(result.data, dict):- result.data["name"] = endpoint.name- result.data["execution_id"] = execution_id- if version_obj:- result.data["endpoint_version"] = version_obj.version- result.data["endpoint_version_created_at"] = version_obj.created_at.isoformat()-- return result-- def validate_run_request(- self, data: EndpointRunRequest, endpoint: Endpoint, version: EndpointVersion | None = None- ) -> None:- version = version or endpoint.get_version()-- query = version.query- is_materialized = bool(version.is_materialized and version.saved_query)-- if version and not version.is_active:- ENDPOINT_VALIDATION_ERROR_TOTAL.labels(reason="inactive_version").inc()- raise ValidationError(f"Version {version.version} is inactive and cannot be executed.")-- query_kind = query.get("kind")-- # Reject query_override (always)- if hasattr(data, "query_override") and data.query_override is not None:- raise ValidationError({"query_override": "Not allowed. Use variables instead."})-- # Allow filters_override for insight endpoints (deprecated but backwards compatible)- # Reject for HogQL endpoints- if data.filters_override is not None:- if query_kind == "HogQLQuery":- raise ValidationError({"filters_override": "Not allowed for HogQL endpoints. Use variables instead."})-- # Validate refresh mode- if data.refresh == EndpointRefreshMode.DIRECT and not is_materialized:- ENDPOINT_VALIDATION_ERROR_TOTAL.labels(reason="direct_refresh_not_materialized").inc()- raise ValidationError(- {- "refresh": "'direct' refresh mode is only valid for materialized endpoints. "- "Use 'cache' or 'force' instead, or enable materialization on this endpoint."- }- )-- # Validate variables- if data.variables:- allowed_vars = self._get_allowed_variables(query, is_materialized)- unknown_vars = set(data.variables.keys()) - allowed_vars- if unknown_vars:- ENDPOINT_VALIDATION_ERROR_TOTAL.labels(reason="unknown_variable").inc()- raise ValidationError({"variables": f"Unknown variable(s): {', '.join(sorted(unknown_vars))}"})-- # SECURITY: For materialized endpoints with required variables, ALL must be provided.- # Without this check, omitting variables would return ALL data instead of filtered data.- # Exception: filters_override is the deprecated way to provide filters for insight endpoints- if is_materialized and not (data.filters_override and data.filters_override.properties):- required_vars = self._get_required_variables_for_materialized(query, version)- if required_vars:- provided = set(data.variables.keys()) if data.variables else set()- missing = sorted(required_vars - provided)- if missing:- ENDPOINT_VALIDATION_ERROR_TOTAL.labels(reason="missing_required_variable").inc()- raise ValidationError(- {"variables": f"Required variable(s) {', '.join(repr(v) for v in missing)} not provided"}- )+ return service.execute(endpoint, data, version_obj, limit=limit, offset=offset)@extend_schema(description=(@@ -2674,19 +540,9 @@ class EndpointViewSet(capture_exception(e, {"product": Product.ENDPOINTS, "team_id": self.team_id})raise- def handle_column_ch_error(self, error):- if getattr(error, "message", None):- match = re.search(r"There's no column.*in table", error.message)- if match:- # TODO: remove once we support all column types- raise ValidationError(match.group(0) + ". Not all column types are fully supported yet.")- return-- def _tag_client_query_id(self, query_id: str | None):- if query_id is None:- return-- tag_queries(client_query_id=query_id)+ # ------------------------------------------------------------------+ # Versions + materialization+ # ------------------------------------------------------------------@extend_schema(responses={200: EndpointVersionResponseSerializer(many=True)},@@ -2719,16 +575,11 @@ class EndpointViewSet("""endpoint = self._get_endpoint_with_object_access(name)- version_number = self._parse_version_param(request)- if version_number is not None:- try:- version = endpoint.get_version(version_number)- except EndpointVersion.DoesNotExist:- return Response({"error": f"Version {version_number} not found"}, status=status.HTTP_404_NOT_FOUND)- else:- version = endpoint.get_version()+ version = self._resolve_version_param(request, endpoint)+ if isinstance(version, Response):+ return version- return Response(self._build_materialization_info(version, endpoint_name=endpoint.name))+ return Response(build_materialization_info(version, endpoint_name=endpoint.name))@validated_request(MaterializationPreviewRequestSerializer,@@ -2751,124 +602,12 @@ class EndpointViewSet(else:version = endpoint.get_version()- can_mat, reason = version.can_materialize()- if not can_mat:- return _cant_materialize_response(reason)-bucket_overrides = request.validated_data.get("bucket_overrides")if bucket_overrides:- _validate_bucket_overrides(bucket_overrides)-- hogql_query = convert_insight_query_to_hogql(version.query, self.team)-- range_pairs: list[dict] = []- aggregates: list[dict] = []- transformed_query_str: str | None = None- variable_infos: list = []-- if version.query.get("variables"):- can_materialize_vars, var_reason, variable_infos = analyze_variables_for_materialization(- version.query, bucket_overrides=bucket_overrides- )-- if not can_materialize_vars:- return _cant_materialize_response(var_reason)+ validate_bucket_overrides(bucket_overrides)- if variable_infos:- transformed = transform_query_for_materialization(- hogql_query, variable_infos, self.team, bucket_overrides=bucket_overrides- )- transformed_query_str = transformed.get("query")-- # Extract range pairs grouped by column- seen_columns: dict[str, dict] = {}- for v in variable_infos:- if v.bucket_fn is not None:- col_key = ".".join(v.column_chain) if v.column_chain else v.column_expression- if col_key not in seen_columns:- seen_columns[col_key] = {- "column": col_key,- "variables": [],- "bucket_fn": v.bucket_fn,- }- seen_columns[col_key]["variables"].append(v.code_name)- range_pairs = list(seen_columns.values())-- query_str = hogql_query.get("query", "")- if query_str:- try:- parsed = parse_select(query_str)- except Exception:- logger.warning("materialization_preview: failed to parse HogQL for aggregate extraction")- else:- if isinstance(parsed, ast.SelectQuery) and parsed.select:- for expr in parsed.select:- agg_name = _extract_aggregate_name(expr)- if agg_name:- reagg_info = get_reaggregation(agg_name)- reagg = reagg_info.reaggregate_fn if reagg_info else None- if isinstance(expr, ast.Alias):- label = expr.alias- else:- label = expr.to_hogql()- aggregates.append(- {- "expression": label,- "reaggregate_fn": reagg,- }- )- else:- # No variables — just show the converted query as-is- transformed_query_str = hogql_query.get("query")-- # Build the execution query preview — what runs at request time against the materialized table- execution_query_str: str | None = None- display_execution_query_str: str | None = None- try:- saved_query_name = f"{endpoint.name}_v{version.version}"-- def _build_exec_preview(table_name: str) -> ast.SelectQuery:- q, _ = self._build_materialized_select_query(- table_name=table_name,- version=version,- variable_infos=variable_infos or None,- )- for v in variable_infos:- self._apply_where_filter(- q,- v.code_name,- f"{{variables.{v.code_name}}}",- op=v.operator,- value_wrapper_fns=v.value_wrapper_fns,- bucket_fn=v.bucket_fn,- )- return q-- # Each call builds a fresh SelectQuery, so WHERE mutations don't leak between calls- execution_query_str = to_printed_hogql(_build_exec_preview(saved_query_name), team=self.team)-- # Display variant uses the friendly endpoint name — printed without type resolution- # since the friendly name isn't a real table in the database- display_execution_query_str = print_prepared_ast(- node=_build_exec_preview(endpoint.name),- context=HogQLContext(team_id=self.team.pk, enable_select_queries=True),- dialect="hogql",- pretty=True,- )- except Exception:- logger.debug("Failed to build execution query preview", exc_info=True)-- return Response(- {- "can_materialize": True,- "reason": None,- "transformed_query": transformed_query_str,- "execution_query": execution_query_str,- "display_execution_query": display_execution_query_str,- "range_pairs": range_pairs,- "aggregates": aggregates,- }- )+ service = EndpointMaterializationService(self.team, request)+ return Response(dataclasses.asdict(service.preview(endpoint, version, bucket_overrides)))@extend_schema(# url_path="openapi.json" would otherwise produce `..._openapi.json_retrieve` —@@ -2907,85 +646,17 @@ class EndpointViewSet(spec = generate_openapi_spec(endpoint, self.team.id, request, version)return Response(spec, content_type="application/json")+ # ------------------------------------------------------------------+ # Tags+ # -------------------------------------------------------------------def _clean_breakdown_sentinels(result: dict) -> None:- """Replace breakdown sentinel strings in API response results in-place.-- Handles both list-of-lists (materialized/HogQL) and list-of-dicts (inline insight).- If the "Other" sentinel is found, it means the breakdown_limit was exceeded —- we clean it to "Other" but also capture_exception for visibility.- """- rows = result.get("results")- if not rows:- return-- found_other = False- columns = result.get("columns")- if columns:- # HogQL/materialized path: results are list[tuple] or list[list]- indices = [i for i, col in enumerate(columns) if col == "breakdown_value"]- if not indices:- return- for row_idx, row in enumerate(rows):- needs_clean = any(isinstance(row[i], (str, list)) or row[i] is None for i in indices)- if not needs_clean:- continue- if not found_other:- found_other = any(_value_contains_other(row[i], BREAKDOWN_OTHER_STRING_LABEL) for i in indices)- row_list = list(row)- for i in indices:- row_list[i] = _clean_sentinel_value(row_list[i])- rows[row_idx] = type(row)(row_list)- elif isinstance(rows[0], dict):- # Inline insight path: results are list[dict]- for row in rows:- if "breakdown_value" in row:- if not found_other:- found_other = _value_contains_other(row["breakdown_value"], BREAKDOWN_OTHER_STRING_LABEL)- row["breakdown_value"] = _clean_sentinel_value(row["breakdown_value"])- if "label" in row:- if not found_other and isinstance(row["label"], str):- found_other = BREAKDOWN_OTHER_STRING_LABEL in row["label"]- row["label"] = _clean_sentinel_label(row["label"])-- if found_other:- capture_exception(- Exception(- f"Endpoint breakdown limit ({ENDPOINT_BREAKDOWN_LIMIT}) exceeded — 'Other' bucket appeared in results"- )+ @extend_schema(exclude=True)+ @action(methods=["POST"], detail=False)+ def bulk_update_tags(self, request: Request, *args, **kwargs) -> Response:+ # The inherited TaggedItemViewSetMixin.bulk_update_tags assumes integer PKs (its+ # BulkUpdateTagsRequestSerializer validates ids as IntegerField). Endpoint uses+ # UUID PKs, so the action is unusable. Return 405 until the mixin gains UUID support.+ return Response(+ {"detail": "Bulk tag updates are not supported for endpoints."},+ status=status.HTTP_405_METHOD_NOT_ALLOWED,)---def _value_contains_other(value: object, other_label: str) -> bool:- """Check if a breakdown value contains the 'Other' sentinel."""- if isinstance(value, str):- return value == other_label- if isinstance(value, list):- return any(item == other_label for item in value if isinstance(item, str))- return False---def _clean_sentinel_value(value: object) -> object:- """Clean breakdown sentinel strings (null and other) in a value or list of values."""- if isinstance(value, str):- if value == BREAKDOWN_NULL_STRING_LABEL or value == "":- return None- if value == BREAKDOWN_OTHER_STRING_LABEL:- return "Other"- elif isinstance(value, list):- return [_clean_sentinel_value(item) for item in value]- return value---def _clean_sentinel_label(label: object) -> object:- """Clean a label string containing ::-joined breakdown parts."""- if not isinstance(label, str):- return label- if BREAKDOWN_NULL_STRING_LABEL not in label and BREAKDOWN_OTHER_STRING_LABEL not in label:- return label- parts = label.split("::")- cleaned = [- "null" if p == BREAKDOWN_NULL_STRING_LABEL else "Other" if p == BREAKDOWN_OTHER_STRING_LABEL else p- for p in parts- ]- return "::".join(cleaned)diff --git a/products/endpoints/backend/constants.py b/products/endpoints/backend/constants.pynew file mode 100644index 000000000000..b6ef219b9796--- /dev/null+++ b/products/endpoints/backend/constants.py@@ -0,0 +1,25 @@+import dataclasses++[email protected](frozen=True)+class DataFreshnessBucket:+ seconds: int+ sync_label: str # key understood by sync_frequency_to_sync_frequency_interval+ human: str+++DATA_FRESHNESS_BUCKET_SPECS: tuple[DataFreshnessBucket, ...] = (+ DataFreshnessBucket(900, "15min", "15 minutes"),+ DataFreshnessBucket(1800, "30min", "30 minutes"),+ DataFreshnessBucket(3600, "1hour", "1 hour"),+ DataFreshnessBucket(21600, "6hour", "6 hours"),+ DataFreshnessBucket(43200, "12hour", "12 hours"),+ DataFreshnessBucket(86400, "24hour", "24 hours"),+ DataFreshnessBucket(604800, "7day", "7 days"),+)++DATA_FRESHNESS_BUCKETS: dict[int, str] = {b.seconds: b.sync_label for b in DATA_FRESHNESS_BUCKET_SPECS}+VALID_DATA_FRESHNESS_SECONDS: frozenset[int] = frozenset(DATA_FRESHNESS_BUCKETS)+DEFAULT_DATA_FRESHNESS_SECONDS = 86400++ENDPOINT_NAME_REGEX = r"^[a-zA-Z][a-zA-Z0-9_-]{0,127}$"diff --git a/products/endpoints/backend/materialization.py b/products/endpoints/backend/materialization_transforms.pysimilarity index 100%rename from products/endpoints/backend/materialization.pyrename to products/endpoints/backend/materialization_transforms.pydiff --git a/products/endpoints/backend/metrics.py b/products/endpoints/backend/metrics.pyindex 5464edfbd8cd..4e0879ead9e9 100644--- a/products/endpoints/backend/metrics.py+++ b/products/endpoints/backend/metrics.py@@ -41,6 +41,7 @@ ENDPOINT_RATE_LIMITED_TOTAL = Counter(ENDPOINT_CONCURRENCY_REJECTED_TOTAL = Counter("posthog_endpoint_concurrency_rejected_total","Endpoint executions rejected because the concurrency limit was exceeded",+ # team_id is safe cardinality here: only teams actually hitting concurrency limits appearlabelnames=["team_id"],)diff --git a/products/endpoints/backend/models.py b/products/endpoints/backend/models.pyindex 31909364ced3..2be4b17deba6 100644--- a/products/endpoints/backend/models.py+++ b/products/endpoints/backend/models.py@@ -72,6 +72,59 @@ def _clickhouse_type_to_serialized_type(ch_type: str) -> str:return "unknown"+def can_materialize_query(query: dict | None) -> tuple[bool, str]:+ """Check whether an endpoint query can be materialized.++ Returns: (can_materialize: bool, reason: str)+ """+ query_kind = query.get("kind") if query else None++ MATERIALIZABLE_QUERY_TYPES = {+ "HogQLQuery",+ "TrendsQuery",+ "LifecycleQuery",+ "RetentionQuery",+ }++ if query_kind not in MATERIALIZABLE_QUERY_TYPES:+ supported = ", ".join(sorted(MATERIALIZABLE_QUERY_TYPES))+ return (+ False,+ f"Query type '{query_kind}' cannot be materialized. Supported types: {supported}",+ )++ assert query is not None++ # Block compare mode — materialization can't reconstruct doubled series+ compare_filter = query.get("compareFilter") or {}+ if compare_filter.get("compare"):+ return False, "Compare mode is not supported for materialized endpoints."++ # Block cohort breakdowns — they produce a UNION ALL across cohorts, which+ # inject_series_index tags as separate series, causing a mismatch at read time.+ breakdown_filter = query.get("breakdownFilter") or {}+ if breakdown_filter.get("breakdown_type") == "cohort":+ return False, "Cohort breakdowns are not supported for materialized endpoints."+ for breakdown in breakdown_filter.get("breakdowns") or []:+ if isinstance(breakdown, dict) and breakdown.get("type") == "cohort":+ return False, "Cohort breakdowns are not supported for materialized endpoints."++ if query.get("variables"):+ from products.endpoints.backend.materialization_transforms import analyze_variables_for_materialization++ can_materialize, reason, _ = analyze_variables_for_materialization(query)++ if not can_materialize:+ return False, f"Variables not supported: {reason}"++ if query_kind == "HogQLQuery":+ hogql_query = query.get("query")+ if not hogql_query or not isinstance(hogql_query, str):+ return False, "Query is empty or invalid."++ return True, ""++def validate_endpoint_name(value: str) -> None:"""Validate that the endpoint name is URL-safe and follows naming conventions."""if not re.match(r"^[a-zA-Z][a-zA-Z0-9_-]*$", value):@@ -184,6 +237,17 @@ class EndpointVersion(UpdatedMetaFields, models.Model):capture_exception(exc)return self.columns+ @property+ def materialized_view_name(self) -> str:+ """Name of the saved query backing this version: {endpoint_name}_v{version}."""+ return f"{self.endpoint.name}_v{self.version}"++ def enable_materialization(self, saved_query, bucket_overrides: dict[str, str] | None = None) -> None:+ """Counterpart of disable_materialization: link the backing saved query to this version."""+ self.saved_query = saved_query+ self.bucket_overrides = bucket_overrides+ self.save(update_fields=["saved_query", "bucket_overrides", "updated_at"])+def disable_materialization(self) -> None:"""Disable materialization: revert and soft-delete the saved query, clear version fields."""if not self.saved_query:@@ -208,50 +272,7 @@ class EndpointVersion(UpdatedMetaFields, models.Model):Returns: (can_materialize: bool, reason: str)"""- query_kind = self.query.get("kind") if self.query else None-- MATERIALIZABLE_QUERY_TYPES = {- "HogQLQuery",- "TrendsQuery",- "LifecycleQuery",- "RetentionQuery",- }-- if query_kind not in MATERIALIZABLE_QUERY_TYPES:- supported = ", ".join(sorted(MATERIALIZABLE_QUERY_TYPES))- return (- False,- f"Query type '{query_kind}' cannot be materialized. Supported types: {supported}",- )-- # Block compare mode — materialization can't reconstruct doubled series- compare_filter = self.query.get("compareFilter") or {}- if compare_filter.get("compare"):- return False, "Compare mode is not supported for materialized endpoints."-- # Block cohort breakdowns — they produce a UNION ALL across cohorts, which- # inject_series_index tags as separate series, causing a mismatch at read time.- breakdown_filter = self.query.get("breakdownFilter") or {}- if breakdown_filter.get("breakdown_type") == "cohort":- return False, "Cohort breakdowns are not supported for materialized endpoints."- for breakdown in breakdown_filter.get("breakdowns") or []:- if isinstance(breakdown, dict) and breakdown.get("type") == "cohort":- return False, "Cohort breakdowns are not supported for materialized endpoints."-- if self.query.get("variables"):- from products.endpoints.backend.materialization import analyze_variables_for_materialization-- can_materialize, reason, _ = analyze_variables_for_materialization(self.query)-- if not can_materialize:- return False, f"Variables not supported: {reason}"-- if query_kind == "HogQLQuery":- hogql_query = self.query.get("query")- if not hogql_query or not isinstance(hogql_query, str):- return False, "Query is empty or invalid."-- return True, ""+ return can_materialize_query(self.query)@staticmethoddef extract_columns(query: dict, team_id: int) -> list[dict]:diff --git a/products/endpoints/backend/openapi.py b/products/endpoints/backend/openapi.pyindex 8b2e284369fc..aba90e04189d 100644--- a/products/endpoints/backend/openapi.py+++ b/products/endpoints/backend/openapi.py@@ -3,6 +3,7 @@ from django.conf import settingsfrom rest_framework.request import Requestfrom products.endpoints.backend.models import Endpoint, EndpointVersion+from products.endpoints.backend.services.strategies import InsightEndpointStrategyfrom products.product_analytics.backend.models.insight_variable import InsightVariableINSIGHT_VARIABLE_TYPE_TO_OPENAPI: dict[str, dict] = {@@ -236,10 +237,6 @@ def _get_single_breakdown_property(breakdown_filter: dict) -> str | None:return None-# Query types that support user-configurable breakdown filtering-BREAKDOWN_SUPPORTED_QUERY_TYPES = {"TrendsQuery", "RetentionQuery"}--def _build_variables_schema(query: dict, is_materialized: bool, team_id: int) -> dict | None:"""Build schema for variables based on query type and materialization state."""query_kind = query.get("kind")@@ -274,7 +271,7 @@ def _build_variables_schema(query: dict, is_materialized: bool, team_id: int) ->properties[code_name]["example"] = default_valueelse:# Insight queries - only include breakdown for supported query types- if query_kind in BREAKDOWN_SUPPORTED_QUERY_TYPES:+ if query_kind in InsightEndpointStrategy.BREAKDOWN_SUPPORTED_QUERY_TYPES:breakdown_filter = query.get("breakdownFilter") or {}breakdown = _get_single_breakdown_property(breakdown_filter)if breakdown:diff --git a/products/endpoints/backend/rate_limit.py b/products/endpoints/backend/rate_limit.pyindex d48314b98c92..f4ff58d6c714 100644--- a/products/endpoints/backend/rate_limit.py+++ b/products/endpoints/backend/rate_limit.py@@ -1,3 +1,5 @@+from collections.abc import Iterable+from django.core.cache import cachefrom rest_framework.throttling import SimpleRateThrottle@@ -11,89 +13,144 @@ from posthog.rate_limit import (from products.endpoints.backend.metrics import ENDPOINT_RATE_LIMITED_TOTAL-MATERIALIZED_ENDPOINT_CACHE_KEY = "endpoint_materialized_ready:{team_id}:{endpoint_name}"+# Keyed per version so the throttle budget matches the version actually being executed:+# an explicit `?version=N` request is classified by that version's readiness, everything+# else by the current version's (the "current" label).+MATERIALIZED_ENDPOINT_CACHE_KEY = "endpoint_materialized_ready:{team_id}:{endpoint_name}:{version_label}"MATERIALIZED_ENDPOINT_CACHE_TTL = 3600 # 1 hour fallback TTL+CURRENT_VERSION_LABEL = "current"+++def _version_label(version: int | None) -> str:+ return f"v{version}" if version is not None else CURRENT_VERSION_LABEL+-def get_endpoint_materialization_cache_key(team_id: int, endpoint_name: str) -> str:- return MATERIALIZED_ENDPOINT_CACHE_KEY.format(team_id=team_id, endpoint_name=endpoint_name)+def get_endpoint_materialization_cache_key(team_id: int, endpoint_name: str, version: int | None = None) -> str:+ return MATERIALIZED_ENDPOINT_CACHE_KEY.format(+ team_id=team_id, endpoint_name=endpoint_name, version_label=_version_label(version)+ )-def is_endpoint_materialization_ready(team_id: int, endpoint_name: str) -> bool | None:+def is_endpoint_materialization_ready(team_id: int, endpoint_name: str, version: int | None = None) -> bool | None:"""- Check if an endpoint's materialization is ready (cached).+ Check if an endpoint version's materialization is ready (cached).Returns:True if materialization is readyFalse if materialization is not readyNone if cache miss (caller should check DB and populate cache)"""- cache_key = get_endpoint_materialization_cache_key(team_id, endpoint_name)+ cache_key = get_endpoint_materialization_cache_key(team_id, endpoint_name, version)return cache.get(cache_key)-def set_endpoint_materialization_ready(team_id: int, endpoint_name: str, is_ready: bool) -> None:+def set_endpoint_materialization_ready(+ team_id: int, endpoint_name: str, is_ready: bool, version: int | None = None+) -> None:"""- Set the cached materialization ready status for an endpoint.+ Set the cached materialization ready status for an endpoint version.Called when:- Temporal workflow completes successfully (is_ready=True)- Temporal workflow fails (is_ready=False)- Materialization is disabled (is_ready=False)"""- cache_key = get_endpoint_materialization_cache_key(team_id, endpoint_name)+ cache_key = get_endpoint_materialization_cache_key(team_id, endpoint_name, version)cache.set(cache_key, is_ready, timeout=MATERIALIZED_ENDPOINT_CACHE_TTL)-def clear_endpoint_materialization_cache(team_id: int, endpoint_name: str) -> None:- """Clear the cached materialization status for an endpoint."""- cache_key = get_endpoint_materialization_cache_key(team_id, endpoint_name)- cache.delete(cache_key)+def clear_endpoint_materialization_cache(+ team_id: int, endpoint_name: str, versions: Iterable[int] | None = None+) -> None:+ """Clear the cached materialization status for the given versions plus the "current" key."""+ keys = [get_endpoint_materialization_cache_key(team_id, endpoint_name)]+ if versions is not None:+ keys.extend(get_endpoint_materialization_cache_key(team_id, endpoint_name, version) for version in versions)+ cache.delete_many(keys)-def _get_endpoint_info_from_request(request, view) -> tuple[int | None, str | None]:- """Extract team_id and endpoint_name from request/view context."""+def update_materialization_ready_for_saved_query(team_id: int, saved_query, is_ready: bool) -> None:+ """Update the readiness cache for the endpoint version backed by this saved query.++ Used by the data modeling workflow on materialization completion/failure. Updates the+ version's own key, and the "current" key when that version is the endpoint's current one.+ """+ from products.endpoints.backend.models import EndpointVersion++ # Scope by endpoint__team_id: EndpointVersion.team is a nullable denormalized field.+ version = (+ EndpointVersion.objects.select_related("endpoint")+ .filter(saved_query=saved_query, endpoint__team_id=team_id)+ .first()+ )+ if version is None:+ return++ endpoint_name = version.endpoint.name+ set_endpoint_materialization_ready(team_id, endpoint_name, is_ready, version=version.version)+ if version.version == version.endpoint.current_version:+ set_endpoint_materialization_ready(team_id, endpoint_name, is_ready)+++def _parse_requested_version(request) -> int | None:+ """Best-effort parse of the targeted version from the request (body first, then query params).++ Mirrors EndpointViewSet._parse_version_param; invalid or absent values fall back to None+ (current version) — the view validates and rejects properly later.+ """+ try:+ body_version = request.data.get("version") if hasattr(request, "data") else None+ raw_version = body_version if body_version is not None else request.query_params.get("version")+ return int(raw_version) if raw_version is not None else None+ except Exception:+ return None+++def _get_endpoint_info_from_request(request, view) -> tuple[int | None, str | None, int | None]:+ """Extract team_id, endpoint_name, and requested version from request/view context."""team_id = getattr(view, "team_id", None)endpoint_name = view.kwargs.get("name") if hasattr(view, "kwargs") else None- return team_id, endpoint_name+ return team_id, endpoint_name, _parse_requested_version(request)-def _check_and_cache_materialization_status(team_id: int, endpoint_name: str) -> bool:+def _check_and_cache_materialization_status(team_id: int, endpoint_name: str, version: int | None = None) -> bool:"""Check materialization status from DB and populate cache.Called on cache miss for lazy loading.- Returns True if endpoint's current version is ready for materialized execution.+ Returns True if the targeted endpoint version (current when version is None) is ready+ for materialized execution."""from products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery- from products.endpoints.backend.models import Endpoint+ from products.endpoints.backend.models import Endpoint, EndpointVersiontry:endpoint = Endpoint.objects.get(team_id=team_id, name=endpoint_name, is_active=True, deleted=False)- version = endpoint.get_version()+ endpoint_version = endpoint.get_version(version)is_ready = (- version.is_materialized- and version.saved_query is not None- and version.saved_query.status == DataWarehouseSavedQuery.Status.COMPLETED+ endpoint_version.is_materialized+ and endpoint_version.saved_query is not None+ and endpoint_version.saved_query.status == DataWarehouseSavedQuery.Status.COMPLETED)- set_endpoint_materialization_ready(team_id, endpoint_name, is_ready)+ set_endpoint_materialization_ready(team_id, endpoint_name, is_ready, version=version)return is_ready- except Endpoint.DoesNotExist:- set_endpoint_materialization_ready(team_id, endpoint_name, False)+ except (Endpoint.DoesNotExist, EndpointVersion.DoesNotExist):+ set_endpoint_materialization_ready(team_id, endpoint_name, False, version=version)return Falsedef _is_materialized_endpoint_request(request, view) -> bool:- """Check if this request is for a materialized endpoint (cached check with lazy loading)."""- team_id, endpoint_name = _get_endpoint_info_from_request(request, view)+ """Check if this request targets a materialized endpoint version (cached check with lazy loading)."""+ team_id, endpoint_name, version = _get_endpoint_info_from_request(request, view)if not team_id or not endpoint_name:return False- cached_status = is_endpoint_materialization_ready(team_id, endpoint_name)+ cached_status = is_endpoint_materialization_ready(team_id, endpoint_name, version)if cached_status is None:- return _check_and_cache_materialization_status(team_id, endpoint_name)+ return _check_and_cache_materialization_status(team_id, endpoint_name, version)return cached_statusdiff --git a/products/endpoints/backend/services/activity.py b/products/endpoints/backend/services/activity.pynew file mode 100644index 000000000000..3095c58518f1--- /dev/null+++ b/products/endpoints/backend/services/activity.py@@ -0,0 +1,10 @@+import dataclasses+from typing import Optional++from posthog.models.activity_logging.activity_log import ActivityContextBase++[email protected](frozen=True)+class EndpointContext(ActivityContextBase):+ id: Optional[int] = None+ version: Optional[int] = Nonediff --git a/products/endpoints/backend/services/crud.py b/products/endpoints/backend/services/crud.pynew file mode 100644index 000000000000..deca76ca342d--- /dev/null+++ b/products/endpoints/backend/services/crud.py@@ -0,0 +1,499 @@+"""Create/update/delete orchestration for endpoints.++``EndpointCrudService`` owns the write-path business rules: version creation on+query change, materialization transfer between versions, tag application, and+activity logging. The viewset only parses/validates the request and serializes+the result.+"""++import dataclasses+from typing import Union, cast++from django.db import transaction++import structlog+from loginas.utils import is_impersonated_session+from rest_framework.exceptions import APIException, ValidationError+from rest_framework.request import Request++from posthog.schema import EndpointRequest, HogQLQuery++from posthog.api.tagged_item import cleanup_orphan_tags, set_tags_on_object+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 Team, User+from posthog.models.activity_logging.activity_log import Change, Detail, changes_between, log_activity+from posthog.types import InsightQueryNode++from products.data_modeling.backend.services.saved_query_dag_sync import delete_node_from_dag+from products.data_warehouse.backend.data_load.saved_query_service import trigger_saved_query_schedule+from products.endpoints.backend.constants import DEFAULT_DATA_FRESHNESS_SECONDS+from products.endpoints.backend.models import Endpoint, EndpointVersion+from products.endpoints.backend.rate_limit import clear_endpoint_materialization_cache+from products.endpoints.backend.services.activity import EndpointContext+from products.endpoints.backend.services.materialization import EndpointMaterializationService+from products.endpoints.backend.services.validation import validate_bucket_overrides++logger = structlog.get_logger(__name__)+++def apply_tags(endpoint: Endpoint, tags: list[str] | None) -> None:+ """Replace the endpoint's tags. No-op when tags is None (field omitted)."""+ if tags is None:+ return+ # `prefetched_tags` is a dynamic attribute populated by the TaggedItem prefetch / set_tags_on_object;+ # it's not declared on the Endpoint model.+ endpoint.prefetched_tags = set_tags_on_object(tags, endpoint) # type: ignore[attr-defined]+ cleanup_orphan_tags(endpoint.team_id)++[email protected](frozen=True)+class EndpointUpdateResult:+ """Outcome of an update, with everything the viewset needs to build the response."""++ endpoint: Endpoint+ target_version: EndpointVersion+ version_targeted: bool+ materialization_error: str | None = None+++class EndpointCrudService:+ """Write-path orchestration for endpoints."""++ def __init__(self, team: Team, request: Request):+ self.team = team+ self.request = request+ self.user = cast(User, request.user)+ self.materialization = EndpointMaterializationService(team, request)++ def _log_activity(self, *, item_id: str, scope: str, activity: str, detail: Detail) -> None:+ log_activity(+ organization_id=self.team.organization_id,+ team_id=self.team.pk,+ user=self.user,+ was_impersonated=is_impersonated_session(self.request),+ item_id=item_id,+ scope=scope,+ activity=activity,+ detail=detail,+ )++ # ------------------------------------------------------------------+ # Create+ # ------------------------------------------------------------------++ def create(self, data: EndpointRequest) -> Endpoint:+ """Create an endpoint with its initial version. Assumes the payload is validated."""+ if Endpoint.objects.filter(team=self.team, name=data.name, deleted=False).exists():+ raise ValidationError({"name": "An endpoint with this name already exists for this team."})++ try:+ query_dict = cast(Union[HogQLQuery, InsightQueryNode], data.query).model_dump()++ # Column extraction hits ClickHouse — do it outside the transaction.+ try:+ columns: list[dict] | None = EndpointVersion.extract_columns(query_dict, team_id=self.team.pk)+ except Exception as e:+ capture_exception(+ e,+ {"product": Product.ENDPOINTS, "team_id": self.team.pk, "endpoint_name": data.name},+ )+ columns = None++ # The endpoint and its initial version must exist together — a version-less+ # endpoint can't run and would squat on the name.+ with transaction.atomic():+ endpoint = Endpoint.objects.create(+ team=self.team,+ created_by=self.user,+ name=cast(str, data.name), # verified in validate_endpoint_request+ is_active=data.is_active if data.is_active is not None else True,+ current_version=1,+ derived_from_insight=data.derived_from_insight,+ )+ EndpointVersion.objects.create(+ endpoint=endpoint,+ team=self.team,+ version=1,+ query=query_dict,+ description=data.description or "",+ data_freshness_seconds=(+ data.data_freshness_seconds+ if data.data_freshness_seconds is not None+ else DEFAULT_DATA_FRESHNESS_SECONDS+ ),+ created_by=self.user,+ columns=columns,+ )++ apply_tags(endpoint, data.tags)++ self._log_activity(+ item_id=str(endpoint.id),+ scope="Endpoint",+ activity="created",+ detail=Detail(name=endpoint.name),+ )++ report_user_action(+ user=self.user,+ event="endpoint created",+ properties={+ "endpoint_id": str(endpoint.id),+ "endpoint_name": endpoint.name,+ "query_kind": query_dict.get("kind") if isinstance(query_dict, dict) else None,+ },+ team=self.team,+ request=self.request,+ )++ return endpoint++ except ValidationError:+ raise+ except Exception as e:+ capture_exception(+ e,+ {+ "product": Product.ENDPOINTS,+ "team_id": self.team.pk,+ "endpoint_name": data.name,+ },+ )+ raise ValidationError("Failed to create endpoint.")++ # ------------------------------------------------------------------+ # Update+ # ------------------------------------------------------------------++ def update(+ self,+ endpoint: Endpoint,+ data: EndpointRequest,+ raw_data: dict,+ version_number: int | None = None,+ ) -> EndpointUpdateResult:+ """Update an endpoint, creating a new version when the query changes.++ When version_number is provided, updates target that specific version+ (and query changes are rejected). ``raw_data`` is the unparsed request+ payload, needed to distinguish omitted fields from explicit nulls.+ """+ endpoint_before_update = Endpoint.objects.get(pk=endpoint.id)++ target_version_override = self._resolve_target_version_override(endpoint, data, version_number)+ version_targeted = target_version_override is not None++ step = "start"+ try:+ current_version = endpoint.get_version()+ # get_version raises when no versions exist, so target_version is never None.+ target_version = target_version_override or current_version+ version_before_update = EndpointVersion.objects.get(pk=target_version.pk)+ was_materialized = current_version.saved_query_id is not None++ step = "endpoint_activation"+ # Endpoint-level activation only — deactivating a single version must never+ # touch the endpoint or the current version's materialization.+ if data.is_active is not None and not version_targeted:+ endpoint.is_active = data.is_active+ endpoint.save()+ if not version_targeted and not endpoint.is_active and was_materialized:+ self.materialization.disable_materialization(endpoint, current_version)+ if data.is_active is not None and not version_targeted:+ # Activation affects throttle classification — force a lazy re-check.+ clear_endpoint_materialization_cache(self.team.pk, endpoint.name)++ step = "versioning"+ target_version, version_was_created, old_bucket_overrides = self._apply_query_change(+ endpoint, data, target_version, was_materialized+ )++ step = "version_fields"+ self._apply_version_field_updates(target_version, data, raw_data, version_targeted)++ step = "materialization"+ materialization_error = self._reconcile_materialization(+ endpoint,+ data,+ raw_data,+ target_version,+ version_targeted,+ was_materialized=was_materialized,+ version_was_created=version_was_created,+ old_bucket_overrides=old_bucket_overrides,+ )++ step = "tags_and_activity"+ apply_tags(endpoint, data.tags)+ self._log_update_activity(+ endpoint, endpoint_before_update, target_version, version_before_update, version_was_created+ )++ return EndpointUpdateResult(+ endpoint=endpoint,+ target_version=target_version,+ version_targeted=version_targeted,+ materialization_error=materialization_error,+ )++ except APIException:+ raise+ except Exception as e:+ current_version = endpoint.get_version()+ capture_exception(+ e,+ {+ "product": Product.ENDPOINTS,+ "team_id": self.team.pk,+ "endpoint_id": endpoint.id,+ "saved_query_id": current_version.saved_query.id if current_version.saved_query else None,+ "update_step": step,+ },+ )+ raise ValidationError("Failed to update endpoint.")++ def _resolve_target_version_override(+ self, endpoint: Endpoint, data: EndpointRequest, version_number: int | None+ ) -> EndpointVersion | None:+ if version_number is None:+ return None+ try:+ target_version_override = endpoint.get_version(version_number)+ except EndpointVersion.DoesNotExist:+ raise ValidationError({"version": f"Version {version_number} not found for this endpoint."})+ if data.query is not None:+ raise ValidationError(+ {"query": "Cannot change query when targeting a specific version. Query changes create a new version."}+ )+ return target_version_override++ def _apply_query_change(+ self,+ endpoint: Endpoint,+ data: EndpointRequest,+ target_version: EndpointVersion,+ was_materialized: bool,+ ) -> tuple[EndpointVersion, bool, dict[str, str] | None]:+ """Create a new version when the query changed. Returns (target_version, created, old_bucket_overrides)."""+ if data.query is None:+ return target_version, False, None++ new_query_dict = data.query.model_dump()+ if not endpoint.has_query_changed(new_query_dict):+ return target_version, False, None++ # Preserve bucketing across the version bump so materialization transfers cleanly.+ old_bucket_overrides = target_version.bucket_overrides if was_materialized else None+ new_version = endpoint.create_new_version(query=new_query_dict, user=self.user)+ # The "current" version changed — its cached throttle readiness no longer applies.+ clear_endpoint_materialization_cache(self.team.pk, endpoint.name)+ return new_version, True, old_bucket_overrides++ def _apply_version_field_updates(+ self,+ target_version: EndpointVersion,+ data: EndpointRequest,+ raw_data: dict,+ version_targeted: bool,+ ) -> None:+ update_fields = []+ if data.description is not None:+ target_version.description = data.description+ update_fields.append("description")+ if "data_freshness_seconds" in raw_data:+ target_version.data_freshness_seconds = (+ data.data_freshness_seconds+ if data.data_freshness_seconds is not None+ else DEFAULT_DATA_FRESHNESS_SECONDS+ )+ update_fields.append("data_freshness_seconds")+ # When targeting a specific version, is_active updates the version+ if data.is_active is not None and version_targeted:+ target_version.is_active = data.is_active+ update_fields.append("is_active")+ if update_fields:+ update_fields.append("updated_at")+ target_version.save(update_fields=update_fields)++ def _reconcile_materialization(+ self,+ endpoint: Endpoint,+ data: EndpointRequest,+ raw_data: dict,+ target_version: EndpointVersion,+ version_targeted: bool,+ *,+ was_materialized: bool,+ version_was_created: bool,+ old_bucket_overrides: dict[str, str] | None,+ ) -> str | None:+ """Bring the target version's materialization in line with the request.++ Returns a materialization error message when enabling failed after a new+ version was already committed (the update itself still succeeds).+ """+ if not endpoint.is_active:+ # Endpoint-level deactivation already tore down the current version's materialization.+ return None++ if version_targeted and not target_version.is_active:+ # Deactivating a version: tear down its own materialization, never enable.+ if target_version.saved_query_id is not None:+ self.materialization.disable_materialization(endpoint, target_version)+ return None++ # When targeting a specific version, check that version's materialization state.+ # Otherwise use the pre-update state so materialization transfers across a version bump.+ check_was_materialized = target_version.saved_query_id is not None if version_targeted else was_materialized++ should_enable = data.is_materialized is True or (data.is_materialized is None and check_was_materialized)+ if data.is_materialized is False:+ self.materialization.disable_materialization(endpoint, target_version)+ return None+ if not should_enable:+ return None++ bucket_overrides = raw_data.get("bucket_overrides")+ if bucket_overrides is None and version_was_created:+ bucket_overrides = old_bucket_overrides+ validate_bucket_overrides(bucket_overrides)+ stored_bucket_overrides = target_version.bucket_overrides++ try:+ self.materialization.enable_materialization(+ endpoint,+ target_version,+ target_version.data_freshness_seconds,+ bucket_overrides=bucket_overrides,+ )+ if (+ bucket_overrides is not None+ and bucket_overrides != stored_bucket_overrides+ and target_version.saved_query is not None+ ):+ # enable only triggers an immediate Temporal run when it creates the schedule;+ # changed bucketing on an existing materialization needs an explicit refresh.+ try:+ trigger_saved_query_schedule(target_version.saved_query)+ except Exception:+ logger.warning(+ "failed_to_trigger_materialization_refresh",+ team_id=self.team.pk,+ endpoint_name=endpoint.name,+ saved_query_id=str(target_version.saved_query_id),+ bucket_overrides=bucket_overrides,+ )+ except Exception as e:+ if not version_was_created:+ raise+ # The new version was already committed — don't fail the whole update.+ # Materialization can be retried via a subsequent update.+ logger.exception(+ "Materialization failed after version creation",+ endpoint_name=endpoint.name,+ version=target_version.version,+ )+ capture_exception(+ e,+ {+ "product": Product.ENDPOINTS,+ "team_id": self.team.pk,+ "endpoint_name": endpoint.name,+ "version": target_version.version,+ },+ )+ return str(e)+ return None++ def _log_update_activity(+ self,+ endpoint: Endpoint,+ endpoint_before_update: Endpoint,+ target_version: EndpointVersion,+ version_before_update: EndpointVersion,+ version_was_created: bool,+ ) -> None:+ endpoint_changes = changes_between("Endpoint", previous=endpoint_before_update, current=endpoint)+ if endpoint_changes:+ self._log_activity(+ item_id=str(endpoint.id),+ scope="Endpoint",+ activity="updated",+ detail=Detail(name=endpoint.name, changes=endpoint_changes),+ )++ if version_was_created:+ query_change = Change(+ type="EndpointVersion",+ action="changed",+ field="query",+ before=version_before_update.query,+ after=target_version.query,+ )+ self._log_activity(+ item_id=str(endpoint.id),+ scope="Endpoint",+ activity="version_created",+ detail=Detail(+ name=endpoint.name,+ changes=[query_change],+ context=EndpointContext(version=target_version.version),+ ),+ )+ else:+ version_changes = changes_between("EndpointVersion", previous=version_before_update, current=target_version)+ if version_changes:+ self._log_activity(+ item_id=str(endpoint.id),+ scope="EndpointVersion",+ activity="version_updated",+ detail=Detail(+ name=endpoint.name,+ changes=version_changes,+ context=EndpointContext(version=target_version.version),+ ),+ )++ # ------------------------------------------------------------------+ # Destroy+ # ------------------------------------------------------------------++ def destroy(self, endpoint: Endpoint) -> None:+ """Soft-delete an endpoint and clean up materialized queries."""+ endpoint_id = str(endpoint.id)+ endpoint_name = endpoint.name++ # DAG cleanup only — the saved queries themselves are reverted and soft-deleted+ # by endpoint.soft_delete() via version.disable_materialization().+ for version in endpoint.versions.filter(saved_query__isnull=False):+ try:+ if version.saved_query:+ delete_node_from_dag(version.saved_query)+ except Exception as e:+ logger.exception(+ "Failed to remove endpoint node from DAG on destroy",+ endpoint_name=endpoint.name,+ saved_query_id=version.saved_query.id if version.saved_query else None,+ )+ capture_exception(+ e,+ {+ "product": Product.ENDPOINTS,+ "team_id": self.team.pk,+ "endpoint_name": endpoint.name,+ "saved_query_id": version.saved_query.id if version and version.saved_query else None,+ },+ )++ endpoint.soft_delete()+ clear_endpoint_materialization_cache(+ self.team.pk, endpoint.name, versions=endpoint.versions.values_list("version", flat=True)+ )+ self._log_activity(+ item_id=endpoint_id,+ scope="Endpoint",+ activity="deleted",+ detail=Detail(name=endpoint_name),+ )diff --git a/products/endpoints/backend/services/endpoint_materialization_service.py b/products/endpoints/backend/services/endpoint_materialization_service.pydeleted file mode 100644index 0fd10bf9a6cc..000000000000--- a/products/endpoints/backend/services/endpoint_materialization_service.py+++ /dev/null@@ -1,17 +0,0 @@-from products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery-from products.endpoints.backend.materialization import build_endpoint_hogql---class OrphanedEndpointSavedQueryError(Exception):- pass---def prepare_executable_query(saved_query: DataWarehouseSavedQuery) -> None:- version = saved_query.endpoint_versions.first()- if version is None:- raise OrphanedEndpointSavedQueryError(- f"Saved query {saved_query.id} ({saved_query.name}) has no linked EndpointVersion"- )-- saved_query.query = build_endpoint_hogql(version.query, saved_query.team, bucket_overrides=version.bucket_overrides)- saved_query.save(update_fields=["query", "updated_at"])diff --git a/products/endpoints/backend/services/execution.py b/products/endpoints/backend/services/execution.pynew file mode 100644index 000000000000..a01259af7b85--- /dev/null+++ b/products/endpoints/backend/services/execution.py@@ -0,0 +1,971 @@+"""Endpoint run-path orchestration.++``EndpointExecutionService`` owns everything that happens after the viewset has+authenticated the caller and parsed the request: run-request validation, choosing+between materialized / inline / DuckLake execution, query-service invocation,+response post-processing, metrics, and failure signals. Kind-specific behavior+(variables, WHERE building, response re-shaping) is delegated to the+``EndpointQueryStrategy`` classes.+"""++import re+import time+import uuid+from datetime import timedelta+from typing import Literal, Union, cast++from django.utils import timezone++import structlog+import posthoganalytics+from asgiref.sync import async_to_sync+from dateutil.parser import isoparse+from pydantic import BaseModel+from rest_framework import status+from rest_framework.authentication import SessionAuthentication+from rest_framework.exceptions import Throttled, ValidationError+from rest_framework.request import Request+from rest_framework.response import Response++from posthog.schema import (+ EndpointRefreshMode,+ EndpointRunRequest,+ HogQLQuery,+ HogQLQueryModifiers,+ HogQLVariable,+ QueryRequest,+ RefreshType,+)++from posthog.hogql.errors import ExposedHogQLError, ResolutionError++from posthog.api.mixins import PydanticModelMixin+from posthog.api.query import _process_query_request+from posthog.api.services.query import process_query_model+from posthog.clickhouse.client.connection import Workload+from posthog.clickhouse.client.limit import ConcurrencyLimitExceeded+from posthog.clickhouse.query_tagging import (+ Feature,+ Product,+ get_query_tag_value,+ is_api_key_access_method,+ tag_queries,+)+from posthog.ducklake.common import get_duckgres_server_for_organization+from posthog.errors import ExposedCHQueryError+from posthog.event_usage import get_request_analytics_properties, report_user_action+from posthog.exceptions_capture import capture_exception+from posthog.models import Team, User+from posthog.permissions import is_authenticated_via_project_secret_api_key+from posthog.synthetic_user import SyntheticUser++from products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery+from products.data_warehouse.backend.data_load.saved_query_service import trigger_saved_query_schedule+from products.endpoints.backend.insight_transformers import MaterializedSeriesMismatchError+from products.endpoints.backend.logs import build_execution_message, log_endpoint_execution+from products.endpoints.backend.metrics import (+ ENDPOINT_CACHE_RESULT_TOTAL,+ ENDPOINT_CONCURRENCY_REJECTED_TOTAL,+ ENDPOINT_DUCKLAKE_FALLBACK_TOTAL,+ ENDPOINT_EXECUTION_DURATION_SECONDS,+ ENDPOINT_EXECUTION_TOTAL,+ ENDPOINT_HOGQL_RESULT_ROWS,+ ENDPOINT_MATERIALIZED_FRESHNESS_RATIO,+ ENDPOINT_VALIDATION_ERROR_TOTAL,+ query_kind_label,+)+from products.endpoints.backend.models import Endpoint, EndpointVersion+from products.endpoints.backend.services.pagination import EndpointPagination+from products.endpoints.backend.services.strategies import EndpointQueryStrategy, strategy_for++from common.hogvm.python.utils import HogVMException++logger = structlog.get_logger(__name__)++LAST_EXECUTED_THROTTLE = timedelta(minutes=30)++ExecutionType = Literal["materialized", "materialized_fallback", "inline", "ducklake", "ducklake_fallback"]+++def _emit_endpoint_failure_signal(+ team,+ endpoint: Endpoint,+ exc: BaseException,+ *,+ materialized: bool,+ version: int | None = None,+ saved_query_id: Union[str, uuid.UUID, None] = None,+ query_kind: str | None = None,+ executed_sql: str | None = None,+ saved_query_status: str | None = None,+ saved_query_last_run_at: str | None = None,+ saved_query_columns: dict | None = None,+ endpoint_columns: list | None = None,+) -> None:+ """Fire a Signal when an endpoint execution fails, so the AI can reason about it later.++ Fails silently — signal emission must never mask the underlying error.+ """+ from products.signals.backend.facade.api import emit_signal++ try:+ error_class = type(exc).__name__+ error_msg = str(exc)+ version_str = f" v{version}" if version else ""++ if materialized:+ execution_mode = "materialized"+ context = (+ f"The materialized table (saved_query_id={saved_query_id}) may be stale, missing, or have a schema mismatch. "+ f"Check whether the materialization refresh completed successfully and whether the underlying query still produces valid columns."+ )+ if saved_query_status:+ context += f"\nSaved query status: {saved_query_status}"+ if saved_query_last_run_at:+ context += f", last materialized at: {saved_query_last_run_at}"+ if saved_query_columns:+ context += f"\nMaterialized table columns: {saved_query_columns}"+ if endpoint_columns:+ context += f"\nEndpoint version columns: {endpoint_columns}"+ else:+ execution_mode = "inline"+ context = (+ f"The query is executed on-demand against live data. "+ f"Common causes: invalid HogQL syntax, missing or renamed properties, query timeout, or incompatible variable overrides."+ )++ parts = [+ f"Endpoint '{endpoint.name}'{version_str} failed during {execution_mode} execution.",+ f"Error: {error_class}: {error_msg}",+ ]+ if query_kind:+ parts.append(f"Query kind: {query_kind}")+ if executed_sql:+ parts.append(f"Executed HogQL: {executed_sql}")+ parts.append(context)+ parts.append(f"Endpoint path: {endpoint.endpoint_path}")+ description = "\n".join(parts)++ async_to_sync(emit_signal)(+ team=team,+ source_product="endpoints",+ source_type="endpoint_execution_failed",+ source_id=f"{team.id}:{endpoint.name}",+ description=description,+ weight=0.5,+ extra={+ "endpoint_name": endpoint.name,+ "endpoint_version": version,+ "materialized": materialized,+ "saved_query_id": str(saved_query_id) if saved_query_id else None,+ "error_class": error_class,+ "error_message": error_msg,+ },+ )+ except Exception as signal_exc:+ logger.exception(+ "Failed to emit endpoint failure signal",+ endpoint_name=endpoint.name,+ team_id=team.id,+ signal_error_class=type(signal_exc).__name__,+ signal_error=str(signal_exc),+ )+ capture_exception(+ signal_exc,+ {+ "product": Product.ENDPOINTS,+ "team_id": team.id,+ "endpoint_name": endpoint.name,+ "signal_emission": True,+ },+ )+++def _endpoint_refresh_mode_to_refresh_type(+ mode: EndpointRefreshMode | None,+) -> RefreshType:+ """+ Map EndpointRefreshMode to RefreshType.++ - cache -> blocking+ - force/direct -> force_blocking (materialization bypass handled in should_use_materialized_table)+ """+ if mode is None or mode == EndpointRefreshMode.CACHE:+ return RefreshType.BLOCKING+ return RefreshType.FORCE_BLOCKING+++class EndpointExecutionService(PydanticModelMixin):+ """Executes an endpoint version, choosing the best execution path."""++ def __init__(self, team: Team, request: Request):+ self.team = team+ self.request = request++ # ------------------------------------------------------------------+ # Validation+ # ------------------------------------------------------------------++ @staticmethod+ def format_validation_detail(detail: object) -> str:+ """Flatten a DRF ValidationError detail into one line for logs."""+ if isinstance(detail, dict):+ return "; ".join(+ f"{field}: {EndpointExecutionService.format_validation_detail(messages)}"+ for field, messages in detail.items()+ )+ if isinstance(detail, list):+ return "; ".join(EndpointExecutionService.format_validation_detail(item) for item in detail)+ return str(detail)++ def log_rejected_run(self, endpoint: Endpoint, reason: str) -> None:+ log_endpoint_execution(+ team_id=self.team.pk,+ endpoint_id=str(endpoint.id),+ instance_id=str(uuid.uuid4()),+ level="ERROR",+ message=f"Endpoint execution failed · invalid request · {reason}",+ )++ def validate_run_request(+ self,+ data: EndpointRunRequest,+ endpoint: Endpoint,+ version: EndpointVersion,+ offset: int | None = None,+ ) -> None:+ strategy = strategy_for(endpoint, version, self.team)++ is_materialized = bool(version.is_materialized and version.saved_query)++ if not version.is_active:+ ENDPOINT_VALIDATION_ERROR_TOTAL.labels(reason="inactive_version").inc()+ raise ValidationError(f"Version {version.version} is inactive and cannot be executed.")++ # Reject query_override (always)+ if hasattr(data, "query_override") and data.query_override is not None:+ raise ValidationError({"query_override": "Not allowed. Use variables instead."})++ # Allow filters_override for insight endpoints (deprecated but backwards compatible)+ # Reject for HogQL endpoints+ if data.filters_override is not None:+ if strategy.query_kind == "HogQLQuery":+ raise ValidationError({"filters_override": "Not allowed for HogQL endpoints. Use variables instead."})++ if offset is not None and not strategy.supports_pagination:+ raise ValidationError({"offset": "offset is only supported for HogQL endpoints"})++ # Validate refresh mode+ if data.refresh == EndpointRefreshMode.DIRECT and not is_materialized:+ ENDPOINT_VALIDATION_ERROR_TOTAL.labels(reason="direct_refresh_not_materialized").inc()+ raise ValidationError(+ {+ "refresh": "'direct' refresh mode is only valid for materialized endpoints. "+ "Use 'cache' or 'force' instead, or enable materialization on this endpoint."+ }+ )++ # Validate variables+ if data.variables:+ allowed_vars = strategy.allowed_variables(is_materialized)+ unknown_vars = set(data.variables.keys()) - allowed_vars+ if unknown_vars:+ ENDPOINT_VALIDATION_ERROR_TOTAL.labels(reason="unknown_variable").inc()+ raise ValidationError({"variables": f"Unknown variable(s): {', '.join(sorted(unknown_vars))}"})++ # SECURITY: For materialized endpoints with required variables, ALL must be provided.+ # Without this check, omitting variables would return ALL data instead of filtered data.+ # filters_override (deprecated) only counts when it actually applies the breakdown filter —+ # a property with no usable value adds no WHERE clause and must not bypass this check.+ if is_materialized and not strategy.materialized_filters_override_satisfies_required(data):+ required_vars = strategy.required_materialized_variables()+ if required_vars:+ provided = {key for key, value in (data.variables or {}).items() if value is not None}+ missing = sorted(required_vars - provided)+ if missing:+ ENDPOINT_VALIDATION_ERROR_TOTAL.labels(reason="missing_required_variable").inc()+ raise ValidationError(+ {"variables": f"Required variable(s) {', '.join(repr(v) for v in missing)} not provided"}+ )++ # ------------------------------------------------------------------+ # Execution path selection+ # ------------------------------------------------------------------++ def should_use_materialized_table(+ self, endpoint: Endpoint, data: EndpointRunRequest, version: EndpointVersion+ ) -> bool:+ """+ Decide whether to use materialized table or inline execution.++ Reads materialization state from the DB — the authoritative source. (The redis+ "materialization ready" cache in rate_limit.py only classifies requests for+ throttling and is intentionally not consulted here.)++ Returns False if:+ - Not materialized+ - Materialization incomplete/failed+ - Materialized data is stale (older than sync frequency)+ - User overrides present (variables, query)+ - 'direct' mode requested (explicitly bypass materialization)+ """+ 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:+ return False++ # Check if materialized data is stale+ if saved_query.last_run_at and saved_query.sync_frequency_interval:+ next_refresh_due = saved_query.last_run_at + saved_query.sync_frequency_interval+ if timezone.now() >= next_refresh_due:+ return False++ # 'direct' mode explicitly bypasses materialization to run the original query+ if data.refresh == EndpointRefreshMode.DIRECT:+ return False++ # Check if variables are valid for materialized execution+ if data.variables:+ strategy = strategy_for(endpoint, version, self.team)+ if not strategy.can_serve_variables_from_materialized(set(data.variables.keys())):+ return False++ return True++ def _should_use_ducklake(self, endpoint: Endpoint, version: EndpointVersion | None) -> bool:+ if version is None:+ return False+ if version.query.get("kind") != "HogQLQuery":+ return False++ ff_result = posthoganalytics.feature_enabled(+ "endpoints-ducklake-execution",+ str(self.team.uuid),+ groups={+ "organization": str(self.team.organization_id),+ "project": str(self.team.id),+ },+ group_properties={+ "organization": {"id": str(self.team.organization_id)},+ "project": {"id": str(self.team.id)},+ },+ only_evaluate_locally=True,+ send_feature_flag_events=False,+ )+ logger.info(+ "Ducklake FF evaluation",+ endpoint_name=endpoint.name,+ ff_result=ff_result,+ )+ if not ff_result:+ return False++ server = get_duckgres_server_for_organization(str(self.team.organization_id))+ if server is None:+ logger.info("Ducklake skip: no duckgres server", endpoint_name=endpoint.name, team_id=self.team.pk)+ return server is not None++ # ------------------------------------------------------------------+ # Top-level entry point+ # ------------------------------------------------------------------++ def execute(+ self,+ endpoint: Endpoint,+ data: EndpointRunRequest,+ version_obj: EndpointVersion | None,+ limit: int | None = None,+ offset: int | None = None,+ ) -> Response:+ """Run an endpoint version and return the HTTP response.++ Assumes the caller has resolved the version (or established that none was+ requested explicitly) and parsed limit/offset.+ """+ if version_obj is None:+ return Response(+ {"error": "No version found for this endpoint"},+ status=status.HTTP_404_NOT_FOUND,+ )++ try:+ self.validate_run_request(data, endpoint, version_obj, offset=offset)+ except ValidationError as exc:+ self.log_rejected_run(endpoint, self.format_validation_detail(exc.detail))+ raise++ report_user_action(+ cast("User | SyntheticUser", self.request.user),+ "endpoint executed",+ {+ "endpoint_id": str(endpoint.id),+ "endpoint_name": endpoint.name,+ "has_filters_override": bool(data.filters_override),+ "has_variables": bool(data.variables),+ "has_limit": data.limit is not None,+ "has_offset": data.offset is not None,+ "refresh_mode": data.refresh.value if data.refresh else None,+ "auth_method": "project_secret_api_key"+ if is_authenticated_via_project_secret_api_key(self.request)+ else "user",+ },+ team=self.team,+ analytics_props=get_request_analytics_properties(self.request),+ )++ # Check if we should use materialization for this version+ use_materialized = self.should_use_materialized_table(endpoint, data, version_obj)++ debug = data.debug or False+ execution_type: ExecutionType = "materialized" if use_materialized else "inline"+ query_kind_metric = query_kind_label(version_obj.query)+ execution_status: str | None = None+ execution_id = str(uuid.uuid4())+ error_label: str | None = None+ _start_time = time.monotonic()+ _duration = 0.0++ try:+ result: Response | None = None+ if use_materialized:+ try:+ result = self._execute_materialized_endpoint(+ endpoint, data, version=version_obj, debug=debug, limit=limit, offset=offset+ )+ except ConcurrencyLimitExceeded:+ raise+ except Exception:+ # Already logged/captured/signaled inside the materialized path. Serve the+ # request from the original query instead of failing — stale tables and+ # series drift self-heal on the next materialization run.+ execution_type = "materialized_fallback"+ result = None+ elif self._should_use_ducklake(endpoint, version_obj):+ try:+ result = self._execute_ducklake_endpoint(endpoint, version_obj.query.copy(), debug=debug)+ execution_type = "ducklake"+ except Exception:+ logger.warning(+ "DuckLake execution failed, falling back to inline",+ endpoint_name=endpoint.name,+ )+ ENDPOINT_DUCKLAKE_FALLBACK_TOTAL.inc()+ execution_type = "ducklake_fallback"+ result = None++ if result is None:+ result = self._execute_inline_endpoint(+ endpoint,+ data,+ version_obj.query.copy(),+ version=version_obj,+ debug=debug,+ limit=limit,+ offset=offset,+ )+ execution_status = "success"+ except (ExposedHogQLError, ExposedCHQueryError) as e:+ execution_status = "user_error"+ error_label = getattr(e, "code_name", None) or type(e).__name__+ logger.exception(+ "Endpoint execution failed",+ endpoint_name=endpoint.name,+ code_name=getattr(e, "code_name", None),+ )+ raise ValidationError("Query execution failed.", getattr(e, "code_name", None))+ except HogVMException:+ execution_status = "user_error"+ error_label = "HogVMException"+ logger.exception(+ "Endpoint execution failed (HogVM)",+ endpoint_name=endpoint.name,+ )+ raise ValidationError("Query execution failed: HogQL virtual machine error")+ except ResolutionError:+ execution_status = "user_error"+ error_label = "ResolutionError"+ logger.exception(+ "Endpoint resolution failed",+ endpoint_name=endpoint.name,+ )+ raise ValidationError("Query resolution failed: unable to resolve table or field references.")+ except ConcurrencyLimitExceeded:+ ENDPOINT_CONCURRENCY_REJECTED_TOTAL.labels(team_id=str(self.team.pk)).inc()+ raise Throttled(detail="Too many concurrent requests. Please try again later.")+ except Exception as e:+ execution_status = "error"+ error_label = type(e).__name__+ raise+ finally:+ if execution_status is not None:+ _duration = time.monotonic() - _start_time+ ENDPOINT_EXECUTION_DURATION_SECONDS.labels(+ execution_type=execution_type, query_kind=query_kind_metric+ ).observe(_duration)+ ENDPOINT_EXECUTION_TOTAL.labels(+ execution_type=execution_type, query_kind=query_kind_metric, status=execution_status+ ).inc()+ if execution_status in ("error", "user_error"):+ log_endpoint_execution(+ team_id=self.team.pk,+ endpoint_id=str(endpoint.id),+ instance_id=execution_id,+ level="ERROR",+ message=build_execution_message(+ succeeded=False,+ execution_type=execution_type,+ version=version_obj.version,+ error=error_label,+ ),+ )++ cache_outcome, result_row_count = self._record_result_metrics(result, execution_type, query_kind_metric)+ log_endpoint_execution(+ team_id=self.team.pk,+ endpoint_id=str(endpoint.id),+ instance_id=execution_id,+ level="INFO",+ message=build_execution_message(+ succeeded=True,+ execution_type=execution_type,+ cache_outcome=cache_outcome,+ duration_ms=round(_duration * 1000),+ rows=result_row_count,+ version=version_obj.version,+ ),+ )+ self._track_last_executed(endpoint, version_obj)++ if isinstance(result.data, dict):+ result.data["name"] = endpoint.name+ result.data["execution_id"] = execution_id+ result.data["endpoint_version"] = version_obj.version+ result.data["endpoint_version_created_at"] = version_obj.created_at.isoformat()++ return result++ def _record_result_metrics(+ self, result: Response, execution_type: str, query_kind_metric: str+ ) -> tuple[str | None, int | None]:+ cache_outcome: str | None = None+ result_row_count: int | None = None+ try:+ if isinstance(result.data, dict):+ # DuckLake bypasses the query result cache entirely — don't claim hit/miss for it.+ if execution_type != "ducklake":+ cache_outcome = "hit" if bool(result.data.get("is_cached")) else "miss"+ ENDPOINT_CACHE_RESULT_TOTAL.labels(+ execution_type=execution_type, query_kind=query_kind_metric, outcome=cache_outcome+ ).inc()++ results_value = result.data.get("results")+ if isinstance(results_value, list):+ result_row_count = len(results_value)+ if query_kind_metric == "hogql":+ ENDPOINT_HOGQL_RESULT_ROWS.labels(execution_type=execution_type).observe(result_row_count)+ except Exception:+ logger.debug("Failed to record endpoint result metrics", exc_info=True)+ return cache_outcome, result_row_count++ def _track_last_executed(self, endpoint: Endpoint, version_obj: EndpointVersion) -> None:+ """Record last execution time (30-minute granularity, API key calls only)."""+ if not is_api_key_access_method(get_query_tag_value("access_method")):+ return+ now = timezone.now()+ if endpoint.last_executed_at is None or (now - endpoint.last_executed_at > LAST_EXECUTED_THROTTLE):+ endpoint.last_executed_at = now+ endpoint.save(update_fields=["last_executed_at"])+ if version_obj.last_executed_at is None or (now - version_obj.last_executed_at > LAST_EXECUTED_THROTTLE):+ version_obj.last_executed_at = now+ version_obj.save(update_fields=["last_executed_at"])++ # ------------------------------------------------------------------+ # Materialized execution+ # ------------------------------------------------------------------++ def _execute_materialized_endpoint(+ self,+ endpoint: Endpoint,+ data: EndpointRunRequest,+ version: EndpointVersion,+ debug: bool = False,+ limit: int | None = None,+ offset: int | None = None,+ ) -> Response:+ """Execute against a materialized table in S3."""+ materialized_hogql_query = None+ query_kind = None+ saved_query = version.saved_query+ try:+ if not saved_query:+ raise ValidationError("No materialized query found for this endpoint")++ strategy = strategy_for(endpoint, version, self.team)+ query_kind = strategy.query_kind++ select_query, original_limit = strategy.build_materialized_select(table_name=saved_query.name)++ pagination: EndpointPagination | None = None++ # Only paginate flat-row HogQL results. Insight types get transformed+ # into nested structures where flat-row LIMIT/OFFSET is meaningless.+ if limit is not None and strategy.supports_pagination:+ pagination = EndpointPagination(limit=limit, offset=offset or 0, ceiling=original_limit)+ pagination.apply_to(select_query)++ deprecation_headers = strategy.apply_materialized_filters(select_query, data)++ materialized_hogql_query = HogQLQuery(+ query=select_query.to_hogql(),+ modifiers=HogQLQueryModifiers(useMaterializedViews=True),+ )++ refresh_type = _endpoint_refresh_mode_to_refresh_type(data.refresh)++ query_request_data = {+ "client_query_id": data.client_query_id,+ "name": f"{endpoint.name}_materialized",+ "refresh": refresh_type,+ "query": materialized_hogql_query.model_dump(),+ }++ extra_fields = {+ "endpoint_materialized": True,+ "endpoint_materialized_at": saved_query.last_run_at.isoformat() if saved_query.last_run_at else None,+ }+ tag_queries(+ 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 saved_query.last_run_at and version.data_freshness_seconds:+ remaining = (+ saved_query.last_run_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=saved_query.last_run_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,+ )++ if self._is_cache_stale(result, saved_query):+ 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,+ )++ if isinstance(result.data, dict):+ strategy.clean_response_sentinels(result.data)++ try:+ strategy.transform_materialized_response(result.data, saved_query)+ except MaterializedSeriesMismatchError:+ # Series drift: query was likely edited after materialization. Trigger a refresh+ # so future materialized reads succeed; the caller serves this request inline.+ logger.warning(+ "Materialized endpoint series mismatch, triggering re-materialization",+ endpoint_name=endpoint.name,+ saved_query_id=saved_query.id,+ )+ trigger_saved_query_schedule(saved_query)+ raise++ # Freshness relative to the configured target: >1.0 means behind SLA.+ # Absolute age is meaningless across endpoints with different frequencies.+ if saved_query.last_run_at and version.data_freshness_seconds:+ age_seconds = max((timezone.now() - saved_query.last_run_at).total_seconds(), 0.0)+ ENDPOINT_MATERIALIZED_FRESHNESS_RATIO.observe(age_seconds / version.data_freshness_seconds)++ return result+ except Exception as e:+ logger.exception(+ "Materialized endpoint execution failed",+ endpoint_name=endpoint.name,+ saved_query_id=saved_query.id if saved_query else None,+ saved_query_status=saved_query.status if saved_query else None,+ )+ capture_exception(+ e,+ {+ "product": Product.ENDPOINTS,+ "team_id": self.team.pk,+ "endpoint_name": endpoint.name,+ "materialized": True,+ "saved_query_id": saved_query.id if saved_query else None,+ },+ )+ _emit_endpoint_failure_signal(+ self.team,+ endpoint,+ e,+ materialized=True,+ version=version.version,+ saved_query_id=saved_query.id if saved_query else None,+ query_kind=query_kind,+ executed_sql=materialized_hogql_query.query if materialized_hogql_query else None,+ saved_query_status=saved_query.status if saved_query else None,+ saved_query_last_run_at=(+ saved_query.last_run_at.isoformat() if saved_query and saved_query.last_run_at else None+ ),+ saved_query_columns=saved_query.columns if saved_query else None,+ endpoint_columns=version.columns,+ )+ raise++ def _is_cache_stale(self, result: Response, saved_query) -> bool:+ """Check if cached result is older than the materialization."""+ if not isinstance(result.data, dict) or not result.data.get("is_cached"):+ return False++ last_refresh = result.data.get("last_refresh")+ if not last_refresh or not saved_query.last_run_at:+ return False++ if isinstance(last_refresh, str):+ last_refresh = isoparse(last_refresh)++ return last_refresh < saved_query.last_run_at++ # ------------------------------------------------------------------+ # Inline + DuckLake execution+ # ------------------------------------------------------------------++ def _execute_inline_endpoint(+ self,+ endpoint: Endpoint,+ data: EndpointRunRequest,+ query: dict,+ version: EndpointVersion,+ debug: bool = False,+ limit: int | None = None,+ offset: int | None = None,+ ) -> Response:+ """Execute query directly against ClickHouse."""+ strategy: EndpointQueryStrategy | None = None+ try:+ strategy = strategy_for(endpoint, version, self.team)++ query = strategy.prepare_inline_query(query)++ pagination: EndpointPagination | None = None+ if limit is not None:+ query, pagination = strategy.apply_pagination(query, limit, offset or 0)++ refresh_type = _endpoint_refresh_mode_to_refresh_type(data.refresh)++ plan = strategy.build_inline_plan(query, data)++ query_request_data = {+ "client_query_id": data.client_query_id,+ "filters_override": plan.filters_override.model_dump() if plan.filters_override else None,+ "name": endpoint.name,+ "refresh": refresh_type,+ "query": query,+ }++ cache_age = version.data_freshness_seconds+ tag_queries(endpoint_version=version.version)++ result = self._execute_query_and_respond(+ query_request_data,+ data.client_query_id,+ variables_override=plan.variables_override,+ cache_age_seconds=cache_age,+ debug=debug,+ headers=plan.deprecation_headers,+ pagination=pagination,+ )++ if isinstance(result.data, dict):+ strategy.clean_response_sentinels(result.data)++ return result++ except Exception as e:+ self.handle_column_ch_error(e)+ logger.exception(+ "Inline endpoint execution failed",+ endpoint_name=endpoint.name,+ )+ capture_exception(+ e,+ {+ "product": Product.ENDPOINTS,+ "team_id": self.team.pk,+ "materialized": False,+ "endpoint_name": endpoint.name,+ },+ )+ query_kind = strategy.query_kind if strategy else query.get("kind")+ _emit_endpoint_failure_signal(+ self.team,+ endpoint,+ e,+ materialized=False,+ version=version.version,+ query_kind=query_kind,+ executed_sql=query.get("query") if query_kind == "HogQLQuery" else None,+ endpoint_columns=version.columns,+ )+ raise++ def _execute_ducklake_endpoint(+ self,+ endpoint: Endpoint,+ query: dict,+ debug: bool = False,+ ) -> Response:+ from posthog.ducklake.client import execute_ducklake_query++ try:+ result = execute_ducklake_query(+ self.team.pk,+ query=HogQLQuery(query=query["query"]),+ organization_id=str(self.team.organization_id),+ )+ response_data: dict = {+ "results": result.results,+ "columns": result.columns,+ "types": result.types,+ "hasMore": False,+ "backend": "ducklake",+ }+ if debug:+ response_data["query"] = query.get("query")+ response_data["hogql"] = result.hogql+ response_data["ducklake_sql"] = result.sql+ return Response(response_data, status=status.HTTP_200_OK)+ except Exception as e:+ logger.exception(+ "DuckLake endpoint execution failed",+ endpoint_name=endpoint.name,+ )+ capture_exception(+ e,+ {+ "product": Product.ENDPOINTS,+ "team_id": self.team.pk,+ "ducklake": True,+ "endpoint_name": endpoint.name,+ },+ )+ raise++ # ------------------------------------------------------------------+ # Query service plumbing+ # ------------------------------------------------------------------++ def _is_interactive_session(self) -> bool:+ """Whether this request came from the PostHog UI (session auth) rather than a+ programmatic credential (personal API key, OAuth, project secret API key, ...).++ Same idiom as get_event_source (posthog/event_usage.py) minus its session-cookie+ fallback, which could misclassify API-key requests sent from a logged-in browser.+ """+ return isinstance(getattr(self.request, "successful_authenticator", None), SessionAuthentication)++ def _execute_query_and_respond(+ self,+ query_request_data: dict,+ client_query_id: str | None,+ variables_override: list[HogQLVariable] | None = None,+ cache_age_seconds: int | None = None,+ extra_result_fields: dict | None = None,+ debug: bool = False,+ headers: dict[str, str] | None = None,+ pagination: EndpointPagination | None = None,+ ) -> Response:+ """Shared query execution logic."""+ merged_data = self.get_model(query_request_data, QueryRequest)++ query, client_query_id, execution_mode = _process_query_request(+ merged_data, self.team, client_query_id, self.request.user+ )+ self._tag_client_query_id(client_query_id)+ endpoint_feature = Feature.ENDPOINT_PLAYGROUND if self._is_interactive_session() else Feature.ENDPOINT_EXECUTION+ tag_queries(product=Product.ENDPOINTS, feature=endpoint_feature)++ result = process_query_model(+ self.team,+ query,+ variables_override=variables_override,+ execution_mode=execution_mode,+ query_id=client_query_id,+ user=cast(User, self.request.user),+ is_query_service=is_api_key_access_method(get_query_tag_value("access_method")),+ cache_age_seconds=cache_age_seconds,+ analytics_props=get_request_analytics_properties(self.request),+ )++ if isinstance(result, BaseModel):+ result = result.model_dump(by_alias=True)++ if isinstance(result, dict) and extra_result_fields:+ result.update(extra_result_fields)++ if not debug:+ debug_fields_to_remove = [+ "calculation_trigger",+ "cache_key",+ "explain",+ "modifiers",+ "resolved_date_range",+ "timings",+ "hogql",+ ]++ for field in debug_fields_to_remove:+ result.pop(field, None)++ if pagination and "results" in result:+ pagination.process_results(result)+ elif "results" in result:+ result["hasMore"] = False++ if "results" in result:+ result = {"results": result.pop("results"), **result}++ return Response(result, status=status.HTTP_200_OK, headers=headers)++ def handle_column_ch_error(self, error) -> None:+ if getattr(error, "message", None):+ match = re.search(r"There's no column.*in table", error.message)+ if match:+ # TODO: remove once we support all column types+ raise ValidationError(match.group(0) + ". Not all column types are fully supported yet.")+ return++ def _tag_client_query_id(self, query_id: str | None) -> None:+ if query_id is None:+ return++ tag_queries(client_query_id=query_id)diff --git a/products/endpoints/backend/services/materialization.py b/products/endpoints/backend/services/materialization.pynew file mode 100644index 000000000000..537c37629c35--- /dev/null+++ b/products/endpoints/backend/services/materialization.py@@ -0,0 +1,426 @@+"""Materialization lifecycle for endpoint versions.++``EndpointMaterializationService`` owns enabling/disabling materialization+(creating and reverting the backing ``DataWarehouseSavedQuery``), the+materialization preview, and the status payload. The AST-level analysis and+query transforms live in ``products.endpoints.backend.materialization_transforms``.+"""++import dataclasses+from typing import cast++import structlog+from loginas.utils import is_impersonated_session+from rest_framework.exceptions import APIException, ValidationError+from rest_framework.request import Request++from posthog.hogql import ast+from posthog.hogql.context import HogQLContext+from posthog.hogql.parser import parse_select+from posthog.hogql.printer import to_printed_hogql+from posthog.hogql.printer.utils import print_prepared_ast++from posthog.clickhouse.query_tagging import Product+from posthog.exceptions_capture import capture_exception+from posthog.models import Team, User+from posthog.models.activity_logging.activity_log import Detail, log_activity++from products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery+from products.data_modeling.backend.services.saved_query_dag_sync import delete_node_from_dag, sync_saved_query_to_dag+from products.endpoints.backend.constants import DATA_FRESHNESS_BUCKETS+from products.endpoints.backend.materialization_transforms import (+ _extract_aggregate_name,+ analyze_variables_for_materialization,+ build_endpoint_hogql,+ convert_insight_query_to_hogql,+ get_reaggregation,+ transform_query_for_materialization,+)+from products.endpoints.backend.metrics import ENDPOINT_MATERIALIZATION_EVENT_TOTAL+from products.endpoints.backend.models import Endpoint, EndpointVersion+from products.endpoints.backend.rate_limit import clear_endpoint_materialization_cache+from products.endpoints.backend.services.activity import EndpointContext+from products.endpoints.backend.services.strategies import apply_where_filter, strategy_for+from products.warehouse_sources.backend.models.external_data_schema import sync_frequency_to_sync_frequency_interval++logger = structlog.get_logger(__name__)+++class OrphanedEndpointSavedQueryError(Exception):+ pass+++def prepare_executable_query(saved_query: DataWarehouseSavedQuery) -> None:+ """Rebuild the saved query's executable HogQL from its endpoint version.++ Called by the data-modeling Temporal workflow before each materialization run,+ so query-printer changes and bucket overrides are always reflected.+ """+ version = saved_query.endpoint_versions.first()+ if version is None:+ raise OrphanedEndpointSavedQueryError(+ f"Saved query {saved_query.id} ({saved_query.name}) has no linked EndpointVersion"+ )++ saved_query.query = build_endpoint_hogql(version.query, saved_query.team, bucket_overrides=version.bucket_overrides)+ saved_query.save(update_fields=["query", "updated_at"])+++def build_materialization_info(version: EndpointVersion, endpoint_name: str | None = None) -> dict:+ """Build the materialization status dict for a version."""+ if version.saved_query:+ result = {+ "status": version.saved_query.status or "Unknown",+ "can_materialize": True,+ "last_materialized_at": (+ version.saved_query.last_run_at.isoformat() if version.saved_query.last_run_at else None+ ),+ "error": (version.saved_query.latest_error or "")+ if version.saved_query.status != DataWarehouseSavedQuery.Status.COMPLETED+ else "",+ "saved_query_id": str(version.saved_query.id),+ }+ else:+ can_mat, reason = version.can_materialize()+ result = {+ "can_materialize": can_mat,+ "reason": reason if not can_mat else None,+ }++ if endpoint_name is not None:+ result["name"] = endpoint_name+ return result++[email protected](frozen=True)+class MaterializationPreview:+ """Payload of the materialization-preview endpoint."""++ can_materialize: bool+ reason: str | None = None+ transformed_query: str | None = None+ execution_query: str | None = None+ display_execution_query: str | None = None+ range_pairs: list[dict] = dataclasses.field(default_factory=list)+ aggregates: list[dict] = dataclasses.field(default_factory=list)++ @classmethod+ def cant_materialize(cls, reason: str) -> "MaterializationPreview":+ return cls(can_materialize=False, reason=reason)+++class EndpointMaterializationService:+ """Enable, disable, and preview materialization for endpoint versions."""++ def __init__(self, team: Team, request: Request):+ self.team = team+ self.request = request+ self.user = cast(User, request.user)++ def enable_materialization(+ self,+ endpoint: Endpoint,+ version: EndpointVersion,+ data_freshness_seconds: int,+ bucket_overrides: dict[str, str] | None = None,+ ) -> None:+ """Enable materialization for an endpoint version.++ Each version gets its own saved_query named {endpoint_name}_v{version}.+ """+ try:+ self._enable_materialization_inner(endpoint, version, data_freshness_seconds, bucket_overrides)+ 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_session(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),+ ),+ )+ except ValidationError:+ ENDPOINT_MATERIALIZATION_EVENT_TOTAL.labels(action="enable", status="validation_error").inc()+ raise+ except Exception:+ ENDPOINT_MATERIALIZATION_EVENT_TOTAL.labels(action="enable", status="error").inc()+ # Not a request-validation problem — surface as a server error, not a 400.+ raise APIException("Failed to enable materialization.")++ def _enable_materialization_inner(+ self,+ endpoint: Endpoint,+ version: EndpointVersion,+ data_freshness_seconds: int,+ bucket_overrides: dict[str, str] | None = None,+ ) -> None:+ can_mat, reason = version.can_materialize()+ if not can_mat:+ raise ValidationError(f"Cannot materialize endpoint. Reason: {reason}")++ saved_query = self._get_or_build_saved_query(version)+ self._configure_saved_query(saved_query, version, data_freshness_seconds, bucket_overrides)+ version.enable_materialization(saved_query, bucket_overrides)++ # NOTE: schedule_materialization only triggers an immediate run when it CREATES the+ # Temporal schedule; re-enabling an existing materialization just (re)syncs the schedule.+ saved_query.schedule_materialization()++ try:+ sync_saved_query_to_dag(saved_query)+ except Exception as e:+ logger.exception(+ "Failed to sync endpoint node to DAG",+ endpoint_name=endpoint.name,+ saved_query_id=saved_query.id,+ )+ capture_exception(+ e,+ {+ "product": Product.ENDPOINTS,+ "team_id": self.team.pk,+ "endpoint_name": endpoint.name,+ "saved_query_id": saved_query.id,+ },+ )++ def _get_or_build_saved_query(self, version: EndpointVersion) -> DataWarehouseSavedQuery:+ """Find this version's saved query, or build a new (unsaved) one.++ SECURITY: only adopt a saved query that this endpoint owns (ENDPOINT origin and not+ linked to a different version). Without this, a user-created saved query whose name+ happens to collide with {endpoint}_v{n} would be silently taken over — its query+ overwritten and served as the endpoint's data.+ """+ name = version.materialized_view_name+ existing = DataWarehouseSavedQuery.objects.filter(name=name, team=self.team, deleted=False).first()+ if existing is None:+ return DataWarehouseSavedQuery(+ name=name,+ team=self.team,+ origin=DataWarehouseSavedQuery.Origin.ENDPOINT,+ )++ is_foreign = existing.origin != DataWarehouseSavedQuery.Origin.ENDPOINT or (+ existing.endpoint_versions.exclude(pk=version.pk).exists()+ )+ if is_foreign:+ raise ValidationError(+ f"A saved query named '{name}' already exists and is not managed by this endpoint. "+ "Rename or delete it before enabling materialization."+ )+ return existing++ def _configure_saved_query(+ self,+ saved_query: DataWarehouseSavedQuery,+ version: EndpointVersion,+ data_freshness_seconds: int,+ bucket_overrides: dict[str, str] | None,+ ) -> None:+ """Point the saved query at the version's materializable HogQL and sync cadence."""+ saved_query.query = build_endpoint_hogql(version.query, self.team, bucket_overrides=bucket_overrides)+ saved_query.external_tables = saved_query.s3_tables+ saved_query.is_materialized = True+ saved_query.sync_frequency_interval = sync_frequency_to_sync_frequency_interval(+ DATA_FRESHNESS_BUCKETS[data_freshness_seconds]+ )+ saved_query.save()++ def disable_materialization(self, endpoint: Endpoint, version: EndpointVersion) -> None:+ """Disable materialization for an endpoint version."""+ if version.saved_query:+ saved_query_id = str(version.saved_query.id)+ saved_query_name = version.saved_query.name+ try:+ delete_node_from_dag(version.saved_query)+ except Exception as e:+ logger.exception(+ "Failed to remove endpoint node from DAG",+ endpoint_name=endpoint.name,+ saved_query_id=saved_query_id,+ )+ capture_exception(+ e,+ {+ "product": Product.ENDPOINTS,+ "team_id": self.team.pk,+ "endpoint_name": endpoint.name,+ "saved_query_id": saved_query_id,+ },+ )+ try:+ version.disable_materialization()+ except Exception:+ ENDPOINT_MATERIALIZATION_EVENT_TOTAL.labels(action="disable", status="error").inc()+ raise+ ENDPOINT_MATERIALIZATION_EVENT_TOTAL.labels(action="disable", status="success").inc()+ log_activity(+ organization_id=self.team.organization_id,+ team_id=self.team.pk,+ user=self.user,+ was_impersonated=is_impersonated_session(self.request),+ item_id=saved_query_id,+ scope="DataWarehouseSavedQuery",+ activity="materialization_disabled",+ detail=Detail(+ name=saved_query_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,+ endpoint: Endpoint,+ version: EndpointVersion,+ bucket_overrides: dict[str, str] | None = None,+ ) -> MaterializationPreview:+ """Preview the materialization transform without enabling it."""+ can_mat, reason = version.can_materialize()+ if not can_mat:+ return MaterializationPreview.cant_materialize(reason)++ hogql_query = convert_insight_query_to_hogql(version.query, self.team)++ range_pairs: list[dict] = []+ aggregates: list[dict] = []+ transformed_query_str: str | None = None+ variable_infos: list = []++ if version.query.get("variables"):+ can_materialize_vars, var_reason, variable_infos = analyze_variables_for_materialization(+ version.query, bucket_overrides=bucket_overrides+ )++ if not can_materialize_vars:+ return MaterializationPreview.cant_materialize(var_reason)++ if variable_infos:+ transformed = transform_query_for_materialization(+ hogql_query, variable_infos, self.team, bucket_overrides=bucket_overrides+ )+ transformed_query_str = transformed.get("query")++ # Extract range pairs grouped by column+ seen_columns: dict[str, dict] = {}+ for v in variable_infos:+ if v.bucket_fn is not None:+ col_key = ".".join(v.column_chain) if v.column_chain else v.column_expression+ if col_key not in seen_columns:+ seen_columns[col_key] = {+ "column": col_key,+ "variables": [],+ "bucket_fn": v.bucket_fn,+ }+ seen_columns[col_key]["variables"].append(v.code_name)+ range_pairs = list(seen_columns.values())++ query_str = hogql_query.get("query", "")+ if query_str:+ try:+ parsed = parse_select(query_str)+ except Exception as e:+ # Preview degrades (no aggregate re-aggregation info), the request succeeds.+ logger.warning(+ "materialization_preview: converted HogQL failed to parse; "+ "skipping aggregate re-aggregation preview",+ endpoint_name=endpoint.name,+ team_id=self.team.pk,+ )+ capture_exception(+ e,+ {+ "product": Product.ENDPOINTS,+ "team_id": self.team.pk,+ "endpoint_name": endpoint.name,+ "materialization_preview": True,+ },+ )+ else:+ if isinstance(parsed, ast.SelectQuery) and parsed.select:+ for expr in parsed.select:+ agg_name = _extract_aggregate_name(expr)+ if agg_name:+ reagg_info = get_reaggregation(agg_name)+ reagg = reagg_info.reaggregate_fn if reagg_info else None+ if isinstance(expr, ast.Alias):+ label = expr.alias+ else:+ label = expr.to_hogql()+ aggregates.append(+ {+ "expression": label,+ "reaggregate_fn": reagg,+ }+ )+ else:+ # No variables — just show the converted query as-is+ transformed_query_str = hogql_query.get("query")++ # Build the execution query preview — what runs at request time against the materialized table+ execution_query_str: str | None = None+ display_execution_query_str: str | None = None+ try:+ strategy = strategy_for(endpoint, version, self.team)++ def _build_exec_preview(table_name: str) -> ast.SelectQuery:+ q, _ = strategy.build_materialized_select(+ table_name=table_name,+ variable_infos=variable_infos or None,+ )+ for v in variable_infos:+ apply_where_filter(+ q,+ v.code_name,+ f"{{variables.{v.code_name}}}",+ op=v.operator,+ value_wrapper_fns=v.value_wrapper_fns,+ bucket_fn=v.bucket_fn,+ )+ return q++ # Each call builds a fresh SelectQuery, so WHERE mutations don't leak between calls+ execution_query_str = to_printed_hogql(_build_exec_preview(version.materialized_view_name), team=self.team)++ # Display variant uses the friendly endpoint name — printed without type resolution+ # since the friendly name isn't a real table in the database+ display_execution_query_str = print_prepared_ast(+ node=_build_exec_preview(endpoint.name),+ context=HogQLContext(team_id=self.team.pk, enable_select_queries=True),+ dialect="hogql",+ pretty=True,+ )+ except Exception as e:+ logger.warning(+ "Failed to build materialization execution query preview",+ endpoint_name=endpoint.name,+ team_id=self.team.pk,+ exc_info=True,+ )+ capture_exception(+ e,+ {+ "product": Product.ENDPOINTS,+ "team_id": self.team.pk,+ "endpoint_name": endpoint.name,+ "materialization_preview": True,+ },+ )++ return MaterializationPreview(+ can_materialize=True,+ transformed_query=transformed_query_str,+ execution_query=execution_query_str,+ display_execution_query=display_execution_query_str,+ range_pairs=range_pairs,+ aggregates=aggregates,+ )diff --git a/products/endpoints/backend/services/pagination.py b/products/endpoints/backend/services/pagination.pynew file mode 100644index 000000000000..541debf1bfa6--- /dev/null+++ b/products/endpoints/backend/services/pagination.py@@ -0,0 +1,34 @@+import dataclasses++from posthog.hogql import ast++[email protected](frozen=True)+class EndpointPagination:+ limit: int+ offset: int+ ceiling: int | None++ def apply_to(self, select_query: ast.SelectQuery) -> None:+ """Set LIMIT and OFFSET on an AST SelectQuery for pagination."""+ if self.ceiling is not None and self.offset >= self.ceiling:+ select_query.limit = ast.Constant(value=0)+ select_query.offset = ast.Constant(value=0)+ else:+ remaining = (self.ceiling - self.offset) if self.ceiling is not None else None+ effective_limit = min(self.limit, remaining) if remaining is not None else self.limit+ select_query.limit = ast.Constant(value=effective_limit + 1)+ if self.offset > 0:+ select_query.offset = ast.Constant(value=self.offset)++ def process_results(self, result: dict) -> None:+ """Trim the extra row and annotate the result dict with pagination metadata."""+ rows = result.get("results", [])+ has_more = len(rows) > self.limit+ if has_more:+ result["results"] = rows[: self.limit]+ if self.ceiling is not None and self.offset + len(result["results"]) >= self.ceiling:+ has_more = False+ result["hasMore"] = has_more+ result["limit"] = self.limit+ result["offset"] = self.offsetdiff --git a/products/endpoints/backend/services/strategies.py b/products/endpoints/backend/services/strategies.pynew file mode 100644index 000000000000..19c7a29f06b7--- /dev/null+++ b/products/endpoints/backend/services/strategies.py@@ -0,0 +1,826 @@+"""Query-kind strategies for endpoints.++Endpoints execute one of two families of queries, each with its own rules for+variables, materialized-table filtering, pagination, and response shaping:++- ``HogQLEndpointStrategy``: raw HogQL queries with ``{variables.x}`` placeholders.+- ``InsightEndpointStrategy``: insight queries (Trends/Funnels/...) where breakdown+ properties act as variables and responses need re-shaping after materialized reads.++Everything that branches on ``query["kind"]`` belongs here, behind the shared+``EndpointQueryStrategy`` interface, so the execution and materialization services+stay kind-agnostic.+"""++import abc+import dataclasses+from collections.abc import Iterator+from functools import cached_property+from typing import TYPE_CHECKING, ClassVar, Optional++import structlog+from asgiref.sync import async_to_sync+from rest_framework.exceptions import ValidationError++from posthog.schema import DashboardFilter, EndpointRunRequest, HogQLVariable, PropertyOperator++from posthog.hogql import ast+from posthog.hogql.context import HogQLContext+from posthog.hogql.errors import QueryError+from posthog.hogql.parser import parse_expr, parse_select+from posthog.hogql.printer.hogql import HogQLPrinter+from posthog.hogql.visitor import CloningVisitor++from posthog.clickhouse.query_tagging import Product+from posthog.exceptions_capture import capture_exception+from posthog.hogql_queries.insights.utils.breakdowns import BREAKDOWN_NULL_STRING_LABEL, BREAKDOWN_OTHER_STRING_LABEL+from posthog.models.team import Team++from products.endpoints.backend.insight_transformers import transform_materialized_insight_response+from products.endpoints.backend.materialization_transforms import (+ ENDPOINT_BREAKDOWN_LIMIT,+ MaterializableVariable,+ analyze_variables_for_materialization,+ prepare_insight_query_for_endpoint,+ transform_select_for_materialized_table,+)+from products.endpoints.backend.models import Endpoint, EndpointVersion+from products.endpoints.backend.services.pagination import EndpointPagination++if TYPE_CHECKING:+ from products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery++logger = structlog.get_logger(__name__)++# Query types that support user-configurable breakdown filtering+BREAKDOWN_SUPPORTED_QUERY_TYPES: frozenset[str] = frozenset({"TrendsQuery", "RetentionQuery"})+++# ---------------------------------------------------------------------------+# Shared AST helpers+# ---------------------------------------------------------------------------+++def add_where_condition(select_query: ast.SelectQuery, condition: ast.Expr) -> None:+ """Append a condition to select_query.where with AND."""+ if select_query.where:+ select_query.where = ast.And(exprs=[select_query.where, condition])+ else:+ select_query.where = condition+++def apply_where_filter(+ select_query: ast.SelectQuery,+ column: str,+ value: str,+ op: ast.CompareOperationOp = ast.CompareOperationOp.Eq,+ value_wrapper_fns: list[str] | None = None,+ bucket_fn: str | None = None,+) -> None:+ """Add a comparison filter to WHERE clause.++ When bucket_fn is set (range variables), wrap the filter value with the+ bucket function so the comparison matches the bucketed column values.+ """+ right_expr: ast.Expr = ast.Constant(value=value)+ for fn in reversed(value_wrapper_fns or []):+ right_expr = ast.Call(name=fn, args=[right_expr])+ if bucket_fn:+ right_expr = ast.Call(name=bucket_fn, args=[ast.Call(name="toDateTime", args=[right_expr])])+ condition = ast.CompareOperation(+ left=ast.Field(chain=[column]),+ op=op,+ right=right_expr,+ )+ add_where_condition(select_query, condition)+++class PlaceholderPreservingPrinter(HogQLPrinter):+ """HogQL printer that preserves {placeholder} syntax instead of raising on unresolved placeholders."""++ def visit_placeholder(self, node: ast.Placeholder) -> str:+ if node.field is None:+ raise QueryError("You can not use placeholders here")+ return f"{{{node.field}}}"+++# ---------------------------------------------------------------------------+# Breakdown helpers (insight queries)+# ---------------------------------------------------------------------------+++def iter_breakdowns(breakdown_filter: dict) -> Iterator[tuple[str, str]]:+ """Yield (property_name, property_type) from legacy or new breakdown format.++ Legacy: {"breakdown": "$browser", "breakdown_type": "event"}+ New: {"breakdowns": [{"property": "$browser", "type": "event"}]}+ """+ breakdown = breakdown_filter.get("breakdown")+ if breakdown:+ yield (breakdown, breakdown_filter.get("breakdown_type", "event"))+ return+ for b in breakdown_filter.get("breakdowns") or []:+ prop = b.get("property")+ if prop:+ yield (prop, b.get("type", "event"))+++def get_breakdown_properties(breakdown_filter: dict) -> list[str]:+ """Extract all breakdown property names from either legacy or new format."""+ return [name for name, _ in iter_breakdowns(breakdown_filter)]+++def get_breakdown_column_indices(breakdown_filter: dict) -> dict[str, int]:+ """Map breakdown property names to their 1-based index in the breakdown_value array.++ Single breakdown: {"$browser": 0} (0 means use the whole array, not an index)+ Multiple breakdowns: {"$browser": 1, "$os": 2}+ """+ props = get_breakdown_properties(breakdown_filter)+ if len(props) <= 1:+ return {props[0]: 0} if props else {}+ return {prop: i + 1 for i, prop in enumerate(props)}+++def get_breakdown_infos(breakdown_filter: dict) -> list[tuple[str, str]]:+ """Extract all breakdown (property_name, property_type) pairs."""+ return list(iter_breakdowns(breakdown_filter))+++def build_breakdown_filter_condition(query_kind: str | None, value: str, array_index: int = 0) -> ast.Expr | None:+ """Build the appropriate WHERE condition for breakdown filtering based on query type.++ Different insight types store breakdowns in different columns:+ - TrendsQuery, RetentionQuery: `breakdown_value` Array column+ - LifecycleQuery: No breakdown support++ array_index controls how to access the breakdown column:+ - 0: single breakdown — use has() on the full array+ - 1+: multiple breakdowns — use equality on breakdown_value[N]+ """+ if query_kind not in BREAKDOWN_SUPPORTED_QUERY_TYPES:+ logger.warning(+ "Query type does not support breakdown filtering",+ query_kind=query_kind,+ )+ return None++ if array_index > 0:+ return ast.CompareOperation(+ left=ast.ArrayAccess(+ array=ast.Field(chain=["breakdown_value"]),+ property=ast.Constant(value=array_index),+ ),+ op=ast.CompareOperationOp.Eq,+ right=ast.Constant(value=value),+ )++ return ast.Call(+ name="has",+ args=[ast.Field(chain=["breakdown_value"]), ast.Constant(value=value)],+ )+++# ---------------------------------------------------------------------------+# Breakdown sentinel cleaning (response post-processing)+# ---------------------------------------------------------------------------+++def _value_contains_other(value: object, other_label: str) -> bool:+ """Check if a breakdown value contains the 'Other' sentinel."""+ if isinstance(value, str):+ return value == other_label+ if isinstance(value, list):+ return any(item == other_label for item in value if isinstance(item, str))+ return False+++def _clean_sentinel_value(value: object, clean_empty_string: bool) -> object:+ """Clean breakdown sentinel strings (null and other) in a value or list of values."""+ if isinstance(value, str):+ if value == BREAKDOWN_NULL_STRING_LABEL or (clean_empty_string and value == ""):+ return None+ if value == BREAKDOWN_OTHER_STRING_LABEL:+ return "Other"+ elif isinstance(value, list):+ return [_clean_sentinel_value(item, clean_empty_string) for item in value]+ return value+++def _clean_sentinel_label(label: object) -> object:+ """Clean a label string containing ::-joined breakdown parts."""+ if not isinstance(label, str):+ return label+ if BREAKDOWN_NULL_STRING_LABEL not in label and BREAKDOWN_OTHER_STRING_LABEL not in label:+ return label+ parts = label.split("::")+ cleaned = [+ "null" if p == BREAKDOWN_NULL_STRING_LABEL else "Other" if p == BREAKDOWN_OTHER_STRING_LABEL else p+ for p in parts+ ]+ return "::".join(cleaned)+++def clean_breakdown_sentinels(result: dict, clean_empty_string: bool) -> bool:+ """Replace breakdown sentinel strings in API response results in-place.++ Handles both list-of-lists (materialized/HogQL) and list-of-dicts (inline insight).+ ``clean_empty_string`` additionally rewrites plain '' to null — that's how null+ breakdown values are stored in materialized insight tables, but it must NOT be+ applied to arbitrary HogQL results where '' is a legitimate value.++ Returns True if the "Other" sentinel was found — meaning the breakdown_limit+ was exceeded; the caller decides how to report that.+ """+ rows = result.get("results")+ if not rows:+ return False++ found_other = False+ columns = result.get("columns")+ if columns:+ # HogQL/materialized path: results are list[tuple] or list[list]+ indices = [i for i, col in enumerate(columns) if col == "breakdown_value"]+ if not indices:+ return False+ for row_idx, row in enumerate(rows):+ needs_clean = any(isinstance(row[i], (str, list)) or row[i] is None for i in indices)+ if not needs_clean:+ continue+ if not found_other:+ found_other = any(_value_contains_other(row[i], BREAKDOWN_OTHER_STRING_LABEL) for i in indices)+ row_list = list(row)+ for i in indices:+ row_list[i] = _clean_sentinel_value(row_list[i], clean_empty_string)+ rows[row_idx] = type(row)(row_list)+ elif isinstance(rows[0], dict):+ # Inline insight path: results are list[dict]+ for row in rows:+ if "breakdown_value" in row:+ if not found_other:+ found_other = _value_contains_other(row["breakdown_value"], BREAKDOWN_OTHER_STRING_LABEL)+ row["breakdown_value"] = _clean_sentinel_value(row["breakdown_value"], clean_empty_string)+ if "label" in row:+ if not found_other and isinstance(row["label"], str):+ found_other = BREAKDOWN_OTHER_STRING_LABEL in row["label"]+ row["label"] = _clean_sentinel_label(row["label"])++ return found_other+++def _emit_breakdown_limit_signal(team: Team, endpoint: Endpoint) -> None:+ """Fire a Signal when the breakdown limit was exceeded ('Other' bucket in results).++ Fails silently — signal emission must never break the response.+ """+ from products.signals.backend.facade.api import emit_signal++ try:+ async_to_sync(emit_signal)(+ team=team,+ source_product="endpoints",+ source_type="endpoint_breakdown_limit_exceeded",+ source_id=f"{team.id}:{endpoint.name}",+ description=(+ f"Endpoint '{endpoint.name}' exceeded the breakdown limit ({ENDPOINT_BREAKDOWN_LIMIT}) — "+ f"an 'Other' bucket appeared in its results, so callers are seeing aggregated values "+ f"for the long tail instead of per-value rows. Consider a lower-cardinality breakdown "+ f"property or filtering the query.\nEndpoint path: {endpoint.endpoint_path}"+ ),+ weight=0.4,+ extra={+ "endpoint_name": endpoint.name,+ "breakdown_limit": ENDPOINT_BREAKDOWN_LIMIT,+ },+ )+ except Exception:+ logger.exception("Failed to emit breakdown-limit signal", endpoint_name=endpoint.name, team_id=team.id)+++# ---------------------------------------------------------------------------+# Strategy interface+# ---------------------------------------------------------------------------++FILTERS_OVERRIDE_DEPRECATION_HEADERS = {+ "X-PostHog-Warn": "filters_override is deprecated. Use variables instead: https://posthog.com/docs/api/endpoints"+}++[email protected](frozen=True)+class InlineExecutionPlan:+ """Overrides and response headers for executing the original query inline."""++ variables_override: list[HogQLVariable] | None = None+ filters_override: DashboardFilter | None = None+ deprecation_headers: dict[str, str] | None = None+++class EndpointQueryStrategy(abc.ABC):+ """Kind-specific behavior for an endpoint version's query."""++ supports_pagination: ClassVar[bool] = False+ supports_ducklake: ClassVar[bool] = False++ def __init__(self, endpoint: Endpoint, version: EndpointVersion, team: Team):+ self.endpoint = endpoint+ self.version = version+ self.team = team+ self.query: dict = version.query++ @property+ def query_kind(self) -> str | None:+ return self.query.get("kind")++ # --- variables ---++ @abc.abstractmethod+ def allowed_variables(self, is_materialized: bool) -> set[str]:+ """The set of variable names callers may pass to /run."""++ @abc.abstractmethod+ def required_materialized_variables(self) -> set[str]:+ """Variables that MUST be provided when running against the materialized table.++ SECURITY: materialized tables contain rows for every variable value; omitting+ a variable would return unfiltered data.+ """++ @abc.abstractmethod+ def can_serve_variables_from_materialized(self, requested: set[str]) -> bool:+ """Whether all requested variables can be answered by the materialized table."""++ def materialized_filters_override_satisfies_required(self, data: EndpointRunRequest) -> bool:+ """Whether ``data.filters_override`` actually supplies the required materialized filter.++ Only the insight strategy honors filters_override; for any other strategy a+ filters_override never satisfies the required-variable check.+ """+ return False++ # --- materialized execution ---++ @abc.abstractmethod+ def build_materialized_select(+ self,+ table_name: str,+ variable_infos: list[MaterializableVariable] | None = None,+ ) -> tuple[ast.SelectQuery, int | None]:+ """Build the base SELECT against the materialized table.++ Returns (select_query, original_limit) — caller is responsible for pagination.+ """++ @abc.abstractmethod+ def apply_materialized_filters(+ self, select_query: ast.SelectQuery, data: EndpointRunRequest+ ) -> dict[str, str] | None:+ """Apply variable/filter WHERE conditions to the materialized SELECT.++ Returns deprecation headers to attach to the response, if any.+ """++ @abc.abstractmethod+ def transform_materialized_response(self, response_data: dict, saved_query: "DataWarehouseSavedQuery") -> None:+ """Re-shape a materialized read into the inline response format."""++ @abc.abstractmethod+ def clean_response_sentinels(self, response_data: dict) -> None:+ """Rewrite internal breakdown sentinel strings in the response, in place."""++ # --- inline execution ---++ def prepare_inline_query(self, query: dict) -> dict:+ """Adjust the stored query before inline execution. Default: unchanged."""+ return query++ @abc.abstractmethod+ def build_inline_plan(self, query: dict, data: EndpointRunRequest) -> InlineExecutionPlan:+ """Translate request variables/filters into query-runner overrides."""++ def apply_pagination(self, query: dict, limit: int, offset: int) -> tuple[dict, EndpointPagination]:+ """Apply LIMIT/OFFSET pagination to the inline query. Raises for unsupported kinds."""+ raise ValidationError(+ {"limit": f"Limit/offset parameters are only supported for HogQLQuery, not {self.query_kind}"}+ )+++class HogQLEndpointStrategy(EndpointQueryStrategy):+ """Endpoints backed by a raw HogQL query with {variables.x} placeholders."""++ supports_pagination = True+ supports_ducklake = True++ @cached_property+ def materialized_variables(self) -> list[MaterializableVariable]:+ """The materializable variable infos for this query, or [] if not analyzable."""+ if not self.query or not self.query.get("variables"):+ return []++ try:+ can_materialize, _, variable_infos = analyze_variables_for_materialization(+ self.query, bucket_overrides=self.version.bucket_overrides+ )+ return variable_infos if can_materialize else []+ except Exception:+ logger.debug("Failed to analyze variables for materialization", exc_info=True)+ return []++ def allowed_variables(self, is_materialized: bool) -> set[str]:+ variables = self.query.get("variables", {})+ return {v.get("code_name") for v in variables.values() if v.get("code_name")} if variables else set()++ def required_materialized_variables(self) -> set[str]:+ return {v.code_name for v in self.materialized_variables}++ def can_serve_variables_from_materialized(self, requested: set[str]) -> bool:+ materialized_codes = {v.code_name for v in self.materialized_variables}+ if not materialized_codes:+ return False+ return requested.issubset(materialized_codes)++ def _parse_original_query(self) -> tuple[list | None, int | None, bool]:+ """Parse the original HogQL query and extract SELECT columns, LIMIT, and GROUP BY presence.++ Returns (materialized_columns, limit, has_group_by) where columns/limit may be None.+ materialized_columns is a list of MaterializedColumn with re-aggregation metadata.+ """+ query_str = self.query.get("query")+ if not query_str:+ return None, None, False++ try:+ parsed = parse_select(query_str)+ if isinstance(parsed, ast.SelectQuery):+ columns = (+ transform_select_for_materialized_table(list(parsed.select), self.team) if parsed.select else None+ )+ limit = parsed.limit.value if isinstance(parsed.limit, ast.Constant) else None+ has_group_by = bool(parsed.group_by)+ return columns, limit, has_group_by+ except Exception:+ logger.debug("Failed to parse original HogQL query", exc_info=True)++ return None, None, False++ def build_materialized_select(+ self,+ table_name: str,+ variable_infos: list[MaterializableVariable] | None = None,+ ) -> tuple[ast.SelectQuery, int | None]:+ """Build the base SELECT query against a materialized table.++ Wraps aggregate columns with their reaggregate_fn (e.g. sum("count()"))+ when needed to preserve SQL semantics. This happens in two cases:++ 1. Range variables (bucket_fn != None): multiple materialized rows must+ be collapsed back into one aggregate per group.+ 2. No GROUP BY + all-aggregate SELECT: without wrapping, an empty WHERE+ match returns 0 rows instead of the expected 1-row identity result+ (count→0, sum→0, min/max→type default). Wrapping restores the implicit+ single-group aggregate that SQL guarantees.++ Non-aggregate columns (GROUP BY dimensions) are passed through as-is and+ added to the GROUP BY clause.+ """+ select_columns: list[ast.Expr] = [ast.Field(chain=["*"])]+ group_by_columns: list[ast.Expr] = []++ original_select, original_limit, has_group_by = self._parse_original_query()+ mat_vars = variable_infos if variable_infos is not None else self.materialized_variables+ if mat_vars and original_select:+ has_range_vars = any(v.bucket_fn is not None for v in mat_vars)+ all_aggregates = all(col.is_aggregate and col.reaggregate_fn for col in original_select)+ needs_reaggregation = has_range_vars or (not has_group_by and all_aggregates)++ if needs_reaggregation:+ reagg_select: list[ast.Expr] = []+ for col in original_select:+ if col.is_aggregate and col.reaggregate_fn:+ reagg_select.append(ast.Call(name=col.reaggregate_fn, args=[col.expr]))+ else:+ reagg_select.append(col.expr)+ if not col.is_aggregate:+ group_by_columns.append(col.expr)+ select_columns = reagg_select+ else:+ select_columns = [col.expr for col in original_select]++ select_query = ast.SelectQuery(+ select=select_columns,+ select_from=ast.JoinExpr(table=ast.Field(chain=[table_name])),+ )++ if group_by_columns:+ select_query.group_by = [CloningVisitor().visit(c) for c in group_by_columns]++ if original_limit is not None:+ select_query.limit = ast.Constant(value=original_limit)++ return select_query, original_limit++ def transform_materialized_response(self, response_data: dict, saved_query: "DataWarehouseSavedQuery") -> None:+ """HogQL materialized rows are flat and returned as-is — no re-shaping needed."""+ return None++ def clean_response_sentinels(self, response_data: dict) -> None:+ """Clean sentinel literals only — plain '' is a legitimate HogQL value and stays."""+ clean_breakdown_sentinels(response_data, clean_empty_string=False)++ def apply_materialized_filters(+ self, select_query: ast.SelectQuery, data: EndpointRunRequest+ ) -> dict[str, str] | None:+ if not data.variables:+ return None+ for mat_var in self.materialized_variables:+ var_value = data.variables.get(mat_var.code_name)+ if var_value is not None:+ apply_where_filter(+ select_query,+ mat_var.code_name,+ var_value,+ op=mat_var.operator,+ value_wrapper_fns=mat_var.value_wrapper_fns,+ bucket_fn=mat_var.bucket_fn,+ )+ return None++ def build_inline_plan(self, query: dict, data: EndpointRunRequest) -> InlineExecutionPlan:+ if not data.variables:+ return InlineExecutionPlan()+ return InlineExecutionPlan(variables_override=self._parse_variables(query, data.variables))++ def _parse_variables(self, query: dict, variables: dict[str, str]) -> list[HogQLVariable] | None:+ query_variables = query.get("variables", None)+ if not query_variables:+ return None++ variables_override = []+ for request_variable_code_name, request_variable_value in variables.items():+ variable_id = None+ for query_variable_id, query_variable_value in query_variables.items():+ if query_variable_value.get("code_name", None) == request_variable_code_name:+ variable_id = query_variable_id++ if variable_id is None:+ raise ValidationError({"variables": f"Variable '{request_variable_code_name}' not found in query"})++ variables_override.append(+ HogQLVariable(+ variableId=variable_id,+ code_name=request_variable_code_name,+ value=request_variable_value,+ isNull=True if request_variable_value is None else None,+ )+ )+ return variables_override++ def apply_pagination(self, query: dict, limit: int, offset: int) -> tuple[dict, EndpointPagination]:+ """Apply pagination to a HogQL query.++ Parses the HogQL AST, applies LIMIT/OFFSET, and reprints using a+ placeholder-preserving printer so unresolved {variables.*} survive.+ """+ query_sql = query.get("query", "")+ parsed = parse_select(query_sql)+ if not isinstance(parsed, ast.SelectQuery):+ raise ValidationError(+ "Pagination is not supported for UNION queries. Wrap the UNION in a subquery: SELECT * FROM (... UNION ALL ...) LIMIT n"+ )++ ceiling = parsed.limit.value if isinstance(parsed.limit, ast.Constant) else None+ pagination = EndpointPagination(limit=limit, offset=offset, ceiling=ceiling)++ pagination.apply_to(parsed)++ ctx = HogQLContext(enable_select_queries=True, limit_top_select=False)+ query = query.copy()+ query["query"] = PlaceholderPreservingPrinter(context=ctx).visit(parsed)+ return query, pagination+++class InsightEndpointStrategy(EndpointQueryStrategy):+ """Endpoints backed by an insight query (Trends/Lifecycle/Retention/...).++ Breakdown properties act as variables; `filters_override` is the deprecated+ way to provide them. Materialized reads need re-shaping into the inline+ insight response format.+ """++ BREAKDOWN_SUPPORTED_QUERY_TYPES: ClassVar[frozenset[str]] = BREAKDOWN_SUPPORTED_QUERY_TYPES+ # Query types with a materialized-response transformer+ INSIGHT_TRANSFORM_TYPES: ClassVar[set[str]] = {"TrendsQuery", "LifecycleQuery", "RetentionQuery"}++ @property+ def _breakdown_filter(self) -> dict:+ return self.query.get("breakdownFilter") or {}++ def allowed_variables(self, is_materialized: bool) -> set[str]:+ allowed: set[str] = set()++ # Only allow breakdown properties for query types that support it+ if self.query_kind in self.BREAKDOWN_SUPPORTED_QUERY_TYPES:+ allowed.update(get_breakdown_properties(self._breakdown_filter))++ if not is_materialized:+ # Non-materialized also allows date_from/date_to via filters_override+ allowed.update({"date_from", "date_to"})++ return allowed++ def required_materialized_variables(self) -> set[str]:+ if self.query_kind in self.BREAKDOWN_SUPPORTED_QUERY_TYPES:+ return set(get_breakdown_properties(self._breakdown_filter))+ return set()++ def can_serve_variables_from_materialized(self, requested: set[str]) -> bool:+ allowed_props = set(get_breakdown_properties(self._breakdown_filter))+ if not allowed_props:+ return False+ return requested.issubset(allowed_props)++ def materialized_filters_override_satisfies_required(self, data: EndpointRunRequest) -> bool:+ # apply_materialized_filters applies only the first property's value as a single breakdown+ # filter, so filters_override can only satisfy a single-breakdown endpoint. A multi-breakdown+ # endpoint would leave the other breakdowns unfiltered — require variables (one per breakdown).+ if len(self.required_materialized_variables()) != 1:+ return False+ fo = data.filters_override+ if not (fo and fo.properties):+ return False+ for prop in fo.properties:+ prop_value = getattr(prop, "value", None)+ if prop_value is not None:+ value = prop_value[0] if isinstance(prop_value, list) else prop_value+ return build_breakdown_filter_condition(self.query_kind, str(value)) is not None+ return False++ def build_materialized_select(+ self,+ table_name: str,+ variable_infos: list[MaterializableVariable] | None = None,+ ) -> tuple[ast.SelectQuery, int | None]:+ select_query = ast.SelectQuery(+ select=[ast.Field(chain=["*"])],+ select_from=ast.JoinExpr(table=ast.Field(chain=[table_name])),+ )+ return select_query, None++ def apply_materialized_filters(+ self, select_query: ast.SelectQuery, data: EndpointRunRequest+ ) -> dict[str, str] | None:+ # filters_override takes precedence over variables (backwards compat)+ if data.filters_override is not None:+ if data.filters_override.properties:+ for prop in data.filters_override.properties:+ if hasattr(prop, "key") and hasattr(prop, "value") and prop.value is not None:+ # Convert value to string for breakdown filter+ value = prop.value[0] if isinstance(prop.value, list) else prop.value+ condition = build_breakdown_filter_condition(self.query_kind, str(value))+ if condition:+ add_where_condition(select_query, condition)+ # filters_override is deprecated — only the first property is used+ break+ return FILTERS_OVERRIDE_DEPRECATION_HEADERS++ if data.variables:+ index_mapping = get_breakdown_column_indices(self._breakdown_filter)+ for breakdown_prop, array_index in index_mapping.items():+ if breakdown_prop in data.variables:+ condition = build_breakdown_filter_condition(+ self.query_kind, data.variables[breakdown_prop], array_index=array_index+ )+ if condition:+ add_where_condition(select_query, condition)+ return None++ def transform_materialized_response(self, response_data: dict, saved_query: "DataWarehouseSavedQuery") -> None:+ """Re-shape flat materialized rows into the inline insight response format.++ Raises MaterializedSeriesMismatchError on series drift (query edited after+ materialization) — the caller decides how to recover.+ """+ if self.query_kind not in self.INSIGHT_TRANSFORM_TYPES:+ return+ transform_materialized_insight_response(+ response_data,+ self.query,+ self.team,+ now=saved_query.last_run_at,+ )++ def clean_response_sentinels(self, response_data: dict) -> None:+ """Full cleaning: sentinel literals plus '' → null (how materialized insight+ tables store null breakdowns). An 'Other' bucket means the breakdown limit+ was exceeded — report it for visibility."""+ found_other = clean_breakdown_sentinels(response_data, clean_empty_string=True)+ if found_other:+ capture_exception(+ Exception(+ f"Endpoint breakdown limit ({ENDPOINT_BREAKDOWN_LIMIT}) exceeded — 'Other' bucket appeared in results"+ )+ )+ _emit_breakdown_limit_signal(self.team, self.endpoint)++ def prepare_inline_query(self, query: dict) -> dict:+ return prepare_insight_query_for_endpoint(query)++ def build_inline_plan(self, query: dict, data: EndpointRunRequest) -> InlineExecutionPlan:+ # filters_override takes precedence over variables (backwards compat)+ if data.filters_override is not None:+ return InlineExecutionPlan(+ filters_override=data.filters_override,+ deprecation_headers=FILTERS_OVERRIDE_DEPRECATION_HEADERS,+ )+ if data.variables:+ breakdown_infos = get_breakdown_infos(self._breakdown_filter)+ return InlineExecutionPlan(+ filters_override=self._variables_to_filters(data.variables, breakdown_infos=breakdown_infos)+ )+ return InlineExecutionPlan()++ def _variables_to_filters(+ self,+ variables: dict[str, str],+ breakdown_infos: list[tuple[str, str]] | None = None,+ ) -> Optional[DashboardFilter]:+ """Convert insight magic variables to DashboardFilter.++ Args:+ variables: Dict of variable name -> value from the request+ breakdown_infos: List of (property_name, property_type) for breakdown filtering+ """+ date_from = variables.get("date_from")+ date_to = variables.get("date_to")++ properties: list[dict] = []+ for prop_name, prop_type in breakdown_infos or []:+ if prop_name not in variables:+ continue+ value = variables[prop_name]+ # Any failure to build a filter for a breakdown variable must error the+ # request — silently skipping would return unfiltered data, which is a+ # data-leak (same principle that gates materialized endpoints on having+ # all variables present).+ try:+ if prop_type == "hogql":+ # HogQLPropertyFilter.key is a full HogQL predicate and doesn't accept+ # `operator` (HogQLPropertyFilter has extra="forbid"), so build a+ # `<expr> = <value>` (or `isNull(<expr>)`) predicate to filter with.+ key_expr = parse_expr(prop_name)+ predicate_expr: ast.Expr+ if value == "":+ predicate_expr = ast.Call(name="isNull", args=[key_expr])+ else:+ predicate_expr = ast.CompareOperation(+ left=key_expr,+ op=ast.CompareOperationOp.Eq,+ right=ast.Constant(value=value),+ )+ properties.append({"key": predicate_expr.to_hogql(), "type": "hogql"})+ continue+ if value == "":+ # Empty string means "null/unset" — match events where the property is missing.+ # This keeps inline execution consistent with the materialized path,+ # where null breakdown values are stored as '' in S3.+ properties.append(+ {+ "key": prop_name,+ "type": prop_type if prop_type else "event",+ "operator": PropertyOperator.IS_NOT_SET,+ }+ )+ else:+ properties.append(+ {+ "key": prop_name,+ "value": value,+ "type": prop_type if prop_type else "event",+ "operator": PropertyOperator.EXACT,+ }+ )+ except Exception as e:+ capture_exception(+ e,+ {+ "product": Product.ENDPOINTS,+ "team_id": self.team.pk,+ "endpoint_name": self.endpoint.name,+ "prop_name": prop_name,+ "prop_type": prop_type,+ },+ )+ raise ValidationError(+ {"variables": f"Could not apply filter for breakdown variable '{prop_name}'"}+ ) from e++ if not date_from and not date_to and not properties:+ return None++ return DashboardFilter(date_from=date_from, date_to=date_to, properties=properties)+++def strategy_for(endpoint: Endpoint, version: EndpointVersion, team: Team) -> EndpointQueryStrategy:+ """Pick the strategy for an endpoint version based on its query kind."""+ if version.query.get("kind") == "HogQLQuery":+ return HogQLEndpointStrategy(endpoint, version, team)+ return InsightEndpointStrategy(endpoint, version, team)diff --git a/products/endpoints/backend/services/validation.py b/products/endpoints/backend/services/validation.pynew file mode 100644index 000000000000..5e4b83a1eb99--- /dev/null+++ b/products/endpoints/backend/services/validation.py@@ -0,0 +1,236 @@+"""Request payload validation for endpoint create/update.++These functions validate (and normalize) the ``EndpointRequest`` payload before+it reaches the CRUD service: name format, data freshness buckets, HogQL+parseability, and variable placeholder <-> definition consistency.+"""++import re+import uuid+from typing import Optional++from rest_framework.exceptions import ValidationError++from posthog.schema import EndpointRequest, HogQLQuery, HogQLVariable++from posthog.hogql import ast+from posthog.hogql.errors import ExposedHogQLError, ResolutionError+from posthog.hogql.parser import parse_select++from posthog.exceptions_capture import capture_exception+from posthog.models import Team++from products.endpoints.backend.constants import (+ DATA_FRESHNESS_BUCKET_SPECS,+ ENDPOINT_NAME_REGEX,+ VALID_DATA_FRESHNESS_SECONDS,+)+from products.endpoints.backend.materialization_transforms import SUPPORTED_BUCKET_FUNCTIONS, VariablePlaceholderFinder+from products.endpoints.backend.models import Endpoint, can_materialize_query+from products.product_analytics.backend.models.insight_variable import InsightVariable+++def validate_data_freshness(data_freshness_seconds: int | None) -> None:+ """Validate data_freshness_seconds is one of the allowed bucket values."""+ if data_freshness_seconds is None:+ return+ if data_freshness_seconds not in VALID_DATA_FRESHNESS_SECONDS:+ allowed = sorted(VALID_DATA_FRESHNESS_SECONDS)+ human = ", ".join(b.human for b in DATA_FRESHNESS_BUCKET_SPECS)+ raise ValidationError(+ {"data_freshness_seconds": f"Data freshness must be one of: {allowed} seconds ({human})."}+ )+++def validate_bucket_overrides(bucket_overrides: dict[str, str] | None) -> None:+ """Raise ValidationError if any bucket override value is not in SUPPORTED_BUCKET_FUNCTIONS."""+ if not bucket_overrides:+ return++ invalid = {k: v for k, v in bucket_overrides.items() if v not in SUPPORTED_BUCKET_FUNCTIONS}+ if invalid:+ valid_options = list(SUPPORTED_BUCKET_FUNCTIONS.keys())+ raise ValidationError(f"Invalid bucket override values: {invalid}. Valid options: {valid_options}")+++def validate_hogql_query(query: HogQLQuery, team: Team) -> None:+ """Validate that a HogQL query can be parsed and the variables are valid."""+ try:+ ast_node = parse_select(query.query)+ except ExposedHogQLError as e:+ raise ValidationError({"query": f"Invalid HogQL query: {e}"}) from e+ except ResolutionError as e:+ capture_exception(e)+ raise ValidationError({"query": "Invalid HogQL query: unable to resolve table or field references."})+ except Exception as e:+ capture_exception(e)+ raise ValidationError({"query": "Unknown error occurred parsing the query."})++ validate_variable_placeholders(ast_node, query.variables or {}, team)+++def sync_hogql_query_variables(query: HogQLQuery, team: Team) -> None:+ """Sync query variable definitions with the placeholders used in the query string."""+ try:+ ast_node = parse_select(query.query)+ except Exception:+ # Validation runs separately and will surface parse errors.+ return++ finder = VariablePlaceholderFinder()+ finder.visit(ast_node)++ placeholder_names = {str(p.chain[1]) for p in finder.variable_placeholders if p.chain and len(p.chain) > 1}+ if not placeholder_names:+ query.variables = None+ return++ existing_variables = query.variables or {}+ existing_variable_ids: list[str] = []+ for variable in existing_variables.values():+ if not variable.variableId:+ continue+ try:+ uuid.UUID(variable.variableId)+ except ValueError:+ continue+ existing_variable_ids.append(variable.variableId)++ team_variables = InsightVariable.objects.filter(team=team, id__in=existing_variable_ids)+ team_variables_by_id = {str(variable.id): variable for variable in team_variables}++ synced_variables: dict[str, HogQLVariable] = {}+ existing_code_names: set[str] = set()++ for variable_id, variable in existing_variables.items():+ if variable.code_name and variable.code_name in placeholder_names:+ if variable.value is None and variable.isNull is not True:+ team_variable = team_variables_by_id.get(variable.variableId)+ if team_variable:+ variable.value = team_variable.default_value+ variable.isNull = team_variable.default_value is None+ synced_variables[variable_id] = variable+ existing_code_names.add(variable.code_name)++ missing_code_names = placeholder_names - existing_code_names+ if missing_code_names:+ missing_variables = InsightVariable.objects.filter(team=team, code_name__in=missing_code_names)++ for variable in missing_variables:+ if not variable.code_name:+ continue+ synced_variables[str(variable.id)] = HogQLVariable(+ variableId=str(variable.id),+ code_name=variable.code_name,+ value=variable.default_value,+ isNull=variable.default_value is None,+ )++ query.variables = synced_variables or None+++def validate_variable_placeholders(node: ast.AST, variables: Optional[dict[str, HogQLVariable]], team: Team) -> None:+ """Validate that every {variables.X} placeholder in the query has a matching variable definition."""+ finder = VariablePlaceholderFinder()+ finder.visit(node)++ if not finder.variable_placeholders:+ return++ placeholder_names = {str(p.chain[1]) for p in finder.variable_placeholders if p.chain and len(p.chain) > 1}++ defined_code_names: set[str] = set()+ variable_ids: set[str] = set()+ if variables:+ defined_code_names = {v.code_name for v in variables.values() if v.code_name}+ variable_ids = set(variables.keys())++ undefined: list[str] = sorted(placeholder_names - defined_code_names)+ if undefined:+ raise ValidationError(+ {+ "query": f"Query references undefined variable(s): {', '.join(undefined)}. "+ "See https://posthog.com/docs/endpoints/variables for detail."+ }+ )++ if variable_ids:+ valid_uuids: set[str] = set()+ invalid_uuids: set[str] = set()+ invalid_ids: set[str] = set()+ for vid in variable_ids:+ try:+ uuid.UUID(vid)+ valid_uuids.add(vid)+ except ValueError:+ invalid_uuids.add(vid)++ if invalid_uuids:+ raise ValidationError({"query": f"Variable ID(s) not valid UUIDs: {', '.join(sorted(invalid_uuids))}. "})++ if valid_uuids:+ existing_ids = {+ str(id)+ for id in InsightVariable.objects.filter(team=team, id__in=valid_uuids).values_list("id", flat=True)+ }+ invalid_ids = valid_uuids - existing_ids++ if invalid_ids:+ raise ValidationError(+ {+ "query": f"Variable ID(s) not found: {', '.join(sorted(invalid_ids))}. "+ "Make sure the variables exist in https://app.posthog.com/data-management/variables."+ }+ )+++def validate_endpoint_request(data: EndpointRequest, team: Team, strict: bool = True) -> None:+ """Validate a create/update payload. With strict=True, name and query are required."""+ query = data.query+ if not query and strict:+ raise ValidationError({"query": "This field is required."})++ name = data.name+ if not name:+ if name is not None or strict:+ raise ValidationError({"name": "This field is required."})+ return+ if not isinstance(name, str) or not re.fullmatch(ENDPOINT_NAME_REGEX, name):+ raise ValidationError(+ {+ "name": f"Invalid name '{name}'. Must start with a letter, contain only alphanumeric characters, "+ "hyphens, or underscores, and be between 1 and 128 characters long."+ }+ )++ if query and isinstance(query, HogQLQuery) and query.query:+ sync_hogql_query_variables(query, team)+ validate_hogql_query(query, team)++ validate_data_freshness(data.data_freshness_seconds)+++def validate_update_request(data: EndpointRequest, team: Team, endpoint: Endpoint | None = None) -> None:+ """Validate an update payload against the endpoint's resulting state."""+ validate_data_freshness(data.data_freshness_seconds)++ # Determine final states after this request (for validation)+ will_be_active = data.is_active if data.is_active is not None else (endpoint.is_active if endpoint else True)++ if not will_be_active and data.is_materialized is True:+ raise ValidationError({"is_materialized": "Cannot enable materialization on inactive endpoint."})++ if data.is_materialized is True:+ # Fail fast on queries that can't be materialized. The service re-checks against+ # the final version (the authoritative guard); this catches it before any writes.+ effective_query = (+ data.query.model_dump() if data.query is not None else (endpoint.get_version().query if endpoint else None)+ )+ if effective_query is not None:+ can_materialize, reason = can_materialize_query(effective_query)+ if not can_materialize:+ raise ValidationError(f"Cannot materialize endpoint. Reason: {reason}")++ if data.query and isinstance(data.query, HogQLQuery) and data.query.query:+ sync_hogql_query_variables(data.query, team)+ validate_hogql_query(data.query, team)diff --git a/products/endpoints/backend/tests/test_endpoint.py b/products/endpoints/backend/tests/test_endpoint.pyindex 89d5fe129a28..b16ac0dce164 100644--- a/products/endpoints/backend/tests/test_endpoint.py+++ b/products/endpoints/backend/tests/test_endpoint.py@@ -3,7 +3,7 @@ from typing import Anyfrom freezegun import freeze_timefrom posthog.test.base import APIBaseTest, ClickhouseTestMixin-from unittest import TestCase+from unittest import TestCase, mockfrom parameterized import parameterizedfrom rest_framework import status@@ -436,6 +436,19 @@ class TestEndpoint(ClickhouseTestMixin, APIBaseTest):self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.json())self.assertEqual(response.json()["name"], "reusable_name")+ def test_create_rolls_back_endpoint_when_version_creation_fails(self):+ payload = {"name": "rollback-endpoint", "query": {"kind": "HogQLQuery", "query": "SELECT 1"}}++ with mock.patch.object(EndpointVersion.objects, "create", side_effect=RuntimeError("boom")):+ response = self.client.post(f"/api/environments/{self.team.id}/endpoints/", payload, format="json")++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertEqual(Endpoint.objects.filter(team=self.team, name="rollback-endpoint", deleted=False).count(), 0)++ # The name must be reusable after the failed create+ response = self.client.post(f"/api/environments/{self.team.id}/endpoints/", payload, format="json")+ self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.json())+def test_soft_deleted_endpoint_not_runnable(self):create_endpoint_with_version(name="run_deleted",@@ -1454,7 +1467,7 @@ class TestMaterializationPreview(ClickhouseTestMixin, APIBaseTest):assert version.bucket_overrides == {"timestamp": "week"}# Change bucket_overrides — should trigger an immediate refresh- with mock.patch("products.endpoints.backend.api.trigger_saved_query_schedule") as mock_trigger:+ with mock.patch("products.endpoints.backend.services.crud.trigger_saved_query_schedule") as mock_trigger:response = self.client.patch(f"/api/environments/{self.team.id}/endpoints/trigger-bucket/",{"bucket_overrides": {"timestamp": "hour"}},diff --git a/products/endpoints/backend/tests/test_endpoint_ducklake.py b/products/endpoints/backend/tests/test_endpoint_ducklake.pyindex eb3c29e25204..42a0bd4c5918 100644--- a/products/endpoints/backend/tests/test_endpoint_ducklake.py+++ b/products/endpoints/backend/tests/test_endpoint_ducklake.py@@ -4,7 +4,7 @@ from unittest import mockfrom rest_framework import status-from products.endpoints.backend.api import EndpointViewSet+from products.endpoints.backend.services.execution import EndpointExecutionServicefrom products.endpoints.backend.tests.conftest import create_endpoint_with_versionpytestmark = [pytest.mark.django_db]@@ -13,10 +13,8 @@ pytestmark = [pytest.mark.django_db]class TestShouldUseDuckLake(APIBaseTest):"""Test the routing decision for DuckLake vs ClickHouse."""- def _make_viewset(self) -> EndpointViewSet:- viewset = EndpointViewSet()- viewset.team_id = self.team.id- return viewset+ def _make_service(self) -> EndpointExecutionService:+ return EndpointExecutionService(self.team, mock.MagicMock())def test_non_hogql_query_returns_false(self):endpoint = create_endpoint_with_version(@@ -26,9 +24,9 @@ class TestShouldUseDuckLake(APIBaseTest):created_by=self.user,)version = endpoint.get_version()- viewset = self._make_viewset()+ service = self._make_service()- assert viewset._should_use_ducklake(endpoint, version) is False+ assert service._should_use_ducklake(endpoint, version) is Falsedef test_none_version_returns_false(self):endpoint = create_endpoint_with_version(@@ -37,9 +35,9 @@ class TestShouldUseDuckLake(APIBaseTest):query={"kind": "HogQLQuery", "query": "SELECT count() FROM events"},created_by=self.user,)- viewset = self._make_viewset()+ service = self._make_service()- assert viewset._should_use_ducklake(endpoint, None) is False+ assert service._should_use_ducklake(endpoint, None) is Falseclass TestDuckLakeEndpointExecution(APIBaseTest):@@ -57,7 +55,9 @@ class TestDuckLakeEndpointExecution(APIBaseTest):super().tearDown()@mock.patch("posthog.ducklake.client.execute_ducklake_query")- @mock.patch("products.endpoints.backend.api.EndpointViewSet._should_use_ducklake", return_value=True)+ @mock.patch(+ "products.endpoints.backend.services.execution.EndpointExecutionService._should_use_ducklake", return_value=True+ )def test_run_returns_ducklake_result(self, _mock_should, mock_execute):from posthog.ducklake.client import DuckLakeQueryResult@@ -90,7 +90,9 @@ class TestDuckLakeEndpointExecution(APIBaseTest):mock_execute.assert_called_once()@mock.patch("posthog.ducklake.client.execute_ducklake_query")- @mock.patch("products.endpoints.backend.api.EndpointViewSet._should_use_ducklake", return_value=True)+ @mock.patch(+ "products.endpoints.backend.services.execution.EndpointExecutionService._should_use_ducklake", return_value=True+ )def test_run_with_debug_includes_sql_metadata(self, _mock_should, mock_execute):from posthog.ducklake.client import DuckLakeQueryResult@@ -123,7 +125,9 @@ class TestDuckLakeEndpointExecution(APIBaseTest):assert "ducklake_sql" in data@mock.patch("posthog.ducklake.client.execute_ducklake_query")- @mock.patch("products.endpoints.backend.api.EndpointViewSet._should_use_ducklake", return_value=True)+ @mock.patch(+ "products.endpoints.backend.services.execution.EndpointExecutionService._should_use_ducklake", return_value=True+ )def test_run_ducklake_error_falls_back_to_inline(self, _mock_should, mock_execute):mock_execute.side_effect = Exception("Duckgres connection refused")@@ -134,7 +138,9 @@ class TestDuckLakeEndpointExecution(APIBaseTest):created_by=self.user,)- with mock.patch("products.endpoints.backend.api.EndpointViewSet._execute_inline_endpoint") as mock_inline:+ with mock.patch(+ "products.endpoints.backend.services.execution.EndpointExecutionService._execute_inline_endpoint"+ ) as mock_inline:from rest_framework.response import Responsemock_inline.return_value = Response({"results": [], "columns": [], "hasMore": False}, status=200)diff --git a/products/endpoints/backend/tests/test_endpoint_execution.py b/products/endpoints/backend/tests/test_endpoint_execution.pyindex 9e7263a144de..8872e8f386a4 100644--- a/products/endpoints/backend/tests/test_endpoint_execution.py+++ b/products/endpoints/backend/tests/test_endpoint_execution.py@@ -1,3 +1,5 @@+from datetime import timedelta+from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_eventsfrom unittest import mock@@ -10,7 +12,7 @@ from rest_framework.response import Responsefrom posthog.schema import EventsNode, TrendsQueryfrom products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery-from products.endpoints.backend.api import EndpointViewSet+from products.endpoints.backend.services.execution import EndpointExecutionServicefrom products.endpoints.backend.tests.conftest import create_endpoint_with_versionfrom products.product_analytics.backend.models.insight_variable import InsightVariablefrom products.warehouse_sources.backend.models.table import DataWarehouseTable@@ -462,7 +464,9 @@ class TestEndpointExecution(ClickhouseTestMixin, APIBaseTest):self._materialize_endpoint(endpoint)# Execute with variable filter - should filter materialized table by event_name- with mock.patch.object(EndpointViewSet, "_execute_query_and_respond", return_value=Response({})) as mock_exec:+ with mock.patch.object(+ EndpointExecutionService, "_execute_query_and_respond", return_value=Response({})+ ) as mock_exec:response = self.client.post(f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/run/",{"variables": {"event_name": "$pageleave"}},@@ -497,7 +501,9 @@ class TestEndpointExecution(ClickhouseTestMixin, APIBaseTest):)self._materialize_endpoint(endpoint)- with mock.patch.object(EndpointViewSet, "_execute_query_and_respond", return_value=Response({})) as mock_exec:+ with mock.patch.object(+ EndpointExecutionService, "_execute_query_and_respond", return_value=Response({})+ ) as mock_exec:self.client.post(f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/run/",{"variables": {"event_name": "$pageview"}},@@ -685,9 +691,11 @@ class TestEndpointExecution(ClickhouseTestMixin, APIBaseTest):# refresh: direct should bypass materialization and run inlinewith (mock.patch.object(- EndpointViewSet, "_execute_materialized_endpoint", return_value=Response({})+ EndpointExecutionService, "_execute_materialized_endpoint", return_value=Response({})) as mock_materialized,- mock.patch.object(EndpointViewSet, "_execute_inline_endpoint", return_value=Response({})) as mock_inline,+ mock.patch.object(+ EndpointExecutionService, "_execute_inline_endpoint", return_value=Response({})+ ) as mock_inline,):response = self.client.post(f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/run/",@@ -732,7 +740,9 @@ class TestEndpointExecution(ClickhouseTestMixin, APIBaseTest):)self._materialize_endpoint(endpoint)- with mock.patch.object(EndpointViewSet, "_execute_query_and_respond", return_value=Response({})) as mock_exec:+ with mock.patch.object(+ EndpointExecutionService, "_execute_query_and_respond", return_value=Response({})+ ) as mock_exec:response = self.client.post(f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/run/",{"variables": {"event_name": "$pageleave", "browser": "Safari"}},@@ -787,7 +797,9 @@ class TestEndpointExecution(ClickhouseTestMixin, APIBaseTest):)self._materialize_endpoint(endpoint)- with mock.patch.object(EndpointViewSet, "_execute_query_and_respond", return_value=Response({})) as mock_exec:+ with mock.patch.object(+ EndpointExecutionService, "_execute_query_and_respond", return_value=Response({})+ ) as mock_exec:response = self.client.post(f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/run/",{"variables": {"start_date": "2026-01-05", "end_date": "2026-01-08"}},@@ -856,7 +868,9 @@ class TestEndpointExecution(ClickhouseTestMixin, APIBaseTest):)self._materialize_endpoint(endpoint)- with mock.patch.object(EndpointViewSet, "_execute_query_and_respond", return_value=Response({})) as mock_exec:+ with mock.patch.object(+ EndpointExecutionService, "_execute_query_and_respond", return_value=Response({})+ ) as mock_exec:response = self.client.post(f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/run/",{"variables": {"start_ts": "2026-01-05", "end_ts": "2026-01-08", "host": "example.com"}},@@ -900,7 +914,9 @@ class TestEndpointExecution(ClickhouseTestMixin, APIBaseTest):)self._materialize_endpoint(endpoint)- with mock.patch.object(EndpointViewSet, "_execute_query_and_respond", return_value=Response({})) as mock_exec:+ with mock.patch.object(+ EndpointExecutionService, "_execute_query_and_respond", return_value=Response({})+ ) as mock_exec:run_data = {}if request_limit is not None:run_data["limit"] = request_limit@@ -934,7 +950,9 @@ class TestEndpointExecution(ClickhouseTestMixin, APIBaseTest):self._materialize_endpoint(endpoint)# Filter by breakdown using actual property name- with mock.patch.object(EndpointViewSet, "_execute_query_and_respond", return_value=Response({})) as mock_exec:+ with mock.patch.object(+ EndpointExecutionService, "_execute_query_and_respond", return_value=Response({})+ ) as mock_exec:response = self.client.post(f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/run/",{"variables": {"$browser": "Chrome"}},@@ -967,7 +985,9 @@ class TestEndpointExecution(ClickhouseTestMixin, APIBaseTest):)self._materialize_endpoint(endpoint)- with mock.patch.object(EndpointViewSet, "_execute_query_and_respond", return_value=Response({})) as mock_exec:+ with mock.patch.object(+ EndpointExecutionService, "_execute_query_and_respond", return_value=Response({})+ ) as mock_exec:response = self.client.post(f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/run/",{"variables": {"$browser": "Chrome", "$os": "Mac"}},@@ -1004,7 +1024,9 @@ class TestEndpointExecution(ClickhouseTestMixin, APIBaseTest):)self._materialize_endpoint(endpoint)- with mock.patch.object(EndpointViewSet, "_execute_query_and_respond", return_value=Response({})) as mock_exec:+ with mock.patch.object(+ EndpointExecutionService, "_execute_query_and_respond", return_value=Response({})+ ) as mock_exec:response = self.client.post(f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/run/",{"variables": {"$browser": "Chrome", "$os": "Mac", "$device_type": "Desktop"}},@@ -1131,7 +1153,9 @@ class TestEndpointExecution(ClickhouseTestMixin, APIBaseTest):self._materialize_endpoint(endpoint)# Using filters_override instead of variables should work (backwards compat)- with mock.patch.object(EndpointViewSet, "_execute_query_and_respond", return_value=Response({})) as mock_exec:+ with mock.patch.object(+ EndpointExecutionService, "_execute_query_and_respond", return_value=Response({})+ ) as mock_exec:response = self.client.post(f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/run/",{"filters_override": {"properties": [{"key": "$browser", "value": "Chrome", "type": "event"}]}},@@ -1153,9 +1177,11 @@ class TestEndpointExecution(ClickhouseTestMixin, APIBaseTest):with (mock.patch.object(- EndpointViewSet, "_execute_materialized_endpoint", return_value=Response({})+ EndpointExecutionService, "_execute_materialized_endpoint", return_value=Response({})) as mock_materialized,- mock.patch.object(EndpointViewSet, "_execute_inline_endpoint", return_value=Response({})) as mock_inline,+ mock.patch.object(+ EndpointExecutionService, "_execute_inline_endpoint", return_value=Response({})+ ) as mock_inline,):response = self.client.post(f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/run/",@@ -1517,7 +1543,7 @@ class TestEndpointExecution(ClickhouseTestMixin, APIBaseTest):fake_results = [{"event": "$pageview", "distinct_id": "user1"}] * num_result_rowswith mock.patch.object(- EndpointViewSet,+ EndpointExecutionService,"_execute_query_and_respond",return_value=Response({"results": fake_results}),) as mock_exec:@@ -1571,7 +1597,7 @@ class TestEndpointExecution(ClickhouseTestMixin, APIBaseTest):fake_results = [{"event": "$pageview", "count()": 10}] * 5with mock.patch.object(- EndpointViewSet,+ EndpointExecutionService,"_execute_query_and_respond",return_value=Response({"results": fake_results}),) as mock_exec:@@ -1616,7 +1642,7 @@ class TestEndpointExecution(ClickhouseTestMixin, APIBaseTest):fake_results = [{"event": "$pageview", "distinct_id": "user1"}] * num_result_rowswith mock.patch.object(- EndpointViewSet,+ EndpointExecutionService,"_execute_query_and_respond",return_value=Response({"results": fake_results}),) as mock_exec:@@ -1678,7 +1704,7 @@ class TestEndpointExecution(ClickhouseTestMixin, APIBaseTest):)self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)- self.assertIn("only supported for HogQL", response.json()["error"])+ self.assertIn("only supported for HogQL", str(response.json()))# =========================================================================# CALENDAR HEATMAP ENDPOINTS@@ -1710,7 +1736,7 @@ class TestEndpointExecution(ClickhouseTestMixin, APIBaseTest):# BREAKDOWN SENTINEL CLEANUP# =========================================================================- @mock.patch("products.endpoints.backend.api.process_query_model")+ @mock.patch("products.endpoints.backend.services.execution.process_query_model")def test_inline_insight_sentinel_null_cleaned_from_breakdown_value(self, mock_process):mock_process.return_value = {"results": [@@ -1737,7 +1763,7 @@ class TestEndpointExecution(ClickhouseTestMixin, APIBaseTest):self.assertEqual(results[0]["breakdown_value"], ["Chrome", None])self.assertIsNone(results[1]["breakdown_value"])- @mock.patch("products.endpoints.backend.api.process_query_model")+ @mock.patch("products.endpoints.backend.services.execution.process_query_model")def test_inline_insight_sentinel_cleaned_from_label(self, mock_process):mock_process.return_value = {"results": [@@ -1766,7 +1792,7 @@ class TestEndpointExecution(ClickhouseTestMixin, APIBaseTest):results = response.json()["results"]self.assertEqual(results[0]["label"], "Chrome::null")- @mock.patch("products.endpoints.backend.api.process_query_model")+ @mock.patch("products.endpoints.backend.services.execution.process_query_model")def test_hogql_result_sentinel_cleaned_from_breakdown_column(self, mock_process):mock_process.return_value = {"results": [@@ -1820,8 +1846,8 @@ class TestEndpointExecution(ClickhouseTestMixin, APIBaseTest):# Patch the limit to a low value so the 30 distinct breakdown values exceed itwith (- mock.patch("products.endpoints.backend.materialization.ENDPOINT_BREAKDOWN_LIMIT", 5),- mock.patch("products.endpoints.backend.api.capture_exception") as mock_capture,+ mock.patch("products.endpoints.backend.materialization_transforms.ENDPOINT_BREAKDOWN_LIMIT", 5),+ mock.patch("products.endpoints.backend.services.strategies.capture_exception") as mock_capture,):response = self.client.post(f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/run/",@@ -1909,7 +1935,9 @@ class TestEndpointExecution(ClickhouseTestMixin, APIBaseTest):)self._materialize_endpoint(endpoint)- with mock.patch.object(EndpointViewSet, "_execute_query_and_respond", return_value=Response({})) as mock_exec:+ with mock.patch.object(+ EndpointExecutionService, "_execute_query_and_respond", return_value=Response({})+ ) as mock_exec:response = self.client.post(f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/run/",{"variables": {"event_name": "$pageview"}},@@ -2143,15 +2171,14 @@ class TestEndpointExecution(ClickhouseTestMixin, APIBaseTest):def test_disable_materialization_no_op_does_not_increment_counter(self):from prometheus_client import REGISTRY- from products.endpoints.backend.api import EndpointViewSet+ from products.endpoints.backend.services.materialization import EndpointMaterializationServiceendpoint = self._make_simple_hogql_endpoint("metric_disable_no_op")labels = {"action": "disable", "status": "success"}before = REGISTRY.get_sample_value("posthog_endpoint_materialization_event_total", labels) or 0.0- viewset = EndpointViewSet()- viewset.team_id = self.team.id- viewset._disable_materialization(endpoint, mock.MagicMock())+ service = EndpointMaterializationService(self.team, mock.MagicMock())+ service.disable_materialization(endpoint, endpoint.get_version())after = REGISTRY.get_sample_value("posthog_endpoint_materialization_event_total", labels) or 0.0self.assertEqual(after - before, 0.0)@@ -2162,8 +2189,8 @@ class TestEndpointExecution(ClickhouseTestMixin, APIBaseTest):boom = RuntimeError("synthetic failure")with (- mock.patch("products.endpoints.backend.api.process_query_model", side_effect=boom),- mock.patch("products.endpoints.backend.api._emit_endpoint_failure_signal") as mock_emit,+ mock.patch("products.endpoints.backend.services.execution.process_query_model", side_effect=boom),+ mock.patch("products.endpoints.backend.services.execution._emit_endpoint_failure_signal") as mock_emit,):response = self.client.post(f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/run/",@@ -2181,7 +2208,7 @@ class TestEndpointExecution(ClickhouseTestMixin, APIBaseTest):def test_emit_failure_signal_swallows_errors(self):"""Signal emission must never mask the original exception."""- from products.endpoints.backend.api import _emit_endpoint_failure_signal+ from products.endpoints.backend.services.execution import _emit_endpoint_failure_signalendpoint = self._make_simple_hogql_endpoint("failure_signal_swallow")@@ -2190,3 +2217,180 @@ class TestEndpointExecution(ClickhouseTestMixin, APIBaseTest):side_effect=RuntimeError("signal layer exploded"),):_emit_endpoint_failure_signal(self.team, endpoint, RuntimeError("original"), materialized=False, version=1)++ def _make_fresh_materialized_endpoint(self, name: str, query: dict):+ """Endpoint whose current version has a fresh, Completed materialization."""+ saved_query = DataWarehouseSavedQuery.objects.create(+ team=self.team,+ name=f"{name}_v1",+ query=query,+ is_materialized=True,+ status=DataWarehouseSavedQuery.Status.COMPLETED,+ sync_frequency_interval=timedelta(hours=24),+ last_run_at=timezone.now(),+ )+ saved_query.table = DataWarehouseTable.objects.create(+ team=self.team,+ name=f"{name}_v1",+ format=DataWarehouseTable.TableFormat.Parquet,+ url_pattern="s3://test-bucket/path",+ )+ saved_query.save()++ endpoint = create_endpoint_with_version(+ name=name,+ team=self.team,+ query=query,+ created_by=self.user,+ is_active=True,+ )+ version = endpoint.versions.first()+ version.saved_query = saved_query+ version.save()+ return endpoint++ def test_hogql_endpoint_empty_string_in_breakdown_value_column_not_rewritten(self):+ """A HogQL endpoint that happens to emit a column named breakdown_value must not have+ plain empty strings rewritten to null — that rewrite is an insight-materialization artifact."""+ endpoint = create_endpoint_with_version(+ name="hogql-breakdown-col",+ team=self.team,+ query={"kind": "HogQLQuery", "query": "SELECT '' AS breakdown_value, 'x' AS other"},+ created_by=self.user,+ is_active=True,+ )++ response = self.client.post(+ f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/run/",+ {"refresh": "force"},+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())+ results = response.json()["results"]+ self.assertEqual(results[0][0], "", "plain empty string was rewritten to null for a HogQL endpoint")++ def test_breakdown_limit_exceeded_emits_signal(self):+ """When the Other bucket appears (breakdown limit exceeded), a signal should fire."""+ for event_name in [f"event_{i}" for i in range(30)]:+ _create_event(+ event="$pageview",+ distinct_id="user1",+ team=self.team,+ timestamp="2026-01-05 12:00:00",+ properties={"unique_prop": event_name},+ )+ flush_persons_and_events()++ endpoint = create_endpoint_with_version(+ name="limit-signal",+ team=self.team,+ query=TrendsQuery(+ series=[EventsNode(event="$pageview")],+ dateRange={"date_from": "2026-01-01", "date_to": "2026-01-10"},+ breakdownFilter={"breakdown": "unique_prop", "breakdown_type": "event", "breakdown_limit": 5},+ ).model_dump(),+ created_by=self.user,+ is_active=True,+ )++ with (+ mock.patch("products.endpoints.backend.materialization_transforms.ENDPOINT_BREAKDOWN_LIMIT", 5),+ mock.patch("products.signals.backend.facade.api.emit_signal", new_callable=mock.AsyncMock) as mock_emit,+ ):+ response = self.client.post(+ f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/run/",+ {"refresh": "force"},+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ breakdown_signal_calls = [+ c for c in mock_emit.call_args_list if c.kwargs.get("source_type") == "endpoint_breakdown_limit_exceeded"+ ]+ self.assertEqual(len(breakdown_signal_calls), 1, "expected a breakdown-limit-exceeded signal")++ def test_materialized_failure_falls_back_to_inline(self):+ """A materialized execution failure must fall back to inline execution, not 500."""+ endpoint = self._make_fresh_materialized_endpoint(+ "mat-fallback", {"kind": "HogQLQuery", "query": "SELECT count() FROM events"}+ )++ inline_response = Response({"results": [[1]], "columns": ["count()"]})+ with mock.patch.object(+ EndpointExecutionService,+ "_execute_query_and_respond",+ side_effect=[RuntimeError("materialized table exploded"), inline_response],+ ) as mock_exec:+ 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)+ self.assertEqual(mock_exec.call_count, 2, "expected materialized attempt then inline fallback")++ def test_series_mismatch_falls_back_to_inline(self):+ """Series drift triggers re-materialization AND serves the request inline."""+ from products.endpoints.backend.insight_transformers import MaterializedSeriesMismatchError+ from products.endpoints.backend.services.strategies import InsightEndpointStrategy++ endpoint = self._make_fresh_materialized_endpoint(+ "mismatch-fallback",+ TrendsQuery(+ series=[EventsNode(event="$pageview")],+ dateRange={"date_from": "2026-01-01", "date_to": "2026-01-10"},+ ).model_dump(),+ )++ flat_response = Response({"results": [[0, "2026-01-01", 0]], "columns": ["__series_index", "day", "count"]})+ inline_response = Response({"results": [{"label": "$pageview", "count": 0}]})+ with (+ mock.patch.object(+ EndpointExecutionService,+ "_execute_query_and_respond",+ side_effect=[flat_response, inline_response],+ ) as mock_exec,+ mock.patch.object(+ InsightEndpointStrategy,+ "transform_materialized_response",+ side_effect=MaterializedSeriesMismatchError("series drift"),+ ),+ mock.patch("products.endpoints.backend.services.execution.trigger_saved_query_schedule") as mock_trigger,+ ):+ 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_trigger.assert_called_once()+ self.assertEqual(mock_exec.call_count, 2, "expected materialized attempt then inline fallback")++ def test_emit_failure_signal_reaches_workflow_boundary(self):+ """The failure-signal plumbing must make it to the Temporal boundary when the+ org/source gates allow it — anything raising before that is a plumbing bug."""+ from products.endpoints.backend.services.execution import _emit_endpoint_failure_signal+ from products.signals.backend.models import SignalSourceConfig++ self.organization.is_ai_data_processing_approved = True+ self.organization.save()+ endpoint = create_endpoint_with_version(+ name="signal-boundary",+ team=self.team,+ query={"kind": "HogQLQuery", "query": "SELECT 1"},+ created_by=self.user,+ is_active=True,+ )++ mock_client = mock.AsyncMock()+ with (+ mock.patch(+ "products.signals.backend.facade.api.async_connect",+ new=mock.AsyncMock(return_value=mock_client),+ ),+ # The gate runs on a separate DB connection (thread_sensitive=False) and can't see+ # rows from the test transaction, so patch it rather than creating a config row.+ mock.patch.object(SignalSourceConfig, "is_source_enabled", return_value=True),+ ):+ _emit_endpoint_failure_signal(self.team, endpoint, RuntimeError("boom"), materialized=False, version=1)++ self.assertGreaterEqual(mock_client.start_workflow.await_count, 1, "signal never reached the Temporal boundary")diff --git a/products/endpoints/backend/tests/test_endpoint_logs.py b/products/endpoints/backend/tests/test_endpoint_logs.pyindex 1b6cf2870970..4880e9eb322b 100644--- a/products/endpoints/backend/tests/test_endpoint_logs.py+++ b/products/endpoints/backend/tests/test_endpoint_logs.py@@ -76,7 +76,7 @@ class TestEndpointExecutionLogs(ClickhouseTestMixin, APIBaseTest):def test_successful_run_emits_info_log(self):endpoint = self._create_hogql_endpoint("logs_ok", "SELECT 1")- with mock.patch("products.endpoints.backend.api.log_endpoint_execution") as mock_log:+ with mock.patch("products.endpoints.backend.services.execution.log_endpoint_execution") as mock_log:response = self.client.post(f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/run/", {}, format="json")@@ -95,7 +95,7 @@ class TestEndpointExecutionLogs(ClickhouseTestMixin, APIBaseTest):def test_failed_run_emits_error_log(self):endpoint = self._create_hogql_endpoint("logs_fail", "SELECT nonexistent_column_xyz FROM events")- with mock.patch("products.endpoints.backend.api.log_endpoint_execution") as mock_log:+ with mock.patch("products.endpoints.backend.services.execution.log_endpoint_execution") as mock_log:response = self.client.post(f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/run/", {}, format="json")@@ -111,7 +111,7 @@ class TestEndpointExecutionLogs(ClickhouseTestMixin, APIBaseTest):def test_successful_run_returns_execution_id_matching_log(self):endpoint = self._create_hogql_endpoint("logs_exec_id", "SELECT 1")- with mock.patch("products.endpoints.backend.api.log_endpoint_execution") as mock_log:+ with mock.patch("products.endpoints.backend.services.execution.log_endpoint_execution") as mock_log:response = self.client.post(f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/run/", {}, format="json")@@ -125,7 +125,7 @@ class TestEndpointExecutionLogs(ClickhouseTestMixin, APIBaseTest):def test_invalid_refresh_mode_emits_error_log_and_clean_message(self):endpoint = self._create_hogql_endpoint("logs_bad_refresh", "SELECT 1")- with mock.patch("products.endpoints.backend.api.log_endpoint_execution") as mock_log:+ with mock.patch("products.endpoints.backend.services.execution.log_endpoint_execution") as mock_log:response = self.client.post(f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/run/",{"refresh": "hey"},@@ -161,7 +161,7 @@ class TestEndpointExecutionLogs(ClickhouseTestMixin, APIBaseTest):# must still surface in the logs.endpoint = self._create_hogql_endpoint(f"logs_reject_{_name}", "SELECT 1")- with mock.patch("products.endpoints.backend.api.log_endpoint_execution") as mock_log:+ with mock.patch("products.endpoints.backend.services.execution.log_endpoint_execution") as mock_log:response = self.client.post(f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/run/", body, format="json")@@ -178,7 +178,7 @@ class TestEndpointExecutionLogs(ClickhouseTestMixin, APIBaseTest):# non-materialized endpoint — this failure must still surface in the logs.endpoint = self._create_hogql_endpoint("logs_bad_validate", "SELECT 1")- with mock.patch("products.endpoints.backend.api.log_endpoint_execution") as mock_log:+ with mock.patch("products.endpoints.backend.services.execution.log_endpoint_execution") as mock_log:response = self.client.post(f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/run/",{"refresh": "direct"},diff --git a/products/endpoints/backend/tests/test_endpoint_materialization.py b/products/endpoints/backend/tests/test_endpoint_materialization.pyindex 4613c4742e74..c7cbfbae4863 100644--- a/products/endpoints/backend/tests/test_endpoint_materialization.py+++ b/products/endpoints/backend/tests/test_endpoint_materialization.py@@ -24,10 +24,11 @@ from posthog.sync import database_sync_to_asyncfrom products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQueryfrom products.data_modeling.backend.models.modeling import DataWarehouseModelPathfrom products.data_warehouse.backend.data_load.saved_query_service import get_saved_query_schedule-from products.endpoints.backend.api import EndpointViewSet-from products.endpoints.backend.materialization import build_endpoint_hogql+from products.endpoints.backend.materialization_transforms import build_endpoint_hogqlfrom products.endpoints.backend.models import EndpointVersion-from products.endpoints.backend.services.endpoint_materialization_service import (+from products.endpoints.backend.services.execution import EndpointExecutionService+from products.endpoints.backend.services.materialization import (+ EndpointMaterializationService,OrphanedEndpointSavedQueryError,prepare_executable_query,)@@ -627,7 +628,9 @@ class TestEndpointMaterialization(ClickhouseTestMixin, APIBaseTest):)saved_query.save()- with mock.patch("products.endpoints.backend.api.EndpointViewSet._execute_query_and_respond") as mock_execute:+ with mock.patch(+ "products.endpoints.backend.services.execution.EndpointExecutionService._execute_query_and_respond"+ ) as mock_execute:old_cache_time = timezone.now() - timedelta(minutes=30)old_cached_response = Response({@@ -670,7 +673,9 @@ class TestEndpointMaterialization(ClickhouseTestMixin, APIBaseTest):)new_saved_query.save()- with mock.patch("products.endpoints.backend.api.EndpointViewSet._execute_query_and_respond") as mock_execute:+ with mock.patch(+ "products.endpoints.backend.services.execution.EndpointExecutionService._execute_query_and_respond"+ ) as mock_execute:new_cache_time = timezone.now() - timedelta(minutes=5)new_cached_response = Response({@@ -777,9 +782,11 @@ class TestEndpointMaterialization(ClickhouseTestMixin, APIBaseTest):# Mock the execution methods to track which path is takenwith (mock.patch.object(- EndpointViewSet, "_execute_materialized_endpoint", return_value=Response({})+ EndpointExecutionService, "_execute_materialized_endpoint", return_value=Response({})) as mock_materialized,- mock.patch.object(EndpointViewSet, "_execute_inline_endpoint", return_value=Response({})) as mock_inline,+ mock.patch.object(+ EndpointExecutionService, "_execute_inline_endpoint", return_value=Response({})+ ) as mock_inline,):response = self.client.post(f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/run",@@ -828,9 +835,11 @@ class TestEndpointMaterialization(ClickhouseTestMixin, APIBaseTest):# Mock the execution methods to track which path is takenwith (mock.patch.object(- EndpointViewSet, "_execute_materialized_endpoint", return_value=Response({})+ EndpointExecutionService, "_execute_materialized_endpoint", return_value=Response({})) as mock_materialized,- mock.patch.object(EndpointViewSet, "_execute_inline_endpoint", return_value=Response({})) as mock_inline,+ mock.patch.object(+ EndpointExecutionService, "_execute_inline_endpoint", return_value=Response({})+ ) as mock_inline,):response = self.client.post(f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/run",@@ -877,9 +886,11 @@ class TestEndpointMaterialization(ClickhouseTestMixin, APIBaseTest):with (mock.patch.object(- EndpointViewSet, "_execute_materialized_endpoint", return_value=Response({})+ EndpointExecutionService, "_execute_materialized_endpoint", return_value=Response({})) as mock_materialized,- mock.patch.object(EndpointViewSet, "_execute_inline_endpoint", return_value=Response({})) as mock_inline,+ mock.patch.object(+ EndpointExecutionService, "_execute_inline_endpoint", return_value=Response({})+ ) as mock_inline,):response = self.client.post(f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/run",@@ -926,9 +937,11 @@ class TestEndpointMaterialization(ClickhouseTestMixin, APIBaseTest):with (mock.patch.object(- EndpointViewSet, "_execute_materialized_endpoint", return_value=Response({})+ EndpointExecutionService, "_execute_materialized_endpoint", return_value=Response({})) as mock_materialized,- mock.patch.object(EndpointViewSet, "_execute_inline_endpoint", return_value=Response({})) as mock_inline,+ mock.patch.object(+ EndpointExecutionService, "_execute_inline_endpoint", return_value=Response({})+ ) as mock_inline,):response = self.client.post(f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/run",@@ -1035,7 +1048,9 @@ class TestEndpointMaterialization(ClickhouseTestMixin, APIBaseTest):# Execute the endpoint and verify it uses the materialized path correctly# Must provide the breakdown variable (required for security - prevents data leakage)- with mock.patch.object(EndpointViewSet, "_execute_query_and_respond", return_value=Response({})) as mock_exec:+ with mock.patch.object(+ EndpointExecutionService, "_execute_query_and_respond", return_value=Response({})+ ) as mock_exec:response = self.client.post(f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/run",{"variables": {"$browser": "Chrome"}},@@ -1056,6 +1071,125 @@ class TestEndpointMaterialization(ClickhouseTestMixin, APIBaseTest):self.assertIn("has(breakdown_value", query_sql)self.assertIn("chrome", query_sql)+ def test_materialized_insight_filters_override_without_value_does_not_bypass_required_breakdown(self):+ # SECURITY: a filters_override whose property carries no usable value adds no WHERE clause+ # in apply_materialized_filters, so it must not be allowed to skip the required-breakdown+ # check — otherwise the caller gets every materialized breakdown row.+ trends_query_with_breakdown = {+ "kind": "TrendsQuery",+ "series": [{"kind": "EventsNode", "event": "$pageview", "math": "total"}],+ "dateRange": {"date_from": "-7d"},+ "interval": "day",+ "breakdownFilter": {"breakdown": "$browser", "breakdown_type": "event", "breakdown_limit": 5},+ }+ _create_event(team=self.team, event="$pageview", distinct_id="user1")+ flush_persons_and_events()++ endpoint = create_endpoint_with_version(+ name="trends_breakdown_secure",+ team=self.team,+ query=trends_query_with_breakdown,+ created_by=self.user,+ is_active=True,+ )+ response = self.client.patch(+ f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/",+ {"is_materialized": True, "data_freshness_seconds": 43200},+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())++ version = endpoint.versions.first()+ version.refresh_from_db()+ saved_query = version.saved_query+ assert saved_query is not None+ saved_query.status = DataWarehouseSavedQuery.Status.COMPLETED+ saved_query.last_run_at = timezone.now()+ saved_query.table = DataWarehouseTable.objects.create(+ team=self.team,+ name="trends_breakdown_secure",+ format=DataWarehouseTable.TableFormat.Parquet,+ url_pattern="s3://test-bucket/trends-breakdown-secure",+ )+ saved_query.save()++ # Property with a key but no value: passes the deprecated-override gate yet yields no filter.+ with mock.patch.object(EndpointExecutionService, "_execute_query_and_respond", return_value=Response({})):+ response = self.client.post(+ f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/run",+ {"filters_override": {"properties": [{"key": "$browser", "type": "event"}]}},+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.json())+ self.assertIn("Required variable", str(response.json()))++ # A filters_override that DOES carry a usable value still satisfies the requirement.+ with mock.patch.object(EndpointExecutionService, "_execute_query_and_respond", return_value=Response({})):+ response = self.client.post(+ f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/run",+ {"filters_override": {"properties": [{"key": "$browser", "type": "event", "value": "Chrome"}]}},+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())++ def test_materialized_multi_breakdown_filters_override_does_not_bypass_required_breakdowns(self):+ # SECURITY: filters_override applies only its first property as a single breakdown filter, so+ # it can never satisfy a multi-breakdown endpoint — supplying one value must not let the caller+ # omit the other required breakdown variables (which would leak rows across them).+ trends_multi_breakdown = {+ "kind": "TrendsQuery",+ "series": [{"kind": "EventsNode", "event": "$pageview", "math": "total"}],+ "dateRange": {"date_from": "-7d"},+ "interval": "day",+ "breakdownFilter": {+ "breakdowns": [+ {"property": "$browser", "type": "event"},+ {"property": "$os", "type": "event"},+ ],+ "breakdown_limit": 5,+ },+ }+ _create_event(team=self.team, event="$pageview", distinct_id="user1")+ flush_persons_and_events()++ endpoint = create_endpoint_with_version(+ name="trends_multi_breakdown_secure",+ team=self.team,+ query=trends_multi_breakdown,+ created_by=self.user,+ is_active=True,+ )+ response = self.client.patch(+ f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/",+ {"is_materialized": True, "data_freshness_seconds": 43200},+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())++ version = endpoint.versions.first()+ version.refresh_from_db()+ saved_query = version.saved_query+ assert saved_query is not None+ saved_query.status = DataWarehouseSavedQuery.Status.COMPLETED+ saved_query.last_run_at = timezone.now()+ saved_query.table = DataWarehouseTable.objects.create(+ team=self.team,+ name="trends_multi_breakdown_secure",+ format=DataWarehouseTable.TableFormat.Parquet,+ url_pattern="s3://test-bucket/trends-multi-breakdown-secure",+ )+ saved_query.save()++ # Supplying only one breakdown value via filters_override leaves $os unfiltered.+ with mock.patch.object(EndpointExecutionService, "_execute_query_and_respond", return_value=Response({})):+ response = self.client.post(+ f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/run",+ {"filters_override": {"properties": [{"key": "$browser", "type": "event", "value": "Chrome"}]}},+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.json())+ self.assertIn("Required variable", str(response.json()))+def test_materialized_hogql_endpoint_with_variable_executes_correctly(self):"""Test that HogQL endpoints with variables work when materialized.@@ -1130,7 +1264,9 @@ class TestEndpointMaterialization(ClickhouseTestMixin, APIBaseTest):saved_query.save()# Execute with variable filter- with mock.patch.object(EndpointViewSet, "_execute_query_and_respond", return_value=Response({})) as mock_exec:+ with mock.patch.object(+ EndpointExecutionService, "_execute_query_and_respond", return_value=Response({})+ ) as mock_exec:response = self.client.post(f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/run",{"variables": {"event_name": "$pageview"}},@@ -1352,7 +1488,9 @@ class TestEndpointMaterialization(ClickhouseTestMixin, APIBaseTest):# Update with a new query — version creation succeeds, but materialization failsnew_query = {"kind": "HogQLQuery", "query": "SELECT * FROM events WHERE timestamp > now() - INTERVAL 1 DAY"}with mock.patch.object(- EndpointViewSet, "_enable_materialization_inner", side_effect=Exception("Temporal unavailable")+ EndpointMaterializationService,+ "_enable_materialization_inner",+ side_effect=Exception("Temporal unavailable"),):response = self.client.put(f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/",@@ -1380,7 +1518,9 @@ class TestEndpointMaterialization(ClickhouseTestMixin, APIBaseTest):)with mock.patch.object(- EndpointViewSet, "_enable_materialization_inner", side_effect=Exception("Temporal unavailable")+ EndpointMaterializationService,+ "_enable_materialization_inner",+ side_effect=Exception("Temporal unavailable"),):response = self.client.patch(f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/",@@ -1388,7 +1528,8 @@ class TestEndpointMaterialization(ClickhouseTestMixin, APIBaseTest):format="json",)- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ # Unexpected internal failures surface as a server error, not a request error+ self.assertEqual(response.status_code, status.HTTP_500_INTERNAL_SERVER_ERROR)def test_materialized_relative_date_range_advances_on_refresh(self):_create_event(team=self.team, event="$pageview", distinct_id="u1")@@ -1495,6 +1636,83 @@ class TestEndpointMaterialization(ClickhouseTestMixin, APIBaseTest):writes = [q["sql"] for q in ctx.captured_queries if q["sql"].lstrip().lower().startswith(write_prefixes)]self.assertEqual(writes, [], f"build_endpoint_hogql wrote to Postgres: {writes}")+ def test_deactivating_one_version_keeps_current_version_materialization(self):+ """PATCH ?version=N {is_active: false} must not touch the current version's materialization."""+ endpoint = create_endpoint_with_version(+ name="version-deactivate-endpoint",+ team=self.team,+ query=self.sample_hogql_query,+ created_by=self.user,+ is_active=True,+ )++ # Create v2 by changing the query+ response = self.client.patch(+ f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/",+ {"query": {"kind": "HogQLQuery", "query": "SELECT event FROM events LIMIT 5"}},+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())++ # Materialize v2 (the current version)+ response = self.client.patch(+ f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/",+ {"is_materialized": True},+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())+ v2 = endpoint.get_version(2)+ self.assertIsNotNone(v2.saved_query)++ # Deactivate v1 only+ response = self.client.patch(+ f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/",+ {"is_active": False, "version": 1},+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())++ v1 = endpoint.get_version(1)+ self.assertFalse(v1.is_active)+ endpoint.refresh_from_db()+ self.assertTrue(endpoint.is_active)++ # v2's materialization must be untouched+ v2.refresh_from_db()+ self.assertIsNotNone(v2.saved_query_id, "current version's materialization was disabled by mistake")+ assert v2.saved_query is not None+ self.assertFalse(v2.saved_query.deleted)++ def test_enable_materialization_does_not_hijack_user_saved_query(self):+ """A user-created saved query whose name collides with {endpoint}_v{n} must not be taken over."""+ endpoint = create_endpoint_with_version(+ name="hijack-target",+ team=self.team,+ query=self.sample_hogql_query,+ created_by=self.user,+ is_active=True,+ )+ user_query = {"kind": "HogQLQuery", "query": "SELECT 42 AS answer"}+ user_saved_query = DataWarehouseSavedQuery.objects.create(+ team=self.team,+ name="hijack-target_v1",+ query=user_query,+ )++ response = self.client.patch(+ f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/",+ {"is_materialized": True},+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.json())++ user_saved_query.refresh_from_db()+ self.assertEqual(user_saved_query.query, user_query, "user's saved query was overwritten")+ self.assertFalse(user_saved_query.is_materialized)+ version = endpoint.get_version()+ self.assertIsNone(version.saved_query_id)+@pytest.mark.asyncioclass TestEndpointMaterializationTemporal:diff --git a/products/endpoints/backend/tests/test_endpoint_query_tagging.py b/products/endpoints/backend/tests/test_endpoint_query_tagging.pyindex 81d52cad37ae..8858edca849e 100644--- a/products/endpoints/backend/tests/test_endpoint_query_tagging.py+++ b/products/endpoints/backend/tests/test_endpoint_query_tagging.py@@ -43,7 +43,7 @@ class TestEndpointQueryTagging(ClickhouseTestMixin, APIBaseTest):)def test_run_via_session_auth_tags_endpoint_playground(self):- with mock.patch("products.endpoints.backend.api.tag_queries", wraps=tag_queries) as spy:+ with mock.patch("products.endpoints.backend.services.execution.tag_queries", wraps=tag_queries) as spy:response = self.client.post(self.run_url, {}, format="json")assert response.status_code == status.HTTP_200_OK, response.json()call = _find_endpoint_feature_call(spy)@@ -52,7 +52,7 @@ class TestEndpointQueryTagging(ClickhouseTestMixin, APIBaseTest):def test_run_via_personal_api_key_tags_endpoint_execution(self):self.client.logout()- with mock.patch("products.endpoints.backend.api.tag_queries", wraps=tag_queries) as spy:+ with mock.patch("products.endpoints.backend.services.execution.tag_queries", wraps=tag_queries) as spy:response = self.client.post(self.run_url,{},diff --git a/products/endpoints/backend/tests/test_insight_response_parity.py b/products/endpoints/backend/tests/test_insight_response_parity.pyindex f2a0c14b9d80..38bf8b1a24a2 100644--- a/products/endpoints/backend/tests/test_insight_response_parity.py+++ b/products/endpoints/backend/tests/test_insight_response_parity.py@@ -148,7 +148,7 @@ class TestInsightResponseParity(ClickhouseTestMixin, APIBaseTest):)with mock.patch(- "products.endpoints.backend.api.process_query_model",+ "products.endpoints.backend.services.execution.process_query_model",return_value=flat_response,):mat_resp = self._run_endpoint(endpoint)@@ -205,7 +205,7 @@ class TestInsightResponseParity(ClickhouseTestMixin, APIBaseTest):)with mock.patch(- "products.endpoints.backend.api.process_query_model",+ "products.endpoints.backend.services.execution.process_query_model",return_value=flat_response,):mat_resp = self._run_endpoint(endpoint, variables={"$browser": "Chrome"})@@ -360,7 +360,7 @@ class TestInsightResponseParity(ClickhouseTestMixin, APIBaseTest):)with mock.patch(- "products.endpoints.backend.api.process_query_model",+ "products.endpoints.backend.services.execution.process_query_model",return_value=flat_response,):mat_resp = self._run_endpoint(endpoint)@@ -430,7 +430,7 @@ class TestInsightResponseParity(ClickhouseTestMixin, APIBaseTest):)with mock.patch(- "products.endpoints.backend.api.process_query_model",+ "products.endpoints.backend.services.execution.process_query_model",return_value=flat_response,):mat_resp = self._run_endpoint(endpoint)@@ -494,7 +494,7 @@ class TestInsightResponseParity(ClickhouseTestMixin, APIBaseTest):)with mock.patch(- "products.endpoints.backend.api.process_query_model",+ "products.endpoints.backend.services.execution.process_query_model",return_value=flat_response,):mat_resp = self._run_endpoint(endpoint)@@ -549,7 +549,7 @@ class TestInsightResponseParity(ClickhouseTestMixin, APIBaseTest):)with mock.patch(- "products.endpoints.backend.api.process_query_model",+ "products.endpoints.backend.services.execution.process_query_model",return_value=flat_response,):mat_resp = self._run_endpoint(endpoint)@@ -650,7 +650,7 @@ class TestInsightResponseParity(ClickhouseTestMixin, APIBaseTest):)with mock.patch(- "products.endpoints.backend.api.process_query_model",+ "products.endpoints.backend.services.execution.process_query_model",return_value=flat_response,):mat_resp = self._run_endpoint(endpoint)diff --git a/products/endpoints/backend/tests/test_rate_limit.py b/products/endpoints/backend/tests/test_rate_limit.pyindex 09fc0497e7a0..81ac73d5022d 100644--- a/products/endpoints/backend/tests/test_rate_limit.py+++ b/products/endpoints/backend/tests/test_rate_limit.py@@ -40,6 +40,23 @@ class TestMaterializationCache(TestCase):clear_endpoint_materialization_cache(123, "test_endpoint")self.assertIsNone(is_endpoint_materialization_ready(123, "test_endpoint"))+ def test_version_keys_are_independent(self):+ set_endpoint_materialization_ready(123, "test_endpoint", True, version=2)+ self.assertTrue(is_endpoint_materialization_ready(123, "test_endpoint", version=2))+ self.assertIsNone(is_endpoint_materialization_ready(123, "test_endpoint"))+ self.assertIsNone(is_endpoint_materialization_ready(123, "test_endpoint", version=1))++ def test_clear_cache_with_versions_clears_version_and_current_keys(self):+ set_endpoint_materialization_ready(123, "test_endpoint", True)+ set_endpoint_materialization_ready(123, "test_endpoint", True, version=1)+ set_endpoint_materialization_ready(123, "test_endpoint", True, version=2)++ clear_endpoint_materialization_cache(123, "test_endpoint", versions=[1])++ self.assertIsNone(is_endpoint_materialization_ready(123, "test_endpoint"))+ self.assertIsNone(is_endpoint_materialization_ready(123, "test_endpoint", version=1))+ self.assertTrue(is_endpoint_materialization_ready(123, "test_endpoint", version=2))+class TestCheckAndCacheMaterializationStatus(APIBaseTest):def setUp(self):@@ -119,6 +136,82 @@ class TestCheckAndCacheMaterializationStatus(APIBaseTest):self.assertEqual(result, expected_ready)self.assertEqual(is_endpoint_materialization_ready(self.team.id, f"endpoint_{status}"), expected_ready)+ def _create_endpoint_with_materialized_v1_and_inline_v2(self, name="versioned_endpoint"):+ from products.endpoints.backend.models import EndpointVersion++ saved_query = DataWarehouseSavedQuery.objects.create(+ name=f"{name}_v1",+ team=self.team,+ query={"kind": "HogQLQuery", "query": "SELECT 1"},+ is_materialized=True,+ status=DataWarehouseSavedQuery.Status.COMPLETED,+ origin=DataWarehouseSavedQuery.Origin.ENDPOINT,+ )+ table = DataWarehouseTable.objects.create(+ team=self.team,+ name=f"{name}_table",+ format=DataWarehouseTable.TableFormat.Parquet,+ url_pattern=f"s3://test-bucket/{name}",+ )+ saved_query.table = table+ saved_query.save()+ endpoint = Endpoint.objects.create(+ name=name,+ team=self.team,+ created_by=self.user,+ is_active=True,+ current_version=2,+ )+ v1 = EndpointVersion.objects.create(+ endpoint=endpoint,+ team=self.team,+ version=1,+ query={"kind": "HogQLQuery", "query": "SELECT 1"},+ created_by=self.user,+ saved_query=saved_query,+ )+ v2 = EndpointVersion.objects.create(+ endpoint=endpoint,+ team=self.team,+ version=2,+ query={"kind": "HogQLQuery", "query": "SELECT 2"},+ created_by=self.user,+ )+ return endpoint, v1, v2, saved_query++ def test_explicit_version_checked_independently_of_current(self):+ self._create_endpoint_with_materialized_v1_and_inline_v2()++ # Current version (v2) is not materialized; v1 is.+ self.assertFalse(_check_and_cache_materialization_status(self.team.id, "versioned_endpoint"))+ self.assertTrue(_check_and_cache_materialization_status(self.team.id, "versioned_endpoint", version=1))+ self.assertFalse(_check_and_cache_materialization_status(self.team.id, "versioned_endpoint", version=2))++ def test_nonexistent_version_returns_false_and_caches(self):+ self._create_endpoint_with_materialized_v1_and_inline_v2(name="versioned_endpoint2")++ self.assertFalse(_check_and_cache_materialization_status(self.team.id, "versioned_endpoint2", version=99))+ self.assertFalse(is_endpoint_materialization_ready(self.team.id, "versioned_endpoint2", version=99))++ def test_update_materialization_ready_for_saved_query_updates_version_key(self):+ from products.endpoints.backend.rate_limit import update_materialization_ready_for_saved_query++ endpoint, v1, v2, saved_query = self._create_endpoint_with_materialized_v1_and_inline_v2(+ name="versioned_endpoint3"+ )++ # v1 is not the current version: only its own key is updated.+ update_materialization_ready_for_saved_query(self.team.id, saved_query, True)+ self.assertTrue(is_endpoint_materialization_ready(self.team.id, "versioned_endpoint3", version=1))+ self.assertIsNone(is_endpoint_materialization_ready(self.team.id, "versioned_endpoint3"))++ # Make v1 the current version: the "current" key is updated too.+ endpoint.current_version = 1+ endpoint.save()+ update_materialization_ready_for_saved_query(self.team.id, saved_query, False)+ self.assertFalse(is_endpoint_materialization_ready(self.team.id, "versioned_endpoint3", version=1))+ self.assertFalse(is_endpoint_materialization_ready(self.team.id, "versioned_endpoint3"))+class TestIsMaterializedEndpointRequest(APIBaseTest):def setUp(self):@@ -147,6 +240,8 @@ class TestIsMaterializedEndpointRequest(APIBaseTest):set_endpoint_materialization_ready(123, "test", True)request = MagicMock()+ request.data = {}+ request.query_params = {}view = MagicMock()view.team_id = 123view.kwargs = {"name": "test"}@@ -191,6 +286,8 @@ class TestIsMaterializedEndpointRequest(APIBaseTest):self.assertIsNone(is_endpoint_materialization_ready(self.team.id, "lazy_endpoint"))request = MagicMock()+ request.data = {}+ request.query_params = {}view = MagicMock()view.team_id = self.team.idview.kwargs = {"name": "lazy_endpoint"}@@ -198,6 +295,37 @@ class TestIsMaterializedEndpointRequest(APIBaseTest):self.assertTrue(_is_materialized_endpoint_request(request, view))self.assertTrue(is_endpoint_materialization_ready(self.team.id, "lazy_endpoint"))+ @parameterized.expand(+ [+ ("body", {"version": 2}, {}),+ ("query_param", {}, {"version": "2"}),+ ]+ )+ def test_requested_version_drives_classification(self, _name, body, query_params):+ set_endpoint_materialization_ready(123, "test", True) # current version is ready+ set_endpoint_materialization_ready(123, "test", False, version=2) # v2 is not++ request = MagicMock()+ request.data = body+ request.query_params = query_params+ view = MagicMock()+ view.team_id = 123+ view.kwargs = {"name": "test"}++ self.assertFalse(_is_materialized_endpoint_request(request, view))++ def test_invalid_version_param_falls_back_to_current(self):+ set_endpoint_materialization_ready(123, "test", True)++ request = MagicMock()+ request.data = {}+ request.query_params = {"version": "not-a-number"}+ view = MagicMock()+ view.team_id = 123+ view.kwargs = {"name": "test"}++ self.assertTrue(_is_materialized_endpoint_request(request, view))+class TestEndpointThrottles(APIBaseTest):def setUp(self):@@ -230,6 +358,8 @@ class TestEndpointThrottles(APIBaseTest):]:throttle = throttle_class()request = MagicMock()+ request.data = {}+ request.query_params = {}view = MagicMock()view.team_id = self.team.idview.kwargs = {"name": "mat_endpoint"}diff --git a/products/endpoints/backend/tests/test_variable_materialization.py b/products/endpoints/backend/tests/test_variable_materialization.pyindex 55840b4d7c86..d528a6425b0e 100644--- a/products/endpoints/backend/tests/test_variable_materialization.py+++ b/products/endpoints/backend/tests/test_variable_materialization.py@@ -8,7 +8,7 @@ from parameterized import parameterizedfrom posthog.hogql import astfrom posthog.hogql.parser import parse_select-from products.endpoints.backend.materialization import (+from products.endpoints.backend.materialization_transforms import (DownstreamCTEShape,_build_cte_read_graph,_classify_downstream_cte,@@ -747,7 +747,7 @@ class TestCombinatorReaggregation(APIBaseTest):])def test_reaggregatable_combinators_allowed(self, func_name, expected_reagg):- from products.endpoints.backend.materialization import get_reaggregation+ from products.endpoints.backend.materialization_transforms import get_reaggregationreagg = get_reaggregation(func_name)assert reagg is not None, f"{func_name} should be re-aggregatable"@@ -767,7 +767,7 @@ class TestCombinatorReaggregation(APIBaseTest):])def test_non_reaggregatable_functions_rejected(self, func_name):- from products.endpoints.backend.materialization import get_reaggregation+ from products.endpoints.backend.materialization_transforms import get_reaggregationreagg = get_reaggregation(func_name)assert reagg is None, f"{func_name} should NOT be re-aggregatable"@@ -819,7 +819,7 @@ class TestStripCombinators(APIBaseTest):])def test_strips_to_known_base(self, func_name, expected_base):- from products.endpoints.backend.materialization import _strip_combinators+ from products.endpoints.backend.materialization_transforms import _strip_combinatorsassert _strip_combinators(func_name) == expected_base@@ -835,13 +835,13 @@ class TestStripCombinators(APIBaseTest):])def test_returns_none_for_unknown(self, func_name):- from products.endpoints.backend.materialization import _strip_combinators+ from products.endpoints.backend.materialization_transforms import _strip_combinatorsresult = _strip_combinators(func_name)# Should return the base but it won't be in REAGGREGATABLE_BASE_FUNCTIONS# For truly unknown functions, returns Noneif result is not None:- from products.endpoints.backend.materialization import REAGGREGATABLE_BASE_FUNCTIONS+ from products.endpoints.backend.materialization_transforms import REAGGREGATABLE_BASE_FUNCTIONS# The base was found but it's not in the registry — that's the expected path# for functions like uniq, avg whose base is known but not re-aggregatable@@ -1407,7 +1407,7 @@ class TestMaterializedQueryExecution(APIBaseTest):assert True # See _transform_select_for_materialized_table implementationdef test_select_transformation_with_alias(self):- from products.endpoints.backend.materialization import transform_select_for_materialized_table+ from products.endpoints.backend.materialization_transforms import transform_select_for_materialized_tablequery_str = "SELECT count() as total, toStartOfDay(timestamp) as date FROM events"parsed = parse_select(query_str)@@ -1429,7 +1429,7 @@ class TestMaterializedQueryExecution(APIBaseTest):assert transformed[1].is_aggregate is Falsedef test_select_transformation_without_alias(self):- from products.endpoints.backend.materialization import transform_select_for_materialized_table+ from products.endpoints.backend.materialization_transforms import transform_select_for_materialized_tablequery_str = "SELECT count() FROM events"parsed = parse_select(query_str)@@ -1684,7 +1684,7 @@ class TestTransformQuerySnapshots(APIBaseTest):assert group_by_columns.count("event") == 1, f"GROUP BY has duplicate 'event': {group_by_columns}"def test_ast_node_not_shared_between_select_and_group_by(self):- from products.endpoints.backend.materialization import MaterializationTransformer+ from products.endpoints.backend.materialization_transforms import MaterializationTransformerquery_str = "SELECT count() FROM events WHERE toDate(timestamp) >= {variables.from_date}"variables = {"var-1": {"code_name": "from_date", "value": "2024-01-01"}}@@ -1721,7 +1721,7 @@ class TestMaterializedReadPath(APIBaseTest):def _build_read_query(self, query_str: str, variables_meta: dict, variable_values: dict) -> str:"""Simulate the materialized read path: analyze variables, then build a SELECT with filters."""- from products.endpoints.backend.api import EndpointViewSet+ from products.endpoints.backend.services.strategies import apply_where_filterhogql_query = {"kind": "HogQLQuery", "query": query_str, "variables": variables_meta}_, _, var_infos = analyze_variables_for_materialization(hogql_query)@@ -1731,11 +1731,10 @@ class TestMaterializedReadPath(APIBaseTest):select_from=ast.JoinExpr(table=ast.Field(chain=["materialized_table"])),)- viewset = EndpointViewSet()for mat_var in var_infos:var_value = variable_values.get(mat_var.code_name)if var_value is not None:- viewset._apply_where_filter(+ apply_where_filter(select_query,mat_var.code_name,var_value,@@ -2609,7 +2608,7 @@ class TestDownstreamCTEClassifier(APIBaseTest):def test_extract_aggregate_name_canonicalizes_count_distinct(self, src, expected):from posthog.hogql.parser import parse_expr as _parse_expr- from products.endpoints.backend.materialization import _extract_aggregate_name as _extract+ from products.endpoints.backend.materialization_transforms import _extract_aggregate_name as _extractassert _extract(_parse_expr(src)) == expected@@ -2625,7 +2624,7 @@ class TestDownstreamCTEClassifier(APIBaseTest):def test_extract_aggregate_name_canonicalizes_base_aggregates(self, src, expected):from posthog.hogql.parser import parse_expr as _parse_expr- from products.endpoints.backend.materialization import _extract_aggregate_name as _extract+ from products.endpoints.backend.materialization_transforms import _extract_aggregate_name as _extractassert _extract(_parse_expr(src)) == expecteddiff --git a/products/signals/backend/migrations/0039_alter_signalsourceconfig_source_product_and_more.py b/products/signals/backend/migrations/0039_alter_signalsourceconfig_source_product_and_more.pynew file mode 100644index 000000000000..90a085d99277--- /dev/null+++ b/products/signals/backend/migrations/0039_alter_signalsourceconfig_source_product_and_more.py@@ -0,0 +1,57 @@+# Generated by Django 5.2.14 on 2026-06-17 00:00++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("signals", "0038_alter_signalsourceconfig_source_product_and_more"),+ ]++ operations = [+ migrations.AlterField(+ model_name="signalsourceconfig",+ name="source_product",+ field=models.CharField(+ choices=[+ ("session_replay", "Session replay"),+ ("llm_analytics", "LLM analytics"),+ ("github", "GitHub"),+ ("linear", "Linear"),+ ("zendesk", "Zendesk"),+ ("conversations", "Conversations"),+ ("error_tracking", "Error tracking"),+ ("pganalyze", "pganalyze"),+ ("signals_scout", "Signals scout"),+ ("logs", "Logs"),+ ("health_checks", "Health checks"),+ ("endpoints", "Endpoints"),+ ],+ max_length=100,+ ),+ ),+ migrations.AlterField(+ model_name="signalsourceconfig",+ name="source_type",+ field=models.CharField(+ choices=[+ ("session_analysis_cluster", "Session analysis cluster"),+ ("evaluation", "Evaluation"),+ ("issue", "Issue"),+ ("ticket", "Ticket"),+ ("issue_created", "Issue created"),+ ("issue_reopened", "Issue reopened"),+ ("issue_spiking", "Issue spiking"),+ ("cross_source_issue", "Cross source issue"),+ ("alert_state_change", "Alert state change"),+ ("health_issue", "Health issue"),+ ("endpoint_execution_failed", "Endpoint execution failed"),+ (+ "endpoint_breakdown_limit_exceeded",+ "Endpoint breakdown limit exceeded",+ ),+ ],+ max_length=100,+ ),+ ),+ ]diff --git a/products/signals/backend/migrations/max_migration.txt b/products/signals/backend/migrations/max_migration.txtindex 102b197a4652..b0224fdf20d0 100644--- a/products/signals/backend/migrations/max_migration.txt+++ b/products/signals/backend/migrations/max_migration.txt@@ -1 +1 @@-0038_alter_signalsourceconfig_source_product_and_more+0039_alter_signalsourceconfig_source_product_and_morediff --git a/products/signals/backend/models.py b/products/signals/backend/models.pyindex a4f8ec915666..3ec31c1664aa 100644--- a/products/signals/backend/models.py+++ b/products/signals/backend/models.py@@ -29,6 +29,7 @@ class SignalSourceConfig(UUIDModel):SIGNALS_SCOUT = "signals_scout", "Signals scout"LOGS = "logs", "Logs"HEALTH_CHECKS = "health_checks", "Health checks"+ ENDPOINTS = "endpoints", "Endpoints"class SourceType(models.TextChoices):SESSION_ANALYSIS_CLUSTER = "session_analysis_cluster", "Session analysis cluster"@@ -41,6 +42,8 @@ class SignalSourceConfig(UUIDModel):CROSS_SOURCE_ISSUE = "cross_source_issue", "Cross source issue"ALERT_STATE_CHANGE = "alert_state_change", "Alert state change"HEALTH_ISSUE = "health_issue", "Health issue"+ ENDPOINT_EXECUTION_FAILED = "endpoint_execution_failed", "Endpoint execution failed"+ ENDPOINT_BREAKDOWN_LIMIT_EXCEEDED = "endpoint_breakdown_limit_exceeded", "Endpoint breakdown limit exceeded"team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, related_name="signal_source_configs")source_product = models.CharField(max_length=100, choices=SourceProduct)diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.tsindex e4700b347b5a..02b9b492e989 100644--- a/products/signals/frontend/generated/api.schemas.ts+++ b/products/signals/frontend/generated/api.schemas.ts@@ -1158,6 +1158,7 @@ export interface ForgetResponseApi {* * `signals_scout` - Signals scout* * `logs` - Logs* * `health_checks` - Health checks+ * * `endpoints` - Endpoints*/export type SourceProductEnumApi = (typeof SourceProductEnumApi)[keyof typeof SourceProductEnumApi]@@ -1173,6 +1174,7 @@ export const SourceProductEnumApi = {SignalsScout: 'signals_scout',Logs: 'logs',HealthChecks: 'health_checks',+ Endpoints: 'endpoints',} as const/**@@ -1186,6 +1188,8 @@ export const SourceProductEnumApi = {* * `cross_source_issue` - Cross source issue* * `alert_state_change` - Alert state change* * `health_issue` - Health issue+ * * `endpoint_execution_failed` - Endpoint execution failed+ * * `endpoint_breakdown_limit_exceeded` - Endpoint breakdown limit exceeded*/export type SignalSourceConfigSourceTypeEnumApi =(typeof SignalSourceConfigSourceTypeEnumApi)[keyof typeof SignalSourceConfigSourceTypeEnumApi]@@ -1201,6 +1205,8 @@ export const SignalSourceConfigSourceTypeEnumApi = {CrossSourceIssue: 'cross_source_issue',AlertStateChange: 'alert_state_change',HealthIssue: 'health_issue',+ EndpointExecutionFailed: 'endpoint_execution_failed',+ EndpointBreakdownLimitExceeded: 'endpoint_breakdown_limit_exceeded',} as constexport interface SignalSourceConfigApi {diff --git a/products/signals/frontend/generated/api.zod.ts b/products/signals/frontend/generated/api.zod.tsindex 1d58c413414e..fa6caf0d1dfd 100644--- a/products/signals/frontend/generated/api.zod.ts+++ b/products/signals/frontend/generated/api.zod.ts@@ -280,9 +280,10 @@ export const SignalsSourceConfigsCreateBody = /* @__PURE__ */ zod.object({'signals_scout','logs','health_checks',+ 'endpoints',]).describe(- '\* `session_replay` - Session replay\n\* `llm_analytics` - LLM analytics\n\* `github` - GitHub\n\* `linear` - Linear\n\* `zendesk` - Zendesk\n\* `conversations` - Conversations\n\* `error_tracking` - Error tracking\n\* `pganalyze` - pganalyze\n\* `signals_scout` - Signals scout\n\* `logs` - Logs\n\* `health_checks` - Health checks'+ '\* `session_replay` - Session replay\n\* `llm_analytics` - LLM analytics\n\* `github` - GitHub\n\* `linear` - Linear\n\* `zendesk` - Zendesk\n\* `conversations` - Conversations\n\* `error_tracking` - Error tracking\n\* `pganalyze` - pganalyze\n\* `signals_scout` - Signals scout\n\* `logs` - Logs\n\* `health_checks` - Health checks\n\* `endpoints` - Endpoints'),source_type: zod.enum([@@ -296,9 +297,11 @@ export const SignalsSourceConfigsCreateBody = /* @__PURE__ */ zod.object({'cross_source_issue','alert_state_change','health_issue',+ 'endpoint_execution_failed',+ 'endpoint_breakdown_limit_exceeded',]).describe(- '\* `session_analysis_cluster` - Session analysis cluster\n\* `evaluation` - Evaluation\n\* `issue` - Issue\n\* `ticket` - Ticket\n\* `issue_created` - Issue created\n\* `issue_reopened` - Issue reopened\n\* `issue_spiking` - Issue spiking\n\* `cross_source_issue` - Cross source issue\n\* `alert_state_change` - Alert state change\n\* `health_issue` - Health issue'+ '\* `session_analysis_cluster` - Session analysis cluster\n\* `evaluation` - Evaluation\n\* `issue` - Issue\n\* `ticket` - Ticket\n\* `issue_created` - Issue created\n\* `issue_reopened` - Issue reopened\n\* `issue_spiking` - Issue spiking\n\* `cross_source_issue` - Cross source issue\n\* `alert_state_change` - Alert state change\n\* `health_issue` - Health issue\n\* `endpoint_execution_failed` - Endpoint execution failed\n\* `endpoint_breakdown_limit_exceeded` - Endpoint breakdown limit exceeded'),enabled: zod.boolean().optional(),config: zod.unknown().optional(),@@ -318,9 +321,10 @@ export const SignalsSourceConfigsUpdateBody = /* @__PURE__ */ zod.object({'signals_scout','logs','health_checks',+ 'endpoints',]).describe(- '\* `session_replay` - Session replay\n\* `llm_analytics` - LLM analytics\n\* `github` - GitHub\n\* `linear` - Linear\n\* `zendesk` - Zendesk\n\* `conversations` - Conversations\n\* `error_tracking` - Error tracking\n\* `pganalyze` - pganalyze\n\* `signals_scout` - Signals scout\n\* `logs` - Logs\n\* `health_checks` - Health checks'+ '\* `session_replay` - Session replay\n\* `llm_analytics` - LLM analytics\n\* `github` - GitHub\n\* `linear` - Linear\n\* `zendesk` - Zendesk\n\* `conversations` - Conversations\n\* `error_tracking` - Error tracking\n\* `pganalyze` - pganalyze\n\* `signals_scout` - Signals scout\n\* `logs` - Logs\n\* `health_checks` - Health checks\n\* `endpoints` - Endpoints'),source_type: zod.enum([@@ -334,9 +338,11 @@ export const SignalsSourceConfigsUpdateBody = /* @__PURE__ */ zod.object({'cross_source_issue','alert_state_change','health_issue',+ 'endpoint_execution_failed',+ 'endpoint_breakdown_limit_exceeded',]).describe(- '\* `session_analysis_cluster` - Session analysis cluster\n\* `evaluation` - Evaluation\n\* `issue` - Issue\n\* `ticket` - Ticket\n\* `issue_created` - Issue created\n\* `issue_reopened` - Issue reopened\n\* `issue_spiking` - Issue spiking\n\* `cross_source_issue` - Cross source issue\n\* `alert_state_change` - Alert state change\n\* `health_issue` - Health issue'+ '\* `session_analysis_cluster` - Session analysis cluster\n\* `evaluation` - Evaluation\n\* `issue` - Issue\n\* `ticket` - Ticket\n\* `issue_created` - Issue created\n\* `issue_reopened` - Issue reopened\n\* `issue_spiking` - Issue spiking\n\* `cross_source_issue` - Cross source issue\n\* `alert_state_change` - Alert state change\n\* `health_issue` - Health issue\n\* `endpoint_execution_failed` - Endpoint execution failed\n\* `endpoint_breakdown_limit_exceeded` - Endpoint breakdown limit exceeded'),enabled: zod.boolean().optional(),config: zod.unknown().optional(),@@ -356,10 +362,11 @@ export const SignalsSourceConfigsPartialUpdateBody = /* @__PURE__ */ zod.object('signals_scout','logs','health_checks',+ 'endpoints',]).optional().describe(- '\* `session_replay` - Session replay\n\* `llm_analytics` - LLM analytics\n\* `github` - GitHub\n\* `linear` - Linear\n\* `zendesk` - Zendesk\n\* `conversations` - Conversations\n\* `error_tracking` - Error tracking\n\* `pganalyze` - pganalyze\n\* `signals_scout` - Signals scout\n\* `logs` - Logs\n\* `health_checks` - Health checks'+ '\* `session_replay` - Session replay\n\* `llm_analytics` - LLM analytics\n\* `github` - GitHub\n\* `linear` - Linear\n\* `zendesk` - Zendesk\n\* `conversations` - Conversations\n\* `error_tracking` - Error tracking\n\* `pganalyze` - pganalyze\n\* `signals_scout` - Signals scout\n\* `logs` - Logs\n\* `health_checks` - Health checks\n\* `endpoints` - Endpoints'),source_type: zod.enum([@@ -373,10 +380,12 @@ export const SignalsSourceConfigsPartialUpdateBody = /* @__PURE__ */ zod.object('cross_source_issue','alert_state_change','health_issue',+ 'endpoint_execution_failed',+ 'endpoint_breakdown_limit_exceeded',]).optional().describe(- '\* `session_analysis_cluster` - Session analysis cluster\n\* `evaluation` - Evaluation\n\* `issue` - Issue\n\* `ticket` - Ticket\n\* `issue_created` - Issue created\n\* `issue_reopened` - Issue reopened\n\* `issue_spiking` - Issue spiking\n\* `cross_source_issue` - Cross source issue\n\* `alert_state_change` - Alert state change\n\* `health_issue` - Health issue'+ '\* `session_analysis_cluster` - Session analysis cluster\n\* `evaluation` - Evaluation\n\* `issue` - Issue\n\* `ticket` - Ticket\n\* `issue_created` - Issue created\n\* `issue_reopened` - Issue reopened\n\* `issue_spiking` - Issue spiking\n\* `cross_source_issue` - Cross source issue\n\* `alert_state_change` - Alert state change\n\* `health_issue` - Health issue\n\* `endpoint_execution_failed` - Endpoint execution failed\n\* `endpoint_breakdown_limit_exceeded` - Endpoint breakdown limit exceeded'),enabled: zod.boolean().optional(),config: zod.unknown().optional(),diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 448817f32618..666ad9fa8270 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -30440,6 +30440,7 @@ export namespace Schemas {* * `signals_scout` - Signals scout* * `logs` - Logs* * `health_checks` - Health checks+ * * `endpoints` - Endpoints*/export type SourceProductEnum = typeof SourceProductEnum[keyof typeof SourceProductEnum];@@ -30456,6 +30457,7 @@ export namespace Schemas {SignalsScout: 'signals_scout',Logs: 'logs',HealthChecks: 'health_checks',+ Endpoints: 'endpoints',} as const;/**@@ -30469,6 +30471,8 @@ export namespace Schemas {* * `cross_source_issue` - Cross source issue* * `alert_state_change` - Alert state change* * `health_issue` - Health issue+ * * `endpoint_execution_failed` - Endpoint execution failed+ * * `endpoint_breakdown_limit_exceeded` - Endpoint breakdown limit exceeded*/export type SignalSourceConfigSourceTypeEnum = typeof SignalSourceConfigSourceTypeEnum[keyof typeof SignalSourceConfigSourceTypeEnum];@@ -30484,6 +30488,8 @@ export namespace Schemas {CrossSourceIssue: 'cross_source_issue',AlertStateChange: 'alert_state_change',HealthIssue: 'health_issue',+ EndpointExecutionFailed: 'endpoint_execution_failed',+ EndpointBreakdownLimitExceeded: 'endpoint_breakdown_limit_exceeded',} as const;export interface SignalSourceConfig {diff --git a/services/mcp/src/generated/signals/api.ts b/services/mcp/src/generated/signals/api.tsindex 15a2fdea6c61..53cf789436b2 100644--- a/services/mcp/src/generated/signals/api.ts+++ b/services/mcp/src/generated/signals/api.ts@@ -573,9 +573,10 @@ export const SignalsSourceConfigsCreateBody = /* @__PURE__ */ zod.object({'signals_scout','logs','health_checks',+ 'endpoints',]).describe(- '* `session_replay` - Session replay\n* `llm_analytics` - LLM analytics\n* `github` - GitHub\n* `linear` - Linear\n* `zendesk` - Zendesk\n* `conversations` - Conversations\n* `error_tracking` - Error tracking\n* `pganalyze` - pganalyze\n* `signals_scout` - Signals scout\n* `logs` - Logs\n* `health_checks` - Health checks'+ '* `session_replay` - Session replay\n* `llm_analytics` - LLM analytics\n* `github` - GitHub\n* `linear` - Linear\n* `zendesk` - Zendesk\n* `conversations` - Conversations\n* `error_tracking` - Error tracking\n* `pganalyze` - pganalyze\n* `signals_scout` - Signals scout\n* `logs` - Logs\n* `health_checks` - Health checks\n* `endpoints` - Endpoints'),source_type: zod.enum([@@ -589,9 +590,11 @@ export const SignalsSourceConfigsCreateBody = /* @__PURE__ */ zod.object({'cross_source_issue','alert_state_change','health_issue',+ 'endpoint_execution_failed',+ 'endpoint_breakdown_limit_exceeded',]).describe(- '* `session_analysis_cluster` - Session analysis cluster\n* `evaluation` - Evaluation\n* `issue` - Issue\n* `ticket` - Ticket\n* `issue_created` - Issue created\n* `issue_reopened` - Issue reopened\n* `issue_spiking` - Issue spiking\n* `cross_source_issue` - Cross source issue\n* `alert_state_change` - Alert state change\n* `health_issue` - Health issue'+ '* `session_analysis_cluster` - Session analysis cluster\n* `evaluation` - Evaluation\n* `issue` - Issue\n* `ticket` - Ticket\n* `issue_created` - Issue created\n* `issue_reopened` - Issue reopened\n* `issue_spiking` - Issue spiking\n* `cross_source_issue` - Cross source issue\n* `alert_state_change` - Alert state change\n* `health_issue` - Health issue\n* `endpoint_execution_failed` - Endpoint execution failed\n* `endpoint_breakdown_limit_exceeded` - Endpoint breakdown limit exceeded'),enabled: zod.boolean().optional(),config: zod.unknown().optional(),@@ -629,9 +632,10 @@ export const SignalsSourceConfigsUpdateBody = /* @__PURE__ */ zod.object({'signals_scout','logs','health_checks',+ 'endpoints',]).describe(- '* `session_replay` - Session replay\n* `llm_analytics` - LLM analytics\n* `github` - GitHub\n* `linear` - Linear\n* `zendesk` - Zendesk\n* `conversations` - Conversations\n* `error_tracking` - Error tracking\n* `pganalyze` - pganalyze\n* `signals_scout` - Signals scout\n* `logs` - Logs\n* `health_checks` - Health checks'+ '* `session_replay` - Session replay\n* `llm_analytics` - LLM analytics\n* `github` - GitHub\n* `linear` - Linear\n* `zendesk` - Zendesk\n* `conversations` - Conversations\n* `error_tracking` - Error tracking\n* `pganalyze` - pganalyze\n* `signals_scout` - Signals scout\n* `logs` - Logs\n* `health_checks` - Health checks\n* `endpoints` - Endpoints'),source_type: zod.enum([@@ -645,9 +649,11 @@ export const SignalsSourceConfigsUpdateBody = /* @__PURE__ */ zod.object({'cross_source_issue','alert_state_change','health_issue',+ 'endpoint_execution_failed',+ 'endpoint_breakdown_limit_exceeded',]).describe(- '* `session_analysis_cluster` - Session analysis cluster\n* `evaluation` - Evaluation\n* `issue` - Issue\n* `ticket` - Ticket\n* `issue_created` - Issue created\n* `issue_reopened` - Issue reopened\n* `issue_spiking` - Issue spiking\n* `cross_source_issue` - Cross source issue\n* `alert_state_change` - Alert state change\n* `health_issue` - Health issue'+ '* `session_analysis_cluster` - Session analysis cluster\n* `evaluation` - Evaluation\n* `issue` - Issue\n* `ticket` - Ticket\n* `issue_created` - Issue created\n* `issue_reopened` - Issue reopened\n* `issue_spiking` - Issue spiking\n* `cross_source_issue` - Cross source issue\n* `alert_state_change` - Alert state change\n* `health_issue` - Health issue\n* `endpoint_execution_failed` - Endpoint execution failed\n* `endpoint_breakdown_limit_exceeded` - Endpoint breakdown limit exceeded'),enabled: zod.boolean().optional(),config: zod.unknown().optional(),@@ -676,10 +682,11 @@ export const SignalsSourceConfigsPartialUpdateBody = /* @__PURE__ */ zod.object('signals_scout','logs','health_checks',+ 'endpoints',]).optional().describe(- '* `session_replay` - Session replay\n* `llm_analytics` - LLM analytics\n* `github` - GitHub\n* `linear` - Linear\n* `zendesk` - Zendesk\n* `conversations` - Conversations\n* `error_tracking` - Error tracking\n* `pganalyze` - pganalyze\n* `signals_scout` - Signals scout\n* `logs` - Logs\n* `health_checks` - Health checks'+ '* `session_replay` - Session replay\n* `llm_analytics` - LLM analytics\n* `github` - GitHub\n* `linear` - Linear\n* `zendesk` - Zendesk\n* `conversations` - Conversations\n* `error_tracking` - Error tracking\n* `pganalyze` - pganalyze\n* `signals_scout` - Signals scout\n* `logs` - Logs\n* `health_checks` - Health checks\n* `endpoints` - Endpoints'),source_type: zod.enum([@@ -693,10 +700,12 @@ export const SignalsSourceConfigsPartialUpdateBody = /* @__PURE__ */ zod.object('cross_source_issue','alert_state_change','health_issue',+ 'endpoint_execution_failed',+ 'endpoint_breakdown_limit_exceeded',]).optional().describe(- '* `session_analysis_cluster` - Session analysis cluster\n* `evaluation` - Evaluation\n* `issue` - Issue\n* `ticket` - Ticket\n* `issue_created` - Issue created\n* `issue_reopened` - Issue reopened\n* `issue_spiking` - Issue spiking\n* `cross_source_issue` - Cross source issue\n* `alert_state_change` - Alert state change\n* `health_issue` - Health issue'+ '* `session_analysis_cluster` - Session analysis cluster\n* `evaluation` - Evaluation\n* `issue` - Issue\n* `ticket` - Ticket\n* `issue_created` - Issue created\n* `issue_reopened` - Issue reopened\n* `issue_spiking` - Issue spiking\n* `cross_source_issue` - Cross source issue\n* `alert_state_change` - Alert state change\n* `health_issue` - Health issue\n* `endpoint_execution_failed` - Endpoint execution failed\n* `endpoint_breakdown_limit_exceeded` - Endpoint breakdown limit exceeded'),enabled: zod.boolean().optional(),config: zod.unknown().optional(),diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-source-configs-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-source-configs-create.jsonindex a8681f46d94f..9a759eb2d28b 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-source-configs-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-source-configs-create.json@@ -6,7 +6,7 @@"type": "boolean"},"source_product": {- "description": "* `session_replay` - Session replay\n* `llm_analytics` - LLM analytics\n* `github` - GitHub\n* `linear` - Linear\n* `zendesk` - Zendesk\n* `conversations` - Conversations\n* `error_tracking` - Error tracking\n* `pganalyze` - pganalyze\n* `signals_scout` - Signals scout\n* `logs` - Logs\n* `health_checks` - Health checks",+ "description": "* `session_replay` - Session replay\n* `llm_analytics` - LLM analytics\n* `github` - GitHub\n* `linear` - Linear\n* `zendesk` - Zendesk\n* `conversations` - Conversations\n* `error_tracking` - Error tracking\n* `pganalyze` - pganalyze\n* `signals_scout` - Signals scout\n* `logs` - Logs\n* `health_checks` - Health checks\n* `endpoints` - Endpoints","enum": ["session_replay","llm_analytics",@@ -18,12 +18,13 @@"pganalyze","signals_scout","logs",- "health_checks"+ "health_checks",+ "endpoints"],"type": "string"},"source_type": {- "description": "* `session_analysis_cluster` - Session analysis cluster\n* `evaluation` - Evaluation\n* `issue` - Issue\n* `ticket` - Ticket\n* `issue_created` - Issue created\n* `issue_reopened` - Issue reopened\n* `issue_spiking` - Issue spiking\n* `cross_source_issue` - Cross source issue\n* `alert_state_change` - Alert state change\n* `health_issue` - Health issue",+ "description": "* `session_analysis_cluster` - Session analysis cluster\n* `evaluation` - Evaluation\n* `issue` - Issue\n* `ticket` - Ticket\n* `issue_created` - Issue created\n* `issue_reopened` - Issue reopened\n* `issue_spiking` - Issue spiking\n* `cross_source_issue` - Cross source issue\n* `alert_state_change` - Alert state change\n* `health_issue` - Health issue\n* `endpoint_execution_failed` - Endpoint execution failed\n* `endpoint_breakdown_limit_exceeded` - Endpoint breakdown limit exceeded","enum": ["session_analysis_cluster","evaluation",@@ -34,7 +35,9 @@"issue_spiking","cross_source_issue","alert_state_change",- "health_issue"+ "health_issue",+ "endpoint_execution_failed",+ "endpoint_breakdown_limit_exceeded"],"type": "string"}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-source-configs-partial-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-source-configs-partial-update.jsonindex 2a1bcaee3cc3..f89e9d2c3e7a 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-source-configs-partial-update.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-source-configs-partial-update.json@@ -10,7 +10,7 @@"type": "string"},"source_product": {- "description": "* `session_replay` - Session replay\n* `llm_analytics` - LLM analytics\n* `github` - GitHub\n* `linear` - Linear\n* `zendesk` - Zendesk\n* `conversations` - Conversations\n* `error_tracking` - Error tracking\n* `pganalyze` - pganalyze\n* `signals_scout` - Signals scout\n* `logs` - Logs\n* `health_checks` - Health checks",+ "description": "* `session_replay` - Session replay\n* `llm_analytics` - LLM analytics\n* `github` - GitHub\n* `linear` - Linear\n* `zendesk` - Zendesk\n* `conversations` - Conversations\n* `error_tracking` - Error tracking\n* `pganalyze` - pganalyze\n* `signals_scout` - Signals scout\n* `logs` - Logs\n* `health_checks` - Health checks\n* `endpoints` - Endpoints","enum": ["session_replay","llm_analytics",@@ -22,12 +22,13 @@"pganalyze","signals_scout","logs",- "health_checks"+ "health_checks",+ "endpoints"],"type": "string"},"source_type": {- "description": "* `session_analysis_cluster` - Session analysis cluster\n* `evaluation` - Evaluation\n* `issue` - Issue\n* `ticket` - Ticket\n* `issue_created` - Issue created\n* `issue_reopened` - Issue reopened\n* `issue_spiking` - Issue spiking\n* `cross_source_issue` - Cross source issue\n* `alert_state_change` - Alert state change\n* `health_issue` - Health issue",+ "description": "* `session_analysis_cluster` - Session analysis cluster\n* `evaluation` - Evaluation\n* `issue` - Issue\n* `ticket` - Ticket\n* `issue_created` - Issue created\n* `issue_reopened` - Issue reopened\n* `issue_spiking` - Issue spiking\n* `cross_source_issue` - Cross source issue\n* `alert_state_change` - Alert state change\n* `health_issue` - Health issue\n* `endpoint_execution_failed` - Endpoint execution failed\n* `endpoint_breakdown_limit_exceeded` - Endpoint breakdown limit exceeded","enum": ["session_analysis_cluster","evaluation",@@ -38,7 +39,9 @@"issue_spiking","cross_source_issue","alert_state_change",- "health_issue"+ "health_issue",+ "endpoint_execution_failed",+ "endpoint_breakdown_limit_exceeded"],"type": "string"}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-source-configs-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-source-configs-update.jsonindex d68585a7399f..3ba284f07870 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-source-configs-update.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-source-configs-update.json@@ -10,7 +10,7 @@"type": "string"},"source_product": {- "description": "* `session_replay` - Session replay\n* `llm_analytics` - LLM analytics\n* `github` - GitHub\n* `linear` - Linear\n* `zendesk` - Zendesk\n* `conversations` - Conversations\n* `error_tracking` - Error tracking\n* `pganalyze` - pganalyze\n* `signals_scout` - Signals scout\n* `logs` - Logs\n* `health_checks` - Health checks",+ "description": "* `session_replay` - Session replay\n* `llm_analytics` - LLM analytics\n* `github` - GitHub\n* `linear` - Linear\n* `zendesk` - Zendesk\n* `conversations` - Conversations\n* `error_tracking` - Error tracking\n* `pganalyze` - pganalyze\n* `signals_scout` - Signals scout\n* `logs` - Logs\n* `health_checks` - Health checks\n* `endpoints` - Endpoints","enum": ["session_replay","llm_analytics",@@ -22,12 +22,13 @@"pganalyze","signals_scout","logs",- "health_checks"+ "health_checks",+ "endpoints"],"type": "string"},"source_type": {- "description": "* `session_analysis_cluster` - Session analysis cluster\n* `evaluation` - Evaluation\n* `issue` - Issue\n* `ticket` - Ticket\n* `issue_created` - Issue created\n* `issue_reopened` - Issue reopened\n* `issue_spiking` - Issue spiking\n* `cross_source_issue` - Cross source issue\n* `alert_state_change` - Alert state change\n* `health_issue` - Health issue",+ "description": "* `session_analysis_cluster` - Session analysis cluster\n* `evaluation` - Evaluation\n* `issue` - Issue\n* `ticket` - Ticket\n* `issue_created` - Issue created\n* `issue_reopened` - Issue reopened\n* `issue_spiking` - Issue spiking\n* `cross_source_issue` - Cross source issue\n* `alert_state_change` - Alert state change\n* `health_issue` - Health issue\n* `endpoint_execution_failed` - Endpoint execution failed\n* `endpoint_breakdown_limit_exceeded` - Endpoint breakdown limit exceeded","enum": ["session_analysis_cluster","evaluation",@@ -38,7 +39,9 @@"issue_spiking","cross_source_issue","alert_state_change",- "health_issue"+ "health_issue",+ "endpoint_execution_failed",+ "endpoint_breakdown_limit_exceeded"],"type": "string"}