:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(aio): Skip the S3 tier for prompt label cache entries (#71967)
Juraj Majerik325dc04cd967
diff --git a/posthog/storage/hypercache.py b/posthog/storage/hypercache.pyindex def3bfcb2c94..7b5f7d69a4a4 100644--- a/posthog/storage/hypercache.py+++ b/posthog/storage/hypercache.py@@ -179,6 +179,7 @@ class HyperCache:batch_load_fn: Optional[Callable[[list[Team]], dict[int, dict]]] = None,enable_etag: bool = False,expiry_sorted_set_key: Optional[str] = None,+ s3_enabled: bool = True,):if token_based and hashed_credential_based:raise ValueError("token_based and hashed_credential_based are mutually exclusive")@@ -196,6 +197,10 @@ class HyperCache:self.batch_load_fn = batch_load_fnself.enable_etag = enable_etagself.expiry_sorted_set_key = expiry_sorted_set_key+ # Redis-only mode: skips the S3 tier on reads, writes, and deletes. For short-TTL+ # entries whose staleness bound depends on expiry — an S3 copy never expires, so+ # it would restore a stale value past every redis expiry.+ self.s3_enabled = s3_enabled# Derive cache_client and redis_url from cache_alias (single source of truth)if cache_alias:@@ -273,12 +278,13 @@ class HyperCache:return json.loads(data), "redis"try:- data = object_storage.read(cache_key, missing_ok=True)- if data:- response = json.loads(data)- HYPERCACHE_CACHE_COUNTER.labels(result="hit_s3", namespace=self.namespace, value=self.value).inc()- self._set_cache_value_redis(key, response)- return response, "s3"+ if self.s3_enabled:+ data = object_storage.read(cache_key, missing_ok=True)+ if data:+ response = json.loads(data)+ HYPERCACHE_CACHE_COUNTER.labels(result="hit_s3", namespace=self.namespace, value=self.value).inc()+ self._set_cache_value_redis(key, response)+ return response, "s3"except (ObjectStorageError, BotoCoreError, ClientError, ValueError) as e:# Any storage-layer failure here (including a misconfigured S3 endpoint that# makes boto3 raise on client construction) must degrade to a cache miss and@@ -523,7 +529,8 @@ class HyperCache:HYPERCACHE_WRITE_SKIPPED_UNCHANGED_COUNTER.labels(namespace=self.namespace, value=self.value).inc()return len(json_data)size = self._set_cache_value_redis(key, data, ttl=ttl, json_data=json_data)- self._set_cache_value_s3(key, data, ttl=ttl)+ if self.s3_enabled:+ self._set_cache_value_s3(key, data, ttl=ttl)# Only track expiry when we have a Team object (avoids DB lookup)if isinstance(key, Team):self._track_expiry(key, data, ttl=ttl)@@ -574,7 +581,7 @@ class HyperCache:self.cache_client.delete(self.get_cache_key(key))# Always delete ETag key to clean up stale ETags from when enable_etag was Trueself.cache_client.delete(self.get_etag_key(key))- if "s3" in kinds:+ if "s3" in kinds and self.s3_enabled:object_storage.delete(self.get_cache_key(key))finally:self._remove_expiry_tracking(key)diff --git a/posthog/storage/llm_prompt_cache.py b/posthog/storage/llm_prompt_cache.pyindex c5c114b27287..5e0145594ca8 100644--- a/posthog/storage/llm_prompt_cache.py+++ b/posthog/storage/llm_prompt_cache.py@@ -127,15 +127,16 @@ llm_prompts_hypercache = HyperCache(# and version entries hold immutable content, but a label entry is a resolved pointer:# a cache fill racing an invalidation can store an already-stale resolution that the# generation marker cannot detect. The short TTL bounds that staleness to a minute;-# signal invalidation still makes the common path near-instant. Label entries are also-# kept out of S3 (redis-only writes) — an S3 copy has no TTL, so a stale fill there-# would keep restoring itself past every redis expiry.+# signal invalidation still makes the common path near-instant. The S3 tier is disabled+# entirely — an S3 copy has no TTL, so a stale fill there would keep restoring itself+# past every redis expiry, and reads would pay a guaranteed-miss S3 round-trip.llm_prompts_label_hypercache = HyperCache(namespace="llm_prompts",value="prompt.json",load_fn=_load_prompt_cache,cache_ttl=settings.LLM_PROMPTS_LABEL_CACHE_TTL,cache_miss_ttl=settings.LLM_PROMPTS_LABEL_CACHE_TTL,+ s3_enabled=False,)@@ -178,7 +179,7 @@ def get_prompt_by_name_from_cache(return Nonelabeled_prompt = _serialize_labeled_prompt(db_labeled, label)try:- llm_prompts_label_hypercache.set_cache_value_redis_only(label_key, labeled_prompt)+ llm_prompts_label_hypercache.set_cache_value(label_key, labeled_prompt)except Exception as err:capture_exception(err)diff --git a/posthog/storage/test/test_llm_prompt_cache.py b/posthog/storage/test/test_llm_prompt_cache.pyindex c03911fd5f4d..cf28024f445e 100644--- a/posthog/storage/test/test_llm_prompt_cache.py+++ b/posthog/storage/test/test_llm_prompt_cache.py@@ -8,6 +8,7 @@ from django.utils import timezonefrom posthog.storage.llm_prompt_cache import (_serialize_prompt,get_prompt_by_name_from_cache,+ invalidate_prompt_label_cache,invalidate_prompt_latest_cache,invalidate_prompt_name_caches,invalidate_prompt_version_cache,@@ -15,7 +16,7 @@ from posthog.storage.llm_prompt_cache import ()from posthog.storage.llm_prompt_cache_keys import prompt_latest_cache_key-from products.ai_observability.backend.models.llm_prompt import LLMPrompt+from products.ai_observability.backend.models.llm_prompt import LLMPrompt, LLMPromptLabelclass TestLLMPromptCache(BaseTest):@@ -300,3 +301,24 @@ class TestLLMPromptCacheSignals(BaseTest):self.assertTrue(mock_on_commit.called)mock_invalidate_latest.assert_called_with(self.team.id, "signal-prompt")mock_invalidate_version.assert_called_with(self.team.id, "signal-prompt", 1)++ def test_label_cache_never_touches_object_storage(self):+ prompt = LLMPrompt.objects.create(+ team=self.team, name="labeled-prompt", prompt="content", version=1, is_latest=True+ )+ LLMPromptLabel.objects.create(team=self.team, prompt_name="labeled-prompt", name="production", prompt=prompt)+ # Warm the latest entry (the label path reads it for the generation marker); it+ # belongs to the S3-enabled instance, so it must be a redis hit inside the patch.+ get_prompt_by_name_from_cache(self.team, "labeled-prompt")++ # Miss -> DB fill -> hit -> invalidation: none of it may reach S3, or a stale+ # fill would persist there without a TTL and resurrect past every redis expiry.+ with patch("posthog.storage.hypercache.object_storage") as mock_storage:+ fetched = get_prompt_by_name_from_cache(self.team, "labeled-prompt", label="production")+ assert fetched is not None and fetched["label"] == "production"+ get_prompt_by_name_from_cache(self.team, "labeled-prompt", label="production")+ invalidate_prompt_label_cache(self.team.id, "labeled-prompt", "production")++ mock_storage.read.assert_not_called()+ mock_storage.write.assert_not_called()+ mock_storage.delete.assert_not_called()