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.

perf(insights): skip full response model_dump when serving insight results (#71051)

Thomas Obermüllera7dbb9151aae
diff --git a/posthog/caching/calculate_results.py b/posthog/caching/calculate_results.py
index cd14ddd6e381..84eeeaf49267 100644
--- a/posthog/caching/calculate_results.py
+++ b/posthog/caching/calculate_results.py
@@ -1,4 +1,4 @@
-from typing import TYPE_CHECKING, Optional, Union
+from typing import TYPE_CHECKING, Any, Optional, Union
import structlog
from pydantic import BaseModel
@@ -10,7 +10,7 @@ from posthog.hogql.constants import LimitContext
from posthog.api.services.query import ExecutionMode, process_query_dict
from posthog.clickhouse.query_tagging import get_team_query_tags, tag_queries
from posthog.event_usage import AnalyticsProps
-from posthog.hogql_queries.query_runner import get_query_runner_or_none
+from posthog.hogql_queries.query_runner import get_query_runner_or_none, response_results_contain_models
from posthog.models import Team, User
from posthog.schema_migrations.upgrade_manager import upgrade_query
@@ -26,6 +26,33 @@ if TYPE_CHECKING:
logger = structlog.get_logger(__name__)
+def _model_field_as_dict(model: BaseModel, field: str) -> Optional[dict]:
+ value = getattr(model, field, None)
+ if value is None:
+ return None
+ if isinstance(value, BaseModel):
+ return value.model_dump(by_alias=True)
+ return value
+
+
+def _dump_nested_models(value: Any) -> Any:
+ """Container-preserving conversion of pydantic models to dicts (lists, dicts, scalars pass through)."""
+ if isinstance(value, BaseModel):
+ return value.model_dump(by_alias=True)
+ if isinstance(value, list):
+ return [_dump_nested_models(item) for item in value]
+ if isinstance(value, dict):
+ return {key: _dump_nested_models(item) for key, item in value.items()}
+ return value
+
+
+def _model_list_field_as_dicts(model: BaseModel, field: str) -> Optional[list]:
+ value = getattr(model, field, None)
+ if value is None:
+ return None
+ return [item.model_dump(by_alias=True) if isinstance(item, BaseModel) else item for item in value]
+
+
def calculate_cache_key(target: Union[DashboardTile, Insight]) -> Optional[str]:
insight: Optional[Insight] = target if isinstance(target, Insight) else target.insight
dashboard: Optional[Dashboard] = target.dashboard if isinstance(target, DashboardTile) else None
@@ -83,7 +110,7 @@ def calculate_for_query_based_insight(
if query_json is None:
raise ValueError("Insight has no query and no query_override was provided")
- response = process_response = process_query_dict(
+ process_response = process_query_dict(
team,
query_json,
dashboard_filters_json=dashboard_filters_json,
@@ -99,16 +126,43 @@ def calculate_for_query_based_insight(
analytics_props=analytics_props,
)
- if isinstance(process_response, BaseModel):
- response = process_response.model_dump(by_alias=True)
-
- assert isinstance(response, dict)
-
if isinstance(process_response, CacheMissResponse):
- return NothingInCacheResult(cache_key=process_response.cache_key, query_status=response.get("query_status"))
+ return NothingInCacheResult(
+ cache_key=process_response.cache_key, query_status=_model_field_as_dict(process_response, "query_status")
+ )
- cache_key = response.get("cache_key")
- last_refresh = response.get("last_refresh")
+ if isinstance(process_response, BaseModel):
+ # Don't model_dump() the whole response: `results` alone can be tens of MB of plain
+ # dicts, and dumping deep-copies all of it only for a handful of fields to be re-read.
+ # Pull fields off the model instead, converting just the small nested models to dicts
+ # (which is what model_dump produced before). The response class may not carry every
+ # field (legacy insights shape), hence the getattr defaults.
+ result = getattr(process_response, "results", None)
+ if result is not None and response_results_contain_models(type(process_response)):
+ # Model-typed results (e.g. RetentionResult, PathsLink) must be dumped to dicts
+ # like model_dump did — DRF's JSON encoder would otherwise mangle them into
+ # (field, value) tuple arrays. Results whose annotation is plain data (the huge
+ # trends/funnels payloads, or scalar/dict-shaped results) pass through untouched.
+ result = _dump_nested_models(result)
+ return InsightResult(
+ result=result,
+ has_more=getattr(process_response, "hasMore", None),
+ columns=getattr(process_response, "columns", None),
+ last_refresh=getattr(process_response, "last_refresh", None),
+ cache_key=getattr(process_response, "cache_key", None),
+ is_cached=getattr(process_response, "is_cached", False),
+ timezone=getattr(process_response, "timezone", None),
+ next_allowed_client_refresh=getattr(process_response, "next_allowed_client_refresh", None),
+ cache_target_age=getattr(process_response, "cache_target_age", None),
+ timings=_model_list_field_as_dicts(process_response, "timings"),
+ query_status=_model_field_as_dict(process_response, "query_status"),
+ hogql=getattr(process_response, "hogql", None),
+ types=getattr(process_response, "types", None),
+ resolved_date_range=_model_field_as_dict(process_response, "resolved_date_range"),
+ )
+
+ response = process_response
+ assert isinstance(response, dict)
return InsightResult(
# Translating `QueryResponse` to legacy insights shape
@@ -116,8 +170,8 @@ def calculate_for_query_based_insight(
result=response.get("results"),
has_more=response.get("hasMore"),
columns=response.get("columns"),
- last_refresh=last_refresh,
- cache_key=cache_key,
+ last_refresh=response.get("last_refresh"),
+ cache_key=response.get("cache_key"),
is_cached=response.get("is_cached", False),
timezone=response.get("timezone"),
next_allowed_client_refresh=response.get("next_allowed_client_refresh"),
diff --git a/posthog/caching/fetch_from_cache.py b/posthog/caching/fetch_from_cache.py
index 6940e0154ceb..74eda909a959 100644
--- a/posthog/caching/fetch_from_cache.py
+++ b/posthog/caching/fetch_from_cache.py
@@ -5,7 +5,7 @@ from typing import Any, Optional
import structlog
from prometheus_client import Counter
-from posthog.schema import QueryTiming, ResolvedDateRangeResponse
+from posthog.schema import QueryTiming
from posthog.cache_utils import OrjsonJsonSerializer
from posthog.caching.query_cache_routing import get_query_cache
@@ -61,7 +61,8 @@ class InsightResult:
query_status: Optional[Any] = None
hogql: Optional[str] = None
types: Optional[list] = None
- resolved_date_range: Optional[ResolvedDateRangeResponse] = None
+ # A ResolvedDateRangeResponse-shaped dict — the field carries model_dump output
+ resolved_date_range: Optional[dict] = None
@dataclass(frozen=True)
diff --git a/posthog/caching/test/test_calculate_results.py b/posthog/caching/test/test_calculate_results.py
new file mode 100644
index 000000000000..d8b95941c4fc
--- /dev/null
+++ b/posthog/caching/test/test_calculate_results.py
@@ -0,0 +1,106 @@
+from datetime import UTC, datetime
+
+from posthog.test.base import BaseTest
+from unittest.mock import patch
+
+from posthog.schema import (
+ CachedMarketingAnalyticsAggregatedQueryResponse,
+ CachedMarketingAnalyticsTableQueryResponse,
+ CachedRetentionQueryResponse,
+ CachedTrendsQueryResponse,
+ HogQueryResponse,
+ MarketingAnalyticsItem,
+ RetentionResult,
+)
+
+from posthog.api.services.query import ExecutionMode
+from posthog.caching.calculate_results import calculate_for_query_based_insight
+
+from products.product_analytics.backend.models.insight import Insight
+
+
+class TestCalculateForQueryBasedInsight(BaseTest):
+ def _calculate(self, response):
+ insight = Insight.objects.create(
+ team=self.team,
+ query={"kind": "InsightVizNode", "source": {"kind": "TrendsQuery", "series": []}},
+ )
+ with patch("posthog.caching.calculate_results.process_query_dict", return_value=response):
+ return calculate_for_query_based_insight(
+ insight,
+ team=self.team,
+ execution_mode=ExecutionMode.CACHE_ONLY_NEVER_CALCULATE,
+ user=None,
+ )
+
+ # Model-typed results (e.g. retention, paths, marketing analytics) must be dumped to
+ # dicts: DRF's JSON encoder falls back to iterating pydantic models, mangling them into
+ # (field, value) tuple arrays in the rendered response.
+ def test_model_typed_results_are_returned_as_dicts(self):
+ response = CachedRetentionQueryResponse(
+ results=[RetentionResult(date=datetime(2026, 1, 1, tzinfo=UTC), label="Day 0", values=[])],
+ is_cached=True,
+ last_refresh=datetime(2026, 1, 1, tzinfo=UTC),
+ next_allowed_client_refresh=datetime(2026, 1, 1, tzinfo=UTC),
+ cache_key="key",
+ timezone="UTC",
+ )
+
+ insight_result = self._calculate(response)
+
+ assert isinstance(insight_result.result[0], dict)
+ assert insight_result.result[0]["label"] == "Day 0"
+
+ def test_models_nested_in_result_lists_are_returned_as_dicts(self):
+ # e.g. CachedMarketingAnalyticsTableQueryResponse.results: list[list[MarketingAnalyticsItem]]
+ response = CachedMarketingAnalyticsTableQueryResponse(
+ results=[[MarketingAnalyticsItem(key="spend", kind="unit", value=1.0)]],
+ is_cached=True,
+ last_refresh=datetime(2026, 1, 1, tzinfo=UTC),
+ next_allowed_client_refresh=datetime(2026, 1, 1, tzinfo=UTC),
+ cache_key="key",
+ timezone="UTC",
+ )
+
+ insight_result = self._calculate(response)
+
+ assert isinstance(insight_result.result[0][0], dict)
+ assert insight_result.result[0][0]["key"] == "spend"
+
+ def test_dict_shaped_results_keep_their_shape_with_models_dumped(self):
+ response = CachedMarketingAnalyticsAggregatedQueryResponse(
+ results={"spend": MarketingAnalyticsItem(key="spend", kind="unit", value=1.0)},
+ is_cached=True,
+ last_refresh=datetime(2026, 1, 1, tzinfo=UTC),
+ next_allowed_client_refresh=datetime(2026, 1, 1, tzinfo=UTC),
+ cache_key="key",
+ timezone="UTC",
+ )
+
+ insight_result = self._calculate(response)
+
+ assert isinstance(insight_result.result, dict)
+ assert isinstance(insight_result.result["spend"], dict)
+ assert insight_result.result["spend"]["key"] == "spend"
+
+ def test_scalar_results_pass_through(self):
+ insight_result = self._calculate(HogQueryResponse(results="ERROR: nope"))
+
+ assert insight_result.result == "ERROR: nope"
+
+ def test_plain_dict_results_pass_through_without_copying(self):
+ series = {"data": [1.0, 2.0], "label": "series", "action": {"order": 0}}
+ response = CachedTrendsQueryResponse(
+ results=[series],
+ is_cached=True,
+ last_refresh=datetime(2026, 1, 1, tzinfo=UTC),
+ next_allowed_client_refresh=datetime(2026, 1, 1, tzinfo=UTC),
+ cache_key="key",
+ timezone="UTC",
+ )
+
+ insight_result = self._calculate(response)
+
+ assert insight_result.result[0] is response.results[0]
+ assert insight_result.is_cached is True
+ assert insight_result.cache_key == "key"
diff --git a/posthog/hogql_queries/query_runner.py b/posthog/hogql_queries/query_runner.py
index f0ef1c4eadcb..8e0ca04a21e0 100644
--- a/posthog/hogql_queries/query_runner.py
+++ b/posthog/hogql_queries/query_runner.py
@@ -2,6 +2,7 @@ from abc import ABC, abstractmethod
from collections.abc import Sequence
from datetime import UTC, datetime, timedelta
from enum import StrEnum
+from functools import cache
from time import perf_counter
from types import UnionType
from typing import Any, Generic, NamedTuple, Optional, Protocol, TypeGuard, TypeVar, Union, cast, get_args, get_origin
@@ -212,6 +213,33 @@ def get_survey_query_metric_labels(query: Any) -> dict[str, str] | None:
}
+def _annotation_mentions_base_model(annotation: Any) -> bool:
+ if annotation is None:
+ return False
+ if isinstance(annotation, type):
+ return issubclass(annotation, BaseModel)
+ return any(_annotation_mentions_base_model(arg) for arg in get_args(annotation))
+
+
+@cache
+def response_results_contain_models(response_class: type[BaseModel]) -> bool:
+ """Whether the class's `results` annotation can hold pydantic models (e.g. list[RetentionResult]).
+
+ Responses are only ever built by validating plain data (a cached JSON blob, or the dict a fresh
+ calculation was dumped to), so model instances can appear in `results` exactly where the
+ annotation declares a model type — `Any`/`dict[str, Any]` positions stay plain data.
+
+ Response classes are split on this roughly down the middle: many type `results` items as models,
+ while others — including the largest payloads (trends, funnels) — type them as plain data.
+ That split is historical, not a pattern to extend; this helper only exists to serve both
+ correctly, and should disappear if the response classes ever converge on one style.
+ """
+ field = response_class.model_fields.get("results")
+ if field is None:
+ return False
+ return _annotation_mentions_base_model(field.annotation)
+
+
def execution_mode_from_refresh(refresh_requested: bool | str | None) -> ExecutionMode:
if refresh_requested:
if execution_mode := _REFRESH_TO_EXECUTION_MODE.get(refresh_requested):