: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
fix(billing): batch team queries and stream v2 reports (#114147)
Alex Maysb1ff665ba435
diff --git a/ee/billing/quota_limiting.py b/ee/billing/quota_limiting.pyindex 2f6241b86656..89ab3be44287 100644--- a/ee/billing/quota_limiting.py+++ b/ee/billing/quota_limiting.py@@ -8,7 +8,6 @@ from typing import Any, Optional, TypedDict, castfrom django.conf import settingsfrom django.db import close_old_connections, transaction-from django.db.models import Qfrom django.db.models.expressions import RawSQLfrom django.utils import timezone@@ -31,6 +30,7 @@ from posthog.tasks.usage_report import (get_self_driving_credits_used_in_period_for_org,get_signals_credited_refund_credits_for_org,get_teams_with_api_queries_metrics,+ iter_billable_teams,)from posthog.usage_counters import UsageCounter, UsageCounterService, log_usage_counter_comparisonsfrom posthog.utils import get_current_day@@ -1287,17 +1287,16 @@ def update_all_orgs_billing_quotas(progress_callback("queries_done", f"duration={queries_duration_s}s", f"query_count={len(all_data)}")teams: Sequence[Team] = list(- Team.objects.select_related("organization")- .exclude(Q(organization__for_internal_metrics=True) | Q(is_demo=True))- .only(- "id",- "api_token",- "organization__id",- "organization__usage",- "organization__created_at",- "organization__never_drop_data",- "organization__customer_trust_scores",- "organization__customer_id",+ iter_billable_teams(+ team_fields=("id", "api_token"),+ organization_fields=(+ "id",+ "usage",+ "created_at",+ "never_drop_data",+ "customer_trust_scores",+ "customer_id",+ ),))diff --git a/posthog/management/commands/start_temporal_worker.py b/posthog/management/commands/start_temporal_worker.pyindex c28ab4454a3e..167a0bff0652 100644--- a/posthog/management/commands/start_temporal_worker.py+++ b/posthog/management/commands/start_temporal_worker.py@@ -51,7 +51,7 @@ from posthog.temporal.common.interceptor import is_task_queue_supportedfrom posthog.temporal.common.liveness_tracker import LivenessInterceptor, get_liveness_trackerfrom posthog.temporal.common.logger import configure_logger, get_loggerfrom posthog.temporal.common.shutdown import ShutdownSignalListener-from posthog.temporal.common.worker import ManagedWorker, create_worker+from posthog.temporal.common.worker import ActivityWorkerConfig, ManagedWorker, create_workerfrom posthog.temporal.common.zombie_exit import ZombieActivityExitfrom posthog.temporal.data_modeling import (ACTIVITIES as DATA_MODELING_ACTIVITIES,@@ -139,6 +139,7 @@ from posthog.temporal.tests.utils.workflow import ()from posthog.temporal.usage_report import (ACTIVITIES as USAGE_REPORTS_ACTIVITIES,+ AGGREGATION_ACTIVITIES as USAGE_REPORTS_AGGREGATION_ACTIVITIES,WORKFLOWS as USAGE_REPORTS_WORKFLOWS,)from posthog.temporal.warehouse_sources_queue_partition_management import (@@ -650,6 +651,15 @@ for task_queue_name, workflows_for_queue, activities_for_queue in _task_queue_spWORKFLOWS_DICT = _workflowsACTIVITIES_DICT = _activities+ACTIVITY_WORKER_CONFIGS = {+ settings.BILLING_TASK_QUEUE: (+ ActivityWorkerConfig(+ task_queue=settings.USAGE_REPORT_AGGREGATION_TASK_QUEUE,+ activities=USAGE_REPORTS_AGGREGATION_ACTIVITIES,+ max_concurrent_activities=1,+ ),+ ),+}def workflows_include_data_import_syncs(workflows: collections.abc.Iterable[type]) -> bool:@@ -959,6 +969,7 @@ class Command(BaseCommand):),enable_combined_metrics_server=not disable_combined_metrics_server,enable_open_telemetry_plugin=enable_otel,+ activity_worker_configs=ACTIVITY_WORKER_CONFIGS.get(task_queue, ()),))diff --git a/posthog/management/commands/test/test_start_temporal_worker.py b/posthog/management/commands/test/test_start_temporal_worker.pyindex 8d2fa6553312..776a7fa0259d 100644--- a/posthog/management/commands/test/test_start_temporal_worker.py+++ b/posthog/management/commands/test/test_start_temporal_worker.py@@ -6,6 +6,7 @@ from django.conf import settingsfrom posthog.management.commands.start_temporal_worker import (ACTIVITIES_DICT,+ ACTIVITY_WORKER_CONFIGS,AI_WORKFLOWS,ALERT_AI_QUEUE_ACTIVITIES,DATA_SYNC_WORKFLOWS,@@ -16,6 +17,7 @@ from posthog.management.commands.start_temporal_worker import (_task_queue_specs,workflows_include_data_import_syncs,)+from posthog.temporal.usage_report.activities import aggregate_and_chunk_org_reportsfrom products.alerts_platform.backend.facade.temporal import (DELIVERY_ACTIVITIES,@@ -40,6 +42,16 @@ class _NotADataSyncWorkflow:pass+def test_billing_registers_aggregation_with_separate_capacity() -> None:+ (aggregation_worker,) = ACTIVITY_WORKER_CONFIGS[settings.BILLING_TASK_QUEUE]+ assert aggregation_worker.task_queue == settings.USAGE_REPORT_AGGREGATION_TASK_QUEUE+ assert aggregation_worker.task_queue != settings.BILLING_TASK_QUEUE+ assert aggregation_worker.max_concurrent_activities == 1+ assert aggregation_worker.activities == [aggregate_and_chunk_org_reports]+ # A workflow may have scheduled aggregation before the queue change deployed.+ assert aggregate_and_chunk_org_reports in ACTIVITIES_DICT[settings.BILLING_TASK_QUEUE]++@pytest.mark.parametrize("task_queue,expected_workflows,expected_activities",[diff --git a/posthog/settings/temporal.py b/posthog/settings/temporal.pyindex add2b4fe8eac..13428bdccf87 100644--- a/posthog/settings/temporal.py+++ b/posthog/settings/temporal.py@@ -346,6 +346,8 @@ TASKS_DISPATCHER_MAX_DISPATCH_AGE_SECONDS = get_from_env(STAMPHOG_TASK_QUEUE = _set_temporal_task_queue("stamphog-task-queue")TEST_TASK_QUEUE = _set_temporal_task_queue("test-task-queue")BILLING_TASK_QUEUE = _set_temporal_task_queue("billing-task-queue")+# Keep aggregation separate even when local development combines the other queues.+USAGE_REPORT_AGGREGATION_TASK_QUEUE = f"{BILLING_TASK_QUEUE}-usage-report-aggregation"VIDEO_EXPORT_TASK_QUEUE = _set_temporal_task_queue("video-export-task-queue")ANALYTICS_PLATFORM_TASK_QUEUE = _set_temporal_task_queue("analytics-platform-task-queue")# Keep the smoke fleets separate in local development as well as deployed environments.diff --git a/posthog/tasks/test/test_usage_report.py b/posthog/tasks/test/test_usage_report.pyindex 4335aeff4d09..3f87336ede5f 100644--- a/posthog/tasks/test/test_usage_report.py+++ b/posthog/tasks/test/test_usage_report.py@@ -4,7 +4,7 @@ import base64import dataclassesfrom datetime import UTC, datetime, timedeltafrom typing import Any, cast-from uuid import uuid4+from uuid import UUID, uuid4import pytestimport time_machine@@ -5665,20 +5665,56 @@ class TestSendUsageNoLicense(APIBaseTest):mock_post.assert_not_called()- def test_get_teams_for_usage_reports_only_fields(self) -> None:- teams = _get_teams_for_usage_reports()- team: Team = teams[0]- # these fields are included in the query, so shouldn't require additional queries+class TestBillableTeams(TestCase):+ @parameterized.expand([(1, None), (2, None), (10, []), (2, [str(UUID(int=3))])])+ def test_get_teams_for_usage_reports(self, batch_size: int, organization_ids: list[str] | None) -> None:+ org_last = Organization.objects.create(id=UUID(int=3), name="Last")+ org_first = Organization.objects.create(id=UUID(int=1), name="First")+ org_demo = Organization.objects.create(id=UUID(int=2), name="Demo only")+ org_internal = Organization.objects.create(id=UUID(int=4), name="Internal", for_internal_metrics=True)+ first_team = Team.objects.create(organization=org_first, name="First project")+ last_team = Team.objects.create(organization=org_last, name="Last project")+ second_team = Team.objects.create(organization=org_first, name="Second project")+ Team.objects.create(organization=org_demo, is_demo=True)+ Team.objects.create(organization=org_first, is_demo=True)+ Team.objects.create(organization=org_internal)++ org_count = 1 if organization_ids else 3+ expected_queries = 2 * ((org_count + batch_size - 1) // batch_size) + int(org_count % batch_size == 0)+ with (+ patch("posthog.tasks.usage_report.BILLING_ORGANIZATION_BATCH_SIZE", batch_size),+ self.assertNumQueries(expected_queries),+ ):+ teams = list(_get_teams_for_usage_reports(organization_ids=organization_ids))++ expected_teams = [last_team] if organization_ids else [first_team, second_team, last_team]+ assert [team.id for team in teams] == [team.id for team in expected_teams]with self.assertNumQueries(0):- _ = team.id- _ = team.organization.id- _ = team.organization.name- _ = team.organization.created_at+ for team, expected in zip(teams, expected_teams):+ assert team.name == expected.name+ assert team.organization.id == expected.organization.id+ assert team.organization.name == expected.organization.name+ assert team.organization.created_at == expected.organization.created_at+ if not organization_ids:+ assert teams[0].organization is teams[1].organization- # This field is not included in the original team query, so should require an additional querywith self.assertNumQueries(1):- _ = team.organization.for_internal_metrics+ assert teams[0].organization.for_internal_metrics is False++ def test_team_moved_to_a_later_organization_during_the_scan_is_reported_once(self) -> None:+ org_first = Organization.objects.create(id=UUID(int=1), name="First")+ org_last = Organization.objects.create(id=UUID(int=2), name="Last")+ moved_team = Team.objects.create(organization=org_first, name="Moved project")++ with patch("posthog.tasks.usage_report.BILLING_ORGANIZATION_BATCH_SIZE", 1):+ teams = _get_teams_for_usage_reports()+ first = next(teams)+ Team.objects.filter(id=moved_team.id).update(organization=org_last)+ rest = list(teams)++ assert [team.id for team in [first, *rest]] == [moved_team.id]+ assert first.organization.id == org_first.id@time_machine.travel("2021-10-10T23:01:00Z", tick=False)diff --git a/posthog/tasks/usage_report.py b/posthog/tasks/usage_report.pyindex 41ff64373eee..9a334dccaaac 100644--- a/posthog/tasks/usage_report.py+++ b/posthog/tasks/usage_report.py@@ -99,6 +99,8 @@ from products.warehouse_sources.backend.facade.types import ExternalDataSchemaStlogger = structlog.get_logger(__name__)logging.getLogger(__name__).setLevel(logging.INFO)+BILLING_ORGANIZATION_BATCH_SIZE = 1_000+GATEWAY_SPONSORED_TRACE_EVENTS_PER_TRACE = 20GATEWAY_SPONSORED_EVALUATIONS_PER_TRACE = 20# Gateway generations are emitted after provider completion. The default gateway@@ -3243,17 +3245,47 @@ def _get_all_usage_data_as_team_rows(return all_data-def _get_teams_for_usage_reports() -> Sequence[Team]:- return list(- Team.objects.select_related("organization")- .exclude(Q(organization__for_internal_metrics=True) | Q(is_demo=True))- .only(- "id",- "name",- "organization__id",- "organization__name",- "organization__created_at",+def iter_billable_teams(+ *,+ team_fields: Sequence[str],+ organization_fields: Sequence[str],+ organization_ids: Sequence[str] | None = None,+) -> Iterator[Team]:+ # Page organizations to avoid repeating their wide columns on every team or retaining them all.+ # Keyset pagination bounds the organization query even when PgBouncer disables server-side cursors.+ organizations = Organization.objects.exclude(for_internal_metrics=True).only(*organization_fields).order_by("id")+ if organization_ids:+ organizations = organizations.filter(id__in=organization_ids)++ # Each page is a separate read, so a project moved to a later organization during the scan+ # comes back in that organization's page. Yield each team once, or its usage is reported twice.+ yielded_team_ids: set[int] = set()+ page = organizations+ while batch := list(page[:BILLING_ORGANIZATION_BATCH_SIZE]):+ organizations_by_id = {organization.id: organization for organization in batch}+ # Streaming reports require all of an organization's teams to be contiguous.+ teams = (+ Team.objects.filter(organization_id__in=organizations_by_id)+ .exclude(is_demo=True)+ .only(*team_fields, "organization_id")+ .order_by("organization_id", "id"))+ for team in teams.iterator(chunk_size=2_000):+ if team.id in yielded_team_ids:+ continue+ yielded_team_ids.add(team.id)+ team.organization = organizations_by_id[team.organization_id]+ yield team+ if len(batch) < BILLING_ORGANIZATION_BATCH_SIZE:+ return+ page = organizations.filter(id__gt=batch[-1].id)+++def _get_teams_for_usage_reports(*, organization_ids: Sequence[str] | None = None) -> Iterator[Team]:+ return iter_billable_teams(+ team_fields=("id", "name"),+ organization_fields=("id", "name", "created_at"),+ organization_ids=organization_ids,)@@ -3527,21 +3559,17 @@ def _get_all_org_reports(*, period: DayRange, counter_report: UsageCounterReportall_data = _get_all_usage_data_as_team_rows(period.start, period.end, counter_report)- logger.info("Querying all teams")-- teams = _get_teams_for_usage_reports()-- logger.info("Querying all teams complete", teams_count=len(teams))-org_reports: dict[str, OrgReport] = {}+ teams_count = 0logger.info("Generating org reports")- for team in teams:+ for team in _get_teams_for_usage_reports():+ teams_count += 1team_report = _get_team_report(all_data, team)_add_team_report_to_org_reports(org_reports, team, team_report, period.start)- logger.info("Generating org reports complete", org_reports_count=len(org_reports))+ logger.info("Generating org reports complete", teams_count=teams_count, org_reports_count=len(org_reports))return org_reportsdiff --git a/posthog/temporal/common/worker.py b/posthog/temporal/common/worker.pyindex 0ab36ab7ed00..74a22a0b51fc 100644--- a/posthog/temporal/common/worker.py+++ b/posthog/temporal/common/worker.py@@ -1,5 +1,6 @@import socketimport typing+import asyncioimport datetime as dtimport itertoolsimport collections.abc@@ -20,6 +21,7 @@ from temporalio.worker import (WorkerTuner,)+from posthog.dataclasses import frozenfrom posthog.temporal.ai_observability.eval_reports.metrics import (EVAL_REPORTS_LATENCY_HISTOGRAM_BUCKETS,EVAL_REPORTS_LATENCY_HISTOGRAM_METRICS,@@ -200,23 +202,37 @@ ALL_INTERCEPTOR_CLASSES = []+@frozen+class ActivityWorkerConfig:+ task_queue: str+ activities: collections.abc.Sequence[typing.Callable]+ max_concurrent_activities: int++@dataclass(frozen=False)class ManagedWorker:"""A Temporal worker bundled with its associated resources for unified lifecycle management."""worker: Workermetrics_server: CombinedMetricsServer | None = None+ activity_workers: tuple[Worker, ...] = ()async def run(self) -> None:if self.metrics_server:await self.metrics_server.start()- await self.worker.run()+ if not self.activity_workers:+ await self.worker.run()+ return+ # A failed poller must stop its siblings so the pod restarts with all queues served.+ async with asyncio.TaskGroup() as group:+ for worker in (self.worker, *self.activity_workers):+ group.create_task(worker.run())def is_shutdown(self) -> bool:- return self.worker.is_shutdown+ return all(worker.is_shutdown for worker in (self.worker, *self.activity_workers))async def shutdown(self) -> None:- await self.worker.shutdown()+ await asyncio.gather(*(worker.shutdown() for worker in (self.worker, *self.activity_workers)))if self.metrics_server:await self.metrics_server.stop()shutdown_asyncify_executor()@@ -269,6 +285,7 @@ async def create_worker(activity_ramp_throttle: dt.timedelta | None = None,enable_combined_metrics_server: bool = True,enable_open_telemetry_plugin: bool = False,+ activity_worker_configs: collections.abc.Sequence[ActivityWorkerConfig] = (),) -> ManagedWorker:"""Connect to Temporal server and return a ManagedWorker containing the Worker and metrics server.@@ -302,6 +319,8 @@ async def create_worker(enable_combined_metrics_server: Whether to start the combined metrics server. Defaults to True.Set to False to disable the metrics server (useful when it causes GIL contention issues).enable_open_telemetry_plugin: Whether to trace execution with OTel spans. Requires initialize_otel.+ activity_worker_configs: Additional activity queues with independent fixed concurrency limits,+ sharing this process, client, metrics server, and shutdown lifecycle."""metrics_server: CombinedMetricsServer | None = None@@ -547,7 +566,25 @@ async def create_worker(**poller_kwargs,)- return ManagedWorker(worker=worker, metrics_server=metrics_server)+ activity_workers = tuple(+ Worker(+ client,+ task_queue=config.task_queue,+ activities=config.activities,+ max_concurrent_activities=config.max_concurrent_activities,+ activity_executor=ThreadPoolExecutor(max_workers=config.max_concurrent_activities),+ graceful_shutdown_timeout=graceful_shutdown_timeout or dt.timedelta(minutes=5),+ interceptors=[+ interceptor()+ for interceptor in ALL_INTERCEPTOR_CLASSES+ if is_task_queue_supported(config.task_queue, interceptor)+ ],+ max_heartbeat_throttle_interval=dt.timedelta(seconds=5),+ **poller_kwargs,+ )+ for config in activity_worker_configs+ )+ return ManagedWorker(worker=worker, metrics_server=metrics_server, activity_workers=activity_workers)def get_free_port() -> int:diff --git a/posthog/temporal/tests/common/test_worker.py b/posthog/temporal/tests/common/test_worker.pynew file mode 100644index 000000000000..840aa84e2a8d--- /dev/null+++ b/posthog/temporal/tests/common/test_worker.py@@ -0,0 +1,77 @@+import asyncio+from functools import partial++import pytest+from unittest.mock import AsyncMock, Mock, patch++from temporalio.worker import Worker++from posthog.temporal.common.worker import ManagedWorker+++async def test_shutdown_drains_both_queues_before_stopping_shared_resources():+ workers = [Mock(spec=Worker, is_shutdown=False) for _ in range(2)]+ shutdown_started = [asyncio.Event(), asyncio.Event()]+ drained = [asyncio.Event(), asyncio.Event()]+ release = [asyncio.Event(), asyncio.Event()]++ async def shutdown(index):+ shutdown_started[index].set()+ await release[index].wait()+ workers[index].is_shutdown = True+ drained[index].set()++ workers[0].shutdown = AsyncMock(side_effect=partial(shutdown, 0))+ workers[1].shutdown = AsyncMock(side_effect=partial(shutdown, 1))+ metrics = Mock(start=AsyncMock(), stop=AsyncMock())+ managed = ManagedWorker(worker=workers[0], activity_workers=(workers[1],), metrics_server=metrics)++ with patch("posthog.temporal.common.worker.shutdown_asyncify_executor") as shutdown_executor:+ task = asyncio.create_task(managed.shutdown())+ try:+ async with asyncio.timeout(10):+ await asyncio.gather(*(event.wait() for event in shutdown_started))+ release[0].set()+ await drained[0].wait()+ assert not managed.is_shutdown()+ metrics.stop.assert_not_awaited()+ shutdown_executor.assert_not_called()+ release[1].set()+ await task+ finally:+ for event in release:+ event.set()+ await task+ assert managed.is_shutdown()+ metrics.stop.assert_awaited_once()+ shutdown_executor.assert_called_once()++[email protected]("failed_worker", [0, 1])+async def test_worker_failure_stops_the_other_queue(failed_worker):+ workers = [Mock(spec=Worker), Mock(spec=Worker)]+ started = [asyncio.Event(), asyncio.Event()]+ stopped = [asyncio.Event(), asyncio.Event()]++ async def run(index):+ started[index].set()+ try:+ await started[1 - index].wait()+ if index == failed_worker:+ raise RuntimeError("poller failed")+ await asyncio.Event().wait()+ finally:+ stopped[index].set()++ workers[0].run = AsyncMock(side_effect=partial(run, 0))+ workers[1].run = AsyncMock(side_effect=partial(run, 1))+ managed = ManagedWorker(worker=workers[0], activity_workers=(workers[1],))++ async with asyncio.timeout(10):+ with pytest.raises(ExceptionGroup, match="unhandled errors in a TaskGroup") as exc:+ await managed.run()+ assert len(exc.value.exceptions) == 1+ assert str(exc.value.exceptions[0]) == "poller failed"+ assert all(event.is_set() for event in stopped)diff --git a/posthog/temporal/tests/common/test_worker_pollers.py b/posthog/temporal/tests/common/test_worker_pollers.pyindex 5dfaef380773..dfa7e970d052 100644--- a/posthog/temporal/tests/common/test_worker_pollers.py+++ b/posthog/temporal/tests/common/test_worker_pollers.py@@ -5,7 +5,7 @@ from django.test import override_settingsfrom temporalio.worker import PollerBehaviorAutoscaling-from posthog.temporal.common.worker import build_poller_autoscaling, create_worker+from posthog.temporal.common.worker import ActivityWorkerConfig, build_poller_autoscaling, create_worker@pytest.mark.parametrize(@@ -61,7 +61,7 @@ async def test_create_worker_passes_poller_behavior_only_when_configured():with (override_settings(**poller_settings),- mock.patch("posthog.temporal.common.worker.connect", new=mock.AsyncMock()),+ mock.patch("posthog.temporal.common.worker.connect", new=mock.AsyncMock()) as connect,mock.patch("posthog.temporal.common.worker.Runtime"),mock.patch("posthog.temporal.common.worker.configure_asyncify_executor"),mock.patch("posthog.temporal.common.worker.WorkerTuner"),@@ -77,11 +77,20 @@ async def test_create_worker_passes_poller_behavior_only_when_configured(activities=[],enable_combined_metrics_server=False,target_memory_usage=target_memory_usage,+ activity_worker_configs=[+ ActivityWorkerConfig(task_queue="aggregation-queue", activities=[], max_concurrent_activities=1)+ ],)- kwargs = worker_cls.call_args.kwargs+ primary, aggregation = worker_cls.call_args_list+ kwargs = primary.kwargspoller_kwargs = {k: v for k, v in kwargs.items() if k.endswith("poller_behavior")}assert poller_kwargs == expected_kwargs+ assert aggregation.args == primary.args+ assert aggregation.kwargs["task_queue"] == "aggregation-queue"+ assert aggregation.kwargs["max_concurrent_activities"] == 1+ assert "tuner" not in aggregation.kwargs+ connect.assert_awaited_once()@pytest.mark.asynciodiff --git a/posthog/temporal/tests/usage_report/test_aggregate_activity.py b/posthog/temporal/tests/usage_report/test_aggregate_activity.pyindex ee782ddd8cd4..41c2cfd1fc99 100644--- a/posthog/temporal/tests/usage_report/test_aggregate_activity.py+++ b/posthog/temporal/tests/usage_report/test_aggregate_activity.py@@ -11,6 +11,8 @@ aggregate, and write back as in production.import gzipimport jsonimport uuid+import asyncio+from threading import Eventfrom typing import Anyimport pytest@@ -282,6 +284,46 @@ async def test_aggregate_writes_chunks_and_manifest(minio_workflow_ctx: Workflowassert by_org[str(org_a.id)]["teams"][str(team_a.id)]["event_count_in_period"] == 100[email protected]_db(transaction=True)+async def test_aggregate_completes_while_thread_sensitive_executor_is_busy(+ minio_workflow_ctx: WorkflowContext, activity_environment+) -> None:+ org_a = await _make_org("Org A")+ org_b = await _make_org("Org B")+ team_a = await _make_team(org_a, "Team A")+ team_b = await _make_team(org_b, "Team B")+ ctx = minio_workflow_ctx.model_copy(update={"organization_ids": [str(org_a.id), str(org_b.id)]})+ query_results = _seed_query_results(ctx, team_a.id, team_b.id)++ started = asyncio.Event()+ release = Event()+ loop = asyncio.get_running_loop()++ def occupy_shared_thread() -> None:+ loop.call_soon_threadsafe(started.set)+ release.wait()++ blocker = asyncio.create_task(sync_to_async(occupy_shared_thread)())+ try:+ await asyncio.wait_for(started.wait(), timeout=10)+ with patch(+ "posthog.temporal.usage_report.activities.get_instance_metadata",+ return_value=_instance_metadata(),+ ):+ result = await asyncio.wait_for(+ activity_environment.run(+ aggregate_and_chunk_org_reports,+ AggregateInputs(ctx=ctx, query_results=query_results),+ ),+ timeout=30,+ )+ assert result.total_orgs == 2+ finally:+ release.set()+ await blocker++@pytest.mark.django_db(transaction=True)@pytest.mark.asyncioasync def test_aggregate_chunks_into_batches_of_ten_thousand(diff --git a/posthog/temporal/tests/usage_report/test_aggregator.py b/posthog/temporal/tests/usage_report/test_aggregator.pyindex b016d4be0937..8f330ace0815 100644--- a/posthog/temporal/tests/usage_report/test_aggregator.py+++ b/posthog/temporal/tests/usage_report/test_aggregator.py@@ -2,10 +2,11 @@These cover the building blocks the aggregation activity composes:`load_all_data`, `iter_chunk_lines`, `build_manifest`,-`filter_org_reports`, `filter_orgs_with_usage`, `sort_org_reports`.+`write_org_report_chunks`.No Django / Temporal / S3 required."""+import gzipimport jsonimport weakrefimport dataclasses@@ -23,15 +24,14 @@ from posthog.tasks.usage_report import (apply_usage_counter_metadata,iter_reports_with_usage_counter_metadata,)+from posthog.temporal.tests.usage_report.test_aggregate_activity import _instance_metadatafrom posthog.temporal.usage_report.aggregator import (add_pre_sandbox_compute_patch_defaults,build_manifest,- filter_org_reports,- filter_orgs_with_usage,iter_chunk_lines,load_all_data,load_usage_counter_report,- sort_org_reports,+ write_org_report_chunks,)from posthog.temporal.usage_report.types import (AggregateInputs,@@ -388,38 +388,7 @@ def test_build_manifest_returns_typed_manifest() -> None:assert manifest.total_orgs_with_usage == 678-# ---- filter_org_reports / sort_org_reports ----------------------------------def test_filter_org_reports_no_filter_returns_all() -> None:- reports = cast(dict[str, OrgReport], {"a": _FakeOrgReport("a"), "b": _FakeOrgReport("b")})- assert filter_org_reports(reports, None) is reports- assert filter_org_reports(reports, []) is reports # empty list also no-ops---def test_filter_org_reports_with_ids_keeps_only_requested() -> None:- reports = cast(- dict[str, OrgReport],- {"a": _FakeOrgReport("a"), "b": _FakeOrgReport("b"), "c": _FakeOrgReport("c")},- )- out = filter_org_reports(reports, ["a", "c", "missing"])- assert set(out.keys()) == {"a", "c"}---def test_sort_org_reports_orders_by_organization_id() -> None:- reports = cast(- dict[str, OrgReport],- {- "z": _FakeOrgReport("z"),- "a": _FakeOrgReport("a"),- "m": _FakeOrgReport("m"),- },- )- out = sort_org_reports(reports)- assert [r.organization_id for r in out] == ["a", "m", "z"]---# ---- filter_orgs_with_usage ----------------------------------------------+# ---- write_org_report_chunks ---------------------------------------------def _empty_org_report(organization_id: str, **overrides: Any) -> OrgReport:@@ -442,21 +411,77 @@ def _empty_org_report(organization_id: str, **overrides: Any) -> OrgReport:)-def test_filter_orgs_with_usage_keeps_only_orgs_with_billable_counters() -> None:- reports = {- "with-events": _empty_org_report("with-events", event_count_in_period=1),- "with-recordings": _empty_org_report("with-recordings", recording_count_in_period=1),- "idle": _empty_org_report("idle"),- "shadow-only": _empty_org_report(- "shadow-only",- usage_sources={"cdp_billable_invocations_in_period": "both"},- counter_comparisons={"cdp_billable_invocations_in_period": {"legacy": 0, "realtime": 50}},- ),- # Counters not in `has_non_zero_usage` (dashboard counts, query- # bytes read, etc.) must not keep an org in.- "non-billable-only": _empty_org_report("non-billable-only", dashboard_count=10, query_app_bytes_read=5_000_000),- }[email protected]("active_orgs", [0, 4, 5])+def test_chunks_stream_reports_and_preserve_counts(active_orgs: int) -> None:+ references: list[weakref.ReferenceType[OrgReport]] = []+ objects: dict[str, bytes] = {}- out = filter_orgs_with_usage(reports)+ def reports() -> Iterator[OrgReport]:+ for index in range(active_orgs + 1):+ report = _empty_org_report(+ str(index),+ event_count_in_period=int(index < active_orgs),+ dashboard_count=10,+ usage_sources={"cdp_billable_invocations_in_period": "both"},+ counter_comparisons={"cdp_billable_invocations_in_period": {"legacy": 0, "realtime": 50}},+ )+ references.append(weakref.ref(report))+ yield report++ def write(key: str, content: str | bytes, **kwargs: Any) -> None:+ objects[key] = content.encode() if isinstance(content, str) else content+ assert sum(ref() is not None for ref in references) <= 1++ with patch("posthog.storage.object_storage.write", side_effect=write):+ result = write_org_report_chunks(+ _ctx(), reports(), _instance_metadata(), chunk_size=2, version=2, region="US", check_cancelled=lambda: None+ )++ assert result.total_orgs == active_orgs + 1+ assert result.total_orgs_with_usage == active_orgs+ assert len(result.chunk_keys) == (active_orgs + 1) // 2+ chunks = [[json.loads(line) for line in gzip.decompress(objects[key]).splitlines()] for key in result.chunk_keys]+ assert [row["organization_id"] for chunk in chunks for row in chunk] == [str(i) for i in range(active_orgs)]+ assert all(0 < len(chunk) <= 2 for chunk in chunks)+ manifest = json.loads(objects[result.manifest_key])+ assert manifest["total_orgs"] == result.total_orgs+ assert manifest["total_orgs_with_usage"] == result.total_orgs_with_usage+ assert manifest["chunk_keys"] == result.chunk_keys+++ "failure, report_count",+ [+ ("upload", 3),+ # The third report trips the check between reports.+ ("cancel", 3),+ # Both reports fit in the first chunk, so only the check before the manifest can trip.+ ("cancel", 2),+ ],+)+def test_failed_chunk_run_does_not_publish_manifest(failure: str, report_count: int) -> None:+ written: list[str] = []++ def write(key: str, content: str | bytes, **kwargs: Any) -> None:+ if failure == "upload" and written:+ raise OSError("upload failed")+ written.append(key)- assert set(out.keys()) == {"with-events", "with-recordings"}+ def check_cancelled() -> None:+ if failure == "cancel" and written:+ raise RuntimeError("cancelled")++ with (+ patch("posthog.storage.object_storage.write", side_effect=write),+ pytest.raises((OSError, RuntimeError)),+ ):+ write_org_report_chunks(+ _ctx(),+ (_empty_org_report(str(i), event_count_in_period=1) for i in range(report_count)),+ _instance_metadata(),+ chunk_size=2,+ version=2,+ region="US",+ check_cancelled=check_cancelled,+ )+ assert not any(key.endswith("manifest.json") for key in written)diff --git a/posthog/temporal/tests/usage_report/test_parity.py b/posthog/temporal/tests/usage_report/test_parity.pyindex 2ab8111e0c91..c9a854e030e6 100644--- a/posthog/temporal/tests/usage_report/test_parity.py+++ b/posthog/temporal/tests/usage_report/test_parity.py@@ -220,7 +220,6 @@ def test_end_to_end_parity_celery_task_vs_temporal_activity(org_a = Organization.objects.create(name="E2E Parity A")org_b = Organization.objects.create(name="E2E Parity B")team_a1 = Team.objects.create(organization=org_a, name="A1")- team_a2 = Team.objects.create(organization=org_a, name="A2")team_b = Team.objects.create(organization=org_b, name="B")idle_org = Organization.objects.create(name="Idle")idle_team = Team.objects.create(organization=idle_org, name="Idle")@@ -229,11 +228,17 @@ def test_end_to_end_parity_celery_task_vs_temporal_activity(deleted_org_id = str(uuid4())excluded_org_id = str(uuid4())organization_ids = [str(org_a.id), str(org_b.id), str(idle_org.id), str(legacy_only_org.id), deleted_org_id]+ team_a2 = Team.objects.create(organization=org_a, name="A2")+ demo_team = Team.objects.create(organization=org_b, name="Demo", is_demo=True)+ internal_org = Organization.objects.create(name="Internal", for_internal_metrics=True)+ internal_team = Team.objects.create(organization=internal_org, name="Internal")celery_at = datetime(2026, 5, 5, 0, 0, 0, tzinfo=UTC)period = get_previous_day(celery_at)seeded = _seed_all_data(team_a1.id, team_a2.id, team_b.id)seeded["teams_with_workflow_emails_sent_in_period"] = {team_a1.id: 11, team_a2.id: 13, legacy_only_team.id: 5}+ seeded["teams_with_event_count_in_period"].update({demo_team.id: 999, internal_team.id: 999})+ monkeypatch.setattr("posthog.tasks.usage_report.BILLING_ORGANIZATION_BATCH_SIZE", 1)s3 = _install_in_memory_object_storage(monkeypatch)sqs_messages = _install_fake_sqs_producer(monkeypatch)@@ -414,6 +419,7 @@ 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@@ -491,18 +497,13 @@ def test_end_to_end_parity_celery_task_vs_temporal_activity(@pytest.mark.django_db(transaction=True)-def test_temporal_build_org_reports_does_not_run_per_org_membership_queries() -> None:- """The Temporal-local `aggregator.build_org_reports` must fetch- organization membership counts in bulk. The legacy Celery facade still- runs one `OrganizationMembership.count()` per organization inside its- team loop — that's the cost we lifted out of the- `aggregate-and-chunk-org-reports` activity by routing it through the- aggregator's own builder instead of the shared one.+def test_temporal_org_reports_do_not_run_per_org_membership_queries() -> None:+ """The Temporal `aggregator.iter_org_reports` must fetch organization+ membership counts in bulk. The legacy Celery facade still runs one+ `OrganizationMembership.count()` per organization inside its team loop,+ and the `aggregate-and-chunk-org-reports` activity must not."""- from posthog.temporal.usage_report.aggregator import (- build_org_reports as temporal_build_org_reports,- get_org_user_counts,- )+ from posthog.temporal.usage_report.aggregator import get_org_user_counts, iter_org_reports# Create a meaningful number of fresh orgs/teams so the per-org N+1# would have clear daylight from the bulk-fetch path. Without this,@@ -514,18 +515,24 @@ def test_temporal_build_org_reports_does_not_run_per_org_membership_queries() ->fresh_orgs.append(org)period_start = datetime(2026, 5, 4, 0, 0, 0, tzinfo=UTC)+ ctx = WorkflowContext(+ run_id="membership-queries",+ period_start=period_start,+ period_end=datetime(2026, 5, 4, 23, 59, 59, 999999, tzinfo=UTC),+ date_str="2026-05-04",+ )all_data: dict[str, dict[int, int]] = {key: {} for key in _all_destination_keys()}with CaptureQueriesContext(connection) as captured:org_user_counts = get_org_user_counts()- temporal_build_org_reports(all_data, period_start, org_user_counts)+ list(iter_org_reports(all_data, ctx, org_user_counts))# The Temporal path runs ~2 queries (teams + bulk memberships)# regardless of org count. The legacy Celery path runs 1 + N. Cap# well below `1 + N` so any per-org N+1 here blows the test, while# leaving slack for harmless query-count drift (savepoints etc.).assert len(captured.captured_queries) <= 5, (- f"Temporal build_org_reports issued {len(captured.captured_queries)} "+ f"Temporal iter_org_reports issued {len(captured.captured_queries)} "f"queries — with {len(fresh_orgs)} fresh orgs this looks like a "f"per-org N+1, which dominates wall-clock for the aggregation activity.")diff --git a/posthog/temporal/tests/usage_report/test_query_activity.py b/posthog/temporal/tests/usage_report/test_query_activity.pyindex 9649a9a984e9..3cdddaaa04a4 100644--- a/posthog/temporal/tests/usage_report/test_query_activity.py+++ b/posthog/temporal/tests/usage_report/test_query_activity.py@@ -22,6 +22,7 @@ from temporalio.testing import ActivityEnvironmentfrom posthog.storage import object_storagefrom posthog.sync import database_sync_to_async_pool+from posthog.temporal.tests.usage_report.test_aggregator import _ctxfrom posthog.temporal.tests.usage_report.test_parity import _install_in_memory_object_storagefrom posthog.temporal.usage_report import storagefrom posthog.temporal.usage_report.activities import (@@ -398,6 +399,43 @@ async def test_counter_activity_reuses_successful_queries_on_retry(}+async def test_query_persists_while_thread_sensitive_executor_is_busy(+ activity_environment: ActivityEnvironment,+) -> None:+ started = asyncio.Event()+ release = Event()+ loop = asyncio.get_running_loop()++ def occupy_shared_thread() -> None:+ loop.call_soon_threadsafe(started.set)+ release.wait()++ def query(begin: datetime, end: datetime) -> list[tuple[int, int]]:+ return [(1, 17)]++ blocker = asyncio.create_task(sync_to_async(occupy_shared_thread)())+ try:+ await asyncio.wait_for(started.wait(), timeout=10)+ with (+ patch.dict(+ "posthog.temporal.usage_report.activities.QUERY_INDEX",+ {"test_query": QuerySpec(name="test_query", fn=query)},+ ),+ patch("posthog.storage.object_storage.write") as write,+ ):+ result = await asyncio.wait_for(+ activity_environment.run(run_query_to_s3, RunQueryToS3Inputs(ctx=_ctx(), query_name="test_query")),+ timeout=10,+ )+ assert result.query_name == "test_query"+ assert write.call_args.args[0] == result.s3_key+ assert json.loads(write.call_args.args[1]) == [[1, 17]]+ finally:+ release.set()+ await blocker++@pytest.mark.asyncioasync def test_run_query_to_s3_calls_fn_with_period_and_writes_to_s3(minio_workflow_ctx: WorkflowContext, activity_environmentdiff --git a/posthog/temporal/tests/usage_report/test_workflow.py b/posthog/temporal/tests/usage_report/test_workflow.pyindex f5ccd8e7e448..5c2dc8cbf6c3 100644--- a/posthog/temporal/tests/usage_report/test_workflow.py+++ b/posthog/temporal/tests/usage_report/test_workflow.py@@ -14,15 +14,24 @@ from datetime import UTC, datetime, timedeltaimport pytestfrom unittest.mock import patch+from django.test import override_settings+import temporalio.workerfrom parameterized import parameterizedfrom temporalio import activity, workflow+from temporalio.api.enums.v1 import PendingActivityStatefrom temporalio.client import WorkflowFailureErrorfrom temporalio.contrib.pydantic import pydantic_data_converterfrom temporalio.exceptions import ApplicationErrorfrom temporalio.testing import WorkflowEnvironmentfrom temporalio.worker import Replayer, Worker+from posthog.temporal.quota_limiting.run_quota_limiting import (+ QuotaLimitingResult,+ RunQuotaLimitingAllOrgsInputs,+ RunQuotaLimitingInputs,+ RunQuotaLimitingWorkflow,+)from posthog.temporal.usage_report.activities import plan_usage_countersfrom posthog.temporal.usage_report.queries import QUERIESfrom posthog.temporal.usage_report.types import (@@ -36,6 +45,7 @@ from posthog.temporal.usage_report.types import (WorkflowContext,)from posthog.temporal.usage_report.workflow import (+ AGGREGATION_QUEUE_PATCH_ID,PARALLEL_COUNTER_QUERIES_PATCH_ID,QUERY_CONCURRENCY,SANDBOX_COMPUTE_QUERY_NAME,@@ -82,9 +92,18 @@ def test_build_context_reports_full_day_at_offset(@pytest.mark.asyncio-async def test_workflow_rejects_negative_day_offset() -> None:- # Without the guard, a manual-trigger typo like day_offset=-1 reports a- # future empty day and marks it "complete" for billing.+ "inputs, invalid_field",+ [+ # A negative offset reports a future empty day and marks it "complete" for billing.+ (RunUsageReportsInputs(day_offset=-1), "day_offset"),+ # A malformed id fails aggregation only after every gather query has run.+ (RunUsageReportsInputs(organization_ids=["not-a-uuid"]), "organization_ids"),+ ],+)+async def test_workflow_rejects_invalid_inputs_before_running_queries(+ inputs: RunUsageReportsInputs, invalid_field: str+) -> None:ran_queries: list[str] = []@activity.defn(name="run-usage-report-query")@@ -103,7 +122,7 @@ async def test_workflow_rejects_negative_day_offset() -> None:with pytest.raises(WorkflowFailureError) as exc_info:await env.client.execute_workflow(RunUsageReportsWorkflow.run,- RunUsageReportsInputs(day_offset=-1),+ inputs,id=str(uuid.uuid4()),task_queue=worker.task_queue,)@@ -111,7 +130,7 @@ async def test_workflow_rejects_negative_day_offset() -> None:cause = exc_info.value.causeassert isinstance(cause, ApplicationError)assert cause.non_retryable- assert "day_offset" in str(cause)+ assert invalid_field in str(cause)assert ran_queries == []@@ -130,6 +149,8 @@ async def test_workflow_rejects_negative_day_offset() -> None:"concurrency","serial_counters","counter_query_failure",+ "pre_aggregation_queue",+ "aggregation_queue",],)async def test_workflow_runs_query_then_aggregate(report_behavior: str, caplog: pytest.LogCaptureFixture) -> None:@@ -145,6 +166,10 @@ async def test_workflow_runs_query_then_aggregate(report_behavior: str, caplog:query_started = asyncio.Event()counter_started = asyncio.Event()release_queries = asyncio.Event()+ aggregation_started = asyncio.Event()+ release_aggregation = asyncio.Event()+ active_aggregations = 0+ max_active_aggregations = 0starts: asyncio.Queue[str] = asyncio.Queue()releases: dict[str, asyncio.Event] = {}active_queries: set[str] = set()@@ -153,6 +178,7 @@ async def test_workflow_runs_query_then_aggregate(report_behavior: str, caplog:max_active_counters = 0fails = report_behavior in {"activity_failure", "query_failure", "pre_patch_query_failure", "counter_query_failure"}pre_patch = report_behavior.startswith("pre_patch")+ legacy_aggregation_queue = pre_patch or report_behavior == "pre_aggregation_queue"parallel_counters = not pre_patch and report_behavior != "serial_counters"expected_counter_report = RunQueryToS3Result(query_name="usage_counters", s3_key="queries/counters.json", duration_ms=1@@ -228,23 +254,54 @@ async def test_workflow_runs_query_then_aggregate(report_behavior: str, caplog:@activity.defn(name="aggregate-and-chunk-org-reports")async def aggregate_mock(inputs: AggregateInputs) -> AggregateResult:+ nonlocal active_aggregations, max_active_aggregationsaggregate_payloads.append(inputs)aggregated_with.append([r.query_name for r in inputs.query_results])- return expected_aggregate+ active_aggregations += 1+ max_active_aggregations = max(max_active_aggregations, active_aggregations)+ aggregation_started.set()+ try:+ if report_behavior == "aggregation_queue":+ await release_aggregation.wait()+ return expected_aggregate+ finally:+ active_aggregations -= 1++ @activity.defn(name="run-quota-limiting-all-orgs")+ async def quota_mock(inputs: RunQuotaLimitingAllOrgsInputs) -> QuotaLimitingResult:+ return QuotaLimitingResult(orgs_processed=1)@activity.defn(name="usage-reports-enqueue-pointer-message")async def pointer_mock(inputs: EnqueuePointerInputs) -> None:pointer_payloads.append(inputs)task_queue = str(uuid.uuid4())+ aggregation_queue = f"{task_queue}-aggregation"workflow_id = str(uuid.uuid4())- async with await WorkflowEnvironment.start_time_skipping(data_converter=pydantic_data_converter) as env:- async with Worker(- env.client,- task_queue=task_queue,- workflows=[RunUsageReportsWorkflow],- activities=[query_mock, aggregate_mock, pointer_mock, plan_mock, fetch_mock, legacy_counter_mock],- workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),+ with override_settings(USAGE_REPORT_AGGREGATION_TASK_QUEUE=aggregation_queue):+ async with (+ await WorkflowEnvironment.start_time_skipping(data_converter=pydantic_data_converter) as env,+ Worker(+ env.client,+ task_queue=aggregation_queue,+ activities=[aggregate_mock],+ max_concurrent_activities=1,+ ),+ Worker(+ env.client,+ task_queue=task_queue,+ workflows=[RunUsageReportsWorkflow, RunQuotaLimitingWorkflow],+ activities=[+ query_mock,+ aggregate_mock,+ pointer_mock,+ plan_mock,+ fetch_mock,+ legacy_counter_mock,+ quota_mock,+ ],+ workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),+ ),):patched = workflow.patchedwith (@@ -254,10 +311,11 @@ async def test_workflow_runs_query_then_aggregate(report_behavior: str, caplog:Falseif (pre_patch and name == USAGE_COUNTER_SERVICE_PATCH_ID)or (report_behavior == "serial_counters" and name == PARALLEL_COUNTER_QUERIES_PATCH_ID)+ or (legacy_aggregation_queue and name == AGGREGATION_QUEUE_PATCH_ID)else patched(name)),)- if pre_patch or report_behavior == "serial_counters"+ if legacy_aggregation_queue or report_behavior == "serial_counters"else nullcontext()):try:@@ -279,39 +337,78 @@ async def test_workflow_runs_query_then_aggregate(report_behavior: str, caplog:]for name in batch:releases[name].set()+ if report_behavior == "aggregation_queue":+ await asyncio.wait_for(aggregation_started.wait(), timeout=10)+ second = await env.client.start_workflow(+ RunUsageReportsWorkflow.run,+ RunUsageReportsInputs(day_offset=0),+ id=str(uuid.uuid4()),+ task_queue=task_queue,+ execution_timeout=timedelta(minutes=2),+ )+ async with asyncio.timeout(30):+ async for event in second.fetch_history_events(wait_new_event=True):+ if (+ event.activity_task_scheduled_event_attributes.activity_type.name+ == "aggregate-and-chunk-org-reports"+ ):+ break+ quota = await env.client.execute_workflow(+ RunQuotaLimitingWorkflow.run,+ RunQuotaLimitingInputs(),+ id=str(uuid.uuid4()),+ task_queue=task_queue,+ execution_timeout=timedelta(minutes=2),+ )+ assert quota.orgs_processed == 1+ pending = (await second.describe()).raw_description.pending_activities+ assert len(pending) == 1+ assert pending[0].state == PendingActivityState.PENDING_ACTIVITY_STATE_SCHEDULED+ assert len(aggregate_payloads) == 1+ release_aggregation.set()+ assert await second.result() == expected_aggregate.model_dump()+ assert max_active_aggregations == 1result = await asyncio.wait_for(run, timeout=30 if fails else 120)finally:release_queries.set()+ release_aggregation.set()for release in releases.values():release.set()- # Verify the per-query activity scheduling carried `summary=spec.name`- # so the Temporal UI shows which query is running.- handle = env.client.get_workflow_handle(workflow_id)- history = await handle.fetch_history()- scheduled_summaries: dict[str, str] = {}- async for event in handle.fetch_history_events():- attrs = event.activity_task_scheduled_event_attributes- if attrs.activity_type.name not in {"run-usage-report-query", "run-legacy-usage-counter"}:- continue- assert event.user_metadata.HasField("summary"), f"activity {attrs.activity_id} scheduled without a summary"- (decoded_summary,) = pydantic_data_converter.payload_converter.from_payloads(- [event.user_metadata.summary], [str]- )- scheduled_summaries[attrs.activity_id] = decoded_summary+ # Each query activity carries a readable summary in the Temporal UI.+ handle = env.client.get_workflow_handle(workflow_id)+ history = await handle.fetch_history()+ scheduled_summaries: dict[str, str] = {}+ async for event in handle.fetch_history_events():+ attrs = event.activity_task_scheduled_event_attributes+ if attrs.activity_type.name == "aggregate-and-chunk-org-reports":+ assert attrs.task_queue.name == (task_queue if legacy_aggregation_queue else aggregation_queue)+ if attrs.activity_type.name not in {"run-usage-report-query", "run-legacy-usage-counter"}:+ continue+ assert event.user_metadata.HasField("summary"), (+ f"activity {attrs.activity_id} scheduled without a summary"+ )+ (decoded_summary,) = pydantic_data_converter.payload_converter.from_payloads(+ [event.user_metadata.summary], [str]+ )+ scheduled_summaries[attrs.activity_id] = decoded_summarycounter_names = plans[0].query_names if plans else set()expected_names = [spec.name for spec in QUERIES if spec.name not in counter_names]- await Replayer(- workflows=[RunUsageReportsWorkflow],- data_converter=pydantic_data_converter,- workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),- ).replay_workflow(history)+ with override_settings(USAGE_REPORT_AGGREGATION_TASK_QUEUE=aggregation_queue):+ await Replayer(+ workflows=[RunUsageReportsWorkflow],+ data_converter=pydantic_data_converter,+ workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),+ ).replay_workflow(history)if fails:assert set(seen_query_names) <= set(expected_names)assert aggregated_with == []assert pointer_payloads == []return+ if report_behavior == "aggregation_queue":+ assert len(aggregate_payloads) == len(pointer_payloads) == 2+ return# Queries run with bounded concurrency, so completion order is not# deterministic — only assert the set. Result ordering (passed to thediff --git a/posthog/temporal/usage_report/__init__.py b/posthog/temporal/usage_report/__init__.pyindex 4095f5d14ad3..ca4d51ecd969 100644--- a/posthog/temporal/usage_report/__init__.py+++ b/posthog/temporal/usage_report/__init__.py@@ -13,12 +13,15 @@ WORKFLOWS = [RunUsageReportsWorkflow,]+AGGREGATION_ACTIVITIES = [aggregate_and_chunk_org_reports]+ACTIVITIES = [plan_usage_counters,fetch_usage_counter_report,run_legacy_usage_counter,run_query_to_s3,- aggregate_and_chunk_org_reports,+ # Existing workflow histories can still have aggregation scheduled on the billing queue.+ *AGGREGATION_ACTIVITIES,enqueue_pointer_message,cleanup_intermediates,]diff --git a/posthog/temporal/usage_report/activities.py b/posthog/temporal/usage_report/activities.pyindex 041ad5398691..8ec83bae329c 100644--- a/posthog/temporal/usage_report/activities.py+++ b/posthog/temporal/usage_report/activities.py@@ -10,8 +10,8 @@ import jsonimport timeimport asyncioimport dataclasses+from concurrent.futures import ThreadPoolExecutorfrom functools import partial-from itertools import batchedfrom threading import Eventfrom typing import Any@@ -21,21 +21,17 @@ import structlogfrom asgiref.sync import sync_to_asyncfrom temporalio import activity-from posthog.sync import database_sync_to_async, database_sync_to_async_pool-from posthog.tasks.usage_report import apply_usage_counter_metadata, get_instance_metadata+from posthog.sync import database_sync_to_async_pool+from posthog.tasks.usage_report import get_instance_metadata, iter_reports_with_usage_counter_metadatafrom posthog.temporal.common.heartbeat import Heartbeaterfrom posthog.temporal.common.metrics import ExecutionTimeRecorderfrom posthog.temporal.usage_report.aggregator import (add_pre_sandbox_compute_patch_defaults,- build_manifest,- build_org_reports,- filter_org_reports,- filter_orgs_with_usage,get_org_user_counts,- iter_chunk_lines,+ iter_org_reports,load_all_data,load_usage_counter_report,- sort_org_reports,+ write_org_report_chunks,)from posthog.temporal.usage_report.metrics import (USAGE_REPORTS_AGGREGATE_LATENCY,@@ -48,15 +44,12 @@ from posthog.temporal.usage_report.metrics import (from posthog.temporal.usage_report.queries import QUERY_INDEXfrom posthog.temporal.usage_report.storage import (bucket,- chunk_key,chunks_prefix,delete_keys,load_legacy_counter_counts,- manifest_key,queries_key,run_legacy_counter_query,write_json,- write_jsonl_chunk_gzip,)from posthog.temporal.usage_report.types import (AggregateInputs,@@ -76,6 +69,12 @@ logger = structlog.get_logger(__name__)CHUNK_SIZE_ORGS = 50_000SQS_POINTER_VERSION = 2+# One aggregation runs at a time in each worker process. Each run holds every query result and+# all membership counts in memory, so parallel runs multiply peak memory. The executor is also+# separate from the shared thread that quota limiting uses.+# Keep this cap while pre-patch workflows can still aggregate on the main billing queue.+_AGGREGATION_EXECUTOR = ThreadPoolExecutor(max_workers=1, thread_name_prefix="usage-report-aggregation")+# Separate SQS queue for v2 messages so the existing per-org `usage_reports`# stream and the new pointer stream don't clash while both flows run side by# side. Billing opts in by reading from this queue once it's ready.@@ -215,7 +214,7 @@ async def run_query_to_s3(inputs: RunQueryToS3Inputs) -> RunQueryToS3Result:duration_ms = int((time.monotonic() - started) * 1000)key = queries_key(inputs.ctx, inputs.query_name)- await sync_to_async(write_json)(key, result)+ await sync_to_async(write_json, thread_sensitive=False)(key, result)return RunQueryToS3Result(query_name=inputs.query_name,@@ -237,82 +236,54 @@ async def aggregate_and_chunk_org_reports(inputs: AggregateInputs) -> AggregateRUSAGE_REPORTS_AGGREGATE_LATENCY,description="Aggregate per-query S3 results into org-report chunks.",):- all_data = await sync_to_async(load_all_data)(inputs.query_results)- add_pre_sandbox_compute_patch_defaults(all_data, inputs.query_results)- counter_report = await sync_to_async(load_usage_counter_report)(inputs)- all_data.update({field: dict(rows) for field, rows in counter_report.counts.items()})-- @database_sync_to_async- def aggregate_per_org() -> dict[str, Any]:- # Bulk-fetch membership counts once instead of letting the org- # builder issue a Postgres count() per organization. See- # `aggregator.build_org_reports` for the rationale.+ cancelled = Event()++ def check_cancelled() -> None:+ if cancelled.is_set() or activity.is_cancelled():+ raise asyncio.CancelledError()++ @database_sync_to_async_pool(executor=_AGGREGATION_EXECUTOR)+ def aggregate() -> AggregateResult:+ check_cancelled()+ all_data = load_all_data(inputs.query_results)+ add_pre_sandbox_compute_patch_defaults(all_data, inputs.query_results)+ check_cancelled()+ counter_report = load_usage_counter_report(inputs)+ all_data.update({field: dict(rows) for field, rows in counter_report.counts.items()})+ check_cancelled()org_user_counts = get_org_user_counts()- org_reports = build_org_reports(all_data, inputs.ctx.period_start, org_user_counts)- org_reports = filter_org_reports(org_reports, inputs.ctx.organization_ids)- return org_reports-- org_reports = await aggregate_per_org()-- await sync_to_async(apply_usage_counter_metadata)(- org_reports,- counter_report,- caller="usage_reports_v2",- date=inputs.ctx.date_str,- organization_ids=inputs.ctx.organization_ids,- )+ instance_metadata = get_instance_metadata(+ DayRange(start=inputs.ctx.period_start, end=inputs.ctx.period_end)+ )- instance_metadata = await database_sync_to_async(get_instance_metadata)(- DayRange(start=inputs.ctx.period_start, end=inputs.ctx.period_end)- )+ # TODO(usage-reports-v2): re-enable PostHog product-analytics+ # `capture_report` per organization once the billing path is validated.+ # That call updates organization group properties (member/project/dashboard+ # counts) used by customer.io segmentation and emits the+ # "organization usage report" event consumed for internal analytics.++ return write_org_report_chunks(+ inputs.ctx,+ iter_reports_with_usage_counter_metadata(+ iter_org_reports(all_data, inputs.ctx, org_user_counts),+ counter_report,+ caller="usage_reports_v2",+ date=inputs.ctx.date_str,+ organization_ids=inputs.ctx.organization_ids,+ ),+ instance_metadata,+ chunk_size=CHUNK_SIZE_ORGS,+ version=SQS_POINTER_VERSION,+ region=get_instance_region() or "",+ check_cancelled=check_cancelled,+ )- # TODO(usage-reports-v2): re-enable PostHog product-analytics- # `capture_report` per organization once the billing path is validated.- # That call updates organization group properties (member/project/dashboard- # counts) used by customer.io segmentation and emits the- # "organization usage report" event consumed for internal analytics.-- total_orgs = len(org_reports)- orgs_with_usage = filter_orgs_with_usage(org_reports)- total_orgs_with_usage = len(orgs_with_usage)-- sorted_reports = sort_org_reports(orgs_with_usage)- batches = list(enumerate([list(batch) for batch in batched(sorted_reports, CHUNK_SIZE_ORGS, strict=False)]))- chunk_keys: list[str] = [chunk_key(inputs.ctx, index) for index, _ in batches]-- # Each chunk is an independent S3 object, so fan the encode+gzip+PUT- # out across the thread pool. `thread_sensitive=False` opts out of- # the shared-thread default so the PUTs run concurrently — boto3- # releases the GIL during the network call, so they genuinely- # overlap on the wire. Using `asyncio.TaskGroup` (over- # `asyncio.gather`) means a single failed upload doesn't cancel- # in-flight peer uploads mid-PUT; the group waits for every- # started task to finish or fail before re-raising, so Temporal- # retries from a clean state.- def write_chunk(key: str, batch: list[Any]) -> None:- write_jsonl_chunk_gzip(key, iter_chunk_lines(batch, instance_metadata))-- async with asyncio.TaskGroup() as tg:- for index, batch in batches:- tg.create_task(sync_to_async(write_chunk, thread_sensitive=False)(chunk_keys[index], batch))-- manifest = build_manifest(- inputs.ctx,- chunk_keys=chunk_keys,- total_orgs=total_orgs,- total_orgs_with_usage=total_orgs_with_usage,- region=get_instance_region() or "",- version=SQS_POINTER_VERSION,- )- m_key = manifest_key(inputs.ctx)- await sync_to_async(write_json)(m_key, manifest.model_dump(mode="json"))-- return AggregateResult(- chunk_keys=chunk_keys,- manifest_key=m_key,- total_orgs=total_orgs,- total_orgs_with_usage=total_orgs_with_usage,- )+ try:+ return await aggregate()+ except asyncio.CancelledError:+ # Cancelling an await cannot stop a running executor thread.+ cancelled.set()+ raise@activity.defn(name="usage-reports-enqueue-pointer-message")@@ -358,7 +329,7 @@ async def enqueue_pointer_message(inputs: EnqueuePointerInputs) -> None:if inputs.ctx.workflow_started_at is not None:pointer["workflow_started_at"] = inputs.ctx.workflow_started_at.isoformat()- @sync_to_async+ @sync_to_async(thread_sensitive=False)def send() -> None:from ee.sqs.SQSProducer import get_sqs_producer@@ -397,4 +368,4 @@ async def cleanup_intermediates(inputs: CleanupInputs) -> int:"""Delete the per-query S3 intermediates. Chunks and manifest are keptso the billing consumer can read them after the SQS pointer arrives."""- return await sync_to_async(delete_keys)(inputs.query_keys)+ return await sync_to_async(delete_keys, thread_sensitive=False)(inputs.query_keys)diff --git a/posthog/temporal/usage_report/aggregator.py b/posthog/temporal/usage_report/aggregator.pyindex 331d25bfeb89..18c4c7628b53 100644--- a/posthog/temporal/usage_report/aggregator.py+++ b/posthog/temporal/usage_report/aggregator.py@@ -3,16 +3,16 @@Most of this module is pure logic — turning S3-backed query results into thelegacy `all_data` shape, fanning multi-key queries back out into theirdestination keys, and shaping per-organization JSONL lines for the chunked-output. The Temporal-local replacement for the legacy `build_org_reports`-also lives here so the activity can drive aggregation without touching the-Celery code path; that one bulk-fetches `OrganizationMembership` counts so-the per-org `count()` N+1 in the legacy helper never fires for Temporal.-Activities import from here.+output. `iter_org_reports` streams one report per organization without+touching the Celery code path. It reads `OrganizationMembership` counts from+one bulk query, so the per-org `count()` N+1 in the legacy helper never fires+for Temporal. Activities import from here."""import dataclasses-from collections.abc import Iterable, Iterator+from collections.abc import Callable, Iterable, Iteratorfrom datetime import datetime+from itertools import chain, groupby, islicefrom typing import Anyfrom django.conf import settings@@ -32,8 +32,21 @@ from posthog.tasks.usage_report import (serialize_full_org_report,)from posthog.temporal.usage_report.queries import QUERY_INDEX-from posthog.temporal.usage_report.storage import bucket, read_json-from posthog.temporal.usage_report.types import AggregateInputs, Manifest, RunQueryToS3Result, WorkflowContext+from posthog.temporal.usage_report.storage import (+ bucket,+ chunk_key,+ manifest_key,+ read_json,+ write_json,+ write_jsonl_chunk_gzip,+)+from posthog.temporal.usage_report.types import (+ AggregateInputs,+ AggregateResult,+ Manifest,+ RunQueryToS3Result,+ WorkflowContext,+)from posthog.usage_counters import UsageCounterReport_SANDBOX_COMPUTE_QUERY_NAME = "sandbox_compute_usage"@@ -87,8 +100,8 @@ def iter_chunk_lines() -> Iterator[dict[str, Any]]:"""Yield the JSONL line dict billing consumes for each org report.- Filtering by `has_non_zero_usage` happens upstream in the activity, so- everything yielded here is expected to have usage.+ `write_org_report_chunks` drops reports without usage before this step,+ so every report here has usage."""for org_report in org_reports:report_dict = serialize_full_org_report(org_report, instance_metadata)@@ -98,18 +111,6 @@ def iter_chunk_lines(}-def filter_orgs_with_usage(org_reports: dict[str, OrgReport]) -> dict[str, OrgReport]:- """Drop org reports with no billable usage before serialization. Reuses- the legacy `has_non_zero_usage` directly on `OrgReport`s — every field- it checks lives on `UsageReportCounters`, the base class shared by- `OrgReport` and `FullUsageReport`, so we skip the- `dataclasses.asdict(FullUsageReport)` round-trip the legacy path forces.- Skipping that on the >99% of orgs without usage is the dominant CPU- win in the aggregation activity.- """- return {oid: report for oid, report in org_reports.items() if has_non_zero_usage(report)}--def build_manifest(ctx: WorkflowContext,chunk_keys: list[str],@@ -137,22 +138,6 @@ def build_manifest()-def filter_org_reports(- org_reports: dict[str, OrgReport],- organization_ids: list[str] | None,-) -> dict[str, OrgReport]:- """Apply the optional `organization_ids` filter from workflow inputs."""- if not organization_ids:- return org_reports- wanted = set(organization_ids)- return {oid: report for oid, report in org_reports.items() if oid in wanted}---def sort_org_reports(org_reports: dict[str, OrgReport]) -> list[OrgReport]:- """Deterministic ordering so chunk contents are stable across retries."""- return sorted(org_reports.values(), key=lambda r: r.organization_id)--def get_org_user_counts() -> dict[str, int]:"""Bulk membership count per organization, keyed by `str(org_id)`.@@ -175,26 +160,6 @@ def get_org_user_counts() -> dict[str, int]:}-def build_org_reports(- all_data: dict[str, Any],- period_start: datetime,- org_user_counts: dict[str, int],-) -> dict[str, OrgReport]:- """Temporal-local replacement for `posthog.tasks.usage_report.build_org_reports`.-- Same shape and semantics as the legacy facade, but takes a pre-fetched- `org_user_counts` dict instead of issuing one Postgres `count()` per- organization. The legacy facade is intentionally left untouched so the- Celery flow's behavior is preserved — the parity tests pin both paths- against each other.- """- org_reports: dict[str, OrgReport] = {}- for team in _get_teams_for_usage_reports():- team_report = _get_team_report(all_data, team)- _add_team_report_to_org_reports(org_reports, team, team_report, period_start, org_user_counts)- return org_reports--def _add_team_report_to_org_reports(org_reports: dict[str, OrgReport],team: Team,@@ -231,3 +196,66 @@ def _add_team_report_to_org_reports(field.name,getattr(org_report, field.name) + getattr(team_report, field.name),)+++def iter_org_reports(+ all_data: dict[str, dict[int, int]],+ ctx: WorkflowContext,+ org_user_counts: dict[str, int],+) -> Iterator[OrgReport]:+ teams = _get_teams_for_usage_reports(organization_ids=ctx.organization_ids)+ for organization_id, org_teams in groupby(teams, key=lambda team: team.organization_id):+ org_id = str(organization_id)+ org_reports: dict[str, OrgReport] = {}+ for team in org_teams:+ team_report = _get_team_report(all_data, team)+ _add_team_report_to_org_reports(org_reports, team, team_report, ctx.period_start, org_user_counts)+ yield org_reports[org_id]+++def write_org_report_chunks(+ ctx: WorkflowContext,+ org_reports: Iterable[OrgReport],+ instance_metadata: InstanceMetadata,+ *,+ chunk_size: int,+ version: int,+ region: str,+ check_cancelled: Callable[[], None],+) -> AggregateResult:+ total_orgs = 0+ total_orgs_with_usage = 0++ def reports_with_usage() -> Iterator[OrgReport]:+ nonlocal total_orgs, total_orgs_with_usage+ for report in org_reports:+ check_cancelled()+ total_orgs += 1+ if has_non_zero_usage(report):+ total_orgs_with_usage += 1+ yield report++ lines = iter_chunk_lines(reports_with_usage(), instance_metadata)+ chunk_keys: list[str] = []+ while (first_line := next(lines, None)) is not None:+ key = chunk_key(ctx, len(chunk_keys))+ write_jsonl_chunk_gzip(key, chain((first_line,), islice(lines, chunk_size - 1)))+ chunk_keys.append(key)++ check_cancelled()+ manifest = build_manifest(+ ctx,+ chunk_keys=chunk_keys,+ total_orgs=total_orgs,+ total_orgs_with_usage=total_orgs_with_usage,+ region=region,+ version=version,+ )+ m_key = manifest_key(ctx)+ write_json(m_key, manifest.model_dump(mode="json"))+ return AggregateResult(+ chunk_keys=chunk_keys,+ manifest_key=m_key,+ total_orgs=total_orgs,+ total_orgs_with_usage=total_orgs_with_usage,+ )diff --git a/posthog/temporal/usage_report/workflow.py b/posthog/temporal/usage_report/workflow.pyindex 24d93714a4f4..ff1b2450f103 100644--- a/posthog/temporal/usage_report/workflow.py+++ b/posthog/temporal/usage_report/workflow.py@@ -15,9 +15,12 @@ remains in production until billing migrates to consume the S3 layout."""import json+import uuidimport asynciofrom datetime import UTC, datetime, time, timedelta+from django.conf import settings+from temporalio import common, workflowfrom temporalio.exceptions import ApplicationError@@ -52,6 +55,7 @@ SANDBOX_COMPUTE_QUERY_PATCH_ID = "usage-report-sandbox-compute-query-2026-08"SANDBOX_COMPUTE_QUERY_NAME = "sandbox_compute_usage"USAGE_COUNTER_SERVICE_PATCH_ID = "usage-report-counter-service-2026-09"PARALLEL_COUNTER_QUERIES_PATCH_ID = "usage-report-parallel-counter-queries-2026-10"+AGGREGATION_QUEUE_PATCH_ID = "usage-report-aggregation-queue-2026-10"def _queries_for_sandbox_compute_patch(patch_applied: bool) -> list[QuerySpec]:@@ -86,6 +90,14 @@ def build_context(inputs: RunUsageReportsInputs, run_id: str, now: datetime) ->)+def _is_uuid(value: str) -> bool:+ try:+ uuid.UUID(value)+ except ValueError:+ return False+ return True++@workflow.defn(name="run-usage-reports")class RunUsageReportsWorkflow(PostHogWorkflow):@staticmethod@@ -101,6 +113,12 @@ class RunUsageReportsWorkflow(PostHogWorkflow):# non_retryable so the schedule's retry policy doesn't re-run a# validation error.raise ApplicationError(f"day_offset must be >= 0, got {inputs.day_offset}", non_retryable=True)+ invalid_organization_ids = [value for value in inputs.organization_ids or [] if not _is_uuid(value)]+ if invalid_organization_ids:+ # Aggregation reads organization_ids only after every gather query has run.+ raise ApplicationError(+ f"organization_ids must be UUIDs, got {invalid_organization_ids}", non_retryable=True+ )started_at = workflow.now()status = "FAILED"try:@@ -159,6 +177,12 @@ class RunUsageReportsWorkflow(PostHogWorkflow):agg = await workflow.execute_activity(aggregate_and_chunk_org_reports,AggregateInputs(ctx=ctx, query_results=query_results, counter_result=counter_result),+ # Wait for capacity in Temporal, before the activity's start-to-close timer begins.+ task_queue=(+ settings.USAGE_REPORT_AGGREGATION_TASK_QUEUE+ if workflow.patched(AGGREGATION_QUEUE_PATCH_ID)+ else None+ ),start_to_close_timeout=timedelta(minutes=60),retry_policy=common.RetryPolicy(maximum_attempts=2,