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): Better billing limit handling (#75872)

Tomás Farías Santana74f316a53b37
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
new file mode 100644
index 000000000000..d7dd2392d581
--- /dev/null
+++ b/products/batch_exports/backend/management/commands/check_batch_export_billing_limits.py
@@ -0,0 +1,121 @@
+import json
+import datetime as dt
+
+from django.core.management.base import BaseCommand, CommandError
+
+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.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 = (
+ "Check which teams would have their batch exports fail due to being over "
+ "the rows exported billing limit. Runs the same check batch export workflows run."
+ )
+
+ def add_arguments(self, parser):
+ parser.add_argument("--team-id", default=None, type=int, help="Check a single team")
+ parser.add_argument("--organization-id", default=None, type=str, help="Check all teams in an organization")
+ parser.add_argument(
+ "--json", action="store_true", dest="as_json", help="Output machine-readable JSON, one object per line"
+ )
+
+ def handle(self, **options):
+ team_id = options["team_id"]
+ organization_id = options["organization_id"]
+ as_json = options["as_json"]
+
+ checked = False
+ if team_id is not None:
+ teams = [Team.objects.select_related("organization").get(id=team_id)]
+ elif organization_id is not None:
+ try:
+ organization = Organization.objects.get(id=organization_id)
+ except Organization.DoesNotExist:
+ raise CommandError(f"Organization '{organization_id}' not found")
+ teams = list(Team.objects.select_related("organization").filter(organization=organization))
+ else:
+ teams = self._teams_with_limited_billable_exports()
+ checked = True
+
+ for team in teams:
+ self._report_team(team, as_json, checked)
+
+ if not teams:
+ self.stdout.write("No teams with active billable batch exports are over the billing limit.")
+
+ def _teams_with_limited_billable_exports(self) -> list[Team]:
+ """Return teams in the quota-limit zset that have active billable batch exports."""
+ limited_tokens = list_limited_team_attributes(
+ QuotaResource.ROWS_EXPORTED,
+ QuotaLimitingCaches.QUOTA_LIMITER_CACHE_KEY,
+ use_cache=False,
+ )
+ return list(
+ Team.objects.select_related("organization")
+ .filter(
+ api_token__in=limited_tokens,
+ batchexport__deleted=False,
+ batchexport__paused=False,
+ )
+ .exclude(batchexport__destination__type__in=NON_BILLABLE_DESTINATIONS)
+ .distinct()
+ )
+
+ def _report_team(self, team: Team, as_json: bool, checked: bool) -> None:
+ if not checked:
+ is_over_limit = async_to_sync(check_is_over_limit)(team.id)
+ else:
+ is_over_limit = True
+
+ zset_key = f"{QuotaLimitingCaches.QUOTA_LIMITER_CACHE_KEY.value}{QuotaResource.ROWS_EXPORTED.value}"
+ score = get_client().zscore(zset_key, team.api_token)
+ limited_until = dt.datetime.fromtimestamp(score, tz=dt.UTC).isoformat() if score else None
+
+ usage_summary = (team.organization.usage or {}).get(QuotaResource.ROWS_EXPORTED.value) or {}
+ trust_scores = team.organization.customer_trust_scores or {}
+
+ active_exports = (
+ BatchExport.objects.filter(team_id=team.id, deleted=False, paused=False)
+ .exclude(destination__type__in=NON_BILLABLE_DESTINATIONS)
+ .values_list("destination__type", flat=True)
+ )
+
+ report = {
+ "team_id": team.id,
+ "organization_id": str(team.organization_id),
+ "over_billing_limit": is_over_limit,
+ "limited_until": limited_until,
+ "usage": usage_summary.get("usage"),
+ "todays_usage": usage_summary.get("todays_usage"),
+ "limit": usage_summary.get("limit"),
+ "trust_score": trust_scores.get(QuotaResource.ROWS_EXPORTED.value),
+ "never_drop_data": team.organization.never_drop_data,
+ "active_billable_exports": sorted(active_exports),
+ }
+
+ if as_json:
+ self.stdout.write(json.dumps(report))
+ return
+
+ status = self.style.ERROR("OVER LIMIT") if is_over_limit else self.style.SUCCESS("ok")
+ self.stdout.write(
+ f"team={report['team_id']} org={report['organization_id']} {status} "
+ f"usage={report['usage']} todays_usage={report['todays_usage']} limit={report['limit']} "
+ f"trust_score={report['trust_score']} limited_until={report['limited_until']} "
+ f"never_drop_data={report['never_drop_data']} "
+ f"active_billable_exports={report['active_billable_exports']}"
+ )
diff --git a/products/batch_exports/backend/temporal/batch_exports.py b/products/batch_exports/backend/temporal/batch_exports.py
index 63106edfbea0..1ab633e0699b 100644
--- a/products/batch_exports/backend/temporal/batch_exports.py
+++ b/products/batch_exports/backend/temporal/batch_exports.py
@@ -473,6 +473,17 @@ class OverBillingLimitError(Exception):
super().__init__(f"Team {team_id} is over billing limit for batch exports")
+def is_over_billing_limit_error(e: exceptions.ActivityError) -> bool:
+ """Check if an activity failed because a team is over billing limit.
+
+ Temporal doesn't propagate original exception classes across the activity
+ boundary: workflows see an `ActivityError` whose cause is an `ApplicationError`
+ carrying the original class name in its `type` attribute. So workflows cannot
+ catch `OverBillingLimitError` directly and must use this check instead.
+ """
+ return isinstance(e.cause, exceptions.ApplicationError) and e.cause.type == OverBillingLimitError.__name__
+
+
@activity.defn
async def start_batch_export_run(inputs: StartBatchExportRunInputs) -> BatchExportRunId:
"""Activity that creates an BatchExportRun and returns the run id.
@@ -539,11 +550,14 @@ async def check_is_over_limit(team_id: int) -> bool:
"""
team: Team = await Team.objects.aget(id=team_id)
- limited_team_tokens_rows_synced = await asyncio.to_thread(
+ # The ROWS_EXPORTED resource stores a team attribute for each team that has
+ # exceeded their quota and thus is limited. The term "attribute" refers to
+ # a team identifier, which in our case is the team's API token.
+ limited_team_tokens_rows_exported = await asyncio.to_thread(
list_limited_team_attributes, QuotaResource.ROWS_EXPORTED, QuotaLimitingCaches.QUOTA_LIMITER_CACHE_KEY
)
- if team.api_token in limited_team_tokens_rows_synced:
+ if team.api_token in limited_team_tokens_rows_exported:
return True
return False
diff --git a/products/batch_exports/backend/temporal/destinations/azure_blob_batch_export.py b/products/batch_exports/backend/temporal/destinations/azure_blob_batch_export.py
index d6dc9cc23277..bc3f7e609afb 100644
--- a/products/batch_exports/backend/temporal/destinations/azure_blob_batch_export.py
+++ b/products/batch_exports/backend/temporal/destinations/azure_blob_batch_export.py
@@ -8,7 +8,7 @@ from azure.core.exceptions import HttpResponseError
from azure.storage.blob import StorageErrorCode
from azure.storage.blob.aio import BlobServiceClient, ContainerClient, ExponentialRetry
from structlog.contextvars import bind_contextvars
-from temporalio import activity, workflow
+from temporalio import activity, exceptions, workflow
from temporalio.common import RetryPolicy
from posthog.models.integration import AzureBlobIntegration, Integration
@@ -23,10 +23,10 @@ from products.batch_exports.backend.service import (
BatchExportModel,
)
from products.batch_exports.backend.temporal.batch_exports import (
- OverBillingLimitError,
StartBatchExportRunInputs,
events_model_default_fields,
get_data_interval,
+ is_over_billing_limit_error,
start_batch_export_run,
)
from products.batch_exports.backend.temporal.destinations.constants import (
@@ -422,8 +422,10 @@ class AzureBlobBatchExportWorkflow(PostHogWorkflow):
non_retryable_error_types=["NotNullViolation", "IntegrityError", "OverBillingLimitError"],
),
)
- except OverBillingLimitError:
- return
+ except exceptions.ActivityError as e:
+ if is_over_billing_limit_error(e):
+ return
+ raise
if inputs.integration_id is None:
raise AzureBlobIntegrationNotFoundError(inputs.integration_id, inputs.team_id)
diff --git a/products/batch_exports/backend/temporal/destinations/bigquery_batch_export.py b/products/batch_exports/backend/temporal/destinations/bigquery_batch_export.py
index de9fc2346ae2..424223b56803 100644
--- a/products/batch_exports/backend/temporal/destinations/bigquery_batch_export.py
+++ b/products/batch_exports/backend/temporal/destinations/bigquery_batch_export.py
@@ -33,7 +33,7 @@ from google.cloud import bigquery, iam_admin_v1
from google.cloud.bigquery.table import RowIterator, _EmptyRowIterator
from google.oauth2 import service_account
from structlog.contextvars import bind_contextvars
-from temporalio import activity, workflow
+from temporalio import activity, exceptions, workflow
from temporalio.common import RetryPolicy
from posthog.models.integration import GoogleCloudServiceAccountIntegration, Integration
@@ -50,10 +50,10 @@ from products.batch_exports.backend.service import (
BigQueryBatchExportInputs,
)
from products.batch_exports.backend.temporal.batch_exports import (
- OverBillingLimitError,
StartBatchExportRunInputs,
default_fields,
get_data_interval,
+ is_over_billing_limit_error,
start_batch_export_run,
)
from products.batch_exports.backend.temporal.pipeline.consumer import Consumer
@@ -1636,8 +1636,10 @@ class BigQueryBatchExportWorkflow(PostHogWorkflow):
non_retryable_error_types=["NotNullViolation", "IntegrityError", "OverBillingLimitError"],
),
)
- except OverBillingLimitError:
- return
+ except exceptions.ActivityError as e:
+ if is_over_billing_limit_error(e):
+ return
+ raise
insert_inputs = BigQueryInsertInputs(
team_id=inputs.team_id,
diff --git a/products/batch_exports/backend/temporal/destinations/databricks_batch_export.py b/products/batch_exports/backend/temporal/destinations/databricks_batch_export.py
index 95fe2f528a7d..1fc04a348e60 100644
--- a/products/batch_exports/backend/temporal/destinations/databricks_batch_export.py
+++ b/products/batch_exports/backend/temporal/destinations/databricks_batch_export.py
@@ -21,7 +21,7 @@ from databricks.sql.client import Connection, Cursor
from databricks.sql.exc import DatabaseError, OperationalError, ServerOperationError
from databricks.sql.types import Row
from structlog.contextvars import bind_contextvars
-from temporalio import activity, workflow
+from temporalio import activity, exceptions, workflow
from temporalio.common import RetryPolicy
from posthog.models.integration import DatabricksIntegration, Integration
@@ -40,6 +40,7 @@ from products.batch_exports.backend.temporal.batch_exports import (
StartBatchExportRunInputs,
events_model_default_fields,
get_data_interval,
+ is_over_billing_limit_error,
start_batch_export_run,
)
from products.batch_exports.backend.temporal.pipeline.consumer import Consumer, run_consumer_from_stage
@@ -1410,17 +1411,22 @@ class DatabricksBatchExportWorkflow(PostHogWorkflow):
include_events=inputs.include_events,
backfill_id=inputs.backfill_details.backfill_id if inputs.backfill_details else None,
)
- run_id = await workflow.execute_activity(
- start_batch_export_run,
- start_batch_export_run_inputs,
- start_to_close_timeout=dt.timedelta(minutes=5),
- retry_policy=RetryPolicy(
- initial_interval=dt.timedelta(seconds=10),
- maximum_interval=dt.timedelta(seconds=60),
- maximum_attempts=0,
- non_retryable_error_types=["NotNullViolation", "IntegrityError", "OverBillingLimitError"],
- ),
- )
+ try:
+ run_id = await workflow.execute_activity(
+ start_batch_export_run,
+ start_batch_export_run_inputs,
+ start_to_close_timeout=dt.timedelta(minutes=5),
+ retry_policy=RetryPolicy(
+ initial_interval=dt.timedelta(seconds=10),
+ maximum_interval=dt.timedelta(seconds=60),
+ maximum_attempts=0,
+ non_retryable_error_types=["NotNullViolation", "IntegrityError", "OverBillingLimitError"],
+ ),
+ )
+ except exceptions.ActivityError as e:
+ if is_over_billing_limit_error(e):
+ return
+ raise
# should never happen here but check just in case
if inputs.integration_id is None:
diff --git a/products/batch_exports/backend/temporal/destinations/file_download_batch_export.py b/products/batch_exports/backend/temporal/destinations/file_download_batch_export.py
index 48dd4de39ceb..a57f761b6721 100644
--- a/products/batch_exports/backend/temporal/destinations/file_download_batch_export.py
+++ b/products/batch_exports/backend/temporal/destinations/file_download_batch_export.py
@@ -10,7 +10,7 @@ from django.conf import settings
import aioboto3
from botocore.exceptions import ClientError
-from temporalio import activity, workflow
+from temporalio import activity, exceptions, workflow
from temporalio.common import RetryPolicy
from posthog.temporal.common.base import PostHogWorkflow
@@ -20,9 +20,9 @@ from posthog.temporal.common.logger import get_logger, get_write_only_logger
from products.batch_exports.backend.models.batch_export import BatchExportFileDownload
from products.batch_exports.backend.service import BatchExportInsertInputs, FileDownloadBatchExportInputs
from products.batch_exports.backend.temporal.batch_exports import (
- OverBillingLimitError,
StartBatchExportRunInputs,
get_data_interval,
+ is_over_billing_limit_error,
start_batch_export_run,
)
from products.batch_exports.backend.temporal.destinations.s3_batch_export import (
@@ -350,8 +350,10 @@ class FileDownloadBatchExportWorkflow(PostHogWorkflow):
non_retryable_error_types=["NotNullViolation", "IntegrityError", "OverBillingLimitError"],
),
)
- except OverBillingLimitError:
- return FileDownloadBatchExportResult(records_completed=0, bytes_exported=0)
+ except exceptions.ActivityError as e:
+ if is_over_billing_limit_error(e):
+ return FileDownloadBatchExportResult(records_completed=0, bytes_exported=0)
+ raise
export_inputs = ExportInputs(
batch_export=BatchExportInsertInputs(
diff --git a/products/batch_exports/backend/temporal/destinations/postgres_batch_export.py b/products/batch_exports/backend/temporal/destinations/postgres_batch_export.py
index 8dc0f9648bb4..768425a09f35 100644
--- a/products/batch_exports/backend/temporal/destinations/postgres_batch_export.py
+++ b/products/batch_exports/backend/temporal/destinations/postgres_batch_export.py
@@ -18,7 +18,7 @@ import pyarrow as pa
from psycopg import sql
from psycopg.errors import SerializationFailure
from structlog.contextvars import bind_contextvars
-from temporalio import activity, workflow
+from temporalio import activity, exceptions, workflow
from temporalio.common import RetryPolicy
from posthog.models.integration import (
@@ -41,10 +41,10 @@ from products.batch_exports.backend.service import (
PostgresBatchExportInputs,
)
from products.batch_exports.backend.temporal.batch_exports import (
- OverBillingLimitError,
StartBatchExportRunInputs,
default_fields,
get_data_interval,
+ is_over_billing_limit_error,
start_batch_export_run,
)
from products.batch_exports.backend.temporal.destinations.utils import get_query_timeout
@@ -1105,8 +1105,10 @@ class PostgresBatchExportWorkflow(PostHogWorkflow):
non_retryable_error_types=["NotNullViolation", "IntegrityError", "OverBillingLimitError"],
),
)
- except OverBillingLimitError:
- return
+ except exceptions.ActivityError as e:
+ if is_over_billing_limit_error(e):
+ return
+ raise
insert_inputs = PostgresInsertInputs(
team_id=inputs.team_id,
diff --git a/products/batch_exports/backend/temporal/destinations/redshift_batch_export.py b/products/batch_exports/backend/temporal/destinations/redshift_batch_export.py
index ed336fea6197..66947db52f87 100644
--- a/products/batch_exports/backend/temporal/destinations/redshift_batch_export.py
+++ b/products/batch_exports/backend/temporal/destinations/redshift_batch_export.py
@@ -15,7 +15,7 @@ import pyarrow as pa
import botocore.exceptions
from psycopg import sql
from structlog.contextvars import bind_contextvars
-from temporalio import activity, workflow
+from temporalio import activity, exceptions, workflow
from temporalio.common import RetryPolicy
from posthog.models import Team
@@ -34,10 +34,10 @@ from products.batch_exports.backend.service import (
RedshiftBatchExportInputs,
)
from products.batch_exports.backend.temporal.batch_exports import (
- OverBillingLimitError,
StartBatchExportRunInputs,
default_fields,
get_data_interval,
+ is_over_billing_limit_error,
start_batch_export_run,
)
from products.batch_exports.backend.temporal.destinations.postgres_batch_export import (
@@ -1581,8 +1581,10 @@ class RedshiftBatchExportWorkflow(PostHogWorkflow):
non_retryable_error_types=["NotNullViolation", "IntegrityError", "OverBillingLimitError"],
),
)
- except OverBillingLimitError:
- return
+ except exceptions.ActivityError as e:
+ if is_over_billing_limit_error(e):
+ return
+ raise
batch_export_inputs = BatchExportInsertInputs(
team_id=inputs.team_id,
diff --git a/products/batch_exports/backend/temporal/destinations/s3_batch_export.py b/products/batch_exports/backend/temporal/destinations/s3_batch_export.py
index ac208817416e..904c7cac4e4e 100644
--- a/products/batch_exports/backend/temporal/destinations/s3_batch_export.py
+++ b/products/batch_exports/backend/temporal/destinations/s3_batch_export.py
@@ -20,7 +20,7 @@ if typing.TYPE_CHECKING:
from django.conf import settings
from structlog.contextvars import bind_contextvars
-from temporalio import activity, workflow
+from temporalio import activity, exceptions, workflow
from temporalio.common import RetryPolicy
from posthog.models.integration import (
@@ -43,10 +43,10 @@ from products.batch_exports.backend.service import (
S3BatchExportInputs,
)
from products.batch_exports.backend.temporal.batch_exports import (
- OverBillingLimitError,
StartBatchExportRunInputs,
default_fields,
get_data_interval,
+ is_over_billing_limit_error,
start_batch_export_run,
)
from products.batch_exports.backend.temporal.destinations.constants import (
@@ -321,8 +321,10 @@ class S3BatchExportWorkflow(PostHogWorkflow):
non_retryable_error_types=["NotNullViolation", "IntegrityError", "OverBillingLimitError"],
),
)
- except OverBillingLimitError:
- return
+ except exceptions.ActivityError as e:
+ if is_over_billing_limit_error(e):
+ return
+ raise
insert_inputs = S3InsertInputs(
bucket_name=inputs.bucket_name,
diff --git a/products/batch_exports/backend/temporal/destinations/snowflake_batch_export.py b/products/batch_exports/backend/temporal/destinations/snowflake_batch_export.py
index babe8fafa4b2..f50c390dab8c 100644
--- a/products/batch_exports/backend/temporal/destinations/snowflake_batch_export.py
+++ b/products/batch_exports/backend/temporal/destinations/snowflake_batch_export.py
@@ -21,7 +21,7 @@ from snowflake.connector.constants import FIELD_ID_TO_NAME, QueryStatus
from snowflake.connector.cursor import ResultMetadata
from snowflake.connector.errors import HttpError, InterfaceError, OperationalError
from structlog.contextvars import bind_contextvars
-from temporalio import activity, workflow
+from temporalio import activity, exceptions, workflow
from temporalio.common import RetryPolicy
from posthog.models.integration import Integration, SnowflakeIntegration
@@ -37,10 +37,10 @@ from products.batch_exports.backend.service import (
SnowflakeBatchExportInputs,
)
from products.batch_exports.backend.temporal.batch_exports import (
- OverBillingLimitError,
StartBatchExportRunInputs,
default_fields,
get_data_interval,
+ is_over_billing_limit_error,
start_batch_export_run,
)
from products.batch_exports.backend.temporal.destinations.utils import get_query_timeout
@@ -1588,8 +1588,10 @@ class SnowflakeBatchExportWorkflow(PostHogWorkflow):
],
),
)
- except OverBillingLimitError:
- return
+ except exceptions.ActivityError as e:
+ if is_over_billing_limit_error(e):
+ return
+ raise
insert_inputs = SnowflakeInsertInputs(
team_id=inputs.team_id,
diff --git a/products/batch_exports/backend/temporal/destinations/workflows_batch_export.py b/products/batch_exports/backend/temporal/destinations/workflows_batch_export.py
index e7e03bd2e93e..a34c773ea138 100644
--- a/products/batch_exports/backend/temporal/destinations/workflows_batch_export.py
+++ b/products/batch_exports/backend/temporal/destinations/workflows_batch_export.py
@@ -20,7 +20,6 @@ from posthog.temporal.common.logger import get_logger, get_write_only_logger
from products.batch_exports.backend.service import BatchExportField, BatchExportInsertInputs, WorkflowsBatchExportInputs
from products.batch_exports.backend.temporal.batch_exports import (
- OverBillingLimitError,
StartBatchExportRunInputs,
get_data_interval,
start_batch_export_run,
@@ -528,22 +527,21 @@ class WorkflowsBatchExportWorkflow(PostHogWorkflow):
exclude_events=inputs.exclude_events,
include_events=inputs.include_events,
backfill_id=inputs.backfill_details.backfill_id if inputs.backfill_details else None,
+ # Workflows exports are excluded from rows exported billing, so skip the check.
+ check_billing=False,
)
- try:
- run_id = await temporalio.workflow.execute_activity(
- start_batch_export_run,
- start_batch_export_run_inputs,
- start_to_close_timeout=dt.timedelta(minutes=5),
- retry_policy=RetryPolicy(
- initial_interval=dt.timedelta(seconds=10),
- maximum_interval=dt.timedelta(seconds=60),
- maximum_attempts=0,
- non_retryable_error_types=["NotNullViolation", "IntegrityError", "OverBillingLimitError"],
- ),
- )
- except OverBillingLimitError:
- return
+ run_id = await temporalio.workflow.execute_activity(
+ start_batch_export_run,
+ start_batch_export_run_inputs,
+ start_to_close_timeout=dt.timedelta(minutes=5),
+ retry_policy=RetryPolicy(
+ initial_interval=dt.timedelta(seconds=10),
+ maximum_interval=dt.timedelta(seconds=60),
+ maximum_attempts=0,
+ non_retryable_error_types=["NotNullViolation", "IntegrityError", "OverBillingLimitError"],
+ ),
+ )
batch_export_inputs = BatchExportInsertInputs(
team_id=inputs.team_id,
diff --git a/products/batch_exports/backend/tests/management/test_check_batch_export_billing_limits.py b/products/batch_exports/backend/tests/management/test_check_batch_export_billing_limits.py
new file mode 100644
index 000000000000..7c247e17aeef
--- /dev/null
+++ b/products/batch_exports/backend/tests/management/test_check_batch_export_billing_limits.py
@@ -0,0 +1,144 @@
+import json
+import datetime as dt
+from io import StringIO
+
+import pytest
+
+from django.core.management import call_command
+from django.core.management.base import CommandError
+
+from posthog.api.test.test_organization import create_organization
+from posthog.api.test.test_team import create_team
+
+from products.batch_exports.backend.models.batch_export import BatchExport, BatchExportDestination
+
+from ee.billing.quota_limiting import QuotaLimitingCaches, QuotaResource, add_limited_team_tokens
+
+pytestmark = [
+ pytest.mark.django_db,
+]
+
+
+def organization():
+ return create_organization("test-billing-limits")
+
+
+def team(organization):
+ return create_team(organization=organization)
+
+
+def _create_batch_export(team, destination_type="S3", paused=False, deleted=False):
+ destination = BatchExportDestination.objects.create(type=destination_type, config={})
+ return BatchExport.objects.create(
+ name=f"{destination_type}-export",
+ team=team,
+ destination=destination,
+ interval="hour",
+ paused=paused,
+ deleted=deleted,
+ )
+
+
+def _limit_team(team, expired=False):
+ delta = dt.timedelta(days=-1) if expired else dt.timedelta(days=1)
+ score = int((dt.datetime.now(dt.UTC) + delta).timestamp())
+ add_limited_team_tokens(
+ QuotaResource.ROWS_EXPORTED,
+ {team.api_token: score},
+ QuotaLimitingCaches.QUOTA_LIMITER_CACHE_KEY,
+ )
+
+
+def _call_command(*args):
+ stdout = StringIO()
+ call_command("check_batch_export_billing_limits", *args, stdout=stdout)
+ return stdout.getvalue()
+
+
+def _parse_json_output(output):
+ return [json.loads(line) for line in output.splitlines() if line.startswith("{")]
+
+
+ "limited,expired,expected_over_limit",
+ [
+ (True, False, True),
+ (True, True, False),
+ (False, False, False),
+ ],
+)
+def test_team_id_reports_over_limit(organization, team, limited, expired, expected_over_limit):
+ """Test the command runs the production predicate against the quota-limit zset.
+
+ An expired zset entry must not report a team as over limit.
+ """
+ organization.usage = {"rows_exported": {"usage": 500, "todays_usage": 100, "limit": 300}}
+ organization.save()
+ if limited:
+ _limit_team(team, expired=expired)
+
+ reports = _parse_json_output(_call_command("--team-id", str(team.id), "--json"))
+
+ assert len(reports) == 1
+ report = reports[0]
+ assert report["team_id"] == team.id
+ assert report["over_billing_limit"] is expected_over_limit
+ assert report["usage"] == 500
+ assert report["todays_usage"] == 100
+ assert report["limit"] == 300
+
+
+def test_fleet_audit_lists_only_limited_teams_with_active_billable_exports(organization):
+ """Test the fleet audit's filters.
+
+ Only teams in the quota-limit zset with at least one non-deleted, non-paused
+ export to a billable destination should be listed.
+ """
+ team_billable = create_team(organization=organization)
+ _create_batch_export(team_billable)
+ _limit_team(team_billable)
+
+ team_http_only = create_team(organization=organization)
+ _create_batch_export(team_http_only, destination_type="HTTP")
+ _limit_team(team_http_only)
+
+ team_workflows_only = create_team(organization=organization)
+ _create_batch_export(team_workflows_only, destination_type="Workflows")
+ _limit_team(team_workflows_only)
+
+ team_paused = create_team(organization=organization)
+ _create_batch_export(team_paused, paused=True)
+ _limit_team(team_paused)
+
+ team_deleted = create_team(organization=organization)
+ _create_batch_export(team_deleted, deleted=True)
+ _limit_team(team_deleted)
+
+ team_not_limited = create_team(organization=organization)
+ _create_batch_export(team_not_limited)
+
+ reports = _parse_json_output(_call_command("--json"))
+
+ assert [report["team_id"] for report in reports] == [team_billable.id]
+ assert reports[0]["over_billing_limit"] is True
+ assert reports[0]["active_billable_exports"] == ["S3"]
+
+
+def test_organization_id_reports_all_teams(organization):
+ team_limited = create_team(organization=organization)
+ _create_batch_export(team_limited)
+ _limit_team(team_limited)
+
+ team_not_limited = create_team(organization=organization)
+
+ reports = _parse_json_output(_call_command("--organization-id", str(organization.id), "--json"))
+
+ over_limit_by_team = {report["team_id"]: report["over_billing_limit"] for report in reports}
+ assert over_limit_by_team == {team_limited.id: True, team_not_limited.id: False}
+
+
+def test_unknown_organization_raises():
+ with pytest.raises(CommandError):
+ _call_command("--organization-id", "019fb3d0-0000-0000-0000-000000000000")
diff --git a/products/batch_exports/backend/tests/temporal/test_billing_limits.py b/products/batch_exports/backend/tests/temporal/test_billing_limits.py
new file mode 100644
index 000000000000..2d5823ed64a9
--- /dev/null
+++ b/products/batch_exports/backend/tests/temporal/test_billing_limits.py
@@ -0,0 +1,244 @@
+"""Tests for billing limit enforcement across batch export workflows.
+
+The `start_batch_export_run` activity raises `OverBillingLimitError` when a team
+is over its rows exported billing limit. Temporal does not propagate the original
+exception class to the workflow: the workflow sees a `temporalio.exceptions.ActivityError`
+whose cause is an `ApplicationError` with `type == "OverBillingLimitError"`. These
+tests assert both the propagation semantics and that every destination workflow
+handles the error by finishing cleanly, leaving behind a run with 'FailedBilling'
+status.
+"""
+
+import uuid
+import datetime as dt
+
+import pytest
+import unittest.mock
+
+from django.conf import settings
+from django.test import override_settings
+
+from temporalio import exceptions, workflow
+from temporalio.client import WorkflowFailureError
+from temporalio.common import RetryPolicy
+from temporalio.testing import WorkflowEnvironment
+from temporalio.worker import UnsandboxedWorkflowRunner, Worker
+
+from posthog.temporal.tests.utils.models import afetch_batch_export_runs
+
+from products.batch_exports.backend.models.batch_export import BatchExport, BatchExportDestination, BatchExportRun
+from products.batch_exports.backend.service import (
+ AzureBlobBatchExportInputs,
+ BigQueryBatchExportInputs,
+ DatabricksBatchExportInputs,
+ PostgresBatchExportInputs,
+ RedshiftBatchExportInputs,
+ S3BatchExportInputs,
+ SnowflakeBatchExportInputs,
+)
+from products.batch_exports.backend.temporal.batch_exports import (
+ StartBatchExportRunInputs,
+ is_over_billing_limit_error,
+ start_batch_export_run,
+)
+from products.batch_exports.backend.temporal.destinations.azure_blob_batch_export import AzureBlobBatchExportWorkflow
+from products.batch_exports.backend.temporal.destinations.bigquery_batch_export import BigQueryBatchExportWorkflow
+from products.batch_exports.backend.temporal.destinations.databricks_batch_export import DatabricksBatchExportWorkflow
+from products.batch_exports.backend.temporal.destinations.postgres_batch_export import PostgresBatchExportWorkflow
+from products.batch_exports.backend.temporal.destinations.redshift_batch_export import RedshiftBatchExportWorkflow
+from products.batch_exports.backend.temporal.destinations.s3_batch_export import S3BatchExportWorkflow
+from products.batch_exports.backend.temporal.destinations.snowflake_batch_export import SnowflakeBatchExportWorkflow
+
+pytestmark = [
+ pytest.mark.asyncio,
+ pytest.mark.django_db(transaction=True),
+]
+
+TEST_TIME = dt.datetime(2025, 4, 24, 1, 0, 0, tzinfo=dt.UTC)
+
+
+def batch_export(team):
+ destination = BatchExportDestination.objects.create(type="S3", config={})
+ batch_export = BatchExport.objects.create(
+ name="billing-limit-test-export", team=team, destination=destination, interval="hour"
+ )
+
+ yield batch_export
+
+ batch_export.delete()
+ destination.delete()
+
+
+def over_billing_limit():
+ """Report any team as over its rows exported billing limit."""
+ with (
+ override_settings(BATCH_EXPORTS_ENABLE_BILLING_CHECK=True),
+ unittest.mock.patch(
+ "products.batch_exports.backend.temporal.batch_exports.check_is_over_limit",
+ new=unittest.mock.AsyncMock(return_value=True),
+ ) as mock,
+ ):
+ yield mock
+
+
[email protected](name="billing-limit-test-reraise")
+class ReRaiseBillingLimitTestWorkflow:
+ """Workflow calling 'start_batch_export_run' without handling any errors."""
+
+ @workflow.run
+ async def run(self, inputs: StartBatchExportRunInputs) -> str:
+ return await workflow.execute_activity(
+ start_batch_export_run,
+ inputs,
+ start_to_close_timeout=dt.timedelta(minutes=1),
+ retry_policy=RetryPolicy(
+ maximum_attempts=1,
+ non_retryable_error_types=["OverBillingLimitError"],
+ ),
+ )
+
+
[email protected](name="billing-limit-test-catch")
+class CatchBillingLimitTestWorkflow:
+ """Workflow calling 'start_batch_export_run' handling billing limit errors."""
+
+ @workflow.run
+ async def run(self, inputs: StartBatchExportRunInputs) -> str:
+ try:
+ return await workflow.execute_activity(
+ start_batch_export_run,
+ inputs,
+ start_to_close_timeout=dt.timedelta(minutes=1),
+ retry_policy=RetryPolicy(
+ maximum_attempts=1,
+ non_retryable_error_types=["OverBillingLimitError"],
+ ),
+ )
+ except exceptions.ActivityError as e:
+ if is_over_billing_limit_error(e):
+ return "over-billing-limit"
+ raise
+
+
+async def _execute_test_workflow(workflow_class, inputs):
+ workflow_id = str(uuid.uuid4())
+
+ async with await WorkflowEnvironment.start_time_skipping() as env:
+ async with Worker(
+ env.client,
+ task_queue=settings.BATCH_EXPORTS_TASK_QUEUE,
+ workflows=[workflow_class],
+ activities=[start_batch_export_run],
+ workflow_runner=UnsandboxedWorkflowRunner(),
+ ):
+ return await env.client.execute_workflow(
+ workflow_class.run,
+ inputs,
+ id=workflow_id,
+ task_queue=settings.BATCH_EXPORTS_TASK_QUEUE,
+ retry_policy=RetryPolicy(maximum_attempts=1),
+ execution_timeout=dt.timedelta(minutes=1),
+ )
+
+
+async def test_over_billing_limit_error_propagates_as_activity_error(team, batch_export, over_billing_limit):
+ """Test the exception a workflow actually sees when the activity raises 'OverBillingLimitError'.
+
+ Temporal wraps activity exceptions, so a workflow can never catch 'OverBillingLimitError'
+ directly: it must inspect the 'ActivityError' cause.
+ """
+ inputs = StartBatchExportRunInputs(
+ team_id=team.id,
+ batch_export_id=str(batch_export.id),
+ data_interval_start=(TEST_TIME - dt.timedelta(hours=1)).isoformat(),
+ data_interval_end=TEST_TIME.isoformat(),
+ )
+
+ with pytest.raises(WorkflowFailureError) as exc_info:
+ await _execute_test_workflow(ReRaiseBillingLimitTestWorkflow, inputs)
+
+ activity_error = exc_info.value.cause
+ assert isinstance(activity_error, exceptions.ActivityError)
+ assert isinstance(activity_error.cause, exceptions.ApplicationError)
+ assert activity_error.cause.type == "OverBillingLimitError"
+ assert is_over_billing_limit_error(activity_error)
+
+ runs = await afetch_batch_export_runs(batch_export_id=batch_export.id)
+ assert len(runs) == 1
+ assert runs[0].status == BatchExportRun.Status.FAILED_BILLING
+
+
+async def test_over_billing_limit_error_is_caught_by_workflow(team, batch_export, over_billing_limit):
+ """Test a workflow can catch the billing limit error and finish cleanly."""
+ inputs = StartBatchExportRunInputs(
+ team_id=team.id,
+ batch_export_id=str(batch_export.id),
+ data_interval_start=(TEST_TIME - dt.timedelta(hours=1)).isoformat(),
+ data_interval_end=TEST_TIME.isoformat(),
+ )
+
+ result = await _execute_test_workflow(CatchBillingLimitTestWorkflow, inputs)
+
+ assert result == "over-billing-limit"
+
+ runs = await afetch_batch_export_runs(batch_export_id=batch_export.id)
+ assert len(runs) == 1
+ assert runs[0].status == BatchExportRun.Status.FAILED_BILLING
+
+
+ "workflow_class,inputs_class,destination_config",
+ [
+ (
+ S3BatchExportWorkflow,
+ S3BatchExportInputs,
+ {"bucket_name": "a-bucket", "region": "us-east-1", "prefix": "a-prefix"},
+ ),
+ (BigQueryBatchExportWorkflow, BigQueryBatchExportInputs, {"dataset_id": "a-dataset"}),
+ (
+ SnowflakeBatchExportWorkflow,
+ SnowflakeBatchExportInputs,
+ {"database": "a-database", "warehouse": "a-warehouse", "schema": "a-schema"},
+ ),
+ (PostgresBatchExportWorkflow, PostgresBatchExportInputs, {"database": "a-database"}),
+ (
+ RedshiftBatchExportWorkflow,
+ RedshiftBatchExportInputs,
+ {"user": "a-user", "password": "a-password", "host": "a-host", "database": "a-database"},
+ ),
+ (AzureBlobBatchExportWorkflow, AzureBlobBatchExportInputs, {"container_name": "a-container"}),
+ (
+ DatabricksBatchExportWorkflow,
+ DatabricksBatchExportInputs,
+ {"http_path": "a-path", "catalog": "a-catalog", "schema": "a-schema", "table_name": "a-table"},
+ ),
+ ],
+)
+async def test_destination_workflow_finishes_cleanly_when_over_billing_limit(
+ team,
+ batch_export,
+ over_billing_limit,
+ workflow_class,
+ inputs_class,
+ destination_config,
+):
+ """Test destination workflows handle a team over its billing limit.
+
+ The workflow must finish without failing, without running any export activity,
+ and leave behind a run with 'FailedBilling' status.
+ """
+ inputs = inputs_class(
+ team_id=team.id,
+ batch_export_id=str(batch_export.id),
+ interval="hour",
+ data_interval_end=TEST_TIME.isoformat(),
+ **destination_config,
+ )
+
+ await _execute_test_workflow(workflow_class, inputs)
+
+ runs = await afetch_batch_export_runs(batch_export_id=batch_export.id)
+ assert len(runs) == 1
+ assert runs[0].status == BatchExportRun.Status.FAILED_BILLING