: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
fix(batch-exports): validate filter shape (#68159)
Ross166165fa6324
diff --git a/products/batch_exports/backend/api/batch_export.py b/products/batch_exports/backend/api/batch_export.pyindex d5d153b8b10e..13f40cb525aa 100644--- a/products/batch_exports/backend/api/batch_export.py+++ b/products/batch_exports/backend/api/batch_export.py@@ -62,6 +62,7 @@ from products.batch_exports.backend.models.batch_export import ()from products.batch_exports.backend.service import (DESTINATION_WORKFLOWS,+ SUPPORTED_FILTER_TYPES,BaseBatchExportInputs,BatchExportIdError,BatchExportSchema,@@ -84,6 +85,9 @@ from products.batch_exports.backend.temporal.destinations.constants import (logger = 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.@@ -576,7 +580,15 @@ class BatchExportRequestSerializer(serializers.Serializer):required=False,help_text="Optional HogQL SELECT defining a custom model schema. Only recommended in advanced use cases.",)- filters = serializers.JSONField(required=False, allow_null=True)+ filters = serializers.JSONField(+ required=False,+ 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} "+ '(e.g. {"key": "$browser", "operator": "exact", "type": "event", "value": ["Firefox"]}).'+ ),+ )timezone = serializers.CharField(required=False,allow_null=True,@@ -1078,11 +1090,19 @@ class BatchExportSerializer(serializers.ModelSerializer):raise serializers.ValidationError("'filters' should be an array of filters")for filter in filters:- if isinstance(filter, dict) and any(key in filter for key in ("data_interval_start", "data_interval_end")):+ 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}"+ )return filters# TODO: could this be moved inside BatchExportDestinationSerializer::validate?diff --git a/products/batch_exports/backend/service.py b/products/batch_exports/backend/service.pyindex cf2b21f81afa..e67422807e16 100644--- a/products/batch_exports/backend/service.py+++ b/products/batch_exports/backend/service.py@@ -147,6 +147,11 @@ 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"}++@dataclassclass BatchExportModel:name: strdiff --git a/products/batch_exports/backend/temporal/spmc.py b/products/batch_exports/backend/temporal/spmc.pyindex aef1028f884b..1b66c4fa3748 100644--- a/products/batch_exports/backend/temporal/spmc.py+++ b/products/batch_exports/backend/temporal/spmc.py@@ -28,7 +28,7 @@ from posthog.sync import database_sync_to_asyncfrom posthog.temporal.common.clickhouse import get_clientfrom posthog.temporal.common.logger import get_write_only_logger-from products.batch_exports.backend.service import BackfillDetails+from products.batch_exports.backend.service import SUPPORTED_FILTER_TYPES, BackfillDetailsfrom products.batch_exports.backend.temporal.metrics import get_metric_meterfrom products.batch_exports.backend.temporal.record_batch_model import RecordBatchModelfrom products.batch_exports.backend.temporal.sql import (@@ -708,7 +708,11 @@ def compose_filters_clause(context.database = Database.create_for(team=team, modifiers=context.modifiers)exprs = []for filter in filters:- match filter["type"]:+ filter_type = filter["type"]+ if filter_type not in SUPPORTED_FILTER_TYPES:+ raise TypeError(f"Unknown filter type: '{filter_type}'")++ match filter_type:case "event":exprs.append(property_to_expr(EventPropertyFilter(**filter), team=team))case "person":@@ -733,8 +737,9 @@ def compose_filters_clause(except (ExposedHogQLError, InternalHogQLError) as e:raise InvalidFilterError(e) from e- case s:- raise TypeError(f"Unknown filter type: '{s}'")+ case _:+ # Reachable only if SUPPORTED_FILTER_TYPES gains a type without a handler here.+ raise TypeError(f"Unhandled filter type: '{filter_type}'")and_expr = ast.And(exprs=exprs)# This query only supports events at the moment.diff --git a/products/batch_exports/backend/tests/api/test_create.py b/products/batch_exports/backend/tests/api/test_create.pyindex 722ac478b424..74b14ae7c364 100644--- a/products/batch_exports/backend/tests/api/test_create.py+++ b/products/batch_exports/backend/tests/api/test_create.py@@ -702,6 +702,15 @@ _S3_FILTER_TEST_CONFIG = {status.HTTP_400_BAD_REQUEST,"not 'filters'. Trigger a backfill",),+ # A list of bare strings (not objects) would pass decoding into the DB but crash the+ # workflow at input-decode time — reject it at write time instead.+ (["$pageview"], status.HTTP_400_BAD_REQUEST, "must be an object"),+ ([{"key": "$browser", "operator": "exact"}], status.HTTP_400_BAD_REQUEST, "must have a 'type'"),+ (+ [{"key": "$browser", "operator": "exact", "type": "event", "value": ["Firefox"]}],+ status.HTTP_201_CREATED,+ None,+ ),],)def test_creating_batch_export_with_filters(diff --git a/products/batch_exports/frontend/generated/api.schemas.ts b/products/batch_exports/frontend/generated/api.schemas.tsindex c8fec44f3f48..2faee13ec325 100644--- a/products/batch_exports/frontend/generated/api.schemas.ts+++ b/products/batch_exports/frontend/generated/api.schemas.ts@@ -1299,6 +1299,7 @@ export interface BatchExportRequestApi {paused?: boolean/** Optional HogQL SELECT defining a custom model schema. Only recommended in advanced use cases. */hogql_query?: string+ /** Optional list of property filters to restrict which events are exported. Each filter is a serialized HogQL property filter object with a 'type' of one of: 'event', 'hogql', 'person' (e.g. {"key": "$browser", "operator": "exact", "type": "event", "value": ["Firefox"]}). */filters?: unknown/*** IANA timezone name (e.g. 'America/New_York', 'Europe/London', 'UTC') controlling daily and weekly interval boundaries.@@ -1458,6 +1459,7 @@ export interface PatchedBatchExportRequestApi {paused?: boolean/** Optional HogQL SELECT defining a custom model schema. Only recommended in advanced use cases. */hogql_query?: string+ /** Optional list of property filters to restrict which events are exported. Each filter is a serialized HogQL property filter object with a 'type' of one of: 'event', 'hogql', 'person' (e.g. {"key": "$browser", "operator": "exact", "type": "event", "value": ["Firefox"]}). */filters?: unknown/*** IANA timezone name (e.g. 'America/New_York', 'Europe/London', 'UTC') controlling daily and weekly interval boundaries.diff --git a/products/batch_exports/frontend/generated/api.zod.ts b/products/batch_exports/frontend/generated/api.zod.tsindex 905a07e49f1e..c166535d018d 100644--- a/products/batch_exports/frontend/generated/api.zod.ts+++ b/products/batch_exports/frontend/generated/api.zod.ts@@ -305,7 +305,12 @@ export const BatchExportsCreateBody = /* @__PURE__ */ zod.string().optional().describe('Optional HogQL SELECT defining a custom model schema. Only recommended in advanced use cases.'),- filters: zod.unknown().optional(),+ filters: zod+ .unknown()+ .optional()+ .describe(+ 'Optional list of property filters to restrict which events are exported. Each filter is a serialized HogQL property filter object with a \'type\' of one of: \'event\', \'hogql\', \'person\' (e.g. {\"key\": \"$browser\", \"operator\": \"exact\", \"type\": \"event\", \"value\": [\"Firefox\"]}).'+ ),timezone: zod.string().nullish()@@ -872,7 +877,12 @@ export const BatchExportsUpdateBody = /* @__PURE__ */ zod.string().optional().describe('Optional HogQL SELECT defining a custom model schema. Only recommended in advanced use cases.'),- filters: zod.unknown().optional(),+ filters: zod+ .unknown()+ .optional()+ .describe(+ 'Optional list of property filters to restrict which events are exported. Each filter is a serialized HogQL property filter object with a \'type\' of one of: \'event\', \'hogql\', \'person\' (e.g. {\"key\": \"$browser\", \"operator\": \"exact\", \"type\": \"event\", \"value\": [\"Firefox\"]}).'+ ),timezone: zod.string().nullish()@@ -1196,7 +1206,12 @@ export const BatchExportsPartialUpdateBody = /* @__PURE__ */ zod.string().optional().describe('Optional HogQL SELECT defining a custom model schema. Only recommended in advanced use cases.'),- filters: zod.unknown().optional(),+ filters: zod+ .unknown()+ .optional()+ .describe(+ 'Optional list of property filters to restrict which events are exported. Each filter is a serialized HogQL property filter object with a \'type\' of one of: \'event\', \'hogql\', \'person\' (e.g. {\"key\": \"$browser\", \"operator\": \"exact\", \"type\": \"event\", \"value\": [\"Firefox\"]}).'+ ),timezone: zod.string().nullish()diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 9e0dc26d87e8..863ee080c0e4 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -11365,6 +11365,7 @@ export namespace Schemas {paused?: boolean;/** Optional HogQL SELECT defining a custom model schema. Only recommended in advanced use cases. */hogql_query?: string;+ /** Optional list of property filters to restrict which events are exported. Each filter is a serialized HogQL property filter object with a 'type' of one of: 'event', 'hogql', 'person' (e.g. {"key": "$browser", "operator": "exact", "type": "event", "value": ["Firefox"]}). */filters?: unknown;/*** IANA timezone name (e.g. 'America/New_York', 'Europe/London', 'UTC') controlling daily and weekly interval boundaries.@@ -36201,6 +36202,7 @@ export namespace Schemas {paused?: boolean;/** Optional HogQL SELECT defining a custom model schema. Only recommended in advanced use cases. */hogql_query?: string;+ /** Optional list of property filters to restrict which events are exported. Each filter is a serialized HogQL property filter object with a 'type' of one of: 'event', 'hogql', 'person' (e.g. {"key": "$browser", "operator": "exact", "type": "event", "value": ["Firefox"]}). */filters?: unknown;/*** IANA timezone name (e.g. 'America/New_York', 'Europe/London', 'UTC') controlling daily and weekly interval boundaries.