: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(batch-exports): Track on demand on usage report (#62099)
Tomás Farías Santanab735628bc18c
diff --git a/posthog/tasks/test/test_usage_report.py b/posthog/tasks/test/test_usage_report.pyindex d6c82444275d..1196d4180605 100644--- a/posthog/tasks/test/test_usage_report.py+++ b/posthog/tasks/test/test_usage_report.py@@ -44,6 +44,7 @@ from posthog.models import Organization, Teamfrom posthog.models.app_metrics2.sql import TRUNCATE_APP_METRICS2_TABLE_SQLfrom posthog.models.event.util import create_eventfrom posthog.models.group.util import create_group+from posthog.models.scoping import team_scopefrom posthog.models.sharing_configuration import SharingConfigurationfrom posthog.session_recordings.queries.test.session_replay_sql import produce_replay_summaryfrom posthog.tasks.usage_report import (@@ -65,7 +66,12 @@ from posthog.test.fixtures import create_app_metric2from posthog.test.test_utils import create_group_type_mapping_without_created_atfrom posthog.utils import get_previous_day-from products.batch_exports.backend.models.batch_export import BatchExport, BatchExportDestination, BatchExportRun+from products.batch_exports.backend.models.batch_export import (+ BatchExport,+ BatchExportDestination,+ BatchExportOnDemand,+ BatchExportRun,+)from products.cdp.backend.models.plugin import Plugin, PluginConfigfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery@@ -2272,6 +2278,77 @@ class TestExternalDataSyncUsageReport(ClickhouseDestroyTablesMixin, TestCase, Clmodel=BatchExport.Model.EVENTS,)+ batch_export_on_demand_destination = BatchExportDestination.objects.create(+ type=BatchExportDestination.Destination.FILE_DOWNLOAD,+ config={"format": "Parquet"},+ )+ with team_scope(team_id=3, canonical=True):+ batch_export_on_demand = BatchExportOnDemand.objects.create(+ team_id=3,+ destination=batch_export_on_demand_destination,+ model=BatchExport.Model.EVENTS,+ )++ for i in range(3):+ BatchExportRun.objects.create(+ batch_export=batch_export,+ data_interval_end=now() - timedelta(hours=i),+ data_interval_start=now() - timedelta(hours=i + 1),+ finished_at=now(),+ status=BatchExportRun.Status.COMPLETED,+ records_completed=100 * (i + 1), # 100, 200, 300+ )++ for i in range(3):+ BatchExportRun.objects.create(+ batch_export_on_demand=batch_export_on_demand,+ data_interval_end=now() - timedelta(hours=i),+ data_interval_start=now() - timedelta(hours=i + 1),+ finished_at=now(),+ status=BatchExportRun.Status.COMPLETED,+ records_completed=100 * (i + 1), # 100, 200, 300+ )++ period = get_previous_day(at=now() + relativedelta(days=1))+ period_start, period_end = period+ all_reports = _get_all_org_reports(period_start, period_end)++ assert len(all_reports) == 3++ org_1_report = _get_full_org_usage_report_as_dict(+ _get_full_org_usage_report(all_reports[str(self.org_1.id)], get_instance_metadata(period))+ )++ assert org_1_report["organization_name"] == "Org 1"+ assert org_1_report["rows_exported_in_period"] == 1200+ assert org_1_report["teams"]["3"]["rows_exported_in_period"] == 1200++ @patch("posthog.tasks.usage_report.get_ph_client")+ @patch("posthog.tasks.usage_report.send_report_to_billing_service")+ def test_batch_export_rows_exported_in_period_excludes_workflows(+ self, billing_task_mock: MagicMock, posthog_capture_mock: MagicMock+ ) -> None:+ self._setup_teams()++ batch_export_destination = BatchExportDestination.objects.create(+ type=BatchExportDestination.Destination.WORKFLOWS,+ config={},+ )+ batch_export = BatchExport.objects.create(+ team_id=3,+ name="Test export",+ destination=batch_export_destination,+ paused=False,+ model=BatchExport.Model.EVENTS,+ )++ with team_scope(team_id=3, canonical=True):+ batch_export_on_demand = BatchExportOnDemand.objects.create(+ team_id=3,+ destination=batch_export_destination,+ model=BatchExport.Model.EVENTS,+ )+for i in range(3):BatchExportRun.objects.create(batch_export=batch_export,@@ -2282,6 +2359,16 @@ class TestExternalDataSyncUsageReport(ClickhouseDestroyTablesMixin, TestCase, Clrecords_completed=100 * (i + 1), # 100, 200, 300)+ for i in range(3):+ BatchExportRun.objects.create(+ batch_export_on_demand=batch_export_on_demand,+ data_interval_end=now() - timedelta(hours=i),+ data_interval_start=now() - timedelta(hours=i + 1),+ finished_at=now(),+ status=BatchExportRun.Status.COMPLETED,+ records_completed=100 * (i + 1), # 100, 200, 300+ )+period = get_previous_day(at=now() + relativedelta(days=1))period_start, period_end = periodall_reports = _get_all_org_reports(period_start, period_end)@@ -2293,8 +2380,8 @@ class TestExternalDataSyncUsageReport(ClickhouseDestroyTablesMixin, TestCase, Cl)assert org_1_report["organization_name"] == "Org 1"- assert org_1_report["rows_exported_in_period"] == 600- assert org_1_report["teams"]["3"]["rows_exported_in_period"] == 600+ assert org_1_report["rows_exported_in_period"] == 0+ assert org_1_report["teams"]["3"]["rows_exported_in_period"] == 0@patch("posthog.tasks.usage_report.get_ph_client")@patch("posthog.tasks.usage_report.send_report_to_billing_service")diff --git a/posthog/tasks/usage_report.py b/posthog/tasks/usage_report.pyindex c712454f0304..1b2a806e6e43 100644--- a/posthog/tasks/usage_report.py+++ b/posthog/tasks/usage_report.py@@ -12,6 +12,7 @@ from typing import Any, Literal, Optional, TypedDict, Unionfrom django.conf import settingsfrom django.db import connectionfrom django.db.models import Count, F, Q, Sum+from django.db.models.functions import Coalesceimport requestsimport structlog@@ -1414,15 +1415,21 @@ def get_teams_with_rows_exported_in_period(begin: datetime, end: datetime) -> lifinished_at__gte=begin,finished_at__lte=end,status=BatchExportRun.Status.COMPLETED,- batch_export__deleted=False,)+ .filter(Q(batch_export__deleted=False) | Q(batch_export_on_demand__deleted=False)).exclude(batch_export__destination__type__in=[BatchExportDestination.Destination.HTTP,BatchExportDestination.Destination.WORKFLOWS,])- .values(team_id=F("batch_export__team_id"))+ .exclude(+ batch_export_on_demand__destination__type__in=[+ BatchExportDestination.Destination.HTTP,+ BatchExportDestination.Destination.WORKFLOWS,+ ]+ )+ .values(team_id=Coalesce(F("batch_export__team_id"), F("batch_export_on_demand__team_id"))).annotate(total=Sum("records_completed")))