Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(endpoints): throttle inline fallbacks at the inline rate (#96049)

Jovan Sakovicc200352d4def
diff --git a/products/endpoints/backend/facade/api.py b/products/endpoints/backend/facade/api.py
index 524f53258057..43be2c60f9e2 100644
--- a/products/endpoints/backend/facade/api.py
+++ b/products/endpoints/backend/facade/api.py
@@ -149,6 +149,11 @@ def is_materialization_ready(team_id: int, endpoint_name: str, version: int | No
return rate_limit.check_materialization_ready(team_id, endpoint_name, version)
+def is_materialized_request(team_id: int, endpoint_name: str, version: int | None, request_data: object) -> bool:
+ """Whether this run request will be served from the targeted version's materialized table."""
+ return rate_limit.check_materialized_request(team_id, endpoint_name, version, request_data)
+
+
__all__ = [
"REWRITE_CONTRACT",
"EndpointCrudService",
@@ -161,6 +166,7 @@ __all__ = [
"get_endpoint_version",
"get_last_execution_times",
"is_materialization_ready",
+ "is_materialized_request",
"list_endpoints",
"live_materialization_conditions_source",
"materialization_fix_enabled",
diff --git a/products/endpoints/backend/logic/crud.py b/products/endpoints/backend/logic/crud.py
index 25eec59f9348..338592e1aaa9 100644
--- a/products/endpoints/backend/logic/crud.py
+++ b/products/endpoints/backend/logic/crud.py
@@ -222,7 +222,7 @@ class EndpointCrudService:
)
step = "version_fields"
- self._apply_version_field_updates(target_version, data, raw_data, version_targeted)
+ self._apply_version_field_updates(endpoint, target_version, data, raw_data, version_targeted)
step = "materialization"
materialization_error = self._reconcile_materialization(
@@ -306,6 +306,7 @@ class EndpointCrudService:
def _apply_version_field_updates(
self,
+ endpoint: Endpoint,
target_version: EndpointVersion,
data: EndpointRequest,
raw_data: dict,
@@ -332,6 +333,9 @@ class EndpointCrudService:
if update_fields:
update_fields.append("updated_at")
target_version.save(update_fields=update_fields)
+ if {"data_freshness_seconds", "optional_breakdown_properties"} & set(update_fields):
+ # Both fields are part of the cached serving snapshot the throttle classifies from.
+ clear_endpoint_materialization_cache(self.team.pk, endpoint.name, versions=[target_version.version])
def _reconcile_materialization(
self,
diff --git a/products/endpoints/backend/logic/execution.py b/products/endpoints/backend/logic/execution.py
index 3ec5c017f9ec..904ec6c7febd 100644
--- a/products/endpoints/backend/logic/execution.py
+++ b/products/endpoints/backend/logic/execution.py
@@ -68,13 +68,10 @@ from posthog.permissions import is_authenticated_via_project_secret_api_key
from posthog.schema_migrations.upgrade import upgrade
from posthog.synthetic_user import SyntheticUser
-from products.data_modeling.backend.facade.api import (
- is_materialization_fresh,
- materialize_saved_query,
- saved_query_materialized_at,
-)
+from products.data_modeling.backend.facade.api import materialize_saved_query, saved_query_materialized_at
from products.endpoints.backend.exceptions import EndpointAtCapacity, EndpointQueryTooExpensive
from products.endpoints.backend.insight_transformers import MaterializedSeriesMismatchError
+from products.endpoints.backend.logic.materialized_serving import serving_state_for_version
from products.endpoints.backend.logic.pagination import EndpointPagination
from products.endpoints.backend.logic.strategies import EndpointQueryStrategy, strategy_for
from products.endpoints.backend.logs import build_execution_message, log_endpoint_execution
@@ -301,6 +298,26 @@ def _endpoint_refresh_mode_to_refresh_type(
return RefreshType.FORCE_BLOCKING
+def can_serve_from_materialized(
+ team: Team,
+ endpoint: Endpoint,
+ version: EndpointVersion,
+ data: EndpointRunRequest,
+ materialized_at: datetime | None,
+) -> bool:
+ """Whether this run request can be served from the version's materialized table.
+
+ Reads materialization state from the DB — the authoritative source. The throttle
+ caches the same snapshot in rate_limit.py; that cache is intentionally not consulted here.
+ """
+ if not version.is_materialized or not version.saved_query or not version.saved_query.table:
+ return False
+ state = serving_state_for_version(
+ version, strategy_for(endpoint, version, team), ready=True, materialized_at=materialized_at
+ )
+ return state.serves(data)
+
+
class EndpointExecutionService(PydanticModelMixin):
"""Executes an endpoint version, choosing the best execution path."""
@@ -405,42 +422,8 @@ class EndpointExecutionService(PydanticModelMixin):
version: EndpointVersion,
materialized_at: datetime | None,
) -> 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 the version's data freshness target)
- - User overrides present (variables, query)
- - 'direct' mode requested (explicitly bypass materialization)
- """
- if not version.is_materialized or not version.saved_query:
- return False
-
- if not version.saved_query.table or materialized_at is None:
- return False
-
- # Check if materialized data is stale. Keyed on the version's freshness target, not
- # saved_query.sync_frequency_interval — the v2 schedule migration nulls that field.
- if not is_materialization_fresh(materialized_at, version.data_freshness_seconds):
- return False
-
- # 'direct' mode explicitly bypasses materialization to run the original query
- if data.refresh == EndpointRefreshMode.DIRECT:
- 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
+ """Decide whether to use materialized table or inline execution."""
+ return can_serve_from_materialized(self.team, endpoint, version, data, materialized_at)
def _should_shadow_ducklake(self, endpoint: Endpoint, version: EndpointVersion | None) -> bool:
# Flag is scoped to orgs with a duckgres server; the worker re-checks before querying.
diff --git a/products/endpoints/backend/logic/materialization.py b/products/endpoints/backend/logic/materialization.py
index 783147d39b34..c4d8033855c6 100644
--- a/products/endpoints/backend/logic/materialization.py
+++ b/products/endpoints/backend/logic/materialization.py
@@ -174,6 +174,9 @@ class EndpointMaterializationService:
"""
try:
self._enable_materialization_inner(endpoint, version, data_freshness_seconds, bucket_overrides)
+ # The throttle may hold a not-ready snapshot cached before the enable. Drop it so the
+ # first completed run is picked up on the next request, not when the entry expires.
+ clear_endpoint_materialization_cache(self.team.pk, endpoint.name, versions=[version.version])
ENDPOINT_MATERIALIZATION_EVENT_TOTAL.labels(action="enable", status="success").inc()
if version.saved_query:
log_activity(
diff --git a/products/endpoints/backend/logic/materialized_serving.py b/products/endpoints/backend/logic/materialized_serving.py
new file mode 100644
index 000000000000..bc2b1bc2b3b6
--- /dev/null
+++ b/products/endpoints/backend/logic/materialized_serving.py
@@ -0,0 +1,112 @@
+"""The decision "can this run request be served from the materialized table".
+
+Shared by the execution service (which decides the execution path) and the run
+throttle (which grants the materialized rate budget), so the two cannot disagree.
+"""
+
+from collections.abc import Mapping
+from datetime import datetime
+from typing import TypedDict
+
+from posthog.schema import EndpointRefreshMode, EndpointRunRequest
+
+from posthog.dataclasses import frozen
+
+from products.data_modeling.backend.facade.api import is_materialization_fresh
+from products.endpoints.backend.logic.strategies import EndpointQueryStrategy
+from products.endpoints.backend.models import EndpointVersion
+
+
+class CachedServingSnapshot(TypedDict):
+ """The shape a snapshot takes in the throttle cache."""
+
+ ready: bool
+ materialized_at: str | None
+ freshness_seconds: int | None
+ servable_variables: list[str]
+
+
+@frozen
+class MaterializedServingState:
+ """What a version's materialized table can answer, captured at one moment.
+
+ Small enough to live in the throttle cache: classifying a request then needs
+ only this snapshot and the request body, with no database read.
+ """
+
+ ready: bool
+ materialized_at: datetime | None
+ freshness_seconds: int | None
+ servable_variables: frozenset[str]
+
+ def serves(self, data: EndpointRunRequest) -> bool:
+ if not self.ready or self.materialized_at is None:
+ return False
+ if not is_materialization_fresh(self.materialized_at, self.freshness_seconds):
+ return False
+ if data.refresh == EndpointRefreshMode.DIRECT:
+ return False
+ if data.variables:
+ requested = set(data.variables.keys())
+ if not self.servable_variables or not requested.issubset(self.servable_variables):
+ return False
+ return True
+
+ def to_cache(self) -> CachedServingSnapshot:
+ return {
+ "ready": self.ready,
+ "materialized_at": self.materialized_at.isoformat() if self.materialized_at else None,
+ "freshness_seconds": self.freshness_seconds,
+ "servable_variables": sorted(self.servable_variables),
+ }
+
+ @classmethod
+ def from_cache(cls, payload: Mapping[str, object]) -> "MaterializedServingState | None":
+ """The snapshot a cache entry holds, or None when the entry is not in this shape.
+
+ A cache entry outlives the code that wrote it, so a payload in another shape counts
+ as a miss. The caller then reads the database and rewrites the entry.
+ """
+ ready = payload.get("ready")
+ materialized_at = payload.get("materialized_at")
+ freshness_seconds = payload.get("freshness_seconds")
+ servable_variables = payload.get("servable_variables")
+ if (
+ not isinstance(ready, bool)
+ or not isinstance(materialized_at, str | None)
+ # bool is a subclass of int, so the int check alone would accept True here
+ or not isinstance(freshness_seconds, int | None)
+ or isinstance(freshness_seconds, bool)
+ or not isinstance(servable_variables, list)
+ or not all(isinstance(name, str) for name in servable_variables)
+ ):
+ return None
+ try:
+ parsed_at = datetime.fromisoformat(materialized_at) if materialized_at else None
+ except ValueError:
+ return None
+ return cls(
+ ready=ready,
+ materialized_at=parsed_at,
+ freshness_seconds=freshness_seconds,
+ servable_variables=frozenset(servable_variables),
+ )
+
+ @classmethod
+ def not_ready(cls) -> "MaterializedServingState":
+ return cls(ready=False, materialized_at=None, freshness_seconds=None, servable_variables=frozenset())
+
+
+def serving_state_for_version(
+ version: EndpointVersion,
+ strategy: EndpointQueryStrategy,
+ *,
+ ready: bool,
+ materialized_at: datetime | None,
+) -> MaterializedServingState:
+ return MaterializedServingState(
+ ready=ready,
+ materialized_at=materialized_at,
+ freshness_seconds=version.data_freshness_seconds,
+ servable_variables=frozenset(strategy.materialized_variable_names()) if ready else frozenset(),
+ )
diff --git a/products/endpoints/backend/logic/strategies.py b/products/endpoints/backend/logic/strategies.py
index 09b1c7f0f056..493ff308e66e 100644
--- a/products/endpoints/backend/logic/strategies.py
+++ b/products/endpoints/backend/logic/strategies.py
@@ -340,8 +340,8 @@ class EndpointQueryStrategy(abc.ABC):
"""
@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_variable_names(self) -> set[str]:
+ """Variables the materialized table can filter on; empty when it can answer none."""
def materialized_filters_override_satisfies_required(self, data: EndpointRunRequest) -> bool:
"""Whether ``data.filters_override`` actually supplies the required materialized filter.
@@ -426,13 +426,10 @@ class HogQLEndpointStrategy(EndpointQueryStrategy):
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}
+ return self.materialized_variable_names()
- 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 materialized_variable_names(self) -> set[str]:
+ return {v.code_name for v in self.materialized_variables}
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.
@@ -633,11 +630,8 @@ class InsightEndpointStrategy(EndpointQueryStrategy):
return all_breakdowns - optional
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_variable_names(self) -> set[str]:
+ return set(get_breakdown_properties(self._breakdown_filter))
def materialized_filters_override_satisfies_required(self, data: EndpointRunRequest) -> bool:
# apply_materialized_filters applies only the first property's value as a single positionless
diff --git a/products/endpoints/backend/presentation/throttles.py b/products/endpoints/backend/presentation/throttles.py
index ec22f9fd03ec..3cda2d0d49e5 100644
--- a/products/endpoints/backend/presentation/throttles.py
+++ b/products/endpoints/backend/presentation/throttles.py
@@ -1,7 +1,7 @@
"""DRF throttles for the endpoints run API.
-Materialized endpoints get a higher rate budget than inline ones. Readiness is
-resolved through the facade (cached, with a DB fallback); the throttle classes
+Requests served from a materialized table get a higher rate budget than inline
+ones. That classification is resolved through the facade; the throttle classes
and their request-parsing helpers are pure HTTP concerns and live here.
"""
@@ -15,7 +15,7 @@ from posthog.rate_limit import (
ProjectSecretApiKeyTeamRateThrottle,
)
-from products.endpoints.backend.facade.api import is_materialization_ready
+from products.endpoints.backend.facade.api import is_materialized_request
ENDPOINT_RATE_LIMITED_TOTAL = Counter(
"posthog_endpoint_rate_limited_total",
@@ -46,11 +46,20 @@ def _get_endpoint_info_from_request(request, view) -> tuple[int | None, str | No
def _is_materialized_endpoint_request(request, view) -> bool:
- """Check if this request targets a materialized endpoint version (cached check with lazy loading)."""
+ """Check if this request will be served from a materialized endpoint version."""
+ try:
+ body = request.data
+ except Exception:
+ # A body DRF cannot read takes the inline rate, because the view rejects the request.
+ # This has to be the first access to request.data: DRF replaces an unparsable body with
+ # an empty one, and an empty body reads as a clean materialized request. An unsupported
+ # media type instead raises on every access, and an error that escapes a throttle skips
+ # rate accounting for every scope.
+ return False
team_id, endpoint_name, version = _get_endpoint_info_from_request(request, view)
if not team_id or not endpoint_name:
return False
- return is_materialization_ready(team_id, endpoint_name, version)
+ return is_materialized_request(team_id, endpoint_name, version, body)
class _MaterializedRateMixin(SimpleRateThrottle):
diff --git a/products/endpoints/backend/rate_limit.py b/products/endpoints/backend/rate_limit.py
index 59eb912b3515..685916bb3389 100644
--- a/products/endpoints/backend/rate_limit.py
+++ b/products/endpoints/backend/rate_limit.py
@@ -1,20 +1,34 @@
-"""Materialization-readiness cache for endpoint versions.
+"""Materialized-serving cache for endpoint versions.
-Read by the presentation throttles (materialized endpoints get a higher rate
-budget) and written by the data-modeling Temporal workflow on materialization
-completion/failure. The DRF throttle classes themselves live in
+Read by the presentation throttles (a request served from a materialized table gets
+a higher rate budget). The DRF throttle classes themselves live in
``presentation/throttles.py``.
+
+The cached value is a ``MaterializedServingState`` snapshot, so classifying a request
+needs only the snapshot and the request body. The cache is read-through: the database
+is read on a miss, and the entry expires with the table's freshness window. Writes that
+change the snapshot (materialization enable/disable, freshness edits) clear the entry.
"""
from collections.abc import Iterable
+from datetime import timedelta
from django.core.cache import cache
+from django.utils import timezone
+
+from pydantic import ValidationError
+
+from posthog.schema import EndpointRefreshMode, EndpointRunRequest
-# 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}"
+from products.data_modeling.backend.facade.api import saved_query_materialized_at
+from products.endpoints.backend.logic.materialized_serving import MaterializedServingState, serving_state_for_version
+from products.endpoints.backend.logic.strategies import strategy_for
+from products.endpoints.backend.models import Endpoint, EndpointVersion
+
+MATERIALIZED_ENDPOINT_CACHE_KEY = "endpoint_materialized_state:{team_id}:{endpoint_name}:{version_label}"
MATERIALIZED_ENDPOINT_CACHE_TTL = 3600 # 1 hour fallback TTL
+# A snapshot that has gone stale is re-read this often, so a refreshed table regains the budget quickly.
+STALE_STATE_RECHECK_TTL = 60
CURRENT_VERSION_LABEL = "current"
@@ -29,31 +43,60 @@ def get_endpoint_materialization_cache_key(team_id: int, endpoint_name: str, ver
)
-def is_endpoint_materialization_ready(team_id: int, endpoint_name: str, version: int | None = None) -> bool | None:
- """
- Check if an endpoint version's materialization is ready (cached).
+def get_endpoint_materialization_state(
+ team_id: int, endpoint_name: str, version: int | None = None
+) -> MaterializedServingState | None:
+ """The cached serving snapshot, or None on a cache miss."""
+ payload = cache.get(get_endpoint_materialization_cache_key(team_id, endpoint_name, version))
+ if not isinstance(payload, dict):
+ return None
+ return MaterializedServingState.from_cache(payload)
- Returns:
- True if materialization is ready
- False if materialization is not ready
- None if cache miss (caller should check DB and populate cache)
- """
+
+def is_endpoint_materialization_ready(team_id: int, endpoint_name: str, version: int | None = None) -> bool | None:
+ """Cached readiness only: True/False, or None on a cache miss."""
+ state = get_endpoint_materialization_state(team_id, endpoint_name, version)
+ return state.ready if state is not None else None
+
+
+def _cache_timeout(state: MaterializedServingState, *, pending: bool = False) -> int:
+ # The cache only refills on a miss. A snapshot that outlives its freshness window would
+ # keep the endpoint on the inline rate after the next run refreshed the table, so the
+ # entry expires with the window.
+ if not state.ready or state.materialized_at is None or not state.freshness_seconds:
+ # A pending materialization becomes servable on its own, with nothing to refill the
+ # entry, so hold it only briefly. A version with no materialization keeps the full
+ # window, because it becomes servable only through an edit, which clears the entry.
+ return STALE_STATE_RECHECK_TTL if pending else MATERIALIZED_ENDPOINT_CACHE_TTL
+ remaining = (state.materialized_at + timedelta(seconds=state.freshness_seconds) - timezone.now()).total_seconds()
+ return int(max(STALE_STATE_RECHECK_TTL, min(remaining, MATERIALIZED_ENDPOINT_CACHE_TTL)))
+
+
+def set_endpoint_materialization_state(
+ team_id: int,
+ endpoint_name: str,
+ state: MaterializedServingState,
+ version: int | None = None,
+ *,
+ pending: bool = False,
+) -> None:
+ """Cache the snapshot. ``pending`` marks a materialization that has yet to produce a table."""
cache_key = get_endpoint_materialization_cache_key(team_id, endpoint_name, version)
- return cache.get(cache_key)
+ cache.set(cache_key, state.to_cache(), timeout=_cache_timeout(state, pending=pending))
def set_endpoint_materialization_ready(
team_id: int, endpoint_name: str, is_ready: bool, version: int | None = None
) -> None:
+ """Cache a bare readiness flag with no serving detail.
+
+ A True flag with no materialization time never serves a request, so callers with a
+ live version should cache a full snapshot through ``set_endpoint_materialization_state``.
"""
- 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, version)
- cache.set(cache_key, is_ready, timeout=MATERIALIZED_ENDPOINT_CACHE_TTL)
+ state = MaterializedServingState(
+ ready=is_ready, materialized_at=None, freshness_seconds=None, servable_variables=frozenset()
+ )
+ set_endpoint_materialization_state(team_id, endpoint_name, state, version)
def clear_endpoint_materialization_cache(
@@ -66,17 +109,28 @@ def clear_endpoint_materialization_cache(
cache.delete_many(keys)
+def _serving_state(endpoint: Endpoint, version: EndpointVersion, is_ready: bool) -> MaterializedServingState:
+ saved_query = version.saved_query
+ if not is_ready or saved_query is None:
+ return MaterializedServingState.not_ready()
+ return serving_state_for_version(
+ version,
+ strategy_for(endpoint, version, endpoint.team),
+ ready=True,
+ materialized_at=saved_query_materialized_at(saved_query),
+ )
+
+
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.
+ """Refresh the 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")
+ EndpointVersion.objects.select_related("endpoint", "endpoint__team")
.filter(saved_query=saved_query, endpoint__team_id=team_id)
.first()
)
@@ -84,40 +138,50 @@ def update_materialization_ready_for_saved_query(team_id: int, saved_query, is_r
return
endpoint_name = version.endpoint.name
- set_endpoint_materialization_ready(team_id, endpoint_name, is_ready, version=version.version)
+ state = _serving_state(version.endpoint, version, is_ready)
+ set_endpoint_materialization_state(team_id, endpoint_name, state, version=version.version)
if version.version == version.endpoint.current_version:
- set_endpoint_materialization_ready(team_id, endpoint_name, is_ready)
+ set_endpoint_materialization_state(team_id, endpoint_name, state)
-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 the targeted endpoint version (current when version is None) is ready
- for materialized execution.
- """
- from products.data_modeling.backend.facade.api import latest_saved_query_materialization_job
- from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery
- from products.endpoints.backend.models import Endpoint, EndpointVersion
+def _load_and_cache_materialization_state(
+ team_id: int, endpoint_name: str, version: int | None = None
+) -> MaterializedServingState:
+ """Read the targeted version (current when version is None) from the DB and cache its snapshot."""
try:
- endpoint = Endpoint.objects.get(team_id=team_id, name=endpoint_name, is_active=True, deleted=False)
+ endpoint = Endpoint.objects.select_related("team").get(
+ team_id=team_id, name=endpoint_name, is_active=True, deleted=False
+ )
endpoint_version = endpoint.get_version(version)
- saved_query = endpoint_version.saved_query
+ except (Endpoint.DoesNotExist, EndpointVersion.DoesNotExist):
+ state = MaterializedServingState.not_ready()
+ set_endpoint_materialization_state(team_id, endpoint_name, state, version=version)
+ return state
+
+ saved_query = endpoint_version.saved_query
+ if not endpoint_version.is_materialized or saved_query is None or saved_query.table_id is None:
+ state = MaterializedServingState.not_ready()
+ else:
+ # Same test the execution service applies: a live table plus a completed run. A
+ # failed run after a good one leaves the last table servable, so the newest
+ # job's status is not the readiness signal.
+ materialized_at = saved_query_materialized_at(saved_query)
+ state = serving_state_for_version(
+ endpoint_version,
+ strategy_for(endpoint, endpoint_version, endpoint.team),
+ ready=materialized_at is not None,
+ materialized_at=materialized_at,
+ )
+ # A backing saved query means materialization is enabled, so a first table can land at any
+ # moment without a request or an edit to refill this entry.
+ pending = not state.ready and endpoint_version.saved_query_id is not None
+ set_endpoint_materialization_state(team_id, endpoint_name, state, version=version, pending=pending)
+ return state
- is_ready = False
- if endpoint_version.is_materialized and saved_query is not None:
- # The v2 workflow records runs on DataModelingJob and never writes saved_query.status.
- latest_job = latest_saved_query_materialization_job(saved_query)
- status = latest_job.status if latest_job is not None else saved_query.status
- is_ready = status == DataWarehouseSavedQuery.Status.COMPLETED
- set_endpoint_materialization_ready(team_id, endpoint_name, is_ready, version=version)
- return is_ready
- except (Endpoint.DoesNotExist, EndpointVersion.DoesNotExist):
- set_endpoint_materialization_ready(team_id, endpoint_name, False, version=version)
- return False
+def _check_and_cache_materialization_status(team_id: int, endpoint_name: str, version: int | None = None) -> bool:
+ return _load_and_cache_materialization_state(team_id, endpoint_name, version).ready
def check_materialization_ready(team_id: int, endpoint_name: str, version: int | None = None) -> bool:
@@ -126,3 +190,25 @@ def check_materialization_ready(team_id: int, endpoint_name: str, version: int |
if cached_status is None:
return _check_and_cache_materialization_status(team_id, endpoint_name, version)
return cached_status
+
+
+def check_materialized_request(team_id: int, endpoint_name: str, version: int | None, request_data: object) -> bool:
+ """Whether this run request will be served from the targeted version's materialized table.
+
+ The cached snapshot answers "what can this version serve"; the request decides whether
+ it will (``refresh=direct``, variables the table cannot filter on, or a stale
+ materialization all run inline). A body the run action would reject is classified
+ inline, because throttling runs before validation.
+ """
+
+ try:
+ data = EndpointRunRequest.model_validate(request_data)
+ except ValidationError:
+ return False
+ if data.refresh == EndpointRefreshMode.DIRECT:
+ return False
+
+ state = get_endpoint_materialization_state(team_id, endpoint_name, version)
+ if state is None:
+ state = _load_and_cache_materialization_state(team_id, endpoint_name, version)
+ return state.serves(data)
diff --git a/products/endpoints/backend/tests/test_endpoint.py b/products/endpoints/backend/tests/test_endpoint.py
index 9d0a2b0be8f1..a903125248ed 100644
--- a/products/endpoints/backend/tests/test_endpoint.py
+++ b/products/endpoints/backend/tests/test_endpoint.py
@@ -23,6 +23,7 @@ from posthog.models.utils import generate_random_token_personal, hash_key_value
from products.data_modeling.backend.facade.models import DataModelingJob, DataWarehouseSavedQuery
from products.endpoints.backend.models import Endpoint, EndpointVersion
+from products.endpoints.backend.rate_limit import is_endpoint_materialization_ready, set_endpoint_materialization_ready
from products.endpoints.backend.tests.conftest import create_endpoint_with_version
from products.product_analytics.backend.facade.models import InsightVariable
from products.warehouse_sources.backend.facade.models import DataWarehouseTable
@@ -1133,6 +1134,9 @@ class TestEndpoint(ClickhouseTestMixin, APIBaseTest):
data_freshness_seconds=3600,
)
+ set_endpoint_materialization_ready(self.team.pk, endpoint.name, True)
+ set_endpoint_materialization_ready(self.team.pk, endpoint.name, True, version=1)
+
# Update to different data freshness
updated_data: dict[str, int | None] = {"data_freshness_seconds": 21600}
response = self.client.patch(
@@ -1140,6 +1144,9 @@ class TestEndpoint(ClickhouseTestMixin, APIBaseTest):
)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.json()["data_freshness_seconds"], 21600)
+ # The freshness target is part of the throttle's cached snapshot, so the edit drops it.
+ self.assertIsNone(is_endpoint_materialization_ready(self.team.pk, endpoint.name))
+ self.assertIsNone(is_endpoint_materialization_ready(self.team.pk, endpoint.name, version=1))
endpoint.refresh_from_db()
version = endpoint.get_version()
diff --git a/products/endpoints/backend/tests/test_endpoint_materialization.py b/products/endpoints/backend/tests/test_endpoint_materialization.py
index 35bf862c18b8..b6744d86186d 100644
--- a/products/endpoints/backend/tests/test_endpoint_materialization.py
+++ b/products/endpoints/backend/tests/test_endpoint_materialization.py
@@ -33,6 +33,7 @@ from products.endpoints.backend.logic.materialization import (
)
from products.endpoints.backend.materialization_transforms import build_endpoint_hogql
from products.endpoints.backend.models import EndpointVersion
+from products.endpoints.backend.rate_limit import is_endpoint_materialization_ready, set_endpoint_materialization_ready
from products.endpoints.backend.tests.conftest import create_endpoint_with_version
from products.warehouse_sources.backend.facade.models import DataWarehouseTable
@@ -111,6 +112,28 @@ class TestEndpointMaterialization(ClickhouseTestMixin, APIBaseTest):
self.assertIsNone(saved_query.sync_frequency_interval)
self.assertEqual(get_declared_target(Node.objects.get(saved_query=saved_query)), timedelta(hours=24))
+ def test_enable_materialization_drops_the_cached_throttle_snapshot(self):
+ endpoint = create_endpoint_with_version(
+ name="throttle_snapshot_endpoint",
+ team=self.team,
+ query=self.sample_hogql_query,
+ created_by=self.user,
+ is_active=True,
+ )
+ set_endpoint_materialization_ready(self.team.pk, endpoint.name, False)
+ set_endpoint_materialization_ready(self.team.pk, endpoint.name, False, version=1)
+
+ 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())
+
+ # A snapshot cached before the enable would hold the inline rate until it expired.
+ self.assertIsNone(is_endpoint_materialization_ready(self.team.pk, endpoint.name))
+ self.assertIsNone(is_endpoint_materialization_ready(self.team.pk, endpoint.name, version=1))
+
def test_create_with_materialization_enabled_schedules_saved_query(self):
response = self.client.post(
f"/api/environments/{self.team.id}/endpoints/",
diff --git a/products/endpoints/backend/tests/test_rate_limit.py b/products/endpoints/backend/tests/test_rate_limit.py
index b581db1e1e9a..3fa6a4cd6b54 100644
--- a/products/endpoints/backend/tests/test_rate_limit.py
+++ b/products/endpoints/backend/tests/test_rate_limit.py
@@ -1,3 +1,5 @@
+from datetime import timedelta
+
from posthog.test.base import APIBaseTest
from unittest.mock import MagicMock, patch
@@ -6,17 +8,25 @@ from django.test import TestCase
from django.utils import timezone
from parameterized import parameterized
+from rest_framework.parsers import JSONParser
+from rest_framework.request import Request
+from rest_framework.test import APIRequestFactory
from products.data_modeling.backend.facade.models import DataModelingJob, DataWarehouseSavedQuery
-from products.endpoints.backend.models import Endpoint
+from products.endpoints.backend.models import Endpoint, EndpointVersion
from products.endpoints.backend.presentation.throttles import (
EndpointBurstThrottle,
EndpointSustainedThrottle,
_is_materialized_endpoint_request,
)
from products.endpoints.backend.rate_limit import (
+ MATERIALIZED_ENDPOINT_CACHE_TTL,
+ STALE_STATE_RECHECK_TTL,
_check_and_cache_materialization_status,
+ check_materialized_request,
clear_endpoint_materialization_cache,
+ get_endpoint_materialization_cache_key,
+ get_endpoint_materialization_state,
is_endpoint_materialization_ready,
set_endpoint_materialization_ready,
)
@@ -38,6 +48,21 @@ class TestMaterializationCache(TestCase):
set_endpoint_materialization_ready(123, "test_endpoint", is_ready)
self.assertEqual(is_endpoint_materialization_ready(123, "test_endpoint"), is_ready)
+ @parameterized.expand(
+ [
+ ("unparsable_timestamp", {"ready": True, "materialized_at": "not-a-timestamp"}),
+ ("foreign_shape", {"ready": True, "materialized_at": 1234, "freshness_seconds": "3600"}),
+ ("ready_as_string", {"ready": "false", "materialized_at": None, "servable_variables": []}),
+ ("freshness_as_bool", {"ready": True, "materialized_at": None, "freshness_seconds": True}),
+ ("variable_not_a_name", {"ready": True, "materialized_at": None, "servable_variables": ["a", 1]}),
+ ]
+ )
+ def test_payload_in_another_shape_reads_as_a_miss(self, _name, payload):
+ cache.set(get_endpoint_materialization_cache_key(123, "test_endpoint"), payload)
+
+ self.assertIsNone(get_endpoint_materialization_state(123, "test_endpoint"))
+ self.assertIsNone(is_endpoint_materialization_ready(123, "test_endpoint"))
+
def test_clear_cache(self):
set_endpoint_materialization_ready(123, "test_endpoint", True)
clear_endpoint_materialization_cache(123, "test_endpoint")
@@ -109,6 +134,7 @@ class TestCheckAndCacheMaterializationStatus(APIBaseTest):
query={"kind": "HogQLQuery", "query": "SELECT 1"},
is_materialized=True,
status=status,
+ last_run_at=timezone.now() if status == DataWarehouseSavedQuery.Status.COMPLETED else None,
origin=DataWarehouseSavedQuery.Origin.ENDPOINT,
)
endpoint = Endpoint.objects.create(
@@ -189,6 +215,21 @@ class TestCheckAndCacheMaterializationStatus(APIBaseTest):
self.assertEqual(_check_and_cache_materialization_status(self.team.id, f"endpoint_{name}"), expected_ready)
+ def test_failed_run_after_a_good_one_keeps_the_table_servable(self):
+ _create_ready_materialized_endpoint(self.team, self.user, "failed_after_good", timezone.now())
+ saved_query = DataWarehouseSavedQuery.objects.get(name="failed_after_good_query")
+ DataModelingJob.objects.create(
+ team=self.team,
+ saved_query=saved_query,
+ status=DataModelingJob.Status.FAILED,
+ engine=DataModelingJob.Engine.CLICKHOUSE,
+ last_run_at=timezone.now() + timedelta(minutes=1),
+ )
+
+ # The execution service still serves the last good table, so the throttle must agree.
+ self.assertTrue(_check_and_cache_materialization_status(self.team.id, "failed_after_good"))
+ self.assertTrue(check_materialized_request(self.team.id, "failed_after_good", None, {}))
+
def _create_endpoint_with_materialized_v1_and_inline_v2(self, name="versioned_endpoint"):
from products.endpoints.backend.models import EndpointVersion
@@ -198,6 +239,7 @@ class TestCheckAndCacheMaterializationStatus(APIBaseTest):
query={"kind": "HogQLQuery", "query": "SELECT 1"},
is_materialized=True,
status=DataWarehouseSavedQuery.Status.COMPLETED,
+ last_run_at=timezone.now(),
origin=DataWarehouseSavedQuery.Origin.ENDPOINT,
)
table = DataWarehouseTable.objects.create(
@@ -266,6 +308,40 @@ class TestCheckAndCacheMaterializationStatus(APIBaseTest):
self.assertFalse(is_endpoint_materialization_ready(self.team.id, "versioned_endpoint3"))
+def _create_ready_materialized_endpoint(team, user, name: str, materialized_at) -> None:
+ saved_query = DataWarehouseSavedQuery.objects.create(
+ name=f"{name}_query",
+ team=team,
+ query={"kind": "HogQLQuery", "query": "SELECT 1"},
+ is_materialized=True,
+ status=None,
+ origin=DataWarehouseSavedQuery.Origin.ENDPOINT,
+ )
+ saved_query.table = DataWarehouseTable.objects.create(
+ team=team,
+ name=f"{name}_table",
+ format=DataWarehouseTable.TableFormat.Parquet,
+ url_pattern=f"s3://test-bucket/{name}",
+ )
+ saved_query.save()
+ DataModelingJob.objects.create(
+ team=team,
+ saved_query=saved_query,
+ status=DataModelingJob.Status.COMPLETED,
+ engine=DataModelingJob.Engine.CLICKHOUSE,
+ last_run_at=materialized_at,
+ )
+ endpoint = Endpoint.objects.create(name=name, team=team, created_by=user, is_active=True, current_version=1)
+ EndpointVersion.objects.create(
+ endpoint=endpoint,
+ version=1,
+ query={"kind": "HogQLQuery", "query": "SELECT 1"},
+ created_by=user,
+ saved_query=saved_query,
+ data_freshness_seconds=3600,
+ )
+
+
class TestIsMaterializedEndpointRequest(APIBaseTest):
def setUp(self):
super().setUp()
@@ -289,8 +365,8 @@ class TestIsMaterializedEndpointRequest(APIBaseTest):
self.assertFalse(_is_materialized_endpoint_request(request, view))
- def test_uses_cached_value(self):
- set_endpoint_materialization_ready(123, "test", True)
+ def test_cached_not_ready_skips_the_db(self):
+ set_endpoint_materialization_ready(123, "test", False)
request = MagicMock()
request.data = {}
@@ -299,42 +375,11 @@ class TestIsMaterializedEndpointRequest(APIBaseTest):
view.team_id = 123
view.kwargs = {"name": "test"}
- self.assertTrue(_is_materialized_endpoint_request(request, view))
+ with self.assertNumQueries(0):
+ self.assertFalse(_is_materialized_endpoint_request(request, view))
def test_lazy_loads_on_cache_miss(self):
- from products.endpoints.backend.models import EndpointVersion
-
- saved_query = DataWarehouseSavedQuery.objects.create(
- name="lazy_query",
- team=self.team,
- query={"kind": "HogQLQuery", "query": "SELECT 1"},
- is_materialized=True,
- status=DataWarehouseSavedQuery.Status.COMPLETED,
- origin=DataWarehouseSavedQuery.Origin.ENDPOINT,
- )
- endpoint = Endpoint.objects.create(
- name="lazy_endpoint",
- team=self.team,
- created_by=self.user,
- is_active=True,
- current_version=1,
- )
- table = DataWarehouseTable.objects.create(
- team=self.team,
- name="lazy_table",
- format=DataWarehouseTable.TableFormat.Parquet,
- url_pattern="s3://test-bucket/lazy_table",
- )
- saved_query.table = table
- saved_query.save()
-
- EndpointVersion.objects.create(
- endpoint=endpoint,
- version=1,
- query={"kind": "HogQLQuery", "query": "SELECT 1"},
- created_by=self.user,
- saved_query=saved_query,
- )
+ _create_ready_materialized_endpoint(self.team, self.user, "lazy_endpoint", timezone.now())
self.assertIsNone(is_endpoint_materialization_ready(self.team.id, "lazy_endpoint"))
@@ -367,14 +412,30 @@ class TestIsMaterializedEndpointRequest(APIBaseTest):
self.assertFalse(_is_materialized_endpoint_request(request, view))
+ @parameterized.expand(
+ [
+ ("malformed_json", "{not json", "application/json"),
+ ("unsupported_media_type", "<xml/>", "application/xml"),
+ ]
+ )
+ def test_unreadable_body_takes_the_inline_rate(self, name, body, content_type):
+ _create_ready_materialized_endpoint(self.team, self.user, name, timezone.now())
+
+ request = Request(APIRequestFactory().post("/", data=body, content_type=content_type), parsers=[JSONParser()])
+ view = MagicMock()
+ view.team_id = self.team.id
+ view.kwargs = {"name": name}
+
+ 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)
+ _create_ready_materialized_endpoint(self.team, self.user, "test", timezone.now())
request = MagicMock()
request.data = {}
request.query_params = {"version": "not-a-number"}
view = MagicMock()
- view.team_id = 123
+ view.team_id = self.team.id
view.kwargs = {"name": "test"}
self.assertTrue(_is_materialized_endpoint_request(request, view))
@@ -403,7 +464,7 @@ class TestEndpointThrottles(APIBaseTest):
self.assertEqual(throttle.scope, "api_queries_burst")
def test_uses_materialized_scope_when_materialized(self):
- set_endpoint_materialization_ready(self.team.id, "mat_endpoint", True)
+ _create_ready_materialized_endpoint(self.team, self.user, "mat_endpoint", timezone.now())
for throttle_class, expected_scope in [
(EndpointBurstThrottle, "materialized_endpoint_burst"),
@@ -420,3 +481,98 @@ class TestEndpointThrottles(APIBaseTest):
throttle.allow_request(request, view)
self.assertEqual(throttle.scope, expected_scope)
+
+ @parameterized.expand(
+ [
+ ("clean_request", {}, timedelta(minutes=5), "materialized_endpoint_burst"),
+ ("refresh_direct_runs_inline", {"refresh": "direct"}, timedelta(minutes=5), "api_queries_burst"),
+ ("unsupported_variable_runs_inline", {"variables": {"nope": 1}}, timedelta(minutes=5), "api_queries_burst"),
+ ("stale_materialization_runs_inline", {}, timedelta(hours=2), "api_queries_burst"),
+ (
+ "malformed_variables_fall_back_to_inline",
+ {"variables": "nope"},
+ timedelta(minutes=5),
+ "api_queries_burst",
+ ),
+ ]
+ )
+ def test_inline_fallbacks_do_not_draw_the_materialized_budget(self, name, body, materialized_age, expected_scope):
+ _create_ready_materialized_endpoint(self.team, self.user, name, timezone.now() - materialized_age)
+
+ throttle = EndpointBurstThrottle()
+ request = MagicMock()
+ request.data = body
+ request.query_params = {}
+ view = MagicMock()
+ view.team_id = self.team.id
+ view.kwargs = {"name": name}
+
+ throttle.allow_request(request, view)
+ self.assertEqual(throttle.scope, expected_scope)
+
+ # The first classification cached the version's snapshot; a repeat runs off the cache alone.
+ throttle = EndpointBurstThrottle()
+ with self.assertNumQueries(0):
+ throttle.allow_request(request, view)
+ self.assertEqual(throttle.scope, expected_scope)
+
+
+class TestMaterializationStateCacheTimeout(APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ cache.clear()
+
+ def tearDown(self):
+ cache.clear()
+ super().tearDown()
+
+ @parameterized.expand(
+ [
+ ("expires_with_the_freshness_window", timedelta(minutes=55), 300),
+ ("stale_snapshot_rechecks_soon", timedelta(hours=2), STALE_STATE_RECHECK_TTL),
+ ]
+ )
+ def test_cache_timeout_tracks_freshness(self, _name, materialized_age, expected_timeout):
+ _create_ready_materialized_endpoint(self.team, self.user, "timed_endpoint", timezone.now() - materialized_age)
+
+ with patch("products.endpoints.backend.rate_limit.cache.set", wraps=cache.set) as cache_set:
+ check_materialized_request(self.team.id, "timed_endpoint", None, {})
+
+ timeout = cache_set.call_args.kwargs["timeout"]
+ self.assertAlmostEqual(timeout, expected_timeout, delta=5)
+
+ @parameterized.expand(
+ [
+ ("pending_first_run_rechecks_soon", True, STALE_STATE_RECHECK_TTL),
+ ("no_materialization_holds_the_window", False, MATERIALIZED_ENDPOINT_CACHE_TTL),
+ ]
+ )
+ def test_not_ready_timeout_tracks_whether_a_run_is_pending(self, name, materialization_enabled, expected_timeout):
+ saved_query = (
+ DataWarehouseSavedQuery.objects.create(
+ name=f"{name}_query",
+ team=self.team,
+ query={"kind": "HogQLQuery", "query": "SELECT 1"},
+ is_materialized=True,
+ status=DataWarehouseSavedQuery.Status.RUNNING,
+ origin=DataWarehouseSavedQuery.Origin.ENDPOINT,
+ )
+ if materialization_enabled
+ else None
+ )
+ endpoint = Endpoint.objects.create(
+ name=name, team=self.team, created_by=self.user, is_active=True, current_version=1
+ )
+ EndpointVersion.objects.create(
+ endpoint=endpoint,
+ version=1,
+ query={"kind": "HogQLQuery", "query": "SELECT 1"},
+ created_by=self.user,
+ saved_query=saved_query,
+ data_freshness_seconds=3600,
+ )
+
+ with patch("products.endpoints.backend.rate_limit.cache.set", wraps=cache.set) as cache_set:
+ self.assertFalse(check_materialized_request(self.team.id, name, None, {}))
+
+ self.assertEqual(cache_set.call_args.kwargs["timeout"], expected_timeout)