: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(billing): trigger RemoteConfig sync on recordings quota transitions (#59394)
Abhischek53746c4f22ac
diff --git a/ee/billing/quota_limiting.py b/ee/billing/quota_limiting.pyindex ea4320ea613b..80dfd539ea9e 100644--- a/ee/billing/quota_limiting.py+++ b/ee/billing/quota_limiting.py@@ -1,6 +1,6 @@import copyimport json-from collections.abc import Callable, Mapping, Sequence+from collections.abc import Callable, Iterable, Mapping, Sequencefrom datetime import datetime, timedeltafrom enum import Enumfrom time import time@@ -156,6 +156,8 @@ def replace_limited_team_tokens(def add_limited_team_tokens(resource: QuotaResource, tokens: Mapping[str, int], cache_key: QuotaLimitingCaches) -> None:+ if not tokens:+ returnredis_client = get_client()redis_client.zadd(f"{cache_key.value}{resource.value}", tokens) # type: ignore # (zadd takes a Mapping[str, int] but the derived Union type is wrong)@@ -184,18 +186,56 @@ def list_limited_team_attributes(resource: QuotaResource, cache_key: QuotaLimitireturn [x.decode("utf-8") for x in results]+def list_team_attributes_in_zset(resource: QuotaResource, cache_key: QuotaLimitingCaches) -> list[str]:+ """+ Returns every team attribute currently present in the Redis zset for `resource`,+ INCLUDING members whose scores have already expired. Reads Redis directly (uncached) so+ callers see same-tick mutations.+ """+ redis_client = get_client()+ results = redis_client.zrange(f"{cache_key.value}{resource.value}", 0, -1)+ return [x.decode("utf-8") for x in results]+++def _get_previous_recordings_zset_tokens() -> set[str]:+ """Shared accessor for the raw recordings quota-limiter zset; see `list_team_attributes_in_zset`."""+ return set(list_team_attributes_in_zset(QuotaResource.RECORDINGS, QuotaLimitingCaches.QUOTA_LIMITER_CACHE_KEY))++def is_team_limited(team_api_token: str, resource: QuotaResource, cache_key: QuotaLimitingCaches) -> bool:limited_team_attributes = list_limited_team_attributes(resource, cache_key)return team_api_token in limited_team_attributes+def dispatch_recordings_remote_config_sync(team_ids: Iterable[int]) -> None:+ """+ Triggers a `RemoteConfig` rebuild for each team after its recordings quota-limit state+ transitions on `QUOTA_LIMITER_CACHE_KEY`. Passes `bypass_recordings_quota_cache=True` so+ the rebuild sees the just-mutated Redis state — see `list_team_attributes_in_zset`.+ """+ from posthog.tasks.remote_config import update_team_remote_config++ for team_id in team_ids:+ try:+ update_team_remote_config.apply_async(+ args=[team_id],+ kwargs={"bypass_recordings_quota_cache": True},+ countdown=35,+ )+ except Exception as e:+ capture_exception(e, {"team_id": team_id})++# -------------------------------------------------------------------------------------------------# MAIN FUNCTIONS# -------------------------------------------------------------------------------------------------def org_quota_limited_until(- organization: Organization, resource: QuotaResource, previously_quota_limited_team_tokens: list[str]+ organization: Organization,+ resource: QuotaResource,+ previously_quota_limited_team_tokens: list[str],+ team_tokens: Sequence[str] | None = None,) -> Optional[OrgQuotaLimitingInformation]:if not organization.usage:return None@@ -271,7 +311,8 @@ def org_quota_limited_until()return None- team_tokens = get_team_attribute_by_quota_resource(organization)+ if team_tokens is None:+ team_tokens = get_team_attribute_by_quota_resource(organization)team_being_limited = any(x in previously_quota_limited_team_tokens for x in team_tokens)# 2a. already being limited@@ -506,6 +547,16 @@ def update_org_billing_quotas(organization: Organization):if not organization.usage:return None+ teams_by_token: dict[str, int] = {+ api_token: team_id for team_id, api_token in organization.teams.values_list("id", "api_token") if api_token+ }+ team_attributes: list[str] = list(teams_by_token.keys())+ if not team_attributes:+ logger.debug("quota_limiting_no_team_tokens", organization_id=str(organization.id))+ team_attributes_set: set[str] = set(team_attributes)+ prev_recordings_zset_tokens: set[str] = _get_previous_recordings_zset_tokens() & team_attributes_set+ recordings_transitioned_team_ids: set[int] = set()+for resource in QuotaResource:previously_quota_limited_team_tokens = list_limited_team_attributes(resource,@@ -514,8 +565,15 @@ def update_org_billing_quotas(organization: Organization):)# Get the quota limiting information (e.g. {"quota_limited_until": 1737867600, "quota_limiting_suspended_until": 1737867600})- team_attributes = get_team_attribute_by_quota_resource(organization)- result = org_quota_limited_until(organization, resource, previously_quota_limited_team_tokens)+ result = org_quota_limited_until(organization, resource, previously_quota_limited_team_tokens, team_attributes)++ if resource == QuotaResource.RECORDINGS:+ now_limited_for_recordings = bool(result and result.get("quota_limited_until"))+ now_limited_tokens: set[str] = team_attributes_set if now_limited_for_recordings else set()+ for token in prev_recordings_zset_tokens ^ now_limited_tokens:+ team_id = teams_by_token.get(token)+ if team_id is not None:+ recordings_transitioned_team_ids.add(team_id)if result:quota_limited_until = result.get("quota_limited_until")@@ -540,6 +598,9 @@ def update_org_billing_quotas(organization: Organization):remove_limited_team_tokens(resource, team_attributes, QuotaLimitingCaches.QUOTA_LIMITER_CACHE_KEY)remove_limited_team_tokens(resource, team_attributes, QuotaLimitingCaches.QUOTA_LIMITING_SUSPENDED_KEY)+ if recordings_transitioned_team_ids:+ dispatch_recordings_remote_config_sync(recordings_transitioned_team_ids)+def set_org_usage_summary(organization: Organization,@@ -918,6 +979,8 @@ def update_all_orgs_billing_quotas(previously_quota_limiting_suspended_team_tokens[resource.value] = list_limited_team_attributes(resource, QuotaLimitingCaches.QUOTA_LIMITING_SUSPENDED_KEY)++ previously_recordings_zset_tokens: set[str] = _get_previous_recordings_zset_tokens()# We have the teams that are currently under quota limits# previously_quota_limited_team_tokens is a dict of resources to team tokens from redis (e.g. {"events": ["phc_123", "phc_456"], "exceptions": ["phc_123", "phc_456"], "recordings": ["phc_123", "phc_456"], "rows_synced": ["phc_123", "phc_456"], "feature_flag_requests": ["phc_123", "phc_456"], "api_queries_read_bytes": ["phc_123", "phc_456"], "survey_responses": ["phc_123", "phc_456"]})# previously_quota_limiting_suspended_team_tokens has the same shape, drawn from the suspension Redis set.@@ -1045,23 +1108,37 @@ def update_all_orgs_billing_quotas(quota_limited_teams: dict[str, dict[str, int]] = {x.value: {} for x in QuotaResource}quota_limiting_suspended_teams: dict[str, dict[str, int]] = {x.value: {} for x in QuotaResource}+ recordings_transitioned_team_ids: set[int] = set()+ recordings_field = QuotaResource.RECORDINGS.value# Convert the org ids to team tokensfor team in teams:for field in quota_limited_orgs:org_id = str(team.organization.id)+ team_was_in_recordings_zset = team.api_token in previously_recordings_zset_tokensif org_id in quota_limited_orgs[field]:quota_limited_teams[field][team.api_token] = quota_limited_orgs[field][org_id]# If the team was not previously quota limited, we add it to the list of orgs that were addedif team.api_token not in previously_quota_limited_team_tokens[field]:orgs_with_changes.add(org_id)+ if field == recordings_field and not team_was_in_recordings_zset:+ recordings_transitioned_team_ids.add(team.id)elif org_id in quota_limiting_suspended_orgs[field]:quota_limiting_suspended_teams[field][team.api_token] = quota_limiting_suspended_orgs[field][org_id]+ if field == recordings_field and team_was_in_recordings_zset:+ recordings_transitioned_team_ids.add(team.id)else:# If the team was previously quota limited, we add it to the list of orgs that were removedif team.api_token in previously_quota_limited_team_tokens[field]:orgs_with_changes.add(org_id)+ # Decoupled from `orgs_with_changes` on purpose: the recordings RemoteConfig+ # rebuild must also fire for tokens whose scores already expired naturally —+ # those won't appear in the cached `previously_quota_limited_team_tokens` view,+ # but they are still physically in the zset and the persisted config still+ # carries `quotaLimited: ["recordings"]` until we rebuild.+ if field == recordings_field and team_was_in_recordings_zset:+ recordings_transitioned_team_ids.add(team.id)# Now we have the teams that are currently under quota limits# quota_limited_teams is a dict of resources to team tokens (e.g. {"events": {"phc_123": 1737867600}, "exceptions": {"phc_123": 1737867600}, "recordings": {"phc_123": 1737867600}, "rows_synced": {"phc_123": 1737867600}, "feature_flag_requests": {"phc_123": 1737867600}, "api_queries_read_bytes": {"phc_123": 1737867600}, "survey_responses": {"phc_123": 1737867600}})@@ -1105,6 +1182,9 @@ def update_all_orgs_billing_quotas(if progress_callback:progress_callback("redis_done", f"duration={redis_duration_s}s", "")+ if recordings_transitioned_team_ids:+ dispatch_recordings_remote_config_sync(recordings_transitioned_team_ids)+total_duration_s = time() - total_startlogger.info("quota_limiting_run",diff --git a/ee/billing/test/test_quota_limiting.py b/ee/billing/test/test_quota_limiting.pyindex 7fce5e09f308..23131fc3ed1f 100644--- a/ee/billing/test/test_quota_limiting.py+++ b/ee/billing/test/test_quota_limiting.py@@ -2077,6 +2077,152 @@ class TestQuotaLimiting(BaseTest):# flip it to `in quota_limited_orgs["events"]` in the same PR.assert str(org_id) not in quota_limited_orgs["events"]+ # `update_team_remote_config` is lazy-imported inside `dispatch_recordings_remote_config_sync`,+ # so patches target `posthog.tasks.remote_config.update_team_remote_config` directly.++ @parameterized.expand(+ [+ (+ "newly_limited",+ None,+ {"events": {"usage": 1, "limit": 100}, "recordings": {"usage": 6_000, "limit": 5_000}},+ 1,+ ),+ (+ "active_member_becomes_unlimited",+ 10_000,+ {"events": {"usage": 1, "limit": 100}, "recordings": {"usage": 1, "limit": 5_000}},+ 1,+ ),+ (+ "expired_member_becomes_unlimited",+ -10_000,+ {"events": {"usage": 1, "limit": 100}, "recordings": {"usage": 1, "limit": 5_000}},+ 1,+ ),+ (+ "still_limited_no_transition",+ 10_000,+ {"events": {"usage": 1, "limit": 100}, "recordings": {"usage": 6_000, "limit": 5_000}},+ 0,+ ),+ (+ "non_recordings_resource_over_limit",+ None,+ {"events": {"usage": 1_000_000, "limit": 100}, "recordings": {"usage": 0, "limit": 5_000}},+ 0,+ ),+ ]+ )+ @freeze_time("2021-01-25T00:00:00Z")+ @patch("posthog.tasks.remote_config.update_team_remote_config")+ def test_update_org_billing_quotas_recordings_remote_config_dispatch(+ self,+ _name,+ prepopulate_zset_score_offset,+ usage_overrides,+ expected_dispatch_count,+ mock_update_remote_config,+ ) -> None:+ if prepopulate_zset_score_offset is not None:+ score = int(timezone.now().timestamp()) + prepopulate_zset_score_offset+ replace_limited_team_tokens(+ QuotaResource.RECORDINGS,+ {self.team.api_token: score},+ QuotaLimitingCaches.QUOTA_LIMITER_CACHE_KEY,+ )++ self.organization.usage = {+ **usage_overrides,+ "period": ["2021-01-01T00:00:00Z", "2021-01-31T23:59:59Z"],+ }+ self.organization.customer_trust_scores = zero_trust_scores()+ self.organization.save()++ update_org_billing_quotas(self.organization)++ assert mock_update_remote_config.apply_async.call_count == expected_dispatch_count+ if expected_dispatch_count > 0:+ mock_update_remote_config.apply_async.assert_called_with(+ args=[self.team.id],+ kwargs={"bypass_recordings_quota_cache": True},+ countdown=35,+ )++ @freeze_time("2021-01-25T00:00:00Z")+ @patch("posthog.tasks.remote_config.update_team_remote_config")+ def test_update_org_billing_quotas_no_teams_no_dispatch(self, mock_update_remote_config) -> None:+ """An org with no teams (or only teams with empty api_tokens) takes the observe-only+ branch — no Redis mutations, no dispatch, no crash."""+ self.organization.teams.all().delete()+ self.organization.usage = {+ "events": {"usage": 1, "limit": 100},+ "recordings": {"usage": 6_000, "limit": 5_000},+ "period": ["2021-01-01T00:00:00Z", "2021-01-31T23:59:59Z"],+ }+ self.organization.customer_trust_scores = zero_trust_scores()+ self.organization.save()++ update_org_billing_quotas(self.organization)++ mock_update_remote_config.apply_async.assert_not_called()++ @parameterized.expand(+ [+ ("active_member_becomes_unlimited", 10_000, 1, 1, False, 1, False),+ ("expired_member_becomes_unlimited", -10_000, 1, 1, False, 1, False),+ ("still_limited_no_dispatch", 10_000, 6_000, 1, False, 0, True),+ ("non_recordings_over_limit_no_dispatch", None, 1, 1_000_000, False, 0, False),+ ("dry_run_skips_dispatch_and_mutation", 10_000, 1, 1, True, 0, True),+ ]+ )+ @patch("posthog.tasks.remote_config.update_team_remote_config")+ @patch("posthoganalytics.capture")+ @freeze_time("2021-01-25T00:00:00Z")+ def test_update_all_orgs_billing_quotas_recordings_remote_config_dispatch(+ self,+ _name,+ prepopulate_zset_score_offset,+ usage_recordings,+ usage_events,+ dry_run,+ expected_dispatch_count,+ expected_token_in_recordings_zset_after,+ patch_capture,+ mock_update_remote_config,+ ) -> None:+ recordings_zset_key = "@posthog/quota-limits/recordings"++ if prepopulate_zset_score_offset is not None:+ score = int(timezone.now().timestamp()) + prepopulate_zset_score_offset+ replace_limited_team_tokens(+ QuotaResource.RECORDINGS,+ {self.team.api_token: score},+ QuotaLimitingCaches.QUOTA_LIMITER_CACHE_KEY,+ )++ with self.settings(USE_TZ=False):+ self.organization.usage = {+ "events": {"usage": usage_events, "limit": 100, "todays_usage": 0},+ "recordings": {"usage": usage_recordings, "limit": 5_000, "todays_usage": 0},+ "period": ["2021-01-01T00:00:00Z", "2021-01-31T23:59:59Z"],+ }+ self.organization.customer_trust_scores = zero_trust_scores()+ self.organization.save()++ update_all_orgs_billing_quotas(dry_run=dry_run)++ assert mock_update_remote_config.apply_async.call_count == expected_dispatch_count+ if expected_dispatch_count > 0:+ mock_update_remote_config.apply_async.assert_called_with(+ args=[self.team.id],+ kwargs={"bypass_recordings_quota_cache": True},+ countdown=35,+ )++ members_after = {member.decode("utf-8") for member in self.redis_client.zrange(recordings_zset_key, 0, -1)}+ assert (self.team.api_token in members_after) is expected_token_in_recordings_zset_after+def _full_usage_counters(**overrides: int) -> UsageCounters:base = UsageCounters(diff --git a/posthog/cache_utils.py b/posthog/cache_utils.pyindex 96bda383512b..941f97317181 100644--- a/posthog/cache_utils.py+++ b/posthog/cache_utils.py@@ -57,6 +57,12 @@ class CachedFunction(Generic[P, R]):return self._cache[key][1]+ def clear_cache(self) -> None:+ """Drop all in-process cache entries. Intended for tests that need to start+ with a clean slate; production callers should rely on the TTL instead."""+ self._cache.clear()+ self._refreshing.clear()+def cache_for(cache_time: timedelta, background_refresh=False) -> Callable[[Callable[P, R]], CachedFunction[P, R]]:def wrapper(fn: Callable[P, R]) -> CachedFunction[P, R]:diff --git a/posthog/models/organization.py b/posthog/models/organization.pyindex d481839dbac9..9d2fc1b4dc75 100644--- a/posthog/models/organization.py+++ b/posthog/models/organization.py@@ -394,7 +394,9 @@ class Organization(ModelActivityMixin, UUIDTModel): # type: ignore[django-manag"""from ee.billing.quota_limiting import (QuotaLimitingCaches,+ QuotaResource,add_limited_team_tokens,+ dispatch_recordings_remote_config_sync,update_organization_usage_fields,)@@ -404,9 +406,10 @@ class Organization(ModelActivityMixin, UUIDTModel): # type: ignore[django-manag_start, end = billing_periodbilling_period_end_timestamp = int(end.timestamp())- team_tokens: dict[str, int] = {- t: billing_period_end_timestamp for t in self.teams.values_list("api_token", flat=True) if t- }+ team_rows = [+ (team_id, api_token) for team_id, api_token in self.teams.values_list("id", "api_token") if api_token+ ]+ team_tokens: dict[str, int] = {api_token: billing_period_end_timestamp for _, api_token in team_rows}add_limited_team_tokens(resource, team_tokens, QuotaLimitingCaches.QUOTA_LIMITER_CACHE_KEY)update_organization_usage_fields(@@ -414,6 +417,9 @@ class Organization(ModelActivityMixin, UUIDTModel): # type: ignore[django-managresource,{"quota_limited_until": billing_period_end_timestamp, "quota_limiting_suspended_until": None},)++ if resource == QuotaResource.RECORDINGS:+ dispatch_recordings_remote_config_sync(team_id for team_id, _ in team_rows)else:raise RuntimeError("Cannot limit without having a billing period")@@ -424,18 +430,27 @@ class Organization(ModelActivityMixin, UUIDTModel): # type: ignore[django-manag"""from ee.billing.quota_limiting import (QuotaLimitingCaches,+ QuotaResource,+ dispatch_recordings_remote_config_sync,remove_limited_team_tokens,update_organization_usage_fields,)- team_tokens: list[str] = [t for t in self.teams.values_list("api_token", flat=True) if t]- remove_limited_team_tokens(resource, team_tokens, QuotaLimitingCaches.QUOTA_LIMITER_CACHE_KEY)+ team_rows = [+ (team_id, api_token) for team_id, api_token in self.teams.values_list("id", "api_token") if api_token+ ]+ remove_limited_team_tokens(+ resource, [api_token for _, api_token in team_rows], QuotaLimitingCaches.QUOTA_LIMITER_CACHE_KEY+ )if self.usage and resource.value in self.usage:update_organization_usage_fields(self, resource, {"quota_limited_until": None, "quota_limiting_suspended_until": None})+ if resource == QuotaResource.RECORDINGS:+ dispatch_recordings_remote_config_sync(team_id for team_id, _ in team_rows)+def get_limited_products(self) -> dict[str, dict[str, Any]]:"""Returns information about which products are currently limited for this organization.diff --git a/posthog/models/remote_config.py b/posthog/models/remote_config.pyindex 5645a89eaf46..2030bdee38f9 100644--- a/posthog/models/remote_config.py+++ b/posthog/models/remote_config.py@@ -194,7 +194,7 @@ class RemoteConfig(UUIDTModel):}@tracer.start_as_current_span("RemoteConfig.build_config")- def build_config(self):+ def build_config(self, bypass_recordings_quota_cache: bool = False):from posthog.models.team import Teamfrom posthog.plugins.site import get_decide_site_apps@@ -256,7 +256,9 @@ class RemoteConfig(UUIDTModel):from ee.billing.quota_limiting import QuotaLimitingCaches, QuotaResource, list_limited_team_attributeslimited_tokens_recordings = list_limited_team_attributes(- QuotaResource.RECORDINGS, QuotaLimitingCaches.QUOTA_LIMITER_CACHE_KEY+ QuotaResource.RECORDINGS,+ QuotaLimitingCaches.QUOTA_LIMITER_CACHE_KEY,+ use_cache=not bypass_recordings_quota_cache,)if team.api_token in limited_tokens_recordings:@@ -385,15 +387,15 @@ class RemoteConfig(UUIDTModel):return site_apps_js + site_functions_js- def sync(self, force: bool = False):+ def sync(self, force: bool = False, bypass_recordings_quota_cache: bool = False):"""- When called we sync to any configured CDNs as well as redis for the /decide endpoint+ When called we sync to any configured CDNs as well as redis for the /decide endpoint."""logger.info(f"Syncing RemoteConfig for team {self.team_id}")try:- config = self.build_config()+ config = self.build_config(bypass_recordings_quota_cache=bypass_recordings_quota_cache)if not force and config == self.config:CELERY_TASK_REMOTE_CONFIG_SYNC.labels(result="no_changes").inc()diff --git a/posthog/models/test/test_organization_model.py b/posthog/models/test/test_organization_model.pyindex e84d00d61e9c..963107d78aaf 100644--- a/posthog/models/test/test_organization_model.py+++ b/posthog/models/test/test_organization_model.py@@ -373,6 +373,52 @@ class TestOrganization(BaseTest):team_tokens = mock_remove_limited.call_args[0][1]self.assertIn(self.team.api_token, team_tokens)+ @parameterized.expand(+ [+ ("limit_recordings_dispatches", "limit", QuotaResource.RECORDINGS, True),+ ("limit_events_no_dispatch", "limit", QuotaResource.EVENTS, False),+ ("unlimit_recordings_dispatches", "unlimit", QuotaResource.RECORDINGS, True),+ ("unlimit_events_no_dispatch", "unlimit", QuotaResource.EVENTS, False),+ ]+ )+ @patch("posthog.tasks.remote_config.update_team_remote_config")+ @patch("ee.billing.quota_limiting.remove_limited_team_tokens")+ @patch("ee.billing.quota_limiting.add_limited_team_tokens")+ def test_admin_hook_dispatches_recordings_remote_config_sync(+ self,+ _name,+ action,+ resource,+ expect_dispatch,+ mock_add_limited,+ mock_remove_limited,+ mock_update_remote_config,+ ):+ second_team = self.organization.teams.create(name="Second Team", api_token="second_token")+ self.organization.usage = {+ "period": ["2024-01-01T00:00:00Z", "2024-02-01T00:00:00Z"],+ # Carries `quota_limited_until` so `unlimit_product` exercises its usage-field write path.+ # Harmless for `limit_product_until_end_of_billing_cycle`, which overwrites it.+ resource.value: {"usage": 500, "limit": 1000, "quota_limited_until": 1234567890},+ }+ self.organization.save()++ if action == "limit":+ self.organization.limit_product_until_end_of_billing_cycle(resource)+ else:+ self.organization.unlimit_product(resource)++ if expect_dispatch:+ dispatched_team_ids = {+ call.kwargs["args"][0] for call in mock_update_remote_config.apply_async.call_args_list+ }+ self.assertEqual(dispatched_team_ids, {self.team.id, second_team.id})+ for call in mock_update_remote_config.apply_async.call_args_list:+ self.assertEqual(call.kwargs.get("countdown"), 35)+ self.assertEqual(call.kwargs.get("kwargs"), {"bypass_recordings_quota_cache": True})+ else:+ mock_update_remote_config.apply_async.assert_not_called()+@patch("ee.billing.quota_limiting.get_client")def test_get_limited_products_no_teams(self, mock_get_client):self.organization.teams.all().delete()diff --git a/posthog/models/test/test_remote_config.py b/posthog/models/test/test_remote_config.pyindex 8c8c3a0ab522..ca9ff461fc25 100644--- a/posthog/models/test/test_remote_config.py+++ b/posthog/models/test/test_remote_config.py@@ -243,6 +243,45 @@ class TestRemoteConfig(_RemoteConfigBase):self.sync_remote_config()assert self.remote_config.config["sessionRecording"]["scriptConfig"] == expected_script_config+ def test_build_config_bypass_recordings_quota_cache_reads_fresh_redis(self):+ """Pairs the bypass-True / bypass-False paths against a stale in-process cache so a+ regression that drops the kwarg (and reverts to cache-on-by-default in prod) fails+ the bypass-True case."""+ from ee.billing.quota_limiting import (+ QuotaLimitingCaches,+ QuotaResource,+ list_limited_team_attributes,+ replace_limited_team_tokens,+ )++ list_limited_team_attributes.clear_cache()++ replace_limited_team_tokens(QuotaResource.RECORDINGS, {}, QuotaLimitingCaches.QUOTA_LIMITER_CACHE_KEY)+ # Force-prime the cache: `cache_for` defaults `use_cache=not TEST`, so without an+ # explicit `use_cache=True` the call would bypass caching in tests and the assertion+ # below would lose its meaning.+ primed = list_limited_team_attributes(+ QuotaResource.RECORDINGS, QuotaLimitingCaches.QUOTA_LIMITER_CACHE_KEY, use_cache=True+ )+ assert primed == []++ future_ts = int(timezone.now().timestamp()) + 10_000+ replace_limited_team_tokens(+ QuotaResource.RECORDINGS,+ {self.team.api_token: future_ts},+ QuotaLimitingCaches.QUOTA_LIMITER_CACHE_KEY,+ )++ cached_config = self.remote_config.build_config(bypass_recordings_quota_cache=False)+ assert cached_config.get("quotaLimited") is None+ assert cached_config["sessionRecording"] is not False++ fresh_config = self.remote_config.build_config(bypass_recordings_quota_cache=True)+ assert fresh_config["quotaLimited"] == ["recordings"]+ assert fresh_config["sessionRecording"] is False++ list_limited_team_attributes.clear_cache()+class TestRemoteConfigSurveys(_RemoteConfigBase):# Largely copied from TestSurveysAPIListdiff --git a/posthog/tasks/remote_config.py b/posthog/tasks/remote_config.pyindex 08857a9c00ef..10a5ebb877eb 100644--- a/posthog/tasks/remote_config.py+++ b/posthog/tasks/remote_config.py@@ -9,9 +9,14 @@ from posthog.tasks.utils import CeleryQueuelogger = structlog.get_logger(__name__)-@shared_task(ignore_result=True, queue=CeleryQueue.DEFAULT.value)+@shared_task(+ ignore_result=True,+ queue=CeleryQueue.DEFAULT.value,+ soft_time_limit=300,+ time_limit=360,+)@skip_team_scope_audit-def update_team_remote_config(team_id: int) -> None:+def update_team_remote_config(team_id: int, bypass_recordings_quota_cache: bool = False) -> None:try:team = Team.objects.get(id=team_id)except Team.DoesNotExist:@@ -23,7 +28,7 @@ def update_team_remote_config(team_id: int) -> None:except RemoteConfig.DoesNotExist:remote_config = RemoteConfig(team=team)- remote_config.sync()+ 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.pyindex 1c21b91896ed..d0aadadfaa8e 100644--- a/posthog/tasks/test/test_remote_config.py+++ b/posthog/tasks/test/test_remote_config.py@@ -1,8 +1,9 @@from posthog.test.base import BaseTest+from unittest.mock import MagicMock, patchfrom posthog.models.project import Projectfrom posthog.models.remote_config import RemoteConfig-from posthog.tasks.remote_config import sync_all_remote_configs+from posthog.tasks.remote_config import sync_all_remote_configs, update_team_remote_configclass TestRemoteConfig(BaseTest):@@ -61,3 +62,13 @@ class TestRemoteConfig(BaseTest):assert RemoteConfig.objects.get(team=self.other_team_1).synced_at > remote_config_1_synced_at # type: ignore# This one is unchanged so should not be syncedassert RemoteConfig.objects.get(team=self.other_team_2).synced_at == remote_config_2_synced_at++ @patch.object(RemoteConfig, "sync")+ def test_update_team_remote_config_forwards_bypass_recordings_quota_cache(self, mock_sync: MagicMock) -> None:+ """End-to-end coverage that the task forwards the bypass kwarg to `RemoteConfig.sync`."""+ update_team_remote_config(self.team.id, bypass_recordings_quota_cache=True)+ mock_sync.assert_called_once_with(bypass_recordings_quota_cache=True)++ mock_sync.reset_mock()+ update_team_remote_config(self.team.id)+ mock_sync.assert_called_once_with(bypass_recordings_quota_cache=False)