: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
feat(query-cache): store large cached results in S3 behind a Redis pointer (#82910)
Sandy Spicerae1e6cd4eecd
diff --git a/conftest.py b/conftest.pyindex 8978779c7edd..914fe84ff58a 100644--- a/conftest.py+++ b/conftest.py@@ -287,6 +287,7 @@ def _query_cache_raw_redis_uses_fakeredis(monkeypatch):"""In tests the query_cache alias is backed by LocMem, which has no Redis connectionto hand out, so raw-client lookups against it get the shared fakeredis instead."""from posthog import redis # noqa: PLC0415- from posthog.query_cache import size_tracker # noqa: PLC0415+ from posthog.query_cache import storage # noqa: PLC0415- monkeypatch.setattr(size_tracker, "get_redis_connection", lambda alias: redis.get_client())+ monkeypatch.setattr(storage, "query_cache_raw_client", lambda: redis.get_client())+ monkeypatch.setattr(storage, "query_cache_read_client", lambda: redis.get_client())diff --git a/docs/internal/workflows/s3-query-cache-setup.md b/docs/internal/workflows/s3-query-cache-setup.mdindex fc00aa8da864..9dda08e39e8a 100644--- a/docs/internal/workflows/s3-query-cache-setup.md+++ b/docs/internal/workflows/s3-query-cache-setup.md@@ -1,82 +1,39 @@-# S3 Query Cache TTL Implementation+# S3 query cache setup-## How It Works+The query cache zstd-compresses every entry it stores in Redis.+Entries whose compressed form is at least `QUERY_CACHE_S3_MIN_COMPRESSED_BYTES` (default 128KB) can be stored as S3 objects instead of inline Redis blobs; the same compressed bytes serve as the routing decision, the inline value, and the upload body.+Redis then holds a small pointer record under the same cache key.+The threshold applies to compressed bytes because that is what an entry actually costs in Redis.+See `posthog/query_cache/storage.py`.-1 **Object Tagging**: Each S3 object gets tags:+## Semantics-```text-ttl_days=1 # Calculated TTL in days-team_id=123 # Team identifier-```+- **Expiry is governed by the Redis pointer's TTL** (`CACHED_RESULTS_TTL`), not by S3. Once the pointer expires or is evicted, the entry is gone regardless of whether the S3 object still exists.+- **The S3 lifecycle rule is garbage collection only.** It deletes blobs once nothing can reference them (expired or evicted pointers, shadow-mode uploads, rolled-back teams).+- Rollout is controlled by the `query-cache-s3-writes` multivariate feature flag on the organization group. It gates writes only; reads never evaluate the flag, they follow whatever the stored record says.+ - Disabled: every result is stored inline in Redis, as always.+ - `shadow`: write the cache entry to both S3 and Redis, testing the write path; nothing reads the S3 copy.+ - `on`: write the pointer to Redis and the entry to S3; reads fetch the blob from S3.-2 **Automatic Deletion**: S3 lifecycle rules delete objects matching tag criteria+## Object layout and tagging-## Required S3 Lifecycle Rules+Objects are written to `s3://{QUERY_CACHE_S3_BUCKET}/{OBJECT_STORAGE_S3_QUERY_CACHE_FOLDER}/{team_id}/{cache_key}/{upload_id}` with attribution tags (`cache_type=query_data`, `team_id=<id>`). Tags carry no expiry meaning. The per-upload suffix keeps overlapping recomputes of one query from overwriting each other's blob. Superseded objects sit unreferenced until the lifecycle rule collects them; eager deletion was considered and dropped, since 7-day retention of churn costs little and the machinery does not.-**Critical**: You must create lifecycle rules for every `ttl_days` value your app generates.+## Required S3 lifecycle rule-### AWS CLI Configuration+One rule: expire objects after `CACHED_RESULTS_TTL_DAYS` (7) days.+The cloud buckets (`posthog-query-cache-<region>-<env>`) are dedicated to this cache, so their rule is bucket-wide; it is managed in posthog-cloud-infra, `terraform/modules/s3/main.tf` (`enable_query_cache_lifecycle`).-```bash-# Create rules for common TTL values: 1, 2, 7, 14, 30 days-cat > lifecycle-config.json << EOF-{- "Rules": [- {- "ID": "query-cache-ttl-1-day",- "Status": "Enabled",- "Filter": {- "And": {- "Tags": [- {"Key": "ttl_days", "Value": "1"},- ]- }- },- "Expiration": {"Days": 1}- },- {- "ID": "query-cache-ttl-7-days",- "Status": "Enabled",- "Filter": {- "And": {- "Tags": [- {"Key": "ttl_days", "Value": "7"},- ]- }- },- "Expiration": {"Days": 7}- }- ]-}-EOF+**On a shared bucket, scope the rule to the `OBJECT_STORAGE_S3_QUERY_CACHE_FOLDER` prefix** (`query_cache/` by default). `QUERY_CACHE_S3_BUCKET` falls back to the shared `OBJECT_STORAGE_BUCKET` when unset, and a bucket-wide expiry rule there would also delete exports, media uploads, and error-tracking source maps.-aws s3api put-bucket-lifecycle-configuration \- --bucket your-bucket-name \- --lifecycle-configuration file://lifecycle-config.json-```+**If `CACHED_RESULTS_TTL_DAYS` is ever raised, raise the bucket rule first**, otherwise S3 deletes blobs while their Redis pointers still live and large cache entries silently expire early. Lowering the setting is safe: blobs then just outlive their pointers by a few days before GC.-### Terraform Configuration+## Settings-```hcl-resource "aws_s3_bucket_lifecycle_configuration" "query_cache" {- bucket = aws_s3_bucket.query_cache.id+| Setting | Default | Meaning |+| -------------------------------------- | ----------------------- | ---------------------------------------------------------------------- |+| `QUERY_CACHE_S3_BUCKET` | `OBJECT_STORAGE_BUCKET` | Bucket for cache blobs (`posthog-query-cache-<region>-<env>` in cloud) |+| `OBJECT_STORAGE_S3_QUERY_CACHE_FOLDER` | `query_cache` | Key prefix inside the bucket |+| `QUERY_CACHE_S3_MIN_COMPRESSED_BYTES` | `131072` | Minimum zstd-compressed size for S3 routing |- # Repeat this rule block for each TTL value (1, 2, 7, 14, 30 days)- rule {- id = "query-cache-ttl-1-day"- status = "Enabled"- filter {- and {- tags = {- ttl_days = "1"- }- }- }- expiration {- days = 1- }- }-}-```--**Warning**: Objects with `ttl_days` values lacking lifecycle rules will never expire.+These are plain environment variables read at process start. Cloud runs the defaults; overriding one in production means plumbing it through the deployment charts first, the same as any other app setting.diff --git a/posthog/caching/test/test_redis_cluster_keys.py b/posthog/caching/test/test_redis_cluster_keys.pyindex 3c9d20d7fed2..74aecc206d57 100644--- a/posthog/caching/test/test_redis_cluster_keys.py+++ b/posthog/caching/test/test_redis_cluster_keys.py@@ -16,11 +16,10 @@ class TestRedisClusterKeySlots(BaseTest):])def test_hash_tagged_keys_share_same_slot(self, _name: str, team_id: int):- mock_cache = MagicMock()mock_redis = MagicMock()mock_redis.register_script = MagicMock(return_value=MagicMock())- tracker = TeamCacheSizeTracker(team_id, cache_backend=mock_cache, redis_client=mock_redis)+ tracker = TeamCacheSizeTracker(team_id, redis_client=mock_redis)slots = {key_slot(tracker.entries_key.encode()),diff --git a/posthog/ph_client.py b/posthog/ph_client.pyindex 5b2745a65b10..83e4fc97cea4 100644--- a/posthog/ph_client.py+++ b/posthog/ph_client.py@@ -4,7 +4,7 @@ import threadingfrom collections.abc import Mappingfrom contextlib import contextmanagerfrom numbers import Number-from typing import Any+from typing import Any, castfrom uuid import UUIDfrom django.conf import settings@@ -51,6 +51,35 @@ def feature_enabled_or_false()+def get_feature_flag_or_none(+ key: str,+ distinct_id: str,+ groups: dict[str, str] | None = None,+ group_properties: dict[str, dict[str, Any]] | None = None,+ only_evaluate_locally: bool = False,+ send_feature_flag_events: bool = True,+) -> str | bool | None:+ """Variant-returning sibling of feature_enabled_or_false that never raises, so callers on+ paths that must not fail (cache writes, background tasks) can treat any failure as flag-off."""+ try:+ # The library annotates the return as Optional[FeatureFlag], but at runtime a plain+ # variant string or bool comes back, so cast like ee/hogai/utils/feature_flags.py does.+ return cast(+ "str | bool | None",+ posthoganalytics.get_feature_flag(+ key,+ distinct_id,+ groups=groups,+ group_properties=group_properties,+ only_evaluate_locally=only_evaluate_locally,+ send_feature_flag_events=send_feature_flag_events,+ ),+ )+ except Exception:+ logger.warning("get_feature_flag_failed", flag_key=key, exc_info=True)+ return None++def get_regional_ph_client(**kwargs: Any):if not is_cloud():returndiff --git a/posthog/query_cache/__init__.py b/posthog/query_cache/__init__.pyindex 5120cae138bd..15a10cb11628 100644--- a/posthog/query_cache/__init__.py+++ b/posthog/query_cache/__init__.py@@ -2,11 +2,13 @@ from posthog.query_cache.cache import CacheLookup, QueryCachefrom posthog.query_cache.failures import FailureKind, QueryFailureRecordfrom posthog.query_cache.freshness_index import clean_up_stale_insights, get_stale_insightsfrom posthog.query_cache.metrics import count_query_cache_hit+from posthog.query_cache.results import EntryFreshnessfrom posthog.query_cache.serialization import CachedEntry__all__ = ["CachedEntry","CacheLookup",+ "EntryFreshness","FailureKind","QueryCache","QueryFailureRecord",diff --git a/posthog/query_cache/cache.py b/posthog/query_cache/cache.pyindex 0c6b8c8c5e9a..b79733a48925 100644--- a/posthog/query_cache/cache.py+++ b/posthog/query_cache/cache.py@@ -10,13 +10,21 @@ from posthog.cache_utils import OrjsonJsonSerializerfrom posthog.query_cache.failures import Budget, FailureKind, QueryFailureCache, QueryFailureRecordfrom posthog.query_cache.freshness_index import remove_last_refresh, update_target_agefrom posthog.query_cache.metrics import count_cache_write_data-from posthog.query_cache.results import fetch_entry+from posthog.query_cache.results import EntryFreshness, fetch_entry, fetch_entry_freshnessfrom posthog.query_cache.serialization import CachedEntry, encode_split_cached_responsefrom posthog.query_cache.size_tracker import TeamCacheSizeTracker+from posthog.query_cache.storage import encode_inline_value, schedule_upload_for_pointerlogger = structlog.get_logger(__name__)+def _last_refresh_iso(response: dict) -> Optional[str]:+ value = response.get("last_refresh")+ if isinstance(value, datetime):+ return value.isoformat()+ return value if isinstance(value, str) else None++@dataclass(frozen=True)class CacheLookup:"""Everything the cache knows about a cache key: the stored entry and any open failure record."""@@ -49,6 +57,10 @@ class QueryCache:failure = QueryFailureCache(self.cache_key).get_open() if include_failure else Nonereturn CacheLookup(entry=fetch_entry(self.cache_key, self.team_id), failure=failure)+ def freshness(self) -> Optional[EntryFreshness]:+ """Existence and last_refresh of the entry from Redis alone, without resolving S3 blobs."""+ return fetch_entry_freshness(self.cache_key, self.team_id)+def open_failure(self) -> Optional[QueryFailureRecord]:"""The open breaker record alone, for paths that skip the result cache entirely."""return QueryFailureCache(self.cache_key).get_open()@@ -62,19 +74,36 @@ class QueryCache:def store_result(self, *, response: dict, target_age: Optional[datetime]) -> None:if isinstance(response.get("results"), list):# Split format keeps `results` as its own JSON segment so cache hits can skip- # parsing it — see CachedEntry. 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.+ # parsing it (see CachedEntry). Pods that predate the format treat split entries+ # as cache misses and recompute once during a rolling deploy. 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. Caching is an optimization: the query- # has already run, so a bookkeeping failure here must not fail the response.+ # The tracker budgets the bytes actually stored in Redis (compressed blob or pointer);+ # the write metrics below keep counting the uncompressed payload. Caching is an+ # optimization: the query has already run, so a failure in this block must not fail+ # the response.try:+ storage_bytes = encode_inline_value(fresh_response_serialized)tracker = TeamCacheSizeTracker(self.team_id)- tracker.set(self.cache_key, fresh_response_serialized, data_size, settings.CACHED_RESULTS_TTL)+ tracker.set(self.cache_key, storage_bytes, settings.CACHED_RESULTS_TTL)+ # The S3 upload runs on a background thread after the inline write: the fresh+ # result is already cached, so the requester never waits on S3, and a failed or+ # skipped upload leaves the valid inline entry in place. The swap only lands while+ # the entry still holds this store's bytes, so an upload that finishes after a+ # newer store wrote the key cannot put its older result back.+ schedule_upload_for_pointer(+ team_id=self.team_id,+ cache_key=self.cache_key,+ inline_value=storage_bytes,+ last_refresh=_last_refresh_iso(response),+ swap=lambda pointer: tracker.replace_value(+ self.cache_key, pointer, settings.CACHED_RESULTS_TTL, expected=storage_bytes+ ),+ )except Exception:logger.exception("query_cache_store_result_failed", team_id=self.team_id, cache_key=self.cache_key)returndiff --git a/posthog/query_cache/results.py b/posthog/query_cache/results.pyindex 6d0341c03989..bb04853bcfac 100644--- a/posthog/query_cache/results.py+++ b/posthog/query_cache/results.py@@ -1,32 +1,76 @@from typing import Optional-from django.core.cache import caches-import structlog-from posthog.caching.redis_cluster_connection_factory import QUERY_CACHE_ALIAS+from posthog.dataclasses import frozenfrom posthog.query_cache.serialization import CachedEntry, split_cached_response_bytes+from posthog.query_cache.storage import (+ decode_pointer,+ decode_stored_value,+ delete_entry,+ is_s3_pointer,+ load_entry_value,+)logger = structlog.get_logger(__name__)+@frozen+class EntryFreshness:+ """What a freshness probe learns from Redis alone: the entry exists, and when it was+ last refreshed (None when the stored response carries no last_refresh)."""++ last_refresh: Optional[str]++def fetch_entry(cache_key: str, team_id: int) -> Optional[CachedEntry]:- query_cache = caches[QUERY_CACHE_ALIAS]try:- cached_response_bytes = query_cache.get(cache_key)+ stored_value = load_entry_value(cache_key)except Exception:logger.warning("query_cache_read_error", cache_key=cache_key, team_id=team_id, exc_info=True)try:- query_cache.delete(cache_key)+ delete_entry(cache_key)except Exception:passreturn None- if not cached_response_bytes:+ if not stored_value:+ return None++ payload = decode_stored_value(stored_value, team_id=team_id, cache_key=cache_key)+ if payload is None:return Nonetry:- return split_cached_response_bytes(cached_response_bytes, cache_key=cache_key, team_id=team_id)+ return split_cached_response_bytes(payload, cache_key=cache_key, team_id=team_id)except Exception:logger.exception("query_cache_deserialize_error", cache_key=cache_key, team_id=team_id, exc_info=True)return None+++def fetch_entry_freshness(cache_key: str, team_id: int) -> Optional[EntryFreshness]:+ """Existence and last_refresh of an entry without resolving S3 pointers. Never raises.++ Pointer records carry last_refresh, so probing an S3-backed entry costs one Redis read;+ resolving the blob here would put an S3 round trip into every warming candidate check.+ The trade: a pointer whose blob has died still reads as a live entry until the recompute+ that follows a real read's miss overwrites it.+ """+ try:+ stored_value = load_entry_value(cache_key)+ if not stored_value:+ return None+ if is_s3_pointer(stored_value):+ pointer = decode_pointer(stored_value)+ if pointer is None:+ return None+ return EntryFreshness(last_refresh=pointer.last_refresh)+ payload = decode_stored_value(stored_value, team_id=team_id, cache_key=cache_key)+ if payload is None:+ return None+ entry = split_cached_response_bytes(payload, cache_key=cache_key, team_id=team_id)+ last_refresh = entry.header.get("last_refresh")+ return EntryFreshness(last_refresh=last_refresh if isinstance(last_refresh, str) else None)+ except Exception:+ logger.warning("query_cache_freshness_probe_failed", cache_key=cache_key, team_id=team_id, exc_info=True)+ return Nonediff --git a/posthog/query_cache/size_tracker.py b/posthog/query_cache/size_tracker.pyindex 3ab166d402aa..7b8c65492a17 100644--- a/posthog/query_cache/size_tracker.py+++ b/posthog/query_cache/size_tracker.py@@ -3,16 +3,14 @@ from datetime import timedeltafrom typing import Optionalfrom django.conf import settings-from django.core.cache import BaseCache, cachesfrom django.db import DatabaseErrorimport structlog-from django_redis import get_redis_connectionfrom prometheus_client import Counter, Histogramfrom redis import Redis, RedisClusterfrom posthog.cache_utils import cache_for-from posthog.caching.redis_cluster_connection_factory import QUERY_CACHE_ALIAS+from posthog.query_cache import storagelogger = structlog.get_logger(__name__)@@ -96,6 +94,19 @@ redis.call('EXPIRE', total_key, tracking_ttl)return redis.call('GET', total_key)"""+# Lua script for the pointer swap: replace the entry only while it still holds the exact bytes+# the caller wrote, so a swap that lost a race to a newer write skips instead of clobbering it.+# Compares the full expected value rather than a redis.sha1hex digest because fakeredis's Lua+# runtime, which the tests run on, does not implement sha1hex.+REPLACE_IF_UNCHANGED_SCRIPT = """+local current = redis.call('GET', KEYS[1])+if current ~= ARGV[1] then+ return 0+end+redis.call('SET', KEYS[1], ARGV[2], 'EX', tonumber(ARGV[3]))+return 1+"""+# Lua script for atomic and idempotent tracking removal# Only decrements if key exists in hash, preventing double-decrement racesREMOVE_TRACKING_SCRIPT = """@@ -145,13 +156,11 @@ class TeamCacheSizeTracker:def __init__(self,team_id: int,- cache_backend: BaseCache | None = None,redis_client: Redis | RedisCluster | None = None,):self.team_id = team_id- self._cache = cache_backend if cache_backend is not None else caches[QUERY_CACHE_ALIAS]self.redis_client: Redis | RedisCluster = (- redis_client if redis_client is not None else get_redis_connection(QUERY_CACHE_ALIAS)+ redis_client if redis_client is not None else storage.query_cache_raw_client())self.entries_key = f"posthog:cache_sizes:{{{team_id}}}"self.sizes_key = f"posthog:cache_entry_sizes:{{{team_id}}}"@@ -159,9 +168,10 @@ class TeamCacheSizeTracker:# redis-py's stubs omit register_script on RedisCluster; the runtime supports it.self._track_write_script = self.redis_client.register_script(TRACK_CACHE_WRITE_SCRIPT) # type: ignore[union-attr]+ self._replace_if_unchanged_script = self.redis_client.register_script(REPLACE_IF_UNCHANGED_SCRIPT) # type: ignore[union-attr]self._remove_tracking_script = self.redis_client.register_script(REMOVE_TRACKING_SCRIPT) # type: ignore[union-attr]- def set(self, cache_key: str, data: bytes, data_size: int, ttl: int) -> list[str]:+ def set(self, cache_key: str, data: bytes, ttl: int) -> list[str]:"""Set cache data with size limit enforcement.Returns list of evicted keys.@@ -170,6 +180,7 @@ class TeamCacheSizeTracker:temporarily exceed the limit. This is acceptable because the next write willtrigger eviction and bring the size back under limit."""+ data_size = len(data)limit = get_team_cache_limit(self.team_id)evicted: list[str] = []size_before = self.get_total_size()@@ -180,7 +191,7 @@ class TeamCacheSizeTracker:if size_before + data_size > limit:evicted = self.evict_until_under_limit(limit, data_size)- self._cache.set(cache_key, data, ttl)+ self.redis_client.set(storage.entry_redis_key(cache_key), data, ex=ttl)self.track_cache_write(cache_key, data_size)total_size = self.get_total_size()@@ -201,6 +212,22 @@ class TeamCacheSizeTracker:return evicted+ def replace_value(self, cache_key: str, data: bytes, ttl: int, *, expected: bytes) -> bool:+ """Swap an entry's stored bytes for `data` only while it still holds `expected`,+ updating size accounting on success; returns whether the swap landed. Skips set()'s+ limit check and logging: for the pointer swap, where the new value only ever shrinks+ usage, and a store that landed mid-upload must not be replaced by an older upload's+ pointer. Also runs on upload worker threads, so it must stay free of Django ORM calls.+ """+ swapped = self._replace_if_unchanged_script(+ keys=[storage.entry_redis_key(cache_key)],+ args=[expected, data, ttl],+ )+ if not swapped:+ return False+ self.track_cache_write(cache_key, len(data))+ return True+def track_cache_write(self, cache_key: str, size_bytes: int) -> None:"""Track a cache write with its size. Atomic via Lua script."""tracking_ttl = settings.CACHED_RESULTS_TTL + 86400@@ -231,13 +258,13 @@ class TeamCacheSizeTracker:cache_key = cache_key.decode()# Check if key still exists in cache (lazy cleanup for TTL-expired keys)- if cache_key not in self._cache:+ if not self.redis_client.exists(storage.entry_redis_key(cache_key)):# Already expired via TTL, just clean up trackingremoved_size = self._remove_tracking(cache_key)current_size -= removed_sizecontinue- self._cache.delete(cache_key)+ self.redis_client.delete(storage.entry_redis_key(cache_key))removed_size = self._remove_tracking(cache_key)current_size -= removed_sizediff --git a/posthog/query_cache/storage.py b/posthog/query_cache/storage.pynew file mode 100644index 000000000000..fa50358d29eb--- /dev/null+++ b/posthog/query_cache/storage.py@@ -0,0 +1,445 @@+"""The bytes stored in Redis for each query cache entry.++encode_inline_value picks the bytes stored inline for a serialized result;+schedule_upload_for_pointer uploads large frames to S3 in the background and swaps in the+pointer record that replaces them in Redis; decode_stored_value turns stored bytes back into+the result. Everything else serves those.++A Redis value is a bare byte string shared with older pods during rolling deploys, so each+storage format announces itself in its first bytes:++- S3_POINTER_MAGIC: a small pointer record naming the S3 bucket and key that hold the+ zstd-compressed result, plus the result's last_refresh so freshness probes stay a single+ Redis read. Written for large results when the team's rollout flag is on.+- ZSTD_FRAME_MAGIC: the zstd-compressed result, stored inline. The default format for+ results over COMPRESSION_FLOOR_BYTES.+- PICKLE_PROTO_MARKER: a result pickled by django_redis before this module owned the value+ bytes, sometimes inside a zstd frame. Read but never written; these entries disappear as+ CACHED_RESULTS_TTL retires them, and the legacy path at the bottom goes with them.+- No marker: the result as-is, for values too small to be worth a zstd frame.++Sniffing is unambiguous because results start with JSON or QUERY_CACHE_SPLIT_MAGIC, never+with a marker. A pod whose code predates a format cannot read it: it logs a read error,+deletes the entry, and recomputes. Its rewrite is readable by every version, so a+mixed-version deploy costs at most one extra recompute per entry.+"""++import io+import time+import pickle+import threading+from collections.abc import Callable+from concurrent.futures import ThreadPoolExecutor+from datetime import timedelta+from typing import Literal, NoReturn, Optional, cast+from uuid import uuid4++from django.conf import settings+from django.core.cache import caches++import zstd+import structlog+from django_redis import get_redis_connection+from prometheus_client import Counter, Histogram+from redis import Redis, RedisCluster++from posthog.cache_utils import OrjsonJsonSerializer, cache_for+from posthog.caching.redis_cluster_connection_factory import QUERY_CACHE_ALIAS+from posthog.dataclasses import frozen+from posthog.ph_client import get_feature_flag_or_none+from posthog.storage.object_storage import object_storage_client++logger = structlog.get_logger(__name__)++# Format markers. S3_POINTER_MAGIC is this module's own; the other two are fixed by the+# zstd frame format and pickle protocol 2+.+S3_POINTER_MAGIC = b"PHQCS3\x00"+ZSTD_FRAME_MAGIC = b"\x28\xb5\x2f\xfd"+PICKLE_PROTO_MARKER = b"\x80"++# Mirror the django_redis ZstdCompressor: the same floor (below it a zstd frame costs more+# than it saves) and the same settings (preset 0 is zstd's default level, single thread),+# so inline values and S3 blobs compress identically wherever they're produced.+COMPRESSION_FLOOR_BYTES = 512+ZSTD_PRESET = 0+ZSTD_THREADS = 1++QueryCacheS3Mode = Literal["off", "shadow", "on"]++# Multivariate flag on the organization group, evaluated on writes only; the read path never+# touches flags. "shadow" writes the entry to both S3 and Redis to prove out the write path+# while reads keep using the Redis copy; "on" stores the pointer in Redis and the entry in S3.+QUERY_CACHE_S3_FLAG = "query-cache-s3-writes"++# On the default registry, not get_cache_metrics_context: Celery and Temporal workers already+# serve scrape endpoints, and the push gateway replaces the whole job on every push, which+# would collapse these per-call counters and histograms to the latest observation.+S3_WRITE_COUNTER = Counter(+ name="posthog_query_cache_s3_write_total",+ documentation="Query cache blob uploads to S3, by write mode and outcome.",+ labelnames=["mode", "outcome"],+)++S3_READ_COUNTER = Counter(+ name="posthog_query_cache_s3_read_total",+ documentation="Query cache blob reads from S3 pointer entries, by outcome.",+ labelnames=["outcome"],+)++# Buckets start at 50ms because only large blobs make the trip, and reach tens of seconds for+# multi-MB transfers. Failures return fast (1s connect and 5s idle-socket timeouts, no+# retries), so durations carry outcome labels; folded into one series an S3 outage would make+# latency look better, not worse.+_S3_DURATION_BUCKETS = [0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0, 30.0, float("inf")]++S3_WRITE_DURATION = Histogram(+ name="posthog_query_cache_s3_write_duration_seconds",+ documentation="Time spent uploading a query cache blob to S3, by write mode and outcome.",+ labelnames=["mode", "outcome"],+ buckets=_S3_DURATION_BUCKETS,+)++S3_READ_DURATION = Histogram(+ name="posthog_query_cache_s3_read_duration_seconds",+ documentation="Time spent fetching a query cache blob from S3, by outcome.",+ labelnames=["outcome"],+ buckets=_S3_DURATION_BUCKETS,+)++S3_WRITE_BYTES_COUNTER = Counter(+ name="posthog_query_cache_s3_write_bytes_total",+ documentation="Compressed bytes uploaded to S3, by write mode; the growth signal for the bucket.",+ labelnames=["mode"],+)++LEGACY_VALUE_READ_COUNTER = Counter(+ name="posthog_query_cache_legacy_value_read_total",+ documentation="Successful reads of values written through django_redis before this module "+ "owned the value bytes; the legacy unpickling path is deletable once this stays at zero.",+)+++def _record_s3_write(mode: QueryCacheS3Mode, outcome: str, seconds: Optional[float] = None) -> None:+ S3_WRITE_COUNTER.labels(mode=mode, outcome=outcome).inc()+ if seconds is not None:+ S3_WRITE_DURATION.labels(mode=mode, outcome=outcome).observe(seconds)+++def _record_s3_read(outcome: str, seconds: Optional[float] = None) -> None:+ S3_READ_COUNTER.labels(outcome=outcome).inc()+ if seconds is not None:+ S3_READ_DURATION.labels(outcome=outcome).observe(seconds)+++def query_cache_raw_client() -> Redis | RedisCluster:+ return get_redis_connection(QUERY_CACHE_ALIAS)+++def query_cache_read_client() -> Redis | RedisCluster:+ # write=False keeps reads on the reader replica, as the replaced caches[alias].get() did;+ # the default write client would shift the cache's full read load onto the primary.+ return get_redis_connection(QUERY_CACHE_ALIAS, write=False)+++def entry_redis_key(cache_key: str) -> str:+ # The key django_redis computes for this alias, so entries written before this module owned+ # the value bytes stay addressable, and values this module writes stay on the keys older+ # pods read.+ return caches[QUERY_CACHE_ALIAS].make_key(cache_key)+++def load_entry_value(cache_key: str) -> Optional[bytes]:+ return cast(Optional[bytes], query_cache_read_client().get(entry_redis_key(cache_key)))+++def delete_entry(cache_key: str) -> None:+ query_cache_raw_client().delete(entry_redis_key(cache_key))+++def encode_inline_value(payload: bytes) -> bytes:+ """The bytes stored inline in Redis for a serialized result: the payload or its zstd frame.++ Compression happens here, once: the same frame serves as the inline value, the S3 routing+ decision, and the S3 upload body.+ """+ # USE_REDIS_COMPRESSION is the fleet-wide compression kill switch; skipping the frame also+ # keeps the value off the S3 route, which only takes zstd frames.+ if len(payload) <= COMPRESSION_FLOOR_BYTES or not settings.USE_REDIS_COMPRESSION:+ return payload+ return zstd.compress(payload, ZSTD_PRESET, ZSTD_THREADS)+++# Bounds the blob bytes held by queued uploads while S3 is slow or down; a skipped upload is+# safe because the entry is already stored inline.+_UPLOAD_MAX_PENDING = 8++_upload_slots = threading.Semaphore(_UPLOAD_MAX_PENDING)+_upload_executor: Optional[ThreadPoolExecutor] = None+_upload_executor_lock = threading.Lock()+++def _get_upload_executor() -> ThreadPoolExecutor:+ # Created on first use so the threads start in the serving process, not in a pre-fork+ # parent whose threads would not survive the fork.+ global _upload_executor+ if _upload_executor is None:+ with _upload_executor_lock:+ if _upload_executor is None:+ _upload_executor = ThreadPoolExecutor(max_workers=2, thread_name_prefix="query-cache-s3")+ return _upload_executor+++def schedule_upload_for_pointer(+ *,+ team_id: int,+ cache_key: str,+ inline_value: bytes,+ last_refresh: Optional[str],+ swap: Callable[[bytes], bool],+) -> None:+ """Upload an already-stored inline value to S3 off the calling thread, then swap(pointer).++ Only zstd frames of at least QUERY_CACHE_S3_MIN_COMPRESSED_BYTES route to S3, gated by the+ team's flag. "shadow" uploads without swapping, so Redis keeps the blob; "on" swaps in the+ pointer once the upload succeeded, so the blob stops counting against the team's Redis+ cache budget. The write mode resolves on the calling thread because it touches Postgres+ and Django closes connections per request, not per worker thread. Never raises, and the+ caller never waits on S3: with the pool saturated the upload is skipped and the entry+ simply stays inline.+ """+ if (+ not inline_value.startswith(ZSTD_FRAME_MAGIC)+ or len(inline_value) < settings.QUERY_CACHE_S3_MIN_COMPRESSED_BYTES+ ):+ return+ mode = s3_write_mode(team_id)+ if mode == "off":+ return+ if not _upload_slots.acquire(blocking=False):+ _record_s3_write(mode, "saturated")+ return++ def _upload_and_swap() -> None:+ try:+ pointer = write_blob(+ team_id=team_id, cache_key=cache_key, blob=inline_value, mode=mode, last_refresh=last_refresh+ )+ if mode == "on" and pointer is not None:+ swapped = swap(pointer)+ if not swapped:+ # The blob this upload wrote is unreferenced; the lifecycle rule collects it.+ logger.info("query_cache_s3_swap_superseded", team_id=team_id, cache_key=cache_key)+ except Exception:+ logger.warning("query_cache_s3_swap_failed", team_id=team_id, cache_key=cache_key, exc_info=True)+ finally:+ _upload_slots.release()++ try:+ _get_upload_executor().submit(_upload_and_swap)+ except Exception:+ _upload_slots.release()+ logger.warning("query_cache_s3_upload_submit_failed", team_id=team_id, cache_key=cache_key, exc_info=True)+++def decode_stored_value(value: bytes, *, team_id: int, cache_key: str) -> Optional[bytes]:+ """Resolve stored bytes back to the result payload. Never raises, never mutates.++ None means this read found the entry unusable (corrupt bytes, an unresolvable pointer).+ The miss sends the caller to recompute, and its store overwrites the entry, so dead+ entries heal by replacement rather than by deletion here.+ """+ if is_s3_pointer(value):+ return _read_blob(value, team_id=team_id, cache_key=cache_key)+ if value.startswith(ZSTD_FRAME_MAGIC):+ try:+ payload = zstd.decompress(value)+ except Exception:+ # Broader than zstd.Error on purpose: a corrupt frame's declared content size+ # raises MemoryError or OverflowError, and this function must never raise.+ logger.warning("query_cache_decompress_failed", team_id=team_id, cache_key=cache_key, exc_info=True)+ return None+ return _unpickle_if_legacy(payload, team_id=team_id, cache_key=cache_key)+ if value.startswith(PICKLE_PROTO_MARKER):+ return _unpickle_if_legacy(value, team_id=team_id, cache_key=cache_key)+ return value+++@frozen+class S3BlobPointer:+ """Location of a cache entry's blob in object storage, plus the result's last_refresh.++ The bucket is embedded rather than read from settings at resolve time, so entries written+ before a bucket change keep resolving until they expire. last_refresh rides along so+ freshness probes (cache warming) can answer from Redis without fetching the blob.+ """++ bucket: str+ key: str+ last_refresh: Optional[str] = None+++def encode_pointer(pointer: S3BlobPointer) -> bytes:+ record: dict[str, str | int] = {"v": 1, "b": pointer.bucket, "k": pointer.key}+ if pointer.last_refresh is not None:+ record["lr"] = pointer.last_refresh+ return S3_POINTER_MAGIC + OrjsonJsonSerializer({}).dumps(record)+++def is_s3_pointer(data: bytes) -> bool:+ return data.startswith(S3_POINTER_MAGIC)+++def decode_pointer(data: bytes) -> Optional[S3BlobPointer]:+ if not is_s3_pointer(data):+ return None+ try:+ payload = OrjsonJsonSerializer({}).loads(data[len(S3_POINTER_MAGIC) :])+ # An unrecognized version or shape must read as corrupt (miss + recompute), not decode+ # into a bogus pointer that is retried against S3.+ if payload.get("v") != 1 or not isinstance(payload.get("b"), str) or not isinstance(payload.get("k"), str):+ return None+ last_refresh = payload.get("lr")+ return S3BlobPointer(+ bucket=payload["b"],+ key=payload["k"],+ last_refresh=last_refresh if isinstance(last_refresh, str) else None,+ )+ except Exception:+ return None+++@cache_for(timedelta(minutes=1))+def _organization_id_for_team(team_id: int) -> Optional[str]:+ from posthog.models import Team++ try:+ team = Team.objects.only("organization_id").get(pk=team_id)+ return str(team.organization_id)+ except Team.DoesNotExist:+ return None+ except Exception:+ # Caching is an optimization: a failure here (struggling Postgres, dropped pgbouncer+ # connection, anything unexpected) must degrade to the inline path, not abort the write.+ logger.warning("query_cache_s3_org_lookup_failed", team_id=team_id, exc_info=True)+ return None+++def s3_write_mode(team_id: int) -> QueryCacheS3Mode:+ # Without object storage there is nothing to route to: UnavailableStorage swallows writes+ # silently, which would mint pointers to blobs that were never stored.+ if not settings.OBJECT_STORAGE_ENABLED:+ return "off"+ organization_id = _organization_id_for_team(team_id)+ if organization_id is None:+ return "off"+ variant = get_feature_flag_or_none(+ QUERY_CACHE_S3_FLAG,+ organization_id,+ groups={"organization": organization_id},+ # Local evaluation only sees properties supplied here, so an id-filtered rollout needs+ # the id or it evaluates inconclusive and reads as off. Filters on any other+ # organization property still read as off.+ group_properties={"organization": {"id": organization_id}},+ only_evaluate_locally=True,+ send_feature_flag_events=False,+ )+ # Only the two known variants activate S3 writes; a boolean flag, an unknown variant, or an+ # evaluation failure all fail closed to the inline Redis path.+ if variant == "shadow":+ return "shadow"+ if variant == "on":+ return "on"+ return "off"+++def write_blob(+ *, team_id: int, cache_key: str, blob: bytes, mode: QueryCacheS3Mode, last_refresh: Optional[str] = None+) -> Optional[bytes]:+ """Upload a cache entry's compressed blob, returning encoded pointer bytes, or None on failure.++ Never raises: on failure the caller stores the blob inline in Redis, so S3 problems degrade+ to inline caching instead of failing the query response.+ """+ bucket = settings.QUERY_CACHE_S3_BUCKET+ # A fresh object per upload: overlapping recomputes of one query would otherwise race on a+ # shared key, and the last PUT to land could pair an older blob with a newer pointer's+ # metadata. Superseded generations become unreferenced objects the lifecycle rule collects.+ object_key = f"{settings.OBJECT_STORAGE_S3_QUERY_CACHE_FOLDER}/{team_id}/{cache_key}/{uuid4().hex}"+ upload_start = time.perf_counter()+ try:+ # The bucket's lifecycle rule garbage-collects blobs after CACHED_RESULTS_TTL_DAYS;+ # the Redis pointer's TTL is what actually expires the entry. Tags are for attribution+ # only. See docs/internal/workflows/s3-query-cache-setup.md.+ extras = {"Tagging": f"cache_type=query_data&team_id={team_id}"}+ object_storage_client().write(bucket=bucket, key=object_key, content=blob, extras=extras)+ except Exception:+ _record_s3_write(mode, "error", time.perf_counter() - upload_start)+ logger.warning("query_cache_s3_write_failed", team_id=team_id, cache_key=cache_key, exc_info=True)+ return None+ _record_s3_write(mode, "success", time.perf_counter() - upload_start)+ S3_WRITE_BYTES_COUNTER.labels(mode=mode).inc(len(blob))+ return encode_pointer(S3BlobPointer(bucket=bucket, key=object_key, last_refresh=last_refresh))+++def _read_blob(pointer_bytes: bytes, *, team_id: int, cache_key: str) -> Optional[bytes]:+ """Resolve a pointer record to the decompressed payload bytes. Never raises."""+ pointer = decode_pointer(pointer_bytes)+ if pointer is None:+ _record_s3_read("pointer_corrupt")+ logger.warning("query_cache_s3_pointer_corrupt", team_id=team_id, cache_key=cache_key)+ return None+ if not settings.OBJECT_STORAGE_ENABLED:+ # UnavailableStorage would report these reads as "missing", which looks like data+ # loss during a deliberate storage rollback; label them for what they are.+ _record_s3_read("storage_disabled")+ return None+ fetch_start = time.perf_counter()+ try:+ payload = object_storage_client().read_bytes(bucket=pointer.bucket, key=pointer.key, missing_ok=True)+ except Exception:+ _record_s3_read("error", time.perf_counter() - fetch_start)+ logger.warning("query_cache_s3_read_failed", team_id=team_id, cache_key=cache_key, exc_info=True)+ return None+ fetch_seconds = time.perf_counter() - fetch_start+ if payload is None:+ _record_s3_read("missing", fetch_seconds)+ return None+ try:+ data = zstd.decompress(payload)+ except Exception:+ # Broader than zstd.Error on purpose: a corrupt frame's declared content size raises+ # MemoryError or OverflowError, and this function must never raise.+ _record_s3_read("blob_corrupt", fetch_seconds)+ logger.warning("query_cache_s3_decompress_failed", team_id=team_id, cache_key=cache_key, exc_info=True)+ return None+ _record_s3_read("hit", fetch_seconds)+ return data+++class _LegacyValueUnpickler(pickle.Unpickler):+ """django_redis pickled entry values as plain bytes objects, which never reference a global,+ so any attempt to resolve one marks a crafted value rather than a legacy entry."""++ def find_class(self, module: str, name: str) -> NoReturn:+ # ValueError rather than pickle.UnpicklingError: the caller catches broadly, and the+ # qualified call trips the same semgrep rule this class exists to satisfy.+ raise ValueError(f"legacy cache value must not reference {module}.{name}")+++def _unpickle_if_legacy(payload: bytes, *, team_id: int, cache_key: str) -> Optional[bytes]:+ """Unwrap a value that django_redis pickled before this module owned the value bytes.++ Deletable once CACHED_RESULTS_TTL has retired every entry written through django_redis.+ """+ if not payload.startswith(PICKLE_PROTO_MARKER):+ return payload+ try:+ legacy = _LegacyValueUnpickler(io.BytesIO(payload)).load()+ except Exception:+ logger.warning("query_cache_legacy_unpickle_failed", team_id=team_id, cache_key=cache_key, exc_info=True)+ return None+ if not isinstance(legacy, bytes):+ logger.warning("query_cache_legacy_value_not_bytes", team_id=team_id, cache_key=cache_key)+ return None+ LEGACY_VALUE_READ_COUNTER.inc()+ return legacydiff --git a/posthog/query_cache/test/test_cache.py b/posthog/query_cache/test/test_cache.pyindex 18503bed28ef..e54c17881c07 100644--- a/posthog/query_cache/test/test_cache.py+++ b/posthog/query_cache/test/test_cache.py@@ -1,14 +1,18 @@+import picklefrom datetime import UTC, datetime, timedeltafrom posthog.test.base import BaseTestfrom unittest.mock import patch-from django.core.cache import cachesfrom django.db import OperationalErrorfrom posthog.cache_utils import OrjsonJsonSerializer-from posthog.caching.redis_cluster_connection_factory import QUERY_CACHE_ALIAS-from posthog.query_cache import QueryCache, get_stale_insights+from posthog.query_cache import (+ QueryCache,+ get_stale_insights,+ storage as qc_storage,+)+from posthog.query_cache.storage import entry_redis_keyclass TestQueryCacheFacade(BaseTest):@@ -37,7 +41,10 @@ class TestQueryCacheFacade(BaseTest):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"}- caches[QUERY_CACHE_ALIAS].set(cache_key, OrjsonJsonSerializer({}).dumps(response), 60)+ # Entries from before the split format went through django_redis, which pickled them.+ legacy_value = pickle.dumps(OrjsonJsonSerializer({}).dumps(response))+ # Through the module so the fakeredis monkeypatch in conftest applies.+ qc_storage.query_cache_raw_client().set(entry_redis_key(cache_key), legacy_value, ex=60)cache = QueryCache(team_id=self.team.pk, cache_key=cache_key)entry = cache.lookup().entrydiff --git a/posthog/query_cache/test/test_size_tracker.py b/posthog/query_cache/test/test_size_tracker.pyindex 6fdffb319439..2efb53c4e20d 100644--- a/posthog/query_cache/test/test_size_tracker.py+++ b/posthog/query_cache/test/test_size_tracker.py@@ -1,12 +1,24 @@from posthog.test.base import BaseTestfrom unittest.mock import patch-from django.core.cache import cachefrom django.db import OperationalErrorfrom django.test import override_settings+import fakeredis+from posthog.models import Teamfrom posthog.query_cache.size_tracker import TeamCacheSizeTracker, get_team_cache_limit+from posthog.query_cache.storage import entry_redis_key++ENTRY_KEYS = [+ "test_key",+ "test_key_1",+ "test_key_2",+ "test_key_3",+ "expired_key",+ "real_key",+ "large_key",+]class TestTeamCacheSizeTracker(BaseTest):@@ -17,15 +29,15 @@ class TestTeamCacheSizeTracker(BaseTest):def tearDown(self) -> None:self.tracker.purge()- cache.delete("test_key_1")- cache.delete("test_key_2")- cache.delete("test_key_3")- cache.delete("expired_key")- cache.delete("real_key")- cache.delete("test_key")- cache.delete("large_key")+ self.tracker.redis_client.delete(*(entry_redis_key(key) for key in ENTRY_KEYS))super().tearDown()+ def _seed_entry(self, cache_key: str, data: bytes) -> None:+ self.tracker.redis_client.set(entry_redis_key(cache_key), data)++ def _entry(self, cache_key: str) -> bytes | None:+ return self.tracker.redis_client.get(entry_redis_key(cache_key))+def test_track_cache_write_increments_total(self):self.assertEqual(self.tracker.get_total_size(), 0)@@ -60,9 +72,9 @@ class TestTeamCacheSizeTracker(BaseTest):self.tracker.track_cache_write("test_key_1", 100)self.tracker.track_cache_write("test_key_2", 200)self.tracker.track_cache_write("test_key_3", 300)- cache.set("test_key_1", "data1")- cache.set("test_key_2", "data2")- cache.set("test_key_3", "data3")+ self._seed_entry("test_key_1", b"data1")+ self._seed_entry("test_key_2", b"data2")+ self._seed_entry("test_key_3", b"data3")self.assertEqual(self.tracker.get_total_size(), 600)@@ -80,16 +92,15 @@ class TestTeamCacheSizeTracker(BaseTest):# Total should now be under limit + new entry sizeself.assertLessEqual(self.tracker.get_total_size() + 200, 500)# Newest entry should still exist- self.assertIsNotNone(cache.get("test_key_3"))+ self.assertIsNotNone(self._entry("test_key_3"))def test_evict_cleans_up_expired_keys(self):- # Track a key but don't actually set it in cache (simulates TTL expiration)+ # Track a key but don't actually store an entry for it (simulates TTL expiration)self.tracker.track_cache_write("expired_key", 1000)- # Don't set cache.set() - simulating expired key# Track a real keyself.tracker.track_cache_write("real_key", 500)- cache.set("real_key", "data")+ self._seed_entry("real_key", b"data")# Total includes the "expired" keyself.assertEqual(self.tracker.get_total_size(), 1500)@@ -100,13 +111,13 @@ class TestTeamCacheSizeTracker(BaseTest):# Expired key should be cleaned up (not in evicted list since it wasn't actually evicted)self.assertNotIn("expired_key", evicted)# Real key should still exist- self.assertIsNotNone(cache.get("real_key"))+ self.assertIsNotNone(self._entry("real_key"))# Total should now be correct (only real_key)self.assertEqual(self.tracker.get_total_size(), 500)def test_evict_returns_empty_when_under_limit(self):self.tracker.track_cache_write("test_key_1", 100)- cache.set("test_key_1", "data1")+ self._seed_entry("test_key_1", b"data1")# Already under limitevicted = self.tracker.evict_until_under_limit(1000, 100)@@ -126,10 +137,10 @@ class TestTeamCacheSizeTracker(BaseTest):def test_set_method_writes_cache_and_tracks(self):data = b"test_data_content"- self.tracker.set("test_key_1", data, len(data), 300)+ self.tracker.set("test_key_1", data, 300)# Cache should be set- self.assertEqual(cache.get("test_key_1"), data)+ self.assertEqual(self._entry("test_key_1"), data)# Tracking should be updatedself.assertEqual(self.tracker.get_total_size(), len(data))@@ -137,22 +148,22 @@ class TestTeamCacheSizeTracker(BaseTest):def test_set_method_triggers_eviction_when_over_limit(self):# First write - under limitdata1 = b"x" * 200- cache.set("test_key_1", data1)+ self._seed_entry("test_key_1", data1)self.tracker.track_cache_write("test_key_1", len(data1))data2 = b"y" * 200- cache.set("test_key_2", data2)+ self._seed_entry("test_key_2", data2)self.tracker.track_cache_write("test_key_2", len(data2))# This should trigger eviction of test_key_1data3 = b"z" * 200- evicted = self.tracker.set("test_key_3", data3, len(data3), 300)+ evicted = self.tracker.set("test_key_3", data3, 300)self.assertIn("test_key_1", evicted)- self.assertIsNone(cache.get("test_key_1"))+ self.assertIsNone(self._entry("test_key_1"))self.assertIsNone(self.tracker._get_key_size("test_key_1"))self.assertIsNone(self.tracker.redis_client.zscore(self.tracker.entries_key, "test_key_1"))- self.assertIsNotNone(cache.get("test_key_3"))+ self.assertIsNotNone(self._entry("test_key_3"))def test_remove_tracking_is_idempotent(self):self.tracker.track_cache_write("test_key", 1000)@@ -170,12 +181,12 @@ class TestTeamCacheSizeTracker(BaseTest):self.assertEqual(self.tracker.get_total_size(), 0)def test_stale_tracking_cleaned_during_eviction(self):- # Track keys but don't set them in cache (simulates TTL expiration)+ # Track keys but don't store entries for them (simulates TTL expiration)self.tracker.track_cache_write("stale_key_1", 1000)self.tracker.track_cache_write("stale_key_2", 1000)# Also add a real keyself.tracker.track_cache_write("real_key", 500)- cache.set("real_key", "data")+ self._seed_entry("real_key", b"data")# Total is inflated due to stale entriesself.assertEqual(self.tracker.get_total_size(), 2500)@@ -186,7 +197,7 @@ class TestTeamCacheSizeTracker(BaseTest):# Stale entries cleaned up, real_key not evicted (500 + 100 <= 1000)self.assertEqual(evicted, [])self.assertEqual(self.tracker.get_total_size(), 500)- self.assertIsNotNone(cache.get("real_key"))+ self.assertIsNotNone(self._entry("real_key"))def test_team_isolation(self):tracker_team_a = TeamCacheSizeTracker(self.team.pk)@@ -207,38 +218,36 @@ class TestTeamCacheSizeTracker(BaseTest):@override_settings(TEAM_CACHE_SIZE_LIMIT_BYTES=500)def test_entry_larger_than_limit_evicts_all(self):- cache.set("test_key_1", b"x" * 100)+ self._seed_entry("test_key_1", b"x" * 100)self.tracker.track_cache_write("test_key_1", 100)- cache.set("test_key_2", b"y" * 100)+ self._seed_entry("test_key_2", b"y" * 100)self.tracker.track_cache_write("test_key_2", 100)self.assertEqual(self.tracker.get_total_size(), 200)large_data = b"z" * 600- evicted = self.tracker.set("large_key", large_data, len(large_data), 300)+ evicted = self.tracker.set("large_key", large_data, 300)self.assertIn("test_key_1", evicted)self.assertIn("test_key_2", evicted)- self.assertEqual(cache.get("large_key"), large_data)+ self.assertEqual(self._entry("large_key"), large_data)self.assertIsNone(self.tracker._get_key_size("test_key_1"))self.assertIsNone(self.tracker._get_key_size("test_key_2"))self.assertIsNone(self.tracker.redis_client.zscore(self.tracker.entries_key, "test_key_1"))self.assertIsNone(self.tracker.redis_client.zscore(self.tracker.entries_key, "test_key_2"))self.assertEqual(self.tracker.get_total_size(), 600)- def test_set_and_read_through_injected_cache_backend(self):- from django.core.cache.backends.locmem import LocMemCache-- cluster_cache = LocMemCache("query-cache-test", {})- tracker = TeamCacheSizeTracker(self.team.pk, cache_backend=cluster_cache)+ def test_set_and_read_through_injected_redis_client(self):+ injected = fakeredis.FakeRedis()+ tracker = TeamCacheSizeTracker(self.team.pk, redis_client=injected)tracker.purge()data = b"test_data_content"- tracker.set("test_key", data, len(data), 300)+ tracker.set("test_key", data, 300)- # Readable from the injected backend, not the default- self.assertEqual(cluster_cache.get("test_key"), data)- self.assertIsNone(cache.get("test_key"))+ # Entry and tracking both live in the injected client, not the shared one+ self.assertEqual(injected.get(entry_redis_key("test_key")), data)+ self.assertIsNone(self._entry("test_key"))self.assertEqual(tracker.get_total_size(), len(data))tracker.purge()diff --git a/posthog/query_cache/test/test_storage.py b/posthog/query_cache/test/test_storage.pynew file mode 100644index 000000000000..5e6ac01ebcdb--- /dev/null+++ b/posthog/query_cache/test/test_storage.py@@ -0,0 +1,425 @@+import pickle+import hashlib+from datetime import UTC, datetime, timedelta++from posthog.test.base import BaseTest+from unittest.mock import MagicMock, patch++from django.test import SimpleTestCase, override_settings++import zstd+from parameterized import parameterized++from posthog.query_cache import (+ QueryCache,+ get_stale_insights,+ storage as qc_storage,+)+from posthog.query_cache.serialization import QUERY_CACHE_SPLIT_MAGIC, encode_split_cached_response+from posthog.query_cache.storage import (+ S3_POINTER_MAGIC,+ ZSTD_FRAME_MAGIC,+ S3BlobPointer,+ decode_pointer,+ encode_pointer,+ entry_redis_key,+ is_s3_pointer,+ s3_write_mode,+)+from posthog.storage.object_storage import ObjectStorageError+++class FakeObjectStorage:+ def __init__(self) -> None:+ self.objects: dict[tuple[str, str], bytes] = {}+ self.fail_writes = False+ self.fail_reads = False++ def write(self, bucket: str, key: str, content: bytes, extras: dict | None = None) -> None:+ if self.fail_writes:+ raise ObjectStorageError("write failed")+ self.objects[(bucket, key)] = content++ def read_bytes(self, bucket: str, key: str, *, missing_ok: bool = False) -> bytes | None:+ if self.fail_reads:+ raise ObjectStorageError("read failed")+ if (bucket, key) not in self.objects:+ if missing_ok:+ return None+ raise ObjectStorageError("read failed")+ return self.objects[(bucket, key)]+++class TestS3PointerCodec(SimpleTestCase):+ def test_pointer_round_trips(self):+ pointer = S3BlobPointer(bucket="cache-bucket", key="query_cache/1/some_key")+ assert decode_pointer(encode_pointer(pointer)) == pointer++ @parameterized.expand(+ [+ ("legacy_json_blob", b'{"results": []}'),+ ("split_format_blob", QUERY_CACHE_SPLIT_MAGIC + b"\x00rest"),+ ("empty", b""),+ ]+ )+ def test_blob_formats_are_not_pointers(self, _name, data):+ assert not is_s3_pointer(data)+ assert decode_pointer(data) is None++ @parameterized.expand(+ [+ ("not_json", S3_POINTER_MAGIC + b"notjson"),+ ("missing_keys", S3_POINTER_MAGIC + b'{"v": 1}'),+ ("unknown_version", S3_POINTER_MAGIC + b'{"v": 2, "b": "bucket", "k": "key"}'),+ ("non_string_key", S3_POINTER_MAGIC + b'{"v": 1, "b": "bucket", "k": [1, 2]}'),+ ]+ )+ def test_corrupt_pointer_decodes_to_none(self, _name, data):+ assert is_s3_pointer(data)+ assert decode_pointer(data) is None+++@override_settings(OBJECT_STORAGE_ENABLED=True)+class TestS3WriteMode(SimpleTestCase):+ def test_disabled_object_storage_fails_closed(self):+ # UnavailableStorage swallows writes silently, so routing while storage is off would+ # store pointers to blobs that were never written.+ with (+ override_settings(OBJECT_STORAGE_ENABLED=False),+ patch("posthog.query_cache.storage._organization_id_for_team") as org_mock,+ ):+ assert s3_write_mode(team_id=1) == "off"+ org_mock.assert_not_called()++ @parameterized.expand(+ [+ ("on", "on"),+ ("shadow", "shadow"),+ (True, "off"),+ (False, "off"),+ (None, "off"),+ ("unknown-variant", "off"),+ ]+ )+ def test_only_known_variants_activate(self, variant, expected):+ with (+ patch("posthog.query_cache.storage._organization_id_for_team", return_value="0189-org-uuid"),+ patch("posthog.query_cache.storage.get_feature_flag_or_none", return_value=variant),+ ):+ assert s3_write_mode(team_id=1) == expected++ def test_unresolvable_organization_fails_closed_without_flag_evaluation(self):+ with (+ patch("posthog.query_cache.storage._organization_id_for_team", return_value=None),+ patch("posthog.query_cache.storage.get_feature_flag_or_none") as flag_mock,+ ):+ assert s3_write_mode(team_id=1) == "off"+ flag_mock.assert_not_called()++ def test_flag_evaluation_supplies_group_properties(self):+ # Without group_properties, an id-filtered rollout evaluates inconclusive under+ # only_evaluate_locally and silently reads as off.+ with (+ patch("posthog.query_cache.storage._organization_id_for_team", return_value="0189-org-uuid"),+ patch("posthog.query_cache.storage.get_feature_flag_or_none", return_value="on") as flag_mock,+ ):+ assert s3_write_mode(team_id=1) == "on"+ assert flag_mock.call_args.kwargs["groups"] == {"organization": "0189-org-uuid"}+ assert flag_mock.call_args.kwargs["group_properties"] == {"organization": {"id": "0189-org-uuid"}}+++def _redis_raw(cache_key: str) -> bytes | None:+ # Reach the client through the module so the fakeredis monkeypatch in conftest applies.+ return qc_storage.query_cache_raw_client().get(entry_redis_key(cache_key))+++def _incompressible_rows(count: int) -> list[str]:+ return [hashlib.sha256(str(i).encode()).hexdigest() for i in range(count)]+++class TestStoredValueFormats(BaseTest):+ def test_inline_values_are_stored_compressed_and_round_trip(self):+ cache_key = f"storage_inline_{self.team.pk}"+ cache = QueryCache(team_id=self.team.pk, cache_key=cache_key, insight_id=1)+ response = {+ "is_cached": False,+ "results": [{"data": _incompressible_rows(10)}],+ "cache_key": "k",+ "last_refresh": "2026-08-01T00:00:00+00:00",+ }++ cache.store_result(response=response, target_age=None)++ raw = _redis_raw(cache_key)+ assert raw is not None+ assert raw.startswith(ZSTD_FRAME_MAGIC)+ entry = cache.lookup().entry+ assert entry is not None+ assert entry.as_full_response() == response+ freshness = cache.freshness()+ assert freshness is not None+ assert freshness.last_refresh == "2026-08-01T00:00:00+00:00"++ def test_compression_kill_switch_stores_raw_and_round_trips(self):+ cache_key = f"storage_kill_switch_{self.team.pk}"+ cache = QueryCache(team_id=self.team.pk, cache_key=cache_key, insight_id=1)+ response = {"is_cached": False, "results": [{"data": _incompressible_rows(10)}], "cache_key": "k"}++ with override_settings(USE_REDIS_COMPRESSION=False):+ cache.store_result(response=response, target_age=None)++ raw = _redis_raw(cache_key)+ assert raw is not None+ assert not raw.startswith(ZSTD_FRAME_MAGIC)+ entry = cache.lookup().entry+ assert entry is not None+ assert entry.as_full_response() == response++ def test_undecompressable_inline_value_reads_as_miss(self):+ cache_key = f"storage_bad_frame_{self.team.pk}"+ cache = QueryCache(team_id=self.team.pk, cache_key=cache_key, insight_id=1)+ response = {"is_cached": False, "results": [{"data": _incompressible_rows(10)}], "cache_key": "k"}+ cache.store_result(response=response, target_age=None)++ # A corrupt frame's declared content size raises MemoryError, not zstd.Error.+ with patch("posthog.query_cache.storage.zstd.decompress", side_effect=MemoryError):+ assert cache.lookup().entry is None+ # The miss must not mutate: the entry is still there and served once reads work again.+ entry = cache.lookup().entry+ assert entry is not None+ assert entry.as_full_response() == response++ @parameterized.expand(+ [+ ("pickled", False),+ ("zstd_compressed_pickled", True),+ ]+ )+ def test_legacy_django_redis_values_stay_readable(self, _name, compressed):+ cache_key = f"storage_legacy_{_name}_{self.team.pk}"+ response = {"is_cached": False, "results": [{"data": [1]}], "cache_key": "k"}+ legacy_value = pickle.dumps(encode_split_cached_response(response))+ if compressed:+ legacy_value = zstd.compress(legacy_value, 0, 1)+ qc_storage.query_cache_raw_client().set(entry_redis_key(cache_key), legacy_value)++ entry = QueryCache(team_id=self.team.pk, cache_key=cache_key).lookup().entry+ assert entry is not None+ assert entry.as_full_response() == response+++@override_settings(QUERY_CACHE_S3_MIN_COMPRESSED_BYTES=64, OBJECT_STORAGE_ENABLED=True)+class TestQueryCacheS3Routing(BaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.storage = FakeObjectStorage()+ storage_patcher = patch("posthog.query_cache.storage.object_storage_client", return_value=self.storage)+ storage_patcher.start()+ self.addCleanup(storage_patcher.stop)+ # Run uploads inline so assertions right after store_result see the swapped pointer.+ self.upload_executor = MagicMock()+ self.upload_executor.submit.side_effect = lambda fn: fn()+ executor_patcher = patch("posthog.query_cache.storage._get_upload_executor", return_value=self.upload_executor)+ executor_patcher.start()+ self.addCleanup(executor_patcher.stop)++ def _large_response(self) -> dict:+ return {"is_cached": False, "results": [{"data": _incompressible_rows(10)}], "cache_key": "k"}++ def _small_response(self) -> dict:+ return {"is_cached": False, "results": [], "cache_key": "k"}++ def _redis_holds_pointer(self, cache_key: str) -> bool:+ raw = _redis_raw(cache_key)+ assert raw is not None+ return raw.startswith(S3_POINTER_MAGIC)++ def test_stale_upload_cannot_replace_a_newer_entry(self):+ cache_key = f"s3_race_{self.team.pk}"+ cache = QueryCache(team_id=self.team.pk, cache_key=cache_key, insight_id=1)+ pending: list = []+ self.upload_executor.submit.side_effect = pending.append++ older = {**self._large_response(), "cache_key": "older"}+ newer = {**self._large_response(), "cache_key": "newer"}+ with patch("posthog.query_cache.storage.s3_write_mode", return_value="on"):+ cache.store_result(response=older, target_age=None)+ cache.store_result(response=newer, target_age=None)+ older_upload, newer_upload = pending++ newer_upload()+ assert self._redis_holds_pointer(cache_key)+ older_upload()++ entry = cache.lookup().entry+ assert entry is not None+ assert entry.as_full_response() == newer++ def test_on_mode_large_result_round_trips_via_pointer(self):+ cache_key = f"s3_on_large_{self.team.pk}"+ cache = QueryCache(team_id=self.team.pk, cache_key=cache_key, insight_id=1)+ response = self._large_response()++ with patch("posthog.query_cache.storage.s3_write_mode", return_value="on"):+ cache.store_result(response=response, target_age=None)++ assert self._redis_holds_pointer(cache_key)+ assert len(self.storage.objects) == 1+ entry = cache.lookup().entry+ assert entry is not None+ assert entry.as_full_response() == response++ def test_each_upload_writes_a_fresh_object(self):+ cache_key = f"s3_fresh_object_{self.team.pk}"+ cache = QueryCache(team_id=self.team.pk, cache_key=cache_key, insight_id=1)+ first = self._large_response()+ second = {**self._large_response(), "cache_key": "second"}++ with patch("posthog.query_cache.storage.s3_write_mode", return_value="on"):+ cache.store_result(response=first, target_age=None)+ cache.store_result(response=second, target_age=None)++ # A shared object key would let overlapping recomputes overwrite each other's blob.+ assert len(self.storage.objects) == 2+ entry = cache.lookup().entry+ assert entry is not None+ assert entry.as_full_response() == second++ def test_inline_value_is_readable_during_the_upload(self):+ cache_key = f"s3_during_upload_{self.team.pk}"+ cache = QueryCache(team_id=self.team.pk, cache_key=cache_key, insight_id=1)+ observed: dict[str, bytes | None] = {}+ original_write = self.storage.write++ def write_and_peek(bucket: str, key: str, content: bytes, extras: dict | None = None) -> None:+ observed["during_upload"] = _redis_raw(cache_key)+ original_write(bucket, key, content, extras)++ with (+ patch.object(self.storage, "write", side_effect=write_and_peek),+ patch("posthog.query_cache.storage.s3_write_mode", return_value="on"),+ ):+ cache.store_result(response=self._large_response(), target_age=None)++ # Uploading before the inline write would reopen the window where concurrent+ # requests miss and recompute a result that just finished computing.+ assert observed["during_upload"] is not None+ assert observed["during_upload"].startswith(ZSTD_FRAME_MAGIC)+ assert self._redis_holds_pointer(cache_key)++ def test_freshness_probe_reads_pointer_without_s3(self):+ cache_key = f"s3_probe_{self.team.pk}"+ cache = QueryCache(team_id=self.team.pk, cache_key=cache_key, insight_id=1)+ assert cache.freshness() is None+ response = {**self._large_response(), "last_refresh": "2026-08-01T00:00:00+00:00"}++ with patch("posthog.query_cache.storage.s3_write_mode", return_value="on"):+ cache.store_result(response=response, target_age=None)++ assert self._redis_holds_pointer(cache_key)+ self.storage.fail_reads = True+ freshness = cache.freshness()+ assert freshness is not None+ assert freshness.last_refresh == "2026-08-01T00:00:00+00:00"++ @parameterized.expand(+ [+ # Below the compression floor: stored raw, never a candidate for S3.+ ("small_below_floor", [], False),+ # The next two serialize well past the threshold; only their compressed sizes differ.+ ("compressible_stays_inline", [{"data": ["x" * 20000]}], False),+ ("incompressible_goes_to_s3", [{"data": _incompressible_rows(50)}], True),+ ]+ )+ @override_settings(QUERY_CACHE_S3_MIN_COMPRESSED_BYTES=1000)+ def test_only_large_compressed_results_route_to_s3(self, _name, results, expect_pointer):+ cache_key = f"s3_threshold_{_name}_{self.team.pk}"+ cache = QueryCache(team_id=self.team.pk, cache_key=cache_key, insight_id=1)+ response = {"is_cached": False, "results": results, "cache_key": "k"}++ with patch("posthog.query_cache.storage.s3_write_mode", return_value="on"):+ cache.store_result(response=response, target_age=None)++ assert self._redis_holds_pointer(cache_key) == expect_pointer+ assert bool(self.storage.objects) == expect_pointer+ entry = cache.lookup().entry+ assert entry is not None+ assert entry.as_full_response() == response++ def test_shadow_mode_uploads_but_redis_stays_authoritative(self):+ cache_key = f"s3_shadow_{self.team.pk}"+ cache = QueryCache(team_id=self.team.pk, cache_key=cache_key, insight_id=1)+ response = self._large_response()++ with patch("posthog.query_cache.storage.s3_write_mode", return_value="shadow"):+ cache.store_result(response=response, target_age=None)++ assert len(self.storage.objects) == 1+ assert not self._redis_holds_pointer(cache_key)++ self.storage.objects.clear()+ entry = cache.lookup().entry+ assert entry is not None+ assert entry.as_full_response() == response++ def test_off_mode_never_touches_s3(self):+ cache_key = f"s3_off_{self.team.pk}"+ cache = QueryCache(team_id=self.team.pk, cache_key=cache_key, insight_id=1)++ with patch("posthog.query_cache.storage.s3_write_mode", return_value="off"):+ cache.store_result(response=self._large_response(), target_age=None)++ assert self.storage.objects == {}+ assert cache.lookup().entry is not None++ def test_s3_write_failure_falls_back_to_inline_blob(self):+ cache_key = f"s3_write_fail_{self.team.pk}"+ cache = QueryCache(team_id=self.team.pk, cache_key=cache_key, insight_id=1)+ response = self._large_response()+ self.storage.fail_writes = True++ with patch("posthog.query_cache.storage.s3_write_mode", return_value="on"):+ cache.store_result(response=response, target_age=None)++ assert not self._redis_holds_pointer(cache_key)+ entry = cache.lookup().entry+ assert entry is not None+ assert entry.as_full_response() == response++ def test_missing_blob_reads_as_miss_and_keeps_the_entry(self):+ cache_key = f"s3_missing_{self.team.pk}"+ cache = QueryCache(team_id=self.team.pk, cache_key=cache_key, insight_id=1)++ with patch("posthog.query_cache.storage.s3_write_mode", return_value="on"):+ cache.store_result(response=self._large_response(), target_age=None)+ self.storage.objects.clear()++ # Reads never mutate; the recompute a miss triggers is what overwrites dead entries.+ assert cache.lookup().entry is None+ assert self._redis_holds_pointer(cache_key)++ def test_transient_s3_error_keeps_pointer_and_recovers(self):+ cache_key = f"s3_transient_{self.team.pk}"+ cache = QueryCache(team_id=self.team.pk, cache_key=cache_key, insight_id=1)+ response = self._large_response()++ with patch("posthog.query_cache.storage.s3_write_mode", return_value="on"):+ cache.store_result(response=response, target_age=None)++ self.storage.fail_reads = True+ assert cache.lookup().entry is None+ assert self._redis_holds_pointer(cache_key)++ self.storage.fail_reads = False+ entry = cache.lookup().entry+ assert entry is not None+ assert entry.as_full_response() == response++ def test_pointer_write_updates_freshness_index(self):+ cache_key = f"s3_freshness_{self.team.pk}"+ cache = QueryCache(team_id=self.team.pk, cache_key=cache_key, insight_id=42)++ with patch("posthog.query_cache.storage.s3_write_mode", return_value="on"):+ cache.store_result(response=self._large_response(), target_age=datetime.now(UTC) - timedelta(minutes=5))++ assert "42:" in get_stale_insights(team_id=self.team.pk)diff --git a/posthog/settings/object_storage.py b/posthog/settings/object_storage.pyindex 89d0d5c04eb1..6e1b67ccc3aa 100644--- a/posthog/settings/object_storage.py+++ b/posthog/settings/object_storage.py@@ -63,6 +63,14 @@ NOTEBOOKS_FRAME_STORE_S3_BUCKET = os.getenv("NOTEBOOKS_FRAME_STORE_S3_BUCKET") o# Query cache specific bucket - falls back to general object storage bucket if not setQUERY_CACHE_S3_BUCKET = os.getenv("QUERY_CACHE_S3_BUCKET") or OBJECT_STORAGE_BUCKET+# Entries whose zstd-compressed form is at least this large go to S3 (with a Redis pointer) when+# the query-cache-s3-writes flag allows; smaller ones always stay inline in Redis. The threshold+# applies to compressed bytes because that is what an entry actually costs in Redis. Query results+# compress roughly 3-15x, so the 128KB default corresponds to about 0.4-2MB of serialized JSON:+# dashboard tiles, which almost never reach that size, stay on sub-millisecond Redis reads while+# the byte-heavy tail of ad-hoc and API results moves off the cluster.+QUERY_CACHE_S3_MIN_COMPRESSED_BYTES = get_from_env("QUERY_CACHE_S3_MIN_COMPRESSED_BYTES", 128 * 1024, type_cast=int)+# Video segment clustering workflow bucket - should have a 24h lifecycle rule for automatic cleanupVIDEO_SEGMENT_CLUSTERING_S3_BUCKET = os.getenv("VIDEO_SEGMENT_CLUSTERING_S3_BUCKET") or OBJECT_STORAGE_BUCKETdiff --git a/posthog/settings/schedules.py b/posthog/settings/schedules.pyindex 38c30b98c3a2..52694c10db22 100644--- a/posthog/settings/schedules.py+++ b/posthog/settings/schedules.py@@ -34,7 +34,9 @@ COUNT_TILES_WITH_NO_FILTERS_HASH_INTERVAL_SECONDS = get_from_env("COUNT_TILES_WITH_NO_FILTERS_HASH_INTERVAL_SECONDS", 1800, type_cast=int)-# If updating this, need to look into adding more values to S3 TTLs (see query_cache_s3.py)+# The query-cache buckets' lifecycle rule (posthog-cloud-infra) garbage-collects S3 blobs after+# this many days. Raising this value needs the bucket rule raised first, or blobs get deleted+# while their Redis pointers still live (see docs/internal/workflows/s3-query-cache-setup.md).CACHED_RESULTS_TTL_DAYS = 7CACHED_RESULTS_TTL = CACHED_RESULTS_TTL_DAYS * 24 * 60 * 60diff --git a/posthog/storage/object_storage.py b/posthog/storage/object_storage.pyindex 671634c04a50..e2c29ff449bd 100644--- a/posthog/storage/object_storage.py+++ b/posthog/storage/object_storage.py@@ -433,6 +433,10 @@ def object_storage_client() -> ObjectStorageClient:s3_config = Config(signature_version="s3v4",connect_timeout=1,+ # Bounds socket inactivity, not total transfer time, so slow-but-flowing large+ # objects still complete; the botocore default leaves callers blocked for 60s+ # when the store accepts a connection but stops sending bytes.+ read_timeout=5,retries={"max_attempts": 1},)aws_client = client(diff --git a/products/web_analytics/dags/cache_warming.py b/products/web_analytics/dags/cache_warming.pyindex 99cc7d50c528..8be6b95c82ab 100644--- a/products/web_analytics/dags/cache_warming.py+++ b/products/web_analytics/dags/cache_warming.py@@ -920,24 +920,24 @@ def _warm_queries(context: dagster.OpExecutionContext, mode: str, queries: list[return "skipped_duplicate"seen_cache_keys.add((team.pk, cache_key))- entry = QueryCache(team_id=team.pk, cache_key=cache_key).lookup().entry- query_info["_was_cold"] = entry is None+ freshness = QueryCache(team_id=team.pk, cache_key=cache_key).freshness()+ query_info["_was_cold"] = freshness is None# The cache entry doubles as the warm/cold discriminator: a shape# warmed at least once has one (possibly stale); a never-warmed shape# doesn't. refresh keeps the warm set fresh without paying for cold# builds; backfill expands coverage without re-touching the warm set.- if mode == "refresh" and entry is None:+ if mode == "refresh" and freshness is None:WARMING_QUERIES_COUNTER.labels(outcome="skipped_cold").inc()return "skipped_cold"- if mode == "backfill" and entry is not None:+ if mode == "backfill" and freshness is not None:WARMING_QUERIES_COUNTER.labels(outcome="skipped_already_warmed").inc()return "skipped_already_warmed"- cached_data = entry.as_full_response() if entry else None-- if cached_data is not None:- last_refresh = parse_datetime(cached_data["last_refresh"])+ # The probe answers from Redis alone: S3-backed entries carry last_refresh in the+ # pointer record, so no blob is fetched to make the staleness decision.+ if freshness is not None and freshness.last_refresh is not None:+ last_refresh = parse_datetime(freshness.last_refresh)aged_refresh = (last_refresh - _staleness_jitter(query_info["normalized_query_hash"], last_refresh)if last_refreshdiff --git a/products/web_analytics/dags/tests/test_cache_warming.py b/products/web_analytics/dags/tests/test_cache_warming.pyindex d7a57f84e45e..254cdb59da54 100644--- a/products/web_analytics/dags/tests/test_cache_warming.py+++ b/products/web_analytics/dags/tests/test_cache_warming.py@@ -15,6 +15,7 @@ from posthog.clickhouse.query_tagging import Feature, get_query_tags, reset_querfrom posthog.exceptions import ClickHouseAtCapacityfrom posthog.hogql_queries.query_runner import ExecutionModefrom posthog.models import Team+from posthog.query_cache import EntryFreshnessfrom products.web_analytics.backend.hogql_queries.web_lazy_precompute_common import is_background_warming_requestfrom products.web_analytics.dags import cache_warming@@ -590,7 +591,7 @@ class TestWarmQueriesOp(BaseTest):),patch("products.web_analytics.dags.cache_warming.QueryCache") as mock_cm,):- mock_cm.return_value.lookup.return_value.entry = None+ mock_cm.return_value.freshness.return_value = Nonewarm_queries_op(dagster.build_op_context(),WarmQueriesConfig(),@@ -642,7 +643,7 @@ class TestWarmQueriesOp(BaseTest):patch("products.web_analytics.dags.cache_warming.time.sleep") as mock_sleep,patch("products.web_analytics.dags.cache_warming.capture_exception") as mock_capture,):- mock_cm.return_value.lookup.return_value.entry = None+ mock_cm.return_value.freshness.return_value = Nonewarm_queries_op(dagster.build_op_context(),WarmQueriesConfig(),@@ -728,11 +729,8 @@ class TestWarmQueriesOp(BaseTest):patch("products.web_analytics.dags.cache_warming.build_replay_runner", return_value=(runner, {}, True)),patch("products.web_analytics.dags.cache_warming.QueryCache") as mock_cm,):- entry = None- if has_entry:- entry = MagicMock()- entry.as_full_response.return_value = {"last_refresh": "2026-07-01T00:00:00Z"}- mock_cm.return_value.lookup.return_value.entry = entry+ freshness = EntryFreshness(last_refresh="2026-07-01T00:00:00Z") if has_entry else None+ mock_cm.return_value.freshness.return_value = freshnesswarm_queries_op(dagster.build_op_context(),WarmQueriesConfig(mode=mode),@@ -793,7 +791,7 @@ class TestWarmQueriesOp(BaseTest):patch("products.web_analytics.dags.cache_warming.wait", side_effect=fake_wait),patch("products.web_analytics.dags.cache_warming.os._exit", side_effect=_Exited) as mock_exit,):- mock_cm.return_value.lookup.return_value.entry = None+ mock_cm.return_value.freshness.return_value = Noneshapes = [{"team_id": self.team.pk,@@ -847,7 +845,7 @@ class TestWarmQueriesOp(BaseTest):patch("products.web_analytics.dags.cache_warming.time", new=fake_time),patch("products.web_analytics.dags.cache_warming.os._exit", side_effect=_Exited) as mock_exit,):- mock_cm.return_value.lookup.return_value.entry = None+ mock_cm.return_value.freshness.return_value = Noneshapes = [{"team_id": self.team.pk,@@ -887,9 +885,7 @@ class TestWarmQueriesOp(BaseTest):patch("products.web_analytics.dags.cache_warming.build_replay_runner", return_value=(runner, {}, True)),patch("products.web_analytics.dags.cache_warming.QueryCache") as mock_cm,):- entry = MagicMock()- entry.as_full_response.return_value = {"last_refresh": "2026-07-01T00:00:00Z"}- mock_cm.return_value.lookup.return_value.entry = entry+ mock_cm.return_value.freshness.return_value = EntryFreshness(last_refresh="2026-07-01T00:00:00Z")warm_queries_op(dagster.build_op_context(),WarmQueriesConfig(),@@ -946,7 +942,7 @@ class TestWarmQueriesOp(BaseTest):patch("products.web_analytics.dags.cache_warming.wait", side_effect=interrupting_wait),patch("products.web_analytics.dags.cache_warming.os._exit", side_effect=_Exited) as mock_exit,):- mock_cm.return_value.lookup.return_value.entry = None+ mock_cm.return_value.freshness.return_value = Nonewith self.assertRaises(_Exited):warm_queries_op(dagster.build_op_context(),@@ -983,7 +979,7 @@ class TestWarmQueriesOp(BaseTest):patch("products.web_analytics.dags.cache_warming.build_replay_runner", return_value=(runner, {}, True)),patch("products.web_analytics.dags.cache_warming.QueryCache") as mock_cm,):- mock_cm.return_value.lookup.return_value.entry = None+ mock_cm.return_value.freshness.return_value = Nonewarm_queries_op(dagster.build_op_context(),WarmQueriesConfig(team_ids=[self.team.pk], limit=2),@@ -1003,7 +999,7 @@ class TestWarmQueriesOp(BaseTest):patch("products.web_analytics.dags.cache_warming.build_replay_runner", return_value=(runner, {}, True)),patch("products.web_analytics.dags.cache_warming.QueryCache") as mock_cm,):- mock_cm.return_value.lookup.return_value.entry = None+ mock_cm.return_value.freshness.return_value = Nonewarm_queries_op(dagster.build_op_context(),WarmQueriesConfig(),