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): batch quota usage updates (#118222)

Alex Mays5d939c21d0a4
diff --git a/ee/billing/quota_limiting.py b/ee/billing/quota_limiting.py
index 89ab3be44287..b574b8c846af 100644
--- a/ee/billing/quota_limiting.py
+++ b/ee/billing/quota_limiting.py
@@ -1,14 +1,17 @@
import copy
import json
-from collections.abc import Callable, Iterable, Mapping, Sequence
+from collections.abc import Callable, Collection, Iterable, Mapping, Sequence
from datetime import datetime, timedelta
from enum import Enum
+from itertools import batched, groupby
from time import time
from typing import Any, Optional, TypedDict, cast
from django.conf import settings
-from django.db import close_old_connections, transaction
+from django.db import DatabaseError, InterfaceError, close_old_connections, transaction
+from django.db.models import TextField
from django.db.models.expressions import RawSQL
+from django.db.models.functions import MD5, Cast
from django.utils import timezone
import structlog
@@ -35,8 +38,12 @@ from posthog.tasks.usage_report import (
from posthog.usage_counters import UsageCounter, UsageCounterService, log_usage_counter_comparisons
from posthog.utils import get_current_day
+from ee.billing.quota_usage import QuotaUsageBatch, retry_quota_database_operation
+
logger = structlog.get_logger(__name__)
+QUOTA_ORGANIZATION_BATCH_SIZE = 1_000
+
QUOTA_LIMIT_DATA_RETENTION_FLAG = "retain-data-past-quota-limit"
QUOTA_LIMIT_MEDIUM_TRUST_GRACE_PERIOD_DAYS = 1
@@ -425,9 +432,12 @@ def _signals_credited_refund_offset(organization: Organization, resource: QuotaR
def org_quota_limited_until(
organization: Organization,
resource: QuotaResource,
- previously_quota_limited_team_tokens: list[str],
+ previously_quota_limited_team_tokens: Collection[str],
team_tokens: Sequence[str] | None = None,
+ *,
+ batch: QuotaUsageBatch | None = None,
) -> Optional[OrgQuotaLimitingInformation]:
+ report_action = batch.report_action if batch is not None else report_organization_action
if not organization.usage:
return None
@@ -443,7 +453,7 @@ def org_quota_limited_until(
if limit is None:
if quota_limiting_suspended_until is not None or quota_limited_until is not None:
- report_organization_action(
+ report_action(
organization,
"org_quota_limited_until",
properties={
@@ -455,7 +465,10 @@ def org_quota_limited_until(
},
)
update_organization_usage_fields(
- organization, resource, {"quota_limited_until": None, "quota_limiting_suspended_until": None}
+ organization,
+ resource,
+ {"quota_limited_until": None, "quota_limiting_suspended_until": None},
+ batch=batch,
)
return None
@@ -524,7 +537,7 @@ def org_quota_limited_until(
if not is_over_limit:
if quota_limiting_suspended_until or quota_limited_until:
# If they are not over limit, we want to remove the suspension if it exists
- report_organization_action(
+ report_action(
organization,
"org_quota_limited_until",
properties={
@@ -536,13 +549,16 @@ def org_quota_limited_until(
},
)
update_organization_usage_fields(
- organization, resource, {"quota_limited_until": None, "quota_limiting_suspended_until": None}
+ organization,
+ resource,
+ {"quota_limited_until": None, "quota_limiting_suspended_until": None},
+ batch=batch,
)
return None
# 1b. never drop
if resource not in GRACE_PERIOD_EXEMPT_RESOURCES and organization.never_drop_data:
- report_organization_action(
+ report_action(
organization,
"org_quota_limited_until",
properties={
@@ -555,7 +571,7 @@ def org_quota_limited_until(
},
)
update_organization_usage_fields(
- organization, resource, {"quota_limited_until": None, "quota_limiting_suspended_until": None}
+ organization, resource, {"quota_limited_until": None, "quota_limiting_suspended_until": None}, batch=batch
)
return None
@@ -566,7 +582,7 @@ def org_quota_limited_until(
# 2a. already being limited
if team_being_limited or quota_limited_until:
# They are already being limited, do not update their status.
- report_organization_action(
+ report_action(
organization,
"org_quota_limited_until",
properties={
@@ -579,7 +595,10 @@ def org_quota_limited_until(
},
)
update_organization_usage_fields(
- organization, resource, {"quota_limited_until": billing_period_end, "quota_limiting_suspended_until": None}
+ organization,
+ resource,
+ {"quota_limited_until": billing_period_end, "quota_limiting_suspended_until": None},
+ batch=batch,
)
return {
"quota_limited_until": billing_period_end,
@@ -595,7 +614,7 @@ def org_quota_limited_until(
group_properties={"organization": {"id": str(organization.id)}},
):
# Don't drop data for this org but record that they would have been limited.
- report_organization_action(
+ report_action(
organization,
"org_quota_limited_until",
properties={
@@ -607,7 +626,7 @@ def org_quota_limited_until(
},
)
update_organization_usage_fields(
- organization, resource, {"quota_limited_until": None, "quota_limiting_suspended_until": None}
+ organization, resource, {"quota_limited_until": None, "quota_limiting_suspended_until": None}, batch=batch
)
return None
@@ -629,7 +648,7 @@ def org_quota_limited_until(
organization.customer_trust_scores = {**(organization.customer_trust_scores or {}), resource.value: 0}
organization.save(update_fields=["customer_trust_scores"])
- report_organization_action(
+ report_action(
organization,
"org_quota_limited_until",
properties={
@@ -641,7 +660,10 @@ def org_quota_limited_until(
},
)
update_organization_usage_fields(
- organization, resource, {"quota_limited_until": billing_period_end, "quota_limiting_suspended_until": None}
+ organization,
+ resource,
+ {"quota_limited_until": billing_period_end, "quota_limiting_suspended_until": None},
+ batch=batch,
)
return {
"quota_limited_until": billing_period_end,
@@ -651,7 +673,7 @@ def org_quota_limited_until(
# 2c. low trust
elif trust_score == 3 and minimum_grace_period == 0:
# Low trust, immediately limit
- report_organization_action(
+ report_action(
organization,
"org_quota_limited_until",
properties={
@@ -663,7 +685,10 @@ def org_quota_limited_until(
},
)
update_organization_usage_fields(
- organization, resource, {"quota_limited_until": billing_period_end, "quota_limiting_suspended_until": None}
+ organization,
+ resource,
+ {"quota_limited_until": billing_period_end, "quota_limiting_suspended_until": None},
+ batch=batch,
)
return {
"quota_limited_until": billing_period_end,
@@ -680,7 +705,7 @@ def org_quota_limited_until(
(datetime.fromtimestamp(quota_limiting_suspended_until) - timedelta(grace_period_days)).timestamp()
< billing_period_start
):
- report_organization_action(
+ report_action(
organization,
"org_quota_limited_until",
properties={
@@ -733,6 +758,7 @@ def org_quota_limited_until(
organization,
resource,
{"quota_limited_until": None, "quota_limiting_suspended_until": quota_limiting_suspended_until},
+ batch=batch,
)
return {
"quota_limited_until": None,
@@ -741,7 +767,7 @@ def org_quota_limited_until(
elif today_end.timestamp() <= quota_limiting_suspended_until:
# If the suspension is still active (after today's end), we want to return the existing suspension date
- report_organization_action(
+ report_action(
organization,
"org_quota_limited_until",
properties={
@@ -756,6 +782,7 @@ def org_quota_limited_until(
organization,
resource,
{"quota_limited_until": None, "quota_limiting_suspended_until": quota_limiting_suspended_until},
+ batch=batch,
)
return {
"quota_limited_until": None,
@@ -763,7 +790,7 @@ def org_quota_limited_until(
}
else:
# If the suspension is expired, we want to limit the org
- report_organization_action(
+ report_action(
organization,
"org_quota_limited_until",
properties={
@@ -777,6 +804,7 @@ def org_quota_limited_until(
organization,
resource,
{"quota_limited_until": billing_period_end, "quota_limiting_suspended_until": None},
+ batch=batch,
)
return {
"quota_limited_until": billing_period_end,
@@ -785,7 +813,10 @@ def org_quota_limited_until(
else:
# Should never reach here - return the default behavior just to be safe
update_organization_usage_fields(
- organization, resource, {"quota_limited_until": billing_period_end, "quota_limiting_suspended_until": None}
+ organization,
+ resource,
+ {"quota_limited_until": billing_period_end, "quota_limiting_suspended_until": None},
+ batch=batch,
)
return {
"quota_limited_until": billing_period_end,
@@ -1017,7 +1048,9 @@ def _merge_informational_usage_summary(
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:
+def _patch_organization_usage_jsonb(
+ organization: Organization, ops: Sequence[tuple[list[str], Any]], *, batch: QuotaUsageBatch | None = None
+) -> None:
"""
Applies a sequence of partial-write operations to `posthog_organization.usage` for
one row, composing them into a single nested `jsonb_set` / `#-` expression so that
@@ -1033,6 +1066,10 @@ def _patch_organization_usage_jsonb(organization: Organization, ops: Sequence[tu
if not ops:
return
+ if batch is not None:
+ batch.patch(organization, ops)
+ return
+
sql_expr = "usage"
params: list[Any] = []
for path, value in ops:
@@ -1048,7 +1085,9 @@ def _patch_organization_usage_jsonb(organization: Organization, ops: Sequence[tu
Organization.objects.filter(id=organization.id).update(usage=RawSQL(sql_expr, params))
-def _patch_todays_usage(organization: Organization, todays_report: "UsageCounters") -> bool:
+def _patch_todays_usage(
+ organization: Organization, todays_report: "UsageCounters", *, batch: QuotaUsageBatch | None = None
+) -> bool:
"""
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
@@ -1069,7 +1108,7 @@ def _patch_todays_usage(organization: Organization, todays_report: "UsageCounter
if not ops:
return False
- _patch_organization_usage_jsonb(organization, ops)
+ _patch_organization_usage_jsonb(organization, ops, batch=batch)
return True
@@ -1097,6 +1136,8 @@ def _identify_refresh_candidates(
teams_by_org: dict[str, list[str]],
previously_quota_limited_team_tokens: dict[str, list[str]],
previously_quota_limiting_suspended_team_tokens: dict[str, list[str]],
+ *,
+ redis_indicator_lookup: dict[str, set[str]] | None = None,
) -> set[str]:
"""
Returns the set of org ids whose quota decision could change in this run, computed
@@ -1114,11 +1155,12 @@ def _identify_refresh_candidates(
"""
# Either Redis set is reason enough to refresh, so union them once up front and
# do a single membership check per resource below.
- redis_indicator_lookup: dict[str, set[str]] = {
- resource.value: set(previously_quota_limited_team_tokens.get(resource.value, []))
- | set(previously_quota_limiting_suspended_team_tokens.get(resource.value, []))
- for resource in QuotaResource
- }
+ if redis_indicator_lookup is None:
+ redis_indicator_lookup = {
+ resource.value: set(previously_quota_limited_team_tokens.get(resource.value, []))
+ | set(previously_quota_limiting_suspended_team_tokens.get(resource.value, []))
+ for resource in QuotaResource
+ }
candidates: set[str] = set()
for org_id, todays_report in todays_usage_report.items():
@@ -1181,6 +1223,69 @@ class QuotaLimitingRunResult:
stats: dict[str, float | int]
+@frozen
+class _QuotaUsageReports:
+ usage: dict[str, UsageCounters]
+ organizations: dict[str, Organization]
+ team_tokens: dict[str, list[str]]
+
+
+def _aggregate_quota_usage(teams: Sequence[Team], all_data: dict[str, dict[int, int]]) -> _QuotaUsageReports:
+ todays_usage_report: dict[str, UsageCounters] = {}
+ orgs_by_id: dict[str, Organization] = {}
+ teams_by_org: dict[str, list[str]] = {}
+
+ # we iterate through all teams, and add their usage to the organization they belong to
+ for team in teams:
+ decide_requests = all_data["teams_with_decide_requests_count"].get(team.id, 0)
+ local_evaluation_requests = all_data["teams_with_local_evaluation_requests_count"].get(team.id, 0)
+
+ team_report = UsageCounters(
+ events=all_data["teams_with_event_count_in_period"].get(team.id, 0),
+ exceptions=all_data["teams_with_exceptions_captured_in_period"].get(team.id, 0),
+ recordings=all_data["teams_with_recording_count_in_period"].get(team.id, 0),
+ rows_synced=all_data["teams_with_rows_synced_in_period"].get(team.id, 0),
+ feature_flag_requests=decide_requests
+ + (local_evaluation_requests * 10), # Same weighting as in _get_team_report
+ api_queries_read_bytes=all_data["teams_with_api_queries_read_bytes"].get(team.id, 0),
+ survey_responses=all_data["teams_with_survey_responses_count_in_period"].get(team.id, 0),
+ llm_events=all_data["teams_with_ai_event_count_in_period"].get(team.id, 0),
+ 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),
+ workflow_push=all_data["teams_with_workflow_push_sent_in_period"].get(team.id, 0),
+ workflow_destinations_dispatched=all_data["teams_with_workflow_destinations_in_period"].get(team.id, 0),
+ logs_mb_ingested=all_data["teams_with_logs_mb_in_period"].get(team.id, 0),
+ replay_vision_credits=all_data["teams_with_replay_vision_credits_used_in_period"].get(team.id, 0),
+ )
+
+ org_id = str(team.organization.id)
+
+ if org_id not in todays_usage_report:
+ orgs_by_id[org_id] = team.organization
+ todays_usage_report[org_id] = team_report.copy()
+ else:
+ org_report = todays_usage_report[org_id]
+ for field in team_report:
+ org_report[field] += team_report[field] # type: ignore
+
+ if team.api_token:
+ teams_by_org.setdefault(org_id, []).append(team.api_token)
+
+ return _QuotaUsageReports(usage=todays_usage_report, organizations=orgs_by_id, team_tokens=teams_by_org)
+
+
def update_all_orgs_billing_quotas(
dry_run: bool = False,
progress_callback: Callable[[str, str, str], None] | None = None,
@@ -1286,211 +1391,236 @@ def update_all_orgs_billing_quotas(
if progress_callback:
progress_callback("queries_done", f"duration={queries_duration_s}s", f"query_count={len(all_data)}")
- teams: Sequence[Team] = list(
- iter_billable_teams(
- team_fields=("id", "api_token"),
- organization_fields=(
- "id",
- "usage",
- "created_at",
- "never_drop_data",
- "customer_trust_scores",
- "customer_id",
- ),
- )
+ teams_iterator = iter_billable_teams(
+ team_fields=("id", "api_token"),
+ organization_fields=("id", "usage", "created_at", "never_drop_data", "customer_trust_scores", "customer_id"),
+ buffer_teams=True,
+ )
+ total_orgs = (
+ Team.objects.filter(is_demo=False, organization__for_internal_metrics=False)
+ .values("organization_id")
+ .distinct()
+ .count()
)
-
- todays_usage_report: dict[str, UsageCounters] = {}
- orgs_by_id: dict[str, Organization] = {}
- teams_by_org: dict[str, list[str]] = {}
-
- # we iterate through all teams, and add their usage to the organization they belong to
- for team in teams:
- decide_requests = all_data["teams_with_decide_requests_count"].get(team.id, 0)
- local_evaluation_requests = all_data["teams_with_local_evaluation_requests_count"].get(team.id, 0)
-
- team_report = UsageCounters(
- events=all_data["teams_with_event_count_in_period"].get(team.id, 0),
- exceptions=all_data["teams_with_exceptions_captured_in_period"].get(team.id, 0),
- recordings=all_data["teams_with_recording_count_in_period"].get(team.id, 0),
- rows_synced=all_data["teams_with_rows_synced_in_period"].get(team.id, 0),
- feature_flag_requests=decide_requests
- + (local_evaluation_requests * 10), # Same weighting as in _get_team_report
- api_queries_read_bytes=all_data["teams_with_api_queries_read_bytes"].get(team.id, 0),
- survey_responses=all_data["teams_with_survey_responses_count_in_period"].get(team.id, 0),
- llm_events=all_data["teams_with_ai_event_count_in_period"].get(team.id, 0),
- 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),
- workflow_push=all_data["teams_with_workflow_push_sent_in_period"].get(team.id, 0),
- workflow_destinations_dispatched=all_data["teams_with_workflow_destinations_in_period"].get(team.id, 0),
- logs_mb_ingested=all_data["teams_with_logs_mb_in_period"].get(team.id, 0),
- replay_vision_credits=all_data["teams_with_replay_vision_credits_used_in_period"].get(team.id, 0),
- )
-
- org_id = str(team.organization.id)
-
- if org_id not in todays_usage_report:
- orgs_by_id[org_id] = team.organization
- todays_usage_report[org_id] = team_report.copy()
- else:
- org_report = todays_usage_report[org_id]
- for field in team_report:
- org_report[field] += team_report[field] # type: ignore
-
- if team.api_token:
- teams_by_org.setdefault(org_id, []).append(team.api_token)
-
- # Now we have the usage for all orgs for the current day
- # orgs_by_id is a dict of orgs by id (e.g. {"018e9acf-b488-0000-259c-534bcef40359": <Organization: 018e9acf-b488-0000-259c-534bcef40359>})
- # todays_usage_report is a dict of orgs by id with their usage for the current day (e.g. {"018e9acf-b488-0000-259c-534bcef40359": {"events": 100, "exceptions": 100, "recordings": 100, "rows_synced": 100, "feature_flag_requests": 100, "api_queries_read_bytes": 100, "survey_responses": 100}})
quota_limited_orgs: dict[str, dict[str, int]] = {x.value: {} for x in QuotaResource}
quota_limiting_suspended_orgs: dict[str, dict[str, int]] = {x.value: {} for x in QuotaResource}
+ 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
+ failed_org_ids: set[str] = set()
+ failed_team_tokens: set[str] = set()
- # Get the current quota limits so we can track to PostHog if it changes
- orgs_with_changes = set()
- 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.
- # `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(
+ # Reconciliation must use this run's own snapshot, not the asynchronous 30-second cache.
+ previously_quota_limited_team_tokens = {
+ resource.value: list_limited_team_attributes(
resource, QuotaLimitingCaches.QUOTA_LIMITER_CACHE_KEY, use_cache=False
)
- previously_quota_limiting_suspended_team_tokens[resource.value] = list_limited_team_attributes(
+ for resource in QuotaResource
+ }
+ previously_quota_limiting_suspended_team_tokens = {
+ resource.value: list_limited_team_attributes(
resource, QuotaLimitingCaches.QUOTA_LIMITING_SUSPENDED_KEY, use_cache=False
)
+ for resource in QuotaResource
+ }
+ previously_quota_limited_team_token_sets = {
+ field: set(tokens) for field, tokens in previously_quota_limited_team_tokens.items()
+ }
+ redis_indicator_lookup = {
+ field: tokens | set(previously_quota_limiting_suspended_team_tokens[field])
+ for field, tokens in previously_quota_limited_team_token_sets.items()
+ }
+ previously_recordings_zset_tokens = _get_previous_recordings_zset_tokens()
- 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.
-
- # Identify the orgs whose quota decision could change in this run
- candidates_start = time()
- refresh_candidates = _identify_refresh_candidates(
- orgs_by_id,
- todays_usage_report,
- teams_by_org,
- previously_quota_limited_team_tokens,
- previously_quota_limiting_suspended_team_tokens,
- )
- logger.info(
- "quota_limiting_run",
- phase="refresh_candidates",
- status="done",
- duration_ms=round((time() - candidates_start) * 1000, 1),
- candidate_count=len(refresh_candidates),
- org_count=len(todays_usage_report),
- )
-
- # Find all orgs that should be rate limited
- total_orgs = len(todays_usage_report)
logger.info("quota_limiting_run", phase="org_loop", status="start", org_count=total_orgs)
org_loop_start = time()
- orgs_processed = 0
- orgs_limited_count = 0
- orgs_suspended_count = 0
- refresh_count = 0
- refresh_total_seconds = 0.0
+ orgs_processed = orgs_limited_count = orgs_suspended_count = refresh_count = candidate_count = orgs_skipped = 0
+ refresh_total_seconds = candidates_total_seconds = 0.0
- for org_id, todays_report in todays_usage_report.items():
- # Check and refresh DB connections if needed on every iteration.
- # The database_sync_to_async wrapper only closes connections at start/end,
- # but this loop can run for up to 30min.
- # Skip in tests to avoid breaking test transactions.
+ def discard_decision(org_id: str, team_tokens: list[str]) -> None:
+ failed_org_ids.add(org_id)
+ failed_team_tokens.update(team_tokens)
+ for resource in QuotaResource:
+ quota_limited_orgs[resource.value].pop(org_id, None)
+ quota_limiting_suspended_orgs[resource.value].pop(org_id, None)
+ # The shared iterator keeps an organization's teams contiguous, including across read pages.
+ organization_teams = (list(group) for _, group in groupby(teams_iterator, key=lambda team: team.organization_id))
+ for team_groups in batched(organization_teams, QUOTA_ORGANIZATION_BATCH_SIZE, strict=False):
if not settings.TEST:
close_old_connections()
-
- try:
+ teams = [team for group in team_groups for team in group]
+ reports = _aggregate_quota_usage(teams, all_data)
+ orgs_by_id = reports.organizations
+ teams_by_org = reports.team_tokens
+ candidates_start = time()
+ refresh_candidates = _identify_refresh_candidates(
+ orgs_by_id,
+ reports.usage,
+ teams_by_org,
+ previously_quota_limited_team_tokens,
+ previously_quota_limiting_suspended_team_tokens,
+ redis_indicator_lookup=redis_indicator_lookup,
+ )
+ candidate_count += len(refresh_candidates)
+ candidates_total_seconds += time() - candidates_start
+ refresh_start = time()
+ fresh_orgs = {
+ str(org.id): org
+ for org in retry_quota_database_operation(
+ Organization.objects.filter(id__in=refresh_candidates)
+ .only("id", "usage", "customer_trust_scores", "never_drop_data")
+ .annotate(usage_md5=MD5(Cast("usage", output_field=TextField())))
+ .in_bulk
+ ).values()
+ }
+ refresh_count += len(fresh_orgs)
+ refresh_total_seconds += time() - refresh_start
+ usage_batch = QuotaUsageBatch()
+ for org_id, todays_report in reports.usage.items():
org = orgs_by_id[org_id]
-
- if org.usage and org.usage.get("period"):
- if org_id in refresh_candidates:
- # Refresh just before the decision so `org_quota_limited_until`
- # below reads fresh `usage` / `customer_trust_scores` /`never_drop_data`.
- refresh_call_start = time()
- org.refresh_from_db(fields=["usage", "customer_trust_scores", "never_drop_data"])
- refresh_total_seconds += time() - refresh_call_start
- refresh_count += 1
- if (org.usage or {}).get(QuotaResource.SIGNALS_CREDITS.value):
- # The queries-phase snapshot predates any push-refresh that fired during
- # this run (`refresh_org_self_driving_quota` raises `todays_usage` the
- # moment a PR lands); writing the older snapshot back would unpause an
- # over-limit org until the next tick. Recount live instead — as a count
- # of the current window it also keeps legitimate decreases (day
- # rollover, refunds) intact.
- todays_report["signals_credits"] = get_self_driving_credits_used_in_period_for_org(
- org_id, period.start, period.end
+ try:
+ if org.usage and org.usage.get("period"):
+ if org_id in refresh_candidates:
+ fresh = fresh_orgs.get(org_id)
+ if fresh is None:
+ # Deletion cascades to the teams; drop their old quota entries during reconciliation.
+ continue
+ org.usage = fresh.usage
+ org.customer_trust_scores = fresh.customer_trust_scores
+ org.never_drop_data = fresh.never_drop_data
+ usage_batch.require_unchanged_usage(org, fresh.usage_md5)
+ if (org.usage or {}).get(QuotaResource.SIGNALS_CREDITS.value):
+ # Push refreshes can raise signals usage after the source snapshot. Recount before writing it.
+ todays_report["signals_credits"] = get_self_driving_credits_used_in_period_for_org(
+ org_id, period.start, period.end
+ )
+ _patch_todays_usage(org, todays_report, batch=usage_batch)
+ org_is_limited = org_is_suspended = False
+ for resource in QuotaResource:
+ field = resource.value
+ result = org_quota_limited_until(
+ org,
+ resource,
+ previously_quota_limited_team_token_sets[field],
+ teams_by_org.get(org_id, []),
+ batch=usage_batch,
)
+ if result:
+ quota_limited_until = result.get("quota_limited_until")
+ limiting_suspended_until = result.get("quota_limiting_suspended_until")
+ if limiting_suspended_until:
+ quota_limiting_suspended_orgs[field][org_id] = limiting_suspended_until
+ org_is_suspended = True
+ elif quota_limited_until:
+ quota_limited_orgs[field][org_id] = quota_limited_until
+ org_is_limited = True
+ orgs_limited_count += org_is_limited
+ orgs_suspended_count += org_is_suspended
+ except Exception as error:
+ if isinstance(error, (DatabaseError, InterfaceError)) and not settings.TEST:
+ close_old_connections()
+ usage_batch.discard(org)
+ discard_decision(org_id, teams_by_org.get(org_id, []))
+ capture_exception(error, {"organization_id": org_id})
+ finally:
+ orgs_processed += 1
+
+ # Do not reconcile Redis from decisions whose database writes failed.
+ # A skipped organization's usage changed after this chunk read it, and that writer also updates Redis.
+ for skipped_org_id in map(str, usage_batch.write()):
+ orgs_limited_count -= any(skipped_org_id in orgs for orgs in quota_limited_orgs.values())
+ orgs_suspended_count -= any(skipped_org_id in orgs for orgs in quota_limiting_suspended_orgs.values())
+ orgs_skipped += 1
+ discard_decision(skipped_org_id, teams_by_org.get(skipped_org_id, []))
+
+ orgs_with_changes: set[str] = set()
+ # Convert the org ids to team tokens
+ for team in teams:
+ team_was_in_recordings_zset = team.api_token in previously_recordings_zset_tokens
+ if str(team.organization_id) in failed_org_ids:
+ # Reconciliation still purges expired entries, and only a rebuild clears an expired recordings limit.
+ if team_was_in_recordings_zset:
+ recordings_transitioned_team_ids.add(team.id)
+ continue
+ for field in quota_limited_orgs:
+ org_id = str(team.organization.id)
+ if 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 added
+ if team.api_token not in previously_quota_limited_team_token_sets[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 removed
+ if team.api_token in previously_quota_limited_team_token_sets[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)
- _patch_todays_usage(org, todays_report)
-
- org_is_limited = False
- org_is_suspended = False
- 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], 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")
- if limiting_suspended_until:
- quota_limiting_suspended_orgs[field][org_id] = limiting_suspended_until
- org_is_suspended = True
- elif quota_limited_until:
- quota_limited_orgs[field][org_id] = quota_limited_until
- org_is_limited = True
- if org_is_suspended:
- orgs_suspended_count += 1
- if org_is_limited:
- orgs_limited_count += 1
-
- orgs_processed += 1
- if orgs_processed % 1000 == 0:
- logger.info(
- "quota_limiting_run",
- phase="org_loop",
- status="progress",
- orgs_processed=orgs_processed,
- org_count=total_orgs,
- elapsed_ms=round((time() - org_loop_start) * 1000, 1),
- )
- if progress_callback:
- progress_callback(
- "org_processing",
- f"{orgs_processed}/{total_orgs}",
- f"limited={orgs_limited_count},suspended={orgs_suspended_count}",
- )
- 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
- # `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
- # out of the catch.
- orgs_processed += 1
- capture_exception(e, {"organization_id": org_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}})
+ # quota_limiting_suspended_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}})
+
+ for org_id in orgs_with_changes:
+ properties = {
+ "quota_limited_events": quota_limited_orgs["events"].get(org_id, None),
+ "quota_limited_exceptions": quota_limited_orgs["exceptions"].get(org_id, None),
+ "quota_limited_recordings": quota_limited_orgs["recordings"].get(org_id, None),
+ "quota_limited_rows_synced": quota_limited_orgs["rows_synced"].get(org_id, None),
+ "quota_limited_feature_flags": quota_limited_orgs["feature_flag_requests"].get(org_id, None),
+ "quota_limited_api_queries": quota_limited_orgs["api_queries_read_bytes"].get(org_id, None),
+ "quota_limited_survey_responses": quota_limited_orgs["survey_responses"].get(org_id, None),
+ "quota_limited_llm_events": quota_limited_orgs["llm_events"].get(org_id, None),
+ "quota_limited_cdp_trigger_events": quota_limited_orgs["cdp_trigger_events"].get(org_id, None),
+ "quota_limited_rows_exported": quota_limited_orgs["rows_exported"].get(org_id, None),
+ }
+
+ usage_batch.report_action(
+ orgs_by_id[org_id],
+ "organization quota limits changed",
+ properties=properties,
+ group_properties=properties,
+ )
+ usage_batch.publish()
+ logger.info(
+ "quota_limiting_run",
+ phase="org_loop",
+ status="progress",
+ orgs_processed=orgs_processed,
+ org_count=total_orgs,
+ elapsed_ms=round((time() - org_loop_start) * 1000, 1),
+ )
+ if progress_callback:
+ progress_callback(
+ "org_processing",
+ f"{orgs_processed}/{total_orgs}",
+ f"limited={orgs_limited_count},suspended={orgs_suspended_count}",
+ )
+
+ if not settings.TEST:
+ close_old_connections()
+ logger.info(
+ "quota_limiting_run",
+ phase="refresh_candidates",
+ status="done",
+ duration_ms=round(candidates_total_seconds * 1000, 1),
+ candidate_count=candidate_count,
+ org_count=orgs_processed,
+ )
logger.info(
"quota_limiting_run",
phase="org_loop",
@@ -1501,6 +1631,8 @@ def update_all_orgs_billing_quotas(
orgs_suspended=orgs_suspended_count,
refresh_count=refresh_count,
refresh_total_ms=round(refresh_total_seconds * 1000, 1),
+ orgs_failed=len(failed_org_ids),
+ orgs_skipped=orgs_skipped,
)
if progress_callback:
progress_callback(
@@ -1509,68 +1641,17 @@ def update_all_orgs_billing_quotas(
f"limited={orgs_limited_count},suspended={orgs_suspended_count}",
)
- # Now we have the teams that are currently under quota limits
- # quota_limited_orgs is a dict of resources to org ids (e.g. {"events": {"018e9acf-b488-0000-259c-534bcef40359": 1737867600}, "exceptions": {"018e9acf-b488-0000-259c-534bcef40359": 1737867600}, "recordings": {"018e9acf-b488-0000-259c-534bcef40359": 1737867600}, "rows_synced": {"018e9acf-b488-0000-259c-534bcef40359": 1737867600}, "feature_flag_requests": {"018e9acf-b488-0000-259c-534bcef40359": 1737867600}, "api_queries_read_bytes": {"018e9acf-b488-0000-259c-534bcef40359": 1737867600}, "survey_responses": {"018e9acf-b488-0000-259c-534bcef40359": 1737867600}})
- # quota_limiting_suspended_orgs is a dict of resources to org ids (e.g. {"events": {"018e9acf-b488-0000-259c-534bcef40359": 1737867600}, "exceptions": {"018e9acf-b488-0000-259c-534bcef40359": 1737867600}, "recordings": {"018e9acf-b488-0000-259c-534bcef40359": 1737867600}, "rows_synced": {"018e9acf-b488-0000-259c-534bcef40359": 1737867600}, "feature_flag_requests": {"018e9acf-b488-0000-259c-534bcef40359": 1737867600}, "api_queries_read_bytes": {"018e9acf-b488-0000-259c-534bcef40359": 1737867600}, "survey_responses": {"018e9acf-b488-0000-259c-534bcef40359": 1737867600}})
-
- 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 tokens
- for 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_tokens
- if 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 added
- if 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 removed
- if 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}})
- # quota_limiting_suspended_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}})
-
- for org_id in orgs_with_changes:
- properties = {
- "quota_limited_events": quota_limited_orgs["events"].get(org_id, None),
- "quota_limited_exceptions": quota_limited_orgs["exceptions"].get(org_id, None),
- "quota_limited_recordings": quota_limited_orgs["recordings"].get(org_id, None),
- "quota_limited_rows_synced": quota_limited_orgs["rows_synced"].get(org_id, None),
- "quota_limited_feature_flags": quota_limited_orgs["feature_flag_requests"].get(org_id, None),
- "quota_limited_api_queries": quota_limited_orgs["api_queries_read_bytes"].get(org_id, None),
- "quota_limited_survey_responses": quota_limited_orgs["survey_responses"].get(org_id, None),
- "quota_limited_llm_events": quota_limited_orgs["llm_events"].get(org_id, None),
- "quota_limited_cdp_trigger_events": quota_limited_orgs["cdp_trigger_events"].get(org_id, None),
- "quota_limited_rows_exported": quota_limited_orgs["rows_exported"].get(org_id, None),
- }
-
- report_organization_action(
- orgs_by_id[org_id],
- "organization quota limits changed",
- properties=properties,
- group_properties=properties,
- )
+ # A failed decision must not remove that organization's existing Redis state.
+ if failed_team_tokens:
+ for field in previously_quota_limited_team_tokens:
+ previously_quota_limited_team_tokens[field] = [
+ token for token in previously_quota_limited_team_tokens[field] if token not in failed_team_tokens
+ ]
+ previously_quota_limiting_suspended_team_tokens[field] = [
+ token
+ for token in previously_quota_limiting_suspended_team_tokens[field]
+ if token not in failed_team_tokens
+ ]
if not dry_run:
redis_start = time()
@@ -1657,7 +1738,7 @@ def update_organization_usage_field(organization: Organization, resource: QuotaR
def update_organization_usage_fields(
- organization: Organization, resource: QuotaResource, fields: dict[str, Any]
+ organization: Organization, resource: QuotaResource, fields: dict[str, Any], *, batch: QuotaUsageBatch | None = None
) -> None:
"""
Patches specific keys inside organization.usage[resource] using a partial-write
@@ -1693,4 +1774,5 @@ def update_organization_usage_fields(
_patch_organization_usage_jsonb(
organization,
[([resource.value, key], value) for key, value in fields.items()],
+ batch=batch,
)
diff --git a/ee/billing/quota_usage.py b/ee/billing/quota_usage.py
new file mode 100644
index 000000000000..a96ae8a9a2b1
--- /dev/null
+++ b/ee/billing/quota_usage.py
@@ -0,0 +1,143 @@
+import copy
+import json
+from collections import defaultdict
+from collections.abc import Callable, Sequence
+from time import sleep
+from typing import Any, TypeVar
+from uuid import UUID
+
+from django.db import InterfaceError, OperationalError, connection, transaction
+
+import structlog
+
+from posthog.dataclasses import frozen
+from posthog.event_usage import report_organization_action
+from posthog.models.organization import Organization
+
+logger = structlog.get_logger(__name__)
+
+UsagePatch = tuple[list[str], Any]
+_PatchRow = tuple[UUID, str | None, list[Any]]
+T = TypeVar("T")
+
+
+def retry_quota_database_operation(operation: Callable[[], T]) -> T:
+ for attempt in range(2):
+ try:
+ return operation()
+ except (OperationalError, InterfaceError):
+ # Keep a caller-owned transaction open, but replace a lost autocommit connection.
+ if not connection.in_atomic_block:
+ connection.close()
+ logger.warning("quota_limiting_database_retry", attempt=attempt + 1)
+ sleep(0.1 * 2**attempt)
+ return operation()
+
+
+@frozen
+class _QuotaAction:
+ organization: Organization
+ event: str
+ properties: dict[str, Any] | None
+ group_properties: dict[str, Any] | None
+
+ def report(self) -> None:
+ report_organization_action(self.organization, self.event, self.properties, self.group_properties)
+
+
+class QuotaUsageBatch:
+ def __init__(self) -> None:
+ self._patches: dict[UUID, list[UsagePatch]] = {}
+ self._usage_md5: dict[UUID, str] = {}
+ self._actions: dict[UUID, list[_QuotaAction]] = {}
+
+ def patch(self, organization: Organization, operations: Sequence[UsagePatch]) -> None:
+ self._patches.setdefault(organization.id, []).extend(operations)
+
+ def require_unchanged_usage(self, organization: Organization, usage_md5: str) -> None:
+ # The decision read this usage. A different value at write time means the decision is stale.
+ self._usage_md5[organization.id] = usage_md5
+
+ def report_action(
+ self,
+ organization: Organization,
+ event: str,
+ properties: dict[str, Any] | None = None,
+ group_properties: dict[str, Any] | None = None,
+ ) -> None:
+ # Quota decisions mutate usage after reporting it, so deferred events need a snapshot.
+ self._actions.setdefault(organization.id, []).append(
+ _QuotaAction(
+ organization=organization,
+ event=event,
+ properties=copy.deepcopy(properties),
+ group_properties=copy.deepcopy(group_properties),
+ )
+ )
+
+ def discard(self, organization: Organization) -> None:
+ self._patches.pop(organization.id, None)
+ self._usage_md5.pop(organization.id, None)
+ self._actions.pop(organization.id, None)
+
+ def write(self) -> set[UUID]:
+ """Writes the patches and returns the organizations skipped because their usage changed."""
+ skipped = retry_quota_database_operation(self._write)
+ for org_id in skipped:
+ self._actions.pop(org_id, None)
+ self._patches.clear()
+ self._usage_md5.clear()
+ return skipped
+
+ def publish(self) -> None:
+ actions = [action for org_actions in self._actions.values() for action in org_actions]
+ self._actions.clear()
+ for action in actions:
+ transaction.on_commit(action.report)
+
+ def _write(self) -> set[UUID]:
+ groups: dict[tuple[tuple[tuple[str, ...], bool], ...], list[_PatchRow]] = defaultdict(list)
+ for org_id, operations in self._patches.items():
+ if operations:
+ shape = tuple((tuple(path), value is None) for path, value in operations)
+ values = [value for _, value in operations if value is not None]
+ groups[shape].append((org_id, self._usage_md5.get(org_id), values))
+
+ skipped: set[UUID] = set()
+ if not groups:
+ return skipped
+
+ # Each shape can need a separate statement; all of an organization's patches commit together.
+ with transaction.atomic():
+ for shape, rows in groups.items():
+ expression = "o.usage"
+ parameters: list[Any] = []
+ value_index = 0
+ for path, delete in shape:
+ if delete:
+ expression = f"({expression}) #- %s::text[]"
+ else:
+ expression = f"jsonb_set({expression}, %s::text[], v.v{value_index})"
+ value_index += 1
+ parameters.append(list(path))
+
+ array_sql = "%s::uuid[], %s::text[]" + ", %s::jsonb[]" * value_index
+ parameters.append([org_id for org_id, _, _ in rows])
+ parameters.append([usage_md5 for _, usage_md5, _ in rows])
+ parameters.extend([json.dumps(values[index]) for _, _, values in rows] for index in range(value_index))
+ columns = ", ".join(["id", "usage_md5", *(f"v{i}" for i in range(value_index))])
+ table = Organization._meta.db_table
+ sql = (
+ f"UPDATE {table} AS o SET usage = {expression} "
+ f"FROM UNNEST({array_sql}) AS v({columns}) "
+ "WHERE o.id = v.id AND (v.usage_md5 IS NULL OR md5(o.usage::text) = v.usage_md5) "
+ "RETURNING o.id"
+ )
+ with connection.cursor() as cursor:
+ # nosemgrep: python.django.security.audit.raw-query.avoid-raw-sql (identifiers come from model metadata and fixed templates; paths and values are parameters)
+ cursor.execute(sql, parameters)
+ written = {row[0] for row in cursor.fetchall()}
+ skipped.update(
+ org_id for org_id, usage_md5, _ in rows if usage_md5 is not None and org_id not in written
+ )
+ return skipped
diff --git a/ee/billing/test/test_quota_limiting.py b/ee/billing/test/test_quota_limiting.py
index 106cd51eb668..5c0de7f7f3b5 100644
--- a/ee/billing/test/test_quota_limiting.py
+++ b/ee/billing/test/test_quota_limiting.py
@@ -27,6 +27,7 @@ from ee.billing.quota_limiting import (
QUOTA_LIMIT_DATA_RETENTION_FLAG,
OrganizationUsageInfo,
QuotaLimitingCaches,
+ QuotaLimitingRunResult,
QuotaResource,
UsageCounters,
_identify_refresh_candidates,
@@ -43,6 +44,7 @@ from ee.billing.quota_limiting import (
update_org_billing_quotas,
update_organization_usage_fields,
)
+from ee.billing.quota_usage import QuotaUsageBatch
from ee.clickhouse.materialized_columns.columns import materialize
@@ -79,6 +81,10 @@ class TestQuotaLimiting(BaseTest):
self.redis_client.delete(f"@posthog/quota-limiting-suspended/ai_credits")
materialize("events", "$exception_values")
+ def _run_quota_limiting(self) -> QuotaLimitingRunResult:
+ with self.captureOnCommitCallbacks(execute=True):
+ return update_all_orgs_billing_quotas()
+
@patch("posthoganalytics.capture")
@patch("posthoganalytics.feature_enabled", return_value=True)
@time_machine.travel("2021-01-25T23:59:59Z", tick=False)
@@ -123,7 +129,7 @@ class TestQuotaLimiting(BaseTest):
),
patch("posthog.usage_counters.logger.info") as counter_log,
):
- result = update_all_orgs_billing_quotas()
+ result = self._run_quota_limiting()
counter_log.assert_any_call(
"usage_counter_comparison",
caller="quota_limiting",
@@ -192,7 +198,7 @@ class TestQuotaLimiting(BaseTest):
dict.fromkeys(team_tokens, 1612137599),
QuotaLimitingCaches.QUOTA_LIMITER_CACHE_KEY,
)
- result = update_all_orgs_billing_quotas()
+ result = self._run_quota_limiting()
# Check out many times it was called
assert patch_capture.call_count == 1 # 1 org event from org_quota_limited_until
# Find the org action call
@@ -256,8 +262,8 @@ class TestQuotaLimiting(BaseTest):
self.organization.save()
flush_persons_and_events()
- with self.assertNumQueries(FuzzyInt(3, 9)):
- result = update_all_orgs_billing_quotas()
+ with self.assertNumQueries(FuzzyInt(3, 10)):
+ result = self._run_quota_limiting()
assert patch_capture.call_count == 0 # No events should be captured since org won't be limited
assert result.quota_limited_orgs["events"] == {}
assert result.quota_limited_orgs["exceptions"] == {}
@@ -400,7 +406,7 @@ class TestQuotaLimiting(BaseTest):
team=self.team,
)
flush_persons_and_events()
- result = update_all_orgs_billing_quotas()
+ result = self._run_quota_limiting()
# Will be immediately rate limited as trust score was unset.
org_id = str(self.organization.id)
assert result.quota_limited_orgs["events"] == {org_id: 1612137599}
@@ -459,7 +465,7 @@ class TestQuotaLimiting(BaseTest):
"rows_exported": 0,
}
self.organization.save()
- result = update_all_orgs_billing_quotas()
+ result = self._run_quota_limiting()
assert result.quota_limited_orgs["events"] == {org_id: 1612137599}
assert result.quota_limiting_suspended_orgs["events"] == {}
@@ -474,7 +480,7 @@ class TestQuotaLimiting(BaseTest):
events={"usage": 99, "limit": 100, "todays_usage": 0},
)
self.organization.save()
- result = update_all_orgs_billing_quotas()
+ result = self._run_quota_limiting()
assert result.quota_limited_orgs["events"] == {}
assert result.quota_limiting_suspended_orgs["events"] == {org_id: 1611705600}
assert self.redis_client.zrange(f"@posthog/quota-limiting-suspended/events", 0, -1) == [
@@ -485,7 +491,7 @@ class TestQuotaLimiting(BaseTest):
# Check that limiting still suspended 23 hrs later
with time_machine.travel("2021-01-25T23:00:00Z", tick=False):
- result = update_all_orgs_billing_quotas()
+ result = self._run_quota_limiting()
assert result.quota_limited_orgs["events"] == {}
assert result.quota_limiting_suspended_orgs["events"] == {org_id: 1611705600}
@@ -506,7 +512,7 @@ class TestQuotaLimiting(BaseTest):
events={"usage": 109, "limit": 100, "quota_limiting_suspended_until": 1611705600},
)
self.organization.save()
- result = update_all_orgs_billing_quotas()
+ result = self._run_quota_limiting()
assert result.quota_limited_orgs["events"] == {org_id: 1612137599}
assert result.quota_limiting_suspended_orgs["events"] == {}
self.organization.refresh_from_db()
@@ -539,7 +545,7 @@ class TestQuotaLimiting(BaseTest):
events={"usage": 109, "limit": 100, "quota_limiting_suspended_until": 1611705600},
)
self.organization.save()
- result = update_all_orgs_billing_quotas()
+ result = self._run_quota_limiting()
assert_other_resources_not_limited(result.quota_limited_orgs, result.quota_limiting_suspended_orgs)
assert result.quota_limited_orgs["events"] == {}
assert result.quota_limiting_suspended_orgs["events"] == {org_id: 1611705600}
@@ -562,7 +568,7 @@ class TestQuotaLimiting(BaseTest):
events={"usage": 109, "limit": 100},
)
self.organization.save()
- result = update_all_orgs_billing_quotas()
+ result = self._run_quota_limiting()
assert_other_resources_not_limited(result.quota_limited_orgs, result.quota_limiting_suspended_orgs)
assert result.quota_limited_orgs["events"] == {}
assert result.quota_limiting_suspended_orgs["events"] == {org_id: 1611878400}
@@ -577,7 +583,7 @@ class TestQuotaLimiting(BaseTest):
events={"usage": 109, "limit": 100, "quota_limiting_suspended_until": 1611705600},
)
self.organization.save()
- result = update_all_orgs_billing_quotas()
+ result = self._run_quota_limiting()
assert_other_resources_not_limited(result.quota_limited_orgs, result.quota_limiting_suspended_orgs)
assert result.quota_limited_orgs["events"] == {org_id: 1612137599}
assert result.quota_limiting_suspended_orgs["events"] == {}
@@ -605,7 +611,7 @@ class TestQuotaLimiting(BaseTest):
)
self.organization.save()
- result = update_all_orgs_billing_quotas()
+ result = self._run_quota_limiting()
assert_other_resources_not_limited(result.quota_limited_orgs, result.quota_limiting_suspended_orgs)
assert result.quota_limited_orgs["events"] == {}
assert result.quota_limiting_suspended_orgs["events"] == {org_id: 1612137600}
@@ -1574,7 +1580,7 @@ class TestQuotaLimiting(BaseTest):
self.redis_client.zadd(f"@posthog/quota-limits/events", {team_token: 1612137599})
# Run the quota limiting check
- result = update_all_orgs_billing_quotas()
+ result = self._run_quota_limiting()
# Verify the organization is no longer quota limited
assert "events" in result.quota_limited_orgs
@@ -2836,7 +2842,9 @@ class TestPatchTodaysUsage(BaseTest):
# before and isn't bumped now.
assert self.organization.updated_at == before_updated_at
- def test_targeted_patch_does_not_clobber_concurrent_billing_write(self) -> None:
+ @parameterized.expand([("individual", False), ("batch", True)])
+ def test_targeted_patch_does_not_clobber_concurrent_billing_write(self, _name, batched_write) -> None:
+ batch = QuotaUsageBatch() if batched_write else None
self.organization.usage = {
"events": {"usage": 100, "limit": 1_000, "todays_usage": 0},
"period": ["2021-01-01T00:00:00Z", "2021-01-31T23:59:59Z"],
@@ -2854,7 +2862,9 @@ class TestPatchTodaysUsage(BaseTest):
# The stale in-memory org still believes limit=1000; the targeted patch must
# only touch `usage[events][todays_usage]` and leave billing-owned fields alone.
- changed = _patch_todays_usage(self.organization, _full_usage_counters(events=99))
+ changed = _patch_todays_usage(self.organization, _full_usage_counters(events=99), batch=batch)
+ if batch is not None:
+ batch.write()
assert changed is True
fresh = Organization.objects.get(id=self.organization.id)
@@ -2883,7 +2893,9 @@ class TestUpdateOrganizationUsageFields(BaseTest):
self.organization.refresh_from_db()
assert self.organization.updated_at == before_updated_at
- def test_set_and_delete_keys_in_one_call(self) -> None:
+ @parameterized.expand([("individual", False), ("batch", True)])
+ def test_set_and_delete_keys_in_one_call(self, _name, batched_write) -> None:
+ batch = QuotaUsageBatch() if batched_write else None
self.organization.usage = {
"events": {
"usage": 100,
@@ -2899,7 +2911,10 @@ class TestUpdateOrganizationUsageFields(BaseTest):
self.organization,
QuotaResource.EVENTS,
{"quota_limited_until": 1_800_000_000, "quota_limiting_suspended_until": None},
+ batch=batch,
)
+ if batch is not None:
+ batch.write()
# In-memory mirror.
assert self.organization.usage["events"]["quota_limited_until"] == 1_800_000_000
diff --git a/ee/billing/test/test_quota_usage.py b/ee/billing/test/test_quota_usage.py
new file mode 100644
index 000000000000..5e9d806783f4
--- /dev/null
+++ b/ee/billing/test/test_quota_usage.py
@@ -0,0 +1,307 @@
+import copy
+from typing import Any
+from uuid import UUID
+
+import time_machine
+from posthog.test.base import BaseTest
+from unittest.mock import patch
+
+from django.db import DatabaseError, InterfaceError, OperationalError, connection
+from django.test import override_settings
+
+from parameterized import parameterized
+
+from posthog.models import Organization, Team
+from posthog.redis import get_client
+from posthog.usage_counters import UsageCounter, UsageCounterReport
+
+from ee.billing.quota_limiting import QuotaLimitingCaches, QuotaResource, update_all_orgs_billing_quotas
+from ee.billing.quota_usage import QuotaUsageBatch
+
+
+class TestQuotaUsageBatch(BaseTest):
+ @parameterized.expand([("set", False), ("delete_only", True)])
+ def test_sql_shape_is_independent_of_batch_size(self, _name, delete_only) -> None:
+ other = Organization.objects.create(name="Other organization", slug="other-quota-organization")
+ organizations = [self.organization, other]
+ usage = {"events": {"usage": 10, "todays_usage": 0, "quota_limited_until": 1234}}
+ Organization.objects.filter(id__in=[org.id for org in organizations]).update(usage=usage)
+ statements = []
+
+ def record_update(execute, sql, params, many, context):
+ if sql.startswith("UPDATE posthog_organization AS o"):
+ statements.append((sql, len(params)))
+ return execute(sql, params, many, context)
+
+ with connection.execute_wrapper(record_update):
+ for batch_size in (1, 2):
+ batch = QuotaUsageBatch()
+ for index, org in enumerate(organizations[:batch_size], start=1):
+ batch.patch(
+ org,
+ [
+ (["events", "todays_usage"], None if delete_only else index * 20),
+ (["events", "quota_limited_until"], None if delete_only else index * 100),
+ ],
+ )
+ batch.write()
+
+ assert len(statements) == 2
+ assert statements[0] == statements[1]
+ for index, org in enumerate(organizations, start=1):
+ org.refresh_from_db()
+ expected = {"usage": 10}
+ if not delete_only:
+ expected.update(todays_usage=index * 20, quota_limited_until=index * 100)
+ assert org.usage == {"events": expected}
+
+ @parameterized.expand([("all_present", False), ("deleted_organization", True)])
+ def test_multiple_patches_preserve_other_organizations_and_fields(self, _name, delete_second) -> None:
+ other = Organization.objects.create(name="Other organization", slug="other-quota-organization")
+ usage = {"events": {"usage": 10, "limit": 100, "todays_usage": 0}, "period": ["start", "end"]}
+ Organization.objects.filter(id__in=[self.organization.id, other.id]).update(usage=usage)
+ batch = QuotaUsageBatch()
+ batch.patch(self.organization, [(["events", "todays_usage"], 20)])
+ batch.patch(self.organization, [(["events", "quota_limited_until"], 1234)])
+ batch.patch(other, [(["events", "todays_usage"], 30)])
+ if delete_second:
+ other.delete()
+
+ batch.write()
+
+ self.organization.refresh_from_db()
+ assert self.organization.usage == {
+ **usage,
+ "events": {"usage": 10, "limit": 100, "todays_usage": 20, "quota_limited_until": 1234},
+ }
+ if not delete_second:
+ other.refresh_from_db()
+ assert other.usage == {**usage, "events": {"usage": 10, "limit": 100, "todays_usage": 30}}
+
+ @parameterized.expand(
+ [("transient", OperationalError, 1), ("exhausted", OperationalError, 3), ("non_transient", DatabaseError, 1)]
+ )
+ @patch("posthoganalytics.capture")
+ @patch("ee.billing.quota_usage.sleep")
+ def test_failed_statement_rolls_back_batch_before_retry_or_events(
+ self, _name, error_type, failures, _sleep, capture
+ ) -> None:
+ other = Organization.objects.create(name="Other organization", slug="other-quota-organization")
+ usage = {"events": {"usage": 10, "limit": 100, "todays_usage": 0}}
+ Organization.objects.filter(id__in=[self.organization.id, other.id]).update(usage=usage)
+ batch = QuotaUsageBatch()
+ batch.patch(self.organization, [(["events", "todays_usage"], 20)])
+ batch.patch(other, [(["events", "todays_usage"], 30), (["events", "quota_limited_until"], 1234)])
+ properties = {"usage": {"events": 20}}
+ batch.report_action(self.organization, "organization quota limits changed", properties)
+ properties["usage"]["events"] = 999
+ writes = 0
+ errors = 0
+
+ def fail_second_statement(execute, sql, params, many, context):
+ nonlocal writes, errors
+ if sql.startswith("UPDATE posthog_organization AS o"):
+ writes += 1
+ if writes % 2 == 1:
+ assert Organization.objects.get(id=self.organization.id).usage == usage
+ assert Organization.objects.get(id=other.id).usage == usage
+ elif errors < failures:
+ errors += 1
+ raise error_type("synthetic write failure")
+ return execute(sql, params, many, context)
+
+ succeeds = error_type is OperationalError and failures == 1
+ with connection.execute_wrapper(fail_second_statement), self.captureOnCommitCallbacks(execute=True):
+ if succeeds:
+ batch.write()
+ batch.publish()
+ else:
+ with self.assertRaises(error_type):
+ batch.write()
+ capture.assert_not_called()
+
+ self.organization.refresh_from_db()
+ other.refresh_from_db()
+ if succeeds:
+ assert self.organization.usage is not None
+ assert self.organization.usage["events"]["todays_usage"] == 20
+ assert other.usage["events"]["todays_usage"] == 30
+ assert other.usage["events"]["quota_limited_until"] == 1234
+ capture.assert_called_once()
+ assert capture.call_args.kwargs["properties"] == {"usage": {"events": 20}}
+ else:
+ assert self.organization.usage == other.usage == usage
+ capture.assert_not_called()
+
+
+@override_settings(CLOUD_DEPLOYMENT="US")
+@time_machine.travel("2026-06-15T12:00:00Z", tick=False)
+class TestBatchedQuotaRun(BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.enterContext(patch("ee.billing.quota_limiting.QUOTA_ORGANIZATION_BATCH_SIZE", 2))
+ self.enterContext(patch("posthoganalytics.feature_enabled", return_value=False))
+ self.capture = self.enterContext(patch("posthoganalytics.capture"))
+ self.enterContext(patch("ee.billing.quota_usage.sleep"))
+ self.redis = get_client()
+ self.redis.delete(
+ *[cache.value + resource.value for cache in QuotaLimitingCaches for resource in QuotaResource]
+ )
+ others = [
+ Organization.objects.create(name=f"Quota organization {i}", slug=f"quota-organization-{i}")
+ for i in range(2)
+ ]
+ for org in others:
+ Team.objects.create(organization=org)
+ self.orgs = sorted([self.organization, *others], key=lambda org: org.id)
+ self.teams = {str(org.id): list(org.teams.all()) for org in self.orgs}
+ self.teams[str(self.orgs[0].id)].append(Team.objects.create(organization=self.orgs[0]))
+ self.usage: dict[str, Any] = {
+ "events": {"usage": 0, "limit": 100, "todays_usage": 0},
+ "period": ["2026-06-01T00:00:00Z", "2026-07-01T00:00:00Z"],
+ }
+ Organization.objects.filter(id__in=[org.id for org in self.orgs]).update(
+ usage=self.usage, customer_trust_scores={}
+ )
+ counts: dict[str, list[tuple[int, int]]] = {counter.value: [] for counter in UsageCounter}
+ counts[UsageCounter.EVENTS.value] = [
+ (team.id, 60 if index == 0 else 200)
+ for index, org in enumerate(self.orgs)
+ for team in self.teams[str(org.id)]
+ ]
+ counts["teams_with_sandbox_compute_cpu_millicore_seconds_in_period"] = []
+ counts["teams_with_sandbox_compute_memory_mib_seconds_in_period"] = []
+ self.enterContext(
+ patch(
+ "posthog.usage_counters.UsageCounterService.fetch_report",
+ return_value=UsageCounterReport(counts=counts),
+ )
+ )
+ self.enterContext(
+ patch("ee.billing.quota_limiting.get_teams_with_api_queries_metrics", return_value={"read_bytes": []})
+ )
+ self.capture.reset_mock()
+
+ def test_orgs_and_all_their_teams_are_processed_across_chunks(self) -> None:
+ with self.captureOnCommitCallbacks(execute=True):
+ result = update_all_orgs_billing_quotas()
+
+ assert set(result.quota_limited_orgs["events"]) == {str(org.id) for org in self.orgs}
+ assert result.stats["orgs_processed"] == result.stats["orgs_total"] == 3
+ assert result.stats["orgs_limited"] == 3
+ for index, org in enumerate(self.orgs):
+ org.refresh_from_db()
+ assert org.usage["events"]["todays_usage"] == (120 if index == 0 else 200)
+ for team in self.teams[str(org.id)]:
+ assert (
+ self.redis.zscore("@posthog/quota-limits/events", team.api_token)
+ == result.quota_limited_orgs["events"][str(org.id)]
+ )
+
+ def test_exhausted_later_batch_leaves_redis_unchanged_and_next_run_recovers(self) -> None:
+ old_team = self.teams[str(self.orgs[0].id)][0]
+ self.redis.zadd("@posthog/quota-limits/events", {old_team.api_token: 1_782_864_000})
+ initial_redis = self.redis.zrange("@posthog/quota-limits/events", 0, -1, withscores=True)
+ failed_id = self.orgs[-1].id
+
+ def fail_last_batch(execute, sql, params, many, context):
+ if sql.startswith("UPDATE posthog_organization AS o") and any(failed_id in values for values in params):
+ raise OperationalError("synthetic connection failure")
+ return execute(sql, params, many, context)
+
+ with connection.execute_wrapper(fail_last_batch), self.captureOnCommitCallbacks(execute=True):
+ with self.assertRaises(OperationalError):
+ update_all_orgs_billing_quotas()
+ assert self.redis.zrange("@posthog/quota-limits/events", 0, -1, withscores=True) == initial_redis
+ self.orgs[-1].refresh_from_db()
+ assert self.orgs[-1].usage == self.usage
+ assert not any(call.kwargs["distinct_id"] == str(failed_id) for call in self.capture.call_args_list)
+
+ result = update_all_orgs_billing_quotas()
+ assert len(result.quota_limited_orgs["events"]) == 3
+ self.orgs[-1].refresh_from_db()
+ assert self.orgs[-1].usage["events"]["todays_usage"] == 200
+ assert self.redis.zcard("@posthog/quota-limits/events") == 4
+
+ @parameterized.expand([("query_error", OperationalError), ("closed_connection", InterfaceError)])
+ def test_failed_decision_preserves_previous_limits_and_discards_partial_updates(
+ self, _name: str, error_type: type[OperationalError | InterfaceError]
+ ) -> None:
+ failed_org = self.orgs[0]
+ usage = copy.deepcopy(self.usage)
+ usage["signals_credits"] = {"usage": 4500, "limit": 4500, "todays_usage": 0}
+ Organization.objects.filter(id__in=[org.id for org in self.orgs]).update(usage=usage)
+ for team in self.teams[str(failed_org.id)]:
+ self.redis.zadd("@posthog/quota-limits/events", {team.api_token: 1_782_864_000})
+ self.redis.zadd("@posthog/quota-limiting-suspended/signals_credits", {team.api_token: 1_782_864_000})
+ self.redis.zadd("@posthog/quota-limits/recordings", {team.api_token: 1_780_000_000})
+ connection_broken = False
+
+ def refund_credits(organization_id: UUID, *_args: object) -> int:
+ nonlocal connection_broken
+ if organization_id == failed_org.id:
+ connection_broken = True
+ if connection_broken:
+ raise error_type("synthetic disconnected connection")
+ return 0
+
+ def close_connection() -> None:
+ nonlocal connection_broken
+ connection_broken = False
+
+ with (
+ override_settings(TEST=False),
+ patch("ee.billing.quota_limiting.close_old_connections", side_effect=close_connection),
+ patch("ee.billing.quota_limiting.get_self_driving_credits_used_in_period_for_org", return_value=0),
+ patch(
+ "ee.billing.quota_limiting.get_signals_credited_refund_credits_for_org",
+ side_effect=refund_credits,
+ ),
+ patch("ee.billing.quota_limiting.capture_exception"),
+ patch("posthog.tasks.remote_config.update_team_remote_config") as update_remote_config,
+ self.captureOnCommitCallbacks(execute=True),
+ ):
+ result = update_all_orgs_billing_quotas()
+
+ rebuilt_team_ids = {call.kwargs["args"][0] for call in update_remote_config.apply_async.call_args_list}
+ assert rebuilt_team_ids == {team.id for team in self.teams[str(failed_org.id)]}
+
+ failed_org.refresh_from_db()
+ assert failed_org.usage == usage
+ assert str(failed_org.id) not in result.quota_limited_orgs["events"]
+ assert len(result.quota_limited_orgs["events"]) == 2
+ for team in self.teams[str(failed_org.id)]:
+ assert self.redis.zscore("@posthog/quota-limits/events", team.api_token) == 1_782_864_000
+ assert (
+ self.redis.zscore("@posthog/quota-limiting-suspended/signals_credits", team.api_token) == 1_782_864_000
+ )
+ assert not any(call.kwargs["distinct_id"] == str(failed_org.id) for call in self.capture.call_args_list)
+
+ def test_usage_written_during_the_chunk_keeps_the_newer_limit(self) -> None:
+ org = self.orgs[0]
+ usage = copy.deepcopy(self.usage)
+ usage["events"].update(limit=1000, quota_limited_until=1_782_864_000)
+ Organization.objects.filter(id=org.id).update(usage=usage)
+ for team in self.teams[str(org.id)]:
+ self.redis.zadd("@posthog/quota-limits/events", {team.api_token: 1_782_864_000})
+ concurrent_usage = copy.deepcopy(usage)
+ concurrent_usage["events"]["todays_usage"] = 5000
+ written = False
+
+ def write_before_batch(execute, sql, params, many, context):
+ nonlocal written
+ if not written and sql.startswith("UPDATE posthog_organization AS o"):
+ if any(org.id in values for values in params):
+ written = True
+ Organization.objects.filter(id=org.id).update(usage=concurrent_usage)
+ return execute(sql, params, many, context)
+
+ with connection.execute_wrapper(write_before_batch), self.captureOnCommitCallbacks(execute=True):
+ result = update_all_orgs_billing_quotas()
+
+ org.refresh_from_db()
+ assert org.usage == concurrent_usage
+ assert len(result.quota_limited_orgs["events"]) == 2
+ for team in self.teams[str(org.id)]:
+ assert self.redis.zscore("@posthog/quota-limits/events", team.api_token) == 1_782_864_000
+ assert not any(call.kwargs["distinct_id"] == str(org.id) for call in self.capture.call_args_list)
diff --git a/posthog/tasks/test/test_usage_report.py b/posthog/tasks/test/test_usage_report.py
index 1bb4f4be60b8..b4579d19eff8 100644
--- a/posthog/tasks/test/test_usage_report.py
+++ b/posthog/tasks/test/test_usage_report.py
@@ -79,6 +79,7 @@ from posthog.tasks.usage_report import (
get_teams_with_query_metric,
get_teams_with_sdk_logs_records_in_period,
has_non_zero_usage,
+ iter_billable_teams,
send_all_org_usage_reports,
)
from posthog.temporal.usage_report.queries import QUERY_INDEX
@@ -5743,8 +5744,16 @@ class TestSendUsageNoLicense(APIBaseTest):
class TestBillableTeams(TestCase):
- @parameterized.expand([(1, None), (2, None), (10, []), (2, [str(UUID(int=3))])])
- def test_get_teams_for_usage_reports(self, batch_size: int, organization_ids: list[str] | None) -> None:
+ @parameterized.expand(
+ [
+ (batch_size, organization_ids, buffer_teams)
+ for batch_size, organization_ids in [(1, None), (2, None), (10, []), (2, [str(UUID(int=3))])]
+ for buffer_teams in (False, True)
+ ]
+ )
+ def test_get_teams_for_usage_reports(
+ self, batch_size: int, organization_ids: list[str] | None, buffer_teams: bool
+ ) -> None:
org_last = Organization.objects.create(id=UUID(int=3), name="Last")
org_first = Organization.objects.create(id=UUID(int=1), name="First")
org_demo = Organization.objects.create(id=UUID(int=2), name="Demo only")
@@ -5762,7 +5771,16 @@ class TestBillableTeams(TestCase):
patch("posthog.tasks.usage_report.BILLING_ORGANIZATION_BATCH_SIZE", batch_size),
self.assertNumQueries(expected_queries),
):
- teams = list(_get_teams_for_usage_reports(organization_ids=organization_ids))
+ teams = list(
+ iter_billable_teams(
+ team_fields=("id", "name"),
+ organization_fields=("id", "name", "created_at"),
+ organization_ids=organization_ids,
+ buffer_teams=True,
+ )
+ if buffer_teams
+ else _get_teams_for_usage_reports(organization_ids=organization_ids)
+ )
expected_teams = [last_team] if organization_ids else [first_team, second_team, last_team]
assert [team.id for team in teams] == [team.id for team in expected_teams]
@@ -5778,6 +5796,20 @@ class TestBillableTeams(TestCase):
with self.assertNumQueries(1):
assert teams[0].organization.for_internal_metrics is False
+ def test_buffered_teams_survive_closed_server_cursors(self) -> None:
+ org = Organization.objects.create()
+ first_team = Team.objects.create(organization=org)
+ second_team = Team.objects.create(organization=org)
+
+ with patch.dict(connection.settings_dict, DISABLE_SERVER_SIDE_CURSORS=False):
+ teams = iter_billable_teams(team_fields=("id",), organization_fields=("id",), buffer_teams=True)
+ first = next(teams)
+ with connection.cursor() as cursor:
+ cursor.execute("CLOSE ALL")
+ rest = list(teams)
+
+ assert [team.id for team in [first, *rest]] == [first_team.id, second_team.id]
+
def test_team_moved_to_a_later_organization_during_the_scan_is_reported_once(self) -> None:
org_first = Organization.objects.create(id=UUID(int=1), name="First")
org_last = Organization.objects.create(id=UUID(int=2), name="Last")
diff --git a/posthog/tasks/usage_report.py b/posthog/tasks/usage_report.py
index a2b6ea58b774..1dc0800165e2 100644
--- a/posthog/tasks/usage_report.py
+++ b/posthog/tasks/usage_report.py
@@ -3297,6 +3297,7 @@ def iter_billable_teams(
team_fields: Sequence[str],
organization_fields: Sequence[str],
organization_ids: Sequence[str] | None = None,
+ buffer_teams: bool = False,
) -> Iterator[Team]:
# Page organizations to avoid repeating their wide columns on every team or retaining them all.
# Keyset pagination bounds the organization query even when PgBouncer disables server-side cursors.
@@ -3317,7 +3318,9 @@ def iter_billable_teams(
.only(*team_fields, "organization_id")
.order_by("organization_id", "id")
)
- for team in teams.iterator(chunk_size=2_000):
+ # Callers that reconnect between writes must not leave a read cursor open across yields.
+ team_iterator = iter(teams) if buffer_teams else teams.iterator(chunk_size=2_000)
+ for team in team_iterator:
if team.id in yielded_team_ids:
continue
yielded_team_ids.add(team.id)