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.

fix(ai-gateway): cluster-safe hypercache deletes; keep credential refresh going (#109537)

Brandonafc948686826
diff --git a/posthog/storage/gateway_credential_cache.py b/posthog/storage/gateway_credential_cache.py
index 5ba420071b6f..0e65bfa4c7bb 100644
--- a/posthog/storage/gateway_credential_cache.py
+++ b/posthog/storage/gateway_credential_cache.py
@@ -29,8 +29,11 @@ from django.db import OperationalError
from django.utils import timezone
import structlog
+import redis.exceptions
+from django_redis.exceptions import ConnectionInterrupted
from posthog.caching.ai_gateway_redis_cache import AI_GATEWAY_DEDICATED_CACHE_ALIAS
+from posthog.exceptions_capture import capture_exception
from posthog.models.oauth import OAuthAccessToken
from posthog.models.organization import OrganizationMembership
from posthog.models.project_secret_api_key import ProjectSecretAPIKey
@@ -410,6 +413,11 @@ def clear_gateway_credential(credential_or_hash: Credential | str) -> None:
gateway_credential_hypercache.delete_cache_entry(cache_hash, kinds=["redis"])
+# Infrastructure failures that count toward aborting the refresh.
+_REFRESH_INFRA_ERRORS = (ConnectionInterrupted, redis.exceptions.RedisError, OSError, OperationalError)
+REFRESH_MAX_CONSECUTIVE_INFRA_FAILURES = 3
+
+
def refresh_all_gateway_credentials() -> int:
"""Re-project every credential currently granted llm_gateway:read, keeping entries warm.
@@ -429,11 +437,32 @@ def refresh_all_gateway_credentials() -> int:
)
count = 0
+ failed = 0
+ infra_failures_in_a_row = 0
+ first_error: Exception | None = None
for queryset in querysets:
for credential in queryset.iterator(chunk_size=1000):
- project_gateway_credential(credential, memo)
+ # Skip a failing credential: secret-key blobs expire within hours without this refresh.
+ try:
+ project_gateway_credential(credential, memo)
+ except Exception as e:
+ failed += 1
+ first_error = first_error or e
+ if isinstance(e, _REFRESH_INFRA_ERRORS):
+ infra_failures_in_a_row += 1
+ # An outage: fail the task now, since every remaining credential would time out too.
+ if infra_failures_in_a_row >= REFRESH_MAX_CONSECUTIVE_INFRA_FAILURES:
+ logger.warning("gateway_credential refresh aborted", failed=failed, projected=count)
+ raise
+ continue
count += 1
+ infra_failures_in_a_row = 0
+ if first_error is not None and count == 0:
+ raise first_error
+ if first_error is not None:
+ logger.warning("gateway_credential refresh skipped failing credentials", failed=failed, projected=count)
+ capture_exception(first_error)
return count
diff --git a/posthog/storage/hypercache.py b/posthog/storage/hypercache.py
index 9177c247cfde..4a1e067b3fc9 100644
--- a/posthog/storage/hypercache.py
+++ b/posthog/storage/hypercache.py
@@ -6,6 +6,7 @@ from typing import Optional
from django.conf import settings
from django.core.cache import cache, caches
+from django.core.cache.backends.base import BaseCache
import structlog
import redis.exceptions
@@ -615,15 +616,26 @@ class HyperCache:
try:
cache_key = self.get_cache_key(key)
if "redis" in kinds:
- # One DEL per cache drops the payload and its ETag together. A reader that
- # checks the ETag first would otherwise answer 304 for a payload that is
- # already gone. The ETag key goes even when enable_etag is off, to clear a
- # stale ETag from when it was on.
- redis_keys = [cache_key, self.get_etag_key(key)]
- # Mirror the delete so the secondary never serves an entry the primary dropped,
- # and mirror first so a primary failure cannot block it.
- self._mirror_to_secondary(lambda c: c.delete_many(redis_keys))
- self.cache_client.delete_many(redis_keys)
+ # Single-key DELs: the keys can hash to different cluster slots. The ETag is deleted before
+ # and after the payload so a reader or racing write never sees an ETag without its payload,
+ # and even with enable_etag off, to clear a stale one.
+ etag_key = self.get_etag_key(key)
+ redis_keys = (etag_key, cache_key, etag_key)
+
+ def delete_each(client: BaseCache) -> None:
+ # Every key is attempted, so a failed ETag DEL cannot leave the payload behind.
+ first_error: Exception | None = None
+ for redis_key in redis_keys:
+ try:
+ client.delete(redis_key)
+ except Exception as e:
+ first_error = first_error or e
+ if first_error is not None:
+ raise first_error
+
+ # Mirror first so a primary failure cannot block the secondary.
+ self._mirror_to_secondary(delete_each)
+ delete_each(self.cache_client)
if "s3" in kinds and self.s3_enabled:
object_storage.delete(cache_key)
finally:
diff --git a/posthog/storage/team_llm_gateway_quota_cache.py b/posthog/storage/team_llm_gateway_quota_cache.py
index c46a3f4cab5a..3fa4870d8850 100644
--- a/posthog/storage/team_llm_gateway_quota_cache.py
+++ b/posthog/storage/team_llm_gateway_quota_cache.py
@@ -307,17 +307,11 @@ def _untrack(team_ids: set[int], *, expired_before: float) -> None:
def _missing_blobs(team_ids: set[int]) -> set[int]:
- missing: set[int] = set()
- ordered = sorted(team_ids)
client = team_llm_gateway_quota_hypercache.cache_client
- for start in range(0, len(ordered), 500):
- keys = {
- team_llm_gateway_quota_hypercache.get_cache_key(team_id): team_id
- for team_id in ordered[start : start + 500]
- }
- present = client.get_many(list(keys))
- missing.update(team_id for key, team_id in keys.items() if key not in present)
- return missing
+ # One key per call: a multi-key MGET spans cluster slots.
+ return {
+ team_id for team_id in team_ids if not client.has_key(team_llm_gateway_quota_hypercache.get_cache_key(team_id))
+ }
def reconcile_quota_projection() -> dict[str, int]:
diff --git a/posthog/storage/test/cluster_cache.py b/posthog/storage/test/cluster_cache.py
new file mode 100644
index 000000000000..e75441aa707c
--- /dev/null
+++ b/posthog/storage/test/cluster_cache.py
@@ -0,0 +1,26 @@
+from collections.abc import Iterator
+from contextlib import ExitStack, contextmanager
+
+from unittest.mock import patch
+
+from django.core.cache.backends.base import BaseCache
+
+
+@contextmanager
+def reject_multi_key_commands(client: BaseCache) -> Iterator[None]:
+ """Make `client` raise on any multi-key call, as a cluster does when the keys span slots."""
+
+ def guard(name: str):
+ real = getattr(client, name)
+
+ def call(keys, *args, **kwargs):
+ if len(keys) > 1:
+ raise RuntimeError(f"CROSSSLOT Keys in request don't hash to the same slot ({name})")
+ return real(keys, *args, **kwargs)
+
+ return call
+
+ with ExitStack() as stack:
+ for name in ("delete_many", "get_many", "set_many"):
+ stack.enter_context(patch.object(client, name, side_effect=guard(name)))
+ yield
diff --git a/posthog/storage/test/test_gateway_credential_cache.py b/posthog/storage/test/test_gateway_credential_cache.py
index caba7ebf8f1e..6119fc4fb366 100644
--- a/posthog/storage/test/test_gateway_credential_cache.py
+++ b/posthog/storage/test/test_gateway_credential_cache.py
@@ -1,4 +1,6 @@
import json
+from collections.abc import Callable, Iterator
+from contextlib import contextmanager
from datetime import timedelta
from decimal import Decimal
@@ -22,6 +24,7 @@ from posthog.models.user import User
from posthog.models.utils import SHA256_HASH_PREFIX, generate_random_token, generate_random_token_secret, hash_key_value
from posthog.redis import get_client
from posthog.settings.utils import generate_rsa_private_key_pem
+from posthog.storage import gateway_credential_cache
from posthog.storage.gateway_credential_cache import (
GATEWAY_CREDENTIAL_FIELDS,
GATEWAY_CREDENTIAL_LAST_USED_KEY,
@@ -38,6 +41,7 @@ from posthog.storage.gateway_credential_cache import (
refresh_all_gateway_credentials,
validate_overspend_allowance_usd,
)
+from posthog.storage.test.cluster_cache import reject_multi_key_commands
from posthog.tasks.gateway_credential import (
drain_gateway_credential_last_used_task,
refresh_gateway_credentials,
@@ -501,6 +505,88 @@ class TestGatewayCredentialRefresh(GatewayCredentialTestMixin):
self.assertIsNotNone(self._read_blob(credential_hash(oauth)))
self.assertIsNone(self._read_blob(credential_hash(ignored)))
+ @contextmanager
+ def _failing_blob_writes(
+ self, fails: Callable[[int], bool], error: Callable[[], Exception] = lambda: ConnectionError("redis down")
+ ) -> Iterator[list[str]]:
+ client = hypercache.cache_client
+ real_set = client.set
+ writes: list[str] = []
+
+ def flaky_set(key: str, value: object, timeout: float | None = None) -> None:
+ writes.append(key)
+ if fails(len(writes)):
+ raise error()
+ real_set(key, value, timeout=timeout)
+
+ with patch.object(client, "set", side_effect=flaky_set):
+ yield writes
+
+ def test_refresh_continues_past_a_failing_credential(self):
+ first, _ = self._make_secret_key([GATEWAY_SCOPE])
+ second, _ = self._make_secret_key([GATEWAY_SCOPE])
+
+ with (
+ self._failing_blob_writes(lambda n: n == 1) as writes,
+ patch.object(gateway_credential_cache, "capture_exception") as capture,
+ ):
+ projected = refresh_all_gateway_credentials()
+
+ self.assertEqual(projected, len(writes) - 1)
+ capture.assert_called_once()
+ blobs = [self._read_blob(credential_hash(key)) for key in (first, second)]
+ self.assertEqual(sum(blob is not None for blob in blobs), 1)
+
+ def test_refresh_raises_when_every_credential_fails(self):
+ self._make_secret_key([GATEWAY_SCOPE])
+ self._make_secret_key([GATEWAY_SCOPE])
+ with self._failing_blob_writes(lambda n: True) as writes, self.assertRaises(ConnectionError):
+ refresh_all_gateway_credentials()
+ self.assertEqual(len(writes), 2)
+
+ def test_refresh_resets_the_failure_run_after_a_success(self):
+ for _ in range(3):
+ self._make_secret_key([GATEWAY_SCOPE])
+ with (
+ patch.object(gateway_credential_cache, "REFRESH_MAX_CONSECUTIVE_INFRA_FAILURES", 2),
+ self._failing_blob_writes(lambda n: n % 2 == 1) as writes,
+ patch.object(gateway_credential_cache, "capture_exception") as capture,
+ patch.object(gateway_credential_cache.logger, "warning") as warning,
+ ):
+ projected = refresh_all_gateway_credentials()
+
+ self.assertEqual(projected, 1)
+ self.assertEqual(len(writes), 3)
+ capture.assert_called_once()
+ warning.assert_called_once()
+ self.assertEqual(warning.call_args.kwargs, {"failed": 2, "projected": 1})
+
+ def test_refresh_stops_after_consecutive_infra_failures(self):
+ for _ in range(3):
+ self._make_secret_key([GATEWAY_SCOPE])
+ with (
+ patch.object(gateway_credential_cache, "REFRESH_MAX_CONSECUTIVE_INFRA_FAILURES", 2),
+ self._failing_blob_writes(lambda n: True) as writes,
+ patch.object(gateway_credential_cache.logger, "warning") as warning,
+ self.assertRaises(ConnectionError),
+ ):
+ refresh_all_gateway_credentials()
+ self.assertEqual(len(writes), 2)
+ self.assertEqual(warning.call_args.kwargs, {"failed": 2, "projected": 0})
+
+ def test_refresh_does_not_abort_on_credential_errors(self):
+ for _ in range(4):
+ self._make_secret_key([GATEWAY_SCOPE])
+ with (
+ patch.object(gateway_credential_cache, "REFRESH_MAX_CONSECUTIVE_INFRA_FAILURES", 2),
+ self._failing_blob_writes(lambda n: n <= 3, error=lambda: ValueError("bad policy")) as writes,
+ patch.object(gateway_credential_cache, "capture_exception"),
+ ):
+ projected = refresh_all_gateway_credentials()
+
+ self.assertEqual(projected, 1)
+ self.assertEqual(len(writes), 4)
+
class TestGatewayCredentialTasks(GatewayCredentialTestMixin):
def test_update_task_projects_secret_key(self):
@@ -647,6 +733,50 @@ class TestGatewayCredentialSignals(GatewayCredentialTestMixin):
secret_key.delete()
self.assertIsNone(self._read_blob(cache_hash))
+ @patch("posthog.storage.gateway_credential_signal_handlers.settings")
+ def test_secret_key_delete_clears_cache_on_a_cluster(self, mock_settings):
+ mock_settings.AI_GATEWAY_REDIS_URL = "redis://localhost"
+ secret_key, _ = self._make_secret_key([GATEWAY_SCOPE])
+ project_gateway_credential(secret_key)
+ cache_hash = credential_hash(secret_key)
+
+ with reject_multi_key_commands(hypercache.cache_client):
+ secret_key.delete()
+ self.assertIsNone(self._read_blob(cache_hash))
+
+ @patch("posthog.storage.gateway_credential_signal_handlers.settings")
+ def test_secret_key_delete_clears_cache_when_the_etag_delete_fails(self, mock_settings):
+ mock_settings.AI_GATEWAY_REDIS_URL = "redis://localhost"
+ secret_key, _ = self._make_secret_key([GATEWAY_SCOPE])
+ project_gateway_credential(secret_key)
+ cache_hash = credential_hash(secret_key)
+ client = hypercache.cache_client
+ real_delete = client.delete
+
+ def etag_shard_down(key: str) -> bool:
+ if key.endswith(":etag"):
+ raise ConnectionError("etag shard down")
+ return real_delete(key)
+
+ with patch.object(client, "delete", side_effect=etag_shard_down):
+ secret_key.delete()
+ self.assertIsNone(self._read_blob(cache_hash))
+
+ @patch("posthog.storage.gateway_credential_signal_handlers.transaction")
+ @patch("posthog.storage.gateway_credential_signal_handlers.settings")
+ @patch("posthog.tasks.gateway_credential.update_gateway_credential_cache_task.delay")
+ def test_secret_key_rotation_clears_old_hash_on_a_cluster(self, mock_delay, mock_settings, mock_transaction):
+ mock_settings.AI_GATEWAY_REDIS_URL = "redis://localhost"
+ mock_transaction.on_commit.side_effect = lambda fn: fn()
+ old_token = generate_random_token_secret()
+ secret_key, _ = self._make_secret_key([GATEWAY_SCOPE], token=old_token)
+ project_gateway_credential(secret_key)
+
+ with reject_multi_key_commands(hypercache.cache_client):
+ secret_key.secure_value = hash_key_value(generate_random_token_secret())
+ secret_key.save()
+ self.assertIsNone(self._read_blob(hash_key_value(old_token)))
+
@patch("posthog.storage.gateway_credential_signal_handlers.transaction")
@patch("posthog.storage.gateway_credential_signal_handlers.settings")
@patch("posthog.tasks.gateway_credential.reproject_user_gateway_credentials_task")
diff --git a/posthog/storage/test/test_hypercache.py b/posthog/storage/test/test_hypercache.py
index dec16d1b8b52..5b5093f2e8e0 100644
--- a/posthog/storage/test/test_hypercache.py
+++ b/posthog/storage/test/test_hypercache.py
@@ -2,7 +2,7 @@ import json
import pytest
from posthog.test.base import BaseTest
-from unittest.mock import Mock, patch
+from unittest.mock import Mock, call, patch
from django.core.cache import cache
from django.test import override_settings
@@ -758,7 +758,7 @@ class TestHyperCacheSecondaryCache(BaseTest):
# The mirrored delete must also swallow the failure and still drop the primary entry.
hc.delete_cache_entry(team_id, kinds=["redis"])
- broken.delete_many.assert_called()
+ broken.delete.assert_called()
assert caches["flags_dedicated"].get(cache_key) is None
@parameterized.expand([("etag", True), ("no_etag", False)])
@@ -853,6 +853,72 @@ class TestHyperCacheSecondaryCache(BaseTest):
assert caches["default"].get(cache_key) is None
assert caches["default"].get(etag_key) is None
+ def test_delete_sends_one_key_per_command_etag_around_payload(self):
+ hc = HyperCache(namespace="test", value="value", load_fn=lambda team: self.sample_data, enable_etag=True)
+ hc.cache_client = Mock()
+ hc.cache_client.delete_many.side_effect = RuntimeError("CROSSSLOT Keys in request don't hash to the same slot")
+ team_id = self.team.id
+
+ hc.delete_cache_entry(team_id, kinds=["redis"])
+
+ assert hc.cache_client.delete.call_args_list == [
+ call(hc.get_etag_key(team_id)),
+ call(hc.get_cache_key(team_id)),
+ call(hc.get_etag_key(team_id)),
+ ]
+ hc.cache_client.delete_many.assert_not_called()
+
+ def test_delete_attempts_every_key_and_raises_the_first_error(self):
+ hc = HyperCache(namespace="test", value="value", load_fn=lambda team: self.sample_data, enable_etag=True)
+ hc.cache_client = Mock()
+ first = ConnectionError("etag shard down")
+ hc.cache_client.delete.side_effect = [first, True, ConnectionError("again")]
+ team_id = self.team.id
+
+ with pytest.raises(ConnectionError) as raised:
+ hc.delete_cache_entry(team_id, kinds=["redis"])
+
+ assert raised.value is first
+ assert hc.cache_client.delete.call_args_list == [
+ call(hc.get_etag_key(team_id)),
+ call(hc.get_cache_key(team_id)),
+ call(hc.get_etag_key(team_id)),
+ ]
+
+ def test_delete_leaves_no_etag_when_a_write_lands_between_deletes(self):
+ hc = HyperCache(namespace="test", value="value", load_fn=lambda team: self.sample_data, enable_etag=True)
+ team_id = self.team.id
+ hc.set_cache_value(team_id, self.sample_data)
+ real_delete = hc.cache_client.delete
+ deleted: list[str] = []
+
+ def write_after_first_delete(key: str) -> bool:
+ deleted.append(key)
+ result = real_delete(key)
+ if len(deleted) == 1:
+ hc.set_cache_value(team_id, {"rewritten": True})
+ return result
+
+ with patch.object(hc.cache_client, "delete", side_effect=write_after_first_delete):
+ hc.delete_cache_entry(team_id, kinds=["redis"])
+
+ assert hc.cache_client.get(hc.get_cache_key(team_id)) is None
+ assert hc.cache_client.get(hc.get_etag_key(team_id)) is None
+
+ def test_delete_mirrors_the_same_sequence_before_the_primary(self):
+ hc = HyperCache(namespace="test", value="value", load_fn=lambda team: self.sample_data, enable_etag=True)
+ calls = Mock()
+ hc.cache_client = calls.primary
+ hc.secondary_cache_client = calls.secondary
+ team_id = self.team.id
+
+ hc.delete_cache_entry(team_id, kinds=["redis"])
+
+ sequence = [hc.get_etag_key(team_id), hc.get_cache_key(team_id), hc.get_etag_key(team_id)]
+ assert calls.mock_calls == [
+ getattr(call, client).delete(key) for client in ("secondary", "primary") for key in sequence
+ ]
+
def test_unknown_secondary_alias_falls_back_to_no_op(self):
"""A secondary_cache_alias not in settings.CACHES is silently ignored."""
@@ -1424,7 +1490,7 @@ class TestHyperCacheRemoveExpiryTracking(BaseTest):
hc = self._make_hypercache(token_based=False)
hc.cache_client = Mock()
- hc.cache_client.delete_many.side_effect = ConnectionError("Redis unavailable")
+ hc.cache_client.delete.side_effect = ConnectionError("Redis unavailable")
with pytest.raises(ConnectionError):
hc.clear_cache(42)
diff --git a/posthog/storage/test/test_team_llm_gateway_quota_cache.py b/posthog/storage/test/test_team_llm_gateway_quota_cache.py
index 28b5db9db0e8..16bdaeadbb06 100644
--- a/posthog/storage/test/test_team_llm_gateway_quota_cache.py
+++ b/posthog/storage/test/test_team_llm_gateway_quota_cache.py
@@ -34,6 +34,7 @@ from posthog.storage.team_llm_gateway_quota_cache import (
reconcile_quota_projection,
team_llm_gateway_quota_hypercache as hypercache,
)
+from posthog.storage.test.cluster_cache import reject_multi_key_commands
from ee.billing.quota_limiting import (
QuotaLimitingCaches,
@@ -192,6 +193,16 @@ class TestProjectTeamQuota(QuotaProjectionTestMixin):
self.assertIsNone(hypercache.cache_client.get(hypercache.get_cache_key(self.team)))
self.assertNotIn(self.team.id, projected_team_ids())
+ def test_lifting_the_limit_deletes_the_blob_on_a_cluster(self, mock_settings):
+ self._enable(mock_settings)
+ _limit(self.team, QuotaResource.AI_CREDITS, (timezone.now() + timedelta(days=3)).timestamp())
+ project_team_quota(self.team)
+
+ _unlimit(self.team, QuotaResource.AI_CREDITS)
+ with reject_multi_key_commands(hypercache.cache_client):
+ self.assertIs(project_team_quota(self.team), False)
+ self.assertIsNone(hypercache.cache_client.get(hypercache.get_cache_key(self.team)))
+
def test_expired_score_is_ignored(self, mock_settings):
self._enable(mock_settings)
_limit(self.team, QuotaResource.AI_CREDITS, (timezone.now() - timedelta(seconds=5)).timestamp())
@@ -474,6 +485,18 @@ class TestReconcileQuotaProjection(QuotaProjectionTestMixin):
self.assertEqual(second, {"candidates": 1, "written": 1, "cleared": 0, "failed": 0})
self.assertEqual(projected_team_ids(), {self.team.id})
+ def test_reconcile_reads_one_key_per_command(self, mock_settings):
+ mock_settings.AI_GATEWAY_REDIS_URL = _GATEWAY_REDIS_URL
+ # A reachable deactivated org with no blob is the path that checks blob presence.
+ Organization.objects.filter(pk=self.organization.pk).update(is_active=False)
+ with patch.object(
+ hypercache.cache_client, "get_many", side_effect=RuntimeError("CROSSSLOT Keys in request don't hash")
+ ):
+ reconcile_quota_projection()
+ blob = get_team_quota_blob(self.team)
+ assert blob is not None
+ self.assertTrue(blob["org_deactivated"])
+
def test_reconcile_counts_failed_writes_and_clears_apart(self, mock_settings):
mock_settings.AI_GATEWAY_REDIS_URL = _GATEWAY_REDIS_URL
stray = Team.objects.create(organization=self.organization, name="stray")