:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat: Incremental improvements to usage reports temporal workflow (#57846)
Marce Collfa282ccda695
diff --git a/posthog/temporal/tests/usage_report/test_workflow.py b/posthog/temporal/tests/usage_report/test_workflow.pyindex f5857546fc42..6d3f7a7d1b4a 100644--- a/posthog/temporal/tests/usage_report/test_workflow.py+++ b/posthog/temporal/tests/usage_report/test_workflow.py@@ -1,8 +1,10 @@"""End-to-end workflow tests using a Temporal `WorkflowEnvironment`.The activities are mocked at the `@activity.defn` boundary so the workflow's-orchestration logic — query fan-out, aggregation, SQS pointer — can be-verified without standing up real ClickHouse / Postgres / S3.+orchestration logic — query fan-out, aggregation — can be verified without+standing up real ClickHouse / Postgres / S3. The SQS pointer activity call+is currently disabled in the workflow (see `workflow.py`), so it's not+exercised here."""import uuid@@ -28,7 +30,7 @@ from posthog.temporal.usage_report.workflow import RunUsageReportsWorkflow@pytest.mark.asyncio-async def test_workflow_runs_query_aggregate_pointer_in_order() -> None:+async def test_workflow_runs_query_then_aggregate() -> None:seen_query_names: list[str] = []aggregated_with: list[list[str]] = []pointer_payloads: list[EnqueuePointerInputs] = []@@ -52,11 +54,14 @@ async def test_workflow_runs_query_aggregate_pointer_in_order() -> None:total_orgs_with_usage=1,)+ # Pointer activity is registered so the worker accepts it if dispatched,+ # but the workflow currently does not call it (see workflow.py for why).@activity.defn(name="usage-reports-enqueue-pointer-message")async def pointer_mock(inputs: EnqueuePointerInputs) -> None:pointer_payloads.append(inputs)task_queue = str(uuid.uuid4())+ workflow_id = str(uuid.uuid4())async with await WorkflowEnvironment.start_time_skipping(data_converter=pydantic_data_converter) as env:async with Worker(env.client,@@ -68,20 +73,41 @@ async def test_workflow_runs_query_aggregate_pointer_in_order() -> None:result = await env.client.execute_workflow(RunUsageReportsWorkflow.run,RunUsageReportsInputs(at="2026-05-04T12:00:00+00:00"),- id=str(uuid.uuid4()),+ id=workflow_id,task_queue=task_queue,)+ # 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)+ 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 != "run-usage-report-query":+ 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+expected_names = [spec.name for spec in QUERIES]- assert seen_query_names == expected_names+ # Queries run with bounded concurrency, so completion order is not+ # deterministic — only assert the set. Result ordering (passed to the+ # aggregator) is preserved via `asyncio.gather`.+ assert set(seen_query_names) == set(expected_names)+ assert len(seen_query_names) == len(expected_names)assert len(aggregated_with) == 1assert aggregated_with[0] == expected_names- assert len(pointer_payloads) == 1- pointer = pointer_payloads[0]- assert pointer.aggregate.chunk_keys == ["chunks/chunk_0000.jsonl.gz"]- assert pointer.aggregate.total_orgs == 2+ # Pointer dispatch is currently disabled in the workflow.+ assert pointer_payloads == []++ # Each scheduled query activity carries its query name as the Temporal+ # `summary`, so the UI surfaces which query is running.+ assert set(scheduled_summaries.values()) == set(expected_names)+ assert len(scheduled_summaries) == len(expected_names)assert (resultdiff --git a/posthog/temporal/usage_report/activities.py b/posthog/temporal/usage_report/activities.pyindex d79d3a24a7ae..b77df6325aad 100644--- a/posthog/temporal/usage_report/activities.py+++ b/posthog/temporal/usage_report/activities.py@@ -16,7 +16,7 @@ import structlogfrom asgiref.sync import sync_to_asyncfrom temporalio import activity-from posthog.sync import database_sync_to_async+from posthog.sync import database_sync_to_async, database_sync_to_async_poolfrom posthog.tasks.usage_report import build_org_reports, get_instance_metadatafrom posthog.temporal.common.heartbeat import Heartbeaterfrom posthog.temporal.usage_report.aggregator import (@@ -70,7 +70,11 @@ async def run_query_to_s3(inputs: RunQueryToS3Inputs) -> RunQueryToS3Result:async with Heartbeater():spec = QUERY_INDEX[inputs.query_name]- @database_sync_to_async+ # Use the pooled variant so concurrent query activities on the same+ # worker actually run in parallel. The default thread_sensitive=True+ # serializes everything onto a single shared thread, defeating the+ # bounded fan-out in the workflow.+ @database_sync_to_async_pooldef run() -> Any:# Snapshot specs ignore the period (they read current state);# period specs filter on (begin, end). The signature is enforceddiff --git a/posthog/temporal/usage_report/workflow.py b/posthog/temporal/usage_report/workflow.pyindex 9c806f2a7bb9..bae7af996e05 100644--- a/posthog/temporal/usage_report/workflow.py+++ b/posthog/temporal/usage_report/workflow.py@@ -4,10 +4,13 @@ for the billing service.The workflow runs ~50 gather queries (each as its own retriable activity),then a single aggregation activity reads them all back from S3, builds one`FullUsageReport` dict per organization, and writes those reports as gzipped-JSONL chunks (≤10k orgs each) plus a manifest. A final-`enqueue_pointer_message` activity sends a single SQS message to the billing-service pointing at the S3 prefix; billing reads the chunks from S3 instead-of receiving 50k+ per-org SQS messages.+JSONL chunks (≤10k orgs each) plus a manifest.++The final step — an `enqueue_pointer_message` activity that sends a single+SQS pointer to billing — is currently disabled until the `usage_reports_v2`+queue is provisioned in deployment. For now the workflow stops after the+chunks and manifest are in S3; billing isn't notified yet. See the+commented-out call below for re-enabling.This replaces the per-org SQS fan-out in`posthog/tasks/usage_report.py:send_all_org_usage_reports`. The Celery task@@ -15,6 +18,7 @@ remains in production until billing migrates to consume the S3 layout."""import json+import asynciofrom datetime import datetime, timedeltafrom typing import Optional@@ -23,16 +27,11 @@ from temporalio import common, workflowfrom posthog.exceptions_capture import capture_exceptionfrom posthog.temporal.common.base import PostHogWorkflow-from posthog.temporal.usage_report.activities import (- aggregate_and_chunk_org_reports,- enqueue_pointer_message,- run_query_to_s3,-)+from posthog.temporal.usage_report.activities import aggregate_and_chunk_org_reports, run_query_to_s3from posthog.temporal.usage_report.queries import QUERIES, QuerySpecfrom posthog.temporal.usage_report.storage import run_prefixfrom posthog.temporal.usage_report.types import (AggregateInputs,- EnqueuePointerInputs,RunQueryToS3Inputs,RunQueryToS3Result,RunUsageReportsInputs,@@ -40,6 +39,10 @@ from posthog.temporal.usage_report.types import ()from posthog.utils import get_previous_day+# Cap concurrent gather queries so we don't overwhelm ClickHouse / Postgres+# with ~40 simultaneous heavy queries.+QUERY_CONCURRENCY = 4+def build_context(inputs: RunUsageReportsInputs, run_id: str, now: Optional[datetime] = None) -> WorkflowContext:"""Compute the period and S3 layout context. Pure function so it's safe@@ -80,14 +83,19 @@ class RunUsageReportsWorkflow(PostHogWorkflow):},)- # Run the gather queries serially. Even though Temporal could run- # them in parallel, we deliberately stagger them so we don't pile- # ~40 simultaneous heavy queries onto ClickHouse / Postgres at- # once — the daily report is not latency-sensitive, and giving- # the databases breathing room matters more than wall-clock.- query_results: list[RunQueryToS3Result] = []- for spec in QUERIES:- query_results.append(await self._run_query(ctx, spec))+ # Run the gather queries with bounded concurrency. We don't want+ # ~40 simultaneous heavy queries hitting ClickHouse / Postgres,+ # but a small batch shortens wall-clock substantially without+ # overwhelming the databases.+ sem = asyncio.Semaphore(QUERY_CONCURRENCY)++ async def _run_with_sem(spec: QuerySpec) -> RunQueryToS3Result:+ async with sem:+ return await self._run_query(ctx, spec)++ query_results: list[RunQueryToS3Result] = list(+ await asyncio.gather(*(_run_with_sem(spec) for spec in QUERIES))+ )agg = await workflow.execute_activity(aggregate_and_chunk_org_reports,@@ -100,16 +108,22 @@ class RunUsageReportsWorkflow(PostHogWorkflow):heartbeat_timeout=timedelta(minutes=5),)- await workflow.execute_activity(- enqueue_pointer_message,- EnqueuePointerInputs(ctx=ctx, aggregate=agg),- start_to_close_timeout=timedelta(minutes=2),- retry_policy=common.RetryPolicy(- maximum_attempts=5,- initial_interval=timedelta(seconds=10),- ),- heartbeat_timeout=timedelta(minutes=1),- )+ # SQS pointer dispatch is disabled until the `usage_reports_v2`+ # queue is provisioned in deployment and+ # `SQS_USAGE_REPORT_V2_QUEUE_URL` is set on the temporal-worker+ # pods. Re-enable by uncommenting the call below once billing has+ # the queue ready to consume.+ #+ # await workflow.execute_activity(+ # enqueue_pointer_message,+ # EnqueuePointerInputs(ctx=ctx, aggregate=agg),+ # start_to_close_timeout=timedelta(minutes=2),+ # retry_policy=common.RetryPolicy(+ # maximum_attempts=5,+ # initial_interval=timedelta(seconds=10),+ # ),+ # heartbeat_timeout=timedelta(minutes=1),+ # )# Intentionally NOT cleaning up the per-query intermediates yet —# we want them around in S3 for debugging while we validate the@@ -150,4 +164,5 @@ class RunUsageReportsWorkflow(PostHogWorkflow):initial_interval=timedelta(seconds=30),),heartbeat_timeout=timedelta(minutes=2),+ summary=spec.name,)