: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
chore(batch-exports): move core callers onto the batch exports facade (#105971)
Ross6300c2f14bf8
diff --git a/posthog/admin/admins/organization_admin.py b/posthog/admin/admins/organization_admin.pyindex d2985a3a2937..8ed8be88fb88 100644--- a/posthog/admin/admins/organization_admin.py+++ b/posthog/admin/admins/organization_admin.py@@ -34,6 +34,9 @@ from posthog.person_db_router import PERSONS_DB_MODELSfrom posthog.tasks.ai_observability_usage_report import internal_reporting_team_idfrom posthog.utils import pluralize+from products.batch_exports.backend.facade import api as batch_exports_api+from products.batch_exports.backend.facade.contracts import BATCH_EXPORT_MODEL_LABEL+# Registry of default-db models to count for bulk-delete report.# Format: (app_label.ModelName, filter_field, display_name)# This mirrors delete_bulky_postgres_data() in posthog/models/team/util.py@@ -87,16 +90,13 @@ def get_model_counts_for_organization(organization: Organization) -> list[dict]:})- # BatchExport requires deleted=False filter to match delete_batch_exports() behavior+ # Not in the registry above, because the count must leave out deleted exports, as team deletion does.try:- from products.batch_exports.backend.models.batch_export import BatchExport-- batch_export_count = BatchExport.objects.filter(team_id__in=team_ids, deleted=False).count()results.append({"name": "Batch Exports",- "count": batch_export_count,- "model": BatchExport._meta.label,+ "count": batch_exports_api.count_batch_exports_for_teams(team_ids),+ "model": BATCH_EXPORT_MODEL_LABEL,})except Exception as e:@@ -104,7 +104,7 @@ def get_model_counts_for_organization(organization: Organization) -> list[dict]:{"name": "Batch Exports","count": f"Error: {e}",- "model": "products.batch_exports.backend.models.batch_export.BatchExport",+ "model": BATCH_EXPORT_MODEL_LABEL,})diff --git a/posthog/api/integration.py b/posthog/api/integration.pyindex 94974ce85e7f..6d4eb156870a 100644--- a/posthog/api/integration.py+++ b/posthog/api/integration.py@@ -118,7 +118,7 @@ from posthog.tasks.email import send_integration_access_requestfrom posthog.utils import is_relative_urlfrom products.access_control.backend.presentation.access_control import UserAccessControlSerializerMixin-from products.batch_exports.backend.models.batch_export import get_batch_exports_using_integration+from products.batch_exports.backend.facade.api import list_batch_exports_using_integrationfrom products.cdp.backend.services.integration_usage import get_enabled_hog_functions_using_integrationfrom products.slack_app.backend.services.slack_auth import SLACK_AUTH_FAILURE_CODESfrom products.tasks.backend.facade.api import count_in_progress_runs_for_github_integration@@ -250,7 +250,8 @@ def _ensure_oauth_token_valid(instance: Integration) -> None:class _HasNameOrId(Protocol):- id: Any+ @property+ def id(self) -> Any: ...@propertydef name(self) -> str | None: ...@@ -1379,7 +1380,7 @@ class IntegrationViewSet(functions_using_integration = get_enabled_hog_functions_using_integration(team_id=instance.team_id, integration_id=instance.id)- batch_exports_using_integration = get_batch_exports_using_integration(+ batch_exports_using_integration = list_batch_exports_using_integration(team_id=instance.team_id, integration_id=instance.id)diff --git a/posthog/api/test/test_integration.py b/posthog/api/test/test_integration.pyindex cf65d1c60b3f..f6ee53cc1482 100644--- a/posthog/api/test/test_integration.py+++ b/posthog/api/test/test_integration.py@@ -78,7 +78,8 @@ from posthog.rate_limit import GitHubRepositoryRefreshThrottlefrom posthog.slack.channels import is_shared_channelfrom products.access_control.backend.models.access_control import AccessControl-from products.batch_exports.backend.models import BatchExport, BatchExportDestination+from products.batch_exports.backend.facade import testing as batch_exports_testing+from products.batch_exports.backend.facade.contracts import DestinationTypefrom products.cdp.backend.models import HogFunctionfrom products.cdp.backend.models.hog_function_template import HogFunctionTemplatefrom products.workflows.backend.models import HogFlow@@ -6868,10 +6869,13 @@ class TestIntegrationDeletionHogFunctionGuard:assert Integration.objects.filter(id=self.integration.id).exists()def test_destroy_blocked_message_includes_batch_exports(self, client: HttpClient):- dest = BatchExportDestination.objects.create(- config={}, type=BatchExportDestination.Destination.AWS_S3, integration=self.integration+ batch_exports_testing.create_batch_export(+ self.team.id,+ name="Test batch export",+ destination_type=DestinationType.AWS_S3,+ destination_config={},+ integration_id=self.integration.id,)- BatchExport.objects.create(name="Test batch export", destination=dest, team=self.team, interval="hour")response = self._delete(client)diff --git a/posthog/api/test/test_team_deletion.py b/posthog/api/test/test_team_deletion.pyindex ad2d8db3da79..62974d1c8e25 100644--- a/posthog/api/test/test_team_deletion.py+++ b/posthog/api/test/test_team_deletion.py@@ -269,7 +269,7 @@ class TestTeamDeletionSideEffects(NonAtomicBaseTest):response = self.client.delete(f"/api/environments/{team.id}")assert response.status_code == 204- @patch("posthog.models.team.util.sync_connect")+ @patch("posthog.temporal.common.client.sync_connect")@patch("products.data_modeling.backend.logic.schedule_reconcile.delete_schedule")@patch("products.data_modeling.backend.logic.schedule_reconcile.sync_connect")def test_delete_data_modeling_schedules(self, mock_sync_connect, mock_delete_schedule, _batch_export_connect):@@ -293,7 +293,7 @@ class TestTeamDeletionSideEffects(NonAtomicBaseTest):mock_delete_schedule.assert_called_once_with(mock_temporal, schedule_id=str(saved_query.id))- @patch("posthog.models.team.util.sync_connect")+ @patch("posthog.temporal.common.client.sync_connect")@patch("products.data_modeling.backend.facade.api.delete_team_data_modeling_schedules")def test_team_is_still_deleted_when_the_schedule_teardown_fails(self, mock_delete_schedules, _batch_export_connect):team: Team = Team.objects.create_with_data(initiating_user=self.user, organization=self.organization)@@ -306,7 +306,7 @@ class TestTeamDeletionSideEffects(NonAtomicBaseTest):mock_delete_schedules.assert_any_call(team.id)assert not Team.objects.filter(id=team.id).exists()- @patch("posthog.models.team.util.sync_connect")+ @patch("posthog.temporal.common.client.sync_connect")@patch("products.data_modeling.backend.logic.schedule_reconcile.delete_schedule")@patch("products.data_modeling.backend.logic.schedule_reconcile.sync_connect")def test_delete_data_modeling_schedules_handles_not_found(diff --git a/posthog/hogql/database/schema/test/test_system_tables.py b/posthog/hogql/database/schema/test/test_system_tables.pyindex 30d993588027..6d2d993d4b70 100644--- a/posthog/hogql/database/schema/test/test_system_tables.py+++ b/posthog/hogql/database/schema/test/test_system_tables.py@@ -45,6 +45,12 @@ from products.ai_observability.backend.models.trace_reviews import TraceReview,from products.alerts.backend.models.alert import AlertConfigurationfrom products.annotations.backend.models.annotation import Annotationfrom products.autoresearch.backend.facade import testing as autoresearch_testing+from products.batch_exports.backend.facade import testing as batch_exports_testing+from products.batch_exports.backend.facade.contracts import (+ BatchExportBackfillStatus,+ BatchExportRunStatus,+ DestinationType,+)from products.business_knowledge.backend.models import KnowledgeChunk, KnowledgeDocument, KnowledgeSourcefrom products.business_knowledge.backend.models.constants import SourceStatus, SourceTypefrom products.canvas.backend.models import Canvas@@ -206,11 +212,10 @@ class TestSystemTablesTeamScoping(BaseTest):}-def _create_batch_export(team: Team, label: str):- from products.batch_exports.backend.models.batch_export import BatchExport, BatchExportDestination-- destination = BatchExportDestination.objects.create(type="AwsS3", config={})- return BatchExport.objects.create(team=team, name=f"export_{label}", destination=destination, interval="hour")+def _create_batch_export(team: Team, label: str) -> uuid.UUID:+ return batch_exports_testing.create_batch_export(+ team.pk, name=f"export_{label}", destination_type=DestinationType.AWS_S3, destination_config={}+ )def _create_data_deletion_request(team: Team, label: str) -> DataDeletionRequest:@@ -223,44 +228,35 @@ def _create_data_deletion_request(team: Team, label: str) -> DataDeletionRequest)-def _create_batch_export_backfill(team: Team, label: str):- from products.batch_exports.backend.models.batch_export import (- BatchExport,- BatchExportBackfill,- BatchExportDestination,+def _create_batch_export_backfill(team: Team, label: str) -> uuid.UUID:+ batch_export_id = batch_exports_testing.create_batch_export(+ team.pk, name=f"export_for_backfill_{label}", destination_type=DestinationType.AWS_S3, destination_config={})-- destination = BatchExportDestination.objects.create(type="AwsS3", config={})- batch_export = BatchExport.objects.create(- team=team, name=f"export_for_backfill_{label}", destination=destination, interval="hour"+ return batch_exports_testing.create_backfill(+ batch_export_id, team_id=team.pk, status=BatchExportBackfillStatus.RUNNING)- return BatchExportBackfill.objects.create(team=team, batch_export=batch_export, status="Running")--def _create_batch_export_run(team: Team, label: str):- from products.batch_exports.backend.models.batch_export import BatchExport, BatchExportDestination, BatchExportRun- destination = BatchExportDestination.objects.create(type="AwsS3", config={})- batch_export = BatchExport.objects.create(- team=team, name=f"export_for_run_{label}", destination=destination, interval="hour"+def _create_batch_export_run(team: Team, label: str) -> uuid.UUID:+ batch_export_id = batch_exports_testing.create_batch_export(+ team.pk, name=f"export_for_run_{label}", destination_type=DestinationType.AWS_S3, destination_config={}+ )+ return batch_exports_testing.create_batch_export_run(+ batch_export_id=batch_export_id, status=BatchExportRunStatus.RUNNING, data_interval_end=timezone.now())- return BatchExportRun.objects.create(batch_export=batch_export, status="Running", data_interval_end=timezone.now())--def _create_batch_export_on_demand(team: Team, label: str):- from products.batch_exports.backend.models.batch_export import BatchExportDestination, BatchExportOnDemand-- destination = BatchExportDestination.objects.create(type="AwsS3", config={})- with team_scope(team.pk):- return BatchExportOnDemand.objects.create(team=team, destination=destination)+def _create_batch_export_on_demand(team: Team, label: str) -> uuid.UUID:+ return batch_exports_testing.create_batch_export_on_demand(+ team.pk, destination_type=DestinationType.AWS_S3, destination_config={}+ )-def _create_batch_export_run_on_demand(team: Team, label: str):- from products.batch_exports.backend.models.batch_export import BatchExportRun- on_demand = _create_batch_export_on_demand(team, label)- return BatchExportRun.objects.create(- batch_export_on_demand=on_demand, status="Running", data_interval_end=timezone.now()+def _create_batch_export_run_on_demand(team: Team, label: str) -> uuid.UUID:+ return batch_exports_testing.create_batch_export_run(+ on_demand_id=_create_batch_export_on_demand(team, label),+ status=BatchExportRunStatus.RUNNING,+ data_interval_end=timezone.now(),)diff --git a/posthog/management/commands/migrate_team.py b/posthog/management/commands/migrate_team.pyindex ec01a61146a9..545e63e60109 100644--- a/posthog/management/commands/migrate_team.py+++ b/posthog/management/commands/migrate_team.py@@ -1,26 +1,24 @@import loggingimport datetime as dt+from collections.abc import Sequencefrom django.core.management.base import BaseCommand, CommandError-from django.db import transactionfrom posthog.models import Team-from posthog.temporal.common.client import sync_connect--from products.batch_exports.backend.models.batch_export import (- BATCH_EXPORT_INTERVALS,- BatchExport,- BatchExportBackfill,- BatchExportDestination,- BatchExportRun,++from products.batch_exports.backend.facade import api as batch_exports_api+from products.batch_exports.backend.facade.contracts import (+ BatchExportBackfillSummary,+ BatchExportDetail,+ DestinationType,)-from products.batch_exports.backend.service import backfill_export, delete_batch_export, sync_batch_exportlogger = logging.getLogger(__name__)logger.setLevel(logging.INFO)EXPORT_NAME = "PostHog HTTP Migration"-VALID_INTERVALS = {i[0] for i in BATCH_EXPORT_INTERVALS}+DATA_START_UNBOUNDED = "the start of the team's data"+VALID_INTERVALS = set(batch_exports_api.list_supported_intervals())REGION_URLS = {"us": "https://app.posthog.com/batch","eu": "https://eu.posthog.com/batch",@@ -100,9 +98,16 @@ class Command(BaseCommand):)try:- existing_export: BatchExport = BatchExport.objects.get(- team=team, destination__type="HTTP", name=EXPORT_NAME, deleted=False+ existing_export = batch_exports_api.get_batch_export_by_name(team.id, EXPORT_NAME, DestinationType.HTTP)+ except batch_exports_api.MultipleBatchExportsError:+ raise CommandError(+ "More than one existing migration found! This should never happen if the management command is used, we don't know enough to proceed")++ if existing_export is None:+ is_existing_export = False+ display("No existing migration was found")+ else:is_existing_export = Truedisplay_existing(existing_export=existing_export, verbose=verbose)@@ -113,16 +118,9 @@ class Command(BaseCommand):raise CommandError("Didn't receive 'y', exiting")print() # noqa: T201- delete_batch_export(existing_export)+ batch_exports_api.delete_batch_export(existing_export.id, team.id)is_existing_export = Falsedisplay("Deleted existing batch export and backfill")- except BatchExport.DoesNotExist:- is_existing_export = False- display("No existing migration was found")- except BatchExport.MultipleObjectsReturned:- raise CommandError(- "More than one existing migration found! This should never happen if the management command is used, we don't know enough to proceed"- )if not create_requested:# User didn't provide any arguments to create a migration, so they must have just wanted@@ -148,9 +146,30 @@ class Command(BaseCommand):)-def display_existing(*, existing_export: BatchExport, verbose: bool):- existing_backfill = BatchExportBackfill.objects.get(batch_export=existing_export)- most_recent_run = BatchExportRun.objects.filter(batch_export=existing_export).order_by("-created_at").first()+def get_migrated_data_start(backfills: Sequence[BatchExportBackfillSummary]) -> dt.datetime | str | None:+ """Return where the migrated data begins, from the backfills that did not fail.++ A later backfill can cover a narrower range than the one the command started, so the+ earliest start wins. A backfill with no start exports all data, so the range is then+ unbounded. None means that every backfill failed.+ """+ starts = [+ backfill.adjusted_start_at or backfill.start_at+ for backfill in backfills+ if backfill.status not in batch_exports_api.FAILED_BACKFILL_STATUSES+ ]+ if not starts:+ return None+ if any(start is None for start in starts):+ return DATA_START_UNBOUNDED+ return min(start for start in starts if start is not None)+++def display_existing(*, existing_export: BatchExportDetail, verbose: bool):+ existing_backfills = batch_exports_api.list_backfills_for_export(existing_export.id, existing_export.team_id)+ if not existing_backfills:+ raise CommandError("The existing migration has no backfill, so we don't know enough to proceed")+ most_recent_run = batch_exports_api.get_latest_run(existing_export.id, existing_export.team_id)if verbose:display(@@ -160,29 +179,28 @@ def display_existing(*, existing_export: BatchExport, verbose: bool):interval=existing_export.interval,created_at=existing_export.created_at,last_updated_at=existing_export.last_updated_at,- exclude_events=existing_export.destination.config.get("exclude_events", []),- include_events=existing_export.destination.config.get("include_events", []),- )- display(- "Existing migration backfill (verbose details)",- backfill_id=existing_backfill.id,- status=existing_backfill.status,- start_at=existing_backfill.start_at,- created_at=existing_backfill.created_at,- last_updated_at=existing_backfill.last_updated_at,+ exclude_events=list(existing_export.exclude_events),+ include_events=list(existing_export.include_events),)+ for existing_backfill in existing_backfills:+ display(+ "Existing migration backfill (verbose details)",+ backfill_id=existing_backfill.id,+ status=existing_backfill.status,+ start_at=existing_backfill.start_at,+ created_at=existing_backfill.created_at,+ last_updated_at=existing_backfill.last_updated_at,+ )if not most_recent_run:display("No batch export runs found, is the migration brand new?")else:- most_recent_completed_run = (- BatchExportRun.objects.filter(batch_export=existing_export, status=BatchExportRun.Status.COMPLETED)- .order_by("-finished_at")- .first()+ most_recent_completed_run = batch_exports_api.get_latest_completed_run(+ existing_export.id, existing_export.team_id)if most_recent_completed_run:- data_start_at = existing_backfill.adjusted_start_at or existing_backfill.start_at+ data_start_at = get_migrated_data_start(existing_backfills)data_end_at = most_recent_completed_run.data_interval_enddisplay("Found an existing migration, range of data migrated:",@@ -256,26 +274,22 @@ def create_migration(# This is a precaution so we don't accidentally leave the export running indefinitely.end_at = now + dt.timedelta(days=end_days_from_now)- destination = BatchExportDestination(- type=BatchExportDestination.Destination.HTTP,- config={"url": url, "token": dest_token, "include_events": include_events, "exclude_events": exclude_events},- )- batch_export = BatchExport(- team_id=team_id,- destination=destination,+ batch_export = batch_exports_api.create_batch_export(+ team_id,name=EXPORT_NAME,+ destination_type=DestinationType.HTTP,+ destination_config={+ "url": url,+ "token": dest_token,+ "include_events": include_events,+ "exclude_events": exclude_events,+ },interval=interval,paused=True,end_at=end_at,)- sync_batch_export(batch_export, created=True)-- with transaction.atomic():- destination.save()- batch_export.save()- temporal = sync_connect()- backfill_id = backfill_export(temporal, str(batch_export.pk), team_id, start_at_datetime, end_at=None)+ backfill_id = batch_exports_api.backfill_batch_export(batch_export.id, team_id, start_at_datetime, end_at=None)display("Backfill started", batch_export_id=batch_export.id, backfill_id=backfill_id)diff --git a/posthog/management/commands/test/test_migrate_team.py b/posthog/management/commands/test/test_migrate_team.pynew file mode 100644index 000000000000..744f86b4ecdf--- /dev/null+++ b/posthog/management/commands/test/test_migrate_team.py@@ -0,0 +1,47 @@+import uuid+import datetime as dt++import pytest++from posthog.management.commands.migrate_team import DATA_START_UNBOUNDED, get_migrated_data_start++from products.batch_exports.backend.facade.contracts import BatchExportBackfillStatus, BatchExportBackfillSummary++JAN_1 = dt.datetime(2026, 1, 1, tzinfo=dt.UTC)+JAN_2 = JAN_1 + dt.timedelta(days=1)+JAN_3 = JAN_1 + dt.timedelta(days=2)+++def _backfill(status: str, start_at: dt.datetime | None) -> BatchExportBackfillSummary:+ return BatchExportBackfillSummary(+ id=uuid.uuid4(),+ status=status,+ start_at=start_at,+ adjusted_start_at=None,+ created_at=JAN_3,+ last_updated_at=JAN_3,+ )+++ "backfills,expected",+ [+ (+ [+ (BatchExportBackfillStatus.COMPLETED, JAN_3),+ (BatchExportBackfillStatus.RUNNING, JAN_2),+ (BatchExportBackfillStatus.FAILED, JAN_1),+ ],+ JAN_2,+ ),+ (+ [(BatchExportBackfillStatus.COMPLETED, JAN_2), (BatchExportBackfillStatus.COMPLETED, None)],+ DATA_START_UNBOUNDED,+ ),+ ([(BatchExportBackfillStatus.CANCELLED, None), (BatchExportBackfillStatus.COMPLETED, JAN_2)], JAN_2),+ ([(BatchExportBackfillStatus.FAILED, JAN_1), (BatchExportBackfillStatus.TIMEDOUT, JAN_2)], None),+ ],+ ids=["earliest of the backfills that did not fail", "no start is unbounded", "failed no start", "all failed"],+)+def test_migrated_data_start(backfills, expected):+ assert get_migrated_data_start([_backfill(status, start_at) for status, start_at in backfills]) == expecteddiff --git a/posthog/models/team/util.py b/posthog/models/team/util.pyindex 4e9bf52daab8..8d0c79ba301f 100644--- a/posthog/models/team/util.py+++ b/posthog/models/team/util.py@@ -9,10 +9,8 @@ import structlogfrom posthog.cache_utils import cache_forfrom posthog.models.async_migration import is_async_migration_complete-from posthog.temporal.common.client import sync_connectfrom products.ai_training.backend.facade.api import queue_training_deletion-from products.batch_exports.backend.service import BatchExportServiceScheduleNotFound, batch_export_delete_schedulefrom products.dashboards.backend.models.dashboard_tile import DashboardTilelogger = structlog.get_logger(__name__)@@ -309,30 +307,6 @@ def _raw_delete_batch(queryset: Any, batch_size: int = 10000):time.sleep(0.1)-def delete_batch_exports(team_ids: list[int]):- """Delete BatchExports for deleted teams.-- Using normal CASCADE doesn't trigger a delete from Temporal.- """- from products.batch_exports.backend.models.batch_export import BatchExport-- temporal = sync_connect()-- for batch_export in BatchExport.objects.filter(team_id__in=team_ids, deleted=False):- schedule_id = batch_export.id-- batch_export.delete()- batch_export.destination.delete()-- try:- batch_export_delete_schedule(temporal, str(schedule_id))- except BatchExportServiceScheduleNotFound as e:- logger.warning(- "Schedule not found during team deletion",- schedule_id=e.schedule_id,- )--def delete_team_records(team_ids: list[int]) -> None:"""Delete the Team rows once their bulky child data has been removed.diff --git a/posthog/tasks/email.py b/posthog/tasks/email.pyindex 49bb3e859f7a..877ed5d93465 100644--- a/posthog/tasks/email.py+++ b/posthog/tasks/email.py@@ -50,13 +50,12 @@ from posthog.models.organization_notification_lock import (pipeline_lock_for_team,)from posthog.models.scoping import with_team_scope-from posthog.models.utils import UUIDTfrom posthog.ph_client import feature_enabled_or_false, get_client, ph_scoped_capturefrom posthog.scoping_audit import skip_team_scope_auditfrom posthog.user_permissions import UserPermissionsfrom products.access_control.backend.facade.user_access_control import UserAccessControl-from products.batch_exports.backend.models.batch_export import BatchExport, BatchExportRun+from products.batch_exports.backend.facade import api as batch_exports_apifrom products.cdp.backend.models.hog_functions.hog_function import HogFunctionfrom products.cdp.backend.models.plugin import Plugin, PluginConfigfrom products.conversations.backend.models import Ticket@@ -1085,7 +1084,8 @@ def send_email_sending_tier_demoted(team_id: int, per_day: int, per_hour: int, ddef send_batch_export_run_failure(- batch_export_run_id: str | UUIDT,+ batch_export_run_id: str | uuid.UUID,+ team_id: int,failure_rate: float = 1.0,) -> None:logger = structlog.get_logger(__name__)@@ -1095,17 +1095,14 @@ def send_batch_export_run_failure(logger.warning("Email service is not available")return None- batch_export_run: BatchExportRun = BatchExportRun.objects.select_related(- "batch_export__team", "batch_export_on_demand__team"- ).get(id=batch_export_run_id)- batch_export = batch_export_run.parent+ run_failure = batch_exports_api.get_run_failure(batch_export_run_id, team_id)# On-demand exports do not have a page for this email to link to.- if not isinstance(batch_export, BatchExport):+ if run_failure is None:return- team: Team = batch_export.team+ team = Team.objects.get(id=run_failure.team_id)- pipeline_id = f"batch_export:{batch_export.id}"+ pipeline_id = f"batch_export:{run_failure.export_id}"memberships_to_email = get_members_to_notify_for_pipeline_error(team, failure_rate, pipeline_id=pipeline_id)if not memberships_to_email:return@@ -1113,20 +1110,22 @@ def send_batch_export_run_failure(logger.info("Preparing notification email for batch export run %s", batch_export_run_id)# NOTE: We are taking only the date component to cap the number of emails at one per day per batch export.- last_updated_at_date = batch_export_run.last_updated_at.strftime("%Y-%m-%d")+ last_updated_at_date = run_failure.last_updated_at.strftime("%Y-%m-%d")- campaign_key: str = f"batch_export_run_email_batch_export_{batch_export.id}_last_updated_at_{last_updated_at_date}"+ campaign_key: str = (+ f"batch_export_run_email_batch_export_{run_failure.export_id}_last_updated_at_{last_updated_at_date}"+ )- subject = f"PostHog: {batch_export.name} batch export run failure"+ subject = f"PostHog: {run_failure.export_name} batch export run failure"message = EmailMessage(campaign_key=campaign_key,subject=subject,template_name="batch_export_run_failure",template_context={- "time": batch_export_run.last_updated_at.strftime("%I:%M%p %Z on %B %d"),+ "time": run_failure.last_updated_at.strftime("%I:%M%p %Z on %B %d"),"team": team,- "id": batch_export.id,- "name": batch_export.name,+ "id": run_failure.export_id,+ "name": run_failure.export_name,},)logger.info("Prepared notification email for campaign %s", campaign_key)diff --git a/posthog/tasks/test/test_email.py b/posthog/tasks/test/test_email.pyindex 76a4bea483f9..ca178f6b77bc 100644--- a/posthog/tasks/test/test_email.py+++ b/posthog/tasks/test/test_email.py@@ -23,7 +23,6 @@ from posthog.models.instance_setting import set_instance_settingfrom posthog.models.messaging import MessagingRecord, get_email_hashesfrom posthog.models.organization import OrganizationMembershipfrom posthog.models.organization_invite import OrganizationInvite-from posthog.models.scoping import team_scopefrom posthog.tasks.email import (MAX_VIEWS_PER_DIGEST_EMAIL,get_members_to_notify_for_pipeline_error,@@ -60,18 +59,31 @@ from posthog.tasks.test.utils_email_tests import mock_email_messagesfrom posthog.test.api_keys import create_project_secret_api_keyfrom products.access_control.backend.models.access_control import AccessControl-from products.batch_exports.backend.models.batch_export import (- BatchExport,- BatchExportDestination,- BatchExportOnDemand,- BatchExportRun,-)+from products.batch_exports.backend.facade import testing as batch_exports_testing+from products.batch_exports.backend.facade.contracts import BatchExportRunStatus, DestinationTypefrom products.cdp.backend.models.hog_functions.hog_function import HogFunctionfrom products.cdp.backend.models.plugin import Plugin, PluginConfigfrom products.data_modeling.backend.facade.api import mark_node_suspended, sync_saved_query_to_dagfrom products.data_modeling.backend.facade.models import DataModelingJob, DataModelingJobEngine, DataWarehouseSavedQuery+def _create_failed_batch_export_run(team_id: int) -> tuple[uuid.UUID, uuid.UUID]:+ batch_export_id = batch_exports_testing.create_batch_export(+ team_id,+ name="A batch export",+ destination_type=DestinationType.AWS_S3,+ destination_config={"bucket_name": "my_production_s3_bucket"},+ )+ now = dt.datetime.now()+ batch_export_run_id = batch_exports_testing.create_batch_export_run(+ batch_export_id=batch_export_id,+ status=BatchExportRunStatus.FAILED,+ data_interval_start=now - dt.timedelta(hours=1),+ data_interval_end=now,+ )+ return batch_export_id, batch_export_run_id++def create_org_team_and_user(creation_date: str, email: str, ingested_event: bool = False) -> tuple[Organization, User]:with time_machine.travel(creation_date, tick=False):org = Organization.objects.create(name="too_late_org")@@ -615,21 +627,10 @@ class TestEmail(APIBaseTest, ClickhouseTestMixin):def test_send_batch_export_run_failure(self, MockEmailMessage: MagicMock) -> None:mocked_email_messages = mock_email_messages(MockEmailMessage)_, user = create_org_team_and_user("2022-01-02 00:00:00", "[email protected]")- batch_export_destination = BatchExportDestination.objects.create(- type=BatchExportDestination.Destination.AWS_S3, config={"bucket_name": "my_production_s3_bucket"}- )- batch_export = BatchExport.objects.create( # type: ignore- team=user.team, name="A batch export", destination=batch_export_destination- )- now = dt.datetime.now()- batch_export_run = BatchExportRun.objects.create(- batch_export=batch_export,- status=BatchExportRun.Status.FAILED,- data_interval_start=now - dt.timedelta(hours=1),- data_interval_end=now,- )+ team_id = cast(Team, user.team).id+ _, batch_export_run_id = _create_failed_batch_export_run(team_id)- send_batch_export_run_failure(batch_export_run.id)+ send_batch_export_run_failure(batch_export_run_id, team_id)assert len(mocked_email_messages) == 1assert mocked_email_messages[0].send.call_count == 1@@ -637,44 +638,32 @@ class TestEmail(APIBaseTest, ClickhouseTestMixin):def test_does_not_send_batch_export_run_failure_for_on_demand_export(self, MockEmailMessage: MagicMock) -> None:mocked_email_messages = mock_email_messages(MockEmailMessage)- destination = BatchExportDestination.objects.create(- type=BatchExportDestination.Destination.AWS_S3, config={"bucket_name": "my_production_s3_bucket"}+ on_demand_id = batch_exports_testing.create_batch_export_on_demand(+ self.team.pk,+ destination_type=DestinationType.AWS_S3,+ destination_config={"bucket_name": "my_production_s3_bucket"},)- with team_scope(team_id=self.team.pk, canonical=True):- on_demand_export = BatchExportOnDemand.objects.create(team=self.team, destination=destination)now = dt.datetime.now()- batch_export_run = BatchExportRun.objects.create(- batch_export_on_demand=on_demand_export,- status=BatchExportRun.Status.FAILED,+ batch_export_run_id = batch_exports_testing.create_batch_export_run(+ on_demand_id=on_demand_id,+ status=BatchExportRunStatus.FAILED,data_interval_start=now - dt.timedelta(hours=1),data_interval_end=now,)- send_batch_export_run_failure(batch_export_run.id)+ send_batch_export_run_failure(batch_export_run_id, self.team.pk)assert mocked_email_messages == []def test_send_batch_export_run_failure_with_settings(self, MockEmailMessage: MagicMock) -> None:mocked_email_messages = mock_email_messages(MockEmailMessage)- batch_export_destination = BatchExportDestination.objects.create(- type=BatchExportDestination.Destination.AWS_S3, config={"bucket_name": "my_production_s3_bucket"}- )- batch_export = BatchExport.objects.create( # type: ignore- team=self.user.team, name="A batch export", destination=batch_export_destination- )- now = dt.datetime.now()- batch_export_run = BatchExportRun.objects.create(- batch_export=batch_export,- status=BatchExportRun.Status.FAILED,- data_interval_start=now - dt.timedelta(hours=1),- data_interval_end=now,- )+ _, batch_export_run_id = _create_failed_batch_export_run(self.team.id)user2 = self._create_user("[email protected]")self.user.partial_notification_settings = {"plugin_disabled": False}self.user.save()- send_batch_export_run_failure(batch_export_run.id)+ send_batch_export_run_failure(batch_export_run_id, self.team.id)# Should only be sent to user2assert mocked_email_messages[0].to == [{"recipient": "[email protected]", "raw_email": "[email protected]", "distinct_id": str(user2.distinct_id)}@@ -683,28 +672,16 @@ class TestEmail(APIBaseTest, ClickhouseTestMixin):self.user.partial_notification_settings = {"plugin_disabled": True}self.user.save()- send_batch_export_run_failure(batch_export_run.id)+ send_batch_export_run_failure(batch_export_run_id, self.team.id)# should be sent to bothassert len(mocked_email_messages[1].to) == 2def test_send_batch_export_run_failure_with_threshold(self, MockEmailMessage: MagicMock) -> None:mocked_email_messages = mock_email_messages(MockEmailMessage)- batch_export_destination = BatchExportDestination.objects.create(- type=BatchExportDestination.Destination.AWS_S3, config={"bucket_name": "my_production_s3_bucket"}- )- batch_export = BatchExport.objects.create( # type: ignore- team=self.user.team, name="A batch export", destination=batch_export_destination- )- now = dt.datetime.now()- batch_export_run = BatchExportRun.objects.create(- batch_export=batch_export,- status=BatchExportRun.Status.FAILED,- data_interval_start=now - dt.timedelta(hours=1),- data_interval_end=now,- )+ _, batch_export_run_id = _create_failed_batch_export_run(self.team.id)# Default threshold is 1% - failure rate 0.5 exceeds it, so notify- send_batch_export_run_failure(batch_export_run.id, failure_rate=0.5)+ send_batch_export_run_failure(batch_export_run_id, self.team.id, failure_rate=0.5)assert len(mocked_email_messages) == 1assert mocked_email_messages[0].send.call_count == 1@@ -714,17 +691,17 @@ class TestEmail(APIBaseTest, ClickhouseTestMixin):"data_pipeline_error_threshold": 0.5,}self.user.save()- send_batch_export_run_failure(batch_export_run.id, failure_rate=0.6)+ send_batch_export_run_failure(batch_export_run_id, self.team.id, failure_rate=0.6)assert len(mocked_email_messages) == 2assert mocked_email_messages[1].send.call_count == 1# Test with threshold 0.5 and failure rate 0.4 - should NOT notify- send_batch_export_run_failure(batch_export_run.id, failure_rate=0.4)+ send_batch_export_run_failure(batch_export_run_id, self.team.id, failure_rate=0.4)# Should still be 2 messages (no new message sent)assert len(mocked_email_messages) == 2# Test with threshold 0.5 and failure rate exactly 0.5 - should NOT notify (threshold is exclusive)- send_batch_export_run_failure(batch_export_run.id, failure_rate=0.5)+ send_batch_export_run_failure(batch_export_run_id, self.team.id, failure_rate=0.5)assert len(mocked_email_messages) == 2# Test with threshold 0.0 explicitly set - should notify on any failure@@ -733,25 +710,13 @@ class TestEmail(APIBaseTest, ClickhouseTestMixin):"data_pipeline_error_threshold": 0.0,}self.user.save()- send_batch_export_run_failure(batch_export_run.id, failure_rate=0.1)+ send_batch_export_run_failure(batch_export_run_id, self.team.id, failure_rate=0.1)assert len(mocked_email_messages) == 3assert mocked_email_messages[2].send.call_count == 1def test_send_batch_export_run_failure_with_threshold_disabled(self, MockEmailMessage: MagicMock) -> None:mocked_email_messages = mock_email_messages(MockEmailMessage)- batch_export_destination = BatchExportDestination.objects.create(- type=BatchExportDestination.Destination.AWS_S3, config={"bucket_name": "my_production_s3_bucket"}- )- batch_export = BatchExport.objects.create( # type: ignore- team=self.user.team, name="A batch export", destination=batch_export_destination- )- now = dt.datetime.now()- batch_export_run = BatchExportRun.objects.create(- batch_export=batch_export,- status=BatchExportRun.Status.FAILED,- data_interval_start=now - dt.timedelta(hours=1),- data_interval_end=now,- )+ _, batch_export_run_id = _create_failed_batch_export_run(self.team.id)# Test with plugin_disabled=False - should not notify even with high failure rateself.user.partial_notification_settings = {@@ -759,7 +724,7 @@ class TestEmail(APIBaseTest, ClickhouseTestMixin):"data_pipeline_error_threshold": 0.5,}self.user.save()- send_batch_export_run_failure(batch_export_run.id, failure_rate=1.0)+ send_batch_export_run_failure(batch_export_run_id, self.team.id, failure_rate=1.0)assert len(mocked_email_messages) == 0def test_send_external_data_failure_digest(self, MockEmailMessage: MagicMock) -> None:@@ -1352,28 +1317,16 @@ class TestEmail(APIBaseTest, ClickhouseTestMixin):def test_send_batch_export_run_failure_per_pipeline_opt_out(self, MockEmailMessage: MagicMock) -> None:mocked_email_messages = mock_email_messages(MockEmailMessage)- batch_export_destination = BatchExportDestination.objects.create(- type=BatchExportDestination.Destination.AWS_S3, config={"bucket_name": "my_production_s3_bucket"}- )- batch_export = BatchExport.objects.create( # type: ignore- team=self.user.team, name="A batch export", destination=batch_export_destination- )- now = dt.datetime.now()- batch_export_run = BatchExportRun.objects.create(- batch_export=batch_export,- status=BatchExportRun.Status.FAILED,- data_interval_start=now - dt.timedelta(hours=1),- data_interval_end=now,- )+ batch_export_id, batch_export_run_id = _create_failed_batch_export_run(self.team.id)user2 = self._create_user("[email protected]")self.user.partial_notification_settings = {"plugin_disabled": True,- "pipeline_notifications_disabled": {f"batch_export:{batch_export.id}": True},+ "pipeline_notifications_disabled": {f"batch_export:{batch_export_id}": True},}self.user.save()- send_batch_export_run_failure(batch_export_run.id)+ send_batch_export_run_failure(batch_export_run_id, self.team.id)assert mocked_email_messages[0].to == [{"recipient": "[email protected]", "raw_email": "[email protected]", "distinct_id": str(user2.distinct_id)}diff --git a/posthog/tasks/test/test_usage_report.py b/posthog/tasks/test/test_usage_report.pyindex 174c26b59bbe..c4ee4d507484 100644--- a/posthog/tasks/test/test_usage_report.py+++ b/posthog/tasks/test/test_usage_report.py@@ -47,7 +47,6 @@ from posthog.models import Organization, Project, 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 (@@ -80,12 +79,8 @@ 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,- BatchExportOnDemand,- BatchExportRun,-)+from products.batch_exports.backend.facade import testing as batch_exports_testing+from products.batch_exports.backend.facade.contracts import BatchExportModel, BatchExportRunStatus, DestinationTypefrom products.cdp.backend.models.plugin import Plugin, PluginConfigfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.data_modeling.backend.facade.models import DataWarehouseSavedQuery@@ -2738,23 +2733,13 @@ class TestExternalDataSyncUsageReport(ClickhouseDestroyTablesMixin, TestCase, Cl# created at doesn't matter. just what's running or completed at run timeself._setup_teams()- batch_export_destination = BatchExportDestination.objects.create(- type=BatchExportDestination.Destination.AWS_S3,- config={"bucket_name": "my_production_s3_bucket"},- )- BatchExport.objects.create(- team_id=3,- name="A batch export",- destination=batch_export_destination,- paused=False,- )-- BatchExport.objects.create(- team=self.analytics_team,- name="A batch export",- destination=batch_export_destination,- paused=False,- )+ for team_id in (3, self.analytics_team.id):+ batch_exports_testing.create_batch_export(+ team_id,+ name="A batch export",+ destination_type=DestinationType.AWS_S3,+ destination_config={"bucket_name": "my_production_s3_bucket"},+ )period = get_previous_day(at=now() + relativedelta(days=1))all_reports = _get_all_org_reports(period=period)@@ -2782,75 +2767,56 @@ class TestExternalDataSyncUsageReport(ClickhouseDestroyTablesMixin, TestCase, Cl) -> None:self._setup_teams()- batch_export_destination = BatchExportDestination.objects.create(- type=BatchExportDestination.Destination.AWS_S3,- config={"bucket_name": "test_bucket"},- )- batch_export = BatchExport.objects.create(- team_id=3,+ batch_export_id = batch_exports_testing.create_batch_export(+ 3,name="Test export",- destination=batch_export_destination,- paused=False,- model=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- )+ destination_type=DestinationType.AWS_S3,+ destination_config={"bucket_name": "test_bucket"},+ model=BatchExportModel.EVENTS,+ )+ on_demand_id = batch_exports_testing.create_batch_export_on_demand(+ 3,+ destination_type=DestinationType.FILE_DOWNLOAD,+ destination_config={"format": "Parquet"},+ model=BatchExportModel.EVENTS,+ )++ for parent_id, parent_on_demand_id in ((batch_export_id, None), (None, on_demand_id)):+ for i in range(3):+ batch_exports_testing.create_batch_export_run(+ batch_export_id=parent_id,+ on_demand_id=parent_on_demand_id,+ data_interval_end=now() - timedelta(hours=i),+ data_interval_start=now() - timedelta(hours=i + 1),+ finished_at=now(),+ status=BatchExportRunStatus.COMPLETED,+ 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,+ hogql_batch_export_id = batch_exports_testing.create_batch_export(+ 3,name="Test HogQL export",- destination=batch_export_destination,- paused=False,- model=BatchExport.Model.HOGQL,+ destination_type=DestinationType.AWS_S3,+ destination_config={"bucket_name": "test_bucket"},+ model=BatchExportModel.HOGQL,+ )+ hogql_on_demand_id = batch_exports_testing.create_batch_export_on_demand(+ 3,+ destination_type=DestinationType.FILE_DOWNLOAD,+ destination_config={"format": "Parquet"},+ model=BatchExportModel.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(+ for parent_id, parent_on_demand_id in ((hogql_batch_export_id, None), (None, hogql_on_demand_id)):+ batch_exports_testing.create_batch_export_run(+ batch_export_id=parent_id,+ on_demand_id=parent_on_demand_id,data_interval_end=now(),data_interval_start=now() - timedelta(hours=1),finished_at=now(),- status=BatchExportRun.Status.COMPLETED,+ status=BatchExportRunStatus.COMPLETED,records_completed=5000,- **hogql_export_kwargs,)period = get_previous_day(at=now() + relativedelta(days=1))@@ -2873,44 +2839,28 @@ class TestExternalDataSyncUsageReport(ClickhouseDestroyTablesMixin, TestCase, Cl) -> None:self._setup_teams()- batch_export_destination = BatchExportDestination.objects.create(- type=BatchExportDestination.Destination.WORKFLOWS,- config={},- )- batch_export = BatchExport.objects.create(- team_id=3,+ batch_export_id = batch_exports_testing.create_batch_export(+ 3,name="Test export",- destination=batch_export_destination,- paused=False,- model=BatchExport.Model.EVENTS,+ destination_type=DestinationType.WORKFLOWS,+ destination_config={},+ model=BatchExportModel.EVENTS,+ )+ on_demand_id = batch_exports_testing.create_batch_export_on_demand(+ 3, destination_type=DestinationType.WORKFLOWS, destination_config={}, model=BatchExportModel.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,- 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- )+ for parent_id, parent_on_demand_id in ((batch_export_id, None), (None, on_demand_id)):+ for i in range(3):+ batch_exports_testing.create_batch_export_run(+ batch_export_id=parent_id,+ on_demand_id=parent_on_demand_id,+ data_interval_end=now() - timedelta(hours=i),+ data_interval_start=now() - timedelta(hours=i + 1),+ finished_at=now(),+ status=BatchExportRunStatus.COMPLETED,+ records_completed=100 * (i + 1), # 100, 200, 300+ )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.pyindex a74f68b957ce..42c6e82e5436 100644--- a/posthog/tasks/usage_report.py+++ b/posthog/tasks/usage_report.py@@ -13,8 +13,7 @@ from typing import Any, Literal, Optional, TypedDict, Unionfrom django.conf import settingsfrom django.core.exceptions import ImproperlyConfiguredfrom django.db import connection-from django.db.models import Count, F, Q, Sum-from django.db.models.functions import Coalesce+from django.db.models import Count, Q, Sumimport requestsimport structlog@@ -50,8 +49,7 @@ from posthog.tasks.report_utils import capture_eventfrom posthog.tasks.utils import CeleryQueuefrom posthog.utils import DayRange, get_helm_info_env, get_instance_realm, get_instance_region, get_previous_day-from products.batch_exports.backend.billing import exclude_non_billable_runs-from products.batch_exports.backend.models.batch_export import BatchExport, BatchExportRun+from products.batch_exports.backend.facade import api as batch_exports_apifrom products.cdp.backend.models.hog_functions.hog_function import HogFunction, HogFunctionTypefrom products.cdp.backend.models.plugin import PluginConfigfrom products.dashboards.backend.models.dashboard import Dashboard@@ -2130,16 +2128,10 @@ 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(- 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"))- )+ return [+ {"team_id": row.team_id, "total": row.total}+ for row in batch_exports_api.get_teams_with_billable_rows_exported(begin, end)+ ]@timed_log()@@ -2161,8 +2153,9 @@ def get_teams_with_active_external_data_schemas_in_period() -> list:@timed_log()@retry(tries=QUERY_RETRIES, delay=QUERY_RETRY_DELAY, backoff=QUERY_RETRY_BACKOFF)def get_teams_with_active_batch_exports_in_period() -> list:- # get all batch exports that are active or completed at run time- return list(BatchExport.objects.filter(paused=False).values("team_id").annotate(total=Count("id")))+ return [+ {"team_id": row.team_id, "total": row.total} for row in batch_exports_api.get_teams_with_active_batch_exports()+ ]@timed_log()diff --git a/posthog/temporal/delete_teams/activities.py b/posthog/temporal/delete_teams/activities.pyindex dffdfa38d970..1762ff779376 100644--- a/posthog/temporal/delete_teams/activities.py+++ b/posthog/temporal/delete_teams/activities.py@@ -65,9 +65,9 @@ async def delete_team_persons_activity(inputs: TeamDataActivityInputs) -> None:@temporalio.activity.defnasync def delete_batch_exports_activity(inputs: TeamDataActivityInputs) -> None:async with Heartbeater():- from posthog.models.team.util import delete_batch_exports+ from products.batch_exports.backend.facade.api import delete_batch_exports_for_teams- await database_sync_to_async_pool(delete_batch_exports)(inputs.team_ids)+ await database_sync_to_async_pool(delete_batch_exports_for_teams)(inputs.team_ids)@temporalio.activity.defndiff --git a/posthog/test/activity_log_utils.py b/posthog/test/activity_log_utils.pyindex 92ce4b15da30..9d776733a15a 100644--- a/posthog/test/activity_log_utils.py+++ b/posthog/test/activity_log_utils.py@@ -6,7 +6,7 @@ covered by the activity logging system."""from typing import TYPE_CHECKING, Any, Optional-from uuid import uuid4+from uuid import UUID, uuid4from django.utils import timezone@@ -492,21 +492,18 @@ class ActivityLogTestHelper(APILicensedTest):# BatchExportdef create_batch_export(self, name: str = "Test Export", **kwargs) -> dict[str, Any]:- """Create a batch export via direct model creation (like the original tests)."""- from products.batch_exports.backend.models.batch_export import BatchExport, BatchExportDestination+ """Create a batch export directly, without the API."""+ from products.batch_exports.backend.facade import testing as batch_exports_testing+ from products.batch_exports.backend.facade.contracts import DestinationType- # Create destination first (like the original tests do)- destination = BatchExportDestination.objects.create(- type=BatchExportDestination.Destination.HTTP, config={"url": "https://example.com"}- )-- batch_export = BatchExport.objects.create(- team=self.team,+ batch_export_id = batch_exports_testing.create_batch_export(+ self.team.id,name=name,- destination=destination,- interval="hour",+ destination_type=DestinationType.HTTP,+ destination_config={"url": "https://example.com"},**kwargs,)+ batch_export = batch_exports_testing.get_batch_export(batch_export_id, team_id=self.team.id)# Return in the same format as API wouldreturn {@@ -517,13 +514,10 @@ class ActivityLogTestHelper(APILicensedTest):}def update_batch_export(self, export_id: str, updates: dict[str, Any]) -> dict[str, Any]:- """Update a batch export via direct model access (like the original tests)."""- from products.batch_exports.backend.models.batch_export import BatchExport+ """Update a batch export directly, without the API."""+ from products.batch_exports.backend.facade import testing as batch_exports_testing- batch_export = BatchExport.objects.get(id=export_id)- for field, value in updates.items():- setattr(batch_export, field, value)- batch_export.save()+ batch_export = batch_exports_testing.update_batch_export(UUID(export_id), team_id=self.team.id, **updates)return {"id": str(batch_export.id),diff --git a/products/batch_exports/backend/facade/api.py b/products/batch_exports/backend/facade/api.pyindex e48e4ac6d781..e001e5d90acb 100644--- a/products/batch_exports/backend/facade/api.py+++ b/products/batch_exports/backend/facade/api.py@@ -45,19 +45,20 @@ if TYPE_CHECKING:from temporalio.client import Client__all__ = [+ "FAILED_BACKFILL_STATUSES","MultipleBatchExportsError","backfill_batch_export","count_batch_exports_for_teams","create_batch_export","delete_batch_export","delete_batch_exports_for_teams",- "get_backfill_for_export","get_batch_export_by_name","get_latest_completed_run","get_latest_run","get_run_failure","get_teams_with_active_batch_exports","get_teams_with_billable_rows_exported",+ "list_backfills_for_export","list_batch_exports_using_integration","list_latest_failed_runs","list_supported_intervals",@@ -73,6 +74,17 @@ FAILED_RUN_STATUSES = (BatchExportRun.Status.TERMINATED,)+# The statuses of a backfill that can stop before it exports anything.+FAILED_BACKFILL_STATUSES = frozenset(+ {+ BatchExportBackfill.Status.CANCELLED,+ BatchExportBackfill.Status.FAILED,+ BatchExportBackfill.Status.FAILED_RETRYABLE,+ BatchExportBackfill.Status.TERMINATED,+ BatchExportBackfill.Status.TIMEDOUT,+ }+)+# An on-demand export has no name of its own, so a failure list labels it generically.ON_DEMAND_EXPORT_NAME = "On-demand batch export"@@ -278,12 +290,10 @@ def get_batch_export_by_name(team_id: int, name: str, destination_type: str) ->return _to_detail(batch_export)-def get_backfill_for_export(export_id: UUID, team_id: int) -> contracts.BatchExportBackfillSummary | None:- """Return the most recent backfill of an export, or None if it has never been backfilled."""- backfill = (- BatchExportBackfill.objects.filter(batch_export_id=export_id, team_id=team_id).order_by("-created_at").first()- )- return _to_backfill_summary(backfill) if backfill is not None else None+def list_backfills_for_export(export_id: UUID, team_id: int) -> list[contracts.BatchExportBackfillSummary]:+ """Return every backfill of an export, newest first. An export can have any number of them."""+ backfills = BatchExportBackfill.objects.filter(batch_export_id=export_id, team_id=team_id).order_by("-created_at")+ return [_to_backfill_summary(backfill) for backfill in backfills]def get_latest_run(export_id: UUID, team_id: int) -> contracts.BatchExportRunSummary | None:diff --git a/products/batch_exports/backend/facade/contracts.py b/products/batch_exports/backend/facade/contracts.pyindex 1e52d7ab69df..c83be3a29f40 100644--- a/products/batch_exports/backend/facade/contracts.py+++ b/products/batch_exports/backend/facade/contracts.py@@ -3,7 +3,9 @@ Contract types for batch_exports.Stable, framework-free dataclasses defining what this product hands to the rest of thecodebase. No Django or DRF imports, and enums are flattened to their ``str`` value, so a-consumer never needs a model class to read a batch export.+consumer never needs a model class to read a batch export. The ``StrEnum`` classes name+those values for a consumer that writes them. They copy the model's ``TextChoices``, and+``tests/test_facade.py`` fails when the two copies differ.The fields are the ones consumers read today and nothing more. An encrypted model fieldnever crosses whole, because reading one decrypts it; ``BatchExportDetail`` documents the@@ -20,6 +22,7 @@ from dataclasses import (dataclass as stdlib_dataclass,field,)+from enum import StrEnumfrom uuid import UUIDfrom pydantic.dataclasses import dataclass@@ -28,6 +31,56 @@ from pydantic.dataclasses import dataclassBATCH_EXPORT_MODEL_LABEL = "batch_exports.BatchExport"+class DestinationType(StrEnum):+ S3 = "S3"+ AWS_S3 = "AwsS3"+ S3_COMPATIBLE = "S3Compatible"+ SNOWFLAKE = "Snowflake"+ POSTGRES = "Postgres"+ REDSHIFT = "Redshift"+ BIGQUERY = "BigQuery"+ DATABRICKS = "Databricks"+ AZURE_BLOB = "AzureBlob"+ WORKFLOWS = "Workflows"+ HTTP = "HTTP"+ NOOP = "NoOp"+ FILE_DOWNLOAD = "FileDownload"+++class BatchExportModel(StrEnum):+ """The data model an export reads, for scheduled and on-demand exports alike."""++ EVENTS = "events"+ PERSONS = "persons"+ SESSIONS = "sessions"+ HOGQL = "hogql"+++class BatchExportRunStatus(StrEnum):+ CANCELLED = "Cancelled"+ COMPLETED = "Completed"+ CONTINUED_AS_NEW = "ContinuedAsNew"+ FAILED = "Failed"+ FAILED_RETRYABLE = "FailedRetryable"+ FAILED_BILLING = "FailedBilling"+ TERMINATED = "Terminated"+ TIMEDOUT = "TimedOut"+ RUNNING = "Running"+ STARTING = "Starting"+++class BatchExportBackfillStatus(StrEnum):+ CANCELLED = "Cancelled"+ COMPLETED = "Completed"+ CONTINUED_AS_NEW = "ContinuedAsNew"+ FAILED = "Failed"+ FAILED_RETRYABLE = "FailedRetryable"+ TERMINATED = "Terminated"+ TIMEDOUT = "TimedOut"+ RUNNING = "Running"+ STARTING = "Starting"++@dataclass(frozen=True)class BatchExportRef:"""The bare identity of a batch export, for listing it by name."""diff --git a/products/batch_exports/backend/facade/testing.py b/products/batch_exports/backend/facade/testing.pyindex ecb53fb001be..cc423acd1670 100644--- a/products/batch_exports/backend/facade/testing.py+++ b/products/batch_exports/backend/facade/testing.py@@ -46,6 +46,7 @@ def create_batch_export(model: str | None = None,timezone: str | None = None,interval_offset: int | None = None,+ integration_id: int | None = None,sync_schedule: bool = False,) -> UUID:"""Create a scheduled batch export and return its id.@@ -53,7 +54,9 @@ def create_batch_export(``sync_schedule`` also creates the Temporal schedule, which a test only needs when itexercises the schedule itself. It costs a Temporal connection, so it is off by default."""- destination = BatchExportDestination(type=destination_type, config=dict(destination_config))+ destination = BatchExportDestination(+ type=destination_type, config=dict(destination_config), integration_id=integration_id+ )batch_export = BatchExport(team_id=team_id,destination=destination,@@ -142,6 +145,11 @@ def create_backfill().id+def get_batch_export(batch_export_id: UUID, *, team_id: int) -> contracts.BatchExportDetail:+ """Return a batch export as the facade's read functions shape it."""+ return _to_detail(BatchExport.objects.select_related("destination").get(id=batch_export_id, team_id=team_id))++def update_batch_export(batch_export_id: UUID, *, team_id: int, **fields: Any) -> contracts.BatchExportDetail:"""Set fields on a batch export and return what it looks like afterwards."""batch_export = BatchExport.objects.select_related("destination").get(id=batch_export_id, team_id=team_id)diff --git a/products/batch_exports/backend/temporal/batch_exports.py b/products/batch_exports/backend/temporal/batch_exports.pyindex 4b53d5ee7ca7..2ddbba08c7e2 100644--- a/products/batch_exports/backend/temporal/batch_exports.py+++ b/products/batch_exports/backend/temporal/batch_exports.py@@ -74,14 +74,14 @@ AsyncRecordsGenerator = collections.abc.AsyncGenerator[pa.RecordBatch]KafkaPayload = dict[str, typing.Any]-def _notify_run_failure(batch_export_run_id: str | UUIDT) -> None:+def _notify_run_failure(batch_export_run_id: str | UUIDT, team_id: int) -> None:"""Fan out failure notifications across every channel for a failed run.Both channels swallow their own exceptions, so this helper itself never raises."""email_sent = Falsetry:- send_batch_export_run_failure(batch_export_run_id)+ send_batch_export_run_failure(batch_export_run_id, team_id)email_sent = Trueexcept Exception:LOGGER.exception(@@ -704,7 +704,7 @@ async def finish_batch_export_run(inputs: FinishBatchExportRunInputs) -> None:)elif batch_export_run.status == BatchExportRun.Status.FAILED:- await database_sync_to_async(_notify_run_failure)(inputs.id)+ await database_sync_to_async(_notify_run_failure)(inputs.id, inputs.team_id)external_logger.error("Batch export for range %s - %s failed with a non-recoverable error: %s",diff --git a/products/batch_exports/backend/tests/conftest.py b/products/batch_exports/backend/tests/conftest.pyindex 2d001ea3a4c0..5dc9ef7e3fdd 100644--- a/products/batch_exports/backend/tests/conftest.py+++ b/products/batch_exports/backend/tests/conftest.py@@ -26,7 +26,7 @@ async def ateam(aorganization):yield team# Skip Temporal schedule cleanup — team.delete() CASCADE-deletes BatchExport# rows from the DB, and Temporal schedules in CI don't need explicit removal.- # Calling delete_batch_exports() here can hang indefinitely because+ # Calling delete_batch_exports_for_teams() here can hang indefinitely because# sync_to_async threads blocked on gRPC cannot be cancelled by asyncio.await sync_to_async(team.delete)()diff --git a/products/batch_exports/backend/tests/temporal/conftest.py b/products/batch_exports/backend/tests/temporal/conftest.pyindex 610abf3761ea..5cab201dd380 100644--- a/products/batch_exports/backend/tests/temporal/conftest.py+++ b/products/batch_exports/backend/tests/temporal/conftest.py@@ -21,13 +21,13 @@ from posthog.models import Organization, Teamfrom posthog.models.integration import Integrationfrom posthog.models.team.extensions import get_or_create_team_extensionfrom posthog.models.team.team_revenue_analytics_config import TeamRevenueAnalyticsConfig-from posthog.models.team.util import delete_batch_exportsfrom posthog.models.utils import uuid7from posthog.temporal.common.clickhouse import ClickHouseClientfrom posthog.temporal.common.client import connectfrom posthog.temporal.common.logger import configure_loggerfrom posthog.temporal.tests.utils.events import generate_test_events_in_clickhouse+from products.batch_exports.backend.facade.api import delete_batch_exports_for_teamsfrom products.batch_exports.backend.temporal import ACTIVITIES, WORKFLOWSfrom products.batch_exports.backend.temporal.metrics import BatchExportsMetricsInterceptorfrom products.batch_exports.backend.tests.temporal.utils.clickhouse import (@@ -105,7 +105,7 @@ def team(organization):team.save()yield team- delete_batch_exports(team_ids=[team.pk])+ delete_batch_exports_for_teams([team.pk])team.delete()@@ -135,7 +135,7 @@ async def ateam(aorganization):team = await sync_to_async(_create_async_fixture_team)(aorganization)yield team- await sync_to_async(delete_batch_exports)(team_ids=[team.pk])+ await sync_to_async(delete_batch_exports_for_teams)([team.pk])await sync_to_async(team.delete)()@@ -144,7 +144,7 @@ async def another_ateam(aorganization):team = await sync_to_async(_create_async_fixture_team)(aorganization)yield team- await sync_to_async(delete_batch_exports)(team_ids=[team.pk])+ await sync_to_async(delete_batch_exports_for_teams)([team.pk])await sync_to_async(team.delete)()diff --git a/posthog/test/activity_logging/test_batch_export_activity_logging.py b/products/batch_exports/backend/tests/test_batch_export_activity_logging.pysimilarity index 95%rename from posthog/test/activity_logging/test_batch_export_activity_logging.pyrename to products/batch_exports/backend/tests/test_batch_export_activity_logging.pyindex 7a841af546f7..167aed1ae6fa 100644--- a/posthog/test/activity_logging/test_batch_export_activity_logging.py+++ b/products/batch_exports/backend/tests/test_batch_export_activity_logging.py@@ -5,13 +5,11 @@ from products.batch_exports.backend.models.batch_export import BatchExport, Batcclass TestBatchExportActivityLogging(ActivityLogTestHelper):def create_test_destination(self):- """Helper to create a test destination for batch exports."""return BatchExportDestination.objects.create(type=BatchExportDestination.Destination.HTTP, config={"url": "https://example.com"})def test_batch_export_model_has_activity_mixin(self):- """Test that BatchExport has ModelActivityMixin and proper scope"""# Verify that BatchExport inherits from ModelActivityMixinfrom posthog.models.activity_logging.model_activity import ModelActivityMixin@@ -28,7 +26,6 @@ class TestBatchExportActivityLogging(ActivityLogTestHelper):self.assertEqual(batch_export.name, "Test Export")def test_batch_export_field_exclusions_configured(self):- """Test that field exclusions are properly configured"""from posthog.models.activity_logging.activity_log import field_exclusionsbatch_export_exclusions = field_exclusions.get("BatchExport", [])@@ -40,7 +37,6 @@ class TestBatchExportActivityLogging(ActivityLogTestHelper):self.assertIn("batchexportbackfill_set", batch_export_exclusions)def test_batch_export_scope_in_activity_log_types(self):- """Test that BatchExport scope is defined in ActivityScope"""from typing import get_argsfrom posthog.models.activity_logging.activity_log import ActivityScope@@ -50,7 +46,6 @@ class TestBatchExportActivityLogging(ActivityLogTestHelper):self.assertIn("BatchExport", get_args(ActivityScope))def test_batch_export_integration_test(self):- """Integration test to verify the basic setup works"""from posthog.models.activity_logging.utils import activity_storageactivity_storage.set_user(self.user)diff --git a/products/batch_exports/backend/tests/test_facade.py b/products/batch_exports/backend/tests/test_facade.pyindex adcc37dd86bc..4c3ef6d2683a 100644--- a/products/batch_exports/backend/tests/test_facade.py+++ b/products/batch_exports/backend/tests/test_facade.py@@ -12,7 +12,13 @@ from posthog.api.test.test_team import create_teamfrom posthog.temporal.common.client import sync_connectfrom products.batch_exports.backend.facade import api, contracts, testing-from products.batch_exports.backend.models.batch_export import BatchExport, BatchExportDestination, BatchExportRun+from products.batch_exports.backend.models.batch_export import (+ BatchExport,+ BatchExportBackfill,+ BatchExportDestination,+ BatchExportOnDemand,+ BatchExportRun,+)from products.batch_exports.backend.service import BatchExportServiceScheduleNotFoundpytestmark = [pytest.mark.django_db]@@ -65,7 +71,22 @@ def _create_run(*, finished_at, records=0, status=BatchExportRun.Status.COMPLETEreturn run_id-def test_billable_rows_exported_sums_scheduled_and_on_demand_runs_per_team(team):+ "contract_enum,model_choices",+ [+ (contracts.DestinationType, BatchExportDestination.Destination),+ (contracts.BatchExportModel, BatchExport.Model),+ (contracts.BatchExportModel, BatchExportOnDemand.Model),+ (contracts.BatchExportRunStatus, BatchExportRun.Status),+ (contracts.BatchExportBackfillStatus, BatchExportBackfill.Status),+ ],+ ids=["destination type", "model", "on-demand model", "run status", "backfill status"],+)+def test_contract_enums_match_the_model_choices(contract_enum, model_choices):+ assert {member.value for member in contract_enum} == set(model_choices.values)+++def test_billable_rows_exported_sums_scheduled_and_on_demand_runs_per_team(team, organization):scheduled = _create_export(team, name="scheduled")on_demand = testing.create_batch_export_on_demand(team.pk, destination_type=FILE_DOWNLOAD, destination_config={})@@ -75,9 +96,14 @@ def test_billable_rows_exported_sums_scheduled_and_on_demand_runs_per_team(team)_create_run(batch_export_id=scheduled, finished_at=WINDOW_END + dt.timedelta(hours=1), records=100)_create_run(batch_export_id=scheduled, finished_at=IN_WINDOW, records=100, status=BatchExportRun.Status.FAILED)- assert api.get_teams_with_billable_rows_exported(WINDOW_BEGIN, WINDOW_END) == [- contracts.TeamTotal(team_id=team.pk, total=22)- ]+ uncounted_team = create_team(organization=organization)+ uncounted = _create_export(uncounted_team, name="uncounted")+ _create_run(batch_export_id=uncounted, finished_at=IN_WINDOW, records=None)++ assert set(api.get_teams_with_billable_rows_exported(WINDOW_BEGIN, WINDOW_END)) == {+ contracts.TeamTotal(team_id=team.pk, total=22),+ contracts.TeamTotal(team_id=uncounted_team.pk, total=0),+ }@pytest.mark.parametrize(@@ -235,6 +261,28 @@ def test_latest_run_is_by_creation_and_latest_completed_run_is_by_finish(team):assert latest_completed is not None and latest_completed.id == finished_last+def test_backfills_for_export_lists_every_backfill_newest_first_within_the_team(team, organization):+ export_id = _create_export(team)+ backfill_ids = []+ for offset in (2, 0, 1):+ backfill_id = testing.create_backfill(+ export_id,+ team_id=team.pk,+ status=BatchExportBackfill.Status.COMPLETED,+ start_at=IN_WINDOW - dt.timedelta(days=offset),+ )+ BatchExportBackfill.objects.filter(id=backfill_id).update(created_at=IN_WINDOW + dt.timedelta(hours=offset))+ backfill_ids.append(backfill_id)+ other_team = create_team(organization=organization)++ assert [backfill.id for backfill in api.list_backfills_for_export(export_id, team.pk)] == [+ backfill_ids[0],+ backfill_ids[2],+ backfill_ids[1],+ ]+ assert api.list_backfills_for_export(export_id, other_team.pk) == []++def test_deleting_team_batch_exports_continues_past_a_missing_schedule(team):first = _create_export(team, name="first")second = _create_export(team, name="second")diff --git a/tach.toml b/tach.tomlindex e89fc3cedbf7..a846a3a438ef 100644--- a/tach.toml+++ b/tach.toml@@ -1287,25 +1287,20 @@ from = ["products.batch_exports",]-# Legacy leaks — core (posthog/ee), cdp and warehouse_sources still import these batch_exports+# Legacy leaks — core (posthog), cdp and warehouse_sources still import these batch_exports# internals directly. Each entry names its crossing and the facade that replaces it. The block# drains as those callers move, and keeps backend:contract-check off until it is empty.# tach interfaces have no consumer scoping, so this block opens the listed paths to every module,# not only to the consumers named below.[[interfaces]]expose = [- # Integration teardown, the organization admin's model counts, the migrate_team command, the- # run-failure email, the usage report and team deletion read the models, as do core's API,- # activity-log, email, usage-report and HogQL system-table tests.- # Exit: facade.api and facade.testing.+ # The shared Temporal test utilities read the models.+ # Exit: move the utilities into the product."backend\\.models.*",- # The migrate_team command, team deletion, the shared Temporal test utilities, the payload- # codec test and the warehouse_sources S3 writer reach the service layer.- # Exit: facade.api, facade.testing and contracts.AWSCredentials.+ # The shared Temporal test utilities, the payload codec test and the warehouse_sources S3+ # writer reach the service layer.+ # Exit: facade.testing and contracts.AWSCredentials."backend\\.service.*",- # The usage report drops non-billable runs itself.- # Exit: facade.api.get_teams_with_billable_rows_exported.- "backend\\.billing.*",# The worker bootstrap commands, the worker's metrics interceptor, the shared Temporal test# conftest and the team-deletion test register the workflows and activities.# Exit: facade.temporal.