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(remote-config): force a full sync when a project token changes (#102625)

posthog[bot]4bfeccea3290
diff --git a/posthog/models/remote_config.py b/posthog/models/remote_config.py
index f530183ae5ba..ab804fa561a4 100644
--- a/posthog/models/remote_config.py
+++ b/posthog/models/remote_config.py
@@ -46,6 +46,11 @@ REMOTE_CONFIG_CDN_PURGE_COUNTER = Counter(
logger = structlog.get_logger(__name__)
+
+class RemoteConfigTokenChangeSyncError(Exception):
+ pass
+
+
# Sorted set tracking each team's array/config.json cache-entry expiry, so the hourly
# refresh task can re-stamp entries before the TTL lapses and reads fall through to S3.
REMOTE_CONFIG_CACHE_EXPIRY_SORTED_SET = "remote_config_cache_expiry"
@@ -408,9 +413,13 @@ class RemoteConfig(UUIDTModel):
return site_apps_js + site_functions_js
- def sync(self, force: bool = False, bypass_recordings_quota_cache: bool = False):
+ def sync(self, force: bool = False, bypass_recordings_quota_cache: bool = False) -> bool:
"""
When called we sync to any configured CDNs as well as redis for the /decide endpoint.
+
+ Returns False when the cache write failed. The failure is logged and captured, not raised.
+ Without force, an unchanged config writes Redis only, so True does not mean object storage
+ holds a copy.
"""
logger.info(f"Syncing RemoteConfig for team {self.team_id}")
@@ -426,10 +435,11 @@ class RemoteConfig(UUIDTModel):
except Exception as e:
logger.exception(f"Failed to refresh hypercache TTL for team {self.team_id}")
capture_exception(e)
+ return False
CELERY_TASK_REMOTE_CONFIG_SYNC.labels(result="no_changes").inc()
logger.info(f"RemoteConfig for team {self.team_id} is unchanged")
- return
+ return True
self.config = config
self.synced_at = timezone.now()
@@ -438,22 +448,58 @@ class RemoteConfig(UUIDTModel):
try:
# Pass the already-built config via data= so update_cache() reuses it
# instead of rebuilding via load_fn.
- RemoteConfig.get_hypercache().update_cache(self.team, data=config)
+ cache_written = RemoteConfig.get_hypercache().update_cache(self.team, data=config)
except Exception as e:
logger.exception(f"Failed to update hypercache for team {self.team_id}")
capture_exception(e)
+ cache_written = False
# Invalidate Cloudflare CDN cache
self._purge_cdn()
CELERY_TASK_REMOTE_CONFIG_SYNC.labels(result="success").inc()
+ return cache_written
except Exception as e:
capture_exception(e)
logger.exception(f"Failed to sync RemoteConfig for team {self.team_id}", exception=str(e))
CELERY_TASK_REMOTE_CONFIG_SYNC.labels(result="failure").inc()
raise
- def _purge_cdn(self):
+ def sync_after_token_change(self, old_token: str) -> None:
+ """
+ Re-sync every tier after the team's project API token changed.
+
+ The cache entry is keyed by the token, but the payload holds no token, so a
+ token change leaves the rebuilt config identical and sync() takes the
+ unchanged fast path, which writes Redis only. The new token would then have
+ no object-storage copy to fall back on, and the old token would keep serving
+ until its own entries expire.
+
+ Raises RemoteConfigTokenChangeSyncError when the old token's entry was not evicted or
+ the new token's entry was not written, so that the task retries.
+ """
+ evicted = True
+ try:
+ # hypercache-server reads the secondary Redis, so a failed delete there must fail the sync.
+ RemoteConfig.get_hypercache().delete_cache_entry(old_token, strict_mirror=True)
+ except Exception as e:
+ # A failed eviction leaves the revoked token serving. The new token still needs
+ # its object-storage copy, so the forced sync runs before the failure is raised.
+ logger.exception(f"Failed to evict old token cache entry for team {self.team_id}")
+ capture_exception(e)
+ evicted = False
+
+ self._purge_cdn(token=old_token)
+ try:
+ written = self.sync(force=True)
+ except Exception as e:
+ raise RemoteConfigTokenChangeSyncError(f"Token change sync for team {self.team_id} failed") from e
+ if not evicted or not written:
+ raise RemoteConfigTokenChangeSyncError(
+ f"Token change sync for team {self.team_id} is incomplete: evicted={evicted}, written={written}"
+ )
+
+ def _purge_cdn(self, token: str | None = None):
if (
not settings.REMOTE_CONFIG_CDN_PURGE_ENDPOINT
or not settings.REMOTE_CONFIG_CDN_PURGE_TOKEN
@@ -461,13 +507,14 @@ class RemoteConfig(UUIDTModel):
):
return
+ token = token or self.team.api_token
data: dict[str, Any] = {"files": []}
for domain in settings.REMOTE_CONFIG_CDN_PURGE_DOMAINS:
# Check if the domain starts with https:// and if not add it
full_domain = domain if domain.startswith("https://") else f"https://{domain}"
- data["files"].append({"url": f"{full_domain}/array/{self.team.api_token}/config"})
- data["files"].append({"url": f"{full_domain}/array/{self.team.api_token}/config.js"})
+ data["files"].append({"url": f"{full_domain}/array/{token}/config"})
+ data["files"].append({"url": f"{full_domain}/array/{token}/config.js"})
logger.info(f"Purging CDN for team {self.team_id}", {"data": data})
diff --git a/posthog/models/team/team.py b/posthog/models/team/team.py
index 81e86df46c2a..5a8d1aa17dc2 100644
--- a/posthog/models/team/team.py
+++ b/posthog/models/team/team.py
@@ -970,8 +970,13 @@ class Team(UUIDTClassicModel):
def _persist_api_token_change(self, *, old_token: str, user: "User", is_impersonated_session: bool) -> None:
from posthog.models.activity_logging.activity_log import Change, Detail, log_activity
+ from posthog.tasks.remote_config import update_team_remote_config
self.save()
+ # The post_save receiver also dispatches the plain remote config sync for this save.
+ # A worker that predates the old_token argument rejects this task. That worker still
+ # runs the plain sync, which writes the new token's Redis entry.
+ transaction.on_commit(lambda: update_team_remote_config.delay(self.id, old_token=old_token))
set_team_in_cache(old_token, None)
set_team_in_cache(self.api_token, self)
log_activity(
diff --git a/posthog/models/test/test_remote_config.py b/posthog/models/test/test_remote_config.py
index 5df56630fa13..625c77feb763 100644
--- a/posthog/models/test/test_remote_config.py
+++ b/posthog/models/test/test_remote_config.py
@@ -6,14 +6,20 @@ import pytest
from posthog.test.base import BaseTest
from unittest.mock import MagicMock, call, patch
+from django.core.cache import caches
from django.test import override_settings
from django.utils import timezone
from parameterized import parameterized
+from posthog.caching.flags_redis_cache import FLAGS_DEDICATED_CACHE_ALIAS
from posthog.models.integration import Integration
from posthog.models.project import Project
-from posthog.models.remote_config import REMOTE_CONFIG_CACHE_EXPIRY_SORTED_SET, RemoteConfig
+from posthog.models.remote_config import (
+ REMOTE_CONFIG_CACHE_EXPIRY_SORTED_SET,
+ RemoteConfig,
+ RemoteConfigTokenChangeSyncError,
+)
from products.actions.backend.models.action import Action
from products.cdp.backend.models.hog_functions.hog_function import HogFunction
@@ -796,10 +802,6 @@ class TestRemoteConfigCaching(_RemoteConfigBase):
assert RemoteConfig.get_hypercache().get_from_cache(self.team.api_token) is not None
def test_hypercache_uses_dedicated_cache_when_alias_registered(self):
- from django.core.cache import caches
-
- from posthog.caching.flags_redis_cache import FLAGS_DEDICATED_CACHE_ALIAS
-
# When cache_alias is set, HyperCache.__init__ calls get_cache_writer_url which
# reads CACHES[alias]["LOCATION"]. Provide a stub URL to satisfy that lookup;
# the in-memory backend ignores it.
@@ -854,6 +856,76 @@ class TestRemoteConfigCaching(_RemoteConfigBase):
)
+class TestRemoteConfigTokenChange(_RemoteConfigBase):
+ def setUp(self):
+ super().setUp()
+ self.hypercache = RemoteConfig.get_hypercache()
+ self.old_token = self.team.api_token
+ self.team.api_token = "phc_new_token"
+ self.team.save()
+ self.hypercache.clear_cache("phc_new_token")
+
+ def test_token_change_writes_the_new_token_to_every_tier(self):
+ with patch("posthog.storage.object_storage.write") as mock_s3_write:
+ self.remote_config.sync_after_token_change(self.old_token)
+
+ assert self.hypercache.get_from_cache_with_source("phc_new_token")[1] == "redis"
+ written_keys = [call.args[0] for call in mock_s3_write.call_args_list]
+ assert self.hypercache.get_cache_key("phc_new_token") in written_keys
+
+ def test_token_change_drops_the_old_token_entry(self):
+ self.hypercache.set_cache_value_redis_only(self.old_token, self.remote_config.config)
+
+ with patch("posthog.storage.object_storage.delete") as mock_s3_delete:
+ self.remote_config.sync_after_token_change(self.old_token)
+
+ assert self.hypercache.get_from_cache_with_source(self.old_token)[1] != "redis"
+ mock_s3_delete.assert_called_once_with(self.hypercache.get_cache_key(self.old_token))
+
+ @patch("posthog.models.remote_config.requests.post")
+ def test_token_change_purges_both_tokens_from_the_cdn(self, mock_post):
+ with self.settings(
+ REMOTE_CONFIG_CDN_PURGE_ENDPOINT="https://api.cloudflare.com/client/v4/zones/MY_ZONE_ID/purge_cache",
+ REMOTE_CONFIG_CDN_PURGE_TOKEN="MY_TOKEN",
+ REMOTE_CONFIG_CDN_PURGE_DOMAINS=["cdn.posthog.com"],
+ ):
+ self.remote_config.sync_after_token_change(self.old_token)
+
+ purged = [file["url"] for call in mock_post.call_args_list for file in call.kwargs["json"]["files"]]
+ assert f"https://cdn.posthog.com/array/{self.old_token}/config" in purged
+ assert "https://cdn.posthog.com/array/phc_new_token/config" in purged
+
+ @parameterized.expand(
+ [
+ ("old_token_eviction", "posthog.storage.object_storage.delete"),
+ ("new_token_durable_write", "posthog.storage.object_storage.write"),
+ ]
+ )
+ def test_token_change_raises_when_a_tier_fails(self, _name, failing_call):
+ with patch(failing_call, side_effect=Exception("object storage unavailable")):
+ with pytest.raises(RemoteConfigTokenChangeSyncError):
+ self.remote_config.sync_after_token_change(self.old_token)
+
+ assert self.hypercache.get_from_cache_with_source("phc_new_token")[1] == "redis"
+
+ @override_settings(
+ CACHES={
+ "default": {
+ "BACKEND": "django.core.cache.backends.locmem.LocMemCache",
+ "LOCATION": "token-change-shared-cache",
+ },
+ FLAGS_DEDICATED_CACHE_ALIAS: {
+ "BACKEND": "django.core.cache.backends.locmem.LocMemCache",
+ "LOCATION": "token-change-flags-cache",
+ },
+ }
+ )
+ def test_token_change_raises_when_the_shared_redis_delete_fails(self):
+ with patch.object(caches["default"], "delete", side_effect=ConnectionError("shared redis down")):
+ with pytest.raises(RemoteConfigTokenChangeSyncError):
+ self.remote_config.sync_after_token_change(self.old_token)
+
+
class TestRemoteConfigRaceCondition(_RemoteConfigBase):
"""Test for the race condition where post_save signal fires before transaction commits."""
diff --git a/posthog/models/test/test_team_model.py b/posthog/models/test/test_team_model.py
index c3030a67aa73..5282212f178d 100644
--- a/posthog/models/test/test_team_model.py
+++ b/posthog/models/test/test_team_model.py
@@ -423,14 +423,18 @@ class TestTeamSetTokenAndSave(BaseTest):
self.team.refresh_from_db()
assert self.team.api_token == "phc_old_token_value"
+ @patch("posthog.tasks.remote_config.update_team_remote_config.delay")
@patch("posthog.tasks.integrations.push_vercel_secrets.delay")
@patch("posthog.models.team.team.set_team_in_cache")
- def test_set_token_and_save_success_runs_full_side_effect_chain(self, mock_set_cache, mock_push_vercel) -> None:
- self.team.set_token_and_save(
- new_token="phc_new_token_value",
- user=self.user,
- is_impersonated_session=False,
- )
+ def test_set_token_and_save_success_runs_full_side_effect_chain(
+ self, mock_set_cache, mock_push_vercel, mock_sync_remote_config
+ ) -> None:
+ with self.captureOnCommitCallbacks(execute=True):
+ self.team.set_token_and_save(
+ new_token="phc_new_token_value",
+ user=self.user,
+ is_impersonated_session=False,
+ )
self.team.refresh_from_db()
assert self.team.api_token == "phc_new_token_value"
@@ -441,6 +445,10 @@ class TestTeamSetTokenAndSave(BaseTest):
mock_push_vercel.assert_called_once_with(self.team.id)
+ # Without the old token, the sync rewrites array/config.json in Redis only.
+ # The revoked token then keeps serving.
+ mock_sync_remote_config.assert_any_call(self.team.id, old_token="phc_old_token_value")
+
log_entry = ActivityLog.objects.get(scope="Team", item_id=str(self.team.pk), activity="updated")
assert log_entry.detail is not None
change = log_entry.detail["changes"][0]
diff --git a/posthog/storage/hypercache.py b/posthog/storage/hypercache.py
index 4a1e067b3fc9..d79be7e2772f 100644
--- a/posthog/storage/hypercache.py
+++ b/posthog/storage/hypercache.py
@@ -606,13 +606,18 @@ class HyperCache:
"""Test helper alias for delete_cache_entry."""
return self.delete_cache_entry(key, kinds)
- def delete_cache_entry(self, key: KeyType, kinds: Optional[list[str]] = None):
+ def delete_cache_entry(self, key: KeyType, kinds: Optional[list[str]] = None, *, strict_mirror: bool = False):
"""Hard-delete an entry from the given tiers (default redis + s3).
Production-safe: the gateway credential projection uses this to revoke a
credential's blob immediately — a missing key fails closed at the gateway.
+
+ A failed Redis delete raises after the object-storage delete ran. With strict_mirror,
+ a failed delete on the secondary cache raises too. Otherwise the secondary delete is
+ best-effort.
"""
kinds = kinds or ["redis", "s3"]
+ redis_error: Exception | None = None
try:
cache_key = self.get_cache_key(key)
if "redis" in kinds:
@@ -634,17 +639,25 @@ class HyperCache:
raise first_error
# Mirror first so a primary failure cannot block the secondary.
- self._mirror_to_secondary(delete_each)
- delete_each(self.cache_client)
+ mirror_error = self._mirror_to_secondary(delete_each)
+ try:
+ delete_each(self.cache_client)
+ except Exception as e:
+ redis_error = e
+ else:
+ redis_error = mirror_error if strict_mirror else None
+ # The object-storage copy has no TTL, so a Redis failure must not skip its delete.
if "s3" in kinds and self.s3_enabled:
object_storage.delete(cache_key)
+ if redis_error is not None:
+ raise redis_error
finally:
self._remove_expiry_tracking(key)
- def _mirror_to_secondary(self, op: Callable[..., None]) -> None:
- """Best-effort mirror op; failures are logged and captured, never propagated."""
+ def _mirror_to_secondary(self, op: Callable[..., None]) -> Exception | None:
+ """Best-effort mirror op; failures are logged, captured and returned, never raised."""
if self.secondary_cache_client is None:
- return
+ return None
try:
op(self.secondary_cache_client)
except Exception as e:
@@ -658,6 +671,8 @@ class HyperCache:
exc_info=True,
)
capture_exception(e)
+ return e
+ return None
def _set_cache_value_redis(
self,
diff --git a/posthog/storage/test/test_hypercache.py b/posthog/storage/test/test_hypercache.py
index 5b5093f2e8e0..b510049c3e85 100644
--- a/posthog/storage/test/test_hypercache.py
+++ b/posthog/storage/test/test_hypercache.py
@@ -919,6 +919,29 @@ class TestHyperCacheSecondaryCache(BaseTest):
getattr(call, client).delete(key) for client in ("secondary", "primary") for key in sequence
]
+ @parameterized.expand(
+ [
+ ("primary", "cache_client", False),
+ ("strict_secondary", "secondary_cache_client", True),
+ ]
+ )
+ def test_delete_raises_a_redis_failure_after_every_tier(self, _name, failing_client, strict_mirror):
+ hc = HyperCache(namespace="test", value="value", load_fn=lambda team: self.sample_data, enable_etag=True)
+ hc.cache_client = Mock()
+ hc.secondary_cache_client = Mock()
+ redis_error = ConnectionError("redis down")
+ getattr(hc, failing_client).delete.side_effect = redis_error
+ team_id = self.team.id
+
+ with patch.object(object_storage, "delete") as mock_s3_delete:
+ with pytest.raises(ConnectionError) as raised:
+ hc.delete_cache_entry(team_id, strict_mirror=strict_mirror)
+
+ assert raised.value is redis_error
+ assert hc.cache_client.delete.call_count == 3
+ assert hc.secondary_cache_client.delete.call_count == 3
+ mock_s3_delete.assert_called_once_with(hc.get_cache_key(team_id))
+
def test_unknown_secondary_alias_falls_back_to_no_op(self):
"""A secondary_cache_alias not in settings.CACHES is silently ignored."""
diff --git a/posthog/tasks/remote_config.py b/posthog/tasks/remote_config.py
index a16ac0d26f99..9afc5180bd2d 100644
--- a/posthog/tasks/remote_config.py
+++ b/posthog/tasks/remote_config.py
@@ -5,7 +5,7 @@ from django.conf import settings
import structlog
from celery import shared_task
-from posthog.models.remote_config import RemoteConfig
+from posthog.models.remote_config import RemoteConfig, RemoteConfigTokenChangeSyncError
from posthog.models.team import Team
from posthog.scoping_audit import skip_team_scope_audit
from posthog.storage.remote_config_cache import cleanup_stale_expiry_tracking, get_cache_stats, refresh_expiring_caches
@@ -19,9 +19,14 @@ logger = structlog.get_logger(__name__)
queue=CeleryQueue.DEFAULT.value,
soft_time_limit=300,
time_limit=360,
+ autoretry_for=(RemoteConfigTokenChangeSyncError,),
+ max_retries=3,
+ retry_backoff=30,
)
@skip_team_scope_audit
-def update_team_remote_config(team_id: int, bypass_recordings_quota_cache: bool = False) -> None:
+def update_team_remote_config(
+ team_id: int, bypass_recordings_quota_cache: bool = False, old_token: str | None = None
+) -> None:
try:
team = Team.objects.get(id=team_id)
except Team.DoesNotExist:
@@ -33,7 +38,10 @@ def update_team_remote_config(team_id: int, bypass_recordings_quota_cache: bool
except RemoteConfig.DoesNotExist:
remote_config = RemoteConfig(team=team)
- remote_config.sync(bypass_recordings_quota_cache=bypass_recordings_quota_cache)
+ if old_token:
+ remote_config.sync_after_token_change(old_token)
+ else:
+ remote_config.sync(bypass_recordings_quota_cache=bypass_recordings_quota_cache)
@shared_task(ignore_result=True, queue=CeleryQueue.DEFAULT.value)
diff --git a/posthog/tasks/test/test_remote_config.py b/posthog/tasks/test/test_remote_config.py
index c4fb6bfdb1fc..3a7e3252ad2f 100644
--- a/posthog/tasks/test/test_remote_config.py
+++ b/posthog/tasks/test/test_remote_config.py
@@ -1,14 +1,16 @@
from collections.abc import Callable
+import pytest
from posthog.test.base import BaseTest
from unittest.mock import MagicMock, patch
from django.test import SimpleTestCase, override_settings
+from celery.exceptions import Retry
from parameterized import parameterized
from posthog.models.project import Project
-from posthog.models.remote_config import RemoteConfig
+from posthog.models.remote_config import RemoteConfig, RemoteConfigTokenChangeSyncError
from posthog.storage.cache_expiry_manager import CacheRefreshCounts
from posthog.tasks.remote_config import (
cleanup_stale_remote_config_expiry_tracking_task,
@@ -85,6 +87,12 @@ class TestRemoteConfig(BaseTest):
update_team_remote_config(self.team.id)
mock_sync.assert_called_once_with(bypass_recordings_quota_cache=False)
+ @patch.object(RemoteConfig, "sync_after_token_change", side_effect=RemoteConfigTokenChangeSyncError)
+ def test_update_team_remote_config_retries_an_incomplete_token_change(self, mock_sync: MagicMock) -> None:
+ with pytest.raises(Retry):
+ update_team_remote_config.apply(args=[self.team.id], kwargs={"old_token": "phc_old_token"})
+ mock_sync.assert_called_once_with("phc_old_token")
+
class TestRemoteConfigCacheTasks(SimpleTestCase):
@parameterized.expand(