Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

refactor(batch-exports): move filter composition out of spmc (#76701)

Ross9fa0ad7b6acc
diff --git a/products/batch_exports/backend/debug/debugger.py b/products/batch_exports/backend/debug/debugger.py
index 69fc0c5900ea..88fa7a51c139 100644
--- a/products/batch_exports/backend/debug/debugger.py
+++ b/products/batch_exports/backend/debug/debugger.py
@@ -39,12 +39,9 @@ from products.batch_exports.backend.temporal.destinations.postgres_batch_export
from products.batch_exports.backend.temporal.destinations.redshift_batch_export import redshift_default_fields
from products.batch_exports.backend.temporal.destinations.s3_batch_export import s3_default_fields
from products.batch_exports.backend.temporal.destinations.snowflake_batch_export import snowflake_default_fields
+from products.batch_exports.backend.temporal.filters import compose_filters_clause
from products.batch_exports.backend.temporal.pipeline.internal_stage import get_base_s3_staging_folder
-from products.batch_exports.backend.temporal.spmc import (
- BatchExportField,
- compose_filters_clause,
- use_distributed_events_recent_table,
-)
+from products.batch_exports.backend.temporal.spmc import BatchExportField, use_distributed_events_recent_table
from products.batch_exports.backend.temporal.sql.events import (
SELECT_FROM_DISTRIBUTED_EVENTS_RECENT,
SELECT_FROM_EVENTS_VIEW,
diff --git a/products/batch_exports/backend/temporal/backfill_batch_export.py b/products/batch_exports/backend/temporal/backfill_batch_export.py
index 5adfca026e6c..26640fd5b8f6 100644
--- a/products/batch_exports/backend/temporal/backfill_batch_export.py
+++ b/products/batch_exports/backend/temporal/backfill_batch_export.py
@@ -42,9 +42,9 @@ from products.batch_exports.backend.service import (
unpause_batch_export,
update_batch_export_backfill,
)
+from products.batch_exports.backend.temporal.filters import compose_filters_clause
from products.batch_exports.backend.temporal.metrics import log_query_duration
from products.batch_exports.backend.temporal.record_batch_model import SessionsRecordBatchModel
-from products.batch_exports.backend.temporal.spmc import compose_filters_clause
from products.batch_exports.backend.temporal.workflow_metadata import (
WorkflowDetails,
build_logs_link,
diff --git a/products/batch_exports/backend/temporal/destinations/http_batch_export.py b/products/batch_exports/backend/temporal/destinations/http_batch_export.py
index 820ec75eb7fd..49070a9bba8c 100644
--- a/products/batch_exports/backend/temporal/destinations/http_batch_export.py
+++ b/products/batch_exports/backend/temporal/destinations/http_batch_export.py
@@ -26,9 +26,9 @@ from products.batch_exports.backend.temporal.batch_exports import (
iter_records,
start_batch_export_run,
)
+from products.batch_exports.backend.temporal.filters import compose_filters_clause
from products.batch_exports.backend.temporal.metrics import get_bytes_exported_metric, get_rows_exported_metric
from products.batch_exports.backend.temporal.pipeline.types import BatchExportResult
-from products.batch_exports.backend.temporal.spmc import compose_filters_clause
from products.batch_exports.backend.temporal.temporary_file import BatchExportTemporaryFile, json_dumps_bytes
from products.batch_exports.backend.temporal.utils import handle_non_retryable_errors
diff --git a/products/batch_exports/backend/temporal/filters.py b/products/batch_exports/backend/temporal/filters.py
new file mode 100644
index 000000000000..6659f8576a41
--- /dev/null
+++ b/products/batch_exports/backend/temporal/filters.py
@@ -0,0 +1,145 @@
+"""Composing HogQL property filters into ClickHouse clauses for batch exports.
+
+Batch exports let users filter which events are exported. The filters arrive as serialized
+HogQL, and this turns them into a printed ClickHouse boolean clause plus the placeholder values
+to send alongside it.
+"""
+
+import typing
+
+from posthog.schema import EventPropertyFilter, HogQLPropertyFilter, HogQLQueryModifiers, MaterializationMode
+
+from posthog.hogql.context import HogQLContext
+from posthog.hogql.database.database import Database
+from posthog.hogql.errors import ExposedHogQLError, InternalHogQLError
+from posthog.hogql.hogql import ast
+from posthog.hogql.parser import parse_expr
+from posthog.hogql.printer import prepare_ast_for_printing, print_prepared_ast
+from posthog.hogql.property import property_to_expr
+from posthog.hogql.visitor import TraversingVisitor
+
+from posthog.models import Team
+
+from products.batch_exports.backend.service import SUPPORTED_FILTER_TYPES
+
+
+class UpdatePropertiesToPersonProperties(TraversingVisitor):
+ """Update 'properties' to 'events.poe.properties' in all fields."""
+
+ def visit_field(self, node: ast.Field):
+ if node.chain and node.chain[0] == "properties":
+ node.chain = ["events", "poe", "properties", *node.chain[1:]]
+
+
+class InvalidFilterError(Exception):
+ """Error raised when an invalid filter is used."""
+
+ def __init__(self, error: ExposedHogQLError | InternalHogQLError):
+ if isinstance(error, ExposedHogQLError):
+ msg = f"One or more provided filters are invalid: {error}"
+ else:
+ # TODO: Figure out if we can include some debug information from internal
+ # errors too
+ msg = "One or more provided filters are invalid"
+ super().__init__(msg)
+
+
+def compose_filters_clause(
+ filters: list[dict[str, str | list[str] | None]],
+ team_id: int,
+ values: dict[str, str] | None = None,
+) -> tuple[str, dict[str, str]]:
+ """Compose a clause of matching filters for a batch exports query.
+
+ `values` must be set if already replacing other values as otherwise there will
+ be collisions with the values returned by this function.
+
+ Arguments:
+ filters: A list of serialized HogQL filters.
+ team_id: Team we are running for.
+ values: HogQL placeholder values already in use.
+
+ Returns:
+ A printed string with the ClickHouse SQL clause, and a dictionary
+ of placeholder to values to be used as query parameters.
+ """
+ team = Team.objects.get(id=team_id)
+ context = HogQLContext(
+ team=team,
+ team_id=team.id,
+ enable_select_queries=False,
+ limit_top_select=False,
+ within_non_hogql_query=False,
+ # Export SQL reads the legacy String-properties tables/views (events, events_recent,
+ # events_batch_export), so filter fragments must stay on the legacy schema. Remove this pin
+ # only together with porting those views and field lists to events_json.
+ use_new_events_schema=False,
+ values=values or {},
+ modifiers=HogQLQueryModifiers(materializationMode=MaterializationMode.DISABLED),
+ )
+ # Export models are only events/persons/sessions; warehouse tables and views are denied.
+ # Pass bypass_warehouse_access_control=True or a user if that becomes an issue.
+ context.database = Database.create_for(team=team, modifiers=context.modifiers)
+ exprs = []
+ for filter in filters:
+ 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":
+ # HACK: We are trying to apply the filter to 'events.person_properties' as that would
+ # mimic workflows behavior of applying it to the person in the event but:
+ # 1. PersonPropertyFilter expects a join with the person table, so we can't use it.
+ # 2. 'persons_properties' doesn't exist in the HogQL 'EventsTable', so we can't use it.
+ # So, we treat this filter like an events property filter (for 1) and manually update
+ # the chain to point to 'events.poe.properties' which does exist in 'EventsTable' (for 2).
+ # This will get resolved to 'events.person_properties' in ClickHouse dialect. This is done
+ # using a visitor, which makes it slightly less of a hack.
+ # I attempted to add a new property filter just for us to use here, but it was a mess
+ # requiring multiple unnecessary (for us) file changes, and consistently failed type checks
+ # everywhere in hogql modules.
+ expr = property_to_expr(EventPropertyFilter(**{**filter, **{"type": "event"}}), team=team)
+ UpdatePropertiesToPersonProperties().visit(expr)
+ exprs.append(expr)
+
+ case "hogql":
+ try:
+ exprs.append(property_to_expr(HogQLPropertyFilter(**filter), team=team))
+ except (ExposedHogQLError, InternalHogQLError) as e:
+ raise InvalidFilterError(e) from e
+
+ 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.
+ # TODO: Extend for other models that also wish to implement property filtering.
+ select_query = ast.SelectQuery(
+ select=[
+ parse_expr("properties as properties"),
+ ],
+ select_from=ast.JoinExpr(table=ast.Field(chain=["events"])),
+ where=and_expr,
+ )
+ prepared_select_query: ast.SelectQuery = typing.cast(
+ ast.SelectQuery, prepare_ast_for_printing(select_query, context=context, dialect="hogql", stack=[select_query])
+ )
+ prepared_and_expr = prepare_ast_for_printing(
+ and_expr, context=context, dialect="clickhouse", stack=[prepared_select_query]
+ )
+
+ try:
+ printed = print_prepared_ast(
+ prepared_and_expr, # type: ignore
+ context=context,
+ dialect="clickhouse",
+ stack=[prepared_select_query],
+ )
+ except (ExposedHogQLError, InternalHogQLError) as e:
+ raise InvalidFilterError(e) from e
+
+ return printed, context.values
diff --git a/products/batch_exports/backend/temporal/pipeline/internal_stage.py b/products/batch_exports/backend/temporal/pipeline/internal_stage.py
index 2b79eec3518b..62f1e2d690d9 100644
--- a/products/batch_exports/backend/temporal/pipeline/internal_stage.py
+++ b/products/batch_exports/backend/temporal/pipeline/internal_stage.py
@@ -48,10 +48,10 @@ from products.batch_exports.backend.service import (
afetch_last_run_records_completed,
)
from products.batch_exports.backend.temporal.batch_exports import default_fields
+from products.batch_exports.backend.temporal.filters import compose_filters_clause
from products.batch_exports.backend.temporal.metrics import log_query_duration
from products.batch_exports.backend.temporal.record_batch_model import RecordBatchModel, resolve_batch_exports_model
from products.batch_exports.backend.temporal.spmc import (
- compose_filters_clause,
generate_query_ranges,
is_5_min_batch_export,
use_distributed_events_recent_table,
diff --git a/products/batch_exports/backend/temporal/spmc.py b/products/batch_exports/backend/temporal/spmc.py
index 855cd61521af..3e9a2f63f753 100644
--- a/products/batch_exports/backend/temporal/spmc.py
+++ b/products/batch_exports/backend/temporal/spmc.py
@@ -11,21 +11,9 @@ from django.conf import settings
import pyarrow as pa
from temporalio.common import MetricHistogram
-from posthog.schema import EventPropertyFilter, HogQLPropertyFilter, HogQLQueryModifiers, MaterializationMode
-
-from posthog.hogql.context import HogQLContext
-from posthog.hogql.database.database import Database
-from posthog.hogql.errors import ExposedHogQLError, InternalHogQLError
-from posthog.hogql.hogql import ast
-from posthog.hogql.parser import parse_expr
-from posthog.hogql.printer import prepare_ast_for_printing, print_prepared_ast
-from posthog.hogql.property import property_to_expr
-from posthog.hogql.visitor import TraversingVisitor
-
-from posthog.models import Team
from posthog.temporal.common.logger import get_write_only_logger
-from products.batch_exports.backend.service import SUPPORTED_FILTER_TYPES, BackfillDetails
+from products.batch_exports.backend.service import BackfillDetails
from products.batch_exports.backend.temporal.metrics import get_metric_meter
LOGGER = get_write_only_logger(__name__)
@@ -348,128 +336,6 @@ def generate_query_ranges(
yield (candidate_start_at, candidate_end_at)
-class UpdatePropertiesToPersonProperties(TraversingVisitor):
- """Update 'properties' to 'events.poe.properties' in all fields."""
-
- def visit_field(self, node: ast.Field):
- if node.chain and node.chain[0] == "properties":
- node.chain = ["events", "poe", "properties", *node.chain[1:]]
-
-
-class InvalidFilterError(Exception):
- """Error raised when an invalid filter is used."""
-
- def __init__(self, error: ExposedHogQLError | InternalHogQLError):
- if isinstance(error, ExposedHogQLError):
- msg = f"One or more provided filters are invalid: {error}"
- else:
- # TODO: Figure out if we can include some debug information from internal
- # errors too
- msg = "One or more provided filters are invalid"
- super().__init__(msg)
-
-
-def compose_filters_clause(
- filters: list[dict[str, str | list[str] | None]],
- team_id: int,
- values: dict[str, str] | None = None,
-) -> tuple[str, dict[str, str]]:
- """Compose a clause of matching filters for a batch exports query.
-
- `values` must be set if already replacing other values as otherwise there will
- be collisions with the values returned by this function.
-
- Arguments:
- filters: A list of serialized HogQL filters.
- team_id: Team we are running for.
- values: HogQL placeholder values already in use.
-
- Returns:
- A printed string with the ClickHouse SQL clause, and a dictionary
- of placeholder to values to be used as query parameters.
- """
- team = Team.objects.get(id=team_id)
- context = HogQLContext(
- team=team,
- team_id=team.id,
- enable_select_queries=False,
- limit_top_select=False,
- within_non_hogql_query=False,
- # Export SQL reads the legacy String-properties tables/views (events, events_recent,
- # events_batch_export), so filter fragments must stay on the legacy schema. Remove this pin
- # only together with porting those views and field lists to events_json.
- use_new_events_schema=False,
- values=values or {},
- modifiers=HogQLQueryModifiers(materializationMode=MaterializationMode.DISABLED),
- )
- # Export models are only events/persons/sessions; warehouse tables and views are denied.
- # Pass bypass_warehouse_access_control=True or a user if that becomes an issue.
- context.database = Database.create_for(team=team, modifiers=context.modifiers)
- exprs = []
- for filter in filters:
- 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":
- # HACK: We are trying to apply the filter to 'events.person_properties' as that would
- # mimic workflows behavior of applying it to the person in the event but:
- # 1. PersonPropertyFilter expects a join with the person table, so we can't use it.
- # 2. 'persons_properties' doesn't exist in the HogQL 'EventsTable', so we can't use it.
- # So, we treat this filter like an events property filter (for 1) and manually update
- # the chain to point to 'events.poe.properties' which does exist in 'EventsTable' (for 2).
- # This will get resolved to 'events.person_properties' in ClickHouse dialect. This is done
- # using a visitor, which makes it slightly less of a hack.
- # I attempted to add a new property filter just for us to use here, but it was a mess
- # requiring multiple unnecessary (for us) file changes, and consistently failed type checks
- # everywhere in hogql modules.
- expr = property_to_expr(EventPropertyFilter(**{**filter, **{"type": "event"}}), team=team)
- UpdatePropertiesToPersonProperties().visit(expr)
- exprs.append(expr)
-
- case "hogql":
- try:
- exprs.append(property_to_expr(HogQLPropertyFilter(**filter), team=team))
- except (ExposedHogQLError, InternalHogQLError) as e:
- raise InvalidFilterError(e) from e
-
- 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.
- # TODO: Extend for other models that also wish to implement property filtering.
- select_query = ast.SelectQuery(
- select=[
- parse_expr("properties as properties"),
- ],
- select_from=ast.JoinExpr(table=ast.Field(chain=["events"])),
- where=and_expr,
- )
- prepared_select_query: ast.SelectQuery = typing.cast(
- ast.SelectQuery, prepare_ast_for_printing(select_query, context=context, dialect="hogql", stack=[select_query])
- )
- prepared_and_expr = prepare_ast_for_printing(
- and_expr, context=context, dialect="clickhouse", stack=[prepared_select_query]
- )
-
- try:
- printed = print_prepared_ast(
- prepared_and_expr, # type: ignore
- context=context,
- dialect="clickhouse",
- stack=[prepared_select_query],
- )
- except (ExposedHogQLError, InternalHogQLError) as e:
- raise InvalidFilterError(e) from e
-
- return printed, context.values
-
-
async def wait_for_delta_past_data_interval_end(
data_interval_end: dt.datetime, delta: dt.timedelta = dt.timedelta(seconds=30)
) -> None:
diff --git a/products/batch_exports/backend/tests/temporal/destinations/test_http_batch_export_workflow.py b/products/batch_exports/backend/tests/temporal/destinations/test_http_batch_export_workflow.py
index 23f3df96466f..c64dad4a3c94 100644
--- a/products/batch_exports/backend/tests/temporal/destinations/test_http_batch_export_workflow.py
+++ b/products/batch_exports/backend/tests/temporal/destinations/test_http_batch_export_workflow.py
@@ -38,7 +38,7 @@ from products.batch_exports.backend.temporal.destinations.http_batch_export impo
http_default_fields,
insert_into_http_activity,
)
-from products.batch_exports.backend.temporal.spmc import compose_filters_clause
+from products.batch_exports.backend.temporal.filters import compose_filters_clause
from products.batch_exports.backend.tests.temporal.utils.workflow import mocked_start_batch_export_run
pytestmark = [
diff --git a/products/batch_exports/backend/tests/temporal/test_spmc.py b/products/batch_exports/backend/tests/temporal/test_spmc.py
index f6e29f7ce2d9..96aa5edcf188 100644
--- a/products/batch_exports/backend/tests/temporal/test_spmc.py
+++ b/products/batch_exports/backend/tests/temporal/test_spmc.py
@@ -8,10 +8,9 @@ import pytest
import pyarrow as pa
from products.batch_exports.backend.service import BackfillDetails
+from products.batch_exports.backend.temporal.filters import InvalidFilterError, compose_filters_clause
from products.batch_exports.backend.temporal.spmc import (
- InvalidFilterError,
RecordBatchQueue,
- compose_filters_clause,
slice_record_batch,
use_distributed_events_recent_table,
)
diff --git a/products/batch_exports/backend/tests/temporal/utils/clickhouse_test_producer.py b/products/batch_exports/backend/tests/temporal/utils/clickhouse_test_producer.py
index 2828a21e1884..a28da2fab076 100644
--- a/products/batch_exports/backend/tests/temporal/utils/clickhouse_test_producer.py
+++ b/products/batch_exports/backend/tests/temporal/utils/clickhouse_test_producer.py
@@ -19,10 +19,10 @@ from posthog.temporal.common.clickhouse import get_client
from posthog.temporal.common.logger import get_write_only_logger
from products.batch_exports.backend.service import BackfillDetails, BatchExportField
+from products.batch_exports.backend.temporal.filters import compose_filters_clause
from products.batch_exports.backend.temporal.record_batch_model import RecordBatchModel
from products.batch_exports.backend.temporal.spmc import (
RecordBatchQueue,
- compose_filters_clause,
generate_query_ranges,
is_5_min_batch_export,
slice_record_batch,