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(billing): clear quota markers when limits are removed (#66255)

Pawel Cebulae1470da61496
diff --git a/ee/billing/billing_manager.py b/ee/billing/billing_manager.py
index ee223547d56b..0491332f7b9c 100644
--- a/ee/billing/billing_manager.py
+++ b/ee/billing/billing_manager.py
@@ -44,6 +44,19 @@ class BillingServiceOpenInvoicesError(Exception):
super().__init__(message)
+def _has_quota_limiting_markers(usage: dict | None) -> bool:
+ if not usage:
+ return False
+
+ for value in usage.values():
+ if isinstance(value, dict) and (
+ value.get("quota_limited_until") is not None or value.get("quota_limiting_suspended_until") is not None
+ ):
+ return True
+
+ return False
+
+
def _get_user_organization_role(user: User, organization: Organization) -> Optional[str]:
"""
Get a user role display string in a given organization, if membership doesn't exist return None.
@@ -416,6 +429,8 @@ class BillingManager:
organization.customer_id = data["customer_id"]
org_modified = True
+ should_update_org_billing_quotas = False
+
usage_summary = cast(dict, data.get("usage_summary"))
if usage_summary:
usage_info = OrganizationUsageInfo(
@@ -440,9 +455,13 @@ class BillingManager:
],
)
- if set_org_usage_summary(organization, new_usage=usage_info):
+ had_quota_limiting_markers = _has_quota_limiting_markers(organization.usage)
+ usage_changed = set_org_usage_summary(organization, new_usage=usage_info)
+
+ if usage_changed:
org_modified = True
- update_org_billing_quotas(organization)
+
+ should_update_org_billing_quotas = usage_changed or had_quota_limiting_markers
available_product_features = data.get("available_product_features", None)
if available_product_features and available_product_features != organization.available_product_features:
@@ -456,27 +475,35 @@ class BillingManager:
customer_trust_scores = data.get("customer_trust_scores", {})
- product_key_to_usage_key = {
- product["type"]: product["usage_key"]
- for product in (
- billing_status["customer"].get("products") or self.get_default_products(organization)["products"]
- )
- }
- org_customer_trust_scores = {}
- for product_key in customer_trust_scores:
- if product_key in product_key_to_usage_key:
- org_customer_trust_scores[product_key_to_usage_key[product_key]] = customer_trust_scores[product_key]
-
- if org_customer_trust_scores != organization.customer_trust_scores:
- organization.customer_trust_scores = {
- **(organization.customer_trust_scores or {}),
+ if customer_trust_scores:
+ product_key_to_usage_key = {
+ product["type"]: product["usage_key"]
+ for product in (
+ billing_status["customer"].get("products") or self.get_default_products(organization)["products"]
+ )
+ }
+ org_customer_trust_scores = {}
+ for product_key in customer_trust_scores:
+ if product_key in product_key_to_usage_key:
+ org_customer_trust_scores[product_key_to_usage_key[product_key]] = customer_trust_scores[
+ product_key
+ ]
+
+ current_customer_trust_scores = organization.customer_trust_scores or {}
+ updated_customer_trust_scores = {
+ **current_customer_trust_scores,
**org_customer_trust_scores,
}
- org_modified = True
+ if updated_customer_trust_scores != current_customer_trust_scores:
+ organization.customer_trust_scores = updated_customer_trust_scores
+ org_modified = True
if org_modified:
organization.save()
+ if should_update_org_billing_quotas:
+ update_org_billing_quotas(organization)
+
return organization
def get_auth_headers(
diff --git a/ee/billing/quota_limiting.py b/ee/billing/quota_limiting.py
index aaa35c87f0c2..818fcdd61240 100644
--- a/ee/billing/quota_limiting.py
+++ b/ee/billing/quota_limiting.py
@@ -255,18 +255,33 @@ def org_quota_limited_until(
summary = organization.usage.get(resource.value, {})
if not summary:
return None
- usage = summary.get("usage", 0)
- todays_usage = summary.get("todays_usage", 0)
+ usage = summary.get("usage") or 0
+ todays_usage = summary.get("todays_usage") or 0
limit = summary.get("limit")
+ quota_limited_until = summary.get("quota_limited_until", None)
+ quota_limiting_suspended_until = summary.get("quota_limiting_suspended_until", None)
if limit is None:
+ if quota_limiting_suspended_until is not None or quota_limited_until is not None:
+ report_organization_action(
+ organization,
+ "org_quota_limited_until",
+ properties={
+ "event": "limit removed",
+ "current_usage": usage + todays_usage,
+ "resource": resource.value,
+ "quota_limited_until": quota_limited_until,
+ "quota_limiting_suspended_until": quota_limiting_suspended_until,
+ },
+ )
+ update_organization_usage_fields(
+ organization, resource, {"quota_limited_until": None, "quota_limiting_suspended_until": None}
+ )
return None
is_over_limit = usage + todays_usage >= 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())
- quota_limited_until = summary.get("quota_limited_until", None)
- quota_limiting_suspended_until = summary.get("quota_limiting_suspended_until", None)
# - customer_trust_scores can be empty {} for orgs not yet synced from billing. Default to 0 (no grace period)
# - customer_trust_scores in posthog_organization use usage_key values (matching QuotaResource values)
diff --git a/ee/billing/test/test_billing_manager.py b/ee/billing/test/test_billing_manager.py
index 1b4d8aa9a045..887ecdda42f1 100644
--- a/ee/billing/test/test_billing_manager.py
+++ b/ee/billing/test/test_billing_manager.py
@@ -147,7 +147,7 @@ class TestBillingManager(BaseTest):
]
@patch("posthoganalytics.capture")
- def test_update_org_details_preserves_quota_limits(self, patch_capture):
+ def test_update_org_details_recomputes_existing_quota_limits(self, patch_capture):
organization = self.organization
organization.usage = {
"events": {
@@ -228,19 +228,16 @@ class TestBillingManager(BaseTest):
"usage": 90,
"limit": 1000,
"todays_usage": 10,
- "quota_limited_until": 1612137599,
},
"exceptions": {
"usage": 10,
"limit": 100,
"todays_usage": 5,
- "quota_limiting_suspended_until": 1611705600,
},
"recordings": {
"usage": 15,
"limit": 100,
"todays_usage": 5,
- "quota_limiting_suspended_until": 1611705600,
},
"rows_synced": {"usage": 45, "limit": 500, "todays_usage": 5},
"rows_exported": {"usage": 10, "limit": 1000, "todays_usage": 5},
@@ -258,10 +255,128 @@ class TestBillingManager(BaseTest):
"usage": 10,
"limit": 100,
"todays_usage": 5,
- "quota_limiting_suspended_until": 1611705600,
},
}
+ @patch("posthoganalytics.capture")
+ def test_update_org_details_applies_never_drop_data_before_recomputing_existing_quota_limits(self, patch_capture):
+ organization = self.organization
+ organization.usage = {
+ "events": {
+ "usage": 1_000,
+ "limit": 100,
+ "todays_usage": 0,
+ "quota_limited_until": 1612137599,
+ },
+ "recordings": {"usage": 0, "limit": 100, "todays_usage": 0},
+ "period": ["2024-01-01T00:00:00Z", "2024-01-31T23:59:59Z"],
+ }
+ organization.never_drop_data = False
+ organization.save()
+
+ license = super(LicenseManager, cast(LicenseManager, License.objects)).create(
+ key="key123::key123",
+ plan="enterprise",
+ valid_until=datetime.datetime(2038, 1, 19, 3, 14, 7),
+ )
+
+ billing_status = {
+ "customer": {
+ "usage_summary": {
+ "events": {"usage": 1_000, "limit": 100},
+ "recordings": {"usage": 0, "limit": 100},
+ },
+ "billing_period": {
+ "current_period_start": "2024-01-01T00:00:00Z",
+ "current_period_end": "2024-01-31T23:59:59Z",
+ },
+ "never_drop_data": True,
+ }
+ }
+
+ BillingManager(license).update_org_details(organization, cast(BillingStatus, billing_status))
+ organization.refresh_from_db()
+
+ assert organization.never_drop_data is True
+ assert organization.usage["events"].get("quota_limited_until") is None
+ assert organization.usage["events"].get("quota_limiting_suspended_until") is None
+
+ @patch("ee.billing.billing_manager.update_org_billing_quotas", side_effect=Exception("Redis unavailable"))
+ def test_update_org_details_saves_org_fields_before_recomputing_existing_quota_limits(
+ self, update_org_billing_quotas_mock: MagicMock
+ ):
+ organization = self.organization
+ organization.usage = {
+ "events": {
+ "usage": 1_000,
+ "limit": 100,
+ "todays_usage": 0,
+ "quota_limited_until": 1612137599,
+ },
+ "recordings": {"usage": 0, "limit": 100, "todays_usage": 0},
+ "period": ["2024-01-01T00:00:00Z", "2024-01-31T23:59:59Z"],
+ }
+ organization.never_drop_data = False
+ organization.save()
+
+ license = super(LicenseManager, cast(LicenseManager, License.objects)).create(
+ key="key123::key123",
+ plan="enterprise",
+ valid_until=datetime.datetime(2038, 1, 19, 3, 14, 7),
+ )
+
+ billing_status = {
+ "customer": {
+ "usage_summary": {
+ "events": {"usage": 1_000, "limit": 100},
+ "recordings": {"usage": 0, "limit": 100},
+ },
+ "billing_period": {
+ "current_period_start": "2024-01-01T00:00:00Z",
+ "current_period_end": "2024-01-31T23:59:59Z",
+ },
+ "never_drop_data": True,
+ }
+ }
+
+ with self.assertRaises(Exception) as context:
+ BillingManager(license).update_org_details(organization, cast(BillingStatus, billing_status))
+
+ assert str(context.exception) == "Redis unavailable"
+ update_org_billing_quotas_mock.assert_called_once_with(organization)
+
+ organization.refresh_from_db()
+ assert organization.never_drop_data is True
+
+ @patch("ee.billing.billing_manager.BillingManager.get_default_products")
+ def test_update_org_details_skips_default_products_without_customer_trust_scores(
+ self, get_default_products_mock: MagicMock
+ ):
+ organization = self.organization
+ organization.never_drop_data = False
+ organization.customer_trust_scores = {"events": 7}
+ organization.save()
+
+ license = super(LicenseManager, cast(LicenseManager, License.objects)).create(
+ key="key123::key123",
+ plan="enterprise",
+ valid_until=datetime.datetime(2038, 1, 19, 3, 14, 7),
+ )
+
+ billing_status = {
+ "customer": {
+ "never_drop_data": False,
+ "customer_trust_scores": {},
+ }
+ }
+
+ BillingManager(license).update_org_details(organization, cast(BillingStatus, billing_status))
+
+ get_default_products_mock.assert_not_called()
+
+ organization.refresh_from_db()
+ assert organization.customer_trust_scores == {"events": 7}
+
@patch(
"ee.billing.billing_manager.requests.post",
return_value=MagicMock(status_code=200, json=MagicMock(return_value={"success": True})),
diff --git a/ee/billing/test/test_quota_limiting.py b/ee/billing/test/test_quota_limiting.py
index f9a3960eac5c..7f312e6be0cf 100644
--- a/ee/billing/test/test_quota_limiting.py
+++ b/ee/billing/test/test_quota_limiting.py
@@ -733,6 +733,8 @@ class TestQuotaLimiting(BaseTest):
)
is None
)
+ assert self.organization.usage["events"].get("quota_limited_until") is None
+ assert self.organization.usage["events"].get("quota_limiting_suspended_until") is None
# Not over quota
self.organization.usage["exceptions"]["usage"] = 99
@@ -2222,6 +2224,76 @@ class TestQuotaLimiting(BaseTest):
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
+ @patch("posthog.tasks.remote_config.update_team_remote_config")
+ def test_update_org_billing_quotas_recordings_limit_removed_clears_usage_marker(
+ self, mock_update_remote_config
+ ) -> None:
+ recordings_zset_key = "@posthog/quota-limits/recordings"
+ score = int(timezone.now().timestamp()) + 10_000
+ replace_limited_team_tokens(
+ QuotaResource.RECORDINGS,
+ {self.team.api_token: score},
+ QuotaLimitingCaches.QUOTA_LIMITER_CACHE_KEY,
+ )
+
+ self.organization.usage = {
+ "events": {"usage": 0, "limit": 100, "todays_usage": 0},
+ "recordings": {
+ # Legacy/partial usage blobs can store explicit JSON null counters.
+ "usage": None,
+ "limit": None,
+ "todays_usage": None,
+ "quota_limited_until": score,
+ },
+ "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 self.organization.usage["recordings"].get("quota_limited_until") is None
+ assert self.organization.usage["recordings"].get("quota_limiting_suspended_until") is None
+ members_after = {member.decode("utf-8") for member in self.redis_client.zrange(recordings_zset_key, 0, -1)}
+ assert self.team.api_token not in members_after
+ mock_update_remote_config.apply_async.assert_called_once_with(
+ args=[self.team.id],
+ kwargs={"bypass_recordings_quota_cache": True},
+ countdown=35,
+ )
+
+ @patch("posthog.tasks.remote_config.update_team_remote_config")
+ def test_update_org_billing_quotas_recordings_free_allocation_keeps_limited_marker(
+ self, mock_update_remote_config
+ ) -> None:
+ recordings_zset_key = "@posthog/quota-limits/recordings"
+ score = int(timezone.now().timestamp()) + 10_000
+ replace_limited_team_tokens(
+ QuotaResource.RECORDINGS,
+ {self.team.api_token: score},
+ QuotaLimitingCaches.QUOTA_LIMITER_CACHE_KEY,
+ )
+
+ self.organization.usage = {
+ "events": {"usage": 0, "limit": 100, "todays_usage": 0},
+ "recordings": {
+ "usage": 6_000,
+ "limit": 5_000,
+ "todays_usage": 0,
+ "quota_limited_until": score,
+ },
+ "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 self.organization.usage["recordings"].get("quota_limited_until") is not None
+ 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
+ mock_update_remote_config.apply_async.assert_not_called()
+
def _full_usage_counters(**overrides: int) -> UsageCounters:
base = UsageCounters(