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): serve cached insight results as raw JSON without parse round trip (#71268)

Thomas Obermüllerf47efb053ec7
diff --git a/posthog/api/services/query.py b/posthog/api/services/query.py
index 59e1e132094a..65ea529bf68b 100644
--- a/posthog/api/services/query.py
+++ b/posthog/api/services/query.py
@@ -1,4 +1,5 @@
-from typing import Optional
+from dataclasses import dataclass
+from typing import Literal, Optional, overload
import structlog
import pydantic_core
@@ -42,6 +43,66 @@ from common.hogvm.python.debugger import color_bytecode
logger = structlog.get_logger(__name__)
+@dataclass(frozen=True)
+class RawCachedQueryResponse:
+ """A cached query response whose `results` field is carried as raw JSON bytes.
+
+ `response.results` holds an empty-list placeholder; `raw_results` is the JSON-encoded
+ results segment straight from the cache, ready to be embedded into a JSON response
+ (e.g. via orjson.Fragment) without a parse/re-serialize round trip. Only produced when
+ a caller passes allow_raw_results=True.
+ """
+
+ response: BaseModel
+ raw_results: bytes
+
+
+# The overloads keep the public contract at `dict | BaseModel` for the vast majority of
+# callers: only allow_raw_results=True can produce a RawCachedQueryResponse.
+@overload
+def process_query_dict(
+ team: Team,
+ query_json: dict,
+ *,
+ dashboard_filters_json: Optional[dict] = ...,
+ variables_override_json: Optional[dict] = ...,
+ limit_context: Optional[LimitContext] = ...,
+ execution_mode: ExecutionMode = ...,
+ user: Optional[User] = ...,
+ user_access_control: Optional[UserAccessControl] = ...,
+ query_id: Optional[str] = ...,
+ insight_id: Optional[int] = ...,
+ dashboard_id: Optional[int] = ...,
+ is_query_service: bool = ...,
+ cache_age_seconds: Optional[int] = ...,
+ pagination_cursor: Optional[str] = ...,
+ analytics_props: Optional[AnalyticsProps] = ...,
+ allow_raw_results: Literal[False] = ...,
+) -> dict | BaseModel: ...
+
+
+@overload
+def process_query_dict(
+ team: Team,
+ query_json: dict,
+ *,
+ dashboard_filters_json: Optional[dict] = ...,
+ variables_override_json: Optional[dict] = ...,
+ limit_context: Optional[LimitContext] = ...,
+ execution_mode: ExecutionMode = ...,
+ user: Optional[User] = ...,
+ user_access_control: Optional[UserAccessControl] = ...,
+ query_id: Optional[str] = ...,
+ insight_id: Optional[int] = ...,
+ dashboard_id: Optional[int] = ...,
+ is_query_service: bool = ...,
+ cache_age_seconds: Optional[int] = ...,
+ pagination_cursor: Optional[str] = ...,
+ analytics_props: Optional[AnalyticsProps] = ...,
+ allow_raw_results: bool,
+) -> dict | BaseModel | RawCachedQueryResponse: ...
+
+
def process_query_dict(
team: Team,
query_json: dict,
@@ -59,7 +120,8 @@ def process_query_dict(
cache_age_seconds: Optional[int] = None,
pagination_cursor: Optional[str] = None,
analytics_props: Optional[AnalyticsProps] = None,
-) -> dict | BaseModel:
+ allow_raw_results: bool = False,
+) -> dict | BaseModel | RawCachedQueryResponse:
upgraded_query_json = upgrade(query_json)
try:
model = QuerySchemaRoot.model_validate(upgraded_query_json)
@@ -111,9 +173,54 @@ def process_query_dict(
cache_age_seconds=cache_age_seconds,
pagination_cursor=pagination_cursor,
analytics_props=analytics_props,
+ allow_raw_results=allow_raw_results,
)
+@overload
+def process_query_model(
+ team: Team,
+ query: BaseModel,
+ *,
+ dashboard_filters: Optional[DashboardFilter] = ...,
+ variables_override: Optional[list[HogQLVariable]] = ...,
+ limit_context: Optional[LimitContext] = ...,
+ execution_mode: ExecutionMode = ...,
+ user: Optional[User] = ...,
+ user_access_control: Optional[UserAccessControl] = ...,
+ query_id: Optional[str] = ...,
+ insight_id: Optional[int] = ...,
+ dashboard_id: Optional[int] = ...,
+ is_query_service: bool = ...,
+ cache_age_seconds: Optional[int] = ...,
+ pagination_cursor: Optional[str] = ...,
+ analytics_props: Optional[AnalyticsProps] = ...,
+ allow_raw_results: Literal[False] = ...,
+) -> dict | BaseModel: ...
+
+
+@overload
+def process_query_model(
+ team: Team,
+ query: BaseModel,
+ *,
+ dashboard_filters: Optional[DashboardFilter] = ...,
+ variables_override: Optional[list[HogQLVariable]] = ...,
+ limit_context: Optional[LimitContext] = ...,
+ execution_mode: ExecutionMode = ...,
+ user: Optional[User] = ...,
+ user_access_control: Optional[UserAccessControl] = ...,
+ query_id: Optional[str] = ...,
+ insight_id: Optional[int] = ...,
+ dashboard_id: Optional[int] = ...,
+ is_query_service: bool = ...,
+ cache_age_seconds: Optional[int] = ...,
+ pagination_cursor: Optional[str] = ...,
+ analytics_props: Optional[AnalyticsProps] = ...,
+ allow_raw_results: bool,
+) -> dict | BaseModel | RawCachedQueryResponse: ...
+
+
def process_query_model(
team: Team,
query: BaseModel, # mypy has problems with unions and isinstance
@@ -131,8 +238,9 @@ def process_query_model(
cache_age_seconds: Optional[int] = None,
pagination_cursor: Optional[str] = None,
analytics_props: Optional[AnalyticsProps] = None,
-) -> dict | BaseModel:
- result: dict | BaseModel
+ allow_raw_results: bool = False,
+) -> dict | BaseModel | RawCachedQueryResponse:
+ result: dict | BaseModel | RawCachedQueryResponse
if isinstance(query, HogQLAutocomplete):
_, database = resolve_database_for_connection(
@@ -203,6 +311,7 @@ def process_query_model(
is_query_service=is_query_service,
cache_age_seconds=cache_age_seconds,
analytics_props=analytics_props,
+ allow_raw_results=allow_raw_results,
)
elif execution_mode == ExecutionMode.CACHE_ONLY_NEVER_CALCULATE:
# Caching is handled by query runners, so in this case we can only return a cache miss
@@ -232,6 +341,8 @@ def process_query_model(
if pagination_cursor:
query_runner.apply_pagination_cursor(pagination_cursor)
query_runner.is_query_service = is_query_service
+ if allow_raw_results:
+ query_runner.serve_raw_cached_results = True
result = query_runner.run(
execution_mode=execution_mode,
@@ -242,5 +353,8 @@ def process_query_model(
cache_age_seconds=cache_age_seconds,
analytics_props=analytics_props,
)
+ raw_results = query_runner.raw_cached_results_bytes
+ if raw_results is not None and isinstance(result, BaseModel):
+ return RawCachedQueryResponse(response=result, raw_results=raw_results)
return result
diff --git a/posthog/api/sharing.py b/posthog/api/sharing.py
index 435953e3dff1..679fa0230028 100644
--- a/posthog/api/sharing.py
+++ b/posthog/api/sharing.py
@@ -950,6 +950,9 @@ class SharingViewerPageViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSe
"insight_variables": InsightVariable.objects.filter(team=resource.team).all(),
"export_cache_keys": export_cache_keys,
"shared_link_user": shared_link_user,
+ # exported_data is embedded into the page with stdlib json.dumps, which cannot
+ # serialize raw cached result bytes (orjson.Fragment)
+ "require_parsed_results": True,
}
exported_data: dict[str, Any] = {"type": "embed" if embedded else "scene"}
diff --git a/posthog/caching/calculate_results.py b/posthog/caching/calculate_results.py
index b7ce0e0e95e3..b725e99f98a3 100644
--- a/posthog/caching/calculate_results.py
+++ b/posthog/caching/calculate_results.py
@@ -1,5 +1,6 @@
from typing import TYPE_CHECKING, Any, Optional, Union
+import orjson
import structlog
from pydantic import BaseModel
@@ -7,7 +8,7 @@ from posthog.schema import CacheMissResponse, DashboardFilter
from posthog.hogql.constants import LimitContext
-from posthog.api.services.query import ExecutionMode, process_query_dict
+from posthog.api.services.query import ExecutionMode, RawCachedQueryResponse, 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.apply_dashboard_filters import resolve_effective_dashboard_filters
@@ -88,6 +89,7 @@ def calculate_for_query_based_insight(
query_override: Optional[dict] = None,
cache_age_seconds: Optional[int] = None,
analytics_props: Optional[AnalyticsProps] = None,
+ allow_raw_results: bool = False,
) -> "InsightResult":
from posthog.caching.fetch_from_cache import InsightResult, NothingInCacheResult
@@ -125,8 +127,14 @@ def calculate_for_query_based_insight(
limit_context=LimitContext.QUERY_ASYNC,
cache_age_seconds=cache_age_seconds,
analytics_props=analytics_props,
+ allow_raw_results=allow_raw_results,
)
+ raw_results: Optional[bytes] = None
+ if isinstance(process_response, RawCachedQueryResponse):
+ raw_results = process_response.raw_results
+ process_response = process_response.response
+
if isinstance(process_response, CacheMissResponse):
return NothingInCacheResult(
cache_key=process_response.cache_key, query_status=_model_field_as_dict(process_response, "query_status")
@@ -138,13 +146,19 @@ def calculate_for_query_based_insight(
# 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)
+ if raw_results is not None:
+ # orjson.Fragment embeds the cached results bytes into the JSON response as-is,
+ # skipping the parse/re-serialize round trip. Callers passing allow_raw_results
+ # guarantee the result feeds an orjson renderer.
+ result: Any = orjson.Fragment(raw_results)
+ else:
+ 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),
diff --git a/posthog/caching/fetch_from_cache.py b/posthog/caching/fetch_from_cache.py
index 74eda909a959..b30541dae38f 100644
--- a/posthog/caching/fetch_from_cache.py
+++ b/posthog/caching/fetch_from_cache.py
@@ -18,8 +18,77 @@ insight_cache_read_counter = Counter(
labelnames=["result"],
)
+# Split cache format: magic + flags byte + 4-byte big-endian header length + header JSON + results JSON.
+# Storing `results` as a separate JSON segment lets cache hits skip parsing (and later re-serializing)
+# the results payload, which dominates CPU for large cached insights. Blobs without the magic prefix
+# are the legacy single-JSON format and stay readable.
+QUERY_CACHE_SPLIT_MAGIC = b"PHQC2\x00"
+# The flags byte is a bitmask: readers must test individual bits, never compare the whole byte,
+# so new flags can be added without breaking existing readers.
+_SPLIT_FLAG_CUSTOM_NAMES = 0b00000001
-def fetch_cached_response_by_key(cache_key: str, team_id: int) -> Optional[dict]:
+
+@dataclass(frozen=True)
+class SplitCachedResponse:
+ """A cached query response with the `results` segment kept as raw, unparsed JSON bytes."""
+
+ header: dict
+ results_bytes: Optional[bytes]
+ """Raw JSON bytes of the `results` field; None means `header` is the full legacy response."""
+ results_have_custom_names: bool = False
+ """Whether any series/step in results carries a non-null custom_name (so a cache hit may need patching)."""
+
+
+def _item_has_custom_name(item: Any) -> bool:
+ if not isinstance(item, dict):
+ return False
+ if item.get("custom_name") is not None:
+ return True
+ action = item.get("action")
+ return isinstance(action, dict) and action.get("custom_name") is not None
+
+
+def results_have_custom_names(results: list) -> bool:
+ for item in results:
+ if _item_has_custom_name(item):
+ return True
+ if isinstance(item, list) and any(_item_has_custom_name(step) for step in item):
+ return True
+ return False
+
+
+def encode_split_cached_response(response: dict) -> bytes:
+ serializer = OrjsonJsonSerializer({})
+ results = response["results"]
+ header = {key: value for key, value in response.items() if key != "results"}
+ flags = _SPLIT_FLAG_CUSTOM_NAMES if results_have_custom_names(results) else 0
+ header_bytes = serializer.dumps(header)
+ return (
+ QUERY_CACHE_SPLIT_MAGIC
+ + bytes([flags])
+ + len(header_bytes).to_bytes(4, "big")
+ + header_bytes
+ + serializer.dumps(results)
+ )
+
+
+def split_cached_response_bytes(cached_response_bytes: bytes) -> SplitCachedResponse:
+ serializer = OrjsonJsonSerializer({})
+ if not cached_response_bytes.startswith(QUERY_CACHE_SPLIT_MAGIC):
+ return SplitCachedResponse(header=serializer.loads(cached_response_bytes), results_bytes=None)
+ offset = len(QUERY_CACHE_SPLIT_MAGIC)
+ flags = cached_response_bytes[offset]
+ header_length = int.from_bytes(cached_response_bytes[offset + 1 : offset + 5], "big")
+ header_start = offset + 5
+ header = serializer.loads(cached_response_bytes[header_start : header_start + header_length])
+ return SplitCachedResponse(
+ header=header,
+ results_bytes=cached_response_bytes[header_start + header_length :],
+ results_have_custom_names=bool(flags & _SPLIT_FLAG_CUSTOM_NAMES),
+ )
+
+
+def fetch_split_cached_response_by_key(cache_key: str, team_id: int) -> Optional[SplitCachedResponse]:
query_cache = get_query_cache()
try:
cached_response_bytes = query_cache.get(cache_key)
@@ -35,7 +104,7 @@ def fetch_cached_response_by_key(cache_key: str, team_id: int) -> Optional[dict]
return None
try:
- return OrjsonJsonSerializer({}).loads(cached_response_bytes)
+ return split_cached_response_bytes(cached_response_bytes)
except Exception:
logger.exception(
"query_cache_deserialize_error",
@@ -46,6 +115,20 @@ def fetch_cached_response_by_key(cache_key: str, team_id: int) -> Optional[dict]
return None
+def fetch_cached_response_by_key(cache_key: str, team_id: int) -> Optional[dict]:
+ split = fetch_split_cached_response_by_key(cache_key, team_id)
+ if split is None:
+ return None
+ if split.results_bytes is None:
+ return split.header
+ try:
+ split.header["results"] = OrjsonJsonSerializer({}).loads(split.results_bytes)
+ except Exception:
+ logger.exception("query_cache_deserialize_error", cache_key=cache_key, team_id=team_id, exc_info=True)
+ return None
+ return split.header
+
+
@dataclass(frozen=True)
class InsightResult:
result: Optional[Any]
diff --git a/posthog/caching/test/test_calculate_results.py b/posthog/caching/test/test_calculate_results.py
index d8b95941c4fc..d9e2f249c83e 100644
--- a/posthog/caching/test/test_calculate_results.py
+++ b/posthog/caching/test/test_calculate_results.py
@@ -3,6 +3,8 @@ from datetime import UTC, datetime
from posthog.test.base import BaseTest
from unittest.mock import patch
+import orjson
+
from posthog.schema import (
CachedMarketingAnalyticsAggregatedQueryResponse,
CachedMarketingAnalyticsTableQueryResponse,
@@ -13,14 +15,14 @@ from posthog.schema import (
RetentionResult,
)
-from posthog.api.services.query import ExecutionMode
+from posthog.api.services.query import ExecutionMode, RawCachedQueryResponse
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):
+ def _calculate(self, response, allow_raw_results: bool = False):
insight = Insight.objects.create(
team=self.team,
query={"kind": "InsightVizNode", "source": {"kind": "TrendsQuery", "series": []}},
@@ -31,6 +33,7 @@ class TestCalculateForQueryBasedInsight(BaseTest):
team=self.team,
execution_mode=ExecutionMode.CACHE_ONLY_NEVER_CALCULATE,
user=None,
+ allow_raw_results=allow_raw_results,
)
# Model-typed results (e.g. retention, paths, marketing analytics) must be dumped to
@@ -104,3 +107,22 @@ class TestCalculateForQueryBasedInsight(BaseTest):
assert insight_result.result[0] is response.results[0]
assert insight_result.is_cached is True
assert insight_result.cache_key == "key"
+
+ def test_raw_cached_results_become_fragments(self):
+ raw = orjson.dumps([{"data": [1.0], "label": "series"}])
+ response = RawCachedQueryResponse(
+ response=CachedTrendsQueryResponse(
+ results=[],
+ 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",
+ ),
+ raw_results=raw,
+ )
+
+ insight_result = self._calculate(response, allow_raw_results=True)
+
+ assert isinstance(insight_result.result, orjson.Fragment)
+ assert orjson.dumps({"result": insight_result.result}) == b'{"result":[{"data":[1.0],"label":"series"}]}'
diff --git a/posthog/caching/test/test_query_cache_format.py b/posthog/caching/test/test_query_cache_format.py
new file mode 100644
index 000000000000..fc1a4ae6e010
--- /dev/null
+++ b/posthog/caching/test/test_query_cache_format.py
@@ -0,0 +1,46 @@
+from posthog.test.base import BaseTest
+
+from posthog.cache_utils import OrjsonJsonSerializer
+from posthog.caching.fetch_from_cache import fetch_cached_response_by_key, fetch_split_cached_response_by_key
+from posthog.caching.query_cache_routing import get_query_cache
+from posthog.hogql_queries.query_cache_factory import get_query_cache_manager
+
+
+class TestQueryCacheWriteFormat(BaseTest):
+ def test_writes_split_format_and_round_trips(self):
+ response = {"is_cached": False, "results": [{"data": [1]}], "cache_key": "k"}
+ manager = get_query_cache_manager(team=self.team, cache_key=f"cache_format_test_{self.team.pk}", insight_id=1)
+
+ manager.set_cache_data(response=response, target_age=None)
+
+ split = fetch_split_cached_response_by_key(manager.cache_key, self.team.pk)
+ assert split is not None
+ assert split.results_bytes == b'[{"data":[1]}]'
+ assert fetch_cached_response_by_key(manager.cache_key, self.team.pk) == {
+ "is_cached": False,
+ "results": [{"data": [1]}],
+ "cache_key": "k",
+ }
+
+ def test_non_list_results_write_legacy_format(self):
+ response = {"is_cached": False, "results": None, "cache_key": "k"}
+ manager = get_query_cache_manager(
+ team=self.team, cache_key=f"cache_format_test_legacy_{self.team.pk}", insight_id=1
+ )
+
+ manager.set_cache_data(response=response, target_age=None)
+
+ split = fetch_split_cached_response_by_key(manager.cache_key, self.team.pk)
+ assert split is not None
+ assert split.results_bytes is None
+ assert split.header == response
+
+ def test_legacy_blobs_written_before_split_rollout_stay_readable(self):
+ cache_key = f"cache_format_test_preexisting_{self.team.pk}"
+ response = {"is_cached": False, "results": [{"data": [1]}], "cache_key": "k"}
+ get_query_cache().set(cache_key, OrjsonJsonSerializer({}).dumps(response), 60)
+
+ split = fetch_split_cached_response_by_key(cache_key, self.team.pk)
+ assert split is not None
+ assert split.results_bytes is None
+ assert fetch_cached_response_by_key(cache_key, self.team.pk) == response
diff --git a/posthog/hogql_queries/query_cache.py b/posthog/hogql_queries/query_cache.py
index cab777565df2..41a0a3e2f2aa 100644
--- a/posthog/hogql_queries/query_cache.py
+++ b/posthog/hogql_queries/query_cache.py
@@ -1,7 +1,10 @@
from collections.abc import Generator
from contextlib import contextmanager
from datetime import datetime
-from typing import NamedTuple, Optional
+from typing import TYPE_CHECKING, NamedTuple, Optional
+
+if TYPE_CHECKING:
+ from posthog.caching.fetch_from_cache import SplitCachedResponse
from django.conf import settings
@@ -176,7 +179,16 @@ class DjangoCacheQueryCacheManager(QueryCacheManagerBase):
"""
def set_cache_data(self, *, response: dict, target_age: Optional[datetime]) -> None:
- fresh_response_serialized = OrjsonJsonSerializer({}).dumps(response)
+ from posthog.caching.fetch_from_cache import encode_split_cached_response
+
+ if isinstance(response.get("results"), list):
+ # Split format keeps `results` as its own JSON segment so cache hits can skip
+ # parsing it — see fetch_from_cache.SplitCachedResponse. Pods that predate this
+ # format treat split entries as cache misses and recompute, so entries written
+ # during a rolling deploy may be recomputed once — accepted, deploys are quick.
+ fresh_response_serialized = encode_split_cached_response(response)
+ else:
+ fresh_response_serialized = OrjsonJsonSerializer({}).dumps(response)
data_size = len(fresh_response_serialized)
# Set cache with per-team size limit enforcement
@@ -202,3 +214,8 @@ class DjangoCacheQueryCacheManager(QueryCacheManagerBase):
from posthog.caching.fetch_from_cache import fetch_cached_response_by_key
return fetch_cached_response_by_key(self.cache_key, self.team_id)
+
+ def get_cache_data_split(self) -> Optional["SplitCachedResponse"]:
+ from posthog.caching.fetch_from_cache import fetch_split_cached_response_by_key
+
+ return fetch_split_cached_response_by_key(self.cache_key, self.team_id)
diff --git a/posthog/hogql_queries/query_cache_base.py b/posthog/hogql_queries/query_cache_base.py
index a7adac0e6927..fc53c55a69d6 100644
--- a/posthog/hogql_queries/query_cache_base.py
+++ b/posthog/hogql_queries/query_cache_base.py
@@ -3,6 +3,7 @@ from datetime import UTC, datetime
from typing import Optional
from posthog import redis
+from posthog.caching.fetch_from_cache import SplitCachedResponse
class QueryCacheManagerBase(ABC):
@@ -105,3 +106,10 @@ class QueryCacheManagerBase(ABC):
def get_cache_data(self) -> Optional[dict]:
"""Retrieve query results from cache."""
pass
+
+ def get_cache_data_split(self) -> Optional[SplitCachedResponse]:
+ """Retrieve cached results, keeping the results segment as raw bytes when the backend supports it."""
+ data = self.get_cache_data()
+ if data is None:
+ return None
+ return SplitCachedResponse(header=data, results_bytes=None)
diff --git a/posthog/hogql_queries/query_runner.py b/posthog/hogql_queries/query_runner.py
index 8e0ca04a21e0..c8eecb71fc33 100644
--- a/posthog/hogql_queries/query_runner.py
+++ b/posthog/hogql_queries/query_runner.py
@@ -7,6 +7,7 @@ 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
+import orjson
import posthoganalytics
from prometheus_client import Counter, Histogram
from pydantic import BaseModel, ConfigDict
@@ -228,11 +229,6 @@ def response_results_contain_models(response_class: type[BaseModel]) -> bool:
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:
@@ -1344,6 +1340,11 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
# query service means programmatic access and /query endpoint
is_query_service: bool = False
workload: Workload
+ # Opt-in (set by process_query_model): on a cache hit, keep the results segment of the
+ # cached response as raw JSON bytes in raw_cached_results_bytes instead of parsing it,
+ # leaving a `results=[]` placeholder on the returned model.
+ serve_raw_cached_results: bool = False
+ raw_cached_results_bytes: Optional[bytes] = None
def __init__(
self,
@@ -1417,6 +1418,12 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
isinstance(data, dict) and "is_cached" in data
)
+ def _query_has_series_custom_names(self) -> bool:
+ series = getattr(self.query, "series", None)
+ if not series:
+ return False
+ return any(getattr(s, "custom_name", None) is not None for s in series)
+
@property
def _limit_context_aliased_for_cache(self) -> LimitContext:
# For caching purposes, QUERY_ASYNC is equivalent to QUERY (max query duration should be the only difference)
@@ -1490,14 +1497,45 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
) -> Optional[CR | CacheMissResponse]:
CachedResponse: type[CR] = self.cached_response_type
cached_response: CR | CacheMissResponse
- cached_response_candidate = cache_manager.get_cache_data()
+ cached_response_candidate: Optional[dict]
+ self.raw_cached_results_bytes = None
+ raw_results: Optional[bytes] = None
+ if self.serve_raw_cached_results:
+ # Serving results as raw bytes skips parsing (and later re-serializing) the results
+ # payload. Only safe when the caller opted in AND validation of the parsed results
+ # wouldn't add protection (the response class types them as plain data — for
+ # model-typed results, e.g. retention, validating a `[]` placeholder would bypass
+ # the schema-drift check that triggers recomputation) AND neither the query nor
+ # the cached results carry custom series names — otherwise
+ # apply_series_custom_names below must be able to patch the parsed results.
+ split_candidate = cache_manager.get_cache_data_split()
+ if split_candidate is None:
+ cached_response_candidate = None
+ else:
+ cached_response_candidate = split_candidate.header
+ if split_candidate.results_bytes is not None:
+ if (
+ response_results_contain_models(CachedResponse)
+ or split_candidate.results_have_custom_names
+ or self._query_has_series_custom_names()
+ ):
+ cached_response_candidate["results"] = orjson.loads(split_candidate.results_bytes)
+ else:
+ raw_results = split_candidate.results_bytes
+ else:
+ cached_response_candidate = cache_manager.get_cache_data()
if self.is_cached_response(cached_response_candidate):
+ assert cached_response_candidate is not None
+ if raw_results is not None:
+ cached_response_candidate["results"] = []
cached_response_candidate["is_cached"] = True
# When rolling out schema changes, cached responses may not match the new schema.
# Trigger recomputation in this case.
try:
cached_response = CachedResponse(**cached_response_candidate)
+ if raw_results is not None:
+ self.raw_cached_results_bytes = raw_results
except Exception as e:
capture_exception(Exception(f"Error parsing cached response: {e}"))
cached_response = CacheMissResponse(cache_key=cache_manager.cache_key)
@@ -1570,7 +1608,9 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
)
return cached_response
- # Nothing useful out of cache, nor async query status
+ # Nothing useful out of cache, nor async query status. A recomputation follows, so the
+ # cached raw results (if any) must not leak onto the fresh response.
+ self.raw_cached_results_bytes = None
return None
def _call_with_rate_limits(self, *, dashboard_id: Optional[int]) -> tuple[R, float]:
diff --git a/products/dashboards/backend/api/dashboard.py b/products/dashboards/backend/api/dashboard.py
index 2b357cd02f9e..c733ecc47511 100644
--- a/products/dashboards/backend/api/dashboard.py
+++ b/products/dashboards/backend/api/dashboard.py
@@ -2340,9 +2340,11 @@ class DashboardsViewSet(
metadata_serializer = DashboardMetadataSerializer(dashboard, context=self.get_serializer_context())
metadata_data = metadata_serializer.data
- # Create serializer context for tiles
+ # Create serializer context for tiles. Tiles are rendered with SafeJSONRenderer below,
+ # so raw cached results (orjson.Fragment) are safe even though the negotiated renderer
+ # is the SSE one.
context = self.get_serializer_context()
- context.update({"dashboard": dashboard})
+ context.update({"dashboard": dashboard, "raw_results_supported": True})
# Get tiles with proper prefetch
tiles = DashboardTile.dashboard_queryset(dashboard.tiles.all()).prefetch_related(
@@ -2769,6 +2771,9 @@ class DashboardsViewSet(
context = self.get_serializer_context()
context["dashboard"] = dashboard
+ # _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
tiles = DashboardTile.dashboard_queryset(dashboard.tiles.all()).prefetch_related(
Prefetch(
diff --git a/products/product_analytics/backend/api/insight.py b/products/product_analytics/backend/api/insight.py
index 696492988acb..c40cc3118b78 100644
--- a/products/product_analytics/backend/api/insight.py
+++ b/products/product_analytics/backend/api/insight.py
@@ -117,6 +117,7 @@ from posthog.rbac.user_access_control import (
UserAccessControlSerializerMixin,
access_level_satisfied_for_resource,
)
+from posthog.renderers import SafeJSONRenderer
from posthog.resource_limits import LimitKey, check_count_limit
from posthog.schema_migrations.upgrade import upgrade
from posthog.schema_migrations.upgrade_manager import upgrade_query
@@ -1168,6 +1169,18 @@ class InsightSerializer(InsightBasicSerializer):
request_user_access_control = (
getattr(view, "user_access_control", None) if isinstance(request_user, User) else None
)
+ # Raw cached results (orjson.Fragment) are only valid when the response is
+ # rendered by orjson: SafeJSONRenderer directly, or a caller that declares it
+ # renders tiles with SafeJSONRenderer itself (the SSE tile stream sets
+ # raw_results_supported — SSE content negotiation alone doesn't guarantee an
+ # orjson boundary). Pretty-printed output (?indent=) would not indent inside a
+ # fragment, so keep the parsed path there.
+ accepted_renderer = getattr(self.context["request"], "accepted_renderer", None)
+ allow_raw_results = (
+ (isinstance(accepted_renderer, SafeJSONRenderer) or bool(self.context.get("raw_results_supported")))
+ and not self.context["request"].query_params.get("indent")
+ and not self.context.get("require_parsed_results")
+ )
with tags_context(product=ProductKey.PRODUCT_ANALYTICS, feature=Feature.INSIGHT, **shared_tags):
return calculate_for_query_based_insight(
insight,
@@ -1181,6 +1194,7 @@ class InsightSerializer(InsightBasicSerializer):
tile_filters_override=tile_filters_override,
cache_age_seconds=shared_cache_age_seconds,
analytics_props=get_request_analytics_properties(self.context["request"]),
+ allow_raw_results=allow_raw_results,
)
except (ExposedHogQLError, ExposedCHQueryError, HogVMException) as e:
raise ValidationError(str(e), getattr(e, "code_name", None))
diff --git a/products/product_analytics/backend/api/test/test_insight.py b/products/product_analytics/backend/api/test/test_insight.py
index 1a232b6f5a05..77c28f123e5b 100644
--- a/products/product_analytics/backend/api/test/test_insight.py
+++ b/products/product_analytics/backend/api/test/test_insight.py
@@ -527,6 +527,7 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
tile_filters_override={},
cache_age_seconds=None,
analytics_props=ANY,
+ allow_raw_results=False,
)
with patch(
@@ -548,6 +549,7 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
tile_filters_override={},
cache_age_seconds=int(SHARED_FORCE_BLOCKING_STALENESS_WINDOW.total_seconds()),
analytics_props=ANY,
+ allow_raw_results=False,
)
def test_get_shared_insight_with_force_refresh_returns_200(self) -> None:
@@ -609,6 +611,7 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
tile_filters_override={},
cache_age_seconds=int(SHARED_FORCE_BLOCKING_STALENESS_WINDOW.total_seconds()),
analytics_props=ANY,
+ allow_raw_results=False,
)
def test_get_insight_by_short_id(self) -> None: