Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(billing): read usage counter flags only in usage reports v2 (#122838)

Alex Mays87bd264c5e3a
diff --git a/docs/internal/feature-flags/billing.md b/docs/internal/feature-flags/billing.md
index d377ebb75607..0c1d264aa05c 100644
--- a/docs/internal/feature-flags/billing.md
+++ b/docs/internal/feature-flags/billing.md
@@ -138,7 +138,7 @@ The workers on that queue need `USAGE_INGESTION_ADDR` with an explicit port, and
The Python gRPC client connects to port 443 when the address has no port, but the usage-ingestion Service listens on port 80.
The task discards counts for teams that the allowlist does not enable.
Delivery is best effort: the shared usage-ingestion client logs a failed send, and the task does not put the counts back.
-This counter is in `RECORD_REALTIME_BLOCKERS`, so its `realtime` mode resolves to `both` and legacy totals stay authoritative during the comparison rollout.
+Usage records from before this task omit the requests that Django served. [Step 4](#step-4-usage-report-generation) lists this gap with the other gaps that keep a counter off `realtime`.
### Redis pipelining
@@ -252,24 +252,17 @@ The usage report task queries ClickHouse for aggregated billing data.
**Source file:** `posthog/tasks/usage_report.py`
Daily reports, usage reports v2, and quota limiting read the billed request counters through `posthog.usage_counters.UsageCounterService`.
-Each counter's feature flag selects `legacy`, `both`, or `realtime`.
-A counter in `RECORD_REALTIME_BLOCKERS` resolves `realtime` to `both` until its producer discrepancy is resolved or confirmed as intended billing behavior.
-All record-backed counters are guarded for the initial comparison rollout.
-These guards cover event, enhanced-person, and exception timestamp attribution, Django local-evaluation requests, replay sessions, and workflow invocations.
-Feature-flag request records use Rust flush time, while legacy billing events use the later Celery export time.
-That counter remains guarded until cutover reconciles requests across those dates.
-CDP and workflow dispatches use independent flush-time clocks for legacy app metrics and usage records.
-Their counters remain guarded until cutover reconciles dispatches across those dates.
-They also cover producer gaps in the exemptions for product-tour survey responses, wallet-billed AI gateway events, and sponsored relay events.
-Guarded counters still collect comparisons while legacy totals remain authoritative.
+The daily report and quota limiting always query billing events.
+Only usage reports v2 reads the counter feature flags.
+There, each counter's feature flag selects `legacy`, `both`, or `realtime`.
`legacy` queries billing events. `both` queries billing events and `billing_usage_records`, and keeps the legacy count authoritative.
-`realtime` uses the usage record count. A report for a complete day also queries billing events, for the comparison. Each caller states whether its period is a complete day. The daily report and finalized usage reports v2 runs pass a complete day. Intraday usage reports v2 runs and quota limiting pass a partial day and skip that query.
+`realtime` uses the usage record count. A finalized run covers a complete day and also queries billing events, for the comparison. An intraday run covers a partial day and skips that query.
Reports retain both totals in `counter_comparisons` for every counter that ran both queries. Both totals count each team under its current organization, the same as the report fields. A failed comparison query omits that counter's pair. A failure in a query needed for normal report fields still fails the report.
The usage record query checks units separately for each usage key and discards all totals for a key with incompatible units.
A mismatch in a comparison-only source omits that counter's pair and records a shadow validation failure; other counters remain available.
A mismatch in a source used for a realtime total fails the report.
Removing the complete-day legacy query will be a later code change.
-The mode selects the authoritative count for every caller and time window.
+The mode selects the authoritative count for finalized and intraday runs.
Each run keeps its resolved plan, and flag lookups are cached for 60 seconds per process.
Usage reports v2 saves each completed legacy query in S3 under its workflow run.
Each legacy counter runs in its own activity, sharing the workflow's four-query limit with other queries.
@@ -278,10 +271,21 @@ The counter-report activity reads those checkpoints before its shared usage-reco
Cancellation stops the counter worker between queries and before checkpoint or report writes; an in-flight query or write can still finish.
Usage reports v2 records query latency and failures under the existing query names, plus `usage_records` for the shared scan and `usage_counters` for the combined activity.
A failed counter activity or remaining query fails the workflow without waiting for the other queries to finish.
-Quota runs log resolved sources as `usage_counter_sources` and successful comparisons as `usage_counter_comparison`.
-Each comparison includes both totals, the number of differing teams, and the sum of absolute differences, so opposite discrepancies cannot cancel each other out.
Missing-organization diagnostics use size-bounded events. Temporal runs their capture and flush outside the event loop.
+Usage records still differ from the legacy queries for every counter.
+Set a counter's flag to `realtime` only after a change removes its gap below.
+The team can also agree to bill the usage record count with the gap.
+
+- Events, enhanced person events, and exceptions: usage records use capture time, and the legacy queries use the event timestamp. The switch must not count an event on both dates or on neither date.
+- Feature flag requests: usage records use the flush time of the Rust flags service. The legacy query uses the later Celery export time.
+- Feature flag local evaluation requests: usage records from before [#118814](https://github.com/PostHog/posthog/pull/118814) omit the requests that the Django feature flag list endpoint served. Compare both producers over a complete window before you switch this counter.
+- CDP invocations and workflow emails, push, and SMS: usage records and app metrics flush on separate clocks. Each source can put one dispatch on a different date.
+- Workflow invocations: the legacy query counts fetch and push dispatches. Before [#118809](https://github.com/PostHog/posthog/pull/118809), a push dispatch wrote only a `workflow_push_sent` record, so `workflow_billable_invocations` held only fetches. Now a push dispatch writes both records. The clock difference above also applies.
+- Web and mobile recordings: the replay pipeline marks a session as seen before it parses the first message. When that message fails, the later messages of the session bill nothing. The fix is [#121613](https://github.com/PostHog/posthog/pull/121613), which bills each saved session once.
+- Survey responses: usage records include product tour responses, which the legacy query exempts.
+- AI events: usage records do not apply the legacy exemptions for wallet-billed gateway events and sponsored relay events.
+
### Billable calculation
Local evaluation requests are weighted 10x compared to decide requests:
diff --git a/ee/billing/quota_limiting.py b/ee/billing/quota_limiting.py
index 6ab5680bb4d2..85bc2fb4dd3c 100644
--- a/ee/billing/quota_limiting.py
+++ b/ee/billing/quota_limiting.py
@@ -39,7 +39,7 @@ from posthog.tasks.usage_report import (
get_teams_with_mcp_event_count_in_period,
iter_billable_teams,
)
-from posthog.usage_counters import UsageCounter, UsageCounterService, log_usage_counter_comparisons
+from posthog.usage_counters import UsageCounter, UsageCounterMode, UsageCounterPlan, UsageCounterService
from posthog.utils import get_current_day
from products.ai_observability.backend.offline_evaluation_billing import get_offline_evaluation_usage
@@ -1357,30 +1357,32 @@ def update_all_orgs_billing_quotas(
total_start = time()
period = get_current_day()
service = UsageCounterService()
- plan = service.resolve_plan(
- period,
+ plan = UsageCounterPlan(
+ period=period,
caller="quota_limiting",
- complete=False,
- counters=(
- UsageCounter.EVENTS,
- UsageCounter.EXCEPTIONS,
- UsageCounter.RECORDINGS,
- UsageCounter.FEATURE_FLAG_REQUESTS,
- UsageCounter.FEATURE_FLAG_LOCAL_EVALUATION_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.POSTHOG_CODE_CREDITS,
- UsageCounter.SANDBOX_COMPUTE_CREDITS,
- UsageCounter.REPLAY_VISION_CREDITS,
+ modes=dict.fromkeys(
+ (
+ UsageCounter.EVENTS,
+ UsageCounter.EXCEPTIONS,
+ UsageCounter.RECORDINGS,
+ UsageCounter.FEATURE_FLAG_REQUESTS,
+ UsageCounter.FEATURE_FLAG_LOCAL_EVALUATION_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.POSTHOG_CODE_CREDITS,
+ UsageCounter.SANDBOX_COMPUTE_CREDITS,
+ UsageCounter.REPLAY_VISION_CREDITS,
+ ),
+ UsageCounterMode.LEGACY,
),
)
@@ -1391,7 +1393,6 @@ def update_all_orgs_billing_quotas(
"offline_evaluation_usage", get_offline_evaluation_usage, period.start, period.start + timedelta(days=1)
)
counter_report = _timed_query("usage_counters", service.fetch_report, period, plan=plan)
- log_usage_counter_comparisons(counter_report, caller="quota_limiting", date=period.start.date().isoformat())
api_queries_usage = _timed_query(
"api_queries_metrics", get_teams_with_api_queries_metrics, period.start, period.end
diff --git a/ee/billing/test/test_quota_limiting.py b/ee/billing/test/test_quota_limiting.py
index 54f195a6421e..c2ea5e00c749 100644
--- a/ee/billing/test/test_quota_limiting.py
+++ b/ee/billing/test/test_quota_limiting.py
@@ -4,7 +4,7 @@ from uuid import uuid4
import time_machine
from posthog.test.base import BaseTest, FuzzyInt, _create_event, flush_persons_and_events
-from unittest.mock import ANY, patch
+from unittest.mock import patch
from django.apps import apps
from django.db import DatabaseError
@@ -21,7 +21,6 @@ from posthog.models.organization import Organization
from posthog.models.team.team import Team
from posthog.redis import get_client
from posthog.test.fixtures import create_app_metric2
-from posthog.usage_counters import UsageRecordTotal, UsageRecordTotals
from products.ai_observability.backend.models.offline_evaluations import OfflineEvaluationUsageLedger
@@ -148,29 +147,11 @@ class TestQuotaLimiting(BaseTest):
flush_persons_and_events()
with (
- self.settings(USAGE_COUNTER_REALTIME_MODES="events:both"),
- patch(
- "posthog.tasks.usage_report.get_usage_records_in_period",
- return_value=UsageRecordTotals(
- totals=[
- UsageRecordTotal(team_id=self.team.id, organization_id=org_id, usage_key="events", quantity=3)
- ]
- ),
- ),
- patch("posthog.usage_counters.logger.info") as counter_log,
+ self.settings(USAGE_COUNTER_REALTIME_MODES="events:realtime"),
+ patch("posthog.tasks.usage_report.get_usage_records_in_period") as records,
):
result = self._run_quota_limiting()
- counter_log.assert_any_call(
- "usage_counter_comparison",
- caller="quota_limiting",
- date="2021-01-25",
- counter="event_count_in_period",
- source="both",
- legacy=ANY,
- realtime=3,
- differing_teams=ANY,
- absolute_difference=ANY,
- )
+ records.assert_not_called()
# feature_enabled will be called for AI billing check and then for data retention flag
patch_feature_enabled.assert_any_call(
QUOTA_LIMIT_DATA_RETENTION_FLAG,
diff --git a/posthog/tasks/test/test_ai_observability_usage_report.py b/posthog/tasks/test/test_ai_observability_usage_report.py
index 325b637d35ac..77f3eecfed99 100644
--- a/posthog/tasks/test/test_ai_observability_usage_report.py
+++ b/posthog/tasks/test/test_ai_observability_usage_report.py
@@ -604,7 +604,7 @@ class TestAIObservabilityUsageReport(APIBaseTest, ClickhouseTestMixin, Clickhous
all_data = defaultdict(dict, {key: dict(rows) for key, rows in counter_report.counts.items()})
org_id = str(self.organization.id)
before = list(OfflineEvaluationUsageLedger.objects.for_team(self.team.id).order_by("id").values())
- celery_report = _get_all_org_reports(period=period, counter_report=counter_report)[org_id]
+ celery_report = _get_all_org_reports(period=period)[org_id]
ctx = WorkflowContext(
run_id="offline-usage", date_str="2026-10-31", period_start=period.start, period_end=period.end
)
diff --git a/posthog/tasks/test/test_usage_counters.py b/posthog/tasks/test/test_usage_counters.py
index 41affe2d96f8..2ac7d7ba0f9c 100644
--- a/posthog/tasks/test/test_usage_counters.py
+++ b/posthog/tasks/test/test_usage_counters.py
@@ -17,12 +17,10 @@ from posthog.usage_counters import (
UsageCounterComparisonRows,
UsageCounterMode,
UsageCounterPlan,
- UsageCounterReport,
UsageCounterService,
UsageRecordTotal,
UsageRecordTotals,
_mode_cache,
- log_usage_counter_comparisons,
resolve_modes,
validate_usage_record_window,
)
@@ -34,24 +32,6 @@ SANDBOX_COMPUTE_RESOURCE_KEYS = (
"teams_with_sandbox_compute_cpu_millicore_seconds_in_period",
"teams_with_sandbox_compute_memory_mib_seconds_in_period",
)
-# Removing a counter from RECORD_REALTIME_BLOCKERS must fail these tests, so this set lists the counters by name.
-REALTIME_GUARDED_COUNTERS = {
- UsageCounter.EVENTS,
- UsageCounter.ENHANCED_PERSON_EVENTS,
- UsageCounter.EXCEPTIONS,
- UsageCounter.CDP_INVOCATIONS,
- UsageCounter.RECORDINGS,
- UsageCounter.MOBILE_RECORDINGS,
- UsageCounter.MOBILE_BILLABLE_RECORDINGS,
- UsageCounter.WORKFLOW_INVOCATIONS,
- UsageCounter.WORKFLOW_EMAILS,
- UsageCounter.WORKFLOW_PUSH,
- UsageCounter.WORKFLOW_SMS,
- UsageCounter.FEATURE_FLAG_REQUESTS,
- UsageCounter.FEATURE_FLAG_LOCAL_EVALUATION_REQUESTS,
- UsageCounter.SURVEY_RESPONSES,
- UsageCounter.AI_EVENTS,
-}
class TestUsageRecordQuery(SimpleTestCase):
@@ -69,7 +49,7 @@ class TestUsageRecordQuery(SimpleTestCase):
period = DayRange(start=datetime(2026, 5, 4, tzinfo=UTC), end=datetime(2026, 5, 5, tzinfo=UTC))
plan = UsageCounterPlan(
period=period,
- caller="daily_report",
+ caller="usage_reports_v2",
modes={UsageCounter.CDP_INVOCATIONS: UsageCounterMode.BOTH, UsageCounter.WORKFLOW_EMAILS: email_mode},
complete=True,
)
@@ -77,7 +57,7 @@ class TestUsageRecordQuery(SimpleTestCase):
if emails:
rows.append((1, "org-a", "workflow_emails_sent", "invocations", emails))
rows.append((1, "org-a", invalid_key, "bytes", 25))
- failures_before = SHADOW_FAILURES.labels(caller="daily_report", stage="validation")._value.get()
+ failures_before = SHADOW_FAILURES.labels(caller="usage_reports_v2", stage="validation")._value.get()
with (
patch("posthog.tasks.usage_report.sync_execute", return_value=rows) as scan,
patch(
@@ -101,7 +81,7 @@ class TestUsageRecordQuery(SimpleTestCase):
)
}
assert (
- SHADOW_FAILURES.labels(caller="daily_report", stage="validation")._value.get()
+ SHADOW_FAILURES.labels(caller="usage_reports_v2", stage="validation")._value.get()
== failures_before + 1
)
scan.assert_called_once()
@@ -117,7 +97,9 @@ class TestUsageRecordQuery(SimpleTestCase):
def test_reads_quantities_in_the_producer_unit(self, usage_key: str, unit: str) -> None:
period = DayRange(start=datetime(2026, 5, 4, tzinfo=UTC), end=datetime(2026, 5, 5, tzinfo=UTC))
with patch("posthog.tasks.usage_report.sync_execute", return_value=[(1, "org-a", usage_key, unit, 25)]):
- assert usage_report.get_usage_records_in_period(period, (usage_key,), "daily_report") == UsageRecordTotals(
+ assert usage_report.get_usage_records_in_period(
+ period, (usage_key,), "usage_reports_v2"
+ ) == UsageRecordTotals(
totals=[UsageRecordTotal(team_id=1, organization_id="org-a", usage_key=usage_key, quantity=25)]
)
@@ -128,7 +110,7 @@ class TestUsageRecordQuery(SimpleTestCase):
if mixed:
rows.insert(0, (1, "org-a", "cdp_billable_invocations", "invocations", 10))
with patch("posthog.tasks.usage_report.sync_execute", return_value=rows) as scan:
- result = usage_report.get_usage_records_in_period(period, ("cdp_billable_invocations",), "daily_report")
+ result = usage_report.get_usage_records_in_period(period, ("cdp_billable_invocations",), "usage_reports_v2")
assert result.totals == []
assert result.errors == {
"cdp_billable_invocations": "Unexpected unit 'bytes' for usage key 'cdp_billable_invocations'; expected 'invocations'"
@@ -224,12 +206,12 @@ class TestUsageCounterReport(SimpleTestCase):
email_query = self.legacy[UsageCounter.WORKFLOW_EMAILS]
email_query.return_value = [(1, 3)]
service = UsageCounterService()
- failures_before = SHADOW_FAILURES.labels(caller="daily_report", stage="scan")._value.get()
+ failures_before = SHADOW_FAILURES.labels(caller="usage_reports_v2", stage="scan")._value.get()
with patch(
"posthoganalytics.get_feature_flag",
side_effect=lambda name, distinct_id: "both" if name.endswith("cdp-invocations") else "legacy",
) as flag:
- plan = service.resolve_plan(period, caller="daily_report", complete=True)
+ plan = service.resolve_plan(period, complete=True)
flag.side_effect = None
flag.return_value = "legacy"
report = service.fetch_report(period, plan=plan)
@@ -253,10 +235,12 @@ class TestUsageCounterReport(SimpleTestCase):
)
}
)
- records_query.assert_called_once_with(period, ("cdp_billable_invocations",), "daily_report")
+ records_query.assert_called_once_with(period, ("cdp_billable_invocations",), "usage_reports_v2")
legacy_query.assert_called_once_with(period.start, period.end)
email_query.assert_called_once_with(period.start, period.end)
- assert SHADOW_FAILURES.labels(caller="daily_report", stage="scan")._value.get() == failures_before + int(fails)
+ assert SHADOW_FAILURES.labels(caller="usage_reports_v2", stage="scan")._value.get() == failures_before + int(
+ fails
+ )
with self.assertRaisesRegex(ValueError, "across periods"):
service.fetch_report(
DayRange(start=period.start + timedelta(days=1), end=period.end + timedelta(days=1)), plan=plan
@@ -275,37 +259,6 @@ class TestUsageCounterReport(SimpleTestCase):
self.records.assert_not_called()
flag.assert_not_called()
- def test_comparison_logs_expose_differences_when_totals_match(self) -> None:
- report = UsageCounterReport(
- counts={},
- usage_sources={"event_count_in_period": UsageCounterMode.BOTH},
- counter_comparisons={
- "event_count_in_period": UsageCounterComparisonRows(
- legacy_by_team={1: 7, 2: 3},
- realtime_by_team={1: {"org-a": 3}, 2: {"org-b": 7}},
- )
- },
- )
- with patch("posthog.usage_counters.logger.info") as log:
- log_usage_counter_comparisons(report, caller="quota_limiting", date="2026-05-04")
- log.assert_any_call(
- "usage_counter_sources",
- caller="quota_limiting",
- date="2026-05-04",
- usage_sources=report.usage_sources,
- )
- log.assert_any_call(
- "usage_counter_comparison",
- caller="quota_limiting",
- date="2026-05-04",
- counter="event_count_in_period",
- source="both",
- legacy=10,
- realtime=10,
- differing_teams=2,
- absolute_difference=8,
- )
-
@parameterized.expand([("legacy",), ("both",)])
def test_authoritative_query_failure_fails_report(self, mode: str) -> None:
period = DayRange(start=datetime(2026, 5, 4, tzinfo=UTC), end=datetime(2026, 5, 5, tzinfo=UTC))
@@ -315,7 +268,7 @@ class TestUsageCounterReport(SimpleTestCase):
self.settings(USAGE_COUNTER_REALTIME_MODES=f"cdp-invocations:{mode}"),
patch("posthoganalytics.get_feature_flag", return_value="legacy"),
):
- plan = service.resolve_plan(period, caller="daily_report", complete=True)
+ plan = service.resolve_plan(period, complete=True)
with self.assertRaisesRegex(RuntimeError, "legacy unavailable"):
service.fetch_report(period, plan=plan)
@@ -350,11 +303,11 @@ class TestUsageCounterReport(SimpleTestCase):
) as flag:
if isinstance(flag_value, Exception):
flag.side_effect = flag_value
- plan = service.resolve_plan(period, caller="daily_report", complete=True)
+ plan = service.resolve_plan(period, complete=True)
report = service.fetch_report(period, plan=plan)
- assert report.counts[UsageCounter.WORKFLOW_EMAILS.value] == [(1, 12)]
+ assert report.counts[UsageCounter.WORKFLOW_EMAILS.value] == [(1, 9 if flag_value == "realtime" else 12)]
assert plan.modes[UsageCounter.WORKFLOW_EMAILS] == (
- UsageCounterMode.BOTH if flag_value in ("both", "realtime") else UsageCounterMode.LEGACY
+ UsageCounterMode(flag_value) if flag_value in ("both", "realtime") else UsageCounterMode.LEGACY
)
assert (report.counter_comparisons is not None) == (flag_value in ("both", "realtime"))
assert records_query.call_count == int(flag_value in ("both", "realtime"))
@@ -368,17 +321,13 @@ class TestUsageCounterReport(SimpleTestCase):
self.settings(USAGE_COUNTER_REALTIME_MODES=f"cdp-invocations:{mode}"),
patch("posthoganalytics.get_feature_flag") as flag,
):
- plan = service.resolve_plan(period, caller="daily_report", complete=True)
+ plan = service.resolve_plan(period, complete=True)
assert (service.fetch_report(period, plan=plan).counter_comparisons is not None) == enabled
assert all(call.args[0] != "usage-counter-realtime-cdp-invocations" for call in flag.call_args_list)
- @parameterized.expand(
- list(product(UsageCounterMode, ("daily_report", "usage_reports_v2", "quota_limiting"), (0, 1)))
- )
+ @parameterized.expand(list(product(UsageCounterMode, (0, 1))))
@time_machine.travel("2026-05-04T12:00:00Z", tick=False)
- def test_resolved_mode_selects_queries_for_every_caller_and_day(
- self, mode: UsageCounterMode, caller: UsageCounterCaller, days_ago: int
- ) -> None:
+ def test_resolved_mode_selects_queries_for_every_day(self, mode: UsageCounterMode, days_ago: int) -> None:
start = datetime(2026, 5, 4, tzinfo=UTC) - timedelta(days=days_ago)
period = DayRange(start=start, end=start + timedelta(days=1))
legacy = self.legacy[UsageCounter.WORKFLOW_EMAILS]
@@ -390,7 +339,7 @@ class TestUsageCounterReport(SimpleTestCase):
service = UsageCounterService()
plan = UsageCounterPlan(
period=period,
- caller=caller,
+ caller="usage_reports_v2",
modes={**dict.fromkeys(UsageCounter, UsageCounterMode.LEGACY), UsageCounter.WORKFLOW_EMAILS: mode},
complete=days_ago > 0,
)
@@ -424,30 +373,23 @@ class TestUsageCounterReport(SimpleTestCase):
patch("posthog.usage_counters.time.monotonic", return_value=100) as clock,
patch("posthoganalytics.get_feature_flag", return_value="both") as flag,
):
- modes = resolve_modes("daily_report")
+ modes = resolve_modes()
assert modes == {
counter: UsageCounterMode.BOTH if counter in COUNTER_FLAG_NAMES else UsageCounterMode.LEGACY
for counter in UsageCounter
}
- plan = service.resolve_plan(period, caller="daily_report", complete=True)
+ plan = service.resolve_plan(period, complete=True)
flag.return_value = "realtime"
- assert resolve_modes("usage_reports_v2") == modes
- assert resolve_modes("quota_limiting") == modes
+ assert resolve_modes() == modes
assert flag.call_count == len(COUNTER_FLAG_NAMES)
clock.return_value = 161
- assert resolve_modes("daily_report") == {
- counter: (
- UsageCounterMode.LEGACY
- if counter not in COUNTER_FLAG_NAMES
- else UsageCounterMode.BOTH
- if counter in REALTIME_GUARDED_COUNTERS
- else UsageCounterMode.REALTIME
- )
+ assert resolve_modes() == {
+ counter: UsageCounterMode.REALTIME if counter in COUNTER_FLAG_NAMES else UsageCounterMode.LEGACY
for counter in UsageCounter
}
assert flag.call_count == 2 * len(COUNTER_FLAG_NAMES)
with self.settings(USAGE_COUNTER_REALTIME_MODES="cdp-invocations:legacy"):
- assert resolve_modes("daily_report")[UsageCounter.CDP_INVOCATIONS] == UsageCounterMode.LEGACY
+ assert resolve_modes()[UsageCounter.CDP_INVOCATIONS] == UsageCounterMode.LEGACY
report = service.fetch_report(period, plan=plan)
assert report.counts[UsageCounter.CDP_INVOCATIONS.value] == []
assert report.counter_comparisons == {
@@ -476,7 +418,7 @@ class TestUsageCounterReport(SimpleTestCase):
service = UsageCounterService()
plan = UsageCounterPlan(
period=period,
- caller="daily_report",
+ caller="usage_reports_v2",
modes={
UsageCounter.CDP_INVOCATIONS: UsageCounterMode.BOTH,
UsageCounter.WORKFLOW_EMAILS: UsageCounterMode.REALTIME,
@@ -502,14 +444,14 @@ class TestUsageCounterReport(SimpleTestCase):
assert report.counter_comparisons == expected
assert report.usage_sources is not None
assert report.usage_sources["workflow_emails_sent_in_period"] == UsageCounterMode.REALTIME
- records.assert_called_once_with(period, ("cdp_billable_invocations", "workflow_emails_sent"), "daily_report")
+ records.assert_called_once_with(
+ period, ("cdp_billable_invocations", "workflow_emails_sent"), "usage_reports_v2"
+ )
email_legacy.assert_called_once_with(period.start, period.end)
- @parameterized.expand(
- list(product(UsageCounterMode, ("flag", "override"), ("daily_report", "usage_reports_v2", "quota_limiting")))
- )
+ @parameterized.expand(list(product(UsageCounterMode, ("flag", "override"))))
def test_remaining_readers_preserve_counts_and_exception_breakdowns(
- self, mode: UsageCounterMode, source: str, caller: UsageCounterCaller
+ self, mode: UsageCounterMode, source: str
) -> None:
period = DayRange(start=datetime(2026, 5, 4, tzinfo=UTC), end=datetime(2026, 5, 5, tzinfo=UTC))
counter_keys = {
@@ -551,28 +493,21 @@ class TestUsageCounterReport(SimpleTestCase):
patch("posthoganalytics.get_feature_flag", return_value=mode if source == "flag" else "legacy"),
):
service = UsageCounterService()
- plan = service.resolve_plan(
- period, caller=caller, complete=caller != "quota_limiting", counters=tuple(counter_keys)
- )
+ plan = service.resolve_plan(period, complete=True, counters=tuple(counter_keys))
report = service.fetch_report(period, plan=plan)
for index, (counter, (_, quantity)) in enumerate(counter_keys.items()):
- reads_records = plan.modes[counter] == UsageCounterMode.REALTIME
- assert reads_records == (mode == UsageCounterMode.REALTIME and counter not in REALTIME_GUARDED_COUNTERS)
- assert report.counts[counter] == [(1, quantity if reads_records else index + 1)]
- if caller == "quota_limiting":
- assert "teams_with_web_exceptions_captured_in_period" not in report.counts
- assert "teams_with_js_lite_exceptions_captured_in_period" not in report.counts
- else:
- assert report.counts["teams_with_web_exceptions_captured_in_period"] == [(1, 3)]
- assert report.counts["teams_with_js_lite_exceptions_captured_in_period"] == [(1, 5)]
+ assert plan.modes[counter] == mode
+ assert report.counts[counter] == [(1, quantity if mode == UsageCounterMode.REALTIME else index + 1)]
+ assert report.counts["teams_with_web_exceptions_captured_in_period"] == [(1, 3)]
+ assert report.counts["teams_with_js_lite_exceptions_captured_in_period"] == [(1, 5)]
self.exceptions.assert_called_once_with(period.start, period.end)
self.legacy[UsageCounter.CDP_INVOCATIONS].assert_called_once_with(period.start, period.end)
if mode == UsageCounterMode.LEGACY:
self.records.assert_not_called()
assert report.counter_comparisons is None
else:
- self.records.assert_called_once_with(period, tuple(dict(counter_keys.values())), caller)
+ self.records.assert_called_once_with(period, tuple(dict(counter_keys.values())), "usage_reports_v2")
assert report.counter_comparisons == {
counter.value.removeprefix("teams_with_"): UsageCounterComparisonRows(
legacy_by_team={1: index + 1}, realtime_by_team={1: {"org-a": quantity}}
@@ -594,7 +529,6 @@ class TestUsageCounterReport(SimpleTestCase):
service = UsageCounterService()
plan = service.resolve_plan(
period,
- caller="daily_report",
complete=True,
counters=(UsageCounter.MOBILE_RECORDINGS, UsageCounter.MOBILE_BILLABLE_RECORDINGS),
)
@@ -613,36 +547,40 @@ class TestUsageCounterReport(SimpleTestCase):
"mobile_recording_count_in_period": UsageCounterMode.LEGACY,
"mobile_billable_recording_count_in_period": UsageCounterMode.BOTH,
}
- self.records.assert_called_once_with(period, ("mobile_replay_recordings",), "daily_report")
+ self.records.assert_called_once_with(period, ("mobile_replay_recordings",), "usage_reports_v2")
self.legacy[UsageCounter.MOBILE_BILLABLE_RECORDINGS].assert_called_once_with(period.start, period.end)
@parameterized.expand([("daily_report", True), ("usage_reports_v2", True), ("quota_limiting", False)])
- def test_legacy_event_reader_preserves_caller_deduplication(
- self, caller: UsageCounterCaller, count_distinct: bool
+ def test_legacy_readers_preserve_caller_deduplication_and_exception_breakdowns(
+ self, caller: UsageCounterCaller, is_report: bool
) -> None:
period = DayRange(start=datetime(2026, 5, 4, tzinfo=UTC), end=datetime(2026, 5, 5, tzinfo=UTC))
self.legacy[UsageCounter.EVENTS].return_value = [(1, 7)]
- with patch("posthoganalytics.get_feature_flag", return_value="legacy"):
- service = UsageCounterService()
- plan = service.resolve_plan(period, caller=caller, complete=True, counters=(UsageCounter.EVENTS,))
- assert service.fetch_report(period, plan=plan).counts == {UsageCounter.EVENTS: [(1, 7)]}
- self.events.assert_called_once_with(period.start, period.end, count_distinct=count_distinct)
- self.exceptions.assert_not_called()
+ self.exceptions.side_effect = None
+ self.exceptions.return_value = ({"web": [(1, 3)]}, [(1, 3)])
+ plan = UsageCounterPlan(
+ period=period,
+ caller=caller,
+ modes=dict.fromkeys((UsageCounter.EVENTS, UsageCounter.EXCEPTIONS), UsageCounterMode.LEGACY),
+ )
+ expected = {UsageCounter.EVENTS.value: [(1, 7)], UsageCounter.EXCEPTIONS.value: [(1, 3)]}
+ if is_report:
+ expected["teams_with_web_exceptions_captured_in_period"] = [(1, 3)]
+ assert UsageCounterService().fetch_report(period, plan=plan).counts == expected
+ self.events.assert_called_once_with(period.start, period.end, count_distinct=is_report)
+ self.exceptions.assert_called_once_with(period.start, period.end)
+ self.records.assert_not_called()
- @parameterized.expand(list(product(("daily_report", "usage_reports_v2", "quota_limiting"), (False, True))))
- def test_guarded_exception_reader_preserves_legacy_totals_and_breakdowns(
- self, caller: UsageCounterCaller, fails: bool
- ) -> None:
+ @parameterized.expand([(False,), (True,)])
+ def test_realtime_exceptions_keep_the_legacy_breakdown_for_a_partial_day(self, fails: bool) -> None:
period = DayRange(start=datetime(2026, 5, 4, tzinfo=UTC), end=datetime(2026, 5, 5, tzinfo=UTC))
self.records.return_value = UsageRecordTotals(
totals=[UsageRecordTotal(team_id=1, organization_id="org-a", usage_key="exceptions", quantity=7)]
)
with patch("posthoganalytics.get_feature_flag", return_value="realtime"):
service = UsageCounterService()
- plan = service.resolve_plan(
- period, caller=caller, complete=caller == "daily_report", counters=(UsageCounter.EXCEPTIONS,)
- )
- assert plan.modes == {UsageCounter.EXCEPTIONS: UsageCounterMode.BOTH}
+ plan = service.resolve_plan(period, complete=False, counters=(UsageCounter.EXCEPTIONS,))
+ assert plan.modes == {UsageCounter.EXCEPTIONS: UsageCounterMode.REALTIME}
self.exceptions.side_effect = RuntimeError("legacy unavailable") if fails else None
self.exceptions.return_value = ({"web": [(1, 3)]}, [(1, 3)])
if fails:
@@ -650,16 +588,16 @@ class TestUsageCounterReport(SimpleTestCase):
service.fetch_report(period, plan=plan)
else:
report = service.fetch_report(period, plan=plan)
- expected = {UsageCounter.EXCEPTIONS.value: [(1, 3)]}
- if caller != "quota_limiting":
- expected["teams_with_web_exceptions_captured_in_period"] = [(1, 3)]
- assert report.counts == expected
+ assert report.counts == {
+ UsageCounter.EXCEPTIONS.value: [(1, 7)],
+ "teams_with_web_exceptions_captured_in_period": [(1, 3)],
+ }
assert report.counter_comparisons == {
"exceptions_captured_in_period": UsageCounterComparisonRows(
legacy_by_team={1: 3}, realtime_by_team={1: {"org-a": 7}}
)
}
- assert report.usage_sources == {"exceptions_captured_in_period": UsageCounterMode.BOTH}
+ assert report.usage_sources == {"exceptions_captured_in_period": UsageCounterMode.REALTIME}
self.exceptions.assert_called_once_with(period.start, period.end)
@parameterized.expand([(mode,) for mode in UsageCounterMode])
@@ -710,7 +648,7 @@ class TestUsageCounterReport(SimpleTestCase):
)
with patch("posthoganalytics.get_feature_flag", return_value=flag_mode) as flag:
service = UsageCounterService()
- plan = service.resolve_plan(period, caller="daily_report", complete=True, counters=counters)
+ plan = service.resolve_plan(period, complete=True, counters=counters)
report = service.fetch_report(period, plan=plan)
assert plan.modes == dict.fromkeys(counters, UsageCounterMode.LEGACY)
diff --git a/posthog/tasks/test/test_usage_report.py b/posthog/tasks/test/test_usage_report.py
index 0886ae8e3a6b..1524ed8114a3 100644
--- a/posthog/tasks/test/test_usage_report.py
+++ b/posthog/tasks/test/test_usage_report.py
@@ -65,7 +65,7 @@ from posthog.tasks.usage_report import (
_get_team_report,
_get_teams_for_usage_reports,
_get_teams_with_ai_credits_for_products,
- apply_usage_counter_metadata,
+ _UsageRecordRow,
capture_event,
capture_report,
get_all_event_metrics_in_period,
@@ -82,6 +82,7 @@ from posthog.tasks.usage_report import (
get_teams_with_sdk_logs_records_in_period,
has_non_zero_usage,
iter_billable_teams,
+ iter_reports_with_usage_counter_metadata,
send_all_org_usage_reports,
)
from posthog.temporal.usage_report.queries import QUERY_INDEX
@@ -3505,15 +3506,17 @@ class TestHogFunctionUsageReports(ClickhouseDestroyTablesMixin, TestCase, Clickh
records,
)
with self.settings(USAGE_COUNTER_REALTIME_MODES="cdp-invocations:both"):
- plan = UsageCounterService().resolve_plan(period, caller="daily_report", complete=True)
+ plan = UsageCounterService().resolve_plan(period, complete=True)
counter_report = UsageCounterService().fetch_report(period, plan=plan)
assert counter_report.counter_comparisons is not None
assert counter_report.counter_comparisons["cdp_billable_invocations_in_period"].realtime_by_team == {
3: {str(self.org_1.id): 7},
4: {str(self.org_1.id): 3},
}
- apply_usage_counter_metadata(
- all_reports, counter_report, caller="daily_report", date=period.start.date().isoformat()
+ list(
+ iter_reports_with_usage_counter_metadata(
+ all_reports.values(), counter_report, caller="usage_reports_v2", date=period.start.date().isoformat()
+ )
)
with_shadow = _get_full_org_usage_report_as_dict(
_get_full_org_usage_report(all_reports[str(self.org_1.id)], get_instance_metadata(period))
@@ -5693,6 +5696,47 @@ class TestSendUsage(LicensedTestMixin, ClickhouseDestroyTablesMixin, APIBaseTest
# timestamp=None,
# )
+ @parameterized.expand([("both",), ("realtime",)])
+ @time_machine.travel("2021-10-10T23:01:00Z", tick=False)
+ @patch("posthog.tasks.usage_report.get_ph_client")
+ @patch("ee.sqs.SQSProducer.get_sqs_producer")
+ def test_send_usage_ignores_usage_counter_modes(
+ self, mode: str, mock_get_sqs_producer: MagicMock, mock_client: MagicMock
+ ) -> None:
+ mock_producer = MagicMock()
+ mock_get_sqs_producer.return_value = mock_producer
+ usage_records = MagicMock(
+ return_value=[
+ _UsageRecordRow(
+ team_id=self.team.id,
+ organization_id=str(self.organization.id),
+ usage_key="workflow_emails_sent",
+ unit="invocations",
+ quantity=16,
+ )
+ ]
+ )
+
+ with (
+ self.settings(USAGE_COUNTER_REALTIME_MODES=f"workflow-emails:{mode}"),
+ patch(
+ "posthog.tasks.usage_report.get_teams_with_workflow_emails_sent_in_period",
+ return_value=[(self.team.id, 24)],
+ ),
+ patch("posthog.tasks.usage_report._query_usage_records", usage_records),
+ ):
+ send_all_org_usage_reports(dry_run=False)
+
+ mock_producer.send_message.assert_called_once()
+ message = json.loads(
+ gzip.decompress(base64.b64decode(mock_producer.send_message.call_args.kwargs["message_body"]))
+ )
+ report = message["usage_report"]
+ assert report["workflow_emails_sent_in_period"] == 24
+ assert "usage_sources" not in report
+ assert "counter_comparisons" not in report
+ usage_records.assert_not_called()
+
@time_machine.travel("2021-10-10T23:01:00Z", tick=False)
@patch("posthog.tasks.usage_report.get_ph_client")
@patch("ee.sqs.SQSProducer.get_sqs_producer")
diff --git a/posthog/tasks/usage_report.py b/posthog/tasks/usage_report.py
index 9cb0f18f1833..facbc2f97c91 100644
--- a/posthog/tasks/usage_report.py
+++ b/posthog/tasks/usage_report.py
@@ -3130,15 +3130,13 @@ def get_usage_records_in_period(
)
-def _get_all_usage_data(
- period_start: datetime, period_end: datetime, counter_report: UsageCounterReport | None = None
-) -> dict[str, Any]:
+def _get_all_usage_data(period_start: datetime, period_end: datetime) -> dict[str, Any]:
"""
Gets all usage data for the specified period. Clickhouse is good at counting things so
we count across all teams rather than doing it one by one
"""
- counter_report = counter_report or UsageCounterService().fetch_report(DayRange(start=period_start, end=period_end))
+ counter_report = UsageCounterService().fetch_report(DayRange(start=period_start, end=period_end))
all_metrics = get_all_event_metrics_in_period(period_start, period_end)
api_queries_usage = get_teams_with_api_queries_metrics(period_start, period_end)
logs_records_rows = get_teams_with_logs_records_in_period(period_start, period_end)
@@ -3378,14 +3376,12 @@ def _get_all_usage_data(
}
-def _get_all_usage_data_as_team_rows(
- period_start: datetime, period_end: datetime, counter_report: UsageCounterReport | None = None
-) -> dict[str, Any]:
+def _get_all_usage_data_as_team_rows(period_start: datetime, period_end: datetime) -> dict[str, Any]:
"""
Gets all usage data for the specified period as a map of team_id -> value. This makes it faster
to access the data than looping over all_data to find what we want.
"""
- all_data = _get_all_usage_data(period_start, period_end, counter_report)
+ all_data = _get_all_usage_data(period_start, period_end)
# convert it to a map of team_id -> value
for key, rows in all_data.items():
all_data[key] = convert_team_usage_rows_to_dict(rows)
@@ -3769,11 +3765,11 @@ def iter_reports_with_offline_evaluation_usage(
)
-def _get_all_org_reports(*, period: DayRange, counter_report: UsageCounterReport | None = None) -> dict[str, OrgReport]:
+def _get_all_org_reports(*, period: DayRange) -> dict[str, OrgReport]:
logger.info("Querying all org reports", period_start=period.start, period_end=period.end)
offline_usage = get_offline_evaluation_usage(period.start, period.start + timedelta(days=1))
- all_data = _get_all_usage_data_as_team_rows(period.start, period.end, counter_report)
+ all_data = _get_all_usage_data_as_team_rows(period.start, period.end)
org_reports: dict[str, OrgReport] = {}
teams_count = 0
@@ -3832,22 +3828,6 @@ def _usage_counter_diagnostic_batches(
yield batch
-def apply_usage_counter_metadata(
- org_reports: dict[str, OrgReport],
- counter_report: UsageCounterReport,
- *,
- caller: UsageCounterCaller,
- date: str,
- organization_ids: list[str] | None = None,
-) -> None:
- if not counter_report.usage_sources:
- return
- for _ in iter_reports_with_usage_counter_metadata(
- org_reports.values(), counter_report, caller=caller, date=date, organization_ids=organization_ids
- ):
- pass
-
-
def iter_reports_with_usage_counter_metadata(
org_reports: Iterable[OrgReport],
counter_report: UsageCounterReport,
@@ -4012,10 +3992,7 @@ def send_all_org_usage_reports(
logger.info("Querying usage report data")
query_time_start = datetime.now()
- service = UsageCounterService()
- plan = service.resolve_plan(period, caller="daily_report", complete=True)
- counter_report = service.fetch_report(period, plan=plan)
- org_reports = _get_all_org_reports(period=period, counter_report=counter_report)
+ org_reports = _get_all_org_reports(period=period)
if organization_ids:
original_count = len(org_reports)
@@ -4034,14 +4011,6 @@ def send_all_org_usage_reports(
filtering_properties["requested_org_count"] = len(organization_ids)
filtering_properties["requested_missing_org_count"] = len(missing_orgs) if missing_orgs else None
- apply_usage_counter_metadata(
- org_reports,
- counter_report,
- caller="daily_report",
- date=period.start.strftime("%Y-%m-%d"),
- organization_ids=organization_ids,
- )
-
query_time_duration = (datetime.now() - query_time_start).total_seconds()
logger.info(f"Found {len(org_reports)} org reports. It took {query_time_duration} seconds.")
diff --git a/posthog/temporal/tests/usage_report/test_aggregator.py b/posthog/temporal/tests/usage_report/test_aggregator.py
index a136f06e87dc..bb578fb67cfe 100644
--- a/posthog/temporal/tests/usage_report/test_aggregator.py
+++ b/posthog/temporal/tests/usage_report/test_aggregator.py
@@ -21,7 +21,6 @@ from posthog.tasks.usage_report import (
InstanceMetadata,
OrgReport,
UsageReportCounters,
- apply_usage_counter_metadata,
iter_reports_with_usage_counter_metadata,
)
from posthog.temporal.tests.usage_report.test_aggregate_activity import _instance_metadata
@@ -208,7 +207,6 @@ def test_shadow_coverage_distinguishes_zero_from_failure(state: str) -> None:
with patch("posthoganalytics.get_feature_flag", return_value="both"):
ctx.usage_counter_plan = UsageCounterService().resolve_plan(
DayRange(start=ctx.period_start, end=ctx.period_end),
- caller="usage_reports_v2",
complete=ctx.report_completeness == "complete",
)
result = RunQueryToS3Result(query_name="usage_counters", s3_key="shadow.json", duration_ms=1)
@@ -238,7 +236,9 @@ def test_shadow_coverage_distinguishes_zero_from_failure(state: str) -> None:
assert counter_report.counts == {"teams_with_cdp_billable_invocations_in_period": [(1, 12)]}
org = _empty_org_report("org-a", cdp_billable_invocations_in_period=12)
org.teams["1"] = _empty_org_report("org-a", cdp_billable_invocations_in_period=12)
- apply_usage_counter_metadata({"org-a": org}, counter_report, caller="usage_reports_v2", date=ctx.date_str)
+ assert list(
+ iter_reports_with_usage_counter_metadata([org], counter_report, caller="usage_reports_v2", date=ctx.date_str)
+ ) == [org]
assert org.cdp_billable_invocations_in_period == 12
if state == "legacy":
assert org.usage_sources is None
@@ -251,8 +251,7 @@ def test_shadow_coverage_distinguishes_zero_from_failure(state: str) -> None:
)
[email protected]("streamed", [False, True])
-def test_counter_comparisons_follow_current_team_ownership(streamed: bool) -> None:
+def test_counter_comparisons_follow_current_team_ownership() -> None:
previous_owner = _empty_org_report("org-a")
previous_owner.teams["1"] = _empty_org_report("org-a")
current_owner = _empty_org_report("org-b", cdp_billable_invocations_in_period=100)
@@ -268,19 +267,11 @@ def test_counter_comparisons_follow_current_team_ownership(streamed: bool) -> No
)
with patch("posthog.tasks.usage_report.ph_scoped_capture") as capture:
- if streamed:
- assert list(
- iter_reports_with_usage_counter_metadata(
- iter((previous_owner, current_owner)), counter_report, caller="usage_reports_v2", date="2026-05-04"
- )
- ) == [previous_owner, current_owner]
- else:
- apply_usage_counter_metadata(
- {"org-a": previous_owner, "org-b": current_owner},
- counter_report,
- caller="daily_report",
- date="2026-05-04",
+ assert list(
+ iter_reports_with_usage_counter_metadata(
+ iter((previous_owner, current_owner)), counter_report, caller="usage_reports_v2", date="2026-05-04"
)
+ ) == [previous_owner, current_owner]
assert previous_owner.counter_comparisons == {"cdp_billable_invocations_in_period": {"legacy": 0, "realtime": 0}}
assert current_owner.counter_comparisons == {"cdp_billable_invocations_in_period": {"legacy": 100, "realtime": 100}}
@@ -329,7 +320,10 @@ def test_missing_organization_diagnostics_split_without_losing_comparisons() ->
},
)
with patch("posthog.tasks.usage_report.ph_scoped_capture") as scoped:
- apply_usage_counter_metadata({}, report, caller="daily_report", date="2026-05-04")
+ assert (
+ list(iter_reports_with_usage_counter_metadata([], report, caller="usage_reports_v2", date="2026-05-04"))
+ == []
+ )
calls = scoped.return_value.__enter__.return_value.call_args_list
assert len(calls) > 1
recovered: dict[str, dict[str, UsageCounterComparison]] = {}
diff --git a/posthog/temporal/tests/usage_report/test_parity.py b/posthog/temporal/tests/usage_report/test_parity.py
index ff82b9bf443f..0896d0d8c387 100644
--- a/posthog/temporal/tests/usage_report/test_parity.py
+++ b/posthog/temporal/tests/usage_report/test_parity.py
@@ -46,7 +46,7 @@ from posthog.temporal.usage_report.types import (
RunQueryToS3Result,
WorkflowContext,
)
-from posthog.usage_counters import RECORD_REALTIME_BLOCKERS, UsageCounter
+from posthog.usage_counters import UsageCounter
from posthog.utils import get_previous_day
from products.tasks.backend.facade.billing import SandboxComputeUsageByTeam
@@ -199,18 +199,17 @@ def _decode_temporal_chunks(s3: dict[str, bytes], chunk_keys: list[str]) -> dict
@pytest.mark.django_db(transaction=True)
- ("mode", "guarded"), [("legacy", True), ("both", True), ("realtime", True), ("realtime", False)]
-)
[email protected]("mode", ["legacy", "both", "realtime"])
def test_end_to_end_parity_celery_task_vs_temporal_activity(
activity_environment: Any,
monkeypatch: pytest.MonkeyPatch,
mode: str,
- guarded: bool,
) -> None:
"""Both production paths must produce the same per-org bytes for the
same `all_data` snapshot. Drift here is what billing's parity check
- will catch in production.
+ will catch in production. The Celery path always uses legacy counts,
+ so it ignores the counter mode. The Temporal path matches it in
+ `legacy` mode, and apart from its counter metadata in `both` mode.
Two orgs × three teams (org_a has two teams so the multi-team rollup
is exercised; org_b has one). The shared test DB may already contain
@@ -249,9 +248,6 @@ def test_end_to_end_parity_celery_task_vs_temporal_activity(
monkeypatch.setattr("posthoganalytics.feature_enabled", lambda *a, **kw: False)
monkeypatch.setattr("django.conf.settings.CLOUD_DEPLOYMENT", "US")
monkeypatch.setattr("django.conf.settings.USAGE_COUNTER_REALTIME_MODES", f"workflow-emails:{mode}")
- if not guarded:
- monkeypatch.delitem(RECORD_REALTIME_BLOCKERS, UsageCounter.WORKFLOW_EMAILS, raising=False)
- resolved_mode = "both" if mode == "realtime" and guarded else mode
captures_on_event_loop: list[str] = []
def check_capture_thread(*args: Any, **kwargs: Any) -> None:
@@ -279,13 +275,7 @@ def test_end_to_end_parity_celery_task_vs_temporal_activity(
monkeypatch.setattr("posthog.tasks.usage_report.get_ph_client", lambda *a, **kw: mock.MagicMock())
# Skip the heavy gather queries — both paths use this same `seeded`
# dict, just shaped differently for each entry point.
- monkeypatch.setattr(
- "posthog.tasks.usage_report._get_all_usage_data_as_team_rows",
- lambda begin, end, counter_report: {
- **seeded,
- **{field: dict(rows) for field, rows in counter_report.counts.items()},
- },
- )
+ monkeypatch.setattr("posthog.tasks.usage_report._get_all_usage_data_as_team_rows", lambda begin, end: dict(seeded))
for counter, query_name in (
(UsageCounter.ROWS_SYNCED, "get_teams_with_rows_synced_in_period"),
@@ -420,7 +410,6 @@ def test_end_to_end_parity_celery_task_vs_temporal_activity(
)
)
temporal_per_org = _decode_temporal_chunks(s3, result.chunk_keys)
- assert temporal_per_org.keys() == celery_per_org.keys()
# Both of our test orgs should have non-zero usage, so Celery should
# have queued them. Sanity-check that before comparing, otherwise a
@@ -428,18 +417,24 @@ def test_end_to_end_parity_celery_task_vs_temporal_activity(
assert str(org_a.id) in celery_per_org
assert str(org_b.id) in celery_per_org
- # Both paths skip zero-usage orgs; comparing on the Celery key set
- # keeps the assertion focused on the orgs billing actually receives.
- assert celery_per_org.keys() == temporal_per_org.keys()
- for org_id, celery_dict in celery_per_org.items():
- assert org_id in temporal_per_org, f"Celery emitted {org_id} but Temporal didn't"
- celery_json = json.dumps(celery_dict, sort_keys=True, default=str)
- temporal_json = json.dumps(temporal_per_org[org_id], sort_keys=True, default=str)
- assert celery_json == temporal_json, (
- f"Drift between Celery SQS payload and Temporal chunk for org {org_id}.\n"
- f"Celery (first 500 chars):\n{celery_json[:500]}\n"
- f"Temporal (first 500 chars):\n{temporal_json[:500]}"
- )
+ counter_metadata = ("usage_sources", "counter_comparisons")
+ assert not any(field in report for report in celery_per_org.values() for field in counter_metadata)
+ if mode != "realtime":
+ # Both paths skip zero-usage orgs; comparing on the Celery key set
+ # keeps the assertion focused on the orgs billing actually receives.
+ assert celery_per_org.keys() == temporal_per_org.keys()
+ for org_id, celery_dict in celery_per_org.items():
+ assert org_id in temporal_per_org, f"Celery emitted {org_id} but Temporal didn't"
+ temporal_dict = {
+ field: value for field, value in temporal_per_org[org_id].items() if field not in counter_metadata
+ }
+ celery_json = json.dumps(celery_dict, sort_keys=True, default=str)
+ temporal_json = json.dumps(temporal_dict, sort_keys=True, default=str)
+ assert celery_json == temporal_json, (
+ f"Drift between Celery SQS payload and Temporal chunk for org {org_id}.\n"
+ f"Celery (first 500 chars):\n{celery_json[:500]}\n"
+ f"Temporal (first 500 chars):\n{temporal_json[:500]}"
+ )
# Sanity-check the rollup math — org_a sums its two teams, org_b
# only has one. If this drifts, the rest of the parity numbers are
@@ -460,17 +455,17 @@ def test_end_to_end_parity_celery_task_vs_temporal_activity(
assert temporal_per_org[str(org_b.id)]["apm_tracing_bytes_in_period"] == 999_999
assert temporal_per_org[str(org_b.id)]["apm_tracing_spans_in_period"] == 5
assert temporal_per_org[str(org_b.id)]["apm_tracing_mb_in_period"] == 0
- assert temporal_per_org[str(org_a.id)]["workflow_emails_sent_in_period"] == (
- 16 if resolved_mode == "realtime" else 24
- )
+ assert temporal_per_org[str(org_a.id)]["workflow_emails_sent_in_period"] == (16 if mode == "realtime" else 24)
+ assert celery_per_org[str(org_a.id)]["workflow_emails_sent_in_period"] == 24
assert temporal_per_org[str(org_a.id)]["posthog_code_credits_used_in_period"] == 321 + 9
assert temporal_per_org[str(org_a.id)]["sandbox_compute_memory_mib_seconds_in_period"] == 2_000
assert temporal_per_org[str(org_a.id)]["logs_retention_mb_days_in_period"] == 4
- assert (str(idle_org.id) in temporal_per_org) == (resolved_mode == "realtime")
- assert (str(idle_org.id) in celery_per_org) == (resolved_mode == "realtime")
- assert scan.call_count == (0 if mode == "legacy" else 2)
+ assert (str(idle_org.id) in temporal_per_org) == (mode == "realtime")
+ assert str(idle_org.id) not in celery_per_org
+ assert scan.call_count == (0 if mode == "legacy" else 1)
assert captures_on_event_loop == []
- assert (str(legacy_only_org.id) in temporal_per_org) == (resolved_mode != "realtime")
+ assert (str(legacy_only_org.id) in temporal_per_org) == (mode != "realtime")
+ assert str(legacy_only_org.id) in celery_per_org
if mode != "legacy":
assert temporal_per_org[str(org_a.id)]["counter_comparisons"] == {
"workflow_emails_sent_in_period": {"legacy": 24, "realtime": 16}
@@ -478,16 +473,16 @@ def test_end_to_end_parity_celery_task_vs_temporal_activity(
assert temporal_per_org[str(org_b.id)]["counter_comparisons"] == {
"workflow_emails_sent_in_period": {"legacy": 0, "realtime": 0}
}
- assert temporal_per_org[str(org_a.id)]["usage_sources"]["workflow_emails_sent_in_period"] == resolved_mode
+ assert temporal_per_org[str(org_a.id)]["usage_sources"]["workflow_emails_sent_in_period"] == mode
missing_events = [
call.kwargs
for call in capture.call_args_list
if call.kwargs.get("event") == "usage counter shadow missing organizations"
]
- assert len(missing_events) == 2
- assert {event["properties"]["caller"] for event in missing_events} == {"daily_report", "usage_reports_v2"}
+ assert len(missing_events) == 1
+ assert missing_events[0]["properties"]["caller"] == "usage_reports_v2"
expected_missing = {deleted_org_id: {"workflow_emails_sent_in_period": {"legacy": 0, "realtime": 6}}}
- if resolved_mode == "both":
+ if mode == "both":
expected_missing[str(idle_org.id)] = {"workflow_emails_sent_in_period": {"legacy": 0, "realtime": 4}}
else:
expected_missing[str(legacy_only_org.id)] = {"workflow_emails_sent_in_period": {"legacy": 5, "realtime": 0}}
diff --git a/posthog/temporal/usage_report/activities.py b/posthog/temporal/usage_report/activities.py
index 4854c39dc429..09c73caa06bd 100644
--- a/posthog/temporal/usage_report/activities.py
+++ b/posthog/temporal/usage_report/activities.py
@@ -88,7 +88,6 @@ SQS_QUEUE_NAME = "usage_reports_v2"
async def plan_usage_counters(ctx: WorkflowContext) -> UsageCounterPlan:
return await sync_to_async(UsageCounterService().resolve_plan, thread_sensitive=False)(
DayRange(start=ctx.period_start, end=ctx.period_end),
- caller="usage_reports_v2",
complete=ctx.report_completeness == "complete",
)
diff --git a/posthog/usage_counters.py b/posthog/usage_counters.py
index 11212a5a9f5d..b7efec49927e 100644
--- a/posthog/usage_counters.py
+++ b/posthog/usage_counters.py
@@ -24,11 +24,6 @@ SHADOW_FAILURES = Counter("usage_counter_shadow_failures_total", "Usage counter
SHADOW_MISSING_ORGS = Gauge(
"usage_counter_shadow_missing_organizations", "Organizations with shadow usage but no report", ["caller"]
)
-REALTIME_BLOCKED = Counter(
- "usage_counter_realtime_blocked_total",
- "Realtime mode requests resolved to both for a producer discrepancy",
- ["counter"],
-)
class UsageCounter(StrEnum):
@@ -145,48 +140,6 @@ COUNTER_FLAG_NAMES = {
UsageCounter.WORKFLOW_SMS: "workflow-sms",
UsageCounter.WORKFLOW_INVOCATIONS: "workflow-invocations",
}
-_REPLAY_UNDERCOUNT = (
- "The replay pipeline marks a session as seen before it parses the first message. "
- "When that message fails, the session writes no usage record, even when later messages record."
-)
-_WORKFLOW_PUSH_UNDERCOUNT = (
- "Workflow invocation records from before push reporting omit push dispatches. "
- "The legacy count includes both fetch and push dispatches."
-)
-_EVENT_DATE_ATTRIBUTION = (
- "Event usage records use capture time; legacy queries use source event time. "
- "A cutover must prevent counting the same event under both dates or omitting it from both."
-)
-_FLAG_REQUEST_DATE_ATTRIBUTION = (
- "Flag usage records use Rust flush time; legacy billing events use the later Celery export time. "
- "A cutover must reconcile these dates to avoid missing or double-counting requests."
-)
-_CDP_DATE_ATTRIBUTION = (
- "CDP and workflow usage records and legacy app metrics use independent flush-time clocks. "
- "A cutover must reconcile dispatches across those dates to avoid missing or double-counting them."
-)
-_LOCAL_EVALUATION_UNDERCOUNT = (
- "Historical local-evaluation records omit requests handled by Django's feature-flag list endpoint. "
- "Validate both producers over a complete comparison window before using records as authoritative."
-)
-# Keep legacy totals authoritative until producer discrepancies are resolved or confirmed as intended billing behavior.
-RECORD_REALTIME_BLOCKERS = {
- UsageCounter.EVENTS: _EVENT_DATE_ATTRIBUTION,
- UsageCounter.ENHANCED_PERSON_EVENTS: _EVENT_DATE_ATTRIBUTION,
- UsageCounter.EXCEPTIONS: _EVENT_DATE_ATTRIBUTION,
- UsageCounter.CDP_INVOCATIONS: _CDP_DATE_ATTRIBUTION,
- UsageCounter.RECORDINGS: _REPLAY_UNDERCOUNT,
- UsageCounter.MOBILE_RECORDINGS: _REPLAY_UNDERCOUNT,
- UsageCounter.MOBILE_BILLABLE_RECORDINGS: _REPLAY_UNDERCOUNT,
- UsageCounter.WORKFLOW_EMAILS: _CDP_DATE_ATTRIBUTION,
- UsageCounter.WORKFLOW_PUSH: _CDP_DATE_ATTRIBUTION,
- UsageCounter.WORKFLOW_SMS: _CDP_DATE_ATTRIBUTION,
- UsageCounter.WORKFLOW_INVOCATIONS: f"{_WORKFLOW_PUSH_UNDERCOUNT} {_CDP_DATE_ATTRIBUTION}",
- UsageCounter.FEATURE_FLAG_REQUESTS: _FLAG_REQUEST_DATE_ATTRIBUTION,
- UsageCounter.FEATURE_FLAG_LOCAL_EVALUATION_REQUESTS: _LOCAL_EVALUATION_UNDERCOUNT,
- UsageCounter.SURVEY_RESPONSES: "Survey usage records include product-tour responses that legacy billing exempts.",
- UsageCounter.AI_EVENTS: "AI usage records omit the legacy exemptions for wallet-billed gateway and sponsored relay events.",
-}
def validate_usage_record_window(period: DayRange) -> None:
@@ -220,12 +173,7 @@ class UsageCounterPlan:
return [
counter
for counter, mode in self.modes.items()
- if mode != UsageCounterMode.REALTIME
- or self.complete
- or (
- counter in LEGACY_QUERY_NAMES
- and not (counter == UsageCounter.EXCEPTIONS and self.caller == "quota_limiting")
- )
+ if mode != UsageCounterMode.REALTIME or self.complete or counter in LEGACY_QUERY_NAMES
]
@@ -255,42 +203,13 @@ def record_shadow_failure(caller: UsageCounterCaller, stage: str) -> None:
logger.exception("usage_counter_shadow_metric_failed", caller=caller, stage=stage)
-def log_usage_counter_comparisons(report: UsageCounterReport, *, caller: UsageCounterCaller, date: str) -> None:
- if report.usage_sources is None:
- return
- try:
- logger.info("usage_counter_sources", caller=caller, date=date, usage_sources=report.usage_sources)
- for counter, rows in (report.counter_comparisons or {}).items():
- realtime = {team: sum(orgs.values()) for team, orgs in rows.realtime_by_team.items()}
- differing_teams = 0
- absolute_difference = 0
- for team in rows.legacy_by_team.keys() | realtime.keys():
- difference = abs(rows.legacy_by_team.get(team, 0) - realtime.get(team, 0))
- differing_teams += int(difference != 0)
- absolute_difference += difference
- logger.info(
- "usage_counter_comparison",
- caller=caller,
- date=date,
- counter=counter,
- source=report.usage_sources[counter],
- legacy=sum(rows.legacy_by_team.values()),
- realtime=sum(realtime.values()),
- differing_teams=differing_teams,
- absolute_difference=absolute_difference,
- )
- except Exception:
- logger.exception("usage_counter_comparison_logging_failed", caller=caller, date=date)
- record_shadow_failure(caller, "diagnostics")
-
-
_mode_cache: TTLCache[tuple[UsageCounter, str], UsageCounterMode] = TTLCache(
maxsize=128, ttl=60, timer=lambda: time.monotonic()
)
-@cached(_mode_cache, key=lambda counter, overrides, caller: (counter, overrides), lock=RLock())
-def _resolve_counter_mode(counter: UsageCounter, overrides: str, caller: UsageCounterCaller) -> UsageCounterMode:
+@cached(_mode_cache, key=lambda counter, overrides: (counter, overrides), lock=RLock())
+def _resolve_counter_mode(counter: UsageCounter, overrides: str) -> UsageCounterMode:
flag_name = COUNTER_FLAG_NAMES.get(counter)
if flag_name is None:
return UsageCounterMode.LEGACY
@@ -303,26 +222,18 @@ def _resolve_counter_mode(counter: UsageCounter, overrides: str, caller: UsageCo
mode = posthoganalytics.get_feature_flag(f"usage-counter-realtime-{flag_name}", "internal_billing_events")
except Exception:
logger.exception("usage_counter_flag_resolution_failed", counter=counter)
- record_shadow_failure(caller, "flags")
+ record_shadow_failure("usage_reports_v2", "flags")
return UsageCounterMode.LEGACY
if not isinstance(mode, str):
return UsageCounterMode.LEGACY
try:
- resolved = UsageCounterMode(mode)
+ return UsageCounterMode(mode)
except ValueError:
return UsageCounterMode.LEGACY
- if resolved == UsageCounterMode.REALTIME and counter in RECORD_REALTIME_BLOCKERS:
- logger.warning("usage_counter_realtime_blocked", counter=counter, reason=RECORD_REALTIME_BLOCKERS[counter])
- REALTIME_BLOCKED.labels(counter=counter.value).inc()
- return UsageCounterMode.BOTH
- return resolved
-def resolve_modes(caller: UsageCounterCaller) -> dict[UsageCounter, UsageCounterMode]:
- return {
- counter: _resolve_counter_mode(counter, settings.USAGE_COUNTER_REALTIME_MODES, caller)
- for counter in UsageCounter
- }
+def resolve_modes() -> dict[UsageCounter, UsageCounterMode]:
+ return {counter: _resolve_counter_mode(counter, settings.USAGE_COUNTER_REALTIME_MODES) for counter in UsageCounter}
class UsageCounterService:
@@ -398,14 +309,14 @@ class UsageCounterService:
self,
period: DayRange,
*,
- caller: UsageCounterCaller,
complete: bool,
counters: Collection[UsageCounter] | None = None,
) -> UsageCounterPlan:
- modes = resolve_modes(caller)
+ # Only usage reports v2 reads the flags. The daily report and quota limiting always use legacy queries.
+ modes = resolve_modes()
return UsageCounterPlan(
period=period,
- caller=caller,
+ caller="usage_reports_v2",
modes={counter: mode for counter, mode in modes.items() if counters is None or counter in counters},
complete=complete,
)
@@ -449,9 +360,7 @@ class UsageCounterService:
counts: UsageCounterCounts = {}
for counter in plan.legacy_counters:
mode = plan.modes[counter]
- requires_breakdown = counter in LEGACY_QUERY_NAMES and not (
- counter == UsageCounter.EXCEPTIONS and plan.caller == "quota_limiting"
- )
+ requires_breakdown = counter in LEGACY_QUERY_NAMES
self._check_cancelled()
try:
with self._record_query(LEGACY_QUERY_NAMES.get(counter, counter.value)):