:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(insights): throttle shared force refresh via cache age override (#69416)
Thomas Obermüller2d79dcf7ad38
diff --git a/frontend/src/scenes/dashboard/dashboardConstants.ts b/frontend/src/scenes/dashboard/dashboardConstants.tsindex 45aba9c24756..6059d7ad8841 100644--- a/frontend/src/scenes/dashboard/dashboardConstants.ts+++ b/frontend/src/scenes/dashboard/dashboardConstants.ts@@ -5,7 +5,7 @@ export const AUTO_REFRESH_INITIAL_INTERVAL_SECONDS = DashboardAutoRefreshInterva/*** Cold-start one-shot threshold: if data is older than this when a shared dashboard loads,* trigger one immediate force_blocking refresh. Aligned with the periodic interval and the- * backend throttle (`SHARED_FORCE_BLOCKING_MIN_AGE`).+ * backend throttle (`SHARED_FORCE_BLOCKING_STALENESS_WINDOW`).*/export const SHARED_DASHBOARD_AUTO_FORCE_IF_STALE_MINUTES = AUTO_REFRESH_INITIAL_INTERVAL_SECONDS / 60diff --git a/posthog/api/services/query.py b/posthog/api/services/query.pyindex fa1935f88aaa..59e1e132094a 100644--- a/posthog/api/services/query.py+++ b/posthog/api/services/query.py@@ -56,6 +56,7 @@ def process_query_dict(insight_id: Optional[int] = None,dashboard_id: Optional[int] = None,is_query_service: bool = False,+ cache_age_seconds: Optional[int] = None,pagination_cursor: Optional[str] = None,analytics_props: Optional[AnalyticsProps] = None,) -> dict | BaseModel:@@ -107,6 +108,7 @@ def process_query_dict(insight_id=insight_id,dashboard_id=dashboard_id,is_query_service=is_query_service,+ cache_age_seconds=cache_age_seconds,pagination_cursor=pagination_cursor,analytics_props=analytics_props,)diff --git a/posthog/api/sharing.py b/posthog/api/sharing.pyindex faee85062bc0..435953e3dff1 100644--- a/posthog/api/sharing.py+++ b/posthog/api/sharing.py@@ -722,7 +722,11 @@ def _compute_inline_query_results_for_shared_notebook(if not inline_nodes:return results_by_node_id- execution_mode = shared_insights_execution_mode(ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE)+ # cache_age_seconds is deliberately unused: blocking-if-stale passes through the whitelist+ # without a throttle override, so there is nothing to thread into process_query_dict here.+ execution_mode = shared_insights_execution_mode(+ ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE+ ).execution_modefor node_id, query in inline_nodes:serialized: dict | None = Nonetry:diff --git a/posthog/caching/calculate_results.py b/posthog/caching/calculate_results.pyindex 83ec8f860200..e4171f4b1b02 100644--- a/posthog/caching/calculate_results.py+++ b/posthog/caching/calculate_results.py@@ -59,6 +59,7 @@ def calculate_for_query_based_insight(variables_override: Optional[dict] = None,tile_filters_override: Optional[dict] = None,query_override: Optional[dict] = None,+ cache_age_seconds: Optional[int] = None,analytics_props: Optional[AnalyticsProps] = None,) -> "InsightResult":from posthog.caching.fetch_from_cache import InsightResult, NothingInCacheResult@@ -96,6 +97,7 @@ def calculate_for_query_based_insight(dashboard_id=dashboard.pk if dashboard else None,# QUERY_ASYNC provides extended max execution time for insight querieslimit_context=LimitContext.QUERY_ASYNC,+ cache_age_seconds=cache_age_seconds,analytics_props=analytics_props,)diff --git a/posthog/hogql_queries/hogql_query_runner.py b/posthog/hogql_queries/hogql_query_runner.pyindex 9976b3168a32..3d548c14a1fd 100644--- a/posthog/hogql_queries/hogql_query_runner.py+++ b/posthog/hogql_queries/hogql_query_runner.py@@ -49,11 +49,6 @@ class HogQLQueryRunner(AnalyticsQueryRunner[HogQLQueryResponse]):def cache_target_age(self, last_refresh: Optional[datetime], lazy: bool = False) -> Optional[datetime]:if last_refresh is None:return None-- override = self._get_cache_age_override(last_refresh)- if override is not None:- return override-return last_refresh + staleness_threshold_map[ThresholdMode.LAZY if lazy else ThresholdMode.DEFAULT]["day"]def to_query(self) -> ast.SelectQuery | ast.SelectSetQuery:diff --git a/posthog/hogql_queries/query_runner.py b/posthog/hogql_queries/query_runner.pyindex 904287627792..f0ef1c4eadcb 100644--- a/posthog/hogql_queries/query_runner.py+++ b/posthog/hogql_queries/query_runner.py@@ -4,9 +4,8 @@ from datetime import UTC, datetime, timedeltafrom enum import StrEnumfrom time import perf_counterfrom types import UnionType-from typing import Any, Generic, Optional, Protocol, TypeGuard, TypeVar, Union, cast, get_args, get_origin+from typing import Any, Generic, NamedTuple, Optional, Protocol, TypeGuard, TypeVar, Union, cast, get_args, get_origin-import structlogimport posthoganalyticsfrom prometheus_client import Counter, Histogramfrom pydantic import BaseModel, ConfigDict@@ -133,8 +132,6 @@ from posthog.slo.types import SloArea, SloOperation, SloOutcomefrom posthog.synthetic_user import SyntheticUserfrom posthog.utils import generate_cache_key, get_from_dict_or_attr, to_json-logger = structlog.get_logger(__name__)-QUERY_EXECUTION_TOTAL = Counter("posthog_query_execution_total","Query executions by category",@@ -222,17 +219,15 @@ def execution_mode_from_refresh(refresh_requested: bool | str | None) -> Executireturn ExecutionMode.CACHE_ONLY_NEVER_CALCULATE-# Minimum age before a shared insight may honor `?refresh=force_blocking`.-# Sourced from the same generated schema as the frontend's auto-refresh interval so the-# two cannot drift. Best-effort throttle, not a hard rate limit.-SHARED_FORCE_BLOCKING_MIN_AGE = timedelta(seconds=DashboardAutoRefreshInterval().root)+# Staleness threshold for `?refresh=force_blocking` on shared insights: the request runs as+# blocking-if-stale with this cache age, so the cached result's own `last_refresh` is the+# throttle clock. Sourced from the same generated schema as the frontend's auto-refresh+# interval so the two cannot drift. Best-effort throttle, not a hard rate limit.+SHARED_FORCE_BLOCKING_STALENESS_WINDOW = timedelta(seconds=DashboardAutoRefreshInterval().root)_SHARED_MODE_WHITELIST = {ExecutionMode.CACHE_ONLY_NEVER_CALCULATE: ExecutionMode.EXTENDED_CACHE_CALCULATE_ASYNC_IF_STALE,- # force_blocking is gated by `shared_insights_execution_mode`; downgrades to IF_STALE- # when the throttle clock is younger than `SHARED_FORCE_BLOCKING_MIN_AGE`.- ExecutionMode.CALCULATE_BLOCKING_ALWAYS: ExecutionMode.CALCULATE_BLOCKING_ALWAYS,ExecutionMode.RECENT_CACHE_CALCULATE_ASYNC_IF_STALE: ExecutionMode.RECENT_CACHE_CALCULATE_ASYNC_IF_STALE,# Used by the shared-notebook inline query payload builder. Without this entry the# request silently falls through to EXTENDED_CACHE_CALCULATE_ASYNC_IF_STALE, which causes@@ -241,12 +236,6 @@ _SHARED_MODE_WHITELIST = {}-def _is_force_blocking_eligible_for_shared(last_refresh: datetime | None) -> bool:- if last_refresh is None:- return False- return datetime.now(UTC) - last_refresh >= SHARED_FORCE_BLOCKING_MIN_AGE--def _classify_error_for_slo(exc: Exception) -> tuple[QueryErrorCategory, SloOutcome]:"""Classify a query exception for SLO emission.@@ -273,21 +262,35 @@ def _classify_error_for_slo(exc: Exception) -> tuple[QueryErrorCategory, SloOutcreturn category, SloOutcome.FAILURE-def shared_insights_execution_mode(- execution_mode: ExecutionMode,- *,- last_refresh: datetime | None = None,-) -> ExecutionMode:- if execution_mode == ExecutionMode.CALCULATE_BLOCKING_ALWAYS and not _is_force_blocking_eligible_for_shared(- last_refresh- ):- logger.info(- "shared_force_blocking_throttled",- last_refresh=last_refresh.isoformat() if last_refresh else None,- min_age_seconds=int(SHARED_FORCE_BLOCKING_MIN_AGE.total_seconds()),+class SharedExecutionSettings(NamedTuple):+ """Execution mode plus the staleness override that makes it a throttle.++ `cache_age_seconds` is not optional garnish: dropping it when threading the mode into+ `calculate_for_query_based_insight`/`process_query_dict` silently disables the shared+ force-refresh throttle. Named so call sites that discard it have to do so visibly.+ """++ execution_mode: ExecutionMode+ cache_age_seconds: int | None+++def shared_insights_execution_mode(execution_mode: ExecutionMode) -> SharedExecutionSettings:+ """Map a requested execution mode to the one allowed on shared/embedded resources.++ Returns the mode plus an optional `cache_age_seconds` override for the query runner.+ force_blocking runs as blocking-if-stale with `SHARED_FORCE_BLOCKING_STALENESS_WINDOW` as the+ staleness threshold: a cached result younger than the window is served as-is, anything+ older (or missing) recomputes synchronously — throttling forced recomputes without a+ separate clock.+ """+ if execution_mode == ExecutionMode.CALCULATE_BLOCKING_ALWAYS:+ return SharedExecutionSettings(+ ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE,+ int(SHARED_FORCE_BLOCKING_STALENESS_WINDOW.total_seconds()),)- return ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE- return _SHARED_MODE_WHITELIST.get(execution_mode, ExecutionMode.EXTENDED_CACHE_CALCULATE_ASYNC_IF_STALE)+ return SharedExecutionSettings(+ _SHARED_MODE_WHITELIST.get(execution_mode, ExecutionMode.EXTENDED_CACHE_CALCULATE_ASYNC_IF_STALE), None+ )RunnableQueryNode = Union[@@ -1492,7 +1495,7 @@ class QueryRunner(ABC, Generic[Q, R, CR]):target_age=cached_response.cache_target_age,)- if not self._is_stale(last_refresh=last_refresh_from_cached_result(cached_response)):+ if not self._is_stale_for_request(last_refresh=last_refresh_from_cached_result(cached_response)):count_query_cache_hit(self.team.pk, hit="hit", trigger=cached_response.calculation_trigger or "")# We have a valid result that's fresh enough, let's return itcached_response.query_status = self.get_async_query_status(cache_key=cache_manager.cache_key)@@ -1516,7 +1519,7 @@ class QueryRunner(ABC, Generic[Q, R, CR]):elif execution_mode == ExecutionMode.EXTENDED_CACHE_CALCULATE_ASYNC_IF_STALE:# We're allowed to calculate if the lazy check fails, but we'll do it asynchronouslyassert isinstance(cached_response, CachedResponse)- if self._is_stale(last_refresh=last_refresh_from_cached_result(cached_response), lazy=True):+ if self._is_stale_for_request(last_refresh=last_refresh_from_cached_result(cached_response), lazy=True):cached_response.query_status = self.enqueue_async_calculation(cache_manager=cache_manager, user=user, analytics_props=analytics_props)@@ -1652,6 +1655,11 @@ class QueryRunner(ABC, Generic[Q, R, CR]):slo_properties["dashboard_id"] = dashboard_idif product_key is not None:slo_properties["product_key"] = product_key+ if cache_age_seconds is not None:+ # Makes the staleness override observable: override set + execution_path=cache_hit+ # + is_cache_stale=false means the shared force-refresh throttle (or an endpoint's+ # data freshness window) served cache instead of recomputing.+ slo_properties["cache_age_override"] = cache_age_secondswith slo_operation(spec=SloSpec(@@ -1734,7 +1742,7 @@ class QueryRunner(ABC, Generic[Q, R, CR]):last_refresh = last_refresh_from_cached_result(results)cache_tracking_props = {- "is_cache_stale": self._is_stale(last_refresh=last_refresh),+ "is_cache_stale": self._is_stale_for_request(last_refresh=last_refresh),"calculation_trigger": results.calculation_trigger,"cache_age_seconds": round((datetime.now(UTC) - last_refresh).total_seconds(), 2)if last_refresh@@ -1756,6 +1764,7 @@ class QueryRunner(ABC, Generic[Q, R, CR]):"query_type": query_type,"cache_key": cache_key,"cache_hit": isinstance(results, CachedResponse),+ "cache_age_override": cache_age_seconds,"response_time_ms": round((perf_counter() - start_time) * 1000, 2),**cache_tracking_props,}@@ -1931,6 +1940,7 @@ class QueryRunner(ABC, Generic[Q, R, CR]):"insight_id": insight_id,"dashboard_id": dashboard_id,"cache_hit": False,+ "cache_age_override": getattr(self, "_cache_age_override", None),"cache_key": cache_key,"calculation_trigger": trigger,"execution_mode": execution_mode.value,@@ -2148,32 +2158,10 @@ class QueryRunner(ABC, Generic[Q, R, CR]):return cached_response, was_modified- def _get_cache_age_override(self, last_refresh: Optional[datetime]) -> Optional[datetime]:- """- Helper method for subclasses that override cache_target_age().- Returns the custom cache target age if _cache_age_override is set, otherwise None.-- Subclasses can call this first in their cache_target_age() implementation:- ```- override = self._get_cache_age_override(last_refresh)- if override is not None:- return override- # ... custom logic- ```- """- if hasattr(self, "_cache_age_override") and self._cache_age_override is not None and last_refresh is not None:- return last_refresh + timedelta(seconds=self._cache_age_override)- return None-def cache_target_age(self, last_refresh: Optional[datetime], lazy: bool = False) -> Optional[datetime]:if last_refresh is None:return None- # Check for custom cache age override (e.g., from Endpoint)- override_target_age = self._get_cache_age_override(last_refresh)- if override_target_age is not None:- return override_target_age-query_date_range = getattr(self, "query_date_range", None)interval = query_date_range.interval_name if query_date_range else "minute"mode = ThresholdMode.LAZY if lazy else ThresholdMode.DEFAULT@@ -2224,21 +2212,28 @@ class QueryRunner(ABC, Generic[Q, R, CR]):"""Overridden by subclasses to add validation rules."""return ()- def _is_stale(self, last_refresh: Optional[datetime], lazy: bool = False) -> bool:- # If a custom cache age was provided (e.g., from Endpoint), use our override logic- target_age = None- if hasattr(self, "_cache_age_override") and self._cache_age_override is not None:- target_age = self.cache_target_age(last_refresh, lazy=lazy)- if not target_age:- return False+ def _is_stale_for_request(self, last_refresh: Optional[datetime], lazy: bool = False) -> bool:+ """Staleness decision for this request, honoring `_cache_age_override` when set.++ The override (shared force refresh, endpoint data freshness) replaces the runner's+ own staleness policy. It is applied here, at the call site, rather than inside the+ polymorphic `_is_stale`/`cache_target_age` hooks, so subclasses overriding those+ cannot silently weaken or tighten the requested window — and it governs this one+ staleness decision only, never the target age persisted on a cache write.+ """+ override = getattr(self, "_cache_age_override", None)+ if override is None:+ return self._is_stale(last_refresh, lazy=lazy)+ if last_refresh is None:+ return True+ return datetime.now(UTC) > last_refresh + timedelta(seconds=override)+ def _is_stale(self, last_refresh: Optional[datetime], lazy: bool = False) -> bool:query_date_range = getattr(self, "query_date_range", None)date_to = query_date_range.date_to() if query_date_range else Noneinterval = query_date_range.interval_name if query_date_range else "minute"mode = ThresholdMode.LAZY if lazy else ThresholdMode.DEFAULT- return is_stale(- self.team, date_to=date_to, interval=interval, last_refresh=last_refresh, mode=mode, target_age=target_age- )+ return is_stale(self.team, date_to=date_to, interval=interval, last_refresh=last_refresh, mode=mode)def _refresh_frequency(self) -> timedelta:return timedelta(minutes=1)diff --git a/posthog/hogql_queries/test/test_query_runner.py b/posthog/hogql_queries/test/test_query_runner.pyindex 696381c0af61..9cbe697dca70 100644--- a/posthog/hogql_queries/test/test_query_runner.py+++ b/posthog/hogql_queries/test/test_query_runner.py@@ -50,6 +50,7 @@ from posthog.errors import ExposedCHQueryErrorfrom posthog.hogql_queries.hogql_query_runner import HogQLQueryRunnerfrom posthog.hogql_queries.insights.trends.trends_query_runner import TrendsQueryRunnerfrom posthog.hogql_queries.query_runner import (+ SHARED_FORCE_BLOCKING_STALENESS_WINDOW,AnalyticsQueryRunner,ExecutionMode,QueryRunner,@@ -483,6 +484,60 @@ class TestQueryRunner(BaseTest):self.assertEqual(response.last_refresh.isoformat(), "2023-02-04T13:37:42+00:00")mock_on_commit.assert_called_once()+ @parameterized.expand(+ [+ # The override replaces the subclass staleness policy in both directions: a runner+ # that considers a young cache stale must still serve it within the window, and a+ # runner that pins a long freshness must still recompute past the window.+ ("subclass_stale_within_window_serves_cache", True, timedelta(minutes=11), True),+ ("subclass_fresh_past_window_recomputes", False, timedelta(minutes=31), False),+ ]+ )+ def test_cache_age_override_governs_staleness_over_subclass_policy(+ self,+ _name: str,+ subclass_says_stale: bool,+ cache_age: timedelta,+ expected_is_cached: bool,+ ):+ base = self.setup_test_query_runner_class()++ class OpinionatedQueryRunner(base): # type: ignore[misc, valid-type]+ def _is_stale(self, last_refresh: Optional[datetime], lazy: bool = False) -> bool:+ return subclass_says_stale++ def cache_target_age(self, last_refresh: Optional[datetime], lazy: bool = False) -> Optional[datetime]:+ return last_refresh + timedelta(hours=24) if last_refresh else None++ start = datetime(2023, 2, 4, 13, 37, 42, tzinfo=UTC)+ with freeze_time(start):+ OpinionatedQueryRunner(query={"some_attr": "bla"}, team=self.team).run(+ execution_mode=ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE+ )++ with freeze_time(start + cache_age):+ response = OpinionatedQueryRunner(query={"some_attr": "bla"}, team=self.team).run(+ execution_mode=ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE,+ cache_age_seconds=1800,+ )+ self.assertEqual(response.is_cached, expected_is_cached)++ def test_cache_age_override_not_persisted_on_cache_write(self):+ TestQueryRunner = self.setup_test_query_runner_class()+ runner = TestQueryRunner(query={"some_attr": "bla"}, team=self.team)++ with freeze_time(datetime(2023, 2, 4, 13, 37, 42, tzinfo=UTC)):+ response = runner.run(+ execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS,+ cache_age_seconds=999,+ )++ # The override governs this request's staleness decision only; the target age written+ # to the cache (served to authenticated viewers and driving cache warming) must stay+ # the runner's default.+ self.assertNotEqual(response.cache_target_age, response.last_refresh + timedelta(seconds=999))+ self.assertEqual(response.cache_target_age, runner.cache_target_age(response.last_refresh))+def test_modifier_passthrough(self):try:from posthog.hogql_queries.hogql_query_runner import HogQLQueryRunner@@ -942,8 +997,6 @@ class TestApplySeriesCustomNames(BaseTest):cached_results: list[dict],expected_results: list[dict],):- from datetime import UTC-from posthog.schema import CachedTrendsQueryResponserunner = TrendsQueryRunner(query=query, team=self.team)@@ -1020,8 +1073,6 @@ class TestApplySeriesCustomNames(BaseTest):expected_results: list,expect_modified: bool,):- from datetime import UTC-from posthog.schema import CachedFunnelsQueryResponse, FunnelsQueryfrom posthog.hogql_queries.insights.funnels.funnels_query_runner import FunnelsQueryRunner@@ -1072,8 +1123,6 @@ class TestApplySeriesCustomNames(BaseTest):expected_results: list,expect_modified: bool,):- from datetime import UTC-from posthog.schema import CachedStickinessQueryResponse, StickinessQueryfrom products.product_analytics.backend.hogql_queries.stickiness.stickiness_query_runner import (@@ -1139,8 +1188,6 @@ class TestApplySeriesCustomNames(BaseTest):expected_results: list,expect_modified: bool,):- from datetime import UTC-from posthog.schema import CachedLifecycleQueryResponse, LifecycleQueryfrom posthog.hogql_queries.insights.lifecycle.lifecycle_query_runner import LifecycleQueryRunner@@ -1214,8 +1261,6 @@ class TestApplySeriesCustomNames(BaseTest):cached_results: list[dict],expect_modified: bool,):- from datetime import UTC-from posthog.schema import CachedTrendsQueryResponserunner = TrendsQueryRunner(query=query, team=self.team)@@ -1237,48 +1282,24 @@ class TestApplySeriesCustomNames(BaseTest):class TestSharedInsightsExecutionMode(BaseTest):@parameterized.expand([- # name, execution_mode, last_refresh_offset (None = no signal, timedelta = age), expected_mode- (- "force_blocking_no_last_refresh_downgrades",- ExecutionMode.CALCULATE_BLOCKING_ALWAYS,- None,- ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE,- ),- (- "force_blocking_just_refreshed_downgrades",- ExecutionMode.CALCULATE_BLOCKING_ALWAYS,- timedelta(seconds=10),- ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE,- ),+ # name, execution_mode, expected_mode, expected_cache_age_seconds(- "force_blocking_just_under_threshold_downgrades",+ "force_blocking_downgrades_with_staleness_window_threshold",ExecutionMode.CALCULATE_BLOCKING_ALWAYS,- timedelta(minutes=29, seconds=59),ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE,- ),- (- "force_blocking_at_threshold_passes_through",- ExecutionMode.CALCULATE_BLOCKING_ALWAYS,- timedelta(minutes=30),- ExecutionMode.CALCULATE_BLOCKING_ALWAYS,- ),- (- "force_blocking_long_stale_passes_through",- ExecutionMode.CALCULATE_BLOCKING_ALWAYS,- timedelta(hours=24),- ExecutionMode.CALCULATE_BLOCKING_ALWAYS,+ int(SHARED_FORCE_BLOCKING_STALENESS_WINDOW.total_seconds()),),("cache_only_remaps_to_extended_async",ExecutionMode.CACHE_ONLY_NEVER_CALCULATE,- timedelta(seconds=10),ExecutionMode.EXTENDED_CACHE_CALCULATE_ASYNC_IF_STALE,+ None,),("recent_cache_async_passes_through",ExecutionMode.RECENT_CACHE_CALCULATE_ASYNC_IF_STALE,- None,ExecutionMode.RECENT_CACHE_CALCULATE_ASYNC_IF_STALE,+ None,),("blocking_if_stale_passes_through",@@ -1287,8 +1308,8 @@ class TestSharedInsightsExecutionMode(BaseTest):# ship a CacheMissResponse to the frontend, which renders the "unsupported node"# placeholder until a later reload picks up the warmed cache.ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE,- None,ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE,+ None,),])@@ -1296,12 +1317,12 @@ class TestSharedInsightsExecutionMode(BaseTest):self,_name: str,execution_mode: ExecutionMode,- last_refresh_offset: timedelta | None,expected_mode: ExecutionMode,+ expected_cache_age_seconds: int | None,) -> None:- last_refresh = None if last_refresh_offset is None else datetime.now(UTC) - last_refresh_offset- result = shared_insights_execution_mode(execution_mode, last_refresh=last_refresh)- self.assertEqual(result, expected_mode)+ result_mode, cache_age_seconds = shared_insights_execution_mode(execution_mode)+ self.assertEqual(result_mode, expected_mode)+ self.assertEqual(cache_age_seconds, expected_cache_age_seconds)@pytest.mark.eediff --git a/posthog/test/test_utils.py b/posthog/test/test_utils.pyindex 801777c5660a..b1dd0b68b2de 100644--- a/posthog/test/test_utils.py+++ b/posthog/test/test_utils.py@@ -1151,6 +1151,39 @@ class TestSharingOverrideProtection(TestCase):assert result == {"breakdown": "region"}+ # The path-based /shared/<token> page load resolves the token from the URL, so no authenticator+ # runs and the successful_authenticator check is blind to it. is_shared must block overrides on+ # its own — otherwise an anonymous viewer can vary these params to churn the query cache key.+ def test_filters_override_blocked_for_shared_context_without_authenticator(self):+ request = self._make_request(None, query_params={"filters_override": json.dumps({"date_from": "-7d"})})+ dashboard = type("Dashboard", (), {"filters": {"date_from": "-30d"}})()++ result = filters_override_requested_by_client(request, dashboard, is_shared=True)++ assert result == {"date_from": "-30d"}++ @patch(+ "products.product_analytics.backend.api.insight_variable.map_stale_to_latest",+ side_effect=lambda variables, _: variables,+ )+ def test_variables_override_blocked_for_shared_context_without_authenticator(self, _mock):+ request = self._make_request(+ None, query_params={"variables_override": json.dumps({"injected": {"value": "evil"}})}+ )+ dashboard = type("Dashboard", (), {"variables": {"var1": {"value": "safe"}}})()++ result = variables_override_requested_by_client(request, dashboard, variables=[], is_shared=True)++ assert result == {"var1": {"value": "safe"}}++ def test_tile_filters_override_blocked_for_shared_context_without_authenticator(self):+ request = self._make_request(None, query_params={"tile_filters_override": json.dumps({"breakdown": "region"})})+ tile = type("DashboardTile", (), {"filters_overrides": {"breakdown": "country"}})()++ result = tile_filters_override_requested_by_client(request, tile, is_shared=True)++ assert result == {"breakdown": "country"}+class TestTemplateContextHistogram(TestCase):@staticmethoddiff --git a/posthog/utils.py b/posthog/utils.pyindex 1096a8e97748..e5a82438c25f 100644--- a/posthog/utils.py+++ b/posthog/utils.py@@ -1714,15 +1714,24 @@ def cache_requested_by_client(request: Request) -> bool | str:return _request_has_key_set("use_cache", request)-def filters_override_requested_by_client(request: Request, dashboard: Optional["Dashboard"]) -> dict:+def filters_override_requested_by_client(+ request: Request, dashboard: Optional["Dashboard"], is_shared: bool = False+) -> dict:from posthog.auth import SharingAccessTokenAuthentication, SharingPasswordProtectedAuthenticationdashboard_filters = dashboard.filters if dashboard else {}raw_override = request.query_params.get("filters_override")- # Security: Don't allow overrides when accessing via sharing tokens- if not raw_override or isinstance(- request.successful_authenticator, (SharingAccessTokenAuthentication, SharingPasswordProtectedAuthentication)+ # Security: never honor client-supplied overrides for shared/embedded access. The+ # successful_authenticator check catches token-authenticated refreshes; is_shared also covers+ # the path-based /shared/<token> page load, where no authenticator runs and the check is blind.+ if (+ not raw_override+ or is_shared+ or isinstance(+ request.successful_authenticator,+ (SharingAccessTokenAuthentication, SharingPasswordProtectedAuthentication),+ )):return dashboard_filters@@ -1735,7 +1744,10 @@ def filters_override_requested_by_client(request: Request, dashboard: Optional["def variables_override_requested_by_client(- request: Optional[Request], dashboard: Optional["Dashboard"], variables: list["InsightVariable"]+ request: Optional[Request],+ dashboard: Optional["Dashboard"],+ variables: list["InsightVariable"],+ is_shared: bool = False,) -> Optional[dict[str, dict]]:from posthog.auth import SharingAccessTokenAuthentication, SharingPasswordProtectedAuthentication@@ -1744,12 +1756,18 @@ def variables_override_requested_by_client(dashboard_variables = (dashboard and dashboard.variables) or {}raw_override = request.query_params.get("variables_override") if request else None- # Security: Don't allow overrides when accessing via sharing tokens- if not raw_override or (- request- and isinstance(- request.successful_authenticator,- (SharingAccessTokenAuthentication, SharingPasswordProtectedAuthentication),+ # Security: never honor client-supplied overrides for shared/embedded access. The+ # successful_authenticator check catches token-authenticated refreshes; is_shared also covers+ # the path-based /shared/<token> page load, where no authenticator runs and the check is blind.+ if (+ not raw_override+ or is_shared+ or (+ request+ and isinstance(+ request.successful_authenticator,+ (SharingAccessTokenAuthentication, SharingPasswordProtectedAuthentication),+ ))):return map_stale_to_latest(dashboard_variables, variables)@@ -1762,15 +1780,24 @@ def variables_override_requested_by_client(return map_stale_to_latest({**dashboard_variables, **request_variables}, variables)-def tile_filters_override_requested_by_client(request: Request, tile: Optional["DashboardTile"]) -> dict:+def tile_filters_override_requested_by_client(+ request: Request, tile: Optional["DashboardTile"], is_shared: bool = False+) -> dict:from posthog.auth import SharingAccessTokenAuthentication, SharingPasswordProtectedAuthenticationtile_filters = tile.filters_overrides if tile and tile.filters_overrides else {}raw_override = request.query_params.get("tile_filters_override")- # Security: Don't allow overrides when accessing via sharing tokens- if not raw_override or isinstance(- request.successful_authenticator, (SharingAccessTokenAuthentication, SharingPasswordProtectedAuthentication)+ # Security: never honor client-supplied overrides for shared/embedded access. The+ # successful_authenticator check catches token-authenticated refreshes; is_shared also covers+ # the path-based /shared/<token> page load, where no authenticator runs and the check is blind.+ if (+ not raw_override+ or is_shared+ or isinstance(+ request.successful_authenticator,+ (SharingAccessTokenAuthentication, SharingPasswordProtectedAuthentication),+ )):return tile_filtersdiff --git a/products/dashboards/backend/api/dashboard.py b/products/dashboards/backend/api/dashboard.pyindex 76dc13effbcc..f0def36237fd 100644--- a/products/dashboards/backend/api/dashboard.py+++ b/products/dashboards/backend/api/dashboard.py@@ -1011,11 +1011,15 @@ class DashboardMetadataSerializer(DashboardBasicSerializer):def get_filters(self, dashboard: Dashboard) -> dict:request = self.context.get("request")- return filters_override_requested_by_client(request, dashboard)+ is_shared = self.context.get("is_shared", False)+ return filters_override_requested_by_client(request, dashboard, is_shared=is_shared)def get_variables(self, dashboard: Dashboard) -> dict | None:request = self.context.get("request")- return variables_override_requested_by_client(request, dashboard, list(self.context["insight_variables"]))+ is_shared = self.context.get("is_shared", False)+ return variables_override_requested_by_client(+ request, dashboard, list(self.context["insight_variables"]), is_shared=is_shared+ )def get_persisted_filters(self, dashboard: Dashboard) -> dict | None:return dashboard.filters if dashboard.filters else Nonediff --git a/products/product_analytics/backend/api/insight.py b/products/product_analytics/backend/api/insight.pyindex 41e89450413b..224aba07a8be 100644--- a/products/product_analytics/backend/api/insight.py+++ b/products/product_analytics/backend/api/insight.py@@ -1,7 +1,7 @@import jsonimport loggingfrom collections.abc import Sequence-from datetime import UTC, datetime, timedelta+from datetime import timedeltafrom functools import lru_cachefrom typing import Any, Union, cast@@ -138,7 +138,6 @@ from products.product_analytics.backend.api.insight_metadata import generate_insfrom products.product_analytics.backend.api.insight_suggestions import get_insight_analysis, get_insight_suggestionsfrom products.product_analytics.backend.api.insight_variable import map_stale_to_latestfrom products.product_analytics.backend.models.insight import Insight, InsightViewed-from products.product_analytics.backend.models.insight_caching_state import InsightCachingStatefrom products.product_analytics.backend.models.insight_variable import InsightVariablefrom common.hogvm.python.utils import HogVMException@@ -449,25 +448,6 @@ class QueryFieldSerializer(serializers.Serializer):return data-def _last_refresh_for_shared_gate(insight: Insight, dashboard_tile: DashboardTile | None) -> datetime | None:- """Throttle clock for `?refresh=force_blocking` on shared insights. On DB error, returns- ``now()`` so the gate fails closed."""- try:- if dashboard_tile is not None:- cs = next(iter(dashboard_tile.caching_states.all()), None)- else:- cs = (- InsightCachingState.objects.filter(insight=insight, dashboard_tile=None)- .only("last_refresh", "created_at")- .first()- )- except Exception:- return datetime.now(UTC)- if cs is None:- return insight.created_at- return cs.last_refresh or cs.created_at--class InsightSerializer(InsightBasicSerializer):result = serializers.SerializerMethodField()hasMore = serializers.SerializerMethodField()@@ -993,9 +973,12 @@ class InsightSerializer(InsightBasicSerializer):dashboard: Dashboard | None = self.context.get("dashboard")request: Request | None = self.context.get("request")- dashboard_filters_override = filters_override_requested_by_client(request, dashboard) if request else None+ is_shared = self.context.get("is_shared", False)+ dashboard_filters_override = (+ filters_override_requested_by_client(request, dashboard, is_shared=is_shared) if request else None+ )dashboard_variables_override = variables_override_requested_by_client(- request, dashboard, list(self.context["insight_variables"])+ request, dashboard, list(self.context["insight_variables"]), is_shared=is_shared)# Tile filters completely replace dashboard filters (same semantics as the compute path in@@ -1003,7 +986,9 @@ class InsightSerializer(InsightBasicSerializer):# filters while the cached result was computed with tile filters — causing the persons modal# to use a different filter set than the chart.dashboard_tile = self.dashboard_tile_from_context(instance, dashboard)- tile_filters_override = tile_filters_override_requested_by_client(request, dashboard_tile) if request else {}+ tile_filters_override = (+ tile_filters_override_requested_by_client(request, dashboard_tile, is_shared=is_shared) if request else {}+ )if instance.query is not None or instance.query_from_filters is not None:# Upgrade before applying dashboard filters: the stored query may predate the current@@ -1100,24 +1085,24 @@ class InsightSerializer(InsightBasicSerializer):with upgrade_query(insight):try:+ is_shared = self.context.get("is_shared", False)refresh_requested = refresh_requested_by_client(self.context["request"])execution_mode = execution_mode_from_refresh(refresh_requested)- filters_override = filters_override_requested_by_client(self.context["request"], dashboard)+ filters_override = filters_override_requested_by_client(+ self.context["request"], dashboard, is_shared=is_shared+ )variables_override = variables_override_requested_by_client(- self.context["request"], dashboard, list(self.context["insight_variables"])+ self.context["request"], dashboard, list(self.context["insight_variables"]), is_shared=is_shared)dashboard_tile = self.dashboard_tile_from_context(insight, dashboard)tile_filters_override = tile_filters_override_requested_by_client(- self.context["request"], dashboard_tile+ self.context["request"], dashboard_tile, is_shared=is_shared)- is_shared = self.context.get("is_shared", False)+ shared_cache_age_seconds: int | None = Noneif is_shared:- execution_mode = shared_insights_execution_mode(- execution_mode,- last_refresh=_last_refresh_for_shared_gate(insight, dashboard_tile),- )+ execution_mode, shared_cache_age_seconds = shared_insights_execution_mode(execution_mode)# Shared rendering bypasses the FE scene-tag flow, so set product/feature# tags here. No-op overwrite for authenticated paths (same values).@@ -1145,6 +1130,7 @@ class InsightSerializer(InsightBasicSerializer):filters_override=filters_override,variables_override=variables_override,tile_filters_override=tile_filters_override,+ cache_age_seconds=shared_cache_age_seconds,analytics_props=get_request_analytics_properties(self.context["request"]),)except (ExposedHogQLError, ExposedCHQueryError, HogVMException) as e:diff --git a/products/product_analytics/backend/api/test/test_insight.py b/products/product_analytics/backend/api/test/test_insight.pyindex 50eb504f59ca..6741e80e5500 100644--- a/products/product_analytics/backend/api/test/test_insight.py+++ b/products/product_analytics/backend/api/test/test_insight.py@@ -50,7 +50,7 @@ from posthog.api.test.dashboards import DashboardAPIfrom posthog.caching.insight_cache import update_cachefrom posthog.caching.insight_caching_state import TargetCacheAgefrom posthog.constants import AvailableFeature-from posthog.hogql_queries.query_runner import ExecutionMode+from posthog.hogql_queries.query_runner import SHARED_FORCE_BLOCKING_STALENESS_WINDOW, ExecutionModefrom posthog.models import Filter, OrganizationMembership, SharingConfiguration, Team, Userfrom posthog.models.project import Projectfrom posthog.test.db_context_capturing import capture_db_queries@@ -60,7 +60,6 @@ from products.alerts.backend.models.alert import AlertConfigurationfrom products.cohorts.backend.models.cohort import Cohortfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.dashboards.backend.models.dashboard_tile import DashboardTile, Text-from products.product_analytics.backend.api.insight import _last_refresh_for_shared_gatefrom products.product_analytics.backend.models.insight import Insight, InsightViewedfrom products.product_analytics.backend.models.insight_caching_state import InsightCachingStatefrom products.product_analytics.backend.models.insight_variable import InsightVariable@@ -529,6 +528,7 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):filters_override={},variables_override={},tile_filters_override={},+ cache_age_seconds=None,analytics_props=ANY,)@@ -539,9 +539,9 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):calculate_for_query_based_insight.assert_called_once_with(mock.ANY,dashboard=mock.ANY,- # The shared force_blocking gate downgrades to IF_STALE because the insight was- # just created — the InsightCachingState row's `created_at` is younger than- # `SHARED_FORCE_BLOCKING_MIN_AGE` and the throttle clock falls back to it.+ # Shared force_blocking runs as blocking-if-stale with the throttle window as+ # the staleness threshold: a cache younger than `SHARED_FORCE_BLOCKING_STALENESS_WINDOW`+ # is served as-is, anything older (or missing) recomputes synchronously.execution_mode=ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE,team=self.team,user=mock.ANY,@@ -549,28 +549,70 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):filters_override={},variables_override={},tile_filters_override={},+ cache_age_seconds=int(SHARED_FORCE_BLOCKING_STALENESS_WINDOW.total_seconds()),analytics_props=ANY,)- @parameterized.expand(- [- # When no caching state row exists, the gate falls back to insight.created_at so- # legitimate stale-refresh isn't silently blocked on insights without rows.- ("missing_row_falls_back_to_insight_created_at", True),- ("existing_row_used_when_present", False),- ]- )- def test_last_refresh_for_shared_gate_fallback(self, _name: str, delete_caching_state: bool) -> None:- insight = Insight.objects.create(team=self.team, filters={"events": [{"id": "$pageview"}]})- if delete_caching_state:- InsightCachingState.objects.filter(insight=insight).delete()- self.assertIsNone(InsightCachingState.objects.filter(insight=insight).first())- expected = insight.created_at- else:- cs = InsightCachingState.objects.filter(insight=insight, dashboard_tile=None).first()- assert cs is not None # narrows type for mypy- expected = cs.created_at # last_refresh is null on a freshly created row- self.assertEqual(_last_refresh_for_shared_gate(insight, None), expected)+ def test_get_shared_insight_with_force_refresh_returns_200(self) -> None:+ # Un-mocked end-to-end regression test: exercises the real process_query_dict ->+ # process_query_model -> query_runner.run() chain that the mocked assertions above+ # never execute the body of. A 200 alone doesn't prove this: insight_result's+ # broad except Exception swallows calculation crashes into a query_status error+ # and still renders 200, so assert the embedded result actually computed.+ filter_dict = {"events": [{"id": "$pageview"}]}++ insight_id, _ = self.dashboard_api.create_insight({"filters": filter_dict, "name": "insight"})+ sharing_config = SharingConfiguration.objects.create(team=self.team, insight_id=insight_id, enabled=True)++ # .json suffix returns exported_data directly, skipping exporter.html rendering+ valid_url = f"{settings.SITE_URL}/shared/{sharing_config.access_token}.json"++ response = self.client.get(valid_url, data={"refresh": "force_blocking"})+ self.assertEqual(response.status_code, status.HTTP_200_OK)++ exported = response.json()+ query_status = exported["insight"]["query_status"] or {}+ self.assertFalse(query_status.get("error"), query_status)+ self.assertIsNotNone(exported["insight"]["result"])++ def test_shared_force_refresh_ignores_client_filter_overrides(self) -> None:+ # Regression: the /shared/<token> page load runs without an authenticator, so the serializer+ # must rely on the is_shared context flag to drop client-supplied overrides. Without the flag+ # reaching the override helpers, a viewer could pair a unique filters_override with+ # refresh=force_blocking on every request — each novel value is a fresh cache miss that+ # recomputes synchronously, defeating the throttle this PR relies on.+ insight_id, _ = self.dashboard_api.create_insight(+ {"filters": {"events": [{"id": "$pageview"}]}, "name": "insight"}+ )+ sharing_config = SharingConfiguration.objects.create(team=self.team, insight_id=insight_id, enabled=True)++ valid_url = f"{settings.SITE_URL}/shared/{sharing_config.access_token}"++ with patch(+ "posthog.caching.calculate_results.calculate_for_query_based_insight"+ ) as calculate_for_query_based_insight:+ self.client.get(+ valid_url,+ data={+ "refresh": "force_blocking",+ "filters_override": json.dumps({"date_from": "-1d"}),+ "variables_override": json.dumps({"injected": {"value": "evil"}}),+ "tile_filters_override": json.dumps({"breakdown": "region"}),+ },+ )+ calculate_for_query_based_insight.assert_called_once_with(+ mock.ANY,+ dashboard=mock.ANY,+ execution_mode=ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE,+ team=self.team,+ user=mock.ANY,+ user_access_control=mock.ANY,+ filters_override={},+ variables_override={},+ tile_filters_override={},+ cache_age_seconds=int(SHARED_FORCE_BLOCKING_STALENESS_WINDOW.total_seconds()),+ analytics_props=ANY,+ )def test_get_insight_by_short_id(self) -> None:filter_dict = {"events": [{"id": "$pageview"}]}