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.

chore(usage-reports): Optimizations for usage reports aggregator (#57980)

Marce Coll93e0d40a6432
diff --git a/posthog/tasks/usage_report.py b/posthog/tasks/usage_report.py
index df9b21ed4672..cb67ee012e5d 100644
--- a/posthog/tasks/usage_report.py
+++ b/posthog/tasks/usage_report.py
@@ -1784,7 +1784,7 @@ def capture_report(
# extend this with future usage based products
-def has_non_zero_usage(report: FullUsageReport) -> bool:
+def has_non_zero_usage(report: UsageReportCounters) -> bool:
return (
report.event_count_in_period > 0
or report.enhanced_persons_event_count_in_period > 0
diff --git a/posthog/temporal/tests/usage_report/test_aggregate_activity.py b/posthog/temporal/tests/usage_report/test_aggregate_activity.py
index 81a4be67c73f..24ac2586b9e5 100644
--- a/posthog/temporal/tests/usage_report/test_aggregate_activity.py
+++ b/posthog/temporal/tests/usage_report/test_aggregate_activity.py
@@ -43,17 +43,25 @@ 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:
+def _canned_query_payload(query_name: str, team_a_id: int, team_b_id: int, *extra_team_ids: int) -> Any:
"""Default payload per query — uses team rows where it makes sense, and
multi-key dicts for the three multi-output specs.
+
+ `extra_team_ids` lets callers seed billable events for additional teams
+ so the orgs they belong to survive the upstream `has_non_zero_usage`
+ filter. Each extra team gets a small `web_events` and
+ `event_count_in_period` row.
"""
+ extra_event_rows = [(tid, 13) for tid in extra_team_ids]
+ extra_total_rows = [(tid, 20) for tid in extra_team_ids]
+
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_events": [(team_a_id, 7), (team_b_id, 11), *extra_event_rows],
"web_lite_events": [],
"node_events": [],
"android_events": [],
@@ -90,7 +98,7 @@ def _canned_query_payload(query_name: str, team_a_id: int, team_b_id: int) -> An
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)]
+ return [(team_a_id, 100), (team_b_id, 50), *extra_total_rows]
if query_name == "teams_with_recording_count_in_period":
return [(team_a_id, 8)]
@@ -131,14 +139,16 @@ def _instance_metadata() -> InstanceMetadata:
)
-def _seed_query_results(ctx: WorkflowContext, team_a_id: int, team_b_id: int) -> list[RunQueryToS3Result]:
+def _seed_query_results(
+ ctx: WorkflowContext, team_a_id: int, team_b_id: int, *extra_team_ids: 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))
+ write_json(key, _canned_query_payload(spec.name, team_a_id, team_b_id, *extra_team_ids))
query_results.append(RunQueryToS3Result(query_name=spec.name, s3_key=key, duration_ms=1))
return query_results
@@ -234,15 +244,16 @@ async def test_aggregate_chunks_into_batches_of_ten_thousand(
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")
+ extra_team_b = 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.
+ # the chunk counts. Each team gets billable events so all three orgs
+ # survive the upstream `has_non_zero_usage` filter.
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)
+ query_results = _seed_query_results(ctx, team.id, extra_team_a.id, extra_team_b.id)
with (
patch.object(module, "CHUNK_SIZE_ORGS", 2),
@@ -258,6 +269,7 @@ async def test_aggregate_chunks_into_batches_of_ten_thousand(
# 3 orgs / 2 per chunk = 2 chunks (2 + 1)
assert result.total_orgs == 3
+ assert result.total_orgs_with_usage == 3
assert len(result.chunk_keys) == 2
all_lines: list[dict] = []
@@ -272,6 +284,59 @@ async def test_aggregate_chunks_into_batches_of_ten_thousand(
assert manifest["chunk_keys"] == result.chunk_keys
+async def test_aggregate_drops_orgs_with_no_usage_from_chunks(
+ minio_workflow_ctx: WorkflowContext, activity_environment
+) -> None:
+ """Orgs with zero billable usage must not show up in any chunk, but
+ they should still be counted in `total_orgs` (which represents orgs in
+ scope) so the manifest stays a faithful snapshot of the run."""
+ org_with_usage = await _make_org("With Usage")
+ team_with_usage = await _make_team(org_with_usage, "T")
+
+ org_idle = await _make_org("Idle")
+ await _make_team(org_idle, "Idle T")
+
+ ctx = minio_workflow_ctx.model_copy(update={"organization_ids": [str(org_with_usage.id), str(org_idle.id)]})
+
+ # Hand-roll a sparse seed so only `team_with_usage` has billable
+ # events — every other team in the org pool stays at zero counters.
+ # The canned helper would assign web_events to the second team, which
+ # would defeat the filter test.
+ query_results: list[RunQueryToS3Result] = []
+ for spec in QUERIES:
+ if spec.name == "teams_with_event_count_in_period":
+ payload: Any = [(team_with_usage.id, 100)]
+ elif spec.name == "all_event_metrics":
+ payload = _canned_query_payload(spec.name, team_with_usage.id, team_with_usage.id)
+ elif spec.name == "exceptions_captured":
+ payload = _canned_query_payload(spec.name, team_with_usage.id, team_with_usage.id)
+ elif spec.name == "api_queries_metrics":
+ payload = {"count": [], "read_bytes": []}
+ else:
+ payload = []
+ key = queries_key(ctx, spec.name)
+ write_json(key, payload)
+ query_results.append(RunQueryToS3Result(query_name=spec.name, s3_key=key, duration_ms=1))
+
+ 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
+ assert result.total_orgs_with_usage == 1
+ assert len(result.chunk_keys) == 1
+
+ rows = _read_jsonl_gz(result.chunk_keys[0])
+ assert {row["organization_id"] for row in rows} == {str(org_with_usage.id)}
+
+
@pytest.mark.django_db
@pytest.mark.asyncio
async def test_aggregate_filters_by_organization_ids(minio_workflow_ctx: WorkflowContext, activity_environment) -> None:
diff --git a/posthog/temporal/tests/usage_report/test_aggregator.py b/posthog/temporal/tests/usage_report/test_aggregator.py
index b7b96448677d..31aa75733005 100644
--- a/posthog/temporal/tests/usage_report/test_aggregator.py
+++ b/posthog/temporal/tests/usage_report/test_aggregator.py
@@ -2,22 +2,24 @@
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.
+`filter_org_reports`, `filter_orgs_with_usage`, `sort_org_reports`.
+No Django / Temporal / S3 required.
"""
import json
+import dataclasses
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.tasks.usage_report import InstanceMetadata, OrgReport, UsageReportCounters
from posthog.temporal.usage_report.aggregator import (
batched,
build_manifest,
filter_org_reports,
+ filter_orgs_with_usage,
iter_chunk_lines,
load_all_data,
sort_org_reports,
@@ -163,7 +165,7 @@ class _FakeOrgReport:
self.organization_id = organization_id
-def test_iter_chunk_lines_emits_id_and_report_with_usage_flag() -> None:
+def test_iter_chunk_lines_emits_id_and_report() -> None:
org_a = _FakeOrgReport("org-a")
org_b = _FakeOrgReport("org-b")
@@ -178,24 +180,11 @@ def test_iter_chunk_lines_emits_id_and_report_with_usage_flag() -> 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,
- ),
+ {"organization_id": "org-a", "usage_report": {"event_count_in_period": 10, "has_non_zero_usage": True}},
+ {"organization_id": "org-b", "usage_report": {"event_count_in_period": 0, "has_non_zero_usage": 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 ------------------------------------------------------
@@ -259,3 +248,41 @@ def test_sort_org_reports_orders_by_organization_id() -> None:
)
out = sort_org_reports(reports)
assert [r.organization_id for r in out] == ["a", "m", "z"]
+
+
+# ---- filter_orgs_with_usage ----------------------------------------------
+
+
+def _empty_org_report(organization_id: str, **overrides: Any) -> OrgReport:
+ """Construct an `OrgReport` with every counter zeroed out. Override
+ individual counters per test to exercise the `has_non_zero_usage`
+ branches without listing the full field set every time.
+ """
+ counter_fields: dict[str, Any] = {f.name: 0 for f in dataclasses.fields(UsageReportCounters)}
+ # `dwh_*_storage_in_s3_in_mib` are floats, but `0` works fine.
+ counter_fields.update(overrides)
+ return OrgReport(
+ date="2026-05-04",
+ organization_id=organization_id,
+ organization_name="org",
+ organization_created_at="2024-01-01T00:00:00+00:00",
+ organization_user_count=0,
+ team_count=0,
+ teams={},
+ **counter_fields,
+ )
+
+
+def test_filter_orgs_with_usage_keeps_only_orgs_with_billable_counters() -> None:
+ reports = {
+ "with-events": _empty_org_report("with-events", event_count_in_period=1),
+ "with-recordings": _empty_org_report("with-recordings", recording_count_in_period=1),
+ "idle": _empty_org_report("idle"),
+ # Counters not in `has_non_zero_usage` (dashboard counts, query
+ # bytes read, etc.) must not keep an org in.
+ "non-billable-only": _empty_org_report("non-billable-only", dashboard_count=10, query_app_bytes_read=5_000_000),
+ }
+
+ out = filter_orgs_with_usage(reports)
+
+ assert set(out.keys()) == {"with-events", "with-recordings"}
diff --git a/posthog/temporal/tests/usage_report/test_parity.py b/posthog/temporal/tests/usage_report/test_parity.py
index cc6dd6c46a1a..44db901bfdbb 100644
--- a/posthog/temporal/tests/usage_report/test_parity.py
+++ b/posthog/temporal/tests/usage_report/test_parity.py
@@ -235,8 +235,8 @@ def test_end_to_end_parity_celery_task_vs_temporal_activity(
assert str(org_a.id) in celery_per_org
assert str(org_b.id) in celery_per_org
- # Celery skips zero-usage orgs; Temporal includes them. Compare only
- # the orgs Celery emitted — those are the ones billing receives.
+ # Both paths skip zero-usage orgs; comparing on the Celery key set
+ # keeps the assertion focused on the orgs billing actually 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)
diff --git a/posthog/temporal/tests/usage_report/test_storage.py b/posthog/temporal/tests/usage_report/test_storage.py
index 05608176f843..d50a706bc84e 100644
--- a/posthog/temporal/tests/usage_report/test_storage.py
+++ b/posthog/temporal/tests/usage_report/test_storage.py
@@ -1,16 +1,15 @@
"""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
+Pure key-formatting tests don't touch storage. Roundtrip 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.
+the bucket stays tidy. Error-path tests (failed delete) 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
@@ -23,7 +22,6 @@ from posthog.temporal.usage_report.storage import (
queries_key,
queries_prefix,
run_prefix,
- streamed_jsonl_gzip_writer,
write_json,
write_jsonl_chunk_gzip,
)
@@ -129,42 +127,18 @@ def test_write_jsonl_chunk_gzip_sets_content_headers_via_minio(minio_workflow_ct
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."""
+def test_write_jsonl_chunk_gzip_handles_empty_input_via_minio(minio_workflow_ctx: WorkflowContext) -> None:
+ """An empty `lines` iterable still produces a valid (empty-after-decompress)
+ object so the activity can write a chunk for "0 orgs in this batch"
+ without blowing up.
+ """
key = chunk_key(minio_workflow_ctx, 0)
+ count = write_jsonl_chunk_gzip(key, [])
- 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
-
+ assert count == 0
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
+ assert gzip.decompress(body) == b""
# ---- mocked error paths --------------------------------------------------
@@ -173,37 +147,24 @@ async def test_streamed_jsonl_gzip_writer_skips_upload_on_exception_via_minio(
# 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.
+def test_write_jsonl_chunk_gzip_does_one_put_object_call() -> None:
+ """Each chunk should land via a single `object_storage.write` call.
+ Multiple writes per chunk would defeat the whole point of batching the
+ upload — verify that path here so it stays single-shot.
"""
- 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
+ with patch("posthog.temporal.usage_report.storage.object_storage.write") as mock_write:
+ write_jsonl_chunk_gzip(
+ "some/key.jsonl.gz",
+ [
+ {"organization_id": "org-1"},
+ {"organization_id": "org-2"},
+ ],
+ )
+
+ assert mock_write.call_count == 1
+ _, kwargs = mock_write.call_args
+ assert kwargs["extras"]["ContentType"] == "application/x-ndjson"
+ assert kwargs["extras"]["ContentEncoding"] == "gzip"
def test_delete_keys_continues_on_failure() -> None:
diff --git a/posthog/temporal/usage_report/activities.py b/posthog/temporal/usage_report/activities.py
index b045b5826898..8c70ec690d99 100644
--- a/posthog/temporal/usage_report/activities.py
+++ b/posthog/temporal/usage_report/activities.py
@@ -8,6 +8,7 @@ elsewhere so these stay easy to read and mock in tests.
import json
import time
+import asyncio
from typing import Any
from django.conf import settings
@@ -24,6 +25,7 @@ from posthog.temporal.usage_report.aggregator import (
build_manifest,
build_org_reports,
filter_org_reports,
+ filter_orgs_with_usage,
get_org_user_counts,
iter_chunk_lines,
load_all_data,
@@ -37,8 +39,8 @@ from posthog.temporal.usage_report.storage import (
delete_keys,
manifest_key,
queries_key,
- streamed_jsonl_gzip_writer,
write_json,
+ write_jsonl_chunk_gzip,
)
from posthog.temporal.usage_report.types import (
AggregateInputs,
@@ -52,7 +54,7 @@ from posthog.utils import get_instance_region
logger = structlog.get_logger(__name__)
-CHUNK_SIZE_ORGS = 10_000
+CHUNK_SIZE_ORGS = 50_000
SQS_POINTER_VERSION = 2
# Separate SQS queue for v2 messages so the existing per-org `usage_reports`
@@ -132,23 +134,34 @@ async def aggregate_and_chunk_org_reports(inputs: AggregateInputs) -> AggregateR
# 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)
+ total_orgs = len(org_reports)
+ orgs_with_usage = filter_orgs_with_usage(org_reports)
+ total_orgs_with_usage = len(orgs_with_usage)
+
+ sorted_reports = sort_org_reports(orgs_with_usage)
+ batches = list(enumerate(batched(sorted_reports, CHUNK_SIZE_ORGS)))
+ chunk_keys: list[str] = [chunk_key(inputs.ctx, index) for index, _ in batches]
+
+ # Each chunk is an independent S3 object, so fan the encode+gzip+PUT
+ # out across the thread pool. `thread_sensitive=False` opts out of
+ # the shared-thread default so the PUTs run concurrently — boto3
+ # releases the GIL during the network call, so they genuinely
+ # overlap on the wire. Using `asyncio.TaskGroup` (over
+ # `asyncio.gather`) means a single failed upload doesn't cancel
+ # in-flight peer uploads mid-PUT; the group waits for every
+ # started task to finish or fail before re-raising, so Temporal
+ # retries from a clean state.
+ def write_chunk(key: str, batch: list[Any]) -> None:
+ write_jsonl_chunk_gzip(key, iter_chunk_lines(batch, instance_metadata))
+
+ async with asyncio.TaskGroup() as tg:
+ for index, batch in batches:
+ tg.create_task(sync_to_async(write_chunk, thread_sensitive=False)(chunk_keys[index], batch))
manifest = build_manifest(
inputs.ctx,
chunk_keys=chunk_keys,
- total_orgs=len(org_reports),
+ total_orgs=total_orgs,
total_orgs_with_usage=total_orgs_with_usage,
region=get_instance_region() or "",
version=SQS_POINTER_VERSION,
@@ -159,7 +172,7 @@ async def aggregate_and_chunk_org_reports(inputs: AggregateInputs) -> AggregateR
return AggregateResult(
chunk_keys=chunk_keys,
manifest_key=m_key,
- total_orgs=len(org_reports),
+ total_orgs=total_orgs,
total_orgs_with_usage=total_orgs_with_usage,
)
diff --git a/posthog/temporal/usage_report/aggregator.py b/posthog/temporal/usage_report/aggregator.py
index 01bc1c72c960..a38211ffde3b 100644
--- a/posthog/temporal/usage_report/aggregator.py
+++ b/posthog/temporal/usage_report/aggregator.py
@@ -27,6 +27,7 @@ from posthog.tasks.usage_report import (
_get_team_report,
_get_teams_for_usage_reports,
convert_team_usage_rows_to_dict,
+ has_non_zero_usage,
serialize_full_org_report,
)
from posthog.temporal.usage_report.queries import QUERY_INDEX
@@ -58,20 +59,30 @@ def load_all_data(query_results: list[RunQueryToS3Result]) -> dict[str, dict[int
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.
+) -> Iterator[dict[str, Any]]:
+ """Yield the JSONL line dict billing consumes 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.
+ Filtering by `has_non_zero_usage` happens upstream in the activity, so
+ everything yielded here is expected to have usage.
"""
for org_report in org_reports:
report_dict = serialize_full_org_report(org_report, instance_metadata)
- line = {
+ yield {
"organization_id": org_report.organization_id,
"usage_report": report_dict,
}
- yield line, bool(report_dict.get("has_non_zero_usage"))
+
+
+def filter_orgs_with_usage(org_reports: dict[str, OrgReport]) -> dict[str, OrgReport]:
+ """Drop org reports with no billable usage before serialization. Reuses
+ the legacy `has_non_zero_usage` directly on `OrgReport`s — every field
+ it checks lives on `UsageReportCounters`, the base class shared by
+ `OrgReport` and `FullUsageReport`, so we skip the
+ `dataclasses.asdict(FullUsageReport)` round-trip the legacy path forces.
+ Skipping that on the >99% of orgs without usage is the dominant CPU
+ win in the aggregation activity.
+ """
+ return {oid: report for oid, report in org_reports.items() if has_non_zero_usage(report)}
def batched(iterable: Iterable[Any], size: int) -> Iterator[list[Any]]:
diff --git a/posthog/temporal/usage_report/storage.py b/posthog/temporal/usage_report/storage.py
index 474a7e1ac804..1b9793f6dcdd 100644
--- a/posthog/temporal/usage_report/storage.py
+++ b/posthog/temporal/usage_report/storage.py
@@ -11,14 +11,12 @@ configuration.
import io
import gzip
import json
-from collections.abc import AsyncIterator, Iterable
-from contextlib import asynccontextmanager
+from collections.abc import Iterable
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
@@ -81,85 +79,32 @@ def read_json(key: str) -> Any:
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 write_jsonl_chunk_gzip(key: str, lines: Iterable[dict[str, Any]]) -> int:
+ """Stream-encode `lines` as JSONL straight into gzip, then PUT the
+ compressed body to S3 in a single `put_object` call.
+
+ Per-line: one encoded `bytes` is fed to `gzip.GzipFile.write` and
+ immediately compressed into the underlying `BytesIO`. We never hold
+ the whole uncompressed payload — peak memory per chunk is roughly
+ `compressed_size` plus gzip's 32 KB window and one in-flight encoded
+ line. That matters when several chunks are written concurrently, since
+ a naive `b"\\n".join(...)` would double-allocate ~25–50 MB per chunk.
"""
-
- 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:
+ line_count = 0
+ buffer = io.BytesIO()
+ with gzip.GzipFile(fileobj=buffer, mode="wb") as gz:
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)
-
+ gz.write(json.dumps(line, separators=(",", ":"), default=str).encode("utf-8"))
+ gz.write(b"\n")
+ line_count += 1
-def _upload_gzipped_jsonl(key: str, body: bytes) -> None:
- object_storage.write_stream(
+ object_storage.write(
key,
- io.BytesIO(body),
+ buffer.getvalue(),
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
+ return line_count
def delete_keys(keys: Iterable[str]) -> int: