:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(usage-reports): add day_offset input and daily finalizer schedule (#68113)
Marce Coll842e2c810614
diff --git a/posthog/temporal/schedule.py b/posthog/temporal/schedule.pyindex fb2a75ded3fa..ff5e42ca19ae 100644--- a/posthog/temporal/schedule.py+++ b/posthog/temporal/schedule.py@@ -577,19 +577,21 @@ async def cleanup_legacy_session_summarization_schedules(client: Client):async def create_run_usage_reports_schedule(client: Client):- """Temporal-based usage report run every 3 hours at minute 45 (8 times a day).-- The 04:45 UTC slot 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.+ """Intraday usage report run every 3 hours at minute 45 (8 times a day).++ Reports *today's* usage so far (`day_offset=0`) so billing gets fresh+ numbers throughout the day. A failed slot is superseded by the next one+ 3 hours later, so no retries. The complete-day capture is handled by the+ daily finalizer schedule (`create_finalize_usage_reports_schedule`). 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"),+ RunUsageReportsInputs(day_offset=0).model_dump(mode="json"),id="run-usage-reports-schedule",task_queue=settings.BILLING_TASK_QUEUE,retry_policy=common.RetryPolicy(maximum_attempts=1),@@ -617,6 +619,56 @@ async def create_run_usage_reports_schedule(client: Client):)+async def create_finalize_usage_reports_schedule(client: Client):+ """Daily finalizer for the usage reports v2 flow, 02:45 UTC.++ Reports *yesterday* (`day_offset=1`) once the day is complete — its+ pointer carries `report_completeness="complete"`, billing's signal that+ the numbers are final for that date.+ 02:45 leaves ~2.75 hours for ingestion lag after midnight, gives the+ 01:45 intraday slot a full hour to finish (the two schedules' SKIP+ policies don't see each other, so spacing is the only concurrency+ control), and stays ahead of the legacy Celery run at 03:45 UTC. Unlike+ the intraday schedule this run has no later slot to supersede it, so the+ retry policy keeps re-running it across the day (5m, 10m, ... capped at+ 2h) until it succeeds. Anything longer than that is a manual backfill:+ trigger the workflow with `day_offset=N` for the missed day.+ """+ finalize_usage_reports_schedule = Schedule(+ action=ScheduleActionStartWorkflow(+ "run-usage-reports",+ RunUsageReportsInputs(day_offset=1).model_dump(mode="json"),+ id="finalize-usage-reports-schedule",+ task_queue=settings.BILLING_TASK_QUEUE,+ retry_policy=common.RetryPolicy(+ maximum_attempts=8,+ initial_interval=timedelta(minutes=5),+ maximum_interval=timedelta(hours=2),+ ),+ ),+ spec=ScheduleSpec(+ calendars=[+ ScheduleCalendarSpec(+ comment="Daily at 02:45 UTC",+ hour=[ScheduleRange(start=2, end=2)],+ minute=[ScheduleRange(start=45, end=45)],+ )+ ]+ ),+ policy=SchedulePolicy(overlap=ScheduleOverlapPolicy.SKIP),+ )++ if await a_schedule_exists(client, "finalize-usage-reports-schedule"):+ await a_update_schedule(client, "finalize-usage-reports-schedule", finalize_usage_reports_schedule)+ else:+ await a_create_schedule(+ client,+ "finalize-usage-reports-schedule",+ finalize_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.@@ -744,6 +796,7 @@ if settings.CLOUD_DEPLOYMENT:schedules.append(create_gemini_cleanup_sweep_schedule)schedules.append(create_replay_vision_gemini_cleanup_sweep_schedule)schedules.append(create_run_usage_reports_schedule)+ schedules.append(create_finalize_usage_reports_schedule)if settings.EE_AVAILABLE:schedules.append(create_schedule_all_subscriptions_schedule)diff --git a/posthog/temporal/tests/usage_report/test_aggregator.py b/posthog/temporal/tests/usage_report/test_aggregator.pyindex 31aa75733005..5345224b4798 100644--- a/posthog/temporal/tests/usage_report/test_aggregator.py+++ b/posthog/temporal/tests/usage_report/test_aggregator.py@@ -24,15 +24,16 @@ from posthog.temporal.usage_report.aggregator import (load_all_data,sort_org_reports,)-from posthog.temporal.usage_report.types import Manifest, RunQueryToS3Result, WorkflowContext+from posthog.temporal.usage_report.types import Manifest, ReportCompleteness, RunQueryToS3Result, WorkflowContext-def _ctx(run_id: str = "abc") -> WorkflowContext:+def _ctx(run_id: str = "abc", report_completeness: ReportCompleteness = "partial") -> 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",+ report_completeness=report_completeness,)@@ -189,7 +190,7 @@ def test_iter_chunk_lines_emits_id_and_report() -> None:def test_build_manifest_returns_typed_manifest() -> None:- ctx = _ctx(run_id="run-1")+ ctx = _ctx(run_id="run-1", report_completeness="complete")with (patch("posthog.temporal.usage_report.aggregator.settings") as mock_settings,patch("posthog.temporal.usage_report.aggregator.bucket", return_value="posthog-billing-usage-reports"),@@ -210,6 +211,7 @@ def test_build_manifest_returns_typed_manifest() -> None:assert manifest.date == "2026-05-04"assert manifest.period_start == ctx.period_startassert manifest.period_end == ctx.period_end+ assert manifest.report_completeness == "complete"assert manifest.region == "US"assert manifest.site_url == "https://us.posthog.com"assert manifest.bucket == "posthog-billing-usage-reports"diff --git a/posthog/temporal/tests/usage_report/test_pointer_activity.py b/posthog/temporal/tests/usage_report/test_pointer_activity.pyindex 23c9548c56ee..a59e070c2c58 100644--- a/posthog/temporal/tests/usage_report/test_pointer_activity.py+++ b/posthog/temporal/tests/usage_report/test_pointer_activity.py@@ -25,6 +25,7 @@ def _ctx() -> WorkflowContext: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",+ report_completeness="complete",)@@ -82,6 +83,7 @@ async def test_pointer_uses_v2_queue_and_correct_payload(activity_environment) -"date": "2026-05-04","period_start": "2026-05-04T00:00:00+00:00","period_end": "2026-05-04T23:59:59.999999+00:00",+ "report_completeness": "complete","region": "US","site_url": "https://us.posthog.com","bucket": "posthog-billing-usage-reports",diff --git a/posthog/temporal/tests/usage_report/test_schedule.py b/posthog/temporal/tests/usage_report/test_schedule.pyindex d7570a95388b..4ee65815d804 100644--- a/posthog/temporal/tests/usage_report/test_schedule.py+++ b/posthog/temporal/tests/usage_report/test_schedule.py@@ -1,4 +1,4 @@-"""Regression tests for `create_run_usage_reports_schedule`.+"""Regression tests for the usage-report schedule builders.The previous version of this code passed `dataclasses.asdict(...)` on`RunUsageReportsInputs` *after* it was migrated to pydantic — that@@ -6,24 +6,34 @@ silently raised `TypeError` the first time the worker registered theschedule, and *no* test caught it because nothing in the suite everimported 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.+These tests close that gap: they actually invoke the functions with a+mocked client and assert they (a) don't raise, (b) hand Temporal a+JSON-serializable input, and (c) carry the right `day_offset` — the+intraday schedule reports today, the finalizer reports yesterday."""import json+from datetime import timedeltaimport pytestfrom unittest.mock import AsyncMock, MagicMock, patch+from posthog.temporal.schedule import create_finalize_usage_reports_schedule, create_run_usage_reports_schedule++SCHEDULE_CASES = [+ (create_run_usage_reports_schedule, "run-usage-reports-schedule", 0),+ (create_finalize_usage_reports_schedule, "finalize-usage-reports-schedule", 1),+]+@pytest.mark.asyncio-async def test_create_run_usage_reports_schedule_does_not_raise() -> None:- """The schedule-builder must not blow up when called — covers both the[email protected]("create_schedule_fn,schedule_id,expected_day_offset", SCHEDULE_CASES)+async def test_create_usage_reports_schedules_do_not_raise(+ create_schedule_fn, schedule_id, expected_day_offset+) -> None:+ """The schedule-builders 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.@@ -32,7 +42,7 @@ async def test_create_run_usage_reports_schedule_does_not_raise() -> None: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)+ await create_schedule_fn(client)create_mock.assert_awaited_once()update_mock.assert_not_awaited()@@ -42,21 +52,26 @@ async def test_create_run_usage_reports_schedule_does_not_raise() -> None: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)+ await create_schedule_fn(client)update_mock.assert_awaited_once()create_mock.assert_not_awaited()@pytest.mark.asyncio-async def test_run_usage_reports_schedule_input_is_json_serializable() -> None:[email protected]("create_schedule_fn,schedule_id,expected_day_offset", SCHEDULE_CASES)+async def test_usage_reports_schedule_input_is_json_serializable(+ create_schedule_fn, schedule_id, expected_day_offset+) -> None:"""Temporal serializes the `ScheduleActionStartWorkflow` input via thedata converter. Even with the pydantic data converter, JSON-encodingmust round-trip — otherwise registration fails the moment it hitsthe wire. Catches the original `dataclasses.asdict(pydantic_model)`bug that landed on this branch.- """- from posthog.temporal.schedule import create_run_usage_reports_schedule+ Also pins each schedule's `day_offset`: the intraday schedule must+ report today (0) and the finalizer yesterday (1) — swapping or+ dropping these silently sends billing the wrong day.+ """captured: dict = {}async def fake_create_schedule(client, schedule_id, schedule, trigger_immediately=False):@@ -67,9 +82,9 @@ async def test_run_usage_reports_schedule_input_is_json_serializable() -> None: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())+ await create_schedule_fn(MagicMock())- assert captured["schedule_id"] == "run-usage-reports-schedule"+ assert captured["schedule_id"] == schedule_id# Pull the args out of the schedule action — Temporal stores positional# args as a list; the workflow input lives at index 0.@@ -87,4 +102,32 @@ async def test_run_usage_reports_schedule_input_is_json_serializable() -> None:revived = RunUsageReportsInputs(**decoded)assert revived.organization_ids is None- assert revived.at is None+ assert revived.day_offset == expected_day_offset+++async def test_finalizer_schedule_retries_until_the_day_is_captured() -> None:+ """The finalizer has no later slot to supersede a failed run — a single+ attempt would silently leave yesterday incomplete (the bug the finalizer+ exists to prevent). Its schedule action must keep retrying across a good+ part of the day, not give up minutes after 03:00.+ """+ captured: dict = {}++ async def fake_create_schedule(client, schedule_id, schedule, trigger_immediately=False):+ 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_finalize_usage_reports_schedule(MagicMock())++ retry_policy = captured["schedule"].action.retry_policy+ assert retry_policy is not None+ # Lower bounds, not exact values, so tuning the policy doesn't break the+ # test — but a token retry (2 quick attempts) or an uncapped-backoff+ # misconfig can't sneak through either.+ assert retry_policy.maximum_attempts >= 5+ assert retry_policy.maximum_interval is not None+ assert retry_policy.maximum_interval >= timedelta(hours=1)diff --git a/posthog/temporal/tests/usage_report/test_workflow.py b/posthog/temporal/tests/usage_report/test_workflow.pyindex dd2c206f6f0f..45f898885076 100644--- a/posthog/temporal/tests/usage_report/test_workflow.py+++ b/posthog/temporal/tests/usage_report/test_workflow.py@@ -6,12 +6,16 @@ can be verified without standing up real ClickHouse / Postgres / S3."""import uuid+from datetime import UTC, datetimeimport pytestimport temporalio.worker+from parameterized import parameterizedfrom temporalio import activity+from temporalio.client import WorkflowFailureErrorfrom temporalio.contrib.pydantic import pydantic_data_converter+from temporalio.exceptions import ApplicationErrorfrom temporalio.testing import WorkflowEnvironmentfrom temporalio.worker import Worker@@ -24,7 +28,64 @@ from posthog.temporal.usage_report.types import (RunQueryToS3Result,RunUsageReportsInputs,)-from posthog.temporal.usage_report.workflow import RunUsageReportsWorkflow+from posthog.temporal.usage_report.workflow import RunUsageReportsWorkflow, build_context+++ [+ # (day_offset, now, expected_date, expected_completeness) — intraday run mid-day reports today+ (0, datetime(2026, 5, 4, 13, 45, tzinfo=UTC), "2026-05-04", "partial"),+ # intraday run just after midnight still reports the new day, not yesterday+ (0, datetime(2026, 5, 4, 1, 45, tzinfo=UTC), "2026-05-04", "partial"),+ # finalizer run early morning reports the completed previous day+ (1, datetime(2026, 5, 4, 3, 0, tzinfo=UTC), "2026-05-03", "complete"),+ # manual backfill of an older day is also complete+ (3, datetime(2026, 5, 4, 3, 0, tzinfo=UTC), "2026-05-01", "complete"),+ ]+)+def test_build_context_reports_full_day_at_offset(+ day_offset: int, now: datetime, expected_date: str, expected_completeness: str+) -> None:+ ctx = build_context(RunUsageReportsInputs(day_offset=day_offset), run_id="run-1", now=now)++ assert ctx.date_str == expected_date+ assert ctx.report_completeness == expected_completeness+ assert ctx.period_start.isoformat() == f"{expected_date}T00:00:00+00:00"+ assert ctx.period_end.isoformat() == f"{expected_date}T23:59:59.999999+00:00"+++async def test_workflow_rejects_negative_day_offset() -> None:+ # Without the guard, a manual-trigger typo like day_offset=-1 reports a+ # future empty day and marks it "complete" for billing.+ ran_queries: list[str] = []++ @activity.defn(name="run-usage-report-query")+ async def query_mock(inputs: RunQueryToS3Inputs) -> RunQueryToS3Result:+ ran_queries.append(inputs.query_name)+ return RunQueryToS3Result(query_name=inputs.query_name, s3_key="unused", duration_ms=1)++ async with await WorkflowEnvironment.start_time_skipping(data_converter=pydantic_data_converter) as env:+ async with Worker(+ env.client,+ task_queue=str(uuid.uuid4()),+ workflows=[RunUsageReportsWorkflow],+ activities=[query_mock],+ workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),+ ) as worker:+ with pytest.raises(WorkflowFailureError) as exc_info:+ await env.client.execute_workflow(+ RunUsageReportsWorkflow.run,+ RunUsageReportsInputs(day_offset=-1),+ id=str(uuid.uuid4()),+ task_queue=worker.task_queue,+ )++ cause = exc_info.value.cause+ assert isinstance(cause, ApplicationError)+ assert cause.non_retryable+ assert "day_offset" in str(cause)+ assert ran_queries == []@pytest.mark.asyncio@@ -71,7 +132,7 @@ async def test_workflow_runs_query_then_aggregate() -> None:):result = await env.client.execute_workflow(RunUsageReportsWorkflow.run,- RunUsageReportsInputs(at="2026-05-04T12:00:00+00:00"),+ RunUsageReportsInputs(day_offset=1),id=workflow_id,task_queue=task_queue,)diff --git a/posthog/temporal/usage_report/activities.py b/posthog/temporal/usage_report/activities.pyindex f33389a052b6..0cd17a7a7c6b 100644--- a/posthog/temporal/usage_report/activities.py+++ b/posthog/temporal/usage_report/activities.py@@ -221,6 +221,9 @@ async def enqueue_pointer_message(inputs: EnqueuePointerInputs) -> None:"date": inputs.ctx.date_str,"period_start": inputs.ctx.period_start.isoformat(),"period_end": inputs.ctx.period_end.isoformat(),+ # "complete" tells billing the reported day was already over when+ # queried — its signal to treat the numbers as final for that date.+ "report_completeness": inputs.ctx.report_completeness,"region": get_instance_region(),"site_url": settings.SITE_URL,"bucket": bucket(),diff --git a/posthog/temporal/usage_report/aggregator.py b/posthog/temporal/usage_report/aggregator.pyindex a38211ffde3b..a9bad8a2de1c 100644--- a/posthog/temporal/usage_report/aggregator.py+++ b/posthog/temporal/usage_report/aggregator.py@@ -113,6 +113,7 @@ def build_manifest(date=ctx.date_str,period_start=ctx.period_start,period_end=ctx.period_end,+ report_completeness=ctx.report_completeness,region=region,site_url=settings.SITE_URL,bucket=bucket(),diff --git a/posthog/temporal/usage_report/types.py b/posthog/temporal/usage_report/types.pyindex c43e8b59cb20..af43ec75a5c9 100644--- a/posthog/temporal/usage_report/types.py+++ b/posthog/temporal/usage_report/types.py@@ -6,15 +6,25 @@ ISO-string round-tripping that plain dataclasses would force."""from datetime import datetime-from typing import Optional+from typing import Literal, Optionalfrom pydantic import BaseModel+# What billing reads off the pointer/manifest: "partial" = intraday snapshot+# of a day still in progress, "complete" = the day was already over when+# queried (finalizer or backfill run), so the numbers are final for that date.+ReportCompleteness = Literal["partial", "complete"]+class RunUsageReportsInputs(BaseModel):- """Top-level workflow input."""+ """Top-level workflow input.++ `day_offset` selects which UTC day to report on, relative to the workflow's+ start time: 0 = today (intraday, data so far), 1 = yesterday (complete),+ N = N days ago (manual backfills).+ """- at: Optional[str] = None+ day_offset: int = 0organization_ids: Optional[list[str]] = None@@ -25,6 +35,7 @@ class WorkflowContext(BaseModel):period_start: datetimeperiod_end: datetimedate_str: str+ report_completeness: ReportCompleteness = "partial"organization_ids: Optional[list[str]] = None@@ -54,6 +65,7 @@ class Manifest(BaseModel):date: strperiod_start: datetimeperiod_end: datetime+ report_completeness: ReportCompleteness = "partial"region: strsite_url: strbucket: strdiff --git a/posthog/temporal/usage_report/workflow.py b/posthog/temporal/usage_report/workflow.pyindex 7c93570a4298..ec7ce51881ea 100644--- a/posthog/temporal/usage_report/workflow.py+++ b/posthog/temporal/usage_report/workflow.py@@ -16,11 +16,10 @@ remains in production until billing migrates to consume the S3 layout.import jsonimport asyncio-from datetime import datetime, timedelta-from typing import Optional+from datetime import UTC, datetime, time, timedelta-from dateutil import parserfrom temporalio import common, workflow+from temporalio.exceptions import ApplicationErrorfrom posthog.exceptions_capture import capture_exceptionfrom posthog.temporal.common.base import PostHogWorkflow@@ -40,26 +39,30 @@ from posthog.temporal.usage_report.types import (RunUsageReportsInputs,WorkflowContext,)-from posthog.utils import get_previous_day# Cap concurrent gather queries so we don't overwhelm ClickHouse / Postgres# with ~40 simultaneous heavy queries.QUERY_CONCURRENCY = 4-def build_context(inputs: RunUsageReportsInputs, run_id: str, now: Optional[datetime] = None) -> WorkflowContext:+def build_context(inputs: RunUsageReportsInputs, run_id: str, now: datetime) -> WorkflowContext:"""Compute the period and S3 layout context. Pure function so it's safeto call from the workflow body (no real-time access).++ The period is always the full UTC day `inputs.day_offset` days before+ `now`. For `day_offset=0` (today) the tail of the window is in the+ future and simply matches no events, so intraday and finalizer runs+ share one code path."""- 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)+ report_day = (now.astimezone(UTC) - timedelta(days=inputs.day_offset)).date()+ period_start = datetime.combine(report_day, time.min, tzinfo=UTC)+ period_end = datetime.combine(report_day, time.max, tzinfo=UTC)return WorkflowContext(run_id=run_id,period_start=period_start,period_end=period_end,date_str=period_start.strftime("%Y-%m-%d"),+ report_completeness="partial" if inputs.day_offset == 0 else "complete",organization_ids=inputs.organization_ids,)@@ -73,6 +76,12 @@ class RunUsageReportsWorkflow(PostHogWorkflow):@workflow.runasync def run(self, inputs: RunUsageReportsInputs) -> dict:+ if inputs.day_offset < 0:+ # A negative offset (manual-trigger typo) would report a future,+ # empty day and mark it "complete" for billing. Fail fast;+ # non_retryable so the schedule's retry policy doesn't re-run a+ # validation error.+ raise ApplicationError(f"day_offset must be >= 0, got {inputs.day_offset}", non_retryable=True)started_at = workflow.now()status = "FAILED"try:@@ -82,6 +91,7 @@ class RunUsageReportsWorkflow(PostHogWorkflow):extra={"run_id": ctx.run_id,"date_str": ctx.date_str,+ "report_completeness": ctx.report_completeness,"period_start": ctx.period_start.isoformat(),"period_end": ctx.period_end.isoformat(),"spec_count": len(QUERIES),