: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(llma): apply cluster event filters inside generation argMaxIf (#59186)
Carlos Marchal2e247e29d4a2
diff --git a/posthog/temporal/llm_analytics/trace_summarization/sampling.py b/posthog/temporal/llm_analytics/trace_summarization/sampling.pyindex b7c898e60251..8105f68a5e42 100644--- a/posthog/temporal/llm_analytics/trace_summarization/sampling.py+++ b/posthog/temporal/llm_analytics/trace_summarization/sampling.py@@ -134,7 +134,7 @@ async def sample_items_in_window_activity(inputs: BatchSummarizationInputs) -> l"""SELECTproperties.$ai_trace_id as trace_id,- argMaxIf(uuid, timestamp, event = '$ai_generation') as last_generation_id,+ argMaxIf(uuid, timestamp, event = '$ai_generation' AND {trace_filter}) as last_generation_id,min(timestamp) as trace_first_timestamp,count() as event_count,sum(length(properties)) as total_properties_size@@ -144,10 +144,10 @@ async def sample_items_in_window_activity(inputs: BatchSummarizationInputs) -> lAND timestamp < toDateTime({end_ts}, 'UTC')AND properties.$ai_trace_id != ''GROUP BY trace_id- HAVING last_generation_id IS NOT NULL+ -- argMaxIf returns the zero UUID (not NULL) when no rows match+ HAVING last_generation_id != toUUIDOrZero('')AND event_count <= {max_events}AND total_properties_size <= {max_properties_size}- AND countIf({trace_filter}) > 0ORDER BY trace_first_timestamp DESCLIMIT {limit}"""diff --git a/posthog/temporal/llm_analytics/trace_summarization/tests/test_workflow.py b/posthog/temporal/llm_analytics/trace_summarization/tests/test_workflow.pyindex 53786ca57fb9..425aa4414094 100644--- a/posthog/temporal/llm_analytics/trace_summarization/tests/test_workflow.py+++ b/posthog/temporal/llm_analytics/trace_summarization/tests/test_workflow.py@@ -132,6 +132,86 @@ class TestSampleItemsInWindowActivity:assert placeholders["max_events"].value == MAX_TRACE_EVENTS_LIMITassert placeholders["max_properties_size"].value == MAX_TRACE_PROPERTIES_SIZE+ @pytest.mark.django_db(transaction=True)+ @pytest.mark.asyncio+ async def test_generation_filter_is_applied_inside_argmaxif(self, mock_team):+ from posthog.hogql import ast+ from posthog.hogql.visitor import TraversingVisitor++ inputs = BatchSummarizationInputs(+ team_id=mock_team.id,+ max_items=10,+ analysis_level="generation",+ window_minutes=60,+ window_start="2025-01-15T11:00:00",+ window_end="2025-01-15T12:00:00",+ event_filters=[{"key": "is_background_task", "type": "event", "value": ["false"], "operator": "exact"}],+ )++ with patch("posthog.temporal.llm_analytics.trace_summarization.sampling.execute_hogql_query") as mock_execute:+ mock_execute.return_value.results = []+ await sample_items_in_window_activity(inputs)++ query: ast.SelectQuery = mock_execute.call_args.kwargs["query"]++ class CallCollector(TraversingVisitor):+ def __init__(self, name: str) -> None:+ self.name = name+ self.found: list[ast.Call] = []++ def visit_call(self, node: ast.Call) -> None:+ if node.name == self.name:+ self.found.append(node)+ super().visit_call(node)++ class KeyReferenced(TraversingVisitor):+ def __init__(self, key: str) -> None:+ self.key = key+ self.found = False++ def visit_field(self, node: ast.Field) -> None:+ if node.chain and node.chain[-1] == self.key:+ self.found = True++ argmaxif = CallCollector("argMaxIf")+ for item in query.select:+ argmaxif.visit(item)+ assert len(argmaxif.found) == 1++ class PlaceholderFinder(TraversingVisitor):+ def __init__(self, name: str) -> None:+ self.name = name+ self.found = False++ def visit_placeholder(self, node: ast.Placeholder) -> None:+ if node.chain and node.chain[-1] == self.name:+ self.found = True++ trace_filter_in_argmaxif = PlaceholderFinder("trace_filter")+ trace_filter_in_argmaxif.visit(argmaxif.found[0].args[2])+ assert trace_filter_in_argmaxif.found, (+ "Filter placeholder must be inside argMaxIf so the picked generation itself satisfies it"+ )++ trace_filter_expr = mock_execute.call_args.kwargs["placeholders"]["trace_filter"]+ key_ref = KeyReferenced("is_background_task")+ key_ref.visit(trace_filter_expr)+ assert key_ref.found, "trace_filter placeholder must reference the configured event property"++ # The trace-level countIf gate is redundant once the filter is in argMaxIf —+ # HAVING drops traces whose argMaxIf returned the zero UUID (no matching generation).+ countif = CallCollector("countIf")+ if query.having is not None:+ countif.visit(query.having)+ assert countif.found == []++ # argMaxIf with no matching rows returns the zero UUID (not NULL), so+ # HAVING must explicitly compare against it — IS NOT NULL doesn't catch it.+ zero_uuid_guard = CallCollector("toUUIDOrZero")+ assert query.having is not None+ zero_uuid_guard.visit(query.having)+ assert zero_uuid_guard.found, "HAVING must guard against zero-UUID phantom generations"+@pytest.mark.django_db(transaction=True)@pytest.mark.asyncioasync def test_sample_items_empty(self, mock_team):