: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 cdp's backfill export onto the facade (#109287)
Ross2cf65f3463e1
diff --git a/products/batch_exports/backend/api/batch_export.py b/products/batch_exports/backend/api/batch_export.pyindex dc905dfdce9b..670c2aabef41 100644--- a/products/batch_exports/backend/api/batch_export.py+++ b/products/batch_exports/backend/api/batch_export.py@@ -58,6 +58,8 @@ from products.batch_exports.backend.api.utils import (HogQLModifiersField,check_hogql_batch_exports_enabled,)+from products.batch_exports.backend.facade.contracts import InvalidBatchExportFilters+from products.batch_exports.backend.filters import SUPPORTED_FILTER_TYPES_DISPLAY, validate_batch_export_filtersfrom products.batch_exports.backend.hogql_source import (DATA_INTERVAL_START_PLACEHOLDER,UnsupportedHogQLQueryError,@@ -80,7 +82,6 @@ from products.batch_exports.backend.models.batch_export import ()from products.batch_exports.backend.service import (DESTINATION_WORKFLOWS,- SUPPORTED_FILTER_TYPES,BaseBatchExportInputs,BatchExportIdError,BatchExportSchema,@@ -104,9 +105,6 @@ from products.batch_exports.backend.temporal.sql.events import EXPORTABLE_EVENTSlogger = structlog.get_logger(__name__)-# Quoted, sorted rendering of the supported filter types for user-facing messages.-_SUPPORTED_FILTER_TYPES_DISPLAY = ", ".join(repr(t) for t in sorted(SUPPORTED_FILTER_TYPES))-def validate_date_input(date_input: Any, batch_export: BatchExport) -> dt.datetime:"""Validate and parse a date/datetime input as a proper dt.datetime.@@ -880,7 +878,7 @@ class BatchExportRequestSerializer(serializers.Serializer):allow_null=True,help_text=("Optional list of property filters to restrict which events are exported. Each filter is a "- f"serialized HogQL property filter object with a 'type' of one of: {_SUPPORTED_FILTER_TYPES_DISPLAY} "+ f"serialized HogQL property filter object with a 'type' of one of: {SUPPORTED_FILTER_TYPES_DISPLAY} "'(e.g. {"key": "$browser", "operator": "exact", "type": "event", "value": ["Firefox"]}).'),)@@ -1431,26 +1429,10 @@ class BatchExportSerializer(serializers.ModelSerializer):return offset_hourdef validate_filters(self, filters):- if filters is None:- return filters-- if not isinstance(filters, list):- raise serializers.ValidationError("'filters' should be an array of filters")-- for filter in filters:- if not isinstance(filter, dict):- raise serializers.ValidationError("Each filter must be an object")-- if any(key in filter for key in ("data_interval_start", "data_interval_end")):- raise serializers.ValidationError(- "'data_interval_start' and 'data_interval_end' are run attributes and not 'filters'."- " Trigger a backfill if you wish to manually control which periods to batch export."- )-- if filter.get("type") not in SUPPORTED_FILTER_TYPES:- raise serializers.ValidationError(- f"Each filter must have a 'type' of one of: {_SUPPORTED_FILTER_TYPES_DISPLAY}"- )+ try:+ validate_batch_export_filters(filters)+ except InvalidBatchExportFilters as e:+ raise serializers.ValidationError(str(e))return filters# TODO: could this be moved inside BatchExportDestinationSerializer::validate?diff --git a/products/batch_exports/backend/facade/api.py b/products/batch_exports/backend/facade/api.pyindex f6f3ec3e35b0..eedfdf22f06a 100644--- a/products/batch_exports/backend/facade/api.py+++ b/products/batch_exports/backend/facade/api.py@@ -31,6 +31,7 @@ from django.db.models.functions import Coalesceimport structlogfrom products.batch_exports.backend.billing import exclude_non_billable_runs+from products.batch_exports.backend.filters import validate_batch_export_filtersfrom products.batch_exports.backend.models.batch_export import (BATCH_EXPORT_INTERVALS,BatchExport,@@ -51,6 +52,7 @@ __all__ = ["backfill_batch_export","count_batch_exports_for_teams","create_batch_export",+ "create_workflows_backfill_export","delete_batch_export","delete_batch_exports_for_teams","get_batch_export_by_name",@@ -321,6 +323,20 @@ def get_latest_completed_run(export_id: UUID, team_id: int) -> contracts.BatchExreturn _to_run_summary(run) if run is not None else None+def _schedule_and_save(batch_export: BatchExport) -> None:+ """Create the Temporal schedule of a new export, then save the export and its destination."""+ service = _service()++ # 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():+ batch_export.destination.save()+ batch_export.save()++def create_batch_export(team_id: int,*,@@ -332,28 +348,48 @@ def create_batch_export(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,+ destination=BatchExportDestination(type=destination_type, config=dict(destination_config)),name=name,interval=interval,paused=paused,end_at=end_at,)+ _schedule_and_save(batch_export)+ return _to_detail(batch_export)- # 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()+def create_workflows_backfill_export(+ team_id: int,+ *,+ hog_function_id: UUID,+ name: str,+ event_filters: list[dict[str, object]] | None,+ last_modified_by_id: int,+) -> contracts.BatchExportRef:+ """Create the paused, hourly export that backfills events into a hog function.- return _to_detail(batch_export)+ Raises ``contracts.InvalidBatchExportFilters`` when ``event_filters`` fail the checks the+ batch export API applies.+ """+ validate_batch_export_filters(event_filters)++ batch_export = BatchExport(+ team_id=team_id,+ destination=BatchExportDestination(+ type=BatchExportDestination.Destination.WORKFLOWS,+ config={"hog_function_id": str(hog_function_id)},+ ),+ name=name,+ model=BatchExport.Model.EVENTS,+ interval="hour",+ paused=True,+ filters=event_filters,+ last_modified_by_id=last_modified_by_id,+ )+ _schedule_and_save(batch_export)+ return _to_ref(batch_export)def delete_batch_export(export_id: UUID, team_id: int) -> None:diff --git a/products/batch_exports/backend/facade/contracts.py b/products/batch_exports/backend/facade/contracts.pyindex 3acb2e519531..77b576d17499 100644--- a/products/batch_exports/backend/facade/contracts.py+++ b/products/batch_exports/backend/facade/contracts.py@@ -29,6 +29,10 @@ from pydantic.dataclasses import dataclassBATCH_EXPORT_MODEL_LABEL = "batch_exports.BatchExport"+class InvalidBatchExportFilters(ValueError):+ """Raised when event filters are not a list of filters a batch export can apply."""++@dataclass(frozen=True)class BatchExportRef:"""The bare identity of a batch export, for listing it by name."""diff --git a/products/batch_exports/backend/filters.py b/products/batch_exports/backend/filters.pynew file mode 100644index 000000000000..1fee7ec895af--- /dev/null+++ b/products/batch_exports/backend/filters.py@@ -0,0 +1,40 @@+"""+The event filters a batch export stores, and the checks they must pass on write.++This module imports no framework and no Temporal code, so the DRF serializer and the facade+share one set of checks. ``service.py`` imports ``temporalio``, so the checks cannot live+there: the facade is on the ``django.setup()`` path.+"""++from products.batch_exports.backend.facade.contracts import InvalidBatchExportFilters++# Single source of truth for the serialized filter `type` values we accept. Enforced at write+# time by `validate_batch_export_filters` and at query time by `compose_filters_clause`.+SUPPORTED_FILTER_TYPES = {"event", "person", "hogql"}++# Quoted, sorted rendering of the supported filter types for user-facing messages.+SUPPORTED_FILTER_TYPES_DISPLAY = ", ".join(repr(t) for t in sorted(SUPPORTED_FILTER_TYPES))+++def validate_batch_export_filters(filters: object) -> None:+ """Raise ``InvalidBatchExportFilters`` unless ``filters`` is None or a list of supported filters."""+ if filters is None:+ return++ if not isinstance(filters, list):+ raise InvalidBatchExportFilters("'filters' should be an array of filters")++ for filter in filters:+ if not isinstance(filter, dict):+ raise InvalidBatchExportFilters("Each filter must be an object")++ if any(key in filter for key in ("data_interval_start", "data_interval_end")):+ raise InvalidBatchExportFilters(+ "'data_interval_start' and 'data_interval_end' are run attributes and not 'filters'."+ " Trigger a backfill if you wish to manually control which periods to batch export."+ )++ if filter.get("type") not in SUPPORTED_FILTER_TYPES:+ raise InvalidBatchExportFilters(+ f"Each filter must have a 'type' of one of: {SUPPORTED_FILTER_TYPES_DISPLAY}"+ )diff --git a/products/batch_exports/backend/service.py b/products/batch_exports/backend/service.pyindex 01c5fd1bc461..7c478bc6a2a0 100644--- a/products/batch_exports/backend/service.py+++ b/products/batch_exports/backend/service.py@@ -148,11 +148,6 @@ class BatchExportEventPropertyFilter:value: list[str]-# Single source of truth for the serialized filter `type` values we accept. Enforced at write-# time by the batch export serializer and at query time by `compose_filters_clause`.-SUPPORTED_FILTER_TYPES = {"event", "person", "hogql"}--@dataclass(frozen=False)class BatchExportModel:name: strdiff --git a/products/batch_exports/backend/temporal/filters.py b/products/batch_exports/backend/temporal/filters.pyindex ad2886bcd5ae..f1ac83109f21 100644--- a/products/batch_exports/backend/temporal/filters.py+++ b/products/batch_exports/backend/temporal/filters.py@@ -20,8 +20,8 @@ from posthog.hogql.visitor import CloningVisitor, TraversingVisitorfrom posthog.models import Team+from products.batch_exports.backend.filters import SUPPORTED_FILTER_TYPESfrom products.batch_exports.backend.hogql_source import native_event_property_chain, native_feature_flag_read-from products.batch_exports.backend.service import SUPPORTED_FILTER_TYPESclass UpdatePropertiesToPersonProperties(TraversingVisitor):diff --git a/products/batch_exports/backend/tests/test_facade.py b/products/batch_exports/backend/tests/test_facade.pyindex afc0abff0b71..87e43e569a37 100644--- a/products/batch_exports/backend/tests/test_facade.py+++ b/products/batch_exports/backend/tests/test_facade.py@@ -1,3 +1,4 @@+import uuidimport datetime as dtimport pytest@@ -9,6 +10,7 @@ from temporalio.client import Clientfrom posthog.api.test.test_organization import create_organizationfrom posthog.api.test.test_team import create_team+from posthog.models import Userfrom posthog.temporal.common.client import sync_connectfrom products.batch_exports.backend.facade import api, contracts, testing@@ -286,6 +288,53 @@ def test_deleting_team_batch_exports_continues_past_a_missing_schedule(team):assert not BatchExportDestination.objects.filter(id__in=destination_ids).exists()+def test_workflows_backfill_export_is_a_paused_hourly_events_export_for_the_hog_function(team, organization):+ user = User.objects.create_and_join(organization=organization, email="[email protected]", password=None)+ hog_function_id = uuid.uuid4()+ event_filters: list[dict[str, object]] = [+ {"key": "$browser", "operator": "exact", "type": "event", "value": ["Firefox"]}+ ]++ with mock.patch("products.batch_exports.backend.service.sync_batch_export") as sync_batch_export:+ ref = api.create_workflows_backfill_export(+ team.pk,+ hog_function_id=hog_function_id,+ name="My destination",+ event_filters=event_filters,+ last_modified_by_id=user.pk,+ )++ sync_batch_export.assert_called_once()+ batch_export = BatchExport.objects.select_related("destination").get(id=ref.id, team_id=team.pk)+ assert ref.name == "My destination"+ assert (+ batch_export.paused,+ batch_export.interval,+ batch_export.model,+ batch_export.filters,+ batch_export.last_modified_by_id,+ ) == (True, "hour", BatchExport.Model.EVENTS, event_filters, user.pk)+ assert batch_export.destination.type == WORKFLOWS+ assert batch_export.destination.config == {"hog_function_id": str(hog_function_id)}+++def test_workflows_backfill_export_rejects_bad_filters_before_it_schedules_anything(team):+ with (+ mock.patch("products.batch_exports.backend.service.sync_batch_export") as sync_batch_export,+ pytest.raises(contracts.InvalidBatchExportFilters),+ ):+ api.create_workflows_backfill_export(+ team.pk,+ hog_function_id=uuid.uuid4(),+ name="My destination",+ event_filters=[{"id": "$pageview", "type": "events"}],+ last_modified_by_id=1,+ )++ sync_batch_export.assert_not_called()+ assert not BatchExport.objects.filter(team_id=team.pk).exists()++@pytest.fixturedef temporal():return sync_connect()diff --git a/products/cdp/backend/api/hog_function.py b/products/cdp/backend/api/hog_function.pyindex 79d8bcafe4ba..fb05a9956380 100644--- a/products/cdp/backend/api/hog_function.py+++ b/products/cdp/backend/api/hog_function.py@@ -51,10 +51,12 @@ from posthog.helpers.trigram_search import (apply_trigram_search,drop_similar_when_exact_exists,)-from posthog.models import Team+from posthog.models import Team, Userfrom posthog.models.activity_logging.activity_log import Change, Detail, log_activityfrom posthog.plugins.plugin_server_api import create_hog_invocation_test, rerun_hog_invocations+from products.batch_exports.backend.facade import api as batch_exports_api+from products.batch_exports.backend.facade.contracts import InvalidBatchExportFiltersfrom products.cdp.backend.api.hog_function_template import HogFunctionTemplateSerializerfrom products.cdp.backend.models.hog_function_template import HogFunctionTemplatefrom products.cdp.backend.models.hog_functions.hog_function import (@@ -1798,8 +1800,6 @@ class HogFunctionViewSet(@action(detail=True, methods=["POST"])def enable_backfills(self, request: Request, *args, **kwargs):- from products.batch_exports.backend.api.batch_export import BatchExportSerializer-hog_function = self.get_object()# Check if backfill is already enabled@@ -1835,27 +1835,16 @@ class HogFunctionViewSet():raise PermissionDenied("Backfilling Workflows is not enabled for this team.")- # Prepare batch export data matching the frontend's structure- batch_export_data = {- "name": hog_function.name,- "paused": True,- "interval": "hour",- "model": "events",- "filters": hog_function.filters.get("events", []) if hog_function.filters else [],- "destination": {- "type": "Workflows",- "config": {"hog_function_id": str(hog_function.id)},- },- }-- batch_export_serializer = BatchExportSerializer(- data=batch_export_data, context={"team_id": self.team_id, "request": request}- )-- if not batch_export_serializer.is_valid():- return Response(batch_export_serializer.errors, status=400)-- batch_export = batch_export_serializer.save()+ try:+ batch_export = batch_exports_api.create_workflows_backfill_export(+ self.team_id,+ hog_function_id=hog_function.id,+ name=hog_function.name or "",+ event_filters=hog_function.filters.get("events", []) if hog_function.filters else [],+ last_modified_by_id=cast(User, request.user).id,+ )+ except InvalidBatchExportFilters as e:+ return Response({"error": str(e)}, status=400)hog_function.batch_export_id = batch_export.idhog_function.save(update_fields=["batch_export_id"])diff --git a/products/cdp/backend/api/test/test_hog_function.py b/products/cdp/backend/api/test/test_hog_function.pyindex b40ec94e4d33..4b31a5164f87 100644--- a/products/cdp/backend/api/test/test_hog_function.py+++ b/products/cdp/backend/api/test/test_hog_function.py@@ -3364,6 +3364,20 @@ class TestHogFunctionAPI(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):assert response.status_code == status.HTTP_400_BAD_REQUESTassert response.json()["error"] == "Backfills are only supported for event-sourced destinations."+ @patch("products.cdp.backend.api.hog_function.posthoganalytics.feature_enabled", return_value=True)+ def test_enable_backfills_rejects_filters_a_batch_export_cannot_apply(self, _mock_feature_enabled):+ response = self.client.post(f"/api/projects/{self.team.id}/hog_functions/", data=EXAMPLE_FULL)+ assert response.status_code == status.HTTP_201_CREATED+ function_id = response.json()["id"]++ response = self.client.post(+ f"/api/projects/{self.team.id}/hog_functions/{function_id}/enable_backfills/",+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert response.json() == {"error": "Each filter must have a 'type' of one of: 'event', 'hogql', 'person'"}+ assert HogFunction.objects.get(id=function_id).batch_export_id is None+class TestLogTransformationAPI(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):def setUp(self):diff --git a/tach.toml b/tach.tomlindex 8d033fa64a82..3e1950479eb6 100644--- a/tach.toml+++ b/tach.toml@@ -1303,21 +1303,6 @@ from = ["products.batch_exports",]-# Legacy leaks — cdp still imports 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 = [- # 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.*",