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(batch-exports): stop billing runs of the hogql model (#98548)

Ross070f91d4645a
diff --git a/posthog/tasks/test/test_usage_report.py b/posthog/tasks/test/test_usage_report.py
index 2e458a1376aa..f47c1a73f70e 100644
--- a/posthog/tasks/test/test_usage_report.py
+++ b/posthog/tasks/test/test_usage_report.py
@@ -2846,6 +2846,34 @@ class TestExternalDataSyncUsageReport(ClickhouseDestroyTablesMixin, TestCase, Cl
records_completed=100 * (i + 1), # 100, 200, 300
)
+ # The HogQL model is free while it is in closed beta, so its rows are not counted.
+ hogql_batch_export = BatchExport.objects.create(
+ team_id=3,
+ name="Test HogQL export",
+ destination=batch_export_destination,
+ paused=False,
+ model=BatchExport.Model.HOGQL,
+ )
+ with team_scope(team_id=3, canonical=True):
+ hogql_batch_export_on_demand = BatchExportOnDemand.objects.create(
+ team_id=3,
+ destination=batch_export_on_demand_destination,
+ model=BatchExportOnDemand.Model.HOGQL,
+ )
+
+ for hogql_export_kwargs in (
+ {"batch_export": hogql_batch_export},
+ {"batch_export_on_demand": hogql_batch_export_on_demand},
+ ):
+ BatchExportRun.objects.create(
+ data_interval_end=now(),
+ data_interval_start=now() - timedelta(hours=1),
+ finished_at=now(),
+ status=BatchExportRun.Status.COMPLETED,
+ records_completed=5000,
+ **hogql_export_kwargs,
+ )
+
period = get_previous_day(at=now() + relativedelta(days=1))
all_reports = _get_all_org_reports(period=period)
diff --git a/posthog/tasks/usage_report.py b/posthog/tasks/usage_report.py
index 77334b21d09e..d82dfda39c63 100644
--- a/posthog/tasks/usage_report.py
+++ b/posthog/tasks/usage_report.py
@@ -49,7 +49,8 @@ from posthog.tasks.report_utils import capture_event
from posthog.tasks.utils import CeleryQueue
from posthog.utils import DayRange, get_helm_info_env, get_instance_realm, get_instance_region, get_previous_day
-from products.batch_exports.backend.models.batch_export import BatchExport, BatchExportDestination, BatchExportRun
+from products.batch_exports.backend.billing import exclude_non_billable_runs
+from products.batch_exports.backend.models.batch_export import BatchExport, BatchExportRun
from products.cdp.backend.models.hog_functions.hog_function import HogFunction, HogFunctionType
from products.cdp.backend.models.plugin import PluginConfig
from products.dashboards.backend.models.dashboard import Dashboard
@@ -2112,25 +2113,13 @@ def get_teams_with_free_historical_rows_synced_in_period(begin: datetime, end: d
@timed_log()
@retry(tries=QUERY_RETRIES, delay=QUERY_RETRY_DELAY, backoff=QUERY_RETRY_BACKOFF)
def get_teams_with_rows_exported_in_period(begin: datetime, end: datetime) -> list:
+ completed_runs = BatchExportRun.objects.filter(
+ finished_at__gte=begin,
+ finished_at__lte=end,
+ status=BatchExportRun.Status.COMPLETED,
+ )
return list(
- BatchExportRun.objects.filter(
- finished_at__gte=begin,
- finished_at__lte=end,
- status=BatchExportRun.Status.COMPLETED,
- )
- .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,
- ]
- )
- .exclude(
- batch_export_on_demand__destination__type__in=[
- BatchExportDestination.Destination.HTTP,
- BatchExportDestination.Destination.WORKFLOWS,
- ]
- )
+ exclude_non_billable_runs(completed_runs)
.values(team_id=Coalesce(F("batch_export__team_id"), F("batch_export_on_demand__team_id")))
.annotate(total=Sum("records_completed"))
)
diff --git a/products/batch_exports/backend/billing.py b/products/batch_exports/backend/billing.py
new file mode 100644
index 000000000000..a19cc2b7c4bc
--- /dev/null
+++ b/products/batch_exports/backend/billing.py
@@ -0,0 +1,38 @@
+from django.db.models import Q, QuerySet
+
+from products.batch_exports.backend.models.batch_export import BatchExport, BatchExportDestination, BatchExportRun
+
+NON_BILLABLE_DESTINATIONS = [
+ BatchExportDestination.Destination.HTTP,
+ BatchExportDestination.Destination.WORKFLOWS,
+]
+
+# Runs of the HogQL model are free while the model is in closed beta.
+# TODO: Remove this once the beta ends, so that its rows become billable like any other model's.
+NON_BILLABLE_MODELS = [BatchExport.Model.HOGQL]
+
+
+def exclude_non_billable_runs(runs: QuerySet[BatchExportRun]) -> QuerySet[BatchExportRun]:
+ """Drop the runs we do not bill from a `BatchExportRun` queryset.
+
+ Each condition is checked against both parents, as a run belongs to either a
+ `BatchExport` or a `BatchExportOnDemand`. The unset parent joins to nulls, which match
+ neither `exclude`, so the run is filtered on its own parent only.
+ """
+ return (
+ runs.filter(Q(batch_export__deleted=False) | Q(batch_export_on_demand__deleted=False))
+ .exclude(batch_export__destination__type__in=NON_BILLABLE_DESTINATIONS)
+ .exclude(batch_export_on_demand__destination__type__in=NON_BILLABLE_DESTINATIONS)
+ .exclude(batch_export__model__in=NON_BILLABLE_MODELS)
+ .exclude(batch_export_on_demand__model__in=NON_BILLABLE_MODELS)
+ )
+
+
+def is_billable_run(run: BatchExportRun) -> bool:
+ """Check if a single run counts towards billing, as `exclude_non_billable_runs` does."""
+ export = run.batch_export or run.batch_export_on_demand
+ if export is None or export.deleted:
+ return False
+ if export.destination.type in NON_BILLABLE_DESTINATIONS:
+ return False
+ return export.model not in NON_BILLABLE_MODELS
diff --git a/products/batch_exports/backend/management/commands/check_batch_export_billing_limits.py b/products/batch_exports/backend/management/commands/check_batch_export_billing_limits.py
index 85c85f4e17cd..e0c5fecd678e 100644
--- a/products/batch_exports/backend/management/commands/check_batch_export_billing_limits.py
+++ b/products/batch_exports/backend/management/commands/check_batch_export_billing_limits.py
@@ -8,17 +8,12 @@ from asgiref.sync import async_to_sync
from posthog.models import Organization, Team
from posthog.redis import get_client
-from products.batch_exports.backend.models.batch_export import BatchExport, BatchExportDestination
+from products.batch_exports.backend.billing import NON_BILLABLE_DESTINATIONS
+from products.batch_exports.backend.models.batch_export import BatchExport
from products.batch_exports.backend.temporal.batch_exports import check_is_over_limit
from ee.billing.quota_limiting import QuotaLimitingCaches, QuotaResource, list_limited_team_attributes
-# Destinations excluded from rows exported billing, and thus from the billing check.
-NON_BILLABLE_DESTINATIONS = [
- BatchExportDestination.Destination.HTTP,
- BatchExportDestination.Destination.WORKFLOWS,
-]
-
class Command(BaseCommand):
help = (
diff --git a/products/batch_exports/backend/temporal/batch_exports.py b/products/batch_exports/backend/temporal/batch_exports.py
index 27bbe9feeecb..735b6e578966 100644
--- a/products/batch_exports/backend/temporal/batch_exports.py
+++ b/products/batch_exports/backend/temporal/batch_exports.py
@@ -26,7 +26,8 @@ from posthog.temporal.common.client import connect
from posthog.temporal.common.logger import get_logger, get_write_only_logger
from posthog.usage_ingestion.client import UsageRecord, areport_usage
-from products.batch_exports.backend.models.batch_export import BatchExport, BatchExportDestination, BatchExportRun
+from products.batch_exports.backend.billing import is_billable_run
+from products.batch_exports.backend.models.batch_export import BatchExport, BatchExportRun
from products.batch_exports.backend.service import (
BackfillDetails,
BatchExportField,
@@ -569,18 +570,6 @@ class FinishBatchExportRunInputs:
on_demand: bool = False
-def _is_billable(run: BatchExportRun) -> bool:
- # Mirrors get_teams_with_rows_exported_in_period in the nightly report, which bills neither
- # HTTP nor Workflows destinations, and skips a run whose export has been deleted.
- export = run.batch_export or run.batch_export_on_demand
- if export is None or export.deleted:
- return False
- return export.destination.type not in (
- BatchExportDestination.Destination.HTTP,
- BatchExportDestination.Destination.WORKFLOWS,
- )
-
-
@activity.defn
async def finish_batch_export_run(inputs: FinishBatchExportRunInputs) -> None:
"""Activity that finishes a 'BatchExportRun'.
@@ -628,13 +617,12 @@ async def finish_batch_export_run(inputs: FinishBatchExportRunInputs) -> None:
**update_params,
)
- # The run is already written, so nothing here may fail the activity — not the destination
- # lookup `_is_billable` walks, not the report itself.
+ # The run is already written, so nothing here must fail the activity
try:
if (
batch_export_run.status == BatchExportRun.Status.COMPLETED
and batch_export_run.records_completed
- and _is_billable(batch_export_run)
+ and is_billable_run(batch_export_run)
):
await areport_usage(
[
diff --git a/products/batch_exports/backend/tests/temporal/test_run_updates.py b/products/batch_exports/backend/tests/temporal/test_run_updates.py
index 4e5927f2d95f..7dfa5f70d43b 100644
--- a/products/batch_exports/backend/tests/temporal/test_run_updates.py
+++ b/products/batch_exports/backend/tests/temporal/test_run_updates.py
@@ -11,6 +11,7 @@ from asgiref.sync import sync_to_async
from posthog.kafka_client.topics import KAFKA_APP_METRICS2, KAFKA_CDP_INTERNAL_EVENTS
from posthog.models import Organization, Team
+from products.batch_exports.backend.billing import is_billable_run
from products.batch_exports.backend.models.batch_export import (
BatchExport,
BatchExportDestination,
@@ -22,7 +23,6 @@ from products.batch_exports.backend.temporal.batch_exports import (
FinishBatchExportRunInputs,
OverBillingLimitError,
StartBatchExportRunInputs,
- _is_billable,
finish_batch_export_run,
start_batch_export_run,
)
@@ -229,8 +229,8 @@ async def test_finish_batch_export_run(activity_environment, team, batch_export,
# Usage is collected after the run is written, so a collector that raises must not cost the
# run its Completed status and send the whole export round again.
with unittest.mock.patch(
- "products.batch_exports.backend.temporal.batch_exports._is_billable",
- side_effect=RuntimeError("boom") if usage_collection_raises else _is_billable,
+ "products.batch_exports.backend.temporal.batch_exports.is_billable_run",
+ side_effect=RuntimeError("boom") if usage_collection_raises else is_billable_run,
):
await activity_environment.run(finish_batch_export_run, finish_inputs)
@@ -605,20 +605,23 @@ async def test_start_batch_export_run_produces_failed_billing_internal_event(act
@pytest.mark.parametrize("on_demand", [False, True])
@pytest.mark.parametrize(
- "destination_type,deleted,billable",
+ "destination_type,model,deleted,billable",
[
- (BatchExportDestination.Destination.S3, False, True),
- (BatchExportDestination.Destination.HTTP, False, False),
- (BatchExportDestination.Destination.WORKFLOWS, False, False),
- (BatchExportDestination.Destination.S3, True, False),
+ (BatchExportDestination.Destination.S3, BatchExport.Model.EVENTS, False, True),
+ (BatchExportDestination.Destination.HTTP, BatchExport.Model.EVENTS, False, False),
+ (BatchExportDestination.Destination.WORKFLOWS, BatchExport.Model.EVENTS, False, False),
+ (BatchExportDestination.Destination.S3, BatchExport.Model.EVENTS, True, False),
+ (BatchExportDestination.Destination.S3, BatchExport.Model.HOGQL, False, False),
],
)
-def test_usage_is_reported_only_for_what_the_nightly_report_bills(destination_type, deleted, billable, on_demand):
+def test_usage_is_reported_only_for_what_the_nightly_report_bills(
+ destination_type, model, deleted, billable, on_demand
+):
destination = BatchExportDestination(type=destination_type)
run = BatchExportRun()
if on_demand:
- run.batch_export_on_demand = BatchExportOnDemand(destination=destination, deleted=deleted)
+ run.batch_export_on_demand = BatchExportOnDemand(destination=destination, model=model, deleted=deleted)
else:
- run.batch_export = BatchExport(destination=destination, deleted=deleted)
+ run.batch_export = BatchExport(destination=destination, model=model, deleted=deleted)
- assert _is_billable(run) is billable
+ assert is_billable_run(run) is billable