:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(billing): skip old billing statuses and count yesterday in quotas (#125180)
Alex Mays1c3b94fd94e8
diff --git a/ee/billing/billing_manager.py b/ee/billing/billing_manager.pyindex 80f416c81b7f..1707c91f0e81 100644--- a/ee/billing/billing_manager.py+++ b/ee/billing/billing_manager.py@@ -41,7 +41,7 @@ from posthog.models.user import Userfrom ee.billing.access_token import mint_billing_access_tokenfrom ee.billing.billing_types import BillingProvider, BillingStatus, CustomerInfofrom ee.billing.grants import EffectiveBillingGrants-from ee.billing.quota_limiting import set_org_usage_summary, update_org_billing_quotas+from ee.billing.quota_limiting import BILLING_STATUS_STAMP_KEYS, set_org_usage_summary, update_org_billing_quotasfrom ee.models import Licensefrom ee.settings import BILLING_SERVICE_URL@@ -135,6 +135,11 @@ def _has_quota_limiting_markers(usage: dict | None) -> bool:return False+def _is_older_than_applied_billing_status(organization: Organization, computed_at: datetime) -> bool:+ applied_at = parse_datetime((organization.usage or {}).get("billing_status_computed_at") or "")+ return applied_at is not None and computed_at < applied_at++def _free_trial_active(customer: CustomerInfo) -> bool:free_trial_until = customer.get("free_trial_until")if not free_trial_until:@@ -757,6 +762,15 @@ class BillingManager:"""Ensure the relevant organization details are up-to-date locally"""+ computed_at = parse_datetime(billing_status.get("computed_at") or "")+ if computed_at is not None and _is_older_than_applied_billing_status(organization, computed_at):+ logger.info(+ "billing_status_out_of_order_skipped",+ organization_id=str(organization.id),+ computed_at=computed_at.isoformat(),+ )+ return organization+org_modified = Falsedata = billing_status["customer"]@@ -802,6 +816,10 @@ class BillingManager:had_quota_limiting_markers = _has_quota_limiting_markers(organization.usage)usage_changed = set_org_usage_summary(organization, new_usage=usage_info)+ if usage_changed and computed_at is None and organization.usage is not None:+ # The stored stamps describe an older total, so the quota check must not pair them with this one.+ for key in BILLING_STATUS_STAMP_KEYS:+ cast(dict, organization.usage).pop(key, None)if usage_changed:org_modified = True@@ -866,6 +884,13 @@ class BillingManager:organization.customer_trust_scores = updated_customer_trust_scoresorg_modified = True+ # The stamp goes out only with a save that a change already needs. A save for the stamp+ # alone writes this in-memory copy back over counters and quota markers that the quota+ # run wrote in the meantime.+ if org_modified and computed_at is not None and organization.usage is not None:+ organization.usage["billing_status_computed_at"] = computed_at.isoformat()+ organization.usage["billing_latest_usage_report_date"] = billing_status.get("latest_usage_report_date")+if org_modified:organization.save()@@ -1139,7 +1164,8 @@ class BillingManager:handle_billing_service_error(res)- self.update_available_product_features(organization)+ # A full status carries `computed_at`, so a status queued before the trial change can't roll it back.+ self.get_billing(organization)return res.json()@@ -1152,7 +1178,8 @@ class BillingManager:handle_billing_service_error(res)- self.update_available_product_features(organization)+ # A full status carries `computed_at`, so a status queued before the trial change can't roll it back.+ self.get_billing(organization)def authorize(self, organization: Organization, billing_provider: BillingProvider | None = None):"""@@ -1257,7 +1284,8 @@ class BillingManager:)handle_billing_service_error(res)- self.update_available_product_features(organization)+ # A full status carries `computed_at`, so a status queued before the plan switch can't roll it back.+ self.get_billing(organization)return res.json()diff --git a/ee/billing/billing_types.py b/ee/billing/billing_types.pyindex 8b6bb52a4132..aeb4088adef5 100644--- a/ee/billing/billing_types.py+++ b/ee/billing/billing_types.py@@ -205,6 +205,8 @@ class CustomerInfo(TypedDict):class BillingStatus(TypedDict):license: LicenseInfocustomer: CustomerInfo+ computed_at: NotRequired[str]+ latest_usage_report_date: NotRequired[Optional[str]]class ProductPlan(TypedDict):diff --git a/ee/billing/quota_limiting.py b/ee/billing/quota_limiting.pyindex f481313098c7..7cf6cb8945a2 100644--- a/ee/billing/quota_limiting.py+++ b/ee/billing/quota_limiting.py@@ -40,7 +40,7 @@ from posthog.tasks.usage_report import (iter_billable_teams,)from posthog.usage_counters import UsageCounter, UsageCounterMode, UsageCounterPlan, UsageCounterService-from posthog.utils import get_current_day+from posthog.utils import DayRange, get_current_day, get_previous_dayfrom products.ai_observability.backend.offline_evaluation_billing import get_offline_evaluation_usagefrom products.feature_flags.backend.flag_analytics import billable_feature_flag_requests@@ -180,6 +180,12 @@ INFORMATIONAL_USAGE_RESOURCES = ("sandbox_compute_cpu_millicore_seconds","sandbox_compute_memory_mib_seconds",)+BILLING_STATUS_STAMP_KEYS = ("billing_status_computed_at", "billing_latest_usage_report_date")+# PostHog's counts for one quota resource, keyed by UTC date. Only the quota run and the signals refresh write it.+DAILY_USAGE_FIELD = "daily_usage"+# The quota run that writes yesterday's finished counts into `daily_usage` sets this key for that day.+YESTERDAY_FINISHED_KEY_PREFIX = "@posthog/quota-limits-yesterday-finished/"+YESTERDAY_FINISHED_TTL = timedelta(days=2)# -------------------------------------------------------------------------------------------------# REDIS FUNCTIONS# -------------------------------------------------------------------------------------------------@@ -457,6 +463,44 @@ def _period_timestamp(value: str) -> int:return round(dateutil.parser.isoparse(value).timestamp())+def _quota_usage(organization_usage: Mapping[str, Any], resource_usage: Mapping[str, Any]) -> int:+ """+ Billing's total plus PostHog's counts for the days that the total does not include.++ Billing's total covers its billing period through `billing_latest_usage_report_date`, and no day+ when that date is None. Without the stamp, or before a quota run stores `daily_usage`, PostHog+ cannot tell which days the total covers, so the result is billing's total plus `todays_usage`.+ """+ billing_total = resource_usage.get("usage") or 0+ daily_usage = resource_usage.get(DAILY_USAGE_FIELD)+ period = organization_usage.get("period")+ if "billing_latest_usage_report_date" not in organization_usage or daily_usage is None or not period:+ return billing_total + (resource_usage.get("todays_usage") or 0)+ first_lacking_day = dateutil.parser.isoparse(period[0]).date()+ latest_report_date = organization_usage["billing_latest_usage_report_date"]+ if latest_report_date is not None:+ first_lacking_day = max(+ first_lacking_day, dateutil.parser.isoparse(latest_report_date).date() + timedelta(days=1)+ )+ return billing_total + sum(+ count for day, count in daily_usage.items() if date.fromisoformat(day) >= first_lacking_day+ )+++def _daily_usage(+ stored: Mapping[str, int] | None, *, today: date, todays_count: int, yesterdays_count: int | None+) -> dict[str, int]:+ """+ Today's count and yesterday's count, keyed by date.++ Without a finished count for yesterday, the stored count for yesterday stays.+ """+ yesterday = (today - timedelta(days=1)).isoformat()+ if yesterdays_count is None:+ yesterdays_count = (stored or {}).get(yesterday, 0)+ return {day: count for day, count in ((yesterday, yesterdays_count), (today.isoformat(), todays_count)) if count}++def org_quota_limited_until(organization: Organization,resource: QuotaResource,@@ -472,9 +516,7 @@ def org_quota_limited_until(summary = organization.usage.get(resource.value, {})if not summary:return None- usage = summary.get("usage") or 0- todays_usage = summary.get("todays_usage") or 0- current_usage = usage + todays_usage+ current_usage = _quota_usage(organization.usage, summary)limit = summary.get("limit")if resource in {QuotaResource.SIGNALS_CREDITS, QuotaResource.SIGNALS_SPEND_CREDITS}:if resource != self_driving_quota_resource(organization):@@ -910,7 +952,12 @@ def update_org_billing_quotas(organization: Organization):)# Get the quota limiting information (e.g. {"quota_limited_until": 1737867600, "quota_limiting_suspended_until": 1737867600})- result = org_quota_limited_until(organization, resource, previously_quota_limited_team_tokens, team_attributes)+ result = org_quota_limited_until(+ organization,+ resource,+ previously_quota_limited_team_tokens,+ team_attributes,+ )if resource == QuotaResource.RECORDINGS:now_limited_for_recordings = bool(result and result.get("quota_limited_until"))@@ -960,9 +1007,9 @@ def refresh_org_self_driving_quota(organization_id: str) -> None:backstop for orgs that cross the limit without a PR event.Concurrent refreshes for one org (two PRs landing close together) are serialized on the org- row, and this path only ever raises `todays_usage`: it fires exclusively because a PR landed,- so a slower refresh that counted usage before a newer PR must not overwrite the fresher value- and momentarily unpause the org. Decreases (refunds, cron corrections) stay the cron's job.+ row, and this path only ever raises `todays_usage` and today's count in `daily_usage`: it fires+ exclusively because a PR landed, so a slower refresh that counted usage before a newer PR must+ not overwrite the fresher value and momentarily unpause the org. Decreases (refunds, cron corrections) stay the cron's job.Scope caveat: the recount covers today's UTC window keyed on the implementation run's`created_at`, so a PR recorded after midnight by a run created before midnight falls in@@ -990,11 +1037,19 @@ def refresh_org_self_driving_quota(organization_id: str) -> None:resource_usage = (organization.usage or {}).get(QuotaResource.SIGNALS_CREDITS.value)if not resource_usage:return+ ops: list[tuple[list[str], Any]] = []if todays_credits > (resource_usage.get("todays_usage") or 0):resource_usage["todays_usage"] = todays_credits- _patch_organization_usage_jsonb(- organization, [([QuotaResource.SIGNALS_CREDITS.value, "todays_usage"], todays_credits)]+ ops.append(([QuotaResource.SIGNALS_CREDITS.value, "todays_usage"], todays_credits))+ stored_daily_usage = resource_usage.get(DAILY_USAGE_FIELD)+ today = period.start.date()+ if stored_daily_usage is not None and todays_credits > stored_daily_usage.get(today.isoformat(), 0):+ daily_usage = _daily_usage(+ stored_daily_usage, today=today, todays_count=todays_credits, yesterdays_count=None)+ resource_usage[DAILY_USAGE_FIELD] = daily_usage+ ops.append(([QuotaResource.SIGNALS_CREDITS.value, DAILY_USAGE_FIELD], daily_usage))+ _patch_organization_usage_jsonb(organization, ops)# Evaluate from the freshest committed usage, not this task's snapshot: a newer concurrent# refresh may have written a higher value while we held or waited on the lock.organization.refresh_from_db(fields=["usage"])@@ -1040,6 +1095,9 @@ def set_org_usage_summary(and "quota_limiting_suspended_until" not in resource_usage):resource_usage["quota_limiting_suspended_until"] = original_field_usage["quota_limiting_suspended_until"]+ # Billing's summary never carries daily_usage, so a billing status keeps PostHog's counts.+ if original_field_usage and DAILY_USAGE_FIELD in original_field_usage:+ resource_usage[DAILY_USAGE_FIELD] = original_field_usage[DAILY_USAGE_FIELD]if todays_usage:resource_usage["todays_usage"] = todays_usage.get(field, 0)@@ -1054,6 +1112,11 @@ def set_org_usage_summary(_merge_informational_usage_summary(cast(dict, new_usage), original_usage, todays_usage)+ # update_org_details writes these after this comparison, so keep the stored values here.+ for key in BILLING_STATUS_STAMP_KEYS:+ if key in original_usage and key not in new_usage:+ cast(dict, new_usage)[key] = original_usage[key]+has_changed = new_usage != organization.usageorganization.usage = new_usage@@ -1123,7 +1186,12 @@ def _patch_organization_usage_jsonb(def _patch_todays_usage(- organization: Organization, todays_report: "UsageCounters", *, batch: QuotaUsageBatch | None = None+ organization: Organization,+ todays_report: "UsageCounters",+ *,+ today: date,+ finished_yesterday: Mapping[str, int] | None,+ batch: QuotaUsageBatch | None = None,) -> bool:"""Cron-only: patches `usage[resource].todays_usage` for each current usage resource where the@@ -1131,6 +1199,10 @@ def _patch_todays_usage(single targeted UPDATE via `_patch_organization_usage_jsonb` so billing-owned fields(`usage`, `limit`, `period`) are not clobbered by stale snapshots. Returns True ifany value changed.++ The same UPDATE stores `daily_usage` for each quota resource: today's count, and yesterday's+ count under yesterday's date. The first run of each day passes yesterday's finished counts in+ `finished_yesterday`. Later runs pass None and keep the stored count for yesterday."""if not organization.usage:return False@@ -1139,6 +1211,15 @@ def _patch_todays_usage(for resource in QuotaResource:_append_todays_usage_patch(organization, todays_report, resource.value, ops)+ yesterdays_count = None if finished_yesterday is None else finished_yesterday.get(resource.value, 0)+ _append_daily_usage_patch(+ organization,+ resource.value,+ ops,+ today=today,+ todays_count=cast(dict[str, int], todays_report)[resource.value],+ yesterdays_count=yesterdays_count,+ )for field in INFORMATIONAL_USAGE_RESOURCES:_append_todays_usage_patch(organization, todays_report, field, ops)@@ -1167,6 +1248,29 @@ def _append_todays_usage_patch(ops.append(([field, "todays_usage"], new_todays_usage))+def _append_daily_usage_patch(+ organization: Organization,+ field: str,+ ops: list[tuple[list[str], Any]],+ *,+ today: date,+ todays_count: int,+ yesterdays_count: int | None,+) -> None:+ existing_resource = organization.usage.get(field) if organization.usage else None+ if not existing_resource:+ return++ stored = existing_resource.get(DAILY_USAGE_FIELD)+ daily_usage = _daily_usage(stored, today=today, todays_count=todays_count, yesterdays_count=yesterdays_count)+ # A missing daily_usage and an empty one give the same quota usage, so an idle organization gets no write.+ if daily_usage == (stored if stored is not None else {}):+ return++ existing_resource[DAILY_USAGE_FIELD] = daily_usage+ ops.append(([field, DAILY_USAGE_FIELD], daily_usage))++def _identify_refresh_candidates(orgs_by_id: dict[str, Organization],todays_usage_report: dict[str, "UsageCounters"],@@ -1174,6 +1278,8 @@ def _identify_refresh_candidates(previously_quota_limited_team_tokens: dict[str, list[str]],previously_quota_limiting_suspended_team_tokens: dict[str, list[str]],*,+ today: date,+ finished_yesterday_by_org: Mapping[str, Mapping[str, int]] | None,redis_indicator_lookup: dict[str, set[str]] | None = None,) -> set[str]:"""@@ -1187,8 +1293,8 @@ def _identify_refresh_candidates(quota-limiting-suspended set;2. its cached `usage[resource]` already carries a `quota_limited_until` or`quota_limiting_suspended_until` marker;- 3. it appears newly limitable from cached state — `usage + todays_usage >= limit + buffer`- for any resource.+ 3. it appears newly limitable from cached state: `_quota_usage` with this run's counts+ reaches `limit + buffer` for any resource.A resource with a zero limit and no overage buffer never makes an org a candidate. Thatlimit blocks the resource at any usage, so the cached state gives the same decision.@@ -1210,6 +1316,9 @@ def _identify_refresh_candidates(continueteam_token_set: set[str] = set(teams_by_org.get(org_id, []))+ org_finished_yesterday = (+ None if finished_yesterday_by_org is None else finished_yesterday_by_org.get(org_id, {})+ )is_candidate = Falsefor resource in QuotaResource:@@ -1238,9 +1347,15 @@ def _identify_refresh_candidates(if limit is None:continue- usage_value = usage_for_resource.get("usage") or 0todays_for_field = todays_report[field] # type: ignore[literal-required]- if usage_value + todays_for_field >= limit + OVERAGE_BUFFER[resource]:+ daily_usage = _daily_usage(+ usage_for_resource.get(DAILY_USAGE_FIELD),+ today=today,+ todays_count=todays_for_field,+ yesterdays_count=None if org_finished_yesterday is None else org_finished_yesterday.get(field, 0),+ )+ this_runs_usage = {**usage_for_resource, "todays_usage": todays_for_field, DAILY_USAGE_FIELD: daily_usage}+ if _quota_usage(org.usage, this_runs_usage) >= limit + OVERAGE_BUFFER[resource]:is_candidate = Truebreak@@ -1372,48 +1487,42 @@ def _iter_quota_organizations(page = organizations.filter(id__gt=batch[-1].id)-def update_all_orgs_billing_quotas(- dry_run: bool = False,- progress_callback: Callable[[str, str, str], None] | None = None,-) -> QuotaLimitingRunResult:- """Refresh organization quotas every 15 minutes, including today's usage."""- total_start = time()- period = get_current_day()- service = UsageCounterService()+QUOTA_USAGE_COUNTERS = (+ UsageCounter.EVENTS,+ UsageCounter.EXCEPTIONS,+ UsageCounter.RECORDINGS,+ UsageCounter.FEATURE_FLAG_REQUESTS,+ UsageCounter.FEATURE_FLAG_LOCAL_EVALUATION_REQUESTS,+ UsageCounter.FEATURE_FLAG_LOCAL_EVALUATION_NOT_MODIFIED_REQUESTS,+ UsageCounter.CDP_INVOCATIONS,+ UsageCounter.SURVEY_RESPONSES,+ UsageCounter.AI_EVENTS,+ UsageCounter.WORKFLOW_EMAILS,+ UsageCounter.WORKFLOW_PUSH,+ UsageCounter.WORKFLOW_INVOCATIONS,+ UsageCounter.ROWS_SYNCED,+ UsageCounter.ROWS_EXPORTED,+ UsageCounter.LOGS_BYTES,+ UsageCounter.AI_CREDITS,+ UsageCounter.SIGNALS_CREDITS,+ UsageCounter.SIGNALS_SPEND_CREDITS,+ UsageCounter.POSTHOG_CODE_CREDITS,+ UsageCounter.SANDBOX_COMPUTE_CREDITS,+ UsageCounter.REPLAY_VISION_CREDITS,+)+++@frozen+class _QuotaUsageCounts:+ # Counter name to team id to count.+ by_team: dict[str, dict[int, int]]+ offline_by_org: dict[str, dict[int, int]]+++def _fetch_quota_usage_counts(service: UsageCounterService, period: DayRange) -> _QuotaUsageCounts:plan = UsageCounterPlan(- period=period,- caller="quota_limiting",- modes=dict.fromkeys(- (- UsageCounter.EVENTS,- UsageCounter.EXCEPTIONS,- UsageCounter.RECORDINGS,- UsageCounter.FEATURE_FLAG_REQUESTS,- UsageCounter.FEATURE_FLAG_LOCAL_EVALUATION_REQUESTS,- UsageCounter.FEATURE_FLAG_LOCAL_EVALUATION_NOT_MODIFIED_REQUESTS,- UsageCounter.CDP_INVOCATIONS,- UsageCounter.SURVEY_RESPONSES,- UsageCounter.AI_EVENTS,- UsageCounter.WORKFLOW_EMAILS,- UsageCounter.WORKFLOW_PUSH,- UsageCounter.WORKFLOW_INVOCATIONS,- UsageCounter.ROWS_SYNCED,- UsageCounter.ROWS_EXPORTED,- UsageCounter.LOGS_BYTES,- UsageCounter.AI_CREDITS,- UsageCounter.SIGNALS_CREDITS,- UsageCounter.SIGNALS_SPEND_CREDITS,- UsageCounter.POSTHOG_CODE_CREDITS,- UsageCounter.SANDBOX_COMPUTE_CREDITS,- UsageCounter.REPLAY_VISION_CREDITS,- ),- UsageCounterMode.LEGACY,- ),+ period=period, caller="quota_limiting", modes=dict.fromkeys(QUOTA_USAGE_COUNTERS, UsageCounterMode.LEGACY))-- tag_queries(product=Product.BILLING, feature=Feature.QUOTA_LIMITING)- logger.info("quota_limiting_run", phase="queries", status="start")- queries_start = time()offline_usage = _timed_query("offline_evaluation_usage", get_offline_evaluation_usage, period.start, period.start + timedelta(days=1))@@ -1433,7 +1542,7 @@ def update_all_orgs_billing_quotas()# Clickhouse is good at counting things so we count across all teams rather than doing it one by one- all_data = {+ all_data: dict[str, dict[int, int]] = {"teams_with_event_count_in_period": dict(counter_report.counts[UsageCounter.EVENTS]),"teams_with_exceptions_captured_in_period": dict(counter_report.counts[UsageCounter.EXCEPTIONS]),"teams_with_recording_count_in_period": dict(counter_report.counts[UsageCounter.RECORDINGS]),@@ -1481,6 +1590,65 @@ def update_all_orgs_billing_quotas(for team_id in logs_bytes.keys() | apm_tracing_bytes.keys()},}+ return _QuotaUsageCounts(by_team=all_data, offline_by_org=offline_usage)+++class _FinishedYesterday:+ """+ Yesterday's finished quota counts, for the first quota run of each day.++ That run counts yesterday once as a finished day and writes the counts into `daily_usage`.+ A Redis key for the day then tells later runs to keep the stored counts instead of counting a whole+ day again. A run that skips or fails to write an organization leaves the key unset, so the next run counts+ yesterday again. Events for yesterday that arrive after a run sets the key count only when billing saves+ yesterday's report.+ """++ def __init__(self, service: UsageCounterService, *, today: DayRange) -> None:+ self._service = service+ self._range = get_previous_day(at=today.start)+ self._key = f"{YESTERDAY_FINISHED_KEY_PREFIX}{self._range.start.date().isoformat()}"+ self._redis = get_client()+ self._written: bool | None = None+ self._counts: _QuotaUsageCounts | None = None++ def for_organizations(+ self, teams: Sequence[Team], organizations: Sequence[Organization]+ ) -> dict[str, dict[str, int]] | None:+ """Returns None when an earlier run already wrote yesterday's finished counts."""+ if self._written is None:+ self._written = bool(self._redis.exists(self._key))+ if self._written:+ return None+ if self._counts is None:+ self._counts = _fetch_quota_usage_counts(self._service, self._range)+ reports = _aggregate_quota_usage(+ teams, self._counts.by_team, offline_usage=self._counts.offline_by_org, organizations=organizations+ )+ return {org_id: cast(dict[str, int], report) for org_id, report in reports.usage.items()}++ def finish(self) -> None:+ # A run that stops early leaves the day unmarked, so the next run counts yesterday again.+ if self._counts is not None:+ self._redis.set(self._key, 1, ex=YESTERDAY_FINISHED_TTL)+++def update_all_orgs_billing_quotas(+ dry_run: bool = False,+ progress_callback: Callable[[str, str, str], None] | None = None,+) -> QuotaLimitingRunResult:+ """Refresh organization quotas every 15 minutes, including today's usage."""+ total_start = time()+ period = get_current_day()+ service = UsageCounterService()++ tag_queries(product=Product.BILLING, feature=Feature.QUOTA_LIMITING)+ logger.info("quota_limiting_run", phase="queries", status="start")+ queries_start = time()+ todays_counts = _fetch_quota_usage_counts(service, period)+ all_data = todays_counts.by_team+ offline_usage = todays_counts.offline_by_org+ finished_yesterday = _FinishedYesterday(service, today=period)queries_duration_s = round((time() - queries_start), 1)logger.info(@@ -1558,6 +1726,7 @@ def update_all_orgs_billing_quotas()orgs_by_id = reports.organizationsteams_by_org = reports.team_tokens+ finished_yesterday_by_org = finished_yesterday.for_organizations(teams, list(orgs_by_id.values()))candidates_start = time()refresh_candidates = _identify_refresh_candidates(orgs_by_id,@@ -1565,6 +1734,8 @@ def update_all_orgs_billing_quotas(teams_by_org,previously_quota_limited_team_tokens,previously_quota_limiting_suspended_team_tokens,+ today=period.start.date(),+ finished_yesterday_by_org=finished_yesterday_by_org,redis_indicator_lookup=redis_indicator_lookup,)candidate_count += len(refresh_candidates)@@ -1617,7 +1788,15 @@ def update_all_orgs_billing_quotas(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"] = signals_recounts.get(org_id, 0)- _patch_todays_usage(org, todays_report, batch=usage_batch)+ _patch_todays_usage(+ org,+ todays_report,+ today=period.start.date(),+ finished_yesterday=(+ None if finished_yesterday_by_org is None else finished_yesterday_by_org.get(org_id, {})+ ),+ batch=usage_batch,+ )org_is_limited = org_is_suspended = Falsefor resource in QuotaResource:field = resource.value@@ -1733,6 +1912,9 @@ def update_all_orgs_billing_quotas(f"limited={orgs_limited_count},suspended={orgs_suspended_count}",)+ # A skipped or failed organization still holds yesterday's partial count.+ if not failed_org_ids:+ finished_yesterday.finish()if not settings.TEST:close_old_connections()logger.info(diff --git a/ee/billing/test/test_billing_manager.py b/ee/billing/test/test_billing_manager.pyindex 3cdeca9cf6f4..8cf74bcf6493 100644--- a/ee/billing/test/test_billing_manager.py+++ b/ee/billing/test/test_billing_manager.py@@ -1,3 +1,4 @@+import copyimport hmacimport jsonimport math@@ -45,6 +46,7 @@ from ee.billing.billing_manager import (http_session,)from ee.billing.billing_types import BillingProvider, BillingStatus, Product+from ee.billing.quota_limiting import QuotaLimitingCaches, QuotaResource, list_limited_team_attributesfrom ee.models.license import License, LicenseManager@@ -970,6 +972,159 @@ class TestBillingManager(BaseTest):organization.refresh_from_db()assert organization.has_active_subscription is expected+ def _billing_status(+ self,+ computed_at: str | None,+ events_usage: int,+ *,+ events_limit: int | None = None,+ latest_usage_report_date: str = "2026-08-02",+ ) -> BillingStatus:+ billing_status: dict[str, Any] = {+ "customer": {+ "usage_summary": {+ "events": {"usage": events_usage, "limit": events_limit},+ "recordings": {"usage": 0, "limit": None},+ },+ "billing_period": {+ "current_period_start": "2026-08-01T00:00:00Z",+ "current_period_end": "2026-09-01T00:00:00Z",+ },+ }+ }+ if computed_at:+ billing_status["computed_at"] = computed_at+ billing_status["latest_usage_report_date"] = latest_usage_report_date+ return cast(BillingStatus, billing_status)++ @time_machine.travel("2026-08-03T04:00:00Z", tick=False)+ def test_status_after_a_report_keeps_todays_count_in_the_quota_check(self):+ self.organization.usage = {+ "events": {+ "usage": 500,+ "limit": 1000,+ "todays_usage": 400,+ "daily_usage": {"2026-08-02": 200, "2026-08-03": 400},+ },+ "recordings": {"usage": 0, "limit": None, "todays_usage": 0},+ "period": ["2026-08-01T00:00:00Z", "2026-09-01T00:00:00Z"],+ "billing_status_computed_at": "2026-08-02T04:00:00+00:00",+ "billing_latest_usage_report_date": "2026-08-01",+ }+ self.organization.save()++ # Billing's total now includes 2026-08-02, but not today.+ BillingManager(license=None).update_org_details(+ self.organization,+ self._billing_status("2026-08-03T04:00:00Z", events_usage=700, events_limit=1000),+ )++ assert self.team.api_token in list_limited_team_attributes(+ QuotaResource.EVENTS, QuotaLimitingCaches.QUOTA_LIMITER_CACHE_KEY+ )++ @parameterized.expand(+ [+ ("newer_status_applies", "2026-08-03T00:00:00Z", 1000, "2026-08-03T00:00:00+00:00", "2026-08-02"),+ ("redelivered_status_applies", "2026-08-02T00:00:00Z", 1000, "2026-08-02T00:00:00+00:00", "2026-08-02"),+ ("older_status_is_skipped", "2026-08-01T00:00:00Z", 500, "2026-08-02T00:00:00+00:00", None),+ ("status_without_stamp_applies_and_drops_the_stamps", None, 1000, None, None),+ ]+ )+ def test_update_org_details_skips_a_status_older_than_the_last_applied(+ self, _name, status_computed_at, expected_events_usage, expected_computed_at, expected_report_date+ ):+ organization = self.organization+ organization.usage = {+ "events": {"usage": 500, "limit": None, "todays_usage": 0},+ "recordings": {"usage": 0, "limit": None, "todays_usage": 0},+ "period": ["2026-08-01T00:00:00Z", "2026-09-01T00:00:00Z"],+ "billing_status_computed_at": "2026-08-02T00:00:00+00:00",+ }+ organization.save()++ BillingManager(license=None).update_org_details(+ organization, self._billing_status(status_computed_at, events_usage=1000)+ )++ organization.refresh_from_db()+ assert organization.usage is not None+ assert organization.usage["events"]["usage"] == expected_events_usage+ assert organization.usage.get("billing_status_computed_at") == expected_computed_at+ assert organization.usage.get("billing_latest_usage_report_date") == expected_report_date++ def test_update_org_details_writes_nothing_for_a_status_that_changes_only_the_stamp(self):+ manager = BillingManager(license=None)+ manager.update_org_details(self.organization, self._billing_status("2026-08-02T00:00:00Z", events_usage=1000))+ assert self.organization.usage is not None+ usage_written_by_quota_run = copy.deepcopy(self.organization.usage)+ usage_written_by_quota_run["events"]["todays_usage"] = 25+ Organization.objects.filter(id=self.organization.id).update(usage=usage_written_by_quota_run)++ with patch("ee.billing.billing_manager.update_org_billing_quotas") as update_org_billing_quotas:+ manager.update_org_details(+ self.organization, self._billing_status("2026-08-03T00:00:00Z", events_usage=1000)+ )++ update_org_billing_quotas.assert_not_called()+ self.organization.refresh_from_db()+ assert self.organization.usage is not None+ assert self.organization.usage["events"]["todays_usage"] == 25++ @parameterized.expand(+ [+ ("activate_trial", {"type": "autosubscribe", "target": "boost"}, 6, None),+ ("cancel_trial", {}, None, 6),+ ("switch_plan", {"from_product_key": "boost", "to_product_key": "scale"}, 6, None),+ ]+ )+ @patch("ee.billing.billing_manager.http_session.get")+ @patch("ee.billing.billing_manager.http_session.post")+ def test_plan_change_skips_a_status_queued_before_it(+ self,+ manager_method: str,+ data: dict[str, Any],+ limit_before: int | None,+ limit_after: int | None,+ mock_post: MagicMock,+ mock_get: MagicMock,+ ):+ license = super(LicenseManager, cast(LicenseManager, License.objects)).create(+ key="key123::key123",+ plan="enterprise",+ valid_until=datetime.datetime(2038, 1, 19, 3, 14, 7),+ )++ def features(projects_limit: int | None) -> list[dict[str, Any]]:+ return [{"key": "organizations_projects", "name": "Projects", "limit": projects_limit}]++ def status(computed_at: str, projects_limit: int | None) -> BillingStatus:+ billing_status = cast(dict[str, Any], self._billing_status(computed_at, events_usage=500))+ billing_status["customer"]["available_product_features"] = features(projects_limit)+ return cast(BillingStatus, billing_status)++ organization = self.organization+ organization.usage = {+ "events": {"usage": 500, "limit": None, "todays_usage": 0},+ "recordings": {"usage": 0, "limit": None, "todays_usage": 0},+ "period": ["2026-08-01T00:00:00Z", "2026-09-01T00:00:00Z"],+ }+ organization.available_product_features = features(limit_before)+ organization.save()+ mock_post.return_value.status_code = 200+ mock_post.return_value.json.return_value = {}+ mock_get.return_value.status_code = 200+ mock_get.return_value.json.return_value = status("2026-08-03T00:00:00Z", projects_limit=limit_after)++ manager = BillingManager(license)+ getattr(manager, manager_method)(organization, data)+ manager.update_org_details(organization, status("2026-08-02T00:00:00Z", projects_limit=limit_before))++ organization.refresh_from_db()+ assert organization.available_product_features == features(limit_after)+ assert organization.usage is not None+ assert organization.usage["billing_status_computed_at"] == "2026-08-03T00:00:00+00:00"+class TestBillingSession(SimpleTestCase):def test_the_session_keeps_no_cookies(self):diff --git a/ee/billing/test/test_quota_limiting.py b/ee/billing/test/test_quota_limiting.pyindex f5dc985689f6..b8ee20905164 100644--- a/ee/billing/test/test_quota_limiting.py+++ b/ee/billing/test/test_quota_limiting.py@@ -1,4 +1,5 @@import datetime+from contextlib import nullcontextfrom typing import Any, castfrom uuid import uuid4@@ -21,12 +22,15 @@ from posthog.models.organization import Organizationfrom posthog.models.team.team import Teamfrom posthog.redis import get_clientfrom posthog.test.fixtures import create_app_metric2+from posthog.usage_counters import UsageCounterServicefrom products.ai_observability.backend.models.offline_evaluations import OfflineEvaluationUsageLedgerfrom ee.billing.quota_limiting import (+ BILLING_STATUS_STAMP_KEYS,INFORMATIONAL_USAGE_RESOURCES,QUOTA_LIMIT_DATA_RETENTION_FLAG,+ YESTERDAY_FINISHED_KEY_PREFIX,OrganizationUsageInfo,QuotaLimitingCaches,QuotaLimitingRunResult,@@ -84,6 +88,8 @@ class TestQuotaLimiting(BaseTest):self.redis_client.delete(f"@posthog/quota-limiting-suspended/mcp_events")self.redis_client.delete(f"@posthog/quota-limiting-suspended/cdp_trigger_events")self.redis_client.delete(f"@posthog/quota-limiting-suspended/ai_credits")+ for key in self.redis_client.scan_iter(f"{YESTERDAY_FINISHED_KEY_PREFIX}*"):+ self.redis_client.delete(key)materialize("events", "$exception_values")def _run_quota_limiting(self) -> QuotaLimitingRunResult:@@ -114,6 +120,86 @@ class TestQuotaLimiting(BaseTest):self.assertEqual(self.organization.usage["llm_events"]["usage"], 50)self.assertEqual(self.organization.usage["llm_events"]["todays_usage"], 0 if deleted_team else 30)+ @parameterized.expand(+ [+ ("billing_total_lacks_yesterday", 0, "2026-10-30", "2026-10-01T00:00:00Z", True, False),+ ("no_report_yet_this_period", 0, None, "2026-10-01T00:00:00Z", True, False),+ ("billing_total_has_yesterday", 0, "2026-10-31", "2026-10-01T00:00:00Z", False, False),+ ("yesterday_is_in_the_previous_period", 0, "2026-10-30", "2026-11-01T00:00:00Z", False, False),+ ("first_stamp_after_the_first_run", 1, "2026-10-30", "2026-10-01T00:00:00Z", True, False),+ ("no_stamp", None, None, "2026-10-01T00:00:00Z", False, False),+ ("first_run_write_skipped", 0, "2026-10-30", "2026-10-01T00:00:00Z", True, True),+ ]+ )+ @patch("posthoganalytics.capture")+ @time_machine.travel("2026-11-01T00:30:00Z", tick=False)+ def test_quota_run_counts_yesterday_until_billings_total_has_it(+ self,+ _name: str,+ stamped_from_run: int | None,+ latest_usage_report_date: str | None,+ period_start: str,+ expect_limited: bool,+ first_write_skipped: bool,+ _capture,+ ) -> None:+ self.organization.usage = {+ "events": {"usage": 90, "limit": 100, "todays_usage": 0},+ "period": [period_start, "2026-12-01T00:00:00Z"],+ }+ self.organization.customer_trust_scores = zero_trust_scores()+ self.organization.save()+ for timestamp, count in (("2026-10-31T12:00:00Z", 15), ("2026-11-01T00:10:00Z", 1)):+ for _ in range(count):+ _create_event(+ distinct_id=str(uuid4()),+ event="$event1",+ properties={"$lib": "$web"},+ timestamp=timestamp,+ team=self.team,+ )+ flush_persons_and_events()+ token = self.team.api_token.encode("UTF-8")++ def billing_status_lands_first(organization: Organization, *args: Any, **kwargs: Any) -> bool:+ Organization.objects.filter(id=organization.id).update(+ usage={**(organization.usage or {}), "billing_status_computed_at": "2026-11-01T00:20:00+00:00"}+ )+ return _patch_todays_usage(organization, *args, **kwargs)++ with patch.object(+ UsageCounterService, "fetch_report", autospec=True, side_effect=UsageCounterService.fetch_report+ ) as fetch_report:+ for run in range(2):+ if run == stamped_from_run:+ self.organization.refresh_from_db()+ stamped_usage: dict[str, Any] = {+ **(self.organization.usage or {}),+ "billing_status_computed_at": "2026-10-31T09:00:00+00:00",+ "billing_latest_usage_report_date": latest_usage_report_date,+ }+ self.organization.usage = stamped_usage+ self.organization.save()+ with (+ patch("ee.billing.quota_limiting._patch_todays_usage", side_effect=billing_status_lands_first)+ if first_write_skipped and run == 0+ else nullcontext()+ ):+ self._run_quota_limiting()+ limited = (+ expect_limited and stamped_from_run is not None and run >= stamped_from_run + first_write_skipped+ )+ assert self.redis_client.zrange("@posthog/quota-limits/events", 0, -1) == ([token] if limited else [])++ self.organization.refresh_from_db()+ assert self.organization.usage["events"]["todays_usage"] == 1+ update_org_billing_quotas(self.organization)+ assert self.redis_client.zrange("@posthog/quota-limits/events", 0, -1) == ([token] if expect_limited else [])+ today, yesterday = datetime.date(2026, 11, 1), datetime.date(2026, 10, 31)+ assert [call.args[1].start.date() for call in fetch_report.call_args_list] == (+ [today, yesterday, today, yesterday] if first_write_skipped else [today, yesterday, today]+ )+@patch("posthoganalytics.capture")@patch("posthoganalytics.feature_enabled", return_value=True)@time_machine.travel("2021-01-25T23:59:59Z", tick=False)@@ -273,7 +359,7 @@ class TestQuotaLimiting(BaseTest):self.organization.save()flush_persons_and_events()- with self.assertNumQueries(FuzzyInt(4, 13)):+ with self.assertNumQueries(FuzzyInt(4, 20)):result = self._run_quota_limiting()assert patch_capture.call_count == 0 # No events should be captured since org won't be limitedassert result.quota_limited_orgs["events"] == {}@@ -467,7 +553,13 @@ class TestQuotaLimiting(BaseTest):self.organization.refresh_from_db()assert self.organization.usage == create_usage_summary(- events={"usage": 99, "limit": 100, "todays_usage": 10, "quota_limited_until": 1612137599}+ events={+ "usage": 99,+ "limit": 100,+ "todays_usage": 10,+ "daily_usage": {"2021-01-25": 10},+ "quota_limited_until": 1612137599,+ })# # Increase the trust score. They are already being limited, so we will not suspend their limiting.@@ -520,7 +612,13 @@ class TestQuotaLimiting(BaseTest):self.organization.refresh_from_db()assert self.organization.usage == create_usage_summary(- events={"usage": 99, "limit": 100, "todays_usage": 10, "quota_limiting_suspended_until": 1611705600}+ events={+ "usage": 99,+ "limit": 100,+ "todays_usage": 10,+ "daily_usage": {"2021-01-25": 10},+ "quota_limiting_suspended_until": 1611705600,+ })# Check that org is being limited after suspension expired@@ -1970,12 +2068,11 @@ class TestQuotaLimiting(BaseTest):def test_usage_keys_stay_in_sync(self):"""Ensure QuotaResource, UsageCounters, and OrganizationUsageInfo all use the same keys- (except for `period`).+ (except for `period` and the billing status stamps)."""from posthog.models.organization import OrganizationUsageInfo- # OrganizationUsageInfo is source of truth (excluding 'period`)- org_usage_keys = set(OrganizationUsageInfo.__annotations__.keys()) - {"period"}+ org_usage_keys = set(OrganizationUsageInfo.__annotations__.keys()) - {"period", *BILLING_STATUS_STAMP_KEYS}quota_resource_keys = {resource.value for resource in QuotaResource}usage_counter_keys = set(UsageCounters.__annotations__.keys())@@ -2545,6 +2642,7 @@ def _fake_org(usage: dict | None) -> Any:_PERIOD = ["2021-01-01T00:00:00Z", "2021-01-31T23:59:59Z"]+_PATCH_DAY = datetime.date(2021, 1, 15)@override_settings(CLOUD_DEPLOYMENT="US")@@ -2610,6 +2708,20 @@ class TestIdentifyRefreshCandidates(SimpleTestCase):{},True,),+ (+ "flags_orgs_over_limit_only_with_yesterdays_count",+ {+ "events": {"usage": 900, "limit": 1_000, "todays_usage": 0},+ "period": _PERIOD,+ "billing_latest_usage_report_date": "2021-01-13",+ },+ _full_usage_counters(events=50),+ [],+ {},+ {},+ True,+ {"events": 100},+ ),("skips_under_limit_orgs_without_markers_or_redis",{@@ -2804,6 +2916,7 @@ class TestIdentifyRefreshCandidates(SimpleTestCase):previously_limited_overrides: dict[str, list[str]],previously_suspended_overrides: dict[str, list[str]],expected_candidate: bool,+ finished_yesterday: dict[str, int] | None = None,) -> None:org = _fake_org(usage=usage)org_id = str(org.id)@@ -2817,7 +2930,13 @@ class TestIdentifyRefreshCandidates(SimpleTestCase):previously_suspended.update(previously_suspended_overrides)candidates = _identify_refresh_candidates(- orgs_by_id, todays_usage_report, teams_by_org, previously_limited, previously_suspended+ orgs_by_id,+ todays_usage_report,+ teams_by_org,+ previously_limited,+ previously_suspended,+ today=_PATCH_DAY,+ finished_yesterday_by_org=None if finished_yesterday is None else {org_id: finished_yesterday},)assert candidates == ({org_id} if expected_candidate else set())@@ -2833,7 +2952,9 @@ class TestPatchTodaysUsage(BaseTest):self.organization.usage = Noneself.organization.save()- changed = _patch_todays_usage(self.organization, _full_usage_counters(events=42))+ changed = _patch_todays_usage(+ self.organization, _full_usage_counters(events=42), today=_PATCH_DAY, finished_yesterday=None+ )assert changed is False@@ -2863,8 +2984,8 @@ class TestPatchTodaysUsage(BaseTest):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+ assert _patch_todays_usage(self.organization, todays_usage, today=_PATCH_DAY, finished_yesterday=None) is True+ assert _patch_todays_usage(self.organization, todays_usage, today=_PATCH_DAY, finished_yesterday=None) is Falseself.organization.refresh_from_db()assert self.organization.usage["posthog_code_credits"]["todays_usage"] == 15@@ -2936,19 +3057,43 @@ class TestPatchTodaysUsage(BaseTest):self.organization.usage = {"period": ["2021-01-01T00:00:00Z", "2021-01-31T23:59:59Z"]}self.organization.save()- changed = _patch_todays_usage(self.organization, _full_usage_counters(events=42))+ changed = _patch_todays_usage(+ self.organization, _full_usage_counters(events=42), today=_PATCH_DAY, finished_yesterday=None+ )assert changed is False+ @parameterized.expand(+ [+ ("first_run_of_the_day", {"2021-01-14": 9}, {"events": 12}),+ ("later_run", {"2021-01-13": 3, "2021-01-14": 12, "2021-01-15": 2}, None),+ ]+ )+ def test_daily_usage_holds_yesterday_and_today(self, _name, stored, finished_yesterday) -> None:+ self.organization.usage = {+ "events": {"usage": 100, "limit": 1_000, "todays_usage": 2, "daily_usage": stored},+ "period": _PERIOD,+ }+ self.organization.save()++ _patch_todays_usage(+ self.organization, _full_usage_counters(events=4), today=_PATCH_DAY, finished_yesterday=finished_yesterday+ )++ self.organization.refresh_from_db()+ assert self.organization.usage["events"]["daily_usage"] == {"2021-01-14": 12, "2021-01-15": 4}+def test_returns_false_when_value_is_unchanged(self) -> None:self.organization.usage = {- "events": {"usage": 100, "limit": 1_000, "todays_usage": 7},+ "events": {"usage": 100, "limit": 1_000, "todays_usage": 7, "daily_usage": {"2021-01-15": 7}},"period": ["2021-01-01T00:00:00Z", "2021-01-31T23:59:59Z"],}self.organization.save()before_updated_at = self.organization.updated_at- changed = _patch_todays_usage(self.organization, _full_usage_counters(events=7))+ changed = _patch_todays_usage(+ self.organization, _full_usage_counters(events=7), today=_PATCH_DAY, finished_yesterday=None+ )assert changed is False# No SQL UPDATE means `updated_at` should not move.@@ -2966,11 +3111,14 @@ class TestPatchTodaysUsage(BaseTest):}self.organization.save()- changed = _patch_todays_usage(self.organization, _full_usage_counters(events=0))+ changed = _patch_todays_usage(+ self.organization, _full_usage_counters(events=0), today=_PATCH_DAY, finished_yesterday=None+ )assert changed is Trueself.organization.refresh_from_db()assert self.organization.usage["events"]["todays_usage"] == 0+ assert "daily_usage" not in self.organization.usage["events"]# Sibling fields untouched.assert self.organization.usage["events"]["usage"] == 100assert self.organization.usage["events"]["limit"] == 1_000@@ -2985,7 +3133,9 @@ class TestPatchTodaysUsage(BaseTest):before_updated_at = self.organization.updated_at# Only `events` changes; `recordings` stays identical.- changed = _patch_todays_usage(self.organization, _full_usage_counters(events=42, recordings=5))+ changed = _patch_todays_usage(+ self.organization, _full_usage_counters(events=42, recordings=5), today=_PATCH_DAY, finished_yesterday=None+ )assert changed is True# In-memory mirror reflects the change.@@ -3024,7 +3174,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), batch=batch)+ changed = _patch_todays_usage(+ self.organization, _full_usage_counters(events=99), today=_PATCH_DAY, finished_yesterday=None, batch=batch+ )if batch is not None:batch.write()@@ -3360,13 +3512,21 @@ class TestRefreshOrgSelfDrivingQuota(BaseTest):== expected_timestamp)+ @parameterized.expand([("without_stamp", False), ("with_stamp", True)])@patch("posthoganalytics.capture")@patch("posthoganalytics.feature_enabled", return_value=False)@time_machine.travel("2026-06-15T12:00:00Z", tick=False)- def test_refresh_patches_todays_usage_and_flips_the_limiter(self, _feature_enabled, _capture) -> None:+ def test_refresh_patches_todays_usage_and_flips_the_limiter(+ self, _name, stamped, _feature_enabled, _capture+ ) -> None:# The event-driven path exists because the cron-patched todays_usage predates the PR that# just landed: a stale value here means the flag doesn't flip until the next cron tick.self._set_self_driving_usage(3000, todays_usage=0)+ if stamped:+ assert self.organization.usage is not None+ self.organization.usage["billing_latest_usage_report_date"] = "2026-06-14"+ self.organization.usage["signals_credits"]["daily_usage"] = {}+ self.organization.save()with patch("ee.billing.quota_limiting.get_self_driving_credits_used_in_period_for_org", return_value=1500) as live_mock:diff --git a/posthog/admin/admins/organization_admin.py b/posthog/admin/admins/organization_admin.pyindex 57b42a5da6fa..7fddcd84c513 100644--- a/posthog/admin/admins/organization_admin.py+++ b/posthog/admin/admins/organization_admin.py@@ -415,11 +415,13 @@ class OrganizationAdmin(admin.ModelAdmin):# Format numbers with thousand separatorsformatted_data = {}for product, data in usage_data.items():- if product == "period":+ # `period` and the billing status stamps sit next to the products and are not dicts.+ if not isinstance(data, dict):continue+ limit = data.get("limit")formatted_data[product] = {"usage": f"{int(data.get('usage', 0)):,}" if data.get("usage") is not None else "-",- "limit": f"{int(data.get('limit')):,}" if data.get("limit") else None,+ "limit": f"{int(limit):,}" if limit else None,"todays_usage": f"{int(data.get('todays_usage', 0)):,}"if data.get("todays_usage") is not Noneelse "-",diff --git a/posthog/admin/test_admin.py b/posthog/admin/test_admin.pyindex e0f0a6243464..0f399da3a08c 100644--- a/posthog/admin/test_admin.py+++ b/posthog/admin/test_admin.py@@ -9,10 +9,11 @@ from django.test import RequestFactory, SimpleTestCasefrom posthog.admin import _OAUTH_ADMIN_MODEL_NAMES, install_admin_app_list_overrides, register_all_adminfrom posthog.admin.admins.event_ingestion_restriction_config import EventIngestionRestrictionConfigAdminfrom posthog.admin.admins.global_rate_limit_threshold_config import GlobalRateLimitThresholdConfigAdmin+from posthog.admin.admins.organization_admin import OrganizationAdminfrom posthog.admin.admins.personal_api_key_admin import PersonalAPIKeyAdminfrom posthog.admin.admins.user_admin import UserAdmin, UserChangeFormfrom posthog.admin.inlines.organization_member_inline import OrganizationMemberForUserInline, OrganizationMemberInline-from posthog.models import PersonalAPIKey, User+from posthog.models import Organization, PersonalAPIKey, Userfrom posthog.models.event_ingestion_restriction_config import EventIngestionRestrictionConfigfrom posthog.models.global_rate_limit_threshold_config import GlobalRateLimitThresholdConfigfrom posthog.models.utils import generate_random_token_personal, hash_key_value@@ -249,6 +250,24 @@ class TestOrganizationMemberInlineConfig(SimpleTestCase):assert "invited_by" in OrganizationMemberForUserInline.readonly_fields+class TestOrganizationAdminUsageDisplay(SimpleTestCase):+ def test_usage_display_renders_products_next_to_billing_status_stamps(self):+ organization = Organization(+ usage={+ "events": {"usage": 1000, "limit": 5000, "todays_usage": 10},+ "period": ["2026-08-01T00:00:00Z", "2026-09-01T00:00:00Z"],+ "billing_status_computed_at": "2026-08-02T00:00:00+00:00",+ "billing_latest_usage_report_date": None,+ }+ )++ html = OrganizationAdmin(Organization, AdminSite()).usage_display(organization)++ assert "events" in html+ assert "5,000" in html+ assert "billing_status_computed_at" not in html++class TestPersonalAPIKeyAdminForm(BaseTest):def test_change_form_saves_unscoped_key_with_blank_scoped_fields(self):# scoped_teams/scoped_organizations must stay optional in Django formsdiff --git a/posthog/models/organization.py b/posthog/models/organization.pyindex 234628e3f0e0..d76d8fe9508f 100644--- a/posthog/models/organization.py+++ b/posthog/models/organization.py@@ -40,6 +40,7 @@ class OrganizationUsageResource(TypedDict):usage: int | Nonelimit: int | Nonetodays_usage: int | None+ daily_usage: NotRequired[dict[str, int]]# The "usage" field is essentially cached info from the Billing Service to be used for visual reporting to the user@@ -71,6 +72,8 @@ class OrganizationUsageInfo(TypedDict):logs_mb_ingested: OrganizationUsageResource | Nonereplay_vision_credits: OrganizationUsageResource | Noneperiod: list[str] | None+ billing_status_computed_at: NotRequired[str]+ billing_latest_usage_report_date: NotRequired[str | None]@frozen