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.

feat(insights): resolve insight refresh mode through one per-surface policy (#72536)

Paul D'Ambra8aed39d344dc
diff --git a/posthog/api/sharing.py b/posthog/api/sharing.py
index ac07c0130924..2e51f79ccba8 100644
--- a/posthog/api/sharing.py
+++ b/posthog/api/sharing.py
@@ -35,6 +35,7 @@ from posthog.constants import AvailableFeature
from posthog.exceptions_capture import capture_exception
from posthog.helpers.impersonation import is_impersonated
from posthog.hogql_queries.query_runner import ExecutionMode, shared_insights_execution_mode
+from posthog.hogql_queries.refresh_policy import ComputeSurface
from posthog.jwt import PosthogJwtAudience, encode_jwt
from posthog.models import SessionRecording, SharePassword, SharingConfiguration, Team
from posthog.models.activity_logging.activity_log import Change, Detail, log_activity
@@ -974,6 +975,7 @@ class SharingViewerPageViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSe
# serialize raw cached result bytes (orjson.Fragment)
"require_parsed_results": True,
"dashboard_access_method": dashboard_access_method(request, is_shared=True, is_embedded=embedded),
+ "compute_surface": ComputeSurface.SHARED,
}
exported_data: dict[str, Any] = {"type": "embed" if embedded else "scene"}
diff --git a/posthog/hogql_queries/refresh_policy.py b/posthog/hogql_queries/refresh_policy.py
new file mode 100644
index 000000000000..f9100223bb18
--- /dev/null
+++ b/posthog/hogql_queries/refresh_policy.py
@@ -0,0 +1,93 @@
+"""Single source of truth for how an insight result is (re)computed per request.
+
+Every HTTP surface that renders insight tiles (the insight detail/list endpoints, the
+dashboard detail/stream/run_insights actions, and shared/embedded rendering) funnels into
+`InsightSerializer.insight_result`, which computes an `ExecutionMode`. Historically each
+surface's *default* (what happens when the client sends no explicit `?refresh=`) was an
+accident of which query params its client happened to send, invisible at the route. This
+module makes that default explicit and per-surface, in one table, without changing the
+rule that an explicit client `?refresh=` always wins.
+"""
+
+from enum import StrEnum
+from typing import TYPE_CHECKING
+
+from posthog.hogql_queries.query_runner import (
+ ExecutionMode,
+ SharedExecutionSettings,
+ execution_mode_from_refresh,
+ shared_insights_execution_mode,
+)
+from posthog.utils import refresh_requested_by_client
+
+if TYPE_CHECKING:
+ from rest_framework.request import Request
+
+
+class ComputeSurface(StrEnum):
+ """The route/caller computing an insight result. Selects the default execution mode
+ when the client sends no explicit `?refresh=`; an explicit value always overrides it."""
+
+ INSIGHT_DETAIL = "insight_detail"
+ INSIGHT_LIST = "insight_list"
+ # An insight rendered as a dashboard tile (insights/{pk}?from_dashboard=…), distinct from the
+ # standalone insight editor (INSIGHT_DETAIL) so the two can carry different refresh defaults.
+ DASHBOARD_TILE = "dashboard_tile"
+ DASHBOARD_DETAIL = "dashboard_detail"
+ DASHBOARD_STREAM = "dashboard_stream"
+ DASHBOARD_RUN_INSIGHTS = "dashboard_run_insights"
+ DASHBOARD_MUTATE = "dashboard_mutate"
+ SHARED = "shared"
+ LEGACY_UNKNOWN = "legacy_unknown"
+
+
+# The one place per-surface refresh defaults live. Every surface is CACHE_ONLY_NEVER_CALCULATE
+# today, which reproduces the historical behavior (an absent `?refresh=` meant cache-only on
+# every route). Listed explicitly per surface (rather than dict.fromkeys) so changing one
+# surface's default is a single greppable, independently measurable line to flip — rather than
+# editing request handling in each viewset.
+SURFACE_DEFAULT_EXECUTION_MODE: dict[ComputeSurface, ExecutionMode] = {
+ ComputeSurface.INSIGHT_DETAIL: ExecutionMode.CACHE_ONLY_NEVER_CALCULATE,
+ ComputeSurface.INSIGHT_LIST: ExecutionMode.CACHE_ONLY_NEVER_CALCULATE,
+ ComputeSurface.DASHBOARD_TILE: ExecutionMode.CACHE_ONLY_NEVER_CALCULATE,
+ ComputeSurface.DASHBOARD_DETAIL: ExecutionMode.CACHE_ONLY_NEVER_CALCULATE,
+ ComputeSurface.DASHBOARD_STREAM: ExecutionMode.CACHE_ONLY_NEVER_CALCULATE,
+ ComputeSurface.DASHBOARD_RUN_INSIGHTS: ExecutionMode.CACHE_ONLY_NEVER_CALCULATE,
+ ComputeSurface.DASHBOARD_MUTATE: ExecutionMode.CACHE_ONLY_NEVER_CALCULATE,
+ ComputeSurface.SHARED: ExecutionMode.CACHE_ONLY_NEVER_CALCULATE,
+ ComputeSurface.LEGACY_UNKNOWN: ExecutionMode.CACHE_ONLY_NEVER_CALCULATE,
+}
+
+
+def _refresh_param_present(request: "Request") -> bool:
+ """Whether the client sent a `refresh` param at all (query string or body), regardless of its
+ value — so an explicit `refresh=false` is distinguished from an absent param."""
+ if request.query_params.get("refresh") is not None:
+ return True
+ data = getattr(request, "data", None)
+ return isinstance(data, dict) and data.get("refresh") is not None
+
+
+def resolve_execution_mode(
+ request: "Request", *, surface: ComputeSurface, is_shared: bool = False
+) -> SharedExecutionSettings:
+ """Resolve the execution mode (and shared staleness window) for one insight computation.
+
+ Precedence: an explicit `?refresh=` from the client wins; otherwise the surface default.
+ Shared/embedded resources are clamped last — anonymous demand must never force a blocking
+ recompute — and that clamp also carries the `cache_age_seconds` staleness window. Returns
+ a `SharedExecutionSettings(execution_mode, cache_age_seconds)`; `cache_age_seconds` is None
+ off the shared path.
+ """
+ # An explicit ?refresh= (any value, including false/0/no) is honored via
+ # execution_mode_from_refresh, matching historical behavior — so a client that opts out of
+ # refreshing still gets CACHE_ONLY even after a surface default is flipped off cache-only.
+ # The surface default applies only when no refresh param is present at all.
+ if _refresh_param_present(request):
+ execution_mode = execution_mode_from_refresh(refresh_requested_by_client(request))
+ else:
+ execution_mode = SURFACE_DEFAULT_EXECUTION_MODE[surface]
+
+ if is_shared:
+ return shared_insights_execution_mode(execution_mode)
+ return SharedExecutionSettings(execution_mode, None)
diff --git a/posthog/hogql_queries/test/test_refresh_policy.py b/posthog/hogql_queries/test/test_refresh_policy.py
new file mode 100644
index 000000000000..1fc8e463e417
--- /dev/null
+++ b/posthog/hogql_queries/test/test_refresh_policy.py
@@ -0,0 +1,77 @@
+from typing import cast
+
+from unittest import mock
+
+from django.http import HttpRequest
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+from rest_framework.request import Request
+
+from posthog.hogql_queries.query_runner import ExecutionMode
+from posthog.hogql_queries.refresh_policy import ComputeSurface, resolve_execution_mode
+
+
+def _request(refresh: str | None = None) -> Request:
+ drf_request = cast(Request, Request(HttpRequest()))
+ drf_request._full_data = {"refresh": refresh} if refresh is not None else {} # type: ignore[attr-defined]
+ return drf_request
+
+
+class TestResolveExecutionMode(SimpleTestCase):
+ @parameterized.expand([(surface,) for surface in ComputeSurface])
+ def test_default_is_cache_only_for_every_surface(self, surface: ComputeSurface) -> None:
+ # Parity snapshot: with no client refresh param, every surface is cache-only today.
+ # When a surface default is deliberately changed, update the expected value here — this
+ # assertion is the tripwire that forces that change to be conscious and reviewed.
+ mode, cache_age = resolve_execution_mode(_request(), surface=surface)
+ assert mode == ExecutionMode.CACHE_ONLY_NEVER_CALCULATE
+ assert cache_age is None
+
+ @parameterized.expand(
+ [
+ ("blocking", ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE),
+ ("force_blocking", ExecutionMode.CALCULATE_BLOCKING_ALWAYS),
+ ("async", ExecutionMode.RECENT_CACHE_CALCULATE_ASYNC_IF_STALE),
+ ("force_cache", ExecutionMode.CACHE_ONLY_NEVER_CALCULATE),
+ ]
+ )
+ def test_explicit_refresh_overrides_surface_default(self, refresh: str, expected: ExecutionMode) -> None:
+ # An explicit ?refresh= wins over the surface default, on every surface. This invariant
+ # must survive any future change to the default table.
+ for surface in ComputeSurface:
+ mode, cache_age = resolve_execution_mode(_request(refresh), surface=surface)
+ assert mode == expected, surface
+ assert cache_age is None
+
+ def test_explicit_refresh_false_stays_cache_only_when_surface_default_is_flipped(self) -> None:
+ # An explicit ?refresh=false is the client opting out of a recompute; it must stay
+ # cache-only even once a surface default is flipped off cache-only, whereas an absent
+ # param follows the (flipped) surface default. Guards the exact regression where explicit
+ # opt-out silently inherits a non-cache default.
+ with mock.patch.dict(
+ "posthog.hogql_queries.refresh_policy.SURFACE_DEFAULT_EXECUTION_MODE",
+ {ComputeSurface.DASHBOARD_TILE: ExecutionMode.RECENT_CACHE_CALCULATE_ASYNC_IF_STALE},
+ ):
+ absent_mode, _ = resolve_execution_mode(_request(), surface=ComputeSurface.DASHBOARD_TILE)
+ assert absent_mode == ExecutionMode.RECENT_CACHE_CALCULATE_ASYNC_IF_STALE
+
+ false_mode, _ = resolve_execution_mode(_request("false"), surface=ComputeSurface.DASHBOARD_TILE)
+ assert false_mode == ExecutionMode.CACHE_ONLY_NEVER_CALCULATE
+
+ def test_shared_flag_applies_the_clamp(self) -> None:
+ # resolve_execution_mode's own responsibility is to route through the shared clamp iff
+ # is_shared (the exhaustive clamp mapping is covered in test_query_runner). Contrast the
+ # same request with/without the flag: only the shared path carries a staleness window,
+ # and dropping that cache_age would silently disable the shared force-refresh throttle.
+ unshared_mode, unshared_cache_age = resolve_execution_mode(
+ _request("force_blocking"), surface=ComputeSurface.SHARED, is_shared=False
+ )
+ assert unshared_mode == ExecutionMode.CALCULATE_BLOCKING_ALWAYS
+ assert unshared_cache_age is None
+
+ shared_mode, shared_cache_age = resolve_execution_mode(
+ _request("force_blocking"), surface=ComputeSurface.SHARED, is_shared=True
+ )
+ assert shared_mode == ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE
+ assert shared_cache_age is not None and shared_cache_age > 0
diff --git a/products/dashboards/backend/api/dashboard.py b/products/dashboards/backend/api/dashboard.py
index a87f299c1360..d0ca50312f00 100644
--- a/products/dashboards/backend/api/dashboard.py
+++ b/products/dashboards/backend/api/dashboard.py
@@ -70,6 +70,7 @@ from posthog.helpers.trigram_search import (
drop_similar_when_exact_exists,
)
from posthog.hogql_queries.apply_dashboard_filters import normalize_dashboard_filters_properties
+from posthog.hogql_queries.refresh_policy import ComputeSurface
from posthog.models.file_system.constants import DEFAULT_SURFACE, surface_q
from posthog.models.file_system.file_system import FileSystem, create_or_update_file, delete_file, join_path, split_path
from posthog.models.quick_filter import QuickFilter
@@ -2214,6 +2215,11 @@ class DashboardsViewSet(
def get_serializer_context(self) -> dict[str, Any]:
context = super().get_serializer_context()
context["insight_variables"] = InsightVariable.objects.filter(team=self.team).all()
+ context["compute_surface"] = (
+ ComputeSurface.DASHBOARD_MUTATE
+ if self.action in {"create", "update", "partial_update"}
+ else ComputeSurface.DASHBOARD_DETAIL
+ )
return context
@@ -2458,6 +2464,7 @@ class DashboardsViewSet(
"dashboard": dashboard,
"dashboard_access_method": access_method,
"raw_results_supported": True,
+ "compute_surface": ComputeSurface.DASHBOARD_STREAM,
}
)
@@ -2914,6 +2921,7 @@ class DashboardsViewSet(
context = self.get_serializer_context()
context["dashboard"] = dashboard
context["dashboard_access_method"] = access_method
+ context["compute_surface"] = ComputeSurface.DASHBOARD_RUN_INSIGHTS
# _format_insight_for_llm consumes results as Python data, so raw cached
# result bytes (orjson.Fragment) must not be used here.
context["require_parsed_results"] = True
diff --git a/products/product_analytics/backend/api/insight.py b/products/product_analytics/backend/api/insight.py
index a18159ed8d27..dd9ea8b0bdaa 100644
--- a/products/product_analytics/backend/api/insight.py
+++ b/products/product_analytics/backend/api/insight.py
@@ -91,12 +91,8 @@ from posthog.hogql_queries.apply_dashboard_filters import (
)
from posthog.hogql_queries.legacy_compatibility.feature_flag import get_query_method
from posthog.hogql_queries.legacy_compatibility.filter_to_query import filter_to_query
-from posthog.hogql_queries.query_runner import (
- BLOCKING_EXECUTION_MODES,
- ExecutionMode,
- execution_mode_from_refresh,
- shared_insights_execution_mode,
-)
+from posthog.hogql_queries.query_runner import BLOCKING_EXECUTION_MODES, ExecutionMode, execution_mode_from_refresh
+from posthog.hogql_queries.refresh_policy import ComputeSurface, resolve_execution_mode
from posthog.kafka_client.topics import KAFKA_METRICS_TIME_TO_SEE_DATA
from posthog.models import Filter, User
from posthog.models.activity_logging.activity_log import (
@@ -1281,8 +1277,11 @@ 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)
+ execution_mode, shared_cache_age_seconds = resolve_execution_mode(
+ self.context["request"],
+ surface=self.context.get("compute_surface", ComputeSurface.LEGACY_UNKNOWN),
+ is_shared=is_shared,
+ )
filters_override = filters_override_requested_by_client(
self.context["request"], dashboard, is_shared=is_shared
)
@@ -1295,10 +1294,6 @@ class InsightSerializer(InsightBasicSerializer):
self.context["request"], dashboard_tile, is_shared=is_shared
)
- shared_cache_age_seconds: int | None = None
- if is_shared:
- 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).
shared_tags = {"access_method": AccessMethod.SHARING_TOKEN} if is_shared else {}
@@ -1752,6 +1747,9 @@ class InsightViewSet(
# the same context key the /shared/ page render uses (SharingViewerPageViewSet).
context["shared_link_user"] = self.request.user
context["insight_variables"] = InsightVariable.objects.filter(team=self.team).all()
+ context["compute_surface"] = (
+ ComputeSurface.INSIGHT_LIST if self.action == "list" else ComputeSurface.INSIGHT_DETAIL
+ )
return context
@@ -2177,6 +2175,7 @@ When set, the specified dashboard's filters and date range override will be appl
"dashboard_access_method": dashboard_access_method(
request, is_shared=serializer_context["is_shared"]
),
+ "compute_surface": ComputeSurface.DASHBOARD_TILE,
}
)