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): Usage Reports Temporal Workflow (#57664)

Marce Coll5e2a5c5939d6
diff --git a/.github/workflows/container-images-cd.yml b/.github/workflows/container-images-cd.yml
index b3b156050730..f52e52112562 100644
--- a/.github/workflows/container-images-cd.yml
+++ b/.github/workflows/container-images-cd.yml
@@ -250,12 +250,12 @@ jobs:
- name: Check for changes that affect general purpose temporal worker
id: check_changes_general_purpose_temporal_worker
run: |
- echo "changed=$((git diff --name-only HEAD^ HEAD | grep -qE '^posthog/temporal/subscriptions|^posthog/temporal/common|^posthog/temporal/session_recordings|^posthog/temporal/proxy_service|^posthog/temporal/usage_reports|^posthog/temporal/llm_analytics|^posthog/temporal/product_analytics|^posthog/temporal/delete_persons|^posthog/temporal/ingestion_acceptance_test|^posthog/management/commands/start_temporal_worker.py$|^pyproject.toml$|^bin/temporal-django-worker$' && echo true) || echo false)" >> $GITHUB_OUTPUT
+ echo "changed=$((git diff --name-only HEAD^ HEAD | grep -qE '^posthog/temporal/subscriptions|^posthog/temporal/common|^posthog/temporal/session_recordings|^posthog/temporal/proxy_service|^posthog/temporal/llm_analytics|^posthog/temporal/product_analytics|^posthog/temporal/delete_persons|^posthog/temporal/ingestion_acceptance_test|^posthog/management/commands/start_temporal_worker.py$|^pyproject.toml$|^bin/temporal-django-worker$' && echo true) || echo false)" >> $GITHUB_OUTPUT
- name: Check for changes that affect billing temporal worker
id: check_changes_billing_temporal_worker
run: |
- echo "changed=$((git diff --name-only HEAD^ HEAD | grep -qE '^ee/billing/|^posthog/temporal/quota_limiting|^posthog/temporal/salesforce_enrichment|^posthog/temporal/common|^posthog/management/commands/start_temporal_worker.py$|^pyproject.toml$|^bin/temporal-django-worker$' && echo true) || echo false)" >> $GITHUB_OUTPUT
+ echo "changed=$((git diff --name-only HEAD^ HEAD | grep -qE '^ee/billing/|^posthog/temporal/quota_limiting|^posthog/temporal/salesforce_enrichment|^posthog/temporal/usage_report|^posthog/temporal/common|^posthog/management/commands/start_temporal_worker.py$|^pyproject.toml$|^bin/temporal-django-worker$' && echo true) || echo false)" >> $GITHUB_OUTPUT
- name: Check for changes that affect video export temporal worker
id: check_changes_video_export_temporal_worker
diff --git a/ee/settings.py b/ee/settings.py
index 5855f9b21827..5c335a0a2665 100644
--- a/ee/settings.py
+++ b/ee/settings.py
@@ -116,6 +116,11 @@ SQS_QUEUES = {
"region": get_from_env("SQS_REGION", "us-east-1", optional=True),
"type": "usage_reports",
},
+ "usage_reports_v2": {
+ "url": get_from_env("SQS_USAGE_REPORT_V2_QUEUE_URL", optional=True),
+ "region": get_from_env("SQS_USAGE_REPORT_V2_REGION", "us-east-1", optional=True),
+ "type": "usage_reports_v2",
+ },
"billing": {
"url": get_from_env("SQS_BILLING_QUEUE_URL", optional=True),
"region": get_from_env("SQS_BILLING_REGION", "us-east-1", optional=True),
diff --git a/posthog/management/commands/execute_temporal_workflow.py b/posthog/management/commands/execute_temporal_workflow.py
index 7a364c8069ef..784ac5ec1d8e 100644
--- a/posthog/management/commands/execute_temporal_workflow.py
+++ b/posthog/management/commands/execute_temporal_workflow.py
@@ -26,7 +26,7 @@ from posthog.temporal.session_replay.import_recording import IMPORT_RECORDING_WO
from posthog.temporal.session_replay.rasterize_recording import RASTERIZE_RECORDING_WORKFLOWS
from posthog.temporal.session_replay.summarization_sweep import SUMMARIZATION_SWEEP_WORKFLOWS
from posthog.temporal.tests.utils.workflow import WORKFLOWS as TEST_WORKFLOWS
-from posthog.temporal.usage_reports import WORKFLOWS as USAGE_REPORTS_WORKFLOWS
+from posthog.temporal.usage_report import WORKFLOWS as USAGE_REPORTS_WORKFLOWS
from posthog.temporal.weekly_digest import WORKFLOWS as WEEKLY_DIGEST_WORKFLOWS
from products.batch_exports.backend.temporal import WORKFLOWS as BATCH_EXPORT_WORKFLOWS
diff --git a/posthog/management/commands/start_temporal_worker.py b/posthog/management/commands/start_temporal_worker.py
index 968b885a712a..fabb1a3f8125 100644
--- a/posthog/management/commands/start_temporal_worker.py
+++ b/posthog/management/commands/start_temporal_worker.py
@@ -148,7 +148,7 @@ from posthog.temporal.tests.utils.workflow import (
ACTIVITIES as TEST_ACTIVITIES,
WORKFLOWS as TEST_WORKFLOWS,
)
-from posthog.temporal.usage_reports import (
+from posthog.temporal.usage_report import (
ACTIVITIES as USAGE_REPORTS_ACTIVITIES,
WORKFLOWS as USAGE_REPORTS_WORKFLOWS,
)
@@ -214,7 +214,6 @@ _task_queue_specs = [
settings.GENERAL_PURPOSE_TASK_QUEUE,
PROXY_SERVICE_WORKFLOWS
+ DELETE_PERSONS_WORKFLOWS
- + USAGE_REPORTS_WORKFLOWS
+ SALESFORCE_ENRICHMENT_WORKFLOWS
+ PRODUCT_ANALYTICS_WORKFLOWS
+ LLM_ANALYTICS_WORKFLOWS
@@ -226,7 +225,6 @@ _task_queue_specs = [
+ WAREHOUSE_SOURCES_QUEUE_PARTITION_WORKFLOWS,
PROXY_SERVICE_ACTIVITIES
+ DELETE_PERSONS_ACTIVITIES
- + USAGE_REPORTS_ACTIVITIES
+ QUOTA_LIMITING_ACTIVITIES
+ SALESFORCE_ENRICHMENT_ACTIVITIES
+ PRODUCT_ANALYTICS_ACTIVITIES
@@ -270,8 +268,8 @@ _task_queue_specs = [
),
(
settings.BILLING_TASK_QUEUE,
- QUOTA_LIMITING_WORKFLOWS + SALESFORCE_ENRICHMENT_WORKFLOWS,
- QUOTA_LIMITING_ACTIVITIES + SALESFORCE_ENRICHMENT_ACTIVITIES,
+ QUOTA_LIMITING_WORKFLOWS + SALESFORCE_ENRICHMENT_WORKFLOWS + USAGE_REPORTS_WORKFLOWS,
+ QUOTA_LIMITING_ACTIVITIES + SALESFORCE_ENRICHMENT_ACTIVITIES + USAGE_REPORTS_ACTIVITIES,
),
(
settings.VIDEO_EXPORT_TASK_QUEUE,
diff --git a/posthog/management/commands/start_temporal_workflow.py b/posthog/management/commands/start_temporal_workflow.py
index 2d49ab575749..cb2662eb2cf9 100644
--- a/posthog/management/commands/start_temporal_workflow.py
+++ b/posthog/management/commands/start_temporal_workflow.py
@@ -27,7 +27,7 @@ from posthog.temporal.session_replay.replay_count_metrics import REPLAY_COUNT_ME
from posthog.temporal.session_replay.summarization_sweep import SUMMARIZATION_SWEEP_WORKFLOWS
from posthog.temporal.sync_person_distinct_ids import WORKFLOWS as SYNC_PERSON_DISTINCT_IDS_WORKFLOWS
from posthog.temporal.tests.utils.workflow import WORKFLOWS as TEST_WORKFLOWS
-from posthog.temporal.usage_reports import WORKFLOWS as USAGE_REPORTS_WORKFLOWS
+from posthog.temporal.usage_report import WORKFLOWS as USAGE_REPORTS_WORKFLOWS
from posthog.temporal.weekly_digest import WORKFLOWS as WEEKLY_DIGEST_WORKFLOWS
from products.batch_exports.backend.temporal import WORKFLOWS as BATCH_EXPORT_WORKFLOWS
diff --git a/posthog/settings/object_storage.py b/posthog/settings/object_storage.py
index 25d8a111ea88..1e17bada83dd 100644
--- a/posthog/settings/object_storage.py
+++ b/posthog/settings/object_storage.py
@@ -41,3 +41,8 @@ QUERY_CACHE_S3_BUCKET = os.getenv("QUERY_CACHE_S3_BUCKET") or OBJECT_STORAGE_BUC
# Video segment clustering workflow bucket - should have a 24h lifecycle rule for automatic cleanup
VIDEO_SEGMENT_CLUSTERING_S3_BUCKET = os.getenv("VIDEO_SEGMENT_CLUSTERING_S3_BUCKET") or OBJECT_STORAGE_BUCKET
+
+# Billing usage report bucket — holds the daily JSONL chunks the billing
+# service consumes. Falls back to the general bucket if not set so dev /
+# self-hosted continue to work without extra configuration.
+BILLING_USAGE_REPORTS_S3_BUCKET = os.getenv("BILLING_USAGE_REPORTS_S3_BUCKET") or OBJECT_STORAGE_BUCKET
diff --git a/posthog/tasks/usage_report.py b/posthog/tasks/usage_report.py
index 14c6db3b2b6f..ffdc623bc6e8 100644
--- a/posthog/tasks/usage_report.py
+++ b/posthog/tasks/usage_report.py
@@ -2295,6 +2295,31 @@ def _get_full_org_usage_report_as_dict(full_report: FullUsageReport) -> dict[str
}
+def build_org_reports(all_data: dict[str, Any], period_start: datetime) -> dict[str, OrgReport]:
+ """Aggregate per-team `all_data` rows into per-organization `OrgReport`s.
+
+ Public facade that bundles `_get_teams_for_usage_reports`, `_get_team_report`,
+ and `_add_team_report_to_org_reports` so callers (e.g. the Temporal
+ workflow) don't need to import the private helpers individually.
+ """
+ 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)
+ return org_reports
+
+
+def serialize_full_org_report(org_report: OrgReport, instance_metadata: InstanceMetadata) -> dict[str, Any]:
+ """Combine an `OrgReport` with `InstanceMetadata` and serialize to a dict.
+
+ Public facade equivalent to `_get_full_org_usage_report` followed by
+ `_get_full_org_usage_report_as_dict`. The result includes the
+ `has_non_zero_usage` flag and is the shape billing consumes.
+ """
+ full = _get_full_org_usage_report(org_report, instance_metadata)
+ return _get_full_org_usage_report_as_dict(full)
+
+
def _queue_report(producer: Any, organization_id: str, full_report_dict: dict[str, Any]) -> None:
json_data = json.dumps(
{"organization_id": organization_id, "usage_report": full_report_dict},
diff --git a/posthog/temporal/schedule.py b/posthog/temporal/schedule.py
index d4c9f034113d..c8f403e3244e 100644
--- a/posthog/temporal/schedule.py
+++ b/posthog/temporal/schedule.py
@@ -70,6 +70,7 @@ from posthog.temporal.session_replay.summarization_sweep.reconciler import (
create_summarization_sweep_reconciler_schedule,
)
from posthog.temporal.subscriptions.types import ScheduleAllSubscriptionsWorkflowInputs
+from posthog.temporal.usage_report.types import RunUsageReportsInputs
from posthog.temporal.warehouse_sources_queue_partition_management.schedule import (
create_warehouse_sources_queue_partition_management_schedule,
)
@@ -495,6 +496,47 @@ async def cleanup_legacy_session_summarization_schedules(client: Client):
await a_delete_schedule(client, schedule_id)
+async def create_run_usage_reports_schedule(client: Client):
+ """Daily Temporal-based usage report run at 04:45 UTC.
+
+ Runs an hour after the existing Celery beat for `send_all_org_usage_reports`
+ (03:45 UTC) so ClickHouse has breathing room while both flows run side by
+ side. The workflow writes per-org usage data to S3 and sends a single SQS
+ pointer to the billing service.
+ """
+ run_usage_reports_schedule = Schedule(
+ action=ScheduleActionStartWorkflow(
+ "run-usage-reports",
+ # `RunUsageReportsInputs` is a pydantic model, not a dataclass —
+ # `dataclasses.asdict` would TypeError on registration.
+ RunUsageReportsInputs().model_dump(mode="json"),
+ id="run-usage-reports-schedule",
+ task_queue=settings.BILLING_TASK_QUEUE,
+ retry_policy=common.RetryPolicy(maximum_attempts=1),
+ ),
+ spec=ScheduleSpec(
+ calendars=[
+ ScheduleCalendarSpec(
+ comment="Daily at 04:45 UTC",
+ hour=[ScheduleRange(start=4, end=4)],
+ minute=[ScheduleRange(start=45, end=45)],
+ )
+ ]
+ ),
+ policy=SchedulePolicy(overlap=ScheduleOverlapPolicy.SKIP),
+ )
+
+ if await a_schedule_exists(client, "run-usage-reports-schedule"):
+ await a_update_schedule(client, "run-usage-reports-schedule", run_usage_reports_schedule)
+ else:
+ await a_create_schedule(
+ client,
+ "run-usage-reports-schedule",
+ run_usage_reports_schedule,
+ trigger_immediately=False,
+ )
+
+
async def create_count_all_playlists_schedule(client: Client):
"""Create or update the schedule for the playlist counting workflow.
@@ -569,6 +611,7 @@ if settings.CLOUD_DEPLOYMENT:
# Sweeper compares the deployment prefix on each Gemini file's display_name against its own
# CLOUD_DEPLOYMENT, so it can't run unscoped (would risk reaping sibling deployments' files).
schedules.append(create_gemini_cleanup_sweep_schedule)
+ schedules.append(create_run_usage_reports_schedule)
if settings.EE_AVAILABLE:
schedules.append(create_schedule_all_subscriptions_schedule)
diff --git a/posthog/temporal/tests/usage_report/__init__.py b/posthog/temporal/tests/usage_report/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/posthog/temporal/tests/usage_report/conftest.py b/posthog/temporal/tests/usage_report/conftest.py
new file mode 100644
index 000000000000..d350e031abd7
--- /dev/null
+++ b/posthog/temporal/tests/usage_report/conftest.py
@@ -0,0 +1,55 @@
+"""Shared fixtures for usage report tests.
+
+`minio_workflow_ctx` yields a `WorkflowContext` whose `run_id` and
+`date_str` are unique per test, then cleans up every S3 object written
+under that prefix. Tests that use it hit real MinIO via
+`posthog.storage.object_storage` instead of an in-memory fake — that
+catches content-type / content-encoding / boto3 idiosyncrasies the
+mocks can't.
+"""
+
+import uuid
+from collections.abc import Iterator
+from datetime import UTC, datetime
+
+import pytest
+
+from django.conf import settings
+
+from boto3 import resource
+from botocore.client import Config
+
+from posthog.temporal.usage_report.storage import bucket, run_prefix
+from posthog.temporal.usage_report.types import WorkflowContext
+
+
+def _s3_resource():
+ return resource(
+ "s3",
+ endpoint_url=settings.OBJECT_STORAGE_ENDPOINT,
+ aws_access_key_id=settings.OBJECT_STORAGE_ACCESS_KEY_ID,
+ aws_secret_access_key=settings.OBJECT_STORAGE_SECRET_ACCESS_KEY,
+ config=Config(signature_version="s3v4"),
+ region_name=settings.OBJECT_STORAGE_REGION,
+ )
+
+
+def _delete_prefix(prefix: str) -> None:
+ s3 = _s3_resource()
+ s3_bucket = s3.Bucket(bucket())
+ s3_bucket.objects.filter(Prefix=prefix).delete()
+
+
+def minio_workflow_ctx() -> Iterator[WorkflowContext]:
+ """A `WorkflowContext` whose run-prefix gets nuked from MinIO at teardown."""
+ ctx = WorkflowContext(
+ run_id=f"test-{uuid.uuid4().hex[:12]}",
+ period_start=datetime(2026, 5, 4, 0, 0, 0, tzinfo=UTC),
+ period_end=datetime(2026, 5, 4, 23, 59, 59, 999999, tzinfo=UTC),
+ date_str=f"test-{uuid.uuid4().hex[:8]}",
+ )
+ try:
+ yield ctx
+ finally:
+ _delete_prefix(run_prefix(ctx))
diff --git a/posthog/temporal/tests/usage_report/test_aggregate_activity.py b/posthog/temporal/tests/usage_report/test_aggregate_activity.py
new file mode 100644
index 000000000000..81a4be67c73f
--- /dev/null
+++ b/posthog/temporal/tests/usage_report/test_aggregate_activity.py
@@ -0,0 +1,297 @@
+"""Tests for the `aggregate_and_chunk_org_reports` Temporal activity.
+
+These run end-to-end against real MinIO (via `minio_workflow_ctx`) and a
+real Postgres test DB (`@pytest.mark.django_db`). Only the "expensive"
+gather queries (the ClickHouse + ORM functions in
+`posthog.tasks.usage_report`) are mocked — by seeding canned per-spec
+JSON files into MinIO ourselves, then letting the activity read,
+aggregate, and write back as in production.
+"""
+
+import gzip
+import json
+import uuid
+from typing import Any
+
+import pytest
+from unittest.mock import patch
+
+from asgiref.sync import sync_to_async
+
+from posthog.models import Organization, Team
+from posthog.storage import object_storage
+from posthog.tasks.usage_report import InstanceMetadata
+from posthog.temporal.usage_report import storage
+from posthog.temporal.usage_report.activities import aggregate_and_chunk_org_reports
+from posthog.temporal.usage_report.queries import QUERIES
+from posthog.temporal.usage_report.storage import queries_key, write_json
+from posthog.temporal.usage_report.types import AggregateInputs, RunQueryToS3Result, WorkflowContext
+
+
+@sync_to_async
+def _make_org(name: str) -> Organization:
+ """Use the sync ORM (so pre_save signals run) wrapped for the async
+ test body. `acreate` skips Django signals, which means auto-slug and
+ auto-project-creation don't fire — both produce IntegrityErrors for
+ Org and Team respectively.
+ """
+ return Organization.objects.create(name=name, slug=f"test-{uuid.uuid4().hex[:12]}")
+
+
+@sync_to_async
+def _make_team(organization: Organization, name: str) -> Team:
+ return Team.objects.create(organization=organization, name=name)
+
+
+def _canned_query_payload(query_name: str, team_a_id: int, team_b_id: int) -> Any:
+ """Default payload per query — uses team rows where it makes sense, and
+ multi-key dicts for the three multi-output specs.
+ """
+ if query_name == "all_event_metrics":
+ return {
+ "helicone_events": [],
+ "langfuse_events": [],
+ "keywords_ai_events": [],
+ "traceloop_events": [],
+ "web_events": [(team_a_id, 7), (team_b_id, 11)],
+ "web_lite_events": [],
+ "node_events": [],
+ "android_events": [],
+ "flutter_events": [],
+ "ios_events": [],
+ "go_events": [],
+ "java_events": [],
+ "react_native_events": [],
+ "ruby_events": [],
+ "python_events": [(team_a_id, 3)],
+ "php_events": [],
+ "dotnet_events": [],
+ "elixir_events": [],
+ "unity_events": [],
+ "rust_events": [],
+ }
+ if query_name == "exceptions_captured":
+ return {
+ "total": [[team_a_id, 5]],
+ "web": [[team_a_id, 5]],
+ "web_lite": [],
+ "node": [],
+ "android": [],
+ "flutter": [],
+ "ios": [],
+ "go": [],
+ "java": [],
+ "react_native": [],
+ "ruby": [],
+ "python": [],
+ "unknown": [],
+ }
+ if query_name == "api_queries_metrics":
+ return {"count": [(team_b_id, 100)], "read_bytes": [(team_b_id, 5_000_000)]}
+
+ if query_name == "teams_with_event_count_in_period":
+ return [(team_a_id, 100), (team_b_id, 50)]
+ if query_name == "teams_with_recording_count_in_period":
+ return [(team_a_id, 8)]
+
+ # Postgres ORM-style queries return dicts with team_id/total
+ if query_name in (
+ "teams_with_dashboard_count",
+ "teams_with_ff_count",
+ "teams_with_survey_count",
+ "teams_with_group_types_total",
+ ):
+ return [{"team_id": team_a_id, "total": 2}, {"team_id": team_b_id, "total": 1}]
+
+ # Everything else gets an empty result list — keeps the test focused on
+ # the few interesting metrics above.
+ return []
+
+
+def _instance_metadata() -> InstanceMetadata:
+ return InstanceMetadata(
+ deployment_infrastructure="test",
+ realm="cloud",
+ period={
+ "start_inclusive": "2026-05-04T00:00:00+00:00",
+ "end_inclusive": "2026-05-04T23:59:59.999999+00:00",
+ },
+ site_url="https://us.posthog.com",
+ product="cloud",
+ helm=None,
+ clickhouse_version=None,
+ users_who_logged_in=None,
+ users_who_logged_in_count=None,
+ users_who_signed_up=None,
+ users_who_signed_up_count=None,
+ table_sizes=None,
+ plugins_installed=None,
+ plugins_enabled=None,
+ instance_tag="test-tag",
+ )
+
+
+def _seed_query_results(ctx: WorkflowContext, team_a_id: int, team_b_id: int) -> list[RunQueryToS3Result]:
+ """Write a canned JSON file per QuerySpec into MinIO and return the
+ matching `RunQueryToS3Result` list the activity expects as input.
+ """
+ query_results: list[RunQueryToS3Result] = []
+ for spec in QUERIES:
+ key = queries_key(ctx, spec.name)
+ write_json(key, _canned_query_payload(spec.name, team_a_id, team_b_id))
+ query_results.append(RunQueryToS3Result(query_name=spec.name, s3_key=key, duration_ms=1))
+ return query_results
+
+
+def _read_jsonl_gz(key: str) -> list[dict]:
+ body = object_storage.read_bytes(key, bucket=storage.bucket())
+ assert body is not None, f"missing chunk at {key}"
+ return [json.loads(line) for line in gzip.decompress(body).decode("utf-8").splitlines()]
+
+
+def _read_json(key: str) -> Any:
+ body = object_storage.read_bytes(key, bucket=storage.bucket())
+ assert body is not None, f"missing object at {key}"
+ return json.loads(body)
+
+
+async def test_aggregate_writes_chunks_and_manifest(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")
+
+ # Scope the run to just the orgs we created — the shared test DB has
+ # pre-seeded orgs that would otherwise inflate the manifest counts.
+ 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)
+
+ with patch(
+ "posthog.temporal.usage_report.activities.get_instance_metadata",
+ return_value=_instance_metadata(),
+ ):
+ result = await activity_environment.run(
+ aggregate_and_chunk_org_reports,
+ AggregateInputs(ctx=ctx, query_results=query_results),
+ )
+
+ assert result.total_orgs == 2
+
+ # Exactly one chunk written, since 2 orgs fits well under the 10k batch.
+ assert len(result.chunk_keys) == 1
+ chunk_key = result.chunk_keys[0]
+ assert chunk_key.endswith("/chunks/chunk_0000.jsonl.gz")
+
+ # Manifest matches what the activity returned.
+ assert result.manifest_key.endswith("/manifest.json")
+ manifest = _read_json(result.manifest_key)
+ assert manifest["version"] == 2
+ assert manifest["run_id"] == minio_workflow_ctx.run_id
+ assert manifest["chunk_count"] == 1
+ assert manifest["chunk_keys"] == [chunk_key]
+ assert manifest["total_orgs"] == 2
+
+ # Decompress the chunk and inspect the per-org rows.
+ rows = _read_jsonl_gz(chunk_key)
+ assert len(rows) == 2
+ by_org = {row["organization_id"]: row["usage_report"] for row in rows}
+ assert set(by_org.keys()) == {str(org_a.id), str(org_b.id)}
+
+ # multi-key fan-out: web events from `all_event_metrics` landed in the
+ # destination key on each org's report.
+ assert by_org[str(org_a.id)]["web_events_count_in_period"] == 7
+ assert by_org[str(org_b.id)]["web_events_count_in_period"] == 11
+
+ # exceptions_captured "total" maps to the flat counter on the org's report.
+ assert by_org[str(org_a.id)]["exceptions_captured_in_period"] == 5
+ assert by_org[str(org_b.id)]["exceptions_captured_in_period"] == 0
+
+ # api_queries_metrics fans out to count + read_bytes destination keys.
+ assert by_org[str(org_b.id)]["api_queries_query_count"] == 100
+ assert by_org[str(org_b.id)]["api_queries_bytes_read"] == 5_000_000
+
+ # has_non_zero_usage is computed and present on every line.
+ assert by_org[str(org_a.id)]["has_non_zero_usage"] is True
+ assert by_org[str(org_b.id)]["has_non_zero_usage"] is True
+
+ # team breakdown is present and matches.
+ assert by_org[str(org_a.id)]["teams"][str(team_a.id)]["event_count_in_period"] == 100
+
+
+async def test_aggregate_chunks_into_batches_of_ten_thousand(
+ minio_workflow_ctx: WorkflowContext, activity_environment
+) -> None:
+ """Exercise chunking — set CHUNK_SIZE_ORGS low and verify multiple chunks."""
+ from posthog.temporal.usage_report import activities as module
+
+ org = await _make_org("Org X")
+ team = await _make_team(org, "T0")
+
+ extra_org_a = await _make_org("Extra A")
+ extra_org_b = await _make_org("Extra B")
+ extra_team_a = await _make_team(extra_org_a, "EA")
+ await _make_team(extra_org_b, "EB")
+
+ # Scope the activity to just the three orgs we created — the shared
+ # test DB has pre-seeded internal orgs that would otherwise inflate
+ # the chunk counts.
+ ctx = minio_workflow_ctx.model_copy(
+ update={"organization_ids": [str(org.id), str(extra_org_a.id), str(extra_org_b.id)]}
+ )
+ query_results = _seed_query_results(ctx, team.id, extra_team_a.id)
+
+ with (
+ patch.object(module, "CHUNK_SIZE_ORGS", 2),
+ patch(
+ "posthog.temporal.usage_report.activities.get_instance_metadata",
+ return_value=_instance_metadata(),
+ ),
+ ):
+ result = await activity_environment.run(
+ aggregate_and_chunk_org_reports,
+ AggregateInputs(ctx=ctx, query_results=query_results),
+ )
+
+ # 3 orgs / 2 per chunk = 2 chunks (2 + 1)
+ assert result.total_orgs == 3
+ assert len(result.chunk_keys) == 2
+
+ all_lines: list[dict] = []
+ for key in result.chunk_keys:
+ all_lines.extend(_read_jsonl_gz(key))
+ assert len(all_lines) == 3
+ assert {row["organization_id"] for row in all_lines} == {str(org.id), str(extra_org_a.id), str(extra_org_b.id)}
+
+ # Manifest enumerates both chunks
+ manifest = _read_json(result.manifest_key)
+ assert manifest["chunk_count"] == 2
+ assert manifest["chunk_keys"] == result.chunk_keys
+
+
+async def test_aggregate_filters_by_organization_ids(minio_workflow_ctx: WorkflowContext, activity_environment) -> None:
+ org_a = await _make_org("A")
+ org_b = await _make_org("B")
+ team_a = await _make_team(org_a, "A")
+ team_b = await _make_team(org_b, "B")
+
+ ctx = minio_workflow_ctx.model_copy(update={"organization_ids": [str(org_a.id)]})
+ query_results = _seed_query_results(ctx, team_a.id, team_b.id)
+
+ with patch(
+ "posthog.temporal.usage_report.activities.get_instance_metadata",
+ return_value=_instance_metadata(),
+ ):
+ result = await activity_environment.run(
+ aggregate_and_chunk_org_reports,
+ AggregateInputs(ctx=ctx, query_results=query_results),
+ )
+
+ assert result.total_orgs == 1
+ rows = _read_jsonl_gz(result.chunk_keys[0])
+ assert {row["organization_id"] for row in rows} == {str(org_a.id)}
diff --git a/posthog/temporal/tests/usage_report/test_aggregator.py b/posthog/temporal/tests/usage_report/test_aggregator.py
new file mode 100644
index 000000000000..b7b96448677d
--- /dev/null
+++ b/posthog/temporal/tests/usage_report/test_aggregator.py
@@ -0,0 +1,261 @@
+"""Pure-logic tests for the aggregator module.
+
+These cover the building blocks the aggregation activity composes:
+`load_all_data`, `iter_chunk_lines`, `batched`, `build_manifest`,
+`filter_org_reports`, `sort_org_reports`. No Django / Temporal / S3
+required.
+"""
+
+import json
+from datetime import UTC, datetime
+from typing import Any, cast
+
+import pytest
+from unittest.mock import patch
+
+from posthog.tasks.usage_report import InstanceMetadata, OrgReport
+from posthog.temporal.usage_report.aggregator import (
+ batched,
+ build_manifest,
+ filter_org_reports,
+ iter_chunk_lines,
+ load_all_data,
+ sort_org_reports,
+)
+from posthog.temporal.usage_report.types import Manifest, RunQueryToS3Result, WorkflowContext
+
+
+def _ctx(run_id: str = "abc") -> WorkflowContext:
+ return WorkflowContext(
+ run_id=run_id,
+ period_start=datetime(2026, 5, 4, 0, 0, 0, tzinfo=UTC),
+ period_end=datetime(2026, 5, 4, 23, 59, 59, 999999, tzinfo=UTC),
+ date_str="2026-05-04",
+ )
+
+
+# ---- batched -------------------------------------------------------------
+
+
+def test_batched_yields_full_and_remainder() -> None:
+ assert list(batched([1, 2, 3, 4, 5], 2)) == [[1, 2], [3, 4], [5]]
+
+
+def test_batched_empty_input() -> None:
+ assert list(batched([], 3)) == []
+
+
+def test_batched_exact_multiple() -> None:
+ assert list(batched([1, 2, 3, 4], 2)) == [[1, 2], [3, 4]]
+
+
+def test_batched_invalid_size_raises() -> None:
+ with pytest.raises(ValueError, match="positive"):
+ list(batched([1, 2], 0))
+
+
+# ---- load_all_data -------------------------------------------------------
+
+
+def _seed_s3(s3: dict[str, bytes], spec_name: str, payload) -> str:
+ key = f"queries/{spec_name}.json"
+ s3[key] = json.dumps(payload, default=str).encode("utf-8")
+ return key
+
+
+def _patch_query_index(specs: dict) -> Any:
+ return patch.dict(
+ "posthog.temporal.usage_report.queries.QUERY_INDEX",
+ specs,
+ clear=True,
+ )
+
+
+class _SingleSpec:
+ """Minimal QuerySpec stand-in for unit tests."""
+
+ def __init__(self, name: str) -> None:
+ self.name = name
+ self.output = "single"
+ self.multi_keys_mapping: dict[str, str] = {}
+
+
+class _MultiSpec:
+ def __init__(self, name: str, mapping: dict[str, str]) -> None:
+ self.name = name
+ self.output = "multi"
+ self.multi_keys_mapping = mapping
+
+
+def test_load_all_data_single_output_uses_spec_name_as_key() -> None:
+ s3: dict[str, bytes] = {}
+ key = _seed_s3(s3, "teams_with_event_count_in_period", [(1, 100), (2, 50)])
+ results = [RunQueryToS3Result(query_name="teams_with_event_count_in_period", s3_key=key, duration_ms=1)]
+
+ with (
+ _patch_query_index({"teams_with_event_count_in_period": _SingleSpec("teams_with_event_count_in_period")}),
+ patch("posthog.temporal.usage_report.aggregator.read_json", side_effect=lambda k: json.loads(s3[k])),
+ ):
+ all_data = load_all_data(results)
+
+ assert all_data == {"teams_with_event_count_in_period": {1: 100, 2: 50}}
+
+
+def test_load_all_data_multi_output_fans_out_destination_keys() -> None:
+ s3: dict[str, bytes] = {}
+ payload = {"web_events": [(1, 7), (2, 11)], "node_events": [(2, 3)]}
+ key = _seed_s3(s3, "all_event_metrics", payload)
+ results = [RunQueryToS3Result(query_name="all_event_metrics", s3_key=key, duration_ms=1)]
+
+ spec = _MultiSpec(
+ "all_event_metrics",
+ mapping={
+ "web_events": "teams_with_web_events_count_in_period",
+ "node_events": "teams_with_node_events_count_in_period",
+ },
+ )
+ with (
+ _patch_query_index({"all_event_metrics": spec}),
+ patch("posthog.temporal.usage_report.aggregator.read_json", side_effect=lambda k: json.loads(s3[k])),
+ ):
+ all_data = load_all_data(results)
+
+ assert all_data == {
+ "teams_with_web_events_count_in_period": {1: 7, 2: 11},
+ "teams_with_node_events_count_in_period": {2: 3},
+ }
+
+
+def test_load_all_data_multi_output_missing_source_key_yields_empty() -> None:
+ """If the upstream query didn't emit one of the expected source_keys,
+ the destination still gets an empty mapping (not a KeyError)."""
+ s3: dict[str, bytes] = {}
+ key = _seed_s3(s3, "all_event_metrics", {"web_events": [(1, 1)]})
+ results = [RunQueryToS3Result(query_name="all_event_metrics", s3_key=key, duration_ms=1)]
+
+ spec = _MultiSpec(
+ "all_event_metrics",
+ mapping={
+ "web_events": "teams_with_web_events_count_in_period",
+ "ruby_events": "teams_with_ruby_events_count_in_period",
+ },
+ )
+ with (
+ _patch_query_index({"all_event_metrics": spec}),
+ patch("posthog.temporal.usage_report.aggregator.read_json", side_effect=lambda k: json.loads(s3[k])),
+ ):
+ all_data = load_all_data(results)
+
+ assert all_data["teams_with_web_events_count_in_period"] == {1: 1}
+ assert all_data["teams_with_ruby_events_count_in_period"] == {}
+
+
+# ---- iter_chunk_lines ----------------------------------------------------
+
+
+class _FakeOrgReport:
+ """Minimal stand-in: only `organization_id` is touched directly by
+ `iter_chunk_lines`. The rest goes through `serialize_full_org_report`,
+ which we mock per test.
+ """
+
+ def __init__(self, organization_id: str) -> None:
+ self.organization_id = organization_id
+
+
+def test_iter_chunk_lines_emits_id_and_report_with_usage_flag() -> None:
+ org_a = _FakeOrgReport("org-a")
+ org_b = _FakeOrgReport("org-b")
+
+ def fake_serialize(report, _meta) -> dict:
+ if report.organization_id == "org-a":
+ return {"event_count_in_period": 10, "has_non_zero_usage": True}
+ return {"event_count_in_period": 0, "has_non_zero_usage": False}
+
+ with patch("posthog.temporal.usage_report.aggregator.serialize_full_org_report", side_effect=fake_serialize):
+ result = list(
+ iter_chunk_lines(cast(list[OrgReport], [org_a, org_b]), instance_metadata=cast(InstanceMetadata, None))
+ )
+
+ assert result == [
+ ({"organization_id": "org-a", "usage_report": {"event_count_in_period": 10, "has_non_zero_usage": True}}, True),
+ (
+ {"organization_id": "org-b", "usage_report": {"event_count_in_period": 0, "has_non_zero_usage": False}},
+ False,
+ ),
+ ]
+
+
+def test_iter_chunk_lines_treats_missing_flag_as_falsy() -> None:
+ org = _FakeOrgReport("org-x")
+ with patch(
+ "posthog.temporal.usage_report.aggregator.serialize_full_org_report",
+ return_value={"event_count_in_period": 0}, # no has_non_zero_usage
+ ):
+ out = list(iter_chunk_lines(cast(list[OrgReport], [org]), instance_metadata=cast(InstanceMetadata, None)))
+ assert out[0][1] is False
+
+
+# ---- build_manifest ------------------------------------------------------
+
+
+def test_build_manifest_returns_typed_manifest() -> None:
+ ctx = _ctx(run_id="run-1")
+ with (
+ patch("posthog.temporal.usage_report.aggregator.settings") as mock_settings,
+ patch("posthog.temporal.usage_report.aggregator.bucket", return_value="posthog-billing-usage-reports"),
+ ):
+ mock_settings.SITE_URL = "https://us.posthog.com"
+ manifest = build_manifest(
+ ctx,
+ chunk_keys=["chunks/chunk_0000.jsonl.gz", "chunks/chunk_0001.jsonl.gz"],
+ total_orgs=12345,
+ total_orgs_with_usage=678,
+ region="US",
+ version=2,
+ )
+
+ assert isinstance(manifest, Manifest)
+ assert manifest.version == 2
+ assert manifest.run_id == "run-1"
+ assert manifest.date == "2026-05-04"
+ assert manifest.period_start == ctx.period_start
+ assert manifest.period_end == ctx.period_end
+ assert manifest.region == "US"
+ assert manifest.site_url == "https://us.posthog.com"
+ assert manifest.bucket == "posthog-billing-usage-reports"
+ assert manifest.chunk_keys == ["chunks/chunk_0000.jsonl.gz", "chunks/chunk_0001.jsonl.gz"]
+ assert manifest.chunk_count == 2
+ assert manifest.total_orgs == 12345
+ 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"]
diff --git a/posthog/temporal/tests/usage_report/test_parity.py b/posthog/temporal/tests/usage_report/test_parity.py
new file mode 100644
index 000000000000..b9ed4e517dfd
--- /dev/null
+++ b/posthog/temporal/tests/usage_report/test_parity.py
@@ -0,0 +1,222 @@
+"""Byte-compatibility parity tests between the legacy Celery serialization
+chain and the new Temporal facade functions.
+
+Both paths must produce *exactly* the same `full_report_dict` per
+organization given the same `all_data` + Postgres state, otherwise
+billing's parity validation will trip the moment we cut over.
+
+The expensive gather queries (`get_teams_with_*`) aren't exercised — the
+parity we care about is everything *after* `all_data` is materialized:
+team aggregation, org rollup, full-report serialization. Both paths
+already call the same private helpers under the hood, so this test
+guards against drift if anyone refactors one chain without the other.
+"""
+
+import json
+import dataclasses
+from datetime import UTC, datetime
+from typing import Any
+
+import pytest
+
+from posthog.models import Organization, Team
+from posthog.tasks.usage_report import (
+ InstanceMetadata,
+ _add_team_report_to_org_reports,
+ _get_full_org_usage_report,
+ _get_full_org_usage_report_as_dict,
+ _get_team_report,
+ _get_teams_for_usage_reports,
+ build_org_reports,
+ serialize_full_org_report,
+)
+from posthog.temporal.usage_report.aggregator import iter_chunk_lines
+from posthog.temporal.usage_report.queries import QUERIES
+
+
+def _all_destination_keys() -> list[str]:
+ """Every key `_get_team_report` reads, derived from the registry so we
+ don't have to keep the test in sync with the spec list by hand.
+ """
+ keys: list[str] = []
+ for spec in QUERIES:
+ if spec.output == "multi":
+ keys.extend(spec.multi_keys_mapping.values())
+ else:
+ keys.append(spec.name)
+ return keys
+
+
+def _instance_metadata() -> InstanceMetadata:
+ return InstanceMetadata(
+ deployment_infrastructure="test",
+ realm="cloud",
+ period={
+ "start_inclusive": "2026-05-04T00:00:00+00:00",
+ "end_inclusive": "2026-05-04T23:59:59.999999+00:00",
+ },
+ site_url="https://us.posthog.com",
+ product="cloud",
+ helm=None,
+ clickhouse_version=None,
+ users_who_logged_in=None,
+ users_who_logged_in_count=None,
+ users_who_signed_up=None,
+ users_who_signed_up_count=None,
+ table_sizes=None,
+ plugins_installed=None,
+ plugins_enabled=None,
+ instance_tag="test-tag",
+ )
+
+
+def _seed_all_data(team_a_id: int, team_b_id: int, team_c_id: int) -> dict[str, dict[int, int]]:
+ """A non-trivial `all_data` covering several destination keys.
+
+ Realistic enough to prove the team→org rollup math is identical:
+ different team distributions per metric, some teams missing from
+ some metrics, and at least one org with multiple teams summed. All
+ other destination keys (derived from the registry) get an empty
+ dict so `_get_team_report`'s lookups don't KeyError.
+ """
+ interesting: dict[str, dict[int, int]] = {
+ "teams_with_event_count_in_period": {team_a_id: 100, team_b_id: 50, team_c_id: 25},
+ "teams_with_enhanced_persons_event_count_in_period": {team_a_id: 80, team_b_id: 40},
+ "teams_with_recording_count_in_period": {team_a_id: 8, team_c_id: 3},
+ "teams_with_recording_bytes_in_period": {team_a_id: 1_234_567, team_c_id: 89_012},
+ "teams_with_decide_requests_count_in_period": {team_a_id: 1_000, team_b_id: 200, team_c_id: 50},
+ "teams_with_local_evaluation_requests_count_in_period": {team_b_id: 5},
+ "teams_with_dashboard_count": {team_a_id: 4, team_b_id: 2, team_c_id: 1},
+ "teams_with_ff_count": {team_a_id: 7, team_b_id: 3},
+ "teams_with_survey_count": {team_a_id: 1, team_c_id: 2},
+ "teams_with_web_events_count_in_period": {team_a_id: 60, team_b_id: 30},
+ "teams_with_exceptions_captured_in_period": {team_a_id: 5, team_b_id: 1},
+ "teams_with_web_exceptions_captured_in_period": {team_a_id: 5},
+ "teams_with_node_exceptions_captured_in_period": {team_b_id: 1},
+ "teams_with_api_queries_count": {team_a_id: 10},
+ "teams_with_api_queries_read_bytes": {team_a_id: 1_500_000},
+ }
+ return {key: interesting.get(key, {}) for key in _all_destination_keys()}
+
+
+def _celery_serialize(team_a_id: int, team_b_id: int, team_c_id: int, period_start: datetime) -> dict[str, Any]:
+ """Walk the same private helpers `send_all_org_usage_reports` uses,
+ then serialize the same way `capture_report` / `_queue_report` see it.
+ """
+ all_data = _seed_all_data(team_a_id, team_b_id, team_c_id)
+ instance_metadata = _instance_metadata()
+ org_reports: dict[str, Any] = {}
+ 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)
+ return {
+ org_id: _get_full_org_usage_report_as_dict(_get_full_org_usage_report(report, instance_metadata))
+ for org_id, report in org_reports.items()
+ }
+
+
+def _temporal_serialize(team_a_id: int, team_b_id: int, team_c_id: int, period_start: datetime) -> dict[str, Any]:
+ """Walk the public facade functions the Temporal aggregation activity
+ uses (`build_org_reports` → `serialize_full_org_report`).
+ """
+ all_data = _seed_all_data(team_a_id, team_b_id, team_c_id)
+ instance_metadata = _instance_metadata()
+ org_reports = build_org_reports(all_data, period_start)
+ return {org_id: serialize_full_org_report(report, instance_metadata) for org_id, report in org_reports.items()}
+
+
+def test_serialization_parity_celery_vs_temporal() -> None:
+ """The full per-org dict billing consumes must be identical between
+ the Celery and Temporal paths for any given `all_data` snapshot.
+
+ Two orgs × three teams (org_a has two teams so we exercise the
+ multi-team rollup; org_b has one). If this drifts, billing's parity
+ validation will explode — fix the divergent helper, not the test.
+ """
+ org_a = Organization.objects.create(name="Parity Org A")
+ org_b = Organization.objects.create(name="Parity Org 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")
+
+ period_start = datetime(2026, 5, 4, 0, 0, 0, tzinfo=UTC)
+
+ celery_dicts = _celery_serialize(team_a1.id, team_a2.id, team_b.id, period_start)
+ temporal_dicts = _temporal_serialize(team_a1.id, team_a2.id, team_b.id, period_start)
+
+ # Both paths must produce the same set of organizations.
+ assert set(celery_dicts.keys()) == set(temporal_dicts.keys())
+
+ # And the same dict per org — compare via JSON to fail loudly on any
+ # drift (unhashable types, ordering of nested dicts, etc.).
+ for org_id in celery_dicts:
+ celery_json = json.dumps(celery_dicts[org_id], sort_keys=True, default=str)
+ temporal_json = json.dumps(temporal_dicts[org_id], sort_keys=True, default=str)
+ assert celery_json == temporal_json, (
+ f"Drift between Celery and Temporal serialization for org {org_id}.\n"
+ f"Celery diff:\n{celery_json[:500]}\n"
+ f"Temporal diff:\n{temporal_json[:500]}"
+ )
+
+ # Sanity check: the rollup math is non-trivial — org_a has two teams,
+ # so its event_count_in_period should be the sum.
+ assert temporal_dicts[str(org_a.id)]["event_count_in_period"] == 100 + 50 # team_a1 + team_a2
+ assert temporal_dicts[str(org_b.id)]["event_count_in_period"] == 25 # team_b only
+
+
+def test_iter_chunk_lines_matches_celery_serialization() -> None:
+ """The aggregation activity ends up writing JSONL lines via
+ `iter_chunk_lines`. That function should yield the same per-org
+ `usage_report` dict the Celery `_queue_report` would have built.
+
+ The shared test DB may have pre-seeded orgs; we don't care how many
+ rows come out, only that the row for *our* org matches between the
+ two paths.
+ """
+ org = Organization.objects.create(name="Parity Iter Org")
+ team = Team.objects.create(organization=org, name="Solo")
+
+ period_start = datetime(2026, 5, 4, 0, 0, 0, tzinfo=UTC)
+ all_data = _seed_all_data(team.id, team.id, team.id)
+ instance_metadata = _instance_metadata()
+
+ celery_dicts = _celery_serialize(team.id, team.id, team.id, period_start)
+
+ org_reports = build_org_reports(all_data, period_start)
+ assert str(org.id) in org_reports
+
+ lines_by_org = {
+ line["organization_id"]: (line, has_usage)
+ for line, has_usage in iter_chunk_lines(org_reports.values(), instance_metadata)
+ }
+ assert str(org.id) in lines_by_org
+ line, has_usage = lines_by_org[str(org.id)]
+ assert has_usage is True
+ assert line["usage_report"] == celery_dicts[str(org.id)]
+
+
+def test_build_org_reports_matches_legacy_loop() -> None:
+ """Spot-check that the public `build_org_reports` facade returns
+ the same `OrgReport` dataclass the legacy in-line loop produced for
+ a given org. Other orgs in the shared test DB are ignored.
+ """
+ org = Organization.objects.create(name="Facade Parity Org")
+ team_1 = Team.objects.create(organization=org, name="One")
+ team_2 = Team.objects.create(organization=org, name="Two")
+
+ period_start = datetime(2026, 5, 4, 0, 0, 0, tzinfo=UTC)
+ all_data = _seed_all_data(team_1.id, team_2.id, team_1.id)
+
+ legacy: dict[str, Any] = {}
+ for team in _get_teams_for_usage_reports():
+ team_report = _get_team_report(all_data, team)
+ _add_team_report_to_org_reports(legacy, team, team_report, period_start)
+
+ facade = build_org_reports(all_data, period_start)
+
+ assert str(org.id) in legacy
+ assert str(org.id) in facade
+ assert dataclasses.asdict(legacy[str(org.id)]) == dataclasses.asdict(facade[str(org.id)])
diff --git a/posthog/temporal/tests/usage_report/test_pointer_activity.py b/posthog/temporal/tests/usage_report/test_pointer_activity.py
new file mode 100644
index 000000000000..452d4cb2f49f
--- /dev/null
+++ b/posthog/temporal/tests/usage_report/test_pointer_activity.py
@@ -0,0 +1,172 @@
+"""Tests for `enqueue_pointer_message` — the activity that sends the
+single SQS pointer to billing.
+
+We mock the SQS producer so the test verifies (a) the queue name we route
+to, (b) the exact JSON body shape billing will read, and (c) the message
+attributes.
+"""
+
+import json
+from datetime import UTC, datetime
+from typing import Any
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from django.conf import settings
+
+from posthog.temporal.usage_report.activities import SQS_POINTER_VERSION, SQS_QUEUE_NAME, enqueue_pointer_message
+from posthog.temporal.usage_report.types import AggregateResult, EnqueuePointerInputs, WorkflowContext
+
+
+def _ctx() -> WorkflowContext:
+ return WorkflowContext(
+ run_id="run-test",
+ period_start=datetime(2026, 5, 4, 0, 0, 0, tzinfo=UTC),
+ period_end=datetime(2026, 5, 4, 23, 59, 59, 999999, tzinfo=UTC),
+ date_str="2026-05-04",
+ )
+
+
+def _agg() -> AggregateResult:
+ return AggregateResult(
+ chunk_keys=[
+ "tasks/billing/usage_reports/2026-05-04/run-test/chunks/chunk_0000.jsonl.gz",
+ "tasks/billing/usage_reports/2026-05-04/run-test/chunks/chunk_0001.jsonl.gz",
+ ],
+ manifest_key="tasks/billing/usage_reports/2026-05-04/run-test/manifest.json",
+ total_orgs=12345,
+ total_orgs_with_usage=678,
+ )
+
+
+async def test_pointer_uses_v2_queue_and_correct_payload(activity_environment) -> None:
+ """End-to-end activity test: sends to `usage_reports_v2` with the
+ expected pointer body and metadata attributes.
+ """
+ captured: dict[str, Any] = {}
+ fake_producer = MagicMock()
+ fake_producer.send_message.return_value = {"MessageId": "abc"}
+
+ def fake_get_producer(queue_name):
+ captured["queue_name"] = queue_name
+ return fake_producer
+
+ with (
+ patch("posthog.temporal.usage_report.activities.settings") as mock_settings,
+ patch("posthog.temporal.usage_report.activities.bucket", return_value="posthog-billing-usage-reports"),
+ patch("ee.sqs.SQSProducer.get_sqs_producer", side_effect=fake_get_producer),
+ patch("posthog.temporal.usage_report.activities.get_instance_region", return_value="US"),
+ ):
+ mock_settings.EE_AVAILABLE = True
+ mock_settings.SITE_URL = "https://us.posthog.com"
+
+ await activity_environment.run(
+ enqueue_pointer_message,
+ EnqueuePointerInputs(ctx=_ctx(), aggregate=_agg()),
+ )
+
+ # Routed to the new dedicated queue
+ assert captured["queue_name"] == "usage_reports_v2"
+ assert SQS_QUEUE_NAME == "usage_reports_v2"
+
+ fake_producer.send_message.assert_called_once()
+ call_kwargs = fake_producer.send_message.call_args.kwargs
+
+ # Body has every field billing reads
+ body = json.loads(call_kwargs["message_body"])
+ assert body == {
+ "version": SQS_POINTER_VERSION,
+ "run_id": "run-test",
+ "date": "2026-05-04",
+ "period_start": "2026-05-04T00:00:00+00:00",
+ "period_end": "2026-05-04T23:59:59.999999+00:00",
+ "region": "US",
+ "site_url": "https://us.posthog.com",
+ "bucket": "posthog-billing-usage-reports",
+ "manifest_key": "tasks/billing/usage_reports/2026-05-04/run-test/manifest.json",
+ "chunk_prefix": "tasks/billing/usage_reports/2026-05-04/run-test/chunks/",
+ "chunk_count": 2,
+ "total_orgs": 12345,
+ "total_orgs_with_usage": 678,
+ }
+
+ # Metadata attributes carry routing/versioning info billing keys off
+ assert call_kwargs["message_attributes"] == {
+ "content_type": "application/json",
+ "schema_version": str(SQS_POINTER_VERSION),
+ "run_id": "run-test",
+ }
+
+
+async def test_pointer_skipped_when_ee_unavailable(activity_environment) -> None:
+ """Self-hosted (no EE) → activity is a no-op, no SQS import or call."""
+ fake_producer = MagicMock()
+
+ with (
+ patch("posthog.temporal.usage_report.activities.settings") as mock_settings,
+ patch("ee.sqs.SQSProducer.get_sqs_producer", return_value=fake_producer) as get_producer,
+ ):
+ mock_settings.EE_AVAILABLE = False
+
+ await activity_environment.run(
+ enqueue_pointer_message,
+ EnqueuePointerInputs(ctx=_ctx(), aggregate=_agg()),
+ )
+
+ get_producer.assert_not_called()
+ fake_producer.send_message.assert_not_called()
+
+
+async def test_pointer_raises_when_producer_misconfigured(activity_environment) -> None:
+ """If `get_sqs_producer` returns None we should fail loudly (so Temporal
+ retries) rather than silently drop the pointer.
+ """
+ with (
+ patch("posthog.temporal.usage_report.activities.settings") as mock_settings,
+ patch("posthog.temporal.usage_report.activities.bucket", return_value="posthog"),
+ patch("ee.sqs.SQSProducer.get_sqs_producer", return_value=None),
+ ):
+ mock_settings.EE_AVAILABLE = True
+ mock_settings.SITE_URL = "https://us.posthog.com"
+
+ with pytest.raises(Exception, match="usage_reports_v2"):
+ await activity_environment.run(
+ enqueue_pointer_message,
+ EnqueuePointerInputs(ctx=_ctx(), aggregate=_agg()),
+ )
+
+
+async def test_pointer_raises_when_send_returns_none(activity_environment) -> None:
+ """`send_message` returning `None` indicates an SQS error — must raise
+ so Temporal retries.
+ """
+ fake_producer = MagicMock()
+ fake_producer.send_message.return_value = None
+
+ with (
+ patch("posthog.temporal.usage_report.activities.settings") as mock_settings,
+ patch("posthog.temporal.usage_report.activities.bucket", return_value="posthog"),
+ patch("ee.sqs.SQSProducer.get_sqs_producer", return_value=fake_producer),
+ patch("posthog.temporal.usage_report.activities.get_instance_region", return_value="US"),
+ ):
+ mock_settings.EE_AVAILABLE = True
+ mock_settings.SITE_URL = "https://us.posthog.com"
+
+ with pytest.raises(Exception, match="no response"):
+ await activity_environment.run(
+ enqueue_pointer_message,
+ EnqueuePointerInputs(ctx=_ctx(), aggregate=_agg()),
+ )
+
+
+def test_v2_queue_is_configured_in_settings() -> None:
+ queues = getattr(settings, "SQS_QUEUES", {})
+ assert SQS_QUEUE_NAME in queues, (
+ f"Queue {SQS_QUEUE_NAME!r} must be declared in settings.SQS_QUEUES — "
+ f"otherwise the pointer activity raises after S3 work is done"
+ )
diff --git a/posthog/temporal/tests/usage_report/test_queries_registry.py b/posthog/temporal/tests/usage_report/test_queries_registry.py
new file mode 100644
index 000000000000..a1a684046038
--- /dev/null
+++ b/posthog/temporal/tests/usage_report/test_queries_registry.py
@@ -0,0 +1,115 @@
+"""Static validity checks for the QuerySpec registry.
+
+These run cheaply and catch the kind of refactoring mistakes that would
+otherwise only surface during an aggregation activity in production:
+duplicated names, multi specs without mappings, two specs writing to the
+same destination key, etc.
+"""
+
+import inspect
+
+from posthog.temporal.usage_report.queries import QUERIES, QUERY_INDEX
+
+
+def _required_arg_count(fn) -> int:
+ """Count positional/positional-or-keyword params with no default."""
+ sig = inspect.signature(fn)
+ return sum(
+ 1
+ for p in sig.parameters.values()
+ if p.default is inspect.Parameter.empty
+ and p.kind in (inspect.Parameter.POSITIONAL_ONLY, inspect.Parameter.POSITIONAL_OR_KEYWORD)
+ )
+
+
+def test_query_index_matches_queries_list() -> None:
+ assert len(QUERY_INDEX) == len(QUERIES)
+ for spec in QUERIES:
+ assert QUERY_INDEX[spec.name] is spec
+
+
+def test_query_names_are_unique() -> None:
+ names = [spec.name for spec in QUERIES]
+ duplicates = {name for name in names if names.count(name) > 1}
+ assert not duplicates, f"Duplicate spec names: {duplicates}"
+
+
+def test_multi_specs_have_non_empty_mapping() -> None:
+ for spec in QUERIES:
+ if spec.output == "multi":
+ assert spec.multi_keys_mapping, f"Multi spec {spec.name!r} has no multi_keys_mapping"
+
+
+def test_single_specs_have_no_mapping() -> None:
+ for spec in QUERIES:
+ if spec.output == "single":
+ assert not spec.multi_keys_mapping, (
+ f"Single spec {spec.name!r} has a multi_keys_mapping; either remove it or change output to 'multi'"
+ )
+
+
+def test_destination_keys_are_unique_across_registry() -> None:
+ """Each destination key in `all_data` must be produced by exactly one
+ spec — otherwise the aggregator overwrites a real result with another
+ one and we silently lose a metric.
+ """
+ destinations: dict[str, str] = {}
+ for spec in QUERIES:
+ keys = list(spec.multi_keys_mapping.values()) if spec.output == "multi" else [spec.name]
+ for key in keys:
+ assert key not in destinations, (
+ f"Destination key {key!r} produced by both {destinations[key]!r} and {spec.name!r}"
+ )
+ destinations[key] = spec.name
+
+
+def test_kind_is_period_or_snapshot() -> None:
+ for spec in QUERIES:
+ assert spec.kind in {"period", "snapshot"}, f"Spec {spec.name!r} has unexpected kind {spec.kind!r}"
+
+
+def test_snapshot_quarantine_disclaimer_lives_in_module() -> None:
+ """The whole `kind="snapshot"` mechanism only makes sense alongside the
+ explanatory disclaimer at the top of the module. If anyone strips the
+ docstring this guard tells them why it matters.
+ """
+ import posthog.temporal.usage_report.queries as queries_module
+
+ assert queries_module.__doc__ is not None
+ assert "snapshot" in queries_module.__doc__.lower()
+ assert "re-run safe" in queries_module.__doc__.lower()
+
+
+def test_period_specs_outnumber_snapshot_specs() -> None:
+ """Sanity check: most of the report is event-driven and period-based.
+ If this flips, something has gone wrong with the registry.
+ """
+ period_count = sum(1 for spec in QUERIES if spec.kind == "period")
+ snapshot_count = sum(1 for spec in QUERIES if spec.kind == "snapshot")
+ assert period_count > snapshot_count, f"Period={period_count} Snapshot={snapshot_count}"
+
+
+def test_period_specs_take_begin_and_end() -> None:
+ """`kind='period'` specs must accept (begin, end). The activity passes
+ them through; if a fn doesn't take them we'd silently drop the period.
+ """
+ for spec in QUERIES:
+ if spec.kind == "period":
+ required = _required_arg_count(spec.fn)
+ assert required == 2, (
+ f"Period spec {spec.name!r} fn must take exactly 2 required args (begin, end); got {required}"
+ )
+
+
+def test_snapshot_specs_take_no_args() -> None:
+ """`kind='snapshot'` specs must take zero args — they read current
+ state and the period would be misleading. Forcing zero args means
+ 'fix this snapshot to honor the period' is a typed migration.
+ """
+ for spec in QUERIES:
+ if spec.kind == "snapshot":
+ required = _required_arg_count(spec.fn)
+ assert required == 0, (
+ f"Snapshot spec {spec.name!r} fn must take zero required args; got {required}. "
+ "If this query needs the period, change kind to 'period'."
+ )
diff --git a/posthog/temporal/tests/usage_report/test_query_activity.py b/posthog/temporal/tests/usage_report/test_query_activity.py
new file mode 100644
index 000000000000..330acceb2123
--- /dev/null
+++ b/posthog/temporal/tests/usage_report/test_query_activity.py
@@ -0,0 +1,125 @@
+"""Tests for `run_query_to_s3` — the per-query gather activity.
+
+The dispatch path (period vs snapshot) and result persistence are
+verified end-to-end against real MinIO via the `minio_workflow_ctx`
+fixture; only the failure-propagation test mocks `object_storage.write`
+so we can assert it was *never* called.
+"""
+
+import json
+from datetime import datetime
+
+import pytest
+from unittest.mock import patch
+
+from posthog.storage import object_storage
+from posthog.temporal.usage_report import storage
+from posthog.temporal.usage_report.activities import run_query_to_s3
+from posthog.temporal.usage_report.queries import QuerySpec
+from posthog.temporal.usage_report.storage import queries_key
+from posthog.temporal.usage_report.types import RunQueryToS3Inputs, WorkflowContext
+
+
+async def test_run_query_to_s3_calls_fn_with_period_and_writes_to_s3(
+ minio_workflow_ctx: WorkflowContext, activity_environment
+) -> None:
+ """Period specs receive (begin, end) and the result lands in MinIO."""
+ seen_periods: list[tuple[datetime, datetime]] = []
+
+ def fake_query(begin: datetime, end: datetime) -> list[tuple[int, int]]:
+ seen_periods.append((begin, end))
+ return [(1, 100), (2, 50)]
+
+ fake_spec = QuerySpec(name="test_query_metric", fn=fake_query)
+
+ with patch.dict(
+ "posthog.temporal.usage_report.activities.QUERY_INDEX",
+ {"test_query_metric": fake_spec},
+ clear=False,
+ ):
+ result = await activity_environment.run(
+ run_query_to_s3,
+ RunQueryToS3Inputs(ctx=minio_workflow_ctx, query_name="test_query_metric"),
+ )
+
+ # Period passed through verbatim from WorkflowContext.
+ assert seen_periods == [(minio_workflow_ctx.period_start, minio_workflow_ctx.period_end)]
+
+ # Result advertises the right key + name; duration is non-negative.
+ assert result.query_name == "test_query_metric"
+ assert result.s3_key == queries_key(minio_workflow_ctx, "test_query_metric")
+ assert result.duration_ms >= 0
+
+ # And the returned key actually has the rows in MinIO.
+ body = object_storage.read_bytes(result.s3_key, bucket=storage.bucket())
+ assert body is not None
+ # `default=str` coerces tuples to lists during JSON encoding.
+ assert json.loads(body) == [[1, 100], [2, 50]]
+
+
+async def test_run_query_to_s3_snapshot_kind_calls_fn_without_period(
+ minio_workflow_ctx: WorkflowContext, activity_environment
+) -> None:
+ """Snapshot specs declare zero-arg fns — the activity must dispatch
+ them without the period, otherwise we'd get a TypeError.
+ """
+ fn_args: list[tuple] = []
+
+ def fake_snapshot_query() -> list[dict[str, int]]:
+ fn_args.append(())
+ return [{"team_id": 1, "total": 7}]
+
+ fake_spec = QuerySpec(
+ name="test_snapshot_count",
+ fn=fake_snapshot_query,
+ kind="snapshot",
+ )
+
+ with patch.dict(
+ "posthog.temporal.usage_report.activities.QUERY_INDEX",
+ {"test_snapshot_count": fake_spec},
+ clear=False,
+ ):
+ result = await activity_environment.run(
+ run_query_to_s3,
+ RunQueryToS3Inputs(ctx=minio_workflow_ctx, query_name="test_snapshot_count"),
+ )
+
+ assert fn_args == [()], "Snapshot fn should be invoked with no positional args"
+ assert result.query_name == "test_snapshot_count"
+ body = object_storage.read_bytes(result.s3_key, bucket=storage.bucket())
+ assert body is not None
+ assert json.loads(body) == [{"team_id": 1, "total": 7}]
+
+
+async def test_run_query_to_s3_propagates_query_failure(
+ minio_workflow_ctx: WorkflowContext, activity_environment
+) -> None:
+ """If the underlying query raises, the activity must raise and not
+ write a partial / stale object — otherwise re-runs would skip the
+ gather. We mock `write` so we can assert it was *never* called.
+ """
+
+ def boom(begin: datetime, end: datetime) -> None:
+ raise RuntimeError("boom")
+
+ fake_spec = QuerySpec(name="test_failing_query", fn=boom)
+
+ with (
+ patch.dict(
+ "posthog.temporal.usage_report.activities.QUERY_INDEX",
+ {"test_failing_query": fake_spec},
+ clear=False,
+ ),
+ patch("posthog.temporal.usage_report.storage.object_storage.write") as mock_write,
+ ):
+ with pytest.raises(Exception, match="boom"):
+ await activity_environment.run(
+ run_query_to_s3,
+ RunQueryToS3Inputs(ctx=minio_workflow_ctx, query_name="test_failing_query"),
+ )
+
+ mock_write.assert_not_called()
diff --git a/posthog/temporal/tests/usage_report/test_schedule.py b/posthog/temporal/tests/usage_report/test_schedule.py
new file mode 100644
index 000000000000..d7570a95388b
--- /dev/null
+++ b/posthog/temporal/tests/usage_report/test_schedule.py
@@ -0,0 +1,90 @@
+"""Regression tests for `create_run_usage_reports_schedule`.
+
+The previous version of this code passed `dataclasses.asdict(...)` on
+`RunUsageReportsInputs` *after* it was migrated to pydantic — that
+silently raised `TypeError` the first time the worker registered the
+schedule, and *no* test caught it because nothing in the suite ever
+imported and called the schedule-creation function.
+
+These tests close that gap: they actually invoke the function with a
+mocked client and assert it (a) doesn't raise and (b) hands Temporal a
+JSON-serializable input.
+"""
+
+import json
+
+import pytest
+from unittest.mock import AsyncMock, MagicMock, patch
+
+
+async def test_create_run_usage_reports_schedule_does_not_raise() -> None:
+ """The schedule-builder must not blow up when called — covers both the
+ `a_schedule_exists is False` (create) and `True` (update) branches.
+ """
+ from posthog.temporal.schedule import create_run_usage_reports_schedule
+
+ client = MagicMock()
+
+ # First-time registration: schedule doesn't exist → `a_create_schedule` runs.
+ with (
+ patch("posthog.temporal.schedule.a_schedule_exists", new=AsyncMock(return_value=False)),
+ patch("posthog.temporal.schedule.a_create_schedule", new=AsyncMock()) as create_mock,
+ patch("posthog.temporal.schedule.a_update_schedule", new=AsyncMock()) as update_mock,
+ ):
+ await create_run_usage_reports_schedule(client)
+ create_mock.assert_awaited_once()
+ update_mock.assert_not_awaited()
+
+ # Re-registration: schedule already exists → `a_update_schedule` runs.
+ with (
+ patch("posthog.temporal.schedule.a_schedule_exists", new=AsyncMock(return_value=True)),
+ patch("posthog.temporal.schedule.a_create_schedule", new=AsyncMock()) as create_mock,
+ patch("posthog.temporal.schedule.a_update_schedule", new=AsyncMock()) as update_mock,
+ ):
+ await create_run_usage_reports_schedule(client)
+ update_mock.assert_awaited_once()
+ create_mock.assert_not_awaited()
+
+
+async def test_run_usage_reports_schedule_input_is_json_serializable() -> None:
+ """Temporal serializes the `ScheduleActionStartWorkflow` input via the
+ data converter. Even with the pydantic data converter, JSON-encoding
+ must round-trip — otherwise registration fails the moment it hits
+ the wire. Catches the original `dataclasses.asdict(pydantic_model)`
+ bug that landed on this branch.
+ """
+ from posthog.temporal.schedule import create_run_usage_reports_schedule
+
+ captured: dict = {}
+
+ async def fake_create_schedule(client, schedule_id, schedule, trigger_immediately=False):
+ captured["schedule_id"] = schedule_id
+ captured["schedule"] = schedule
+
+ with (
+ patch("posthog.temporal.schedule.a_schedule_exists", new=AsyncMock(return_value=False)),
+ patch("posthog.temporal.schedule.a_create_schedule", new=fake_create_schedule),
+ ):
+ await create_run_usage_reports_schedule(MagicMock())
+
+ assert captured["schedule_id"] == "run-usage-reports-schedule"
+
+ # Pull the args out of the schedule action — Temporal stores positional
+ # args as a list; the workflow input lives at index 0.
+ action = captured["schedule"].action
+ raw_input = action.args[0]
+ assert isinstance(raw_input, dict), f"input must be a JSON-serializable dict, got {type(raw_input).__name__}"
+
+ # The whole point: this should round-trip through json without exploding.
+ encoded = json.dumps(raw_input)
+ decoded = json.loads(encoded)
+ assert decoded == raw_input
+
+ # And the workflow input model must accept the dict back.
+ from posthog.temporal.usage_report.types import RunUsageReportsInputs
+
+ revived = RunUsageReportsInputs(**decoded)
+ assert revived.organization_ids is None
+ assert revived.at is None
diff --git a/posthog/temporal/tests/usage_report/test_storage.py b/posthog/temporal/tests/usage_report/test_storage.py
new file mode 100644
index 000000000000..05608176f843
--- /dev/null
+++ b/posthog/temporal/tests/usage_report/test_storage.py
@@ -0,0 +1,235 @@
+"""Tests for the usage report S3 helpers.
+
+Pure key-formatting tests don't touch storage. Roundtrip and writer tests
+hit the real MinIO instance configured for the dev stack — the
+`minio_workflow_ctx` fixture cleans up its run prefix at teardown so
+the bucket stays tidy. Error-path tests (failed delete, exception
+during stream) stay mocked because MinIO won't naturally trigger them.
+"""
+
+import gzip
+import json
+
+import pytest
+from unittest.mock import patch
+
+from posthog.storage import object_storage
+from posthog.temporal.usage_report import storage
+from posthog.temporal.usage_report.storage import (
+ chunk_key,
+ chunks_prefix,
+ delete_keys,
+ manifest_key,
+ queries_key,
+ queries_prefix,
+ run_prefix,
+ streamed_jsonl_gzip_writer,
+ write_json,
+ write_jsonl_chunk_gzip,
+)
+from posthog.temporal.usage_report.types import WorkflowContext
+
+
+def _ctx(run_id: str = "abc-123", date_str: str = "2026-05-04") -> WorkflowContext:
+ from datetime import UTC, datetime
+
+ return WorkflowContext(
+ run_id=run_id,
+ period_start=datetime(2026, 5, 4, 0, 0, 0, tzinfo=UTC),
+ period_end=datetime(2026, 5, 4, 23, 59, 59, 999999, tzinfo=UTC),
+ date_str=date_str,
+ )
+
+
+# ---- key formatting (pure) -----------------------------------------------
+
+
+def test_run_prefix_includes_date_and_run_id() -> None:
+ ctx = _ctx()
+ prefix = run_prefix(ctx)
+ assert prefix.endswith("/billing/usage_reports/2026-05-04/abc-123")
+
+
+def test_queries_key_uses_query_name() -> None:
+ ctx = _ctx()
+ assert queries_key(ctx, "teams_with_event_count_in_period").endswith(
+ "/queries/teams_with_event_count_in_period.json"
+ )
+
+
+def test_chunk_key_zero_padded() -> None:
+ ctx = _ctx()
+ assert chunk_key(ctx, 0).endswith("/chunks/chunk_0000.jsonl.gz")
+ assert chunk_key(ctx, 12).endswith("/chunks/chunk_0012.jsonl.gz")
+
+
+def test_manifest_key() -> None:
+ ctx = _ctx()
+ assert manifest_key(ctx).endswith("/abc-123/manifest.json")
+
+
+def test_queries_and_chunks_prefix() -> None:
+ ctx = _ctx()
+ assert queries_prefix(ctx).endswith("/abc-123/queries")
+ assert chunks_prefix(ctx).endswith("/abc-123/chunks")
+
+
+def test_bucket_reads_billing_setting() -> None:
+ """`bucket()` reflects the dedicated billing bucket setting."""
+ with patch("posthog.temporal.usage_report.storage.settings") as mock_settings:
+ mock_settings.BILLING_USAGE_REPORTS_S3_BUCKET = "posthog-billing-usage-reports"
+ assert storage.bucket() == "posthog-billing-usage-reports"
+
+
+# ---- real MinIO roundtrips -----------------------------------------------
+
+
+def test_write_json_roundtrip_via_minio(minio_workflow_ctx: WorkflowContext) -> None:
+ key = queries_key(minio_workflow_ctx, "teams_with_event_count_in_period")
+ payload = {"data": [(1, 100), (2, 50)], "meta": {"version": 1}}
+
+ write_json(key, payload)
+
+ decoded = storage.read_json(key)
+ # `default=str` coerces tuples to lists during JSON encoding.
+ assert decoded == {"data": [[1, 100], [2, 50]], "meta": {"version": 1}}
+
+
+def test_write_jsonl_chunk_gzip_roundtrip_via_minio(minio_workflow_ctx: WorkflowContext) -> None:
+ """End-to-end: gzipped JSONL written via the helper is downloadable
+ and decompresses to the original lines.
+ """
+ key = chunk_key(minio_workflow_ctx, 0)
+ lines = [
+ {"organization_id": "org-1", "usage_report": {"event_count_in_period": 1}},
+ {"organization_id": "org-2", "usage_report": {"event_count_in_period": 2}},
+ {"organization_id": "org-3", "usage_report": {"event_count_in_period": 3}},
+ ]
+
+ count = write_jsonl_chunk_gzip(key, lines)
+
+ assert count == 3
+ body = object_storage.read_bytes(key, bucket=storage.bucket())
+ assert body is not None
+ decompressed = gzip.decompress(body).decode("utf-8")
+ decoded = [json.loads(line) for line in decompressed.splitlines()]
+ assert decoded == lines
+
+
+def test_write_jsonl_chunk_gzip_sets_content_headers_via_minio(minio_workflow_ctx: WorkflowContext) -> None:
+ """The chunk object must land with `application/x-ndjson` + `gzip`
+ encoding so billing's S3 reader can stream-decompress it.
+ """
+ key = chunk_key(minio_workflow_ctx, 0)
+ write_jsonl_chunk_gzip(key, [{"organization_id": "org-1"}])
+
+ head = object_storage.head_object(key, bucket=storage.bucket())
+ assert head is not None
+ assert head["ContentType"] == "application/x-ndjson"
+ assert head["ContentEncoding"] == "gzip"
+
+
+async def test_streamed_jsonl_gzip_writer_uploads_on_clean_exit_via_minio(
+ minio_workflow_ctx: WorkflowContext,
+) -> None:
+ """Async ctx-mgr happy path: lines written, gzip streamed to MinIO."""
+ key = chunk_key(minio_workflow_ctx, 0)
+
+ async with streamed_jsonl_gzip_writer(key) as w:
+ w.write({"organization_id": "org-1"})
+ w.write_lines([{"organization_id": "org-2"}, {"organization_id": "org-3"}])
+ assert w.line_count == 3
+
+ body = object_storage.read_bytes(key, bucket=storage.bucket())
+ assert body is not None
+ rows = [json.loads(line) for line in gzip.decompress(body).decode("utf-8").splitlines()]
+ assert rows == [
+ {"organization_id": "org-1"},
+ {"organization_id": "org-2"},
+ {"organization_id": "org-3"},
+ ]
+
+
+async def test_streamed_jsonl_gzip_writer_skips_upload_on_exception_via_minio(
+ minio_workflow_ctx: WorkflowContext,
+) -> None:
+ """If the body raises, we must not upload a partial chunk."""
+ key = chunk_key(minio_workflow_ctx, 0)
+
+ with pytest.raises(RuntimeError, match="boom"):
+ async with streamed_jsonl_gzip_writer(key) as w:
+ w.write({"organization_id": "org-1"})
+ raise RuntimeError("boom")
+
+ # head_object swallows NoSuchKey and returns None
+ assert object_storage.head_object(key, bucket=storage.bucket()) is None
+
+
+# ---- mocked error paths --------------------------------------------------
+# MinIO doesn't error on `delete` of a missing key, so the failure-handling
+# branch in `delete_keys` is exercised with a mock — there's no way to
+# trigger it against real S3 short of taking the bucket offline.
+
+
+def test_jsonl_gzip_writer_batches_writes_to_gzip_stream() -> None:
+ """Lines should accumulate into the local pending buffer until the
+ flush threshold is crossed, *then* be handed to the gzip stream in
+ one larger chunk — that's what trims the per-line overhead.
+ """
+ from posthog.temporal.usage_report.storage import JsonlGzipWriter
+
+ # 100-byte threshold so a small test still exercises multiple flushes.
+ writer = JsonlGzipWriter(flush_threshold_bytes=100)
+ gz_write_sizes: list[int] = []
+
+ def record_write(payload: bytes) -> int:
+ gz_write_sizes.append(len(payload))
+ return len(payload)
+
+ with patch.object(writer._gz, "write", side_effect=record_write):
+ # 8 lines of ~38 bytes ≈ 300 bytes → expect at least 2 threshold-driven flushes.
+ for i in range(8):
+ writer.write({"line": i, "padding": "x" * 20})
+ flushes_during_writes = len(gz_write_sizes)
+ assert flushes_during_writes >= 2, "should flush when the pending buffer crosses the threshold"
+ assert all(size >= 100 for size in gz_write_sizes), "every threshold-driven flush must clear the threshold"
+
+ # Final flush should drain whatever's still pending, then a second
+ # flush is a no-op.
+ writer._flush_pending()
+ after_first_finalize = len(gz_write_sizes)
+ writer._flush_pending()
+ assert len(gz_write_sizes) == after_first_finalize, "no extra gzip.write when nothing is pending"
+
+ assert writer.line_count == 8
+
+
+def test_delete_keys_continues_on_failure() -> None:
+ calls: list[str] = []
+
+ def fake_delete(key, bucket=None):
+ calls.append(key)
+ if key == "fail":
+ raise RuntimeError("boom")
+
+ with patch("posthog.temporal.usage_report.storage.object_storage.delete", side_effect=fake_delete):
+ deleted = delete_keys(["one", "fail", "two"])
+
+ assert calls == ["one", "fail", "two"]
+ assert deleted == 2
+
+
+def test_delete_keys_via_minio_removes_real_objects(minio_workflow_ctx: WorkflowContext) -> None:
+ """Sanity check the MinIO path of `delete_keys` end-to-end."""
+ key_a = queries_key(minio_workflow_ctx, "spec_a")
+ key_b = queries_key(minio_workflow_ctx, "spec_b")
+ write_json(key_a, {"x": 1})
+ write_json(key_b, {"x": 2})
+
+ deleted = delete_keys([key_a, key_b])
+
+ assert deleted == 2
+ assert object_storage.head_object(key_a, bucket=storage.bucket()) is None
+ assert object_storage.head_object(key_b, bucket=storage.bucket()) is None
diff --git a/posthog/temporal/tests/usage_report/test_workflow.py b/posthog/temporal/tests/usage_report/test_workflow.py
new file mode 100644
index 000000000000..f5857546fc42
--- /dev/null
+++ b/posthog/temporal/tests/usage_report/test_workflow.py
@@ -0,0 +1,94 @@
+"""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.
+"""
+
+import uuid
+
+import pytest
+
+import temporalio.worker
+from temporalio import activity
+from temporalio.contrib.pydantic import pydantic_data_converter
+from temporalio.testing import WorkflowEnvironment
+from temporalio.worker import Worker
+
+from posthog.temporal.usage_report.queries import QUERIES
+from posthog.temporal.usage_report.types import (
+ AggregateInputs,
+ AggregateResult,
+ EnqueuePointerInputs,
+ RunQueryToS3Inputs,
+ RunQueryToS3Result,
+ RunUsageReportsInputs,
+)
+from posthog.temporal.usage_report.workflow import RunUsageReportsWorkflow
+
+
+async def test_workflow_runs_query_aggregate_pointer_in_order() -> None:
+ seen_query_names: list[str] = []
+ aggregated_with: list[list[str]] = []
+ pointer_payloads: list[EnqueuePointerInputs] = []
+
+ @activity.defn(name="run-usage-report-query")
+ async def query_mock(inputs: RunQueryToS3Inputs) -> RunQueryToS3Result:
+ seen_query_names.append(inputs.query_name)
+ return RunQueryToS3Result(
+ query_name=inputs.query_name,
+ s3_key=f"queries/{inputs.query_name}.json",
+ duration_ms=1,
+ )
+
+ @activity.defn(name="aggregate-and-chunk-org-reports")
+ async def aggregate_mock(inputs: AggregateInputs) -> AggregateResult:
+ aggregated_with.append([r.query_name for r in inputs.query_results])
+ return AggregateResult(
+ chunk_keys=["chunks/chunk_0000.jsonl.gz"],
+ manifest_key="manifest.json",
+ total_orgs=2,
+ total_orgs_with_usage=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())
+ 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],
+ workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),
+ ):
+ result = await env.client.execute_workflow(
+ RunUsageReportsWorkflow.run,
+ RunUsageReportsInputs(at="2026-05-04T12:00:00+00:00"),
+ id=str(uuid.uuid4()),
+ task_queue=task_queue,
+ )
+
+ expected_names = [spec.name for spec in QUERIES]
+ assert seen_query_names == expected_names
+
+ assert len(aggregated_with) == 1
+ assert 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
+
+ assert (
+ result
+ == AggregateResult(
+ chunk_keys=["chunks/chunk_0000.jsonl.gz"],
+ manifest_key="manifest.json",
+ total_orgs=2,
+ total_orgs_with_usage=1,
+ ).model_dump()
+ )
diff --git a/posthog/temporal/usage_report/__init__.py b/posthog/temporal/usage_report/__init__.py
new file mode 100644
index 000000000000..6d62adfed358
--- /dev/null
+++ b/posthog/temporal/usage_report/__init__.py
@@ -0,0 +1,18 @@
+from posthog.temporal.usage_report.activities import (
+ aggregate_and_chunk_org_reports,
+ cleanup_intermediates,
+ enqueue_pointer_message,
+ run_query_to_s3,
+)
+from posthog.temporal.usage_report.workflow import RunUsageReportsWorkflow
+
+WORKFLOWS = [
+ RunUsageReportsWorkflow,
+]
+
+ACTIVITIES = [
+ run_query_to_s3,
+ aggregate_and_chunk_org_reports,
+ enqueue_pointer_message,
+ cleanup_intermediates,
+]
diff --git a/posthog/temporal/usage_report/activities.py b/posthog/temporal/usage_report/activities.py
new file mode 100644
index 000000000000..d79d3a24a7ae
--- /dev/null
+++ b/posthog/temporal/usage_report/activities.py
@@ -0,0 +1,210 @@
+"""Temporal activities for the usage reports workflow.
+
+Each activity is a thin wrapper that delegates to either the public
+`posthog.tasks.usage_report` facade (org-report aggregation, instance
+metadata) or the local `aggregator` / `storage` modules. Heavy logic lives
+elsewhere so these stay easy to read and mock in tests.
+"""
+
+import json
+import time
+from typing import Any
+
+from django.conf import settings
+
+import structlog
+from asgiref.sync import sync_to_async
+from temporalio import activity
+
+from posthog.sync import database_sync_to_async
+from posthog.tasks.usage_report import build_org_reports, get_instance_metadata
+from posthog.temporal.common.heartbeat import Heartbeater
+from posthog.temporal.usage_report.aggregator import (
+ batched,
+ build_manifest,
+ filter_org_reports,
+ iter_chunk_lines,
+ load_all_data,
+ sort_org_reports,
+)
+from posthog.temporal.usage_report.queries import QUERY_INDEX
+from posthog.temporal.usage_report.storage import (
+ bucket,
+ chunk_key,
+ chunks_prefix,
+ delete_keys,
+ manifest_key,
+ queries_key,
+ streamed_jsonl_gzip_writer,
+ write_json,
+)
+from posthog.temporal.usage_report.types import (
+ AggregateInputs,
+ AggregateResult,
+ CleanupInputs,
+ EnqueuePointerInputs,
+ RunQueryToS3Inputs,
+ RunQueryToS3Result,
+)
+from posthog.utils import get_instance_region
+
+logger = structlog.get_logger(__name__)
+
+CHUNK_SIZE_ORGS = 10_000
+SQS_POINTER_VERSION = 2
+
+# 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.
+SQS_QUEUE_NAME = "usage_reports_v2"
+
+
[email protected](name="run-usage-report-query")
+async def run_query_to_s3(inputs: RunQueryToS3Inputs) -> RunQueryToS3Result:
+ """Run one gather query and persist the raw result to S3 as JSON.
+
+ Each invocation maps 1:1 to a `QuerySpec` in the registry; the returned
+ `s3_key` is the only thing that flows back into the workflow (so we stay
+ well under Temporal's payload limits).
+ """
+ async with Heartbeater():
+ spec = QUERY_INDEX[inputs.query_name]
+
+ @database_sync_to_async
+ def run() -> Any:
+ # Snapshot specs ignore the period (they read current state);
+ # period specs filter on (begin, end). The signature is enforced
+ # by `QuerySpec.fn`'s union type and validated in registry tests.
+ if spec.kind == "snapshot":
+ return spec.fn() # type: ignore[call-arg]
+ return spec.fn(inputs.ctx.period_start, inputs.ctx.period_end) # type: ignore[call-arg]
+
+ started = time.monotonic()
+ result = await run()
+ duration_ms = int((time.monotonic() - started) * 1000)
+
+ key = queries_key(inputs.ctx, inputs.query_name)
+ await sync_to_async(write_json)(key, result)
+
+ return RunQueryToS3Result(
+ query_name=inputs.query_name,
+ s3_key=key,
+ duration_ms=duration_ms,
+ )
+
+
[email protected](name="aggregate-and-chunk-org-reports")
+async def aggregate_and_chunk_org_reports(inputs: AggregateInputs) -> AggregateResult:
+ """Read per-query S3 files, build org reports, and write JSONL chunks.
+
+ The aggregation logic is delegated to `aggregator` so this activity reads
+ as a sequence of named steps. Output is byte-compatible with the existing
+ Celery flow so we can validate parity before billing cuts over.
+ """
+ async with Heartbeater():
+ all_data = await sync_to_async(load_all_data)(inputs.query_results)
+
+ @database_sync_to_async
+ def aggregate_per_org() -> dict[str, Any]:
+ org_reports = build_org_reports(all_data, inputs.ctx.period_start)
+ org_reports = filter_org_reports(org_reports, inputs.ctx.organization_ids)
+ return org_reports
+
+ org_reports = await aggregate_per_org()
+
+ instance_metadata = await database_sync_to_async(get_instance_metadata)(
+ (inputs.ctx.period_start, 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.
+
+ sorted_reports = sort_org_reports(org_reports)
+ chunk_keys: list[str] = []
+ total_orgs_with_usage = 0
+
+ for index, batch in enumerate(batched(sorted_reports, CHUNK_SIZE_ORGS)):
+ key = chunk_key(inputs.ctx, index)
+ async with streamed_jsonl_gzip_writer(key) as writer:
+ for line, has_usage in iter_chunk_lines(batch, instance_metadata):
+ writer.write(line)
+ if has_usage:
+ total_orgs_with_usage += 1
+ chunk_keys.append(key)
+
+ manifest = build_manifest(
+ inputs.ctx,
+ chunk_keys=chunk_keys,
+ total_orgs=len(org_reports),
+ 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=len(org_reports),
+ total_orgs_with_usage=total_orgs_with_usage,
+ )
+
+
[email protected](name="usage-reports-enqueue-pointer-message")
+async def enqueue_pointer_message(inputs: EnqueuePointerInputs) -> None:
+ """Send a single SQS pointer message to the v2 billing queue.
+
+ Body is plain JSON describing where to find the gzipped chunks; billing
+ reads the actual usage data from S3.
+ """
+ if not settings.EE_AVAILABLE:
+ await logger.awarning("usage_reports.sqs.skipped_no_ee")
+ return
+
+ pointer = {
+ "version": SQS_POINTER_VERSION,
+ "run_id": inputs.ctx.run_id,
+ "date": inputs.ctx.date_str,
+ "period_start": inputs.ctx.period_start.isoformat(),
+ "period_end": inputs.ctx.period_end.isoformat(),
+ "region": get_instance_region(),
+ "site_url": settings.SITE_URL,
+ "bucket": bucket(),
+ "manifest_key": inputs.aggregate.manifest_key,
+ "chunk_prefix": chunks_prefix(inputs.ctx) + "/",
+ "chunk_count": len(inputs.aggregate.chunk_keys),
+ "total_orgs": inputs.aggregate.total_orgs,
+ "total_orgs_with_usage": inputs.aggregate.total_orgs_with_usage,
+ }
+
+ @sync_to_async
+ def send() -> None:
+ from ee.sqs.SQSProducer import get_sqs_producer
+
+ producer = get_sqs_producer(SQS_QUEUE_NAME)
+ if producer is None:
+ raise RuntimeError(f"SQS producer for queue '{SQS_QUEUE_NAME}' is not configured")
+ response = producer.send_message(
+ message_body=json.dumps(pointer, separators=(",", ":")),
+ message_attributes={
+ "content_type": "application/json",
+ "schema_version": str(SQS_POINTER_VERSION),
+ "run_id": inputs.ctx.run_id,
+ },
+ )
+ if response is None:
+ raise RuntimeError("SQS send_message returned no response")
+
+ await send()
+
+
[email protected](name="usage-reports-cleanup-intermediates")
+async def cleanup_intermediates(inputs: CleanupInputs) -> int:
+ """Delete the per-query S3 intermediates. Chunks and manifest are kept
+ so the billing consumer can read them after the SQS pointer arrives.
+ """
+ return await sync_to_async(delete_keys)(inputs.query_keys)
diff --git a/posthog/temporal/usage_report/aggregator.py b/posthog/temporal/usage_report/aggregator.py
new file mode 100644
index 000000000000..5bd1b96c8e26
--- /dev/null
+++ b/posthog/temporal/usage_report/aggregator.py
@@ -0,0 +1,117 @@
+"""Pure-logic helpers for the aggregation step.
+
+Keeps Temporal / IO concerns out of the way: this module only knows how to
+turn S3-backed query results into the legacy `all_data` shape, fan multi-key
+queries back out into their destination keys, and shape per-organization
+JSONL lines for the chunked output. Activities import from here.
+"""
+
+import itertools
+from collections.abc import Iterable, Iterator
+from typing import Any
+
+from django.conf import settings
+
+from posthog.tasks.usage_report import (
+ InstanceMetadata,
+ OrgReport,
+ convert_team_usage_rows_to_dict,
+ 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 Manifest, RunQueryToS3Result, WorkflowContext
+
+
+def load_all_data(query_results: list[RunQueryToS3Result]) -> dict[str, dict[int, int]]:
+ """Reconstruct the legacy `all_data` map from per-query S3 files.
+
+ Single-output specs become one entry keyed by `spec.name`. Multi-output
+ specs are fanned out into the destination keys defined in their
+ `multi_keys_mapping` so downstream code sees the same flat shape the
+ Celery path produces today.
+ """
+ all_data: dict[str, dict[int, int]] = {}
+ for result in query_results:
+ spec = QUERY_INDEX[result.query_name]
+ raw = read_json(result.s3_key)
+ if spec.output == "multi":
+ for source_key, dest_key in spec.multi_keys_mapping.items():
+ rows = raw.get(source_key, [])
+ all_data[dest_key] = convert_team_usage_rows_to_dict(rows)
+ else:
+ all_data[spec.name] = convert_team_usage_rows_to_dict(raw)
+ return all_data
+
+
+def iter_chunk_lines(
+ org_reports: Iterable[OrgReport],
+ instance_metadata: InstanceMetadata,
+) -> Iterator[tuple[dict[str, Any], bool]]:
+ """Yield `(line_dict, has_non_zero_usage)` for each org report.
+
+ `line_dict` is the JSONL line that ends up in S3 (and is what billing
+ consumes). The boolean lets the caller count non-zero orgs without a
+ second pass over the dict.
+ """
+ for org_report in org_reports:
+ report_dict = serialize_full_org_report(org_report, instance_metadata)
+ line = {
+ "organization_id": org_report.organization_id,
+ "usage_report": report_dict,
+ }
+ yield line, bool(report_dict.get("has_non_zero_usage"))
+
+
+def batched(iterable: Iterable[Any], size: int) -> Iterator[list[Any]]:
+ """Local `itertools.batched` so the module stays usable on 3.11."""
+ if size <= 0:
+ raise ValueError("batch size must be positive")
+ it = iter(iterable)
+ while True:
+ batch = list(itertools.islice(it, size))
+ if not batch:
+ return
+ yield batch
+
+
+def build_manifest(
+ ctx: WorkflowContext,
+ chunk_keys: list[str],
+ total_orgs: int,
+ total_orgs_with_usage: int,
+ region: str,
+ *,
+ version: int,
+) -> Manifest:
+ """Build the typed manifest billing reads after the SQS pointer arrives."""
+ return Manifest(
+ version=version,
+ run_id=ctx.run_id,
+ date=ctx.date_str,
+ period_start=ctx.period_start,
+ period_end=ctx.period_end,
+ region=region,
+ site_url=settings.SITE_URL,
+ bucket=bucket(),
+ chunk_keys=chunk_keys,
+ chunk_count=len(chunk_keys),
+ total_orgs=total_orgs,
+ total_orgs_with_usage=total_orgs_with_usage,
+ )
+
+
+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)
diff --git a/posthog/temporal/usage_report/queries.py b/posthog/temporal/usage_report/queries.py
new file mode 100644
index 000000000000..937613b3bd03
--- /dev/null
+++ b/posthog/temporal/usage_report/queries.py
@@ -0,0 +1,555 @@
+"""Registry of usage-report gathering queries.
+
+Each `QuerySpec` describes one fetch — typically one ClickHouse query, one
+Postgres aggregation, or one error-tracking API call — and how its result maps
+back to keys in the legacy `_get_all_usage_data` dict that
+`_get_team_report` consumes.
+
+Most queries produce a single destination key (`output="single"`); a handful
+already return a dict-of-keys in one query (`output="multi"`) and we keep
+those as a single fetch to avoid re-running the same heavy ClickHouse pass
+many times. The aggregation activity fans `multi` results back out into the
+flat `all_data` shape the existing helpers expect.
+
+⚠️ Snapshot queries — re-run safety disclaimer
+-----------------------------------------------
+Specs marked `kind="snapshot"` ignore the period (`begin`, `end`) and read
+the *current* state of the database/storage at the moment they execute. This
+is inherited from the existing Celery `_get_all_usage_data` behavior — names
+like `teams_with_active_external_data_schemas_in_period` end in
+`_in_period` for historical reasons, but the underlying queries do **not**
+filter on the period.
+
+Practical implications:
+
+* Re-running the workflow for the same `period_start`/`period_end` will
+ produce different snapshot numbers if the underlying state has changed
+ (counts of dashboards, feature flags, surveys, active hog destinations,
+ DWH storage in S3, error-tracking issue counts, etc.).
+* These metrics are not strictly attributable to the report's date — they
+ reflect "now" at the time the workflow runs.
+
+Period queries (`kind="period"`) are re-run safe: they filter ClickHouse on
+`timestamp >= begin AND timestamp < end`, so re-running for the same period
+returns the same result (modulo data still being ingested into the period).
+
+Until billing changes how it reads these metrics we keep the existing
+behavior — see `posthog/tasks/usage_report.py:_get_all_usage_data` for the
+canonical reference.
+"""
+
+import dataclasses
+from collections.abc import Callable
+from datetime import datetime
+from typing import Any, Literal
+
+from django.db.models import Count
+
+from posthog.constants import FlagRequestType
+from posthog.models import GroupTypeMapping
+from posthog.models.feature_flag import FeatureFlag
+from posthog.tasks.usage_report import (
+ get_all_event_metrics_in_period,
+ get_teams_with_active_batch_exports_in_period,
+ get_teams_with_active_external_data_schemas_in_period,
+ get_teams_with_active_hog_destinations_in_period,
+ get_teams_with_active_hog_transformations_in_period,
+ get_teams_with_ai_credits_used_in_period,
+ get_teams_with_ai_event_count_in_period,
+ get_teams_with_api_queries_metrics,
+ get_teams_with_billable_enhanced_persons_event_count_in_period,
+ get_teams_with_billable_event_count_in_period,
+ get_teams_with_cdp_billable_invocations_in_period,
+ get_teams_with_dwh_mat_views_storage_in_s3,
+ get_teams_with_dwh_tables_storage_in_s3,
+ get_teams_with_dwh_total_storage_in_s3,
+ get_teams_with_event_count_with_groups_in_period,
+ get_teams_with_exceptions_captured_in_period,
+ get_teams_with_feature_flag_requests_count_in_period,
+ get_teams_with_free_historical_rows_synced_in_period,
+ get_teams_with_hog_function_calls_in_period,
+ get_teams_with_hog_function_fetch_calls_in_period,
+ get_teams_with_logs_bytes_in_period,
+ get_teams_with_logs_records_in_period,
+ get_teams_with_mobile_billable_recording_count_in_period,
+ get_teams_with_query_metric,
+ get_teams_with_recording_bytes_in_period,
+ get_teams_with_recording_count_in_period,
+ get_teams_with_rows_exported_in_period,
+ get_teams_with_rows_synced_in_period,
+ get_teams_with_survey_responses_count_in_period,
+ get_teams_with_workflow_billable_invocations_in_period,
+ get_teams_with_workflow_emails_sent_in_period,
+ get_teams_with_workflow_push_sent_in_period,
+ get_teams_with_workflow_sms_sent_in_period,
+ get_teams_with_zero_duration_recording_count_in_period,
+)
+
+from products.dashboards.backend.models.dashboard import Dashboard
+from products.error_tracking.backend.facade import api as error_tracking_api
+from products.surveys.backend.models import Survey
+
+# ---- Postgres ORM / API helpers ---------------------------------------------
+# These are snapshot queries — they take no period args because they read
+# the *current* state of the database at the moment they run.
+
+
+def _group_types_total() -> list[dict[str, int]]:
+ return list(
+ GroupTypeMapping.objects.values("team_id") # nosemgrep: no-direct-persons-db-orm
+ .annotate(total=Count("id"))
+ .order_by("team_id") # nosemgrep: no-direct-persons-db-orm
+ )
+
+
+def _dashboard_count() -> list[dict[str, int]]:
+ return list(Dashboard.objects.values("team_id").annotate(total=Count("id")).order_by("team_id"))
+
+
+def _dashboard_template_count() -> list[dict[str, int]]:
+ return list(
+ Dashboard.objects.filter(creation_mode="template")
+ .values("team_id")
+ .annotate(total=Count("id"))
+ .order_by("team_id")
+ )
+
+
+def _dashboard_shared_count() -> list[dict[str, int]]:
+ return list(
+ Dashboard.objects.filter(sharingconfiguration__enabled=True)
+ .values("team_id")
+ .annotate(total=Count("id"))
+ .order_by("team_id")
+ )
+
+
+def _dashboard_tagged_count() -> list[dict[str, int]]:
+ return list(
+ Dashboard.objects.filter(tagged_items__isnull=False)
+ .values("team_id")
+ .annotate(total=Count("id"))
+ .order_by("team_id")
+ )
+
+
+def _ff_count() -> list[dict[str, int]]:
+ return list(FeatureFlag.objects.values("team_id").annotate(total=Count("id")).order_by("team_id"))
+
+
+def _ff_active_count() -> list[dict[str, int]]:
+ return list(
+ FeatureFlag.objects.filter(active=True).values("team_id").annotate(total=Count("id")).order_by("team_id")
+ )
+
+
+def _survey_count() -> list[dict[str, int]]:
+ return list(Survey.objects.values("team_id").annotate(total=Count("id")).order_by("team_id"))
+
+
+def _issues_created_total() -> list[dict[str, int]]:
+ return [{"team_id": team_id, "total": total} for team_id, total in error_tracking_api.get_issue_counts_by_team()]
+
+
+def _symbol_sets_count() -> list[dict[str, int]]:
+ return [
+ {"team_id": team_id, "total": total} for team_id, total in error_tracking_api.get_symbol_set_counts_by_team()
+ ]
+
+
+def _resolved_symbol_sets_count() -> list[dict[str, int]]:
+ return [
+ {"team_id": team_id, "total": total}
+ for team_id, total in error_tracking_api.get_symbol_set_counts_by_team(resolved_only=True)
+ ]
+
+
+# ---- Multi-key fan-out helpers ----------------------------------------------
+
+
+def _exceptions_captured(begin: datetime, end: datetime) -> dict[str, list[list[int]]]:
+ """Wrap `get_teams_with_exceptions_captured_in_period` to return a flat
+ dict-of-rows keyed by source_key. The aggregator remaps these source_keys
+ into the destination `all_data` keys via `multi_keys_mapping` below.
+ """
+ library_totals, team_totals_list = get_teams_with_exceptions_captured_in_period(begin, end)
+ out: dict[str, list[list[int]]] = {"total": team_totals_list}
+ for library, rows in library_totals.items():
+ out[library] = rows
+ return out
+
+
+# ---- Registry ---------------------------------------------------------------
+
+
+# Period queries filter on (begin, end) and are re-run safe.
+PeriodFn = Callable[[datetime, datetime], Any]
+# Snapshot queries take no args — they read current state and are *not*
+# re-run safe. See the module-level disclaimer above.
+SnapshotFn = Callable[[], Any]
+
+
[email protected](frozen=True)
+class QuerySpec:
+ name: str
+ fn: PeriodFn | SnapshotFn
+ output: Literal["single", "multi"] = "single"
+ # For output="multi" specs only: maps source-keys returned by fn to
+ # destination keys in the flat `all_data` dict.
+ multi_keys_mapping: dict[str, str] = dataclasses.field(default_factory=dict)
+ timeout_minutes: int = 15
+ kind: Literal["period", "snapshot"] = "period"
+
+
+QUERIES: list[QuerySpec] = [
+ # ---- ClickHouse: events --------------------------------------------------
+ QuerySpec(
+ name="teams_with_event_count_in_period",
+ fn=lambda b, e: get_teams_with_billable_event_count_in_period(b, e, count_distinct=True),
+ timeout_minutes=30,
+ ),
+ QuerySpec(
+ name="teams_with_enhanced_persons_event_count_in_period",
+ fn=lambda b, e: get_teams_with_billable_enhanced_persons_event_count_in_period(b, e, count_distinct=True),
+ timeout_minutes=30,
+ ),
+ QuerySpec(
+ name="teams_with_event_count_with_groups_in_period",
+ fn=get_teams_with_event_count_with_groups_in_period,
+ ),
+ QuerySpec(
+ name="all_event_metrics",
+ fn=get_all_event_metrics_in_period,
+ output="multi",
+ multi_keys_mapping={
+ "helicone_events": "teams_with_event_count_from_helicone_in_period",
+ "langfuse_events": "teams_with_event_count_from_langfuse_in_period",
+ "keywords_ai_events": "teams_with_event_count_from_keywords_ai_in_period",
+ "traceloop_events": "teams_with_event_count_from_traceloop_in_period",
+ "web_events": "teams_with_web_events_count_in_period",
+ "web_lite_events": "teams_with_web_lite_events_count_in_period",
+ "node_events": "teams_with_node_events_count_in_period",
+ "android_events": "teams_with_android_events_count_in_period",
+ "flutter_events": "teams_with_flutter_events_count_in_period",
+ "ios_events": "teams_with_ios_events_count_in_period",
+ "go_events": "teams_with_go_events_count_in_period",
+ "java_events": "teams_with_java_events_count_in_period",
+ "react_native_events": "teams_with_react_native_events_count_in_period",
+ "ruby_events": "teams_with_ruby_events_count_in_period",
+ "python_events": "teams_with_python_events_count_in_period",
+ "php_events": "teams_with_php_events_count_in_period",
+ "dotnet_events": "teams_with_dotnet_events_count_in_period",
+ "elixir_events": "teams_with_elixir_events_count_in_period",
+ "unity_events": "teams_with_unity_events_count_in_period",
+ "rust_events": "teams_with_rust_events_count_in_period",
+ },
+ timeout_minutes=30,
+ ),
+ # ---- ClickHouse: recordings ----------------------------------------------
+ QuerySpec(
+ name="teams_with_recording_count_in_period",
+ fn=lambda b, e: get_teams_with_recording_count_in_period(b, e, snapshot_source="web"),
+ ),
+ QuerySpec(
+ name="teams_with_zero_duration_recording_count_in_period",
+ fn=get_teams_with_zero_duration_recording_count_in_period,
+ ),
+ QuerySpec(
+ name="teams_with_recording_bytes_in_period",
+ fn=lambda b, e: get_teams_with_recording_bytes_in_period(b, e, snapshot_source="web"),
+ ),
+ QuerySpec(
+ name="teams_with_mobile_recording_count_in_period",
+ fn=lambda b, e: get_teams_with_recording_count_in_period(b, e, snapshot_source="mobile"),
+ ),
+ QuerySpec(
+ name="teams_with_mobile_recording_bytes_in_period",
+ fn=lambda b, e: get_teams_with_recording_bytes_in_period(b, e, snapshot_source="mobile"),
+ ),
+ QuerySpec(
+ name="teams_with_mobile_billable_recording_count_in_period",
+ fn=get_teams_with_mobile_billable_recording_count_in_period,
+ ),
+ # ---- ClickHouse: feature flag requests -----------------------------------
+ QuerySpec(
+ name="teams_with_decide_requests_count_in_period",
+ fn=lambda b, e: get_teams_with_feature_flag_requests_count_in_period(b, e, FlagRequestType.DECIDE),
+ ),
+ QuerySpec(
+ name="teams_with_local_evaluation_requests_count_in_period",
+ fn=lambda b, e: get_teams_with_feature_flag_requests_count_in_period(b, e, FlagRequestType.LOCAL_EVALUATION),
+ ),
+ # ---- ClickHouse: query metrics -------------------------------------------
+ QuerySpec(
+ name="teams_with_query_app_bytes_read",
+ fn=lambda b, e: get_teams_with_query_metric(b, e, metric="read_bytes", access_method=""),
+ ),
+ QuerySpec(
+ name="teams_with_query_app_rows_read",
+ fn=lambda b, e: get_teams_with_query_metric(b, e, metric="read_rows", access_method=""),
+ ),
+ QuerySpec(
+ name="teams_with_query_app_duration_ms",
+ fn=lambda b, e: get_teams_with_query_metric(b, e, metric="query_duration_ms", access_method=""),
+ ),
+ QuerySpec(
+ name="teams_with_query_api_bytes_read",
+ fn=lambda b, e: get_teams_with_query_metric(b, e, metric="read_bytes", access_method="personal_api_key"),
+ ),
+ QuerySpec(
+ name="teams_with_query_api_rows_read",
+ fn=lambda b, e: get_teams_with_query_metric(b, e, metric="read_rows", access_method="personal_api_key"),
+ ),
+ QuerySpec(
+ name="teams_with_query_api_duration_ms",
+ fn=lambda b, e: get_teams_with_query_metric(b, e, metric="query_duration_ms", access_method="personal_api_key"),
+ ),
+ QuerySpec(
+ name="api_queries_metrics",
+ fn=get_teams_with_api_queries_metrics,
+ output="multi",
+ multi_keys_mapping={
+ "count": "teams_with_api_queries_count",
+ "read_bytes": "teams_with_api_queries_read_bytes",
+ },
+ ),
+ # ---- ClickHouse: event explorer ------------------------------------------
+ QuerySpec(
+ name="teams_with_event_explorer_app_bytes_read",
+ fn=lambda b, e: get_teams_with_query_metric(
+ b, e, metric="read_bytes", query_types=["EventsQuery"], access_method=""
+ ),
+ ),
+ QuerySpec(
+ name="teams_with_event_explorer_app_rows_read",
+ fn=lambda b, e: get_teams_with_query_metric(
+ b, e, metric="read_rows", query_types=["EventsQuery"], access_method=""
+ ),
+ ),
+ QuerySpec(
+ name="teams_with_event_explorer_app_duration_ms",
+ fn=lambda b, e: get_teams_with_query_metric(
+ b, e, metric="query_duration_ms", query_types=["EventsQuery"], access_method=""
+ ),
+ ),
+ QuerySpec(
+ name="teams_with_event_explorer_api_bytes_read",
+ fn=lambda b, e: get_teams_with_query_metric(
+ b, e, metric="read_bytes", query_types=["EventsQuery"], access_method="personal_api_key"
+ ),
+ ),
+ QuerySpec(
+ name="teams_with_event_explorer_api_rows_read",
+ fn=lambda b, e: get_teams_with_query_metric(
+ b, e, metric="read_rows", query_types=["EventsQuery"], access_method="personal_api_key"
+ ),
+ ),
+ QuerySpec(
+ name="teams_with_event_explorer_api_duration_ms",
+ fn=lambda b, e: get_teams_with_query_metric(
+ b, e, metric="query_duration_ms", query_types=["EventsQuery"], access_method="personal_api_key"
+ ),
+ ),
+ # ---- ClickHouse: surveys -------------------------------------------------
+ QuerySpec(
+ name="teams_with_survey_responses_count_in_period",
+ fn=get_teams_with_survey_responses_count_in_period,
+ ),
+ # ---- ClickHouse: data warehouse / batch exports usage --------------------
+ QuerySpec(
+ name="teams_with_rows_synced_in_period",
+ fn=get_teams_with_rows_synced_in_period,
+ ),
+ QuerySpec(
+ name="teams_with_free_historical_rows_synced_in_period",
+ fn=get_teams_with_free_historical_rows_synced_in_period,
+ ),
+ QuerySpec(
+ name="teams_with_rows_exported_in_period",
+ fn=get_teams_with_rows_exported_in_period,
+ ),
+ # ---- ClickHouse: exceptions / error tracking events ----------------------
+ QuerySpec(
+ name="exceptions_captured",
+ fn=_exceptions_captured,
+ output="multi",
+ multi_keys_mapping={
+ "total": "teams_with_exceptions_captured_in_period",
+ "web": "teams_with_web_exceptions_captured_in_period",
+ "web_lite": "teams_with_js_lite_exceptions_captured_in_period",
+ "node": "teams_with_node_exceptions_captured_in_period",
+ "go": "teams_with_go_exceptions_captured_in_period",
+ "java": "teams_with_java_exceptions_captured_in_period",
+ "ruby": "teams_with_ruby_exceptions_captured_in_period",
+ "python": "teams_with_python_exceptions_captured_in_period",
+ "android": "teams_with_android_exceptions_captured_in_period",
+ "react_native": "teams_with_react_native_exceptions_captured_in_period",
+ "ios": "teams_with_ios_exceptions_captured_in_period",
+ "flutter": "teams_with_flutter_exceptions_captured_in_period",
+ "unknown": "teams_with_unknown_exceptions_captured_in_period",
+ },
+ ),
+ # ---- ClickHouse: hog functions / CDP ------------------------------------
+ QuerySpec(
+ name="teams_with_hog_function_calls_in_period",
+ fn=get_teams_with_hog_function_calls_in_period,
+ ),
+ QuerySpec(
+ name="teams_with_hog_function_fetch_calls_in_period",
+ fn=get_teams_with_hog_function_fetch_calls_in_period,
+ ),
+ QuerySpec(
+ name="teams_with_cdp_billable_invocations_in_period",
+ fn=get_teams_with_cdp_billable_invocations_in_period,
+ ),
+ # ---- ClickHouse: AI ------------------------------------------------------
+ QuerySpec(
+ name="teams_with_ai_event_count_in_period",
+ fn=get_teams_with_ai_event_count_in_period,
+ ),
+ QuerySpec(
+ name="teams_with_ai_credits_used_in_period",
+ fn=get_teams_with_ai_credits_used_in_period,
+ ),
+ # ---- ClickHouse: workflows / messaging ----------------------------------
+ QuerySpec(
+ name="teams_with_workflow_emails_sent_in_period",
+ fn=get_teams_with_workflow_emails_sent_in_period,
+ ),
+ QuerySpec(
+ name="teams_with_workflow_push_sent_in_period",
+ fn=get_teams_with_workflow_push_sent_in_period,
+ ),
+ QuerySpec(
+ name="teams_with_workflow_sms_sent_in_period",
+ fn=get_teams_with_workflow_sms_sent_in_period,
+ ),
+ QuerySpec(
+ name="teams_with_workflow_billable_invocations_in_period",
+ fn=get_teams_with_workflow_billable_invocations_in_period,
+ ),
+ # ---- ClickHouse: logs ---------------------------------------------------
+ QuerySpec(
+ name="teams_with_logs_bytes_in_period",
+ fn=get_teams_with_logs_bytes_in_period,
+ ),
+ QuerySpec(
+ name="teams_with_logs_records_in_period",
+ fn=get_teams_with_logs_records_in_period,
+ ),
+ # ---- Snapshot queries (kind="snapshot") ---------------------------------
+ # ⚠️ Read the disclaimer at the top of this module. These ignore the
+ # period and reflect *current* state at run time. Re-running for the same
+ # date can return different numbers if state has changed since.
+ QuerySpec(
+ name="teams_with_active_external_data_schemas_in_period",
+ fn=get_teams_with_active_external_data_schemas_in_period,
+ timeout_minutes=5,
+ kind="snapshot",
+ ),
+ QuerySpec(
+ name="teams_with_active_batch_exports_in_period",
+ fn=get_teams_with_active_batch_exports_in_period,
+ timeout_minutes=5,
+ kind="snapshot",
+ ),
+ QuerySpec(
+ name="teams_with_dwh_tables_storage_in_s3_in_mib",
+ fn=get_teams_with_dwh_tables_storage_in_s3,
+ timeout_minutes=5,
+ kind="snapshot",
+ ),
+ QuerySpec(
+ name="teams_with_dwh_mat_views_storage_in_s3_in_mib",
+ fn=get_teams_with_dwh_mat_views_storage_in_s3,
+ timeout_minutes=5,
+ kind="snapshot",
+ ),
+ QuerySpec(
+ name="teams_with_dwh_total_storage_in_s3_in_mib",
+ fn=get_teams_with_dwh_total_storage_in_s3,
+ timeout_minutes=5,
+ kind="snapshot",
+ ),
+ QuerySpec(
+ name="teams_with_active_hog_destinations_in_period",
+ fn=get_teams_with_active_hog_destinations_in_period,
+ timeout_minutes=5,
+ kind="snapshot",
+ ),
+ QuerySpec(
+ name="teams_with_active_hog_transformations_in_period",
+ fn=get_teams_with_active_hog_transformations_in_period,
+ timeout_minutes=5,
+ kind="snapshot",
+ ),
+ QuerySpec(
+ name="teams_with_group_types_total",
+ fn=_group_types_total,
+ timeout_minutes=5,
+ kind="snapshot",
+ ),
+ QuerySpec(
+ name="teams_with_dashboard_count",
+ fn=_dashboard_count,
+ timeout_minutes=5,
+ kind="snapshot",
+ ),
+ QuerySpec(
+ name="teams_with_dashboard_template_count",
+ fn=_dashboard_template_count,
+ timeout_minutes=5,
+ kind="snapshot",
+ ),
+ QuerySpec(
+ name="teams_with_dashboard_shared_count",
+ fn=_dashboard_shared_count,
+ timeout_minutes=5,
+ kind="snapshot",
+ ),
+ QuerySpec(
+ name="teams_with_dashboard_tagged_count",
+ fn=_dashboard_tagged_count,
+ timeout_minutes=5,
+ kind="snapshot",
+ ),
+ QuerySpec(
+ name="teams_with_ff_count",
+ fn=_ff_count,
+ timeout_minutes=5,
+ kind="snapshot",
+ ),
+ QuerySpec(
+ name="teams_with_ff_active_count",
+ fn=_ff_active_count,
+ timeout_minutes=5,
+ kind="snapshot",
+ ),
+ QuerySpec(
+ name="teams_with_survey_count",
+ fn=_survey_count,
+ timeout_minutes=5,
+ kind="snapshot",
+ ),
+ QuerySpec(
+ name="teams_with_issues_created_total",
+ fn=_issues_created_total,
+ timeout_minutes=5,
+ kind="snapshot",
+ ),
+ QuerySpec(
+ name="teams_with_symbol_sets_count",
+ fn=_symbol_sets_count,
+ timeout_minutes=5,
+ kind="snapshot",
+ ),
+ QuerySpec(
+ name="teams_with_resolved_symbol_sets_count",
+ fn=_resolved_symbol_sets_count,
+ timeout_minutes=5,
+ kind="snapshot",
+ ),
+]
+
+
+QUERY_INDEX: dict[str, QuerySpec] = {spec.name: spec for spec in QUERIES}
diff --git a/posthog/temporal/usage_report/storage.py b/posthog/temporal/usage_report/storage.py
new file mode 100644
index 000000000000..474a7e1ac804
--- /dev/null
+++ b/posthog/temporal/usage_report/storage.py
@@ -0,0 +1,175 @@
+"""S3 path conventions and IO helpers for the usage reports workflow.
+
+All keys are scoped under
+`{OBJECT_STORAGE_TASKS_FOLDER}/billing/usage_reports/{YYYY-MM-DD}/{run_id}/`
+so multiple runs on the same date never collide. The bucket is
+`settings.BILLING_USAGE_REPORTS_S3_BUCKET`, which falls back to
+`OBJECT_STORAGE_BUCKET` so dev / self-hosted keep working without extra
+configuration.
+"""
+
+import io
+import gzip
+import json
+from collections.abc import AsyncIterator, Iterable
+from contextlib import asynccontextmanager
+from typing import Any
+
+from django.conf import settings
+
+import structlog
+from asgiref.sync import sync_to_async
+
+from posthog.storage import object_storage
+from posthog.temporal.usage_report.types import WorkflowContext
+
+logger = structlog.get_logger(__name__)
+
+
+def bucket() -> str:
+ """The S3 bucket all usage-report artifacts go into. Read at call time
+ rather than module import so tests can `override_settings` cleanly.
+ """
+ return settings.BILLING_USAGE_REPORTS_S3_BUCKET
+
+
+def run_prefix(ctx: WorkflowContext) -> str:
+ """The S3 prefix for everything written by a single workflow run."""
+ return f"{settings.OBJECT_STORAGE_TASKS_FOLDER}/billing/usage_reports/{ctx.date_str}/{ctx.run_id}"
+
+
+def queries_prefix(ctx: WorkflowContext) -> str:
+ return f"{run_prefix(ctx)}/queries"
+
+
+def chunks_prefix(ctx: WorkflowContext) -> str:
+ return f"{run_prefix(ctx)}/chunks"
+
+
+def queries_key(ctx: WorkflowContext, query_name: str) -> str:
+ return f"{queries_prefix(ctx)}/{query_name}.json"
+
+
+def chunk_key(ctx: WorkflowContext, index: int) -> str:
+ return f"{chunks_prefix(ctx)}/chunk_{index:04d}.jsonl.gz"
+
+
+def manifest_key(ctx: WorkflowContext) -> str:
+ return f"{run_prefix(ctx)}/manifest.json"
+
+
+def write_json(key: str, obj: Any) -> None:
+ """Write a JSON-encoded object to S3 with `application/json` content type.
+
+ Uses `default=str` to coerce datetimes / Decimal / etc. into strings; the
+ aggregation activity reads these back and feeds them through existing
+ helpers that already tolerate string ints.
+ """
+ object_storage.write(
+ key,
+ json.dumps(obj, default=str),
+ extras={"ContentType": "application/json"},
+ bucket=bucket(),
+ )
+
+
+def read_json(key: str) -> Any:
+ """Read a JSON object from S3. Raises if the key is missing."""
+ raw = object_storage.read_bytes(key, bucket=bucket())
+ if raw is None:
+ raise FileNotFoundError(f"S3 key not found: {key}")
+ return json.loads(raw)
+
+
+# Encoded JSONL bytes are buffered up to this size before being handed
+# to `gzip.GzipFile.write`. The per-call overhead of gzip.write is small
+# but non-zero, so batching ~256KB at a time noticeably trims the cost
+# of writing 10k lines per chunk without growing memory pressure.
+_GZIP_FLUSH_THRESHOLD_BYTES = 256 * 1024
+
+
+class JsonlGzipWriter:
+ """Buffer used by `streamed_jsonl_gzip_writer`. Encodes JSONL lines
+ into an in-memory `bytearray`, flushes to the gzip stream in
+ `_GZIP_FLUSH_THRESHOLD_BYTES`-sized batches, and the gzip stream
+ then flushes to S3 on context-manager exit.
+ """
+
+ def __init__(self, flush_threshold_bytes: int = _GZIP_FLUSH_THRESHOLD_BYTES) -> None:
+ self._buffer = io.BytesIO()
+ self._gz = gzip.GzipFile(fileobj=self._buffer, mode="wb")
+ self._pending = bytearray()
+ self._flush_threshold = flush_threshold_bytes
+ self.line_count = 0
+
+ def write(self, line: dict[str, Any]) -> None:
+ self._pending += json.dumps(line, separators=(",", ":"), default=str).encode("utf-8")
+ self._pending += b"\n"
+ self.line_count += 1
+ if len(self._pending) >= self._flush_threshold:
+ self._flush_pending()
+
+ def write_lines(self, lines: Iterable[dict[str, Any]]) -> None:
+ for line in lines:
+ self.write(line)
+
+ def _flush_pending(self) -> None:
+ if not self._pending:
+ return
+ self._gz.write(bytes(self._pending))
+ self._pending.clear()
+
+ def _finalize(self) -> bytes:
+ self._flush_pending()
+ self._gz.close()
+ return self._buffer.getvalue()
+
+
+@asynccontextmanager
+async def streamed_jsonl_gzip_writer(key: str) -> AsyncIterator[JsonlGzipWriter]:
+ """Async context manager that yields a `JsonlGzipWriter`. On clean exit
+ the gzipped JSONL bytes are streamed to S3 at `key` with the
+ `application/x-ndjson` + `gzip` headers billing's reader expects. If
+ the body raises, nothing gets uploaded.
+
+ async with streamed_jsonl_gzip_writer(key) as w:
+ w.write_lines(lines)
+ # or w.write({...}) per line
+ """
+ writer = JsonlGzipWriter()
+ yield writer
+ body = writer._finalize()
+ await sync_to_async(_upload_gzipped_jsonl)(key, body)
+
+
+def _upload_gzipped_jsonl(key: str, body: bytes) -> None:
+ object_storage.write_stream(
+ key,
+ io.BytesIO(body),
+ extras={"ContentType": "application/x-ndjson", "ContentEncoding": "gzip"},
+ bucket=bucket(),
+ )
+
+
+def write_jsonl_chunk_gzip(key: str, lines: Iterable[dict[str, Any]]) -> int:
+ """Sync one-shot variant of `streamed_jsonl_gzip_writer` for callers
+ (tests, scripts) that just want to gzip-and-upload a list of lines.
+ """
+ writer = JsonlGzipWriter()
+ writer.write_lines(lines)
+ body = writer._finalize()
+ _upload_gzipped_jsonl(key, body)
+ return writer.line_count
+
+
+def delete_keys(keys: Iterable[str]) -> int:
+ """Best-effort delete; missing keys are logged and skipped."""
+ deleted = 0
+ target_bucket = bucket()
+ for key in keys:
+ try:
+ object_storage.delete(key, bucket=target_bucket)
+ deleted += 1
+ except Exception as err:
+ logger.warning("usage_reports.cleanup.delete_failed", key=key, error=str(err))
+ return deleted
diff --git a/posthog/temporal/usage_report/types.py b/posthog/temporal/usage_report/types.py
new file mode 100644
index 000000000000..c43e8b59cb20
--- /dev/null
+++ b/posthog/temporal/usage_report/types.py
@@ -0,0 +1,80 @@
+"""Workflow + activity input/output models.
+
+All models use pydantic so the Temporal pydantic data converter handles
+`datetime` (and other rich types) natively — that lets us drop the
+ISO-string round-tripping that plain dataclasses would force.
+"""
+
+from datetime import datetime
+from typing import Optional
+
+from pydantic import BaseModel
+
+
+class RunUsageReportsInputs(BaseModel):
+ """Top-level workflow input."""
+
+ at: Optional[str] = None
+ organization_ids: Optional[list[str]] = None
+
+
+class WorkflowContext(BaseModel):
+ """Snapshot of the workflow run, threaded through every activity."""
+
+ run_id: str
+ period_start: datetime
+ period_end: datetime
+ date_str: str
+ organization_ids: Optional[list[str]] = None
+
+
+class RunQueryToS3Inputs(BaseModel):
+ ctx: WorkflowContext
+ query_name: str
+
+
+class RunQueryToS3Result(BaseModel):
+ query_name: str
+ s3_key: str
+ duration_ms: int
+
+
+class AggregateInputs(BaseModel):
+ ctx: WorkflowContext
+ query_results: list[RunQueryToS3Result]
+
+
+class Manifest(BaseModel):
+ """Manifest written next to the JSONL chunks. Billing reads this to
+ discover the chunk list and run metadata before streaming the chunks.
+ """
+
+ version: int
+ run_id: str
+ date: str
+ period_start: datetime
+ period_end: datetime
+ region: str
+ site_url: str
+ bucket: str
+ chunk_keys: list[str]
+ chunk_count: int
+ total_orgs: int
+ total_orgs_with_usage: int
+
+
+class AggregateResult(BaseModel):
+ chunk_keys: list[str]
+ manifest_key: str
+ total_orgs: int
+ total_orgs_with_usage: int
+
+
+class EnqueuePointerInputs(BaseModel):
+ ctx: WorkflowContext
+ aggregate: AggregateResult
+
+
+class CleanupInputs(BaseModel):
+ ctx: WorkflowContext
+ query_keys: list[str]
diff --git a/posthog/temporal/usage_report/workflow.py b/posthog/temporal/usage_report/workflow.py
new file mode 100644
index 000000000000..9c806f2a7bb9
--- /dev/null
+++ b/posthog/temporal/usage_report/workflow.py
@@ -0,0 +1,153 @@
+"""Temporal workflow that aggregates daily usage data and publishes it to S3
+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.
+
+This replaces the per-org SQS fan-out in
+`posthog/tasks/usage_report.py:send_all_org_usage_reports`. The Celery task
+remains in production until billing migrates to consume the S3 layout.
+"""
+
+import json
+from datetime import datetime, timedelta
+from typing import Optional
+
+from dateutil import parser
+from temporalio import common, workflow
+
+from posthog.exceptions_capture import capture_exception
+from 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.queries import QUERIES, QuerySpec
+from posthog.temporal.usage_report.storage import run_prefix
+from posthog.temporal.usage_report.types import (
+ AggregateInputs,
+ EnqueuePointerInputs,
+ RunQueryToS3Inputs,
+ RunQueryToS3Result,
+ RunUsageReportsInputs,
+ WorkflowContext,
+)
+from posthog.utils import get_previous_day
+
+
+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
+ to call from the workflow body (no real-time access).
+ """
+ at_date = parser.parse(inputs.at) if inputs.at else None
+ if at_date is None and now is not None:
+ at_date = now
+ period_start, period_end = get_previous_day(at=at_date)
+ return WorkflowContext(
+ run_id=run_id,
+ period_start=period_start,
+ period_end=period_end,
+ date_str=period_start.strftime("%Y-%m-%d"),
+ organization_ids=inputs.organization_ids,
+ )
+
+
[email protected](name="run-usage-reports")
+class RunUsageReportsWorkflow(PostHogWorkflow):
+ @staticmethod
+ def parse_inputs(inputs: list[str]) -> RunUsageReportsInputs:
+ loaded = json.loads(inputs[0])
+ return RunUsageReportsInputs(**loaded)
+
+ @workflow.run
+ async def run(self, inputs: RunUsageReportsInputs) -> dict:
+ try:
+ ctx = build_context(inputs, run_id=workflow.info().run_id, now=workflow.now())
+ workflow.logger.info(
+ "Starting usage reports workflow",
+ extra={
+ "run_id": ctx.run_id,
+ "date_str": ctx.date_str,
+ "period_start": ctx.period_start.isoformat(),
+ "period_end": ctx.period_end.isoformat(),
+ "spec_count": len(QUERIES),
+ },
+ )
+
+ # 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))
+
+ agg = await workflow.execute_activity(
+ aggregate_and_chunk_org_reports,
+ AggregateInputs(ctx=ctx, query_results=query_results),
+ start_to_close_timeout=timedelta(minutes=60),
+ retry_policy=common.RetryPolicy(
+ maximum_attempts=2,
+ initial_interval=timedelta(seconds=30),
+ ),
+ 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),
+ )
+
+ # Intentionally NOT cleaning up the per-query intermediates yet —
+ # we want them around in S3 for debugging while we validate the
+ # new flow. Re-enable once we trust the pipeline:
+ #
+ # await workflow.execute_activity(
+ # cleanup_intermediates,
+ # CleanupInputs(ctx=ctx, query_keys=[r.s3_key for r in query_results]),
+ # start_to_close_timeout=timedelta(minutes=10),
+ # retry_policy=common.RetryPolicy(maximum_attempts=3),
+ # heartbeat_timeout=timedelta(minutes=2),
+ # )
+
+ workflow.logger.info(
+ "Usage reports workflow complete",
+ extra={
+ "run_id": ctx.run_id,
+ "total_orgs": agg.total_orgs,
+ "total_orgs_with_usage": agg.total_orgs_with_usage,
+ "chunk_count": len(agg.chunk_keys),
+ "run_prefix": run_prefix(ctx),
+ },
+ )
+
+ return agg.model_dump()
+ except Exception as err:
+ workflow.logger.exception("Usage reports workflow failed", extra={"error": str(err)})
+ capture_exception(err)
+ raise
+
+ async def _run_query(self, ctx: WorkflowContext, spec: QuerySpec) -> RunQueryToS3Result:
+ return await workflow.execute_activity(
+ run_query_to_s3,
+ RunQueryToS3Inputs(ctx=ctx, query_name=spec.name),
+ start_to_close_timeout=timedelta(minutes=spec.timeout_minutes),
+ retry_policy=common.RetryPolicy(
+ maximum_attempts=3,
+ initial_interval=timedelta(seconds=30),
+ ),
+ heartbeat_timeout=timedelta(minutes=2),
+ )
diff --git a/posthog/temporal/usage_reports/__init__.py b/posthog/temporal/usage_reports/__init__.py
deleted file mode 100644
index 35a5c41a8bab..000000000000
--- a/posthog/temporal/usage_reports/__init__.py
+++ /dev/null
@@ -1,9 +0,0 @@
-from posthog.temporal.usage_reports.run_usage_reports import RunUsageReportsWorkflow, query_usage_reports
-
-WORKFLOWS = [
- RunUsageReportsWorkflow,
-]
-
-ACTIVITIES = [
- query_usage_reports,
-]
diff --git a/posthog/temporal/usage_reports/run_usage_reports.py b/posthog/temporal/usage_reports/run_usage_reports.py
deleted file mode 100644
index 1894be5525b5..000000000000
--- a/posthog/temporal/usage_reports/run_usage_reports.py
+++ /dev/null
@@ -1,238 +0,0 @@
-import json
-import logging
-import dataclasses
-from datetime import timedelta
-from typing import Optional
-
-from django.conf import settings
-
-import structlog
-from asgiref.sync import sync_to_async
-from dateutil import parser
-from temporalio import activity, common, workflow
-
-from posthog.exceptions_capture import capture_exception
-from posthog.sync import database_sync_to_async
-from posthog.tasks.usage_report import (
- OrgReport,
- _add_team_report_to_org_reports,
- _get_all_usage_data,
- _get_full_org_usage_report,
- _get_full_org_usage_report_as_dict,
- _get_team_report,
- _get_teams_for_usage_reports,
- _queue_report,
- capture_report,
- convert_team_usage_rows_to_dict,
- get_instance_metadata,
- get_ph_client,
- has_non_zero_usage,
-)
-from posthog.temporal.common.base import PostHogWorkflow
-from posthog.temporal.common.heartbeat import Heartbeater
-from posthog.utils import get_instance_region, get_previous_day
-
-logger = structlog.get_logger()
-logging.basicConfig(level=logging.INFO)
-
-
-class RunUsageReportsInputs:
- at: Optional[str] = None
- skip_capture_event: Optional[bool] = False
-
-
-class QueryUsageReportsInputs:
- at: Optional[str] = None
- skip_capture_event: Optional[bool] = False
-
-
[email protected](name="query-usage-reports")
-async def query_usage_reports(
- inputs: QueryUsageReportsInputs,
-) -> None:
- async with Heartbeater():
- import posthoganalytics
-
- are_usage_reports_disabled = posthoganalytics.feature_enabled(
- "disable-usage-reports", "internal_billing_events"
- )
- if are_usage_reports_disabled:
- capture_exception(Exception(f"Usage reports are disabled for {inputs.at}"))
- return None
-
- at_date = parser.parse(inputs.at) if inputs.at else None
- period = get_previous_day(at=at_date)
- period_start, period_end = period
-
- print(f"Querying all org reports {period_start} - {period_end}") # noqa: T201
-
- @database_sync_to_async
- def async_get_all_usage_data(p_start, p_end):
- return _get_all_usage_data(p_start, p_end)
-
- def convert_to_team_rows(raw_data):
- result = {}
- for key, rows in raw_data.items():
- result[key] = convert_team_usage_rows_to_dict(rows)
- return result
-
- raw_data = await async_get_all_usage_data(period_start, period_end)
-
- all_data = convert_to_team_rows(raw_data)
-
- print("Querying all teams") # noqa: T201
-
- @database_sync_to_async
- def async_get_teams_for_usage_reports():
- return _get_teams_for_usage_reports()
-
- teams = await async_get_teams_for_usage_reports()
-
- print(f"Querying all teams complete {len(teams)} teams") # noqa: T201
-
- org_reports: dict[str, OrgReport] = {}
-
- print("Generating org reports") # noqa: T201
-
- @database_sync_to_async
- def async_add_team_report_to_org_reports(o_r, t, t_r, p_start):
- return _add_team_report_to_org_reports(o_r, t, t_r, p_start)
-
- for team in teams:
- team_report = _get_team_report(all_data, team)
- await async_add_team_report_to_org_reports(org_reports, team, team_report, period_start)
-
- print(f"Generating org reports complete {len(org_reports)} orgs") # noqa: T201
-
- @sync_to_async
- def async_get_instance_metadata(p):
- return get_instance_metadata(p)
-
- instance_metadata = await async_get_instance_metadata(period)
-
- producer = None
- try:
- if settings.EE_AVAILABLE:
- from ee.sqs.SQSProducer import get_sqs_producer
-
- producer = get_sqs_producer("usage_reports")
- except Exception:
- pass
-
- pha_client = get_ph_client(sync_mode=True)
-
- total_orgs = len(org_reports)
- total_orgs_sent = 0
-
- pha_client.capture(
- distinct_id="internal_billing_events",
- event="usage reports - starting to send",
- properties={
- "total_orgs": total_orgs,
- "period_start": period_start.isoformat(),
- "period_end": period_end.isoformat(),
- "region": get_instance_region(),
- },
- groups={"instance": settings.SITE_URL},
- )
-
- print(f"Sending usage reports {total_orgs} orgs") # noqa: T201
-
- org_count = 0
- for org_report in org_reports.values():
- try:
- org_count += 1
- if org_count % 500 == 0:
- print(f"Processed {org_count}/{total_orgs} organizations...") # noqa: T201
-
- organization_id = org_report.organization_id
-
- full_report = _get_full_org_usage_report(org_report, instance_metadata)
- full_report_dict = _get_full_org_usage_report_as_dict(full_report)
-
- @sync_to_async
- def async_capture_report(oid, frd, ad) -> None:
- try:
- at_date_str = ad.isoformat() if ad else None
- capture_report(
- organization_id=oid,
- full_report_dict=frd,
- at_date=at_date_str,
- )
- except Exception as err:
- logger.exception(f"Error capturing report for organization {oid}: {err}")
-
- # First capture the events to PostHog
- if not inputs.skip_capture_event:
- await async_capture_report(organization_id, full_report_dict, at_date)
-
- @sync_to_async
- def async_queue_report(p, oid, frd) -> bool:
- try:
- _queue_report(p, oid, frd)
- return True
- except Exception as err:
- logger.exception(f"Error queueing report for organization {oid}: {err}")
- return False
-
- # Then send the reports to billing through SQS (only if the producer is available)
- if has_non_zero_usage(full_report) and producer:
- success = await async_queue_report(producer, organization_id, full_report_dict)
- if success:
- total_orgs_sent += 1
-
- except Exception as loop_err:
- logger.exception(f"Error processing organization report: {loop_err}")
-
- print(f"Total orgs: {total_orgs}") # noqa: T201
- print(f"Total orgs sent: {total_orgs_sent}") # noqa: T201
-
- pha_client.capture(
- distinct_id="internal_billing_events",
- event="usage reports - sending complete",
- properties={
- "total_orgs": total_orgs,
- "total_orgs_sent": total_orgs_sent,
- "period_start": period_start.isoformat(),
- "period_end": period_end.isoformat(),
- "region": get_instance_region(),
- },
- groups={"instance": settings.SITE_URL},
- )
- pha_client.flush() # Flush and close the client
-
- return None
-
-
[email protected](name="run-usage-reports")
-class RunUsageReportsWorkflow(PostHogWorkflow):
- @staticmethod
- def parse_inputs(inputs: list[str]) -> RunUsageReportsInputs:
- """Parse inputs from the management command CLI."""
- loaded = json.loads(inputs[0])
- return RunUsageReportsInputs(**loaded)
-
- @workflow.run
- async def run(self, inputs: RunUsageReportsInputs) -> None:
- try:
- query_usage_reports_inputs = QueryUsageReportsInputs(
- at=inputs.at,
- skip_capture_event=inputs.skip_capture_event,
- )
- await workflow.execute_activity(
- query_usage_reports,
- query_usage_reports_inputs,
- start_to_close_timeout=timedelta(minutes=40),
- retry_policy=common.RetryPolicy(
- maximum_attempts=3,
- initial_interval=timedelta(minutes=1),
- ),
- heartbeat_timeout=timedelta(minutes=4),
- )
-
- except Exception as e:
- logger.exception("Error running usage reports", error=e)
- capture_exception(e)
- raise