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.

fix: Move N+1 query into a single query to reduce cost of aggregate-and-chunk-org-reports (#57844)

Marce Collabf7cf6dc78d
diff --git a/posthog/temporal/tests/usage_report/test_parity.py b/posthog/temporal/tests/usage_report/test_parity.py
index b9ed4e517dfd..cc6dd6c46a1a 100644
--- a/posthog/temporal/tests/usage_report/test_parity.py
+++ b/posthog/temporal/tests/usage_report/test_parity.py
@@ -1,37 +1,38 @@
-"""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.
+"""End-to-end parity between the legacy Celery `send_all_org_usage_reports`
+task and the new Temporal `aggregate-and-chunk-org-reports` activity.
+
+The same seeded `all_data` is fed into both flows against an in-memory S3
+and SQS. The Celery path's per-org SQS payloads are decoded
+(base64 → gzip → JSON), the Temporal path's per-org JSONL chunks are
+decoded (gzip → JSONL), and the per-org dicts must match byte-for-byte
+for every org both paths emit.
+
+This is intentionally end-to-end rather than walking private helpers — we
+want drift in chunk framing, multi-key fan-out, SQS encoding, or activity
+wiring to fail the test, not just drift in one shared serializer.
"""
+import io
+import gzip
import json
-import dataclasses
+import base64
+import asyncio
from datetime import UTC, datetime
from typing import Any
import pytest
+from unittest import mock
+
+from django.db import connection
+from django.test.utils import CaptureQueriesContext
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.tasks.usage_report import send_all_org_usage_reports
+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, AggregateResult, RunQueryToS3Result, WorkflowContext
+from posthog.utils import get_previous_day
def _all_destination_keys() -> list[str]:
@@ -47,37 +48,14 @@ def _all_destination_keys() -> list[str]:
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.
+ Realistic enough to prove the team→org rollup math is identical across
+ both paths: 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},
@@ -99,124 +77,221 @@ def _seed_all_data(team_a_id: int, team_b_id: int, team_c_id: int) -> dict[str,
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.
+def _install_in_memory_object_storage(monkeypatch: pytest.MonkeyPatch) -> dict[str, bytes]:
+ """Patch the S3 helpers used by the Temporal flow to read/write a dict.
+
+ Returns the dict so the test can read what was written and pre-seed
+ keys for `load_all_data` to read back.
"""
- 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()
- }
+ s3: dict[str, bytes] = {}
+ def _write(key: str, content: Any, extras: Any = None, bucket: Any = None) -> None:
+ s3[key] = content.encode("utf-8") if isinstance(content, str) else content
-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 _write_stream(key: str, fileobj: io.IOBase, extras: Any = None, bucket: Any = None) -> None:
+ s3[key] = fileobj.read()
+ def _read_bytes(key: str, bucket: Any = None, *, missing_ok: bool = False) -> bytes | None:
+ if key not in s3:
+ if missing_ok:
+ return None
+ raise FileNotFoundError(key)
+ return s3[key]
-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.
+ monkeypatch.setattr("posthog.storage.object_storage.write", _write)
+ monkeypatch.setattr("posthog.storage.object_storage.write_stream", _write_stream)
+ monkeypatch.setattr("posthog.storage.object_storage.read_bytes", _read_bytes)
+ return s3
- 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)
+def _install_fake_sqs_producer(monkeypatch: pytest.MonkeyPatch) -> list[dict[str, Any]]:
+ """Patch `ee.sqs.SQSProducer.get_sqs_producer` to return a fake producer.
- 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)
+ Returns the list each `send_message` call appends to, so the test can
+ decode the captured per-org payloads after the Celery task runs.
+ """
+ captured: list[dict[str, Any]] = []
- # Both paths must produce the same set of organizations.
- assert set(celery_dicts.keys()) == set(temporal_dicts.keys())
+ class _FakeProducer:
+ def send_message(self, message_body: str, message_attributes: dict[str, str]) -> dict[str, str]:
+ captured.append({"body": message_body, "attributes": message_attributes})
+ return {"MessageId": "fake"}
- # 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]}"
- )
+ monkeypatch.setattr("ee.sqs.SQSProducer.get_sqs_producer", lambda _name: _FakeProducer())
+ return captured
- # 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 _seed_temporal_query_files(
+ s3: dict[str, bytes],
+ ctx: WorkflowContext,
+ seeded: dict[str, dict[int, int]],
+) -> list[RunQueryToS3Result]:
+ """Pre-write the per-query S3 files the activity reads via `load_all_data`.
-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.
+ Inverts `multi_keys_mapping` so multi-output specs end up in the
+ source-key shape the aggregator expects to fan back out.
"""
- 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()
+ results: list[RunQueryToS3Result] = []
+ for spec in QUERIES:
+ key = queries_key(ctx, spec.name)
+ if spec.output == "multi":
+ payload: Any = {
+ source: [{"team_id": tid, "total": cnt} for tid, cnt in seeded[dest].items()]
+ for source, dest in spec.multi_keys_mapping.items()
+ }
+ else:
+ payload = [{"team_id": tid, "total": cnt} for tid, cnt in seeded[spec.name].items()]
+ write_json(key, payload)
+ assert key in s3, f"_install_in_memory_object_storage didn't capture write for {key}"
+ results.append(RunQueryToS3Result(query_name=spec.name, s3_key=key, duration_ms=0))
+ return results
+
+
+def _decode_celery_sqs_messages(messages: list[dict[str, Any]]) -> dict[str, dict[str, Any]]:
+ """Reverse `_queue_report`: base64 → gzip → JSON, keyed by org_id."""
+ out: dict[str, dict[str, Any]] = {}
+ for msg in messages:
+ decoded = json.loads(gzip.decompress(base64.b64decode(msg["body"])).decode("utf-8"))
+ out[decoded["organization_id"]] = decoded["usage_report"]
+ return out
+
+
+def _decode_temporal_chunks(s3: dict[str, bytes], chunk_keys: list[str]) -> dict[str, dict[str, Any]]:
+ """Reverse the activity's chunk writer: gzip → JSONL → per-org dict."""
+ out: dict[str, dict[str, Any]] = {}
+ for key in chunk_keys:
+ gz = gzip.decompress(s3[key]).decode("utf-8")
+ for line in gz.splitlines():
+ obj = json.loads(line)
+ out[obj["organization_id"]] = obj["usage_report"]
+ return out
+
+
[email protected]_db(transaction=True)
+def test_end_to_end_parity_celery_task_vs_temporal_activity(
+ activity_environment: Any,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Both production paths must produce the same per-org bytes for the
+ same `all_data` snapshot. Drift here is what billing's parity check
+ will catch in production.
+
+ Two orgs × three teams (org_a has two teams so the multi-team rollup
+ is exercised; org_b has one). The shared test DB may already contain
+ other orgs with no usage; those are excluded by the Celery path's
+ `has_non_zero_usage` gate, so we compare only the orgs Celery actually
+ sends.
+ """
+ org_a = Organization.objects.create(name="E2E Parity A")
+ org_b = Organization.objects.create(name="E2E Parity B")
+ team_a1 = Team.objects.create(organization=org_a, name="A1")
+ team_a2 = Team.objects.create(organization=org_a, name="A2")
+ team_b = Team.objects.create(organization=org_b, name="B")
- celery_dicts = _celery_serialize(team.id, team.id, team.id, period_start)
+ celery_at = datetime(2026, 5, 5, 0, 0, 0, tzinfo=UTC)
+ period_start, period_end = get_previous_day(celery_at)
+ seeded = _seed_all_data(team_a1.id, team_a2.id, team_b.id)
+
+ s3 = _install_in_memory_object_storage(monkeypatch)
+ sqs_messages = _install_fake_sqs_producer(monkeypatch)
+
+ # Don't let the Celery task short-circuit on the kill-switch flag,
+ # and silence the start/end PostHog `capture` calls.
+ monkeypatch.setattr("posthoganalytics.feature_enabled", lambda *a, **kw: False)
+ monkeypatch.setattr("posthog.tasks.usage_report.get_ph_client", lambda *a, **kw: mock.MagicMock())
+ # Skip the heavy gather queries — both paths use this same `seeded`
+ # dict, just shaped differently for each entry point.
+ monkeypatch.setattr(
+ "posthog.tasks.usage_report._get_all_usage_data_as_team_rows",
+ lambda *a, **kw: seeded,
+ )
- org_reports = build_org_reports(all_data, period_start)
- assert str(org.id) in org_reports
+ # ---- Celery path ----
+ send_all_org_usage_reports(at=celery_at.isoformat(), skip_capture_event=True)
+ celery_per_org = _decode_celery_sqs_messages(sqs_messages)
+
+ # ---- Temporal path ----
+ ctx = WorkflowContext(
+ run_id="e2e-parity-test",
+ period_start=period_start,
+ period_end=period_end,
+ date_str=period_start.strftime("%Y-%m-%d"),
+ organization_ids=None,
+ )
+ query_results = _seed_temporal_query_files(s3, ctx, seeded)
+ # The activity is async; the test is sync so DB setup can use the
+ # ORM directly. `asyncio.run` drives the activity in a fresh loop.
+ result: AggregateResult = asyncio.run(
+ activity_environment.run(
+ aggregate_and_chunk_org_reports,
+ AggregateInputs(ctx=ctx, query_results=query_results),
+ )
+ )
+ temporal_per_org = _decode_temporal_chunks(s3, result.chunk_keys)
+
+ # Both of our test orgs should have non-zero usage, so Celery should
+ # have queued them. Sanity-check that before comparing, otherwise a
+ # silent zero-usage filter could hide actual drift.
+ assert str(org_a.id) in celery_per_org
+ assert str(org_b.id) in celery_per_org
+
+ # Celery skips zero-usage orgs; Temporal includes them. Compare only
+ # the orgs Celery emitted — those are the ones billing receives.
+ for org_id, celery_dict in celery_per_org.items():
+ assert org_id in temporal_per_org, f"Celery emitted {org_id} but Temporal didn't"
+ celery_json = json.dumps(celery_dict, sort_keys=True, default=str)
+ temporal_json = json.dumps(temporal_per_org[org_id], sort_keys=True, default=str)
+ assert celery_json == temporal_json, (
+ f"Drift between Celery SQS payload and Temporal chunk for org {org_id}.\n"
+ f"Celery (first 500 chars):\n{celery_json[:500]}\n"
+ f"Temporal (first 500 chars):\n{temporal_json[:500]}"
+ )
- 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)]
+ # Sanity-check the rollup math — org_a sums its two teams, org_b
+ # only has one. If this drifts, the rest of the parity numbers are
+ # suspect.
+ assert temporal_per_org[str(org_a.id)]["event_count_in_period"] == 100 + 50
+ assert temporal_per_org[str(org_b.id)]["event_count_in_period"] == 25
+ assert temporal_per_org[str(org_a.id)]["team_count"] == 2
+ assert temporal_per_org[str(org_b.id)]["team_count"] == 1
@pytest.mark.django_db
-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.
+def test_temporal_build_org_reports_does_not_run_per_org_membership_queries() -> None:
+ """The Temporal-local `aggregator.build_org_reports` must fetch
+ organization membership counts in bulk. The legacy Celery facade still
+ runs one `OrganizationMembership.count()` per organization inside its
+ team loop — that's the cost we lifted out of the
+ `aggregate-and-chunk-org-reports` activity by routing it through the
+ aggregator's own builder instead of the shared one.
"""
- 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)
+ from posthog.temporal.usage_report.aggregator import (
+ build_org_reports as temporal_build_org_reports,
+ get_org_user_counts,
+ )
- facade = build_org_reports(all_data, period_start)
+ # Create a meaningful number of fresh orgs/teams so the per-org N+1
+ # would have clear daylight from the bulk-fetch path. Without this,
+ # query counts are low enough that any reasonable cap would pass.
+ fresh_orgs: list[Organization] = []
+ for i in range(20):
+ org = Organization.objects.create(name=f"Bulk Org {i}")
+ Team.objects.create(organization=org, name=f"Team {i}")
+ fresh_orgs.append(org)
- 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)])
+ period_start = datetime(2026, 5, 4, 0, 0, 0, tzinfo=UTC)
+ all_data: dict[str, dict[int, int]] = {key: {} for key in _all_destination_keys()}
+
+ with CaptureQueriesContext(connection) as captured:
+ org_user_counts = get_org_user_counts()
+ temporal_build_org_reports(all_data, period_start, org_user_counts)
+
+ # The Temporal path runs ~2 queries (teams + bulk memberships)
+ # regardless of org count. The legacy Celery path runs 1 + N. Cap
+ # well below `1 + N` so any per-org N+1 here blows the test, while
+ # leaving slack for harmless query-count drift (savepoints etc.).
+ assert len(captured.captured_queries) <= 5, (
+ f"Temporal build_org_reports issued {len(captured.captured_queries)} "
+ f"queries — with {len(fresh_orgs)} fresh orgs this looks like a "
+ f"per-org N+1, which dominates wall-clock for the aggregation activity."
+ )
diff --git a/posthog/temporal/usage_report/activities.py b/posthog/temporal/usage_report/activities.py
index b77df6325aad..b045b5826898 100644
--- a/posthog/temporal/usage_report/activities.py
+++ b/posthog/temporal/usage_report/activities.py
@@ -17,12 +17,14 @@ from asgiref.sync import sync_to_async
from temporalio import activity
from posthog.sync import database_sync_to_async, database_sync_to_async_pool
-from posthog.tasks.usage_report import build_org_reports, get_instance_metadata
+from posthog.tasks.usage_report import get_instance_metadata
from posthog.temporal.common.heartbeat import Heartbeater
from posthog.temporal.usage_report.aggregator import (
batched,
build_manifest,
+ build_org_reports,
filter_org_reports,
+ get_org_user_counts,
iter_chunk_lines,
load_all_data,
sort_org_reports,
@@ -110,7 +112,11 @@ async def aggregate_and_chunk_org_reports(inputs: AggregateInputs) -> AggregateR
@database_sync_to_async
def aggregate_per_org() -> dict[str, Any]:
- org_reports = build_org_reports(all_data, inputs.ctx.period_start)
+ # Bulk-fetch membership counts once instead of letting the org
+ # builder issue a Postgres count() per organization. See
+ # `aggregator.build_org_reports` for the rationale.
+ org_user_counts = get_org_user_counts()
+ org_reports = build_org_reports(all_data, inputs.ctx.period_start, org_user_counts)
org_reports = filter_org_reports(org_reports, inputs.ctx.organization_ids)
return org_reports
diff --git a/posthog/temporal/usage_report/aggregator.py b/posthog/temporal/usage_report/aggregator.py
index 5bd1b96c8e26..01bc1c72c960 100644
--- a/posthog/temporal/usage_report/aggregator.py
+++ b/posthog/temporal/usage_report/aggregator.py
@@ -1,20 +1,31 @@
-"""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.
+"""Helpers for the aggregation step of the Temporal usage-reports flow.
+
+Most of this module is pure logic — turning S3-backed query results into the
+legacy `all_data` shape, fanning multi-key queries back out into their
+destination keys, and shaping per-organization JSONL lines for the chunked
+output. The Temporal-local replacement for the legacy `build_org_reports`
+also lives here so the activity can drive aggregation without touching the
+Celery code path; that one bulk-fetches `OrganizationMembership` counts so
+the per-org `count()` N+1 in the legacy helper never fires for Temporal.
+Activities import from here.
"""
import itertools
+import dataclasses
from collections.abc import Iterable, Iterator
+from datetime import datetime
from typing import Any
from django.conf import settings
+from django.db.models import Count
+from posthog.models import OrganizationMembership, Team
from posthog.tasks.usage_report import (
InstanceMetadata,
OrgReport,
+ UsageReportCounters,
+ _get_team_report,
+ _get_teams_for_usage_reports,
convert_team_usage_rows_to_dict,
serialize_full_org_report,
)
@@ -115,3 +126,83 @@ def filter_org_reports(
def sort_org_reports(org_reports: dict[str, OrgReport]) -> list[OrgReport]:
"""Deterministic ordering so chunk contents are stable across retries."""
return sorted(org_reports.values(), key=lambda r: r.organization_id)
+
+
+def get_org_user_counts() -> dict[str, int]:
+ """Bulk membership count per organization, keyed by `str(org_id)`.
+
+ The legacy `_add_team_report_to_org_reports` runs one
+ `OrganizationMembership.count()` per organization inside its team loop,
+ which dominated the aggregation activity's wall-clock at ~50k orgs. The
+ Temporal flow fetches the whole map once up front and looks up by
+ `str(org_id)`. Orgs without memberships are absent — callers default to
+ 0. We keep this off the Celery path on purpose; that path still uses
+ the per-org helper.
+ """
+ # `.iterator()` skips Django's QuerySet result cache, so we don't hold
+ # the full list of rows alongside the dict we're building. `chunk_size`
+ # just tunes the server-side cursor batch.
+ return {
+ str(row["organization_id"]): row["count"]
+ for row in OrganizationMembership.objects.values("organization_id")
+ .annotate(count=Count("id"))
+ .iterator(chunk_size=10_000)
+ }
+
+
+def build_org_reports(
+ all_data: dict[str, Any],
+ period_start: datetime,
+ org_user_counts: dict[str, int],
+) -> dict[str, OrgReport]:
+ """Temporal-local replacement for `posthog.tasks.usage_report.build_org_reports`.
+
+ Same shape and semantics as the legacy facade, but takes a pre-fetched
+ `org_user_counts` dict instead of issuing one Postgres `count()` per
+ organization. The legacy facade is intentionally left untouched so the
+ Celery flow's behavior is preserved — the parity tests pin both paths
+ against each other.
+ """
+ org_reports: dict[str, OrgReport] = {}
+ for team in _get_teams_for_usage_reports():
+ team_report = _get_team_report(all_data, team)
+ _add_team_report_to_org_reports(org_reports, team, team_report, period_start, org_user_counts)
+ return org_reports
+
+
+def _add_team_report_to_org_reports(
+ org_reports: dict[str, OrgReport],
+ team: Team,
+ team_report: UsageReportCounters,
+ period_start: datetime,
+ org_user_counts: dict[str, int],
+) -> None:
+ """Mirror of `posthog.tasks.usage_report._add_team_report_to_org_reports`
+ that reads `organization_user_count` from the bulk dict instead of the
+ per-org Postgres helper. Behavior is otherwise identical.
+ """
+ org_id = str(team.organization.id)
+ if org_id not in org_reports:
+ org_report = OrgReport(
+ date=period_start.strftime("%Y-%m-%d"),
+ organization_id=org_id,
+ organization_name=team.organization.name,
+ organization_created_at=team.organization.created_at.isoformat(),
+ organization_user_count=org_user_counts.get(org_id, 0),
+ team_count=1,
+ teams={str(team.id): team_report},
+ **dataclasses.asdict(team_report), # Clone the team report as the basis
+ )
+ org_reports[org_id] = org_report
+ else:
+ org_report = org_reports[org_id]
+ org_report.teams[str(team.id)] = team_report
+ org_report.team_count += 1
+
+ for field in dataclasses.fields(UsageReportCounters):
+ if hasattr(team_report, field.name):
+ setattr(
+ org_report,
+ field.name,
+ getattr(org_report, field.name) + getattr(team_report, field.name),
+ )