: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(signals): verify period usage before releasing quota blocks (#104296)
Georgiy Tarasovf46ccb44ac24
diff --git a/ee/billing/quota_limiting.py b/ee/billing/quota_limiting.pyindex 05fce97941f9..f1fd6d9274d9 100644--- a/ee/billing/quota_limiting.py+++ b/ee/billing/quota_limiting.py@@ -355,21 +355,11 @@ def org_quota_limited_until(return Noneusage = summary.get("usage") or 0todays_usage = summary.get("todays_usage") or 0+ current_usage = usage + todays_usagelimit = summary.get("limit")quota_limited_until = summary.get("quota_limited_until", None)quota_limiting_suspended_until = summary.get("quota_limiting_suspended_until", None)- # Credited-path signals PR refunds free the org's quota slot posthog-side (billing's stored- # usage still contains the refunded units). Consulted only when the raw comparison is already- # at/over the limit, so the DB query fires for the handful of orgs that would otherwise be- # limited. Surfaced on every quota event below for debuggability of refund-affected decisions.- refund_offset = _signals_credited_refund_offset(- organization,- resource,- limit is not None and usage + todays_usage >= limit + OVERAGE_BUFFER[resource],- )- refund_offset_properties = {"signals_refund_offset": refund_offset} if refund_offset else {}-if limit is None:if quota_limiting_suspended_until is not None or quota_limited_until is not None:report_organization_action(@@ -377,8 +367,7 @@ def org_quota_limited_until("org_quota_limited_until",properties={"event": "limit removed",- "current_usage": usage + todays_usage,- **refund_offset_properties,+ "current_usage": current_usage,"resource": resource.value,"quota_limited_until": quota_limited_until,"quota_limiting_suspended_until": quota_limiting_suspended_until,@@ -389,7 +378,46 @@ def org_quota_limited_until()return None- is_over_limit = usage + todays_usage - refund_offset >= limit + OVERAGE_BUFFER[resource]+ # Credited-path signals PR refunds free the org's quota slot posthog-side (billing's stored+ # usage still contains the refunded units). Consulted only when the raw comparison is already+ # at/over the limit, so the DB query fires for the handful of orgs that would otherwise be+ # limited. Surfaced on every quota event below for debuggability of refund-affected decisions.+ refund_offset = _signals_credited_refund_offset(+ organization,+ resource,+ limit is not None and current_usage >= limit + OVERAGE_BUFFER[resource],+ )+ if resource == QuotaResource.SIGNALS_CREDITS and current_usage - refund_offset < limit:+ active_persisted_limit = quota_limited_until is not None and quota_limited_until > timezone.now().timestamp()+ if team_tokens is None and previously_quota_limited_team_tokens and not active_persisted_limit:+ team_tokens = get_team_attribute_by_quota_resource(organization)+ was_limited = active_persisted_limit or any(+ token in previously_quota_limited_team_tokens for token in (team_tokens or [])+ )+ if was_limited:+ # Midnight resets today's count before billing necessarily includes yesterday's PRs.+ # Verify the whole period before releasing a block; keep billing-owned counters intact.+ period_start = dateutil.parser.isoparse(organization.usage["period"][0])+ period_end = dateutil.parser.isoparse(organization.usage["period"][1])+ try:+ period_usage = get_self_driving_credits_used_in_period_for_org(+ organization.id, period_start, period_end+ )+ except Exception as error:+ capture_exception(error, {"organization_id": str(organization.id)})+ return {+ "quota_limited_until": (+ quota_limited_until if active_persisted_limit else round(period_end.timestamp())+ ),+ "quota_limiting_suspended_until": None,+ }+ current_usage = max(current_usage, period_usage)++ refund_offset = _signals_credited_refund_offset(organization, resource, current_usage >= limit)++ refund_offset_properties = {"signals_refund_offset": refund_offset} if refund_offset else {}++ is_over_limit = current_usage - refund_offset >= limit + OVERAGE_BUFFER[resource]billing_period_start = round(dateutil.parser.isoparse(organization.usage["period"][0]).timestamp())billing_period_end = round(dateutil.parser.isoparse(organization.usage["period"][1]).timestamp())@@ -420,7 +448,7 @@ def org_quota_limited_until("org_quota_limited_until",properties={"event": "suspension removed",- "current_usage": usage + todays_usage,+ "current_usage": current_usage,**refund_offset_properties,"resource": resource.value,"quota_limiting_suspended_until": quota_limiting_suspended_until,@@ -438,7 +466,7 @@ def org_quota_limited_until("org_quota_limited_until",properties={"event": "ignored",- "current_usage": usage + todays_usage,+ "current_usage": current_usage,**refund_offset_properties,"resource": resource.value,"never_drop_data": organization.never_drop_data,@@ -462,7 +490,7 @@ def org_quota_limited_until("org_quota_limited_until",properties={"event": "already limited",- "current_usage": usage + todays_usage,+ "current_usage": current_usage,**refund_offset_properties,"resource": resource.value,"quota_limited_until": billing_period_end,@@ -491,7 +519,7 @@ def org_quota_limited_until("org_quota_limited_until",properties={"event": "ignored",- "current_usage": usage + todays_usage,+ "current_usage": current_usage,**refund_offset_properties,"resource": resource.value,"feature_flag": QUOTA_LIMIT_DATA_RETENTION_FLAG,@@ -525,7 +553,7 @@ def org_quota_limited_until("org_quota_limited_until",properties={"event": "suspended",- "current_usage": usage + todays_usage,+ "current_usage": current_usage,**refund_offset_properties,"resource": resource.value,"trust_score": trust_score,@@ -547,7 +575,7 @@ def org_quota_limited_until("org_quota_limited_until",properties={"event": "suspended",- "current_usage": usage + todays_usage,+ "current_usage": current_usage,**refund_offset_properties,"resource": resource.value,"trust_score": trust_score,@@ -576,7 +604,7 @@ def org_quota_limited_until("org_quota_limited_until",properties={"event": "suspended",- "current_usage": usage + todays_usage,+ "current_usage": current_usage,**refund_offset_properties,"resource": resource.value,"grace_period_days": grace_period_days,@@ -637,7 +665,7 @@ def org_quota_limited_until("org_quota_limited_until",properties={"event": "suspension not expired",- "current_usage": usage + todays_usage,+ "current_usage": current_usage,**refund_offset_properties,"resource": resource.value,"quota_limiting_suspended_until": quota_limiting_suspended_until,@@ -659,7 +687,7 @@ def org_quota_limited_until("org_quota_limited_until",properties={"event": "suspended expired",- "current_usage": usage + todays_usage,+ "current_usage": current_usage,**refund_offset_properties,"resource": resource.value,},@@ -1368,7 +1396,9 @@ def update_all_orgs_billing_quotas(for resource in QuotaResource:field = resource.value# for each organization, we check if the current usage + today's unreported usage is over the limit- result = org_quota_limited_until(org, resource, previously_quota_limited_team_tokens[field])+ result = org_quota_limited_until(+ org, resource, previously_quota_limited_team_tokens[field], teams_by_org.get(org_id, [])+ )if result:quota_limited_until = result.get("quota_limited_until")limiting_suspended_until = result.get("quota_limiting_suspended_until")diff --git a/ee/billing/test/test_quota_limiting.py b/ee/billing/test/test_quota_limiting.pyindex bc36421f4b44..ac12f866cfb7 100644--- a/ee/billing/test/test_quota_limiting.py+++ b/ee/billing/test/test_quota_limiting.py@@ -7,6 +7,7 @@ from posthog.test.base import BaseTest, FuzzyInt, _create_event, flush_persons_afrom unittest.mock import patchfrom django.apps import apps+from django.db import DatabaseErrorfrom django.test import override_settingsfrom django.utils import timezonefrom django.utils.timezone import now@@ -2994,6 +2995,132 @@ class TestRefreshOrgSelfDrivingQuota(BaseTest):self.organization.customer_trust_scores = {}self.organization.save()+ @parameterized.expand(+ [+ ("midnight", True, 1500, False, False, True, False),+ ("midnight_cron", True, 1500, False, False, True, True),+ ("redis_only", False, 1500, False, False, True, False),+ ("raised_limit", True, 3000, False, False, False, False),+ ("removed_limit", True, None, False, False, False, False),+ ("credited_refund", True, 1500, True, False, False, False),+ ("new_period", True, 1500, False, True, False, False),+ ]+ )+ @time_machine.travel("2026-06-15T00:30:00Z", tick=False)+ def test_quota_release_checks_prs_missing_from_billing_usage(+ self,+ _name: str,+ persisted_marker: bool,+ limit: int | None,+ refunded: bool,+ new_period: bool,+ expect_limited: bool,+ via_cron: bool,+ ) -> None:+ self._set_self_driving_usage(0, limit=1500)+ assert self.organization.usage is not None+ self.organization.usage["signals_credits"]["limit"] = limit+ if persisted_marker:+ self.organization.usage["signals_credits"]["quota_limited_until"] = 1782864000+ if new_period:+ self.organization.usage["period"] = ["2026-06-15T00:00:00Z", "2026-07-15T00:00:00Z"]+ self.organization.save()++ report = apps.get_model("signals", "SignalReport").objects.create(team=self.team)+ task = apps.get_model("tasks", "Task").objects.create(team=self.team, title="Quota fixture")+ apps.get_model("signals", "SignalReportTask").objects.create(+ team=self.team, report=report, task=task, relationship="implementation"+ )+ pr_run_at = datetime.datetime(2026, 6, 14, 23, 45, tzinfo=datetime.UTC)+ apps.get_model("tasks", "TaskRun").objects.create(+ team=self.team,+ task=task,+ created_at=pr_run_at,+ output={"pr_url": "https://github.com/example/quota-fixture/pull/1"},+ )+ if refunded:+ apps.get_model("signals", "SignalReportRefund").objects.for_team(self.team.id).create(+ team_id=self.team.id,+ report=report,+ reason="pr_incorrect",+ billing_path="credited",+ credits=1500,+ pr_url="https://github.com/example/quota-fixture/pull/1",+ pr_run_created_at=pr_run_at,+ )++ add_limited_team_tokens(+ QuotaResource.SIGNALS_CREDITS,+ {self.team.api_token: 1782864000},+ QuotaLimitingCaches.QUOTA_LIMITER_CACHE_KEY,+ )+ if via_cron:+ update_all_orgs_billing_quotas()+ else:+ update_org_billing_quotas(self.organization)++ assert (+ self.team.api_token+ in list_limited_team_attributes(QuotaResource.SIGNALS_CREDITS, QuotaLimitingCaches.QUOTA_LIMITER_CACHE_KEY)+ ) == expect_limited+ self.organization.refresh_from_db()+ assert self.organization.usage is not None+ assert self.organization.usage["signals_credits"]["usage"] == 0+ assert self.organization.usage["signals_credits"]["todays_usage"] == 0++ @parameterized.expand(+ [+ ("active", "2026-07-01", "2026-07-01", "2026-07-01"),+ ("active_earlier_expiry", "2026-06-16", "2026-06-16", "2026-06-16"),+ ("expired", "2026-06-01", "2026-06-01", None),+ ("expired_with_active_redis", "2026-06-01", "2026-07-01", "2026-07-01"),+ ("redis_only", None, "2026-07-01", "2026-07-01"),+ ]+ )+ @time_machine.travel("2026-06-15T00:30:00Z", tick=False)+ def test_failed_period_recount_preserves_existing_block(+ self, _name: str, persisted_expiry: str | None, redis_expiry: str, expected_expiry: str | None+ ) -> None:+ self._set_self_driving_usage(0)+ assert self.organization.usage is not None+ if persisted_expiry:+ self.organization.usage["signals_credits"]["quota_limited_until"] = round(+ datetime.datetime.fromisoformat(persisted_expiry).replace(tzinfo=datetime.UTC).timestamp()+ )+ self.organization.save()+ add_limited_team_tokens(+ QuotaResource.SIGNALS_CREDITS,+ {+ self.team.api_token: round(+ datetime.datetime.fromisoformat(redis_expiry).replace(tzinfo=datetime.UTC).timestamp()+ )+ },+ QuotaLimitingCaches.QUOTA_LIMITER_CACHE_KEY,+ )++ def count_credits(organization_id: str, begin: datetime.datetime, end: datetime.datetime) -> int:+ if begin.day == 1:+ raise DatabaseError("Period usage unavailable")+ return 0++ with patch(+ "ee.billing.quota_limiting.get_self_driving_credits_used_in_period_for_org", side_effect=count_credits+ ):+ update_all_orgs_billing_quotas()++ expected_timestamp = (+ datetime.datetime.fromisoformat(expected_expiry).replace(tzinfo=datetime.UTC).timestamp()+ if expected_expiry+ else None+ )+ assert (+ get_client().zscore(+ f"{QuotaLimitingCaches.QUOTA_LIMITER_CACHE_KEY.value}{QuotaResource.SIGNALS_CREDITS.value}",+ self.team.api_token,+ )+ == expected_timestamp+ )+@patch("posthoganalytics.capture")@patch("posthoganalytics.feature_enabled", return_value=False)@time_machine.travel("2026-06-15T12:00:00Z", tick=False)