: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): stop the quota cron wiping limits set during its run (#98322)
Alex Lebedev6e920cb9910e
diff --git a/ee/billing/quota_limiting.py b/ee/billing/quota_limiting.pyindex f3f9975d21e8..05fce97941f9 100644--- a/ee/billing/quota_limiting.py+++ b/ee/billing/quota_limiting.py@@ -189,6 +189,35 @@ def replace_limited_team_tokens(pipe.execute()+def reconcile_limited_team_tokens(+ resource: QuotaResource,+ snapshot_tokens: Iterable[str],+ tokens: Mapping[str, int],+ cache_key: QuotaLimitingCaches,+) -> None:+ """+ Writes one quota run's verdict into the cache without discarding entries the run never saw.++ `snapshot_tokens` is what the run read at its start. A snapshot token the run no longer lists+ is removed. A listed token is added or has its score refreshed. A token in neither set was+ added after the snapshot, by `refresh_org_self_driving_quota` when a PR landed or by+ `update_org_billing_quotas` on a billing sync, while this run was in flight. The run judged+ that org from state that predates the write, so its verdict is stale for that org and the+ entry is kept; the next run reads the persisted `quota_limited_until` marker and settles it.+ A wholesale replace would drop that entry and unblock the org until the next run.+ Expired scores are purged so entries that lapsed on their own do not accumulate.+ """+ key = f"{cache_key.value}{resource.value}"+ stale_tokens = [token for token in snapshot_tokens if token not in tokens]+ pipe = get_client().pipeline()+ pipe.zremrangebyscore(key, "-inf", timezone.now().timestamp())+ if stale_tokens:+ pipe.zrem(key, *stale_tokens)+ if tokens:+ pipe.zadd(key, tokens) # type: ignore # (zadd takes a Mapping[str, int] but the derived Union type is wrong)+ pipe.execute()++def add_limited_team_tokens(resource: QuotaResource, tokens: Mapping[str, int], cache_key: QuotaLimitingCaches) -> None:if not tokens:return@@ -1256,13 +1285,16 @@ def update_all_orgs_billing_quotas(previously_quota_limited_team_tokens: dict[str, list[str]] = {x.value: [] for x in QuotaResource}previously_quota_limiting_suspended_team_tokens: dict[str, list[str]] = {x.value: [] for x in QuotaResource}- # All teams that are currently under quota limits or in a suspension grace period+ # All teams that are currently under quota limits or in a suspension grace period.+ # `reconcile_limited_team_tokens` removes the snapshot entries this run judges under limit, so the+ # snapshot must be this run's own start state. The 30-second cache refreshes in the background and+ # returns the previous value, which for a 15-minute cron is the state at the previous run's start.for resource in QuotaResource:previously_quota_limited_team_tokens[resource.value] = list_limited_team_attributes(- resource, QuotaLimitingCaches.QUOTA_LIMITER_CACHE_KEY+ resource, QuotaLimitingCaches.QUOTA_LIMITER_CACHE_KEY, use_cache=False)previously_quota_limiting_suspended_team_tokens[resource.value] = list_limited_team_attributes(- resource, QuotaLimitingCaches.QUOTA_LIMITING_SUSPENDED_KEY+ resource, QuotaLimitingCaches.QUOTA_LIMITING_SUSPENDED_KEY, use_cache=False)previously_recordings_zset_tokens: set[str] = _get_previous_recordings_zset_tokens()@@ -1369,9 +1401,9 @@ def update_all_orgs_billing_quotas()except Exception as e:# TODO: revisit this swallow. Failures here mean the org never lands in- # `quota_limited_orgs` / `quota_limiting_suspended_orgs`, so the wholesale- # `replace_limited_team_tokens` calls below silently drop any prior Redis- # entries for the org's teams — effectively unblocking a previously+ # `quota_limited_orgs` / `quota_limiting_suspended_orgs`, so the+ # `reconcile_limited_team_tokens` calls below remove the org's teams from Redis+ # when they were in this run's snapshot — effectively unblocking a previously# limited/suspended org on a transient error. Pick an explicit policy# (e.g. preserve prior Redis state on error, or intentionally fail-open# for customer-favorable behavior) rather than letting the outcome fall@@ -1463,12 +1495,16 @@ def update_all_orgs_billing_quotas(if not dry_run:redis_start = time()for field in quota_limited_teams:- replace_limited_team_tokens(- QuotaResource(field), quota_limited_teams[field], QuotaLimitingCaches.QUOTA_LIMITER_CACHE_KEY+ reconcile_limited_team_tokens(+ QuotaResource(field),+ previously_quota_limited_team_tokens[field],+ quota_limited_teams[field],+ QuotaLimitingCaches.QUOTA_LIMITER_CACHE_KEY,)for field in quota_limiting_suspended_teams:- replace_limited_team_tokens(+ reconcile_limited_team_tokens(QuotaResource(field),+ previously_quota_limiting_suspended_team_tokens[field],quota_limiting_suspended_teams[field],QuotaLimitingCaches.QUOTA_LIMITING_SUSPENDED_KEY,)diff --git a/ee/billing/test/test_quota_limiting.py b/ee/billing/test/test_quota_limiting.pyindex f5c064ea3c22..bc36421f4b44 100644--- a/ee/billing/test/test_quota_limiting.py+++ b/ee/billing/test/test_quota_limiting.py@@ -3073,6 +3073,55 @@ class TestRefreshOrgSelfDrivingQuota(BaseTest):QuotaResource.SIGNALS_CREDITS, QuotaLimitingCaches.QUOTA_LIMITER_CACHE_KEY)+ @parameterized.expand(+ [+ ("kept_when_added_after_snapshot", False, 1798761600, True),+ ("removed_when_snapshot_org_is_under_limit", True, 1798761600, False),+ ("expired_entry_purged", False, 1750000000, False),+ ]+ )+ @patch("posthoganalytics.capture")+ @patch("posthoganalytics.feature_enabled", return_value=False)+ @time_machine.travel("2026-06-15T12:00:00Z", tick=False)+ def test_quota_cron_reconciles_limiter_instead_of_replacing_it(+ self, _name, in_snapshot, score, expect_present, _feature_enabled, _capture+ ) -> None:+ # A PR that crosses the limit while the cron runs is written to Redis after the cron's+ # snapshot, so a wholesale replace would wipe it and unblock the org until the next tick.+ self._set_self_driving_usage(1500)+ add_limited_team_tokens(+ QuotaResource.SIGNALS_CREDITS,+ {self.team.api_token: score},+ QuotaLimitingCaches.QUOTA_LIMITER_CACHE_KEY,+ )++ def snapshot(resource: QuotaResource, cache_key: QuotaLimitingCaches, use_cache: bool = True) -> list[str]:+ if (+ in_snapshot+ and resource == QuotaResource.SIGNALS_CREDITS+ and cache_key == QuotaLimitingCaches.QUOTA_LIMITER_CACHE_KEY+ ):+ return [self.team.api_token]+ return []++ with (+ patch("ee.billing.quota_limiting.list_limited_team_attributes", side_effect=snapshot) as snapshot_mock,+ patch("ee.billing.quota_limiting.get_teams_with_signals_credits_used_in_period", return_value=[]),+ patch("ee.billing.quota_limiting.get_self_driving_credits_used_in_period_for_org", return_value=0),+ ):+ update_all_orgs_billing_quotas()++ # The cache is off under TEST, so only this assertion catches a refactor that drops the kwarg+ # and hands the cron the previous run's snapshot in production.+ assert snapshot_mock.call_args_list+ assert all(call.kwargs.get("use_cache") is False for call in snapshot_mock.call_args_list)++ zset_score = get_client().zscore(+ f"{QuotaLimitingCaches.QUOTA_LIMITER_CACHE_KEY.value}{QuotaResource.SIGNALS_CREDITS.value}",+ self.team.api_token,+ )+ assert (zset_score is not None) == expect_present+def test_refresh_is_a_noop_without_self_driving_usage(self) -> None:self.organization.usage = {"events": {"usage": 1, "todays_usage": 0, "limit": None}}self.organization.save()diff --git a/products/signals/ARCHITECTURE.md b/products/signals/ARCHITECTURE.mdindex edc7a668cc80..3366f6482ec5 100644--- a/products/signals/ARCHITECTURE.md+++ b/products/signals/ARCHITECTURE.md@@ -1305,6 +1305,7 @@ Gates, in pipeline order:**The billable event re-evaluates the quota immediately.**When a self-driving-origin run records its first PR URL (agent report, PATCH, or GitHub webhook backstop), the tasks facade queues `refresh_org_self_driving_quota` (Celery), which recomputes the org's live `signals_credits` usage and re-runs the Redis limiter — so the PR that crosses the limit flips the flag within seconds instead of at the next 15-minute quota cron tick.The cron remains the backstop.+The cron writes its verdict by reconciling the Redis set against the snapshot it took at its start, so a limit the push refresh writes while a cron run is in flight survives that run instead of being wiped until the next tick.One timing edge: the live count is keyed to the implementation run's creation day (UTC), so a PR recorded just after midnight by a run created before midnight falls in the previous day's window and does not move the live counters.It reaches enforcement hours later, via that day's usage report; the charge itself still lands in the correct day.