: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): add the facade base and turn on the tach boundary (#102172)
Ross11ebf74d7c50
diff --git a/products/batch_exports/backend/facade/api.py b/products/batch_exports/backend/facade/api.pynew file mode 100644index 000000000000..e48e4ac6d781--- /dev/null+++ b/products/batch_exports/backend/facade/api.py@@ -0,0 +1,369 @@+"""+Facade for batch_exports.++Capability-oriented functions that take and return the framework-free contracts in+``facade/contracts.py``. The facade never hands an ORM instance across the boundary, and+every read is scoped by ``team_id``. Mappers are explicit, so the shape a consumer sees+is visible in one place.++``service.py`` imports ``temporalio`` at module scope, and the startup import budget+(``posthog/test/repo_invariants/test_startup_import_budget.py``) forbids both that module+and ``temporalio`` on the ``django.setup()`` path. Core config-time consumers import this+facade, so it reaches the service only through ``_service()``, which imports it at call+time. For the same reason the Temporal client is built in ``_get_temporal_client()``.++Temporal workflow and activity registration crosses as objects, not data, so it lives in+``facade/temporal.py``; the pipeline internals the warehouse writers reuse live in+``facade/pipeline.py``. Neither may be imported from here.+"""++import datetime as dt+from collections.abc import Mapping, Sequence+from types import ModuleType+from typing import TYPE_CHECKING+from uuid import UUID++from django.db import transaction+from django.db.models import Count, F, Q, Sum+from django.db.models.functions import Coalesce++import structlog++from products.batch_exports.backend.billing import exclude_non_billable_runs+from products.batch_exports.backend.models.batch_export import (+ BATCH_EXPORT_INTERVALS,+ BatchExport,+ BatchExportBackfill,+ BatchExportDestination,+ BatchExportRun,+ get_batch_exports_using_integration,+)++from . import contracts++if TYPE_CHECKING:+ from temporalio.client import Client++__all__ = [+ "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_batch_exports_using_integration",+ "list_latest_failed_runs",+ "list_supported_intervals",+]++logger = structlog.get_logger(__name__)++# The statuses that make the latest run of an export an actionable failure.+FAILED_RUN_STATUSES = (+ BatchExportRun.Status.FAILED,+ BatchExportRun.Status.FAILED_RETRYABLE,+ BatchExportRun.Status.TIMEDOUT,+ BatchExportRun.Status.TERMINATED,+)++# 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"+++class MultipleBatchExportsError(Exception):+ """Raised when a lookup that expects at most one batch export matches several."""+++def _service() -> ModuleType:+ """Import the service layer at call time. See the module docstring for why."""+ from products.batch_exports.backend import service++ return service+++def _get_temporal_client() -> "Client":+ """Connect to Temporal at call time. See the module docstring for why."""+ from posthog.temporal.common.client import sync_connect++ return sync_connect()+++def _to_ref(batch_export: BatchExport) -> contracts.BatchExportRef:+ return contracts.BatchExportRef(id=batch_export.id, name=batch_export.name)+++def _to_detail(batch_export: BatchExport) -> contracts.BatchExportDetail:+ # The destination config is an encrypted field, so reading it decrypts the destination's+ # credentials. Only the two event filters are lifted out of it, which is all any consumer reads.+ # Do not widen this to the whole config unless we are certain all credentials have been migrated+ # to integrations and dropped from the config.+ config = batch_export.destination.config+ return contracts.BatchExportDetail(+ id=batch_export.id,+ team_id=batch_export.team_id,+ name=batch_export.name,+ interval=batch_export.interval,+ paused=batch_export.paused,+ created_at=batch_export.created_at,+ last_updated_at=batch_export.last_updated_at,+ destination_type=batch_export.destination.type,+ # A stored filter can be null, not only absent, so the fallback covers both.+ exclude_events=tuple(config.get("exclude_events") or ()),+ include_events=tuple(config.get("include_events") or ()),+ )+++def _to_backfill_summary(backfill: BatchExportBackfill) -> contracts.BatchExportBackfillSummary:+ return contracts.BatchExportBackfillSummary(+ id=backfill.id,+ status=backfill.status,+ start_at=backfill.start_at,+ adjusted_start_at=backfill.adjusted_start_at,+ created_at=backfill.created_at,+ last_updated_at=backfill.last_updated_at,+ )+++def _to_run_summary(run: BatchExportRun) -> contracts.BatchExportRunSummary:+ return contracts.BatchExportRunSummary(+ id=run.id,+ status=run.status,+ latest_error=run.latest_error,+ data_interval_start=run.data_interval_start,+ data_interval_end=run.data_interval_end,+ finished_at=run.finished_at,+ created_at=run.created_at,+ last_updated_at=run.last_updated_at,+ )+++def list_batch_exports_using_integration(team_id: int, integration_id: int) -> list[contracts.BatchExportRef]:+ """Return the live batch exports that write through this integration."""+ return [_to_ref(batch_export) for batch_export in get_batch_exports_using_integration(team_id, integration_id)]+++def count_batch_exports_for_teams(team_ids: Sequence[int]) -> int:+ """Count the batch exports these teams have, not counting deleted ones."""+ return BatchExport.objects.filter(team_id__in=team_ids, deleted=False).count()+++def list_latest_failed_runs(team_id: int) -> list[contracts.FailedBatchExportRun]:+ """Return the exports whose most recent run failed.++ Only the latest run of each export counts, so an export that has recovered does not+ appear. A paused export is left out too: its last failure is no longer actionable.+ """+ latest_run_ids = (+ BatchExportRun.objects.filter(+ batch_export__team_id=team_id,+ batch_export__deleted=False,+ batch_export__paused=False,+ )+ .order_by("batch_export_id", "-created_at")+ .distinct("batch_export_id")+ .values_list("id", flat=True)+ )++ # nosemgrep: idor-lookup-without-team (IDs from team-scoped queryset)+ failed_runs = BatchExportRun.objects.filter(id__in=latest_run_ids, status__in=FAILED_RUN_STATUSES).select_related(+ "batch_export"+ )++ return [+ contracts.FailedBatchExportRun(+ export_id=run.parent.id,+ export_name=getattr(run.parent, "name", ON_DEMAND_EXPORT_NAME),+ error=run.latest_error,+ failed_at=run.finished_at,+ )+ for run in failed_runs+ ]+++def get_run_failure(run_id: UUID | str, team_id: int) -> contracts.BatchExportRunFailure | None:+ """Return a failed run with the export and team that own it, or None for an on-demand run.++ An on-demand export has no page of its own, so there is nothing to point a person at.+ The team is matched against either parent, so an on-demand run still resolves and+ returns None rather than raising.+ """+ run = BatchExportRun.objects.select_related("batch_export", "batch_export_on_demand").get(+ Q(batch_export__team_id=team_id) | Q(batch_export_on_demand__team_id=team_id),+ id=run_id,+ )+ export = run.parent++ if not isinstance(export, BatchExport):+ return None++ return contracts.BatchExportRunFailure(+ run_id=run.id,+ team_id=export.team_id,+ export_id=export.id,+ export_name=export.name,+ last_updated_at=run.last_updated_at,+ )+++def get_teams_with_billable_rows_exported(begin: dt.datetime, end: dt.datetime) -> list[contracts.TeamTotal]:+ """Sum the rows each team exported through billable runs that finished in the period."""+ completed_runs = BatchExportRun.objects.filter(+ finished_at__gte=begin,+ finished_at__lte=end,+ status=BatchExportRun.Status.COMPLETED,+ )+ rows = (+ exclude_non_billable_runs(completed_runs)+ .values(team_id=Coalesce(F("batch_export__team_id"), F("batch_export_on_demand__team_id")))+ # A run that recorded no count leaves records_completed null, so a team whose runs are+ # all null would sum to null. Coalesce keeps every total an integer.+ .annotate(total=Coalesce(Sum("records_completed"), 0))+ )+ return [contracts.TeamTotal(team_id=row["team_id"], total=row["total"]) for row in rows]+++def get_teams_with_active_batch_exports() -> list[contracts.TeamTotal]:+ """Count the batch exports each team currently runs on a schedule.++ Deleted exports are excluded, which the usage report query this replaces does not do.+ Deletion never leaves an export paused - `service.delete_batch_export` saves a stale+ instance over the paused flag - so that query counts every export a team has ever+ deleted, and the number only ever grows. It drops once the usage report moves here.+ """+ rows = BatchExport.objects.filter(paused=False, deleted=False).values("team_id").annotate(total=Count("id"))+ return [contracts.TeamTotal(team_id=row["team_id"], total=row["total"]) for row in rows]+++def delete_batch_exports_for_teams(team_ids: Sequence[int]) -> None:+ """Delete the batch exports of deleted teams, and the Temporal schedules behind them.++ A CASCADE delete of the team would leave the schedules running, so each export is+ deleted with its destination and its schedule together.+ """+ service = _service()+ temporal = _get_temporal_client()++ 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:+ service.batch_export_delete_schedule(temporal, str(schedule_id))+ except service.BatchExportServiceScheduleNotFound as e:+ logger.warning("Schedule not found during team deletion", schedule_id=e.schedule_id)+++def get_batch_export_by_name(team_id: int, name: str, destination_type: str) -> contracts.BatchExportDetail | None:+ """Return the one live export with this name and destination, or None."""+ try:+ batch_export = BatchExport.objects.select_related("destination").get(+ team_id=team_id, name=name, destination__type=destination_type, deleted=False+ )+ except BatchExport.DoesNotExist:+ return None+ except BatchExport.MultipleObjectsReturned as e:+ raise MultipleBatchExportsError(+ f"Team {team_id} has more than one batch export named {name!r} to {destination_type!r}"+ ) from e++ 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 get_latest_run(export_id: UUID, team_id: int) -> contracts.BatchExportRunSummary | None:+ """Return the most recently created run of an export, or None if it has never run."""+ run = (+ BatchExportRun.objects.filter(batch_export_id=export_id, batch_export__team_id=team_id)+ .order_by("-created_at")+ .first()+ )+ return _to_run_summary(run) if run is not None else None+++def get_latest_completed_run(export_id: UUID, team_id: int) -> contracts.BatchExportRunSummary | None:+ """Return the run that finished most recently, of those that completed."""+ run = (+ BatchExportRun.objects.filter(+ batch_export_id=export_id,+ batch_export__team_id=team_id,+ status=BatchExportRun.Status.COMPLETED,+ )+ .order_by("-finished_at")+ .first()+ )+ return _to_run_summary(run) if run is not None else None+++def create_batch_export(+ team_id: int,+ *,+ name: str,+ destination_type: str,+ destination_config: Mapping[str, object],+ interval: str,+ paused: bool = False,+ end_at: dt.datetime | None = None,+) -> contracts.BatchExportDetail:+ """Create a batch export, its destination, and the Temporal schedule that drives it."""+ service = _service()++ destination = BatchExportDestination(type=destination_type, config=dict(destination_config))+ batch_export = BatchExport(+ team_id=team_id,+ destination=destination,+ name=name,+ interval=interval,+ paused=paused,+ end_at=end_at,+ )++ # Schedule first, then the rows, which is the order every caller uses today. It trades one+ # failure for the other: a failed save leaves an orphaned schedule, where the reverse order+ # would leave a row pointing at no schedule. Neither is compensated yet.+ service.sync_batch_export(batch_export, created=True)++ with transaction.atomic():+ destination.save()+ batch_export.save()++ return _to_detail(batch_export)+++def delete_batch_export(export_id: UUID, team_id: int) -> None:+ """Delete a batch export: pause it, cancel its work, then drop its Temporal schedule."""+ service = _service()+ batch_export = BatchExport.objects.select_related("destination").get(id=export_id, team_id=team_id)+ service.delete_batch_export(batch_export)+++def backfill_batch_export(+ export_id: UUID, team_id: int, start_at: dt.datetime | None, end_at: dt.datetime | None+) -> str:+ """Start a backfill of an export over a date range, and return the backfill id.++ With no ``end_at`` the backfill runs until it catches up with realtime, then unpauses+ the export.+ """+ service = _service()+ return service.backfill_export(_get_temporal_client(), str(export_id), team_id, start_at, end_at)+++def list_supported_intervals() -> tuple[str, ...]:+ """Return the intervals a batch export may be scheduled on."""+ return tuple(interval for interval, _ in BATCH_EXPORT_INTERVALS)diff --git a/products/batch_exports/backend/facade/contracts.py b/products/batch_exports/backend/facade/contracts.pynew file mode 100644index 000000000000..1a52754afb69--- /dev/null+++ b/products/batch_exports/backend/facade/contracts.py@@ -0,0 +1,137 @@+"""+Contract types for batch_exports.++Stable, framework-free dataclasses defining what this product hands to the rest of the+codebase. 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.++The fields are the ones consumers read today and nothing more. An encrypted model field+never crosses whole, because reading one decrypts it; ``BatchExportDetail`` documents the+case that matters here.++Most contracts use ``pydantic.dataclasses.dataclass`` — same syntax and+``is_dataclass()`` compatibility as the stdlib variant, with runtime validation on+construction, so a mapper mistake surfaces at the boundary instead of as a malformed+payload later. ``AWSCredentials`` is the exception and is documented at its definition.+"""++import datetime as dt+from dataclasses import (+ dataclass as stdlib_dataclass,+ field,+)+from uuid import UUID++from pydantic.dataclasses import dataclass++# The Django model label of BatchExport, for consumers that report on models by name.+BATCH_EXPORT_MODEL_LABEL = "batch_exports.BatchExport"+++@dataclass(frozen=True)+class BatchExportRef:+ """The bare identity of a batch export, for listing it by name."""++ id: UUID+ name: str+++@dataclass(frozen=True)+class BatchExportDetail:+ """A scheduled batch export and the destination it writes to.++ The destination's stored config is deliberately absent. It decrypts on read, so it+ holds that destination's credentials: passwords, private keys, tokens. Only the two+ event filters a consumer reads are lifted out of it.+ """++ id: UUID+ team_id: int+ name: str+ interval: str+ paused: bool+ created_at: dt.datetime+ last_updated_at: dt.datetime+ destination_type: str+ exclude_events: tuple[str, ...]+ include_events: tuple[str, ...]+++@dataclass(frozen=True)+class BatchExportBackfillSummary:+ """One backfill of a batch export."""++ id: UUID+ status: str+ start_at: dt.datetime | None+ adjusted_start_at: dt.datetime | None+ created_at: dt.datetime+ last_updated_at: dt.datetime+++@dataclass(frozen=True)+class BatchExportRunSummary:+ """One run of a batch export, over one data interval."""++ id: UUID+ status: str+ latest_error: str | None+ data_interval_start: dt.datetime | None+ data_interval_end: dt.datetime+ finished_at: dt.datetime | None+ created_at: dt.datetime+ last_updated_at: dt.datetime+++@dataclass(frozen=True)+class BatchExportRunFailure:+ """A failed run, with the export and team a failure notification needs."""++ run_id: UUID+ team_id: int+ export_id: UUID+ export_name: str+ last_updated_at: dt.datetime+++@dataclass(frozen=True)+class FailedBatchExportRun:+ """The latest run of an export, when that run failed."""++ export_id: UUID+ export_name: str+ error: str | None+ failed_at: dt.datetime | None+++@dataclass(frozen=True)+class TeamTotal:+ """One row of a per-team aggregate."""++ team_id: int+ total: int+++@stdlib_dataclass(frozen=True)+class AWSCredentials:+ """An AWS key pair, optionally temporary.++ A stdlib dataclass rather than a pydantic one: this crosses the Temporal payload+ boundary on every S3 and Redshift export, and callers build it positionally, so it+ stays as plain a dataclass as the rest of the Temporal inputs in ``service.py``.+ The secret key and the session token stay out of ``repr``, so they cannot reach a+ log line. The access key id identifies the credential rather than authenticating+ it, so it stays visible for debugging.+ """++ aws_access_key_id: str+ aws_secret_access_key: str = field(repr=False)+ aws_session_token: str | None = field(default=None, repr=False)+ expiration: dt.datetime | None = field(default=None)++ @property+ def expiry_time(self) -> str | None:+ """ISO-8601 expiration time for temporary credentials, if available."""+ if self.expiration is None:+ return None+ return self.expiration.isoformat()diff --git a/products/batch_exports/backend/facade/models.py b/products/batch_exports/backend/facade/models.pyindex 1cd70b24d2d0..90d5bf5fbf14 100644--- a/products/batch_exports/backend/facade/models.py+++ b/products/batch_exports/backend/facade/models.py@@ -2,6 +2,11 @@Model-class wiring for batch_exports.Re-exports the BatchExportRun model cross-product consumers read. Light (Django model).++batch_exports is not on the watched-models allowance (``MODEL_CROSSINGS``), so this+re-export is an unsanctioned crossing, not a sanctioned one. Its one consumer is the+failed-runs block of the data_warehouse overview, which ``facade.api.list_latest_failed_runs``+replaces. This module goes when that consumer moves."""from products.batch_exports.backend.models.batch_export import BatchExportRundiff --git a/products/batch_exports/backend/facade/pipeline.py b/products/batch_exports/backend/facade/pipeline.pynew file mode 100644index 000000000000..b611ae4e9f55--- /dev/null+++ b/products/batch_exports/backend/facade/pipeline.py@@ -0,0 +1,100 @@+"""+Export-pipeline wiring for batch_exports.++Re-exports the destination clients, stream transformers and credential helpers that the+warehouse_sources Temporal writers reuse, so a data-import writer and a batch export talk+to Snowflake, BigQuery, Databricks, Postgres, Redshift, S3 and Azure Blob the same way.++Every name here comes from ``backend/temporal/``, so importing this module pulls each+destination's vendor SDK. Only Temporal activity code may import it. Never import it from+``facade/api.py``, or from anything else on the ``django.setup()`` path — see+``posthog/test/repo_invariants/test_startup_import_budget.py``.+"""++from products.batch_exports.backend.temporal.destinations.azure_blob_batch_export import (+ MalformedConnectionStringError,+ _get_azure_blob_integration as get_azure_blob_integration,+ _is_authorization_failure_response_error as is_authorization_failure_response_error,+)+from products.batch_exports.backend.temporal.destinations.bigquery_batch_export import (+ BigQueryClient,+ verify_impersonated_service_account_ownership,+)+from products.batch_exports.backend.temporal.destinations.constants import (+ AZURE_BLOB_SUPPORTED_COMPRESSIONS,+ S3_SUPPORTED_COMPRESSIONS,+)+from products.batch_exports.backend.temporal.destinations.databricks_batch_export import (+ FIVE_MINUTES,+ ONE_HOUR,+ ONE_MINUTE,+ DatabricksClient,+ DatabricksField,+ DatabricksIntegrationNotFoundError,+ handle_common_errors,+)+from products.batch_exports.backend.temporal.destinations.postgres_batch_export import (+ Fields,+ PostgreSQLClient,+ PostgreSQLIntegrationNotFoundError,+ run_in_retryable_transaction,+)+from products.batch_exports.backend.temporal.destinations.redshift_batch_export import RedshiftClient+from products.batch_exports.backend.temporal.destinations.s3_batch_export import (+ ConcurrentS3Consumer,+ IntermittentUploadPartTimeoutError,+ PolicyStatement,+ _get_s3_integration as get_s3_integration,+ get_credentials_using_user_aws_role,+ s3_client,+)+from products.batch_exports.backend.temporal.destinations.snowflake_batch_export import (+ NamedBytesIO,+ SnowflakeClient,+ SnowflakeField,+ SnowflakeTable,+ SnowflakeType,+ _get_snowflake_integration as get_snowflake_integration,+ load_private_key,+)+from products.batch_exports.backend.temporal.pipeline.transformer import CSVStreamTransformer, ParquetStreamTransformer++from .contracts import AWSCredentials++__all__ = [+ "AWSCredentials",+ "AZURE_BLOB_SUPPORTED_COMPRESSIONS",+ "BigQueryClient",+ "CSVStreamTransformer",+ "ConcurrentS3Consumer",+ "DatabricksClient",+ "DatabricksField",+ "DatabricksIntegrationNotFoundError",+ "FIVE_MINUTES",+ "Fields",+ "IntermittentUploadPartTimeoutError",+ "MalformedConnectionStringError",+ "NamedBytesIO",+ "ONE_HOUR",+ "ONE_MINUTE",+ "ParquetStreamTransformer",+ "PolicyStatement",+ "PostgreSQLClient",+ "PostgreSQLIntegrationNotFoundError",+ "RedshiftClient",+ "S3_SUPPORTED_COMPRESSIONS",+ "SnowflakeClient",+ "SnowflakeField",+ "SnowflakeTable",+ "SnowflakeType",+ "get_azure_blob_integration",+ "get_credentials_using_user_aws_role",+ "get_s3_integration",+ "get_snowflake_integration",+ "handle_common_errors",+ "is_authorization_failure_response_error",+ "load_private_key",+ "run_in_retryable_transaction",+ "s3_client",+ "verify_impersonated_service_account_ownership",+]diff --git a/products/batch_exports/backend/facade/temporal.py b/products/batch_exports/backend/facade/temporal.pynew file mode 100644index 000000000000..6250a28343a8--- /dev/null+++ b/products/batch_exports/backend/facade/temporal.py@@ -0,0 +1,52 @@+"""+Temporal registration wiring for batch_exports.++Re-exports what core registers with Temporal: the worker bootstrap commands+(``start_temporal_worker``, ``start_temporal_workflow``, ``execute_temporal_workflow``)+take ``WORKFLOWS`` and ``ACTIVITIES``, ``posthog/temporal/common/worker.py`` takes the+metrics interceptor, and the shared Temporal test conftest and payload-codec test take+the no-op workflow and its activity.++Names resolve lazily (PEP 562), mirroring ``backend/temporal/__init__.py``. Eager imports+here would put every destination's vendor SDK (databricks, snowflake, bigquery, ...) on+the import path of anything that touches this facade, which the startup import budget+forbids — see ``posthog/test/repo_invariants/test_startup_import_budget.py``.+"""++from typing import TYPE_CHECKING, Any++if TYPE_CHECKING:+ from products.batch_exports.backend.temporal.metrics import BatchExportsMetricsInterceptor+ from products.batch_exports.backend.temporal.noop import NoOpWorkflow, noop_activity+ from products.batch_exports.backend.temporal.workflows import ACTIVITIES, WORKFLOWS++_B = "products.batch_exports.backend.temporal."++_LAZY = {+ "ACTIVITIES": "workflows",+ "WORKFLOWS": "workflows",+ "BatchExportsMetricsInterceptor": "metrics",+ "NoOpWorkflow": "noop",+ "noop_activity": "noop",+}++__all__ = [+ "ACTIVITIES",+ "WORKFLOWS",+ "BatchExportsMetricsInterceptor",+ "NoOpWorkflow",+ "noop_activity",+]+++def __getattr__(name: str) -> Any:+ module = _LAZY.get(name)+ if module is None:+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")+ import importlib++ return getattr(importlib.import_module(_B + module), name)+++def __dir__() -> list[str]:+ return sorted(set(globals()) | set(__all__))diff --git a/products/batch_exports/backend/facade/testing.py b/products/batch_exports/backend/facade/testing.pynew file mode 100644index 000000000000..ecb53fb001be--- /dev/null+++ b/products/batch_exports/backend/facade/testing.py@@ -0,0 +1,203 @@+"""+Test-support facade for batch_exports.++Test suites outside this product (core's email digest, the usage report, the integration+and team-deletion API tests, the activity-log helper, the HogQL system-table isolation+tests, the shared Temporal test utilities) create batch exports and their runs. They get+them here instead of importing the models.++Ids go in and ids come out, so a caller never holds an ORM instance. Reads return the+same contracts ``facade/api.py`` returns.++``service.py`` and ``temporalio`` are imported at call time, for the reason+``facade/api.py`` documents: this module must stay off the ``django.setup()`` path.+"""++import datetime as dt+from collections.abc import Mapping+from typing import TYPE_CHECKING, Any+from uuid import UUID++from products.batch_exports.backend.models.batch_export import (+ BatchExport,+ BatchExportBackfill,+ BatchExportDestination,+ BatchExportOnDemand,+ BatchExportRun,+)++from . import contracts+from .api import _to_backfill_summary, _to_detail, _to_run_summary++if TYPE_CHECKING:+ from temporalio.client import Client++ from products.batch_exports.backend.service import NoOpInputs+++def create_batch_export(+ team_id: int,+ *,+ name: str,+ destination_type: str,+ destination_config: Mapping[str, object],+ interval: str = "hour",+ paused: bool = False,+ model: str | None = None,+ timezone: str | None = None,+ interval_offset: int | None = None,+ sync_schedule: bool = False,+) -> UUID:+ """Create a scheduled batch export and return its id.++ ``sync_schedule`` also creates the Temporal schedule, which a test only needs when it+ exercises the schedule itself. It costs a Temporal connection, so it is off by default.+ """+ destination = BatchExportDestination(type=destination_type, config=dict(destination_config))+ batch_export = BatchExport(+ team_id=team_id,+ destination=destination,+ name=name,+ interval=interval,+ paused=paused,+ model=model if model is not None else BatchExport.Model.EVENTS,+ timezone=timezone or "UTC",+ interval_offset=interval_offset,+ )++ if sync_schedule:+ from products.batch_exports.backend.service import sync_batch_export++ sync_batch_export(batch_export, created=True)++ destination.save()+ batch_export.save()++ return batch_export.id+++def create_batch_export_on_demand(+ team_id: int,+ *,+ destination_type: str,+ destination_config: Mapping[str, object],+ model: str | None = None,+) -> UUID:+ """Create an on-demand batch export and return its id."""+ destination = BatchExportDestination.objects.create(type=destination_type, config=dict(destination_config))+ return (+ BatchExportOnDemand.objects.for_team(team_id)+ .create(+ team_id=team_id,+ destination=destination,+ model=model if model is not None else BatchExportOnDemand.Model.EVENTS,+ )+ .id+ )+++def create_batch_export_run(+ *,+ status: str,+ data_interval_end: dt.datetime,+ data_interval_start: dt.datetime | None = None,+ batch_export_id: UUID | None = None,+ on_demand_id: UUID | None = None,+ records_completed: int | None = None,+ finished_at: dt.datetime | None = None,+) -> UUID:+ """Create a run of a scheduled or an on-demand export, and return its id.++ A run belongs to exactly one of the two, which a check constraint enforces.+ """+ if (batch_export_id is None) == (on_demand_id is None):+ raise ValueError("Pass exactly one of batch_export_id or on_demand_id")++ return BatchExportRun.objects.create(+ batch_export_id=batch_export_id,+ batch_export_on_demand_id=on_demand_id,+ status=status,+ data_interval_start=data_interval_start,+ data_interval_end=data_interval_end,+ records_completed=records_completed,+ finished_at=finished_at,+ ).id+++def create_backfill(+ batch_export_id: UUID,+ *,+ team_id: int,+ status: str,+ start_at: dt.datetime | None = None,+ end_at: dt.datetime | None = None,+) -> UUID:+ """Create a backfill of a scheduled export and return its id."""+ return BatchExportBackfill.objects.create(+ batch_export_id=batch_export_id,+ team_id=team_id,+ status=status,+ start_at=start_at,+ end_at=end_at,+ ).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)+ for name, value in fields.items():+ setattr(batch_export, name, value)+ batch_export.save()+ return _to_detail(batch_export)+++def delete_batch_export(batch_export_id: UUID, *, team_id: int, temporal_client: "Client | None" = None) -> None:+ """Remove a batch export row outright, and its Temporal schedule when a client is given.++ This is the teardown counterpart of ``create_batch_export``, not the product's delete+ capability: it drops the row rather than marking it deleted. A schedule that is already+ gone is not an error here.+ """+ if temporal_client is not None:+ import temporalio.service+ from asgiref.sync import async_to_sync++ handle = temporal_client.get_schedule_handle(str(batch_export_id))+ try:+ async_to_sync(handle.delete)()+ except temporalio.service.RPCError as e:+ # Anything else - an auth failure, an unreachable server - must still surface,+ # or a broken Temporal connection reads as a clean teardown.+ if e.status != temporalio.service.RPCStatusCode.NOT_FOUND:+ raise++ BatchExport.objects.filter(id=batch_export_id, team_id=team_id).delete()+++def list_runs(batch_export_id: UUID, *, team_id: int, limit: int = 100) -> list[contracts.BatchExportRunSummary]:+ """Return an export's runs, most recently created first."""+ runs = BatchExportRun.objects.filter(batch_export_id=batch_export_id, batch_export__team_id=team_id).order_by(+ "-created_at"+ )[:limit]+ return [_to_run_summary(run) for run in runs]+++def list_backfills(+ batch_export_id: UUID, *, team_id: int, limit: int = 100+) -> list[contracts.BatchExportBackfillSummary]:+ """Return an export's backfills, most recently created first."""+ backfills = BatchExportBackfill.objects.filter(batch_export_id=batch_export_id, team_id=team_id).order_by(+ "-created_at"+ )[:limit]+ return [_to_backfill_summary(backfill) for backfill in backfills]+++def build_noop_inputs(*, arg: str, team_id: int, batch_export_id: str) -> "NoOpInputs":+ """Build the inputs of the no-op workflow, which core uses to exercise the payload codec.++ A builder rather than a re-export of the class: ``NoOpInputs`` lives in ``service.py``,+ which is not a wiring location, so handing the class out would be a facade leak.+ """+ from products.batch_exports.backend.service import NoOpInputs++ return NoOpInputs(arg=arg, team_id=team_id, batch_export_id=batch_export_id)diff --git a/products/batch_exports/backend/service.py b/products/batch_exports/backend/service.pyindex 0b45101c3da9..28ffb257ca01 100644--- a/products/batch_exports/backend/service.py+++ b/products/batch_exports/backend/service.py@@ -39,6 +39,7 @@ from posthog.temporal.common.schedule import (update_schedule,)+from products.batch_exports.backend.facade.contracts import AWSCredentialsfrom products.batch_exports.backend.models.batch_export import (BatchExport,BatchExportBackfill,@@ -394,21 +395,6 @@ IAMRole = strIntegrationID = int-@dataclass(frozen=False)-class AWSCredentials:- aws_access_key_id: str- aws_secret_access_key: str = field(repr=False)- aws_session_token: str | None = field(default=None, repr=False)- expiration: dt.datetime | None = field(default=None)-- @property- def expiry_time(self) -> str | None:- """ISO-8601 expiration time for temporary credentials, if available."""- if self.expiration is None:- return None- return self.expiration.isoformat()--@frozenclass RedshiftCopyInputs:s3_bucket: strdiff --git a/products/batch_exports/backend/temporal/destinations/postgres_batch_export.py b/products/batch_exports/backend/temporal/destinations/postgres_batch_export.pyindex e05907a7bca6..f2deb0b9203c 100644--- a/products/batch_exports/backend/temporal/destinations/postgres_batch_export.py+++ b/products/batch_exports/backend/temporal/destinations/postgres_batch_export.py@@ -63,6 +63,8 @@ from products.batch_exports.backend.temporal.utils import (PostgreSQLField = tuple[str, typing.LiteralString]Fields = collections.abc.Iterable[PostgreSQLField]+_TransactionResult = typing.TypeVar("_TransactionResult")+# Compiled regex patterns for PostgreSQL data cleaningNULL_UNICODE_PATTERN = re.compile(rb"(?<!\\)\\u0000")UNPAIRED_SURROGATE_PATTERN = re.compile(@@ -217,9 +219,9 @@ class PostgresInsertInputs(BatchExportInsertInputs):async def run_in_retryable_transaction(connection: psycopg.AsyncConnection,- fn: collections.abc.Callable[[], collections.abc.Awaitable[typing.Any]],+ fn: collections.abc.Callable[[], collections.abc.Awaitable[_TransactionResult]],max_attempts: int = 3,-) -> typing.Any:+) -> _TransactionResult:"""Run a callable inside a transaction with retry logic for serialization failures.Inspiration: https://github.com/cockroachdb/example-app-python-psycopg3/blob/main/example.py#L70-L105@@ -245,6 +247,9 @@ async def run_in_retryable_transaction(LOGGER.debug("Sleeping %s seconds", sleep_seconds)await asyncio.sleep(sleep_seconds)+ # Only reachable when the loop never ran, which means no attempt was allowed.+ raise ValueError(f"max_attempts must be at least 1, got {max_attempts}")+class PostgreSQLClient:"""PostgreSQL connection client used in batch exports."""diff --git a/products/batch_exports/backend/tests/test_facade.py b/products/batch_exports/backend/tests/test_facade.pynew file mode 100644index 000000000000..5c0b793c5037--- /dev/null+++ b/products/batch_exports/backend/tests/test_facade.py@@ -0,0 +1,282 @@+import datetime as dt++import pytest+from unittest import mock++import temporalio.service+from asgiref.sync import async_to_sync+from temporalio.client import Client++from posthog.api.test.test_organization import create_organization+from posthog.api.test.test_team import create_team+from posthog.temporal.common.client import sync_connect++from 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.service import BatchExportServiceScheduleNotFound++pytestmark = [pytest.mark.django_db]++# The billing window the aggregate tests query. Nothing under test reads the wall clock, so+# fixed instants stay meaningful however long this test lives.+WINDOW_BEGIN = dt.datetime(2026, 1, 1, tzinfo=dt.UTC)+WINDOW_END = WINDOW_BEGIN + dt.timedelta(days=1)+IN_WINDOW = WINDOW_BEGIN + dt.timedelta(hours=1)++S3 = BatchExportDestination.Destination.S3+HTTP = BatchExportDestination.Destination.HTTP+NOOP = BatchExportDestination.Destination.NOOP+WORKFLOWS = BatchExportDestination.Destination.WORKFLOWS+FILE_DOWNLOAD = BatchExportDestination.Destination.FILE_DOWNLOAD+++def organization():+ return create_organization("BatchExportsFacadeTestOrg")+++def team(organization):+ return create_team(organization=organization)+++def _create_export(team, *, name="export", destination_type=S3, config=None, **fields):+ return testing.create_batch_export(+ team.pk,+ name=name,+ destination_type=destination_type,+ destination_config=config or {},+ **fields,+ )+++def _create_run(*, finished_at, records=0, status=BatchExportRun.Status.COMPLETED, created_at=None, **parent):+ run_id = testing.create_batch_export_run(+ status=status,+ data_interval_start=finished_at - dt.timedelta(hours=1),+ data_interval_end=finished_at,+ records_completed=records,+ finished_at=finished_at,+ **parent,+ )+ if created_at is not None:+ # created_at is auto_now_add, so the ordering a test needs can only be set afterwards.+ BatchExportRun.objects.filter(id=run_id).update(created_at=created_at)+ return run_id+++def test_billable_rows_exported_sums_scheduled_and_on_demand_runs_per_team(team):+ scheduled = _create_export(team, name="scheduled")+ on_demand = testing.create_batch_export_on_demand(team.pk, destination_type=FILE_DOWNLOAD, destination_config={})++ _create_run(batch_export_id=scheduled, finished_at=IN_WINDOW, records=10)+ _create_run(batch_export_id=scheduled, finished_at=IN_WINDOW, records=5)+ _create_run(on_demand_id=on_demand, finished_at=IN_WINDOW, records=7)+ _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)+ ]+++ "destination_type,export_fields,deleted",+ [+ (HTTP, {}, False),+ (WORKFLOWS, {}, False),+ (S3, {"model": BatchExport.Model.HOGQL}, False),+ (S3, {}, True),+ ],+ ids=["http destination", "workflows destination", "hogql model", "deleted export"],+)+def test_billable_rows_exported_drops_non_billable_runs(team, destination_type, export_fields, deleted):+ export_id = _create_export(team, destination_type=destination_type, **export_fields)+ _create_run(batch_export_id=export_id, finished_at=IN_WINDOW, records=10)+ if deleted:+ testing.update_batch_export(export_id, team_id=team.pk, deleted=True)++ assert api.get_teams_with_billable_rows_exported(WINDOW_BEGIN, WINDOW_END) == []+++def test_active_batch_exports_excludes_paused_and_deleted_exports(team):+ _create_export(team, name="running")+ _create_export(team, name="paused", paused=True)+ # Deletion leaves paused False, so a deleted export only drops out on the deleted filter.+ deleted = _create_export(team, name="deleted")+ testing.update_batch_export(deleted, team_id=team.pk, deleted=True)++ # The query spans every team, so read this team's row rather than the whole list.+ totals = {row.team_id: row.total for row in api.get_teams_with_active_batch_exports()}+ assert totals[team.pk] == 1+++def test_latest_failed_runs_reports_only_exports_whose_most_recent_run_failed(team):+ recovered = _create_export(team, name="recovered")+ _create_run(+ batch_export_id=recovered,+ finished_at=IN_WINDOW,+ status=BatchExportRun.Status.FAILED,+ created_at=IN_WINDOW,+ )+ _create_run(batch_export_id=recovered, finished_at=IN_WINDOW, created_at=IN_WINDOW + dt.timedelta(hours=1))++ failing = _create_export(team, name="failing")+ _create_run(batch_export_id=failing, finished_at=IN_WINDOW, created_at=IN_WINDOW)+ _create_run(+ batch_export_id=failing,+ finished_at=IN_WINDOW + dt.timedelta(hours=1),+ status=BatchExportRun.Status.TIMEDOUT,+ created_at=IN_WINDOW + dt.timedelta(hours=1),+ )++ assert api.list_latest_failed_runs(team.pk) == [+ contracts.FailedBatchExportRun(+ export_id=failing,+ export_name="failing",+ error=None,+ failed_at=IN_WINDOW + dt.timedelta(hours=1),+ )+ ]++[email protected]("field", ["paused", "deleted"])+def test_latest_failed_runs_ignores_paused_and_deleted_exports(team, field):+ export_id = _create_export(team)+ _create_run(batch_export_id=export_id, finished_at=IN_WINDOW, status=BatchExportRun.Status.FAILED)+ testing.update_batch_export(export_id, team_id=team.pk, **{field: True})++ assert api.list_latest_failed_runs(team.pk) == []+++def test_run_failure_describes_a_scheduled_export(team):+ export_id = _create_export(team, name="nightly")+ run_id = _create_run(batch_export_id=export_id, finished_at=IN_WINDOW, status=BatchExportRun.Status.FAILED)++ failure = api.get_run_failure(run_id, team.pk)++ assert failure is not None+ assert (failure.run_id, failure.team_id, failure.export_id, failure.export_name) == (+ run_id,+ team.pk,+ export_id,+ "nightly",+ )+++def test_run_failure_is_none_for_an_on_demand_export(team):+ on_demand = testing.create_batch_export_on_demand(team.pk, destination_type=FILE_DOWNLOAD, destination_config={})+ run_id = _create_run(on_demand_id=on_demand, finished_at=IN_WINDOW, status=BatchExportRun.Status.FAILED)++ assert api.get_run_failure(run_id, team.pk) is None+++def test_batch_export_by_name_carries_the_event_filters_and_no_destination_secrets(team):+ export_id = _create_export(+ team,+ name="migration",+ destination_type=HTTP,+ config={+ "url": "https://example.com/batch",+ "token": "totally-made-up-token",+ "exclude_events": ["$pageview"],+ },+ )++ detail = api.get_batch_export_by_name(team.pk, "migration", HTTP)++ assert detail is not None+ assert detail.id == export_id+ assert detail.team_id == team.pk+ assert detail.interval == "hour"+ assert detail.destination_type == HTTP+ assert detail.exclude_events == ("$pageview",)+ assert detail.include_events == ()+ assert "totally-made-up-token" not in str(detail)+++def test_batch_export_by_name_is_none_when_nothing_matches(team):+ _create_export(team, name="migration", destination_type=HTTP)++ assert api.get_batch_export_by_name(team.pk, "migration", S3) is None+++def test_batch_export_by_name_rejects_an_ambiguous_match(team):+ _create_export(team, name="migration", destination_type=HTTP)+ _create_export(team, name="migration", destination_type=HTTP)++ with pytest.raises(api.MultipleBatchExportsError):+ api.get_batch_export_by_name(team.pk, "migration", HTTP)+++def test_latest_run_is_by_creation_and_latest_completed_run_is_by_finish(team):+ export_id = _create_export(team)+ finished_last = _create_run(+ batch_export_id=export_id,+ finished_at=IN_WINDOW + dt.timedelta(hours=2),+ created_at=IN_WINDOW,+ )+ _create_run(+ batch_export_id=export_id,+ finished_at=IN_WINDOW + dt.timedelta(hours=1),+ created_at=IN_WINDOW + dt.timedelta(hours=1),+ )+ created_last = _create_run(+ batch_export_id=export_id,+ finished_at=IN_WINDOW + dt.timedelta(hours=3),+ status=BatchExportRun.Status.FAILED,+ created_at=IN_WINDOW + dt.timedelta(hours=2),+ )++ latest = api.get_latest_run(export_id, team.pk)+ latest_completed = api.get_latest_completed_run(export_id, team.pk)++ assert latest is not None and latest.id == created_last+ assert latest_completed is not None and latest_completed.id == finished_last+++def test_deleting_team_batch_exports_continues_past_a_missing_schedule(team):+ first = _create_export(team, name="first")+ second = _create_export(team, name="second")+ destination_ids = list(BatchExport.objects.filter(id__in=[first, second]).values_list("destination_id", flat=True))++ def delete_schedule(_temporal, schedule_id):+ if schedule_id == str(first):+ raise BatchExportServiceScheduleNotFound(schedule_id)++ with (+ mock.patch("products.batch_exports.backend.facade.api._get_temporal_client"),+ mock.patch("products.batch_exports.backend.service.batch_export_delete_schedule", side_effect=delete_schedule),+ ):+ api.delete_batch_exports_for_teams([team.pk])++ assert not BatchExport.objects.filter(id__in=[first, second]).exists()+ assert not BatchExportDestination.objects.filter(id__in=destination_ids).exists()+++def temporal():+ return sync_connect()+++def _describe_schedule(temporal: Client, schedule_id: str):+ return async_to_sync(temporal.get_schedule_handle(schedule_id).describe)()+++def test_creating_and_deleting_a_batch_export_manages_its_temporal_schedule(team, temporal):+ detail = api.create_batch_export(+ team.pk,+ name="facade export",+ destination_type=NOOP,+ destination_config={},+ interval="hour",+ )++ try:+ assert _describe_schedule(temporal, str(detail.id)).id == str(detail.id)+ finally:+ api.delete_batch_export(detail.id, team.pk)++ assert BatchExport.objects.get(id=detail.id).deleted is True+ with pytest.raises(temporalio.service.RPCError):+ _describe_schedule(temporal, str(detail.id))diff --git a/tach.toml b/tach.tomlindex 82fc2f9cae3c..103ef353e92d 100644--- a/tach.toml+++ b/tach.toml@@ -1097,7 +1097,7 @@ expose = ["backend\\.routes.*",]from = [- "products\\.(autoresearch|customer_analytics|data_modeling|data_warehouse|demo|endpoints|error_tracking|experiments|managed_warehouse|mcp_analytics|mcp_store|metrics|notebooks|notifications|streamlit_apps|tasks|tracing|user_interviews|visual_review|warehouse_sources)",+ "products\\.(autoresearch|batch_exports|customer_analytics|data_modeling|data_warehouse|demo|endpoints|error_tracking|experiments|managed_warehouse|mcp_analytics|mcp_store|metrics|notebooks|notifications|streamlit_apps|tasks|tracing|user_interviews|visual_review|warehouse_sources)",]# TODO: Experiments-specific temporary interface@@ -1256,6 +1256,62 @@ from = ["products.error_tracking",]+# isolation:permanent-interface+# batch_exports exposes its ClickHouse DDL (backend.sql) to ten frozen ClickHouse migrations+# under posthog/clickhouse/migrations/, which import the view constants by dotted path. A frozen+# migration can never be rerouted, and the module holds CREATE ... VIEW constants and nothing+# else, so this coupling is outside the import-reroute path. The marker above declares it+# permanent rather than a legacy leak, so it does not hold the external seal open. turbo.json+# must keep backend/sql.py in the contract-check inputs when that narrowing lands, so a change+# to it still re-runs the Django suite (IsolationChainCheck enforces that).++[[interfaces]]+expose = [+ "backend\\.sql.*",+]+from = [+ "products.batch_exports",+]++# Legacy leaks — core (posthog/ee), 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.+ "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.+ "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.+ "backend\\.temporal\\.ACTIVITIES",+ "backend\\.temporal\\.WORKFLOWS",+ "backend\\.temporal\\.metrics.*",+ "backend\\.temporal\\.noop.*",+ # The warehouse_sources data-import writers reuse the destination clients and the stream+ # transformers.+ # Exit: facade.pipeline.+ "backend\\.temporal\\.destinations.*",+ "backend\\.temporal\\.pipeline\\.transformer.*",+ # cdp's enable_backfills validates with BatchExportSerializer. A facade must not import DRF,+ # so the exit here is the presentation move, after which presentation.views is the channel.+ "backend\\.api\\.batch_export.*",+]+from = [+ "products.batch_exports",+]+[[interfaces]]expose = ["backend\\.facade.*",