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.

feat(billing): sync current Desktop component usage (#76826)

Adam Bowkerbbba730d67b3
diff --git a/ee/billing/billing_manager.py b/ee/billing/billing_manager.py
index 4e5620dcbaaa..c133f3278ffa 100644
--- a/ee/billing/billing_manager.py
+++ b/ee/billing/billing_manager.py
@@ -490,6 +490,10 @@ class BillingManager:
ai_credits=usage_summary.get("ai_credits", {}),
signals_credits=usage_summary.get("signals_credits", {}),
posthog_code_credits=usage_summary.get("posthog_code_credits", {}),
+ posthog_code_token_credits=usage_summary.get("posthog_code_token_credits", {}),
+ sandbox_compute_credits=usage_summary.get("sandbox_compute_credits", {}),
+ sandbox_compute_cpu_millicore_seconds=usage_summary.get("sandbox_compute_cpu_millicore_seconds", {}),
+ sandbox_compute_memory_mib_seconds=usage_summary.get("sandbox_compute_memory_mib_seconds", {}),
workflow_emails=usage_summary.get("workflow_emails", {}),
workflow_push=usage_summary.get("workflow_push", {}),
workflow_destinations_dispatched=usage_summary.get("workflow_destinations_dispatched", {}),
diff --git a/ee/billing/quota_limiting.py b/ee/billing/quota_limiting.py
index e0441530ca87..48a07395e9e8 100644
--- a/ee/billing/quota_limiting.py
+++ b/ee/billing/quota_limiting.py
@@ -25,6 +25,7 @@ from posthog.models.organization import Organization, OrganizationUsageInfo
from posthog.models.team.team import Team
from posthog.redis import get_client
from posthog.tasks.usage_report import (
+ combine_posthog_code_credits,
convert_team_usage_rows_to_dict,
get_self_driving_credits_used_in_period_for_org,
get_signals_credited_refund_credits_for_org,
@@ -32,6 +33,7 @@ from posthog.tasks.usage_report import (
get_teams_with_ai_event_count_in_period,
get_teams_with_api_queries_metrics,
get_teams_with_billable_event_count_in_period,
+ get_teams_with_billable_sandbox_compute_usage_in_period,
get_teams_with_cdp_billable_invocations_in_period,
get_teams_with_exceptions_captured_in_period,
get_teams_with_feature_flag_requests_count_in_period,
@@ -132,7 +134,7 @@ GRACE_PERIOD_EXEMPT_RESOURCES: set[QuotaResource] = {
}
-# These should be kept in sync with OrganizationUsageInfo and QuotaResource values.
+# These should be kept in sync with OrganizationUsageInfo.
class UsageCounters(TypedDict):
events: int
exceptions: int
@@ -147,6 +149,10 @@ class UsageCounters(TypedDict):
ai_credits: int
signals_credits: int
posthog_code_credits: int
+ posthog_code_token_credits: int
+ sandbox_compute_credits: int
+ sandbox_compute_cpu_millicore_seconds: int
+ sandbox_compute_memory_mib_seconds: int
workflow_emails: int
workflow_push: int
workflow_destinations_dispatched: int
@@ -154,6 +160,12 @@ class UsageCounters(TypedDict):
replay_vision_credits: int
+INFORMATIONAL_USAGE_RESOURCES = (
+ "posthog_code_token_credits",
+ "sandbox_compute_credits",
+ "sandbox_compute_cpu_millicore_seconds",
+ "sandbox_compute_memory_mib_seconds",
+)
# -------------------------------------------------------------------------------------------------
# REDIS FUNCTIONS
# -------------------------------------------------------------------------------------------------
@@ -835,12 +847,39 @@ def set_org_usage_summary(
todays_usage_value = original_field_usage.get("todays_usage", 0) if original_field_usage else 0
resource_usage["todays_usage"] = todays_usage_value
+ _merge_informational_usage_summary(cast(dict, new_usage), original_usage, todays_usage)
+
has_changed = new_usage != organization.usage
organization.usage = new_usage
return has_changed
+def _merge_informational_usage_summary(
+ new_usage: dict[str, Any], original_usage: dict[str, Any], todays_usage: Optional[UsageCounters]
+) -> None:
+ for field in INFORMATIONAL_USAGE_RESOURCES:
+ original_field_usage = original_usage.get(field, {})
+ resource_usage = new_usage.get(field)
+
+ if not resource_usage:
+ if original_field_usage:
+ new_usage[field] = original_field_usage
+ else:
+ # Billing omitted the component and there's no last-known value: drop the
+ # empty placeholder OrganizationUsageInfo construction left behind rather
+ # than writing `{}` into every org's usage dict.
+ new_usage.pop(field, None)
+ continue
+
+ if todays_usage:
+ resource_usage["todays_usage"] = todays_usage.get(field, 0)
+ elif original_field_usage.get("usage") != resource_usage.get("usage"):
+ resource_usage["todays_usage"] = 0
+ else:
+ resource_usage["todays_usage"] = original_field_usage.get("todays_usage", 0)
+
+
def _patch_organization_usage_jsonb(organization: Organization, ops: Sequence[tuple[list[str], Any]]) -> None:
"""
Applies a sequence of partial-write operations to `posthog_organization.usage` for
@@ -874,7 +913,7 @@ def _patch_organization_usage_jsonb(organization: Organization, ops: Sequence[tu
def _patch_todays_usage(organization: Organization, todays_report: "UsageCounters") -> bool:
"""
- Cron-only: patches `usage[resource].todays_usage` for each `QuotaResource` where the
+ Cron-only: patches `usage[resource].todays_usage` for each current usage resource where the
org has a non-empty resource dict. Mutates `organization.usage` in-memory and emits a
single targeted UPDATE via `_patch_organization_usage_jsonb` so billing-owned fields
(`usage`, `limit`, `period`) are not clobbered by stale snapshots. Returns True if
@@ -886,17 +925,9 @@ def _patch_todays_usage(organization: Organization, todays_report: "UsageCounter
ops: list[tuple[list[str], Any]] = []
for resource in QuotaResource:
- field = resource.value
- existing_resource = organization.usage.get(field)
- if not existing_resource:
- continue
-
- new_todays_usage = todays_report[field] # type: ignore[literal-required]
- if existing_resource.get("todays_usage") == new_todays_usage:
- continue
-
- existing_resource["todays_usage"] = new_todays_usage
- ops.append(([field, "todays_usage"], new_todays_usage))
+ _append_todays_usage_patch(organization, todays_report, resource.value, ops)
+ for field in INFORMATIONAL_USAGE_RESOURCES:
+ _append_todays_usage_patch(organization, todays_report, field, ops)
if not ops:
return False
@@ -905,6 +936,24 @@ def _patch_todays_usage(organization: Organization, todays_report: "UsageCounter
return True
+def _append_todays_usage_patch(
+ organization: Organization,
+ todays_report: UsageCounters,
+ field: str,
+ ops: list[tuple[list[str], Any]],
+) -> None:
+ existing_resource = organization.usage.get(field) if organization.usage else None
+ if not existing_resource:
+ return
+
+ new_todays_usage = cast(dict[str, int], todays_report)[field]
+ if existing_resource.get("todays_usage") == new_todays_usage:
+ return
+
+ existing_resource["todays_usage"] = new_todays_usage
+ ops.append(([field, "todays_usage"], new_todays_usage))
+
+
def _identify_refresh_candidates(
orgs_by_id: dict[str, Organization],
todays_usage_report: dict[str, "UsageCounters"],
@@ -1013,6 +1062,18 @@ def update_all_orgs_billing_quotas(
_, exception_metrics = _timed_query(
"exceptions_captured", get_teams_with_exceptions_captured_in_period, period_start, period_end
)
+ token_credits = convert_team_usage_rows_to_dict(
+ _timed_query(
+ "posthog_code_token_credits",
+ get_teams_with_posthog_code_credits_used_in_period,
+ period_start,
+ period_end,
+ )
+ )
+ sandbox_compute_usage = _timed_query(
+ "sandbox_compute", get_teams_with_billable_sandbox_compute_usage_in_period, period_start, period_end
+ )
+ compute_credits = convert_team_usage_rows_to_dict(sandbox_compute_usage.credits)
# Clickhouse is good at counting things so we count across all teams rather than doing it one by one
all_data = {
@@ -1063,10 +1124,17 @@ def update_all_orgs_billing_quotas(
"teams_with_signals_credits_used_in_period": convert_team_usage_rows_to_dict(
_timed_query("signals_credits", get_teams_with_signals_credits_used_in_period, period_start, period_end)
),
- "teams_with_posthog_code_credits_used_in_period": convert_team_usage_rows_to_dict(
- _timed_query(
- "posthog_code_credits", get_teams_with_posthog_code_credits_used_in_period, period_start, period_end
- )
+ "teams_with_posthog_code_credits_used_in_period": {
+ team_id: combine_posthog_code_credits(token_credits.get(team_id, 0), compute_credits.get(team_id, 0))
+ for team_id in token_credits.keys() | compute_credits.keys()
+ },
+ "teams_with_posthog_code_token_credits_used_in_period": token_credits,
+ "teams_with_sandbox_compute_credits_used_in_period": compute_credits,
+ "teams_with_sandbox_compute_cpu_millicore_seconds_in_period": convert_team_usage_rows_to_dict(
+ sandbox_compute_usage.cpu_millicore_seconds
+ ),
+ "teams_with_sandbox_compute_memory_mib_seconds_in_period": convert_team_usage_rows_to_dict(
+ sandbox_compute_usage.memory_mib_seconds
),
"teams_with_workflow_emails_sent_in_period": convert_team_usage_rows_to_dict(
_timed_query("workflow_emails", get_teams_with_workflow_emails_sent_in_period, period_start, period_end)
@@ -1143,6 +1211,14 @@ def update_all_orgs_billing_quotas(
ai_credits=all_data["teams_with_ai_credits_used_in_period"].get(team.id, 0),
signals_credits=all_data["teams_with_signals_credits_used_in_period"].get(team.id, 0),
posthog_code_credits=all_data["teams_with_posthog_code_credits_used_in_period"].get(team.id, 0),
+ posthog_code_token_credits=all_data["teams_with_posthog_code_token_credits_used_in_period"].get(team.id, 0),
+ sandbox_compute_credits=all_data["teams_with_sandbox_compute_credits_used_in_period"].get(team.id, 0),
+ sandbox_compute_cpu_millicore_seconds=all_data[
+ "teams_with_sandbox_compute_cpu_millicore_seconds_in_period"
+ ].get(team.id, 0),
+ sandbox_compute_memory_mib_seconds=all_data["teams_with_sandbox_compute_memory_mib_seconds_in_period"].get(
+ team.id, 0
+ ),
cdp_trigger_events=all_data["teams_with_cdp_trigger_events_metrics"].get(team.id, 0),
rows_exported=all_data["teams_with_rows_exported_in_period"].get(team.id, 0),
workflow_emails=all_data["teams_with_workflow_emails_sent_in_period"].get(team.id, 0),
diff --git a/ee/billing/test/test_quota_limiting.py b/ee/billing/test/test_quota_limiting.py
index b70d4ff01b7a..155619e82421 100644
--- a/ee/billing/test/test_quota_limiting.py
+++ b/ee/billing/test/test_quota_limiting.py
@@ -20,6 +20,7 @@ from posthog.models.team.team import Team
from posthog.redis import get_client
from ee.billing.quota_limiting import (
+ INFORMATIONAL_USAGE_RESOURCES,
QUOTA_LIMIT_DATA_RETENTION_FLAG,
OrganizationUsageInfo,
QuotaLimitingCaches,
@@ -1804,8 +1805,12 @@ class TestQuotaLimiting(BaseTest):
quota_resource_keys = {resource.value for resource in QuotaResource}
usage_counter_keys = set(UsageCounters.__annotations__.keys())
- # Check QuotaResource matches OrganizationUsageInfo
- missing_from_quota = org_usage_keys - quota_resource_keys
+ # Check QuotaResource matches OrganizationUsageInfo, except the informational
+ # component fields, which are deliberately never quota-enforced
+ informational_keys = set(INFORMATIONAL_USAGE_RESOURCES)
+ assert informational_keys <= org_usage_keys
+ assert not informational_keys & quota_resource_keys, "informational resources must not be QuotaResources"
+ missing_from_quota = org_usage_keys - quota_resource_keys - informational_keys
extra_in_quota = quota_resource_keys - org_usage_keys
assert not missing_from_quota, f"QuotaResource is missing keys from OrganizationUsageInfo: {missing_from_quota}"
assert not extra_in_quota, f"QuotaResource has extra keys not in OrganizationUsageInfo: {extra_in_quota}"
@@ -2335,6 +2340,10 @@ def _full_usage_counters(**overrides: int) -> UsageCounters:
ai_credits=0,
signals_credits=0,
posthog_code_credits=0,
+ posthog_code_token_credits=0,
+ sandbox_compute_credits=0,
+ sandbox_compute_cpu_millicore_seconds=0,
+ sandbox_compute_memory_mib_seconds=0,
cdp_trigger_events=0,
rows_exported=0,
workflow_emails=0,
@@ -2587,6 +2596,100 @@ class TestPatchTodaysUsage(BaseTest):
assert changed is False
+ def test_patches_desktop_components_without_changing_units_or_double_counting(self) -> None:
+ self.organization.usage = {
+ "posthog_code_credits": {"usage": 100, "limit": 2_000, "todays_usage": 0},
+ "posthog_code_token_credits": {"usage": 80, "limit": None, "todays_usage": 0},
+ "sandbox_compute_credits": {"usage": 20, "limit": None, "todays_usage": 0},
+ "sandbox_compute_cpu_millicore_seconds": {
+ "usage": 1_500,
+ "limit": None,
+ "todays_usage": 0,
+ },
+ "sandbox_compute_memory_mib_seconds": {
+ "usage": 4_608,
+ "limit": None,
+ "todays_usage": 0,
+ },
+ "period": _PERIOD,
+ }
+ self.organization.save()
+ todays_usage = _full_usage_counters(
+ posthog_code_credits=15,
+ posthog_code_token_credits=12,
+ sandbox_compute_credits=3,
+ sandbox_compute_cpu_millicore_seconds=9_876_543_210,
+ sandbox_compute_memory_mib_seconds=7_654_321_098,
+ )
+
+ assert _patch_todays_usage(self.organization, todays_usage) is True
+ assert _patch_todays_usage(self.organization, todays_usage) is False
+
+ self.organization.refresh_from_db()
+ assert self.organization.usage["posthog_code_credits"]["todays_usage"] == 15
+ assert self.organization.usage["posthog_code_token_credits"]["todays_usage"] == 12
+ assert self.organization.usage["sandbox_compute_credits"]["todays_usage"] == 3
+ assert self.organization.usage["sandbox_compute_cpu_millicore_seconds"]["todays_usage"] == 9_876_543_210
+ assert self.organization.usage["sandbox_compute_memory_mib_seconds"]["todays_usage"] == 7_654_321_098
+
+ def test_missing_billing_components_preserve_the_last_known_breakdown(self) -> None:
+ existing_component = {"usage": 10, "limit": None, "todays_usage": 3}
+ self.organization.usage = {
+ "events": {"usage": 100, "limit": 1_000, "todays_usage": 7},
+ "sandbox_compute_credits": existing_component,
+ "posthog_code_token_credits": {
+ "usage": 20,
+ "limit": None,
+ "todays_usage": 4,
+ "quota_limited_until": 123,
+ },
+ "period": _PERIOD,
+ }
+
+ new_usage = cast(
+ OrganizationUsageInfo,
+ {
+ "events": {"usage": 101, "limit": 1_000},
+ "sandbox_compute_credits": {},
+ "posthog_code_token_credits": {"usage": 21, "limit": None},
+ "period": _PERIOD,
+ },
+ )
+
+ assert set_org_usage_summary(self.organization, new_usage=new_usage) is True
+ assert self.organization.usage["sandbox_compute_credits"] == existing_component
+ assert self.organization.usage["posthog_code_token_credits"] == {
+ "usage": 21,
+ "limit": None,
+ "todays_usage": 0,
+ }
+
+ def test_omitted_components_without_prior_data_leave_no_empty_placeholders(self) -> None:
+ # A billing payload that predates component reporting arrives at an org that has
+ # never had component data (today's prod state until billing ships components).
+ # The OrganizationUsageInfo construction defaults each component to {}; those
+ # placeholders must not be written into the org's usage dict.
+ self.organization.usage = {
+ "events": {"usage": 100, "limit": 1_000, "todays_usage": 7},
+ "period": _PERIOD,
+ }
+
+ new_usage = cast(
+ OrganizationUsageInfo,
+ {
+ "events": {"usage": 101, "limit": 1_000},
+ "posthog_code_token_credits": {},
+ "sandbox_compute_credits": {},
+ "sandbox_compute_cpu_millicore_seconds": {},
+ "sandbox_compute_memory_mib_seconds": {},
+ "period": _PERIOD,
+ },
+ )
+
+ assert set_org_usage_summary(self.organization, new_usage=new_usage) is True
+ for field in INFORMATIONAL_USAGE_RESOURCES:
+ assert field not in self.organization.usage, field
+
def test_returns_false_when_no_resources_to_patch(self) -> None:
# Org has only `period` — no per-resource dicts to patch.
self.organization.usage = {"period": ["2021-01-01T00:00:00Z", "2021-01-31T23:59:59Z"]}
diff --git a/posthog/models/organization.py b/posthog/models/organization.py
index cd676b9d85fe..82ce19d27726 100644
--- a/posthog/models/organization.py
+++ b/posthog/models/organization.py
@@ -57,6 +57,10 @@ class OrganizationUsageInfo(TypedDict):
ai_credits: OrganizationUsageResource | None
signals_credits: OrganizationUsageResource | None
posthog_code_credits: OrganizationUsageResource | None
+ posthog_code_token_credits: OrganizationUsageResource | None
+ sandbox_compute_credits: OrganizationUsageResource | None
+ sandbox_compute_cpu_millicore_seconds: OrganizationUsageResource | None
+ sandbox_compute_memory_mib_seconds: OrganizationUsageResource | None
workflow_emails: OrganizationUsageResource | None
workflow_push: OrganizationUsageResource | None
workflow_destinations_dispatched: OrganizationUsageResource | None