: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): return no more traces than the requested limit (#88988)
Bernat Torres64f1e77102d5
diff --git a/ee/hogai/tools/search_traces.py b/ee/hogai/tools/search_traces.pyindex 3aff71e33c9c..a3c492e8829e 100644--- a/ee/hogai/tools/search_traces.py+++ b/ee/hogai/tools/search_traces.py@@ -115,8 +115,8 @@ class SearchLLMTracesTool(MaxTool):results = [LLMTrace.model_validate(r) for r in raw_results]has_more = cast(bool, query_results.get("hasMore", False))- # The query runner returns limit+1 results when hasMore=True — the extra row is- # purely for detection and should not be displayed. Trim to the requested limit.+ # TracesQueryRunner already trims the page to query.limit. This guard keeps the tool+ # within its own contract if the runner ever returns the extra hasMore detection row.if has_more and len(results) > query.limit:results = results[: query.limit]next_cursor = str(current_offset + len(results)) if has_more else Nonediff --git a/ee/hogai/tools/test/test_search_traces.py b/ee/hogai/tools/test/test_search_traces.pyindex 46dbd58ccc06..1a1065edb070 100644--- a/ee/hogai/tools/test/test_search_traces.py+++ b/ee/hogai/tools/test/test_search_traces.py@@ -2,6 +2,7 @@ from posthog.test.base import BaseTestfrom unittest.mock import AsyncMock, patchfrom langchain_core.runnables import RunnableConfig+from parameterized import parameterizedfrom posthog.schema import DateRange, LLMTrace, LLMTraceEvent, TracesQuery@@ -71,19 +72,27 @@ class TestSearchLLMTracesTool(BaseTest):self.assertIn("trace-1", content)self.assertIsNone(artifact)+ @parameterized.expand(+ [+ ("first_page", 1, None, '"1"'),+ ("later_page", 10, "20", '"30"'),+ ]+ )@patch("ee.hogai.context.insight.query_executor.AssistantQueryExecutor.aexecute_query", new_callable=AsyncMock)- def test_search_shows_has_more_with_cursor(self, mock_execute):+ def test_search_shows_has_more_with_cursor(self, _name, limit, cursor, expected_cursor, mock_execute):+ # A full page is what the runner returns now, so the cursor has to advance by the page+ # size. Advancing by anything else re-reads or skips a trace on the next page.mock_execute.return_value = {- "results": [_make_trace()],+ "results": [_make_trace(trace_id=f"trace-{i}") for i in range(limit)],"hasMore": True,}tool = self._create_tool()- query = TracesQuery(dateRange=DateRange(date_from="-7d"), limit=1)- content, _ = tool._run(query=query, config=RunnableConfig(configurable={}))+ query = TracesQuery(dateRange=DateRange(date_from="-7d"), limit=limit)+ content, _ = tool._run(query=query, cursor=cursor, config=RunnableConfig(configurable={}))self.assertIn("More traces are available", content)- self.assertIn('cursor="1"', content)+ self.assertIn(f"cursor={expected_cursor}", content)@patch("ee.hogai.context.insight.query_executor.AssistantQueryExecutor.aexecute_query", new_callable=AsyncMock)def test_search_without_cursor_uses_offset_zero(self, mock_execute):@@ -113,8 +122,7 @@ class TestSearchLLMTracesTool(BaseTest):@patch("ee.hogai.context.insight.query_executor.AssistantQueryExecutor.aexecute_query", new_callable=AsyncMock)def test_search_trims_detection_row_and_advances_cursor(self, mock_execute):- # The query runner returns limit+1 results when hasMore=True.- # With limit=10, it returns 11 results. The tool trims to 10.+ # TracesQueryRunner trims the page, so this over-long response exercises the tool's own guard.mock_execute.return_value = {"results": [_make_trace(trace_id=f"trace-{i}") for i in range(11)],"hasMore": True,diff --git a/posthog/hogql_queries/ai/test/__snapshots__/test_traces_query_runner.ambr b/posthog/hogql_queries/ai/test/__snapshots__/test_traces_query_runner.ambrindex e54f6d0d0bb3..7eb96be37abc 100644--- a/posthog/hogql_queries/ai/test/__snapshots__/test_traces_query_runner.ambr+++ b/posthog/hogql_queries/ai/test/__snapshots__/test_traces_query_runner.ambr@@ -474,7 +474,7 @@GROUP BY trace_idHAVING and(lessOrEquals(min(toTimeZone(events.timestamp, 'UTC')), assumeNotNull(toDateTime('2025-01-16 00:00:59', 'UTC'))), greaterOrEquals(max(toTimeZone(events.timestamp, 'UTC')), assumeNotNull(toDateTime('2025-01-09 00:00:00', 'UTC'))))ORDER BY min(toTimeZone(events.timestamp, 'UTC')) DESC- LIMIT 10)+ LIMIT 9)LIMIT 100 SETTINGS readonly=2,max_execution_time=60,allow_experimental_object_type=1,@@ -514,11 +514,11 @@any(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'ai_support_impersonated'), ''), 'null'), '^"|"$', '')) AS is_support_trace,arrayFilter(x -> ifNull(notEquals(x, ''), 1), arrayDistinct(splitByChar(',', arrayStringConcat(groupArrayIf(toString(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_tools_called'), ''), 'null'), '^"|"$', '')), and(equals(events.event, '$ai_generation'), isNotNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_tools_called'), ''), 'null'), '^"|"$', '')), ifNull(notEquals(toString(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_tools_called'), ''), 'null'), '^"|"$', '')), ''), 1))), ',')))) AS toolsFROM events- WHERE and(equals(events.team_id, 99999), and(in(events.event, tuple('$ai_span', '$ai_generation', '$ai_embedding', '$ai_metric', '$ai_feedback', '$ai_trace')), and(greaterOrEquals(events.timestamp, assumeNotNull(toDateTime('2025-01-15 00:50:00', 'UTC'))), lessOrEquals(events.timestamp, assumeNotNull(toDateTime('2025-01-15 10:10:00', 'UTC'))))), in(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_trace_id'), ''), 'null'), '^"|"$', ''), tuple('trace_10', 'trace_9', 'trace_8', 'trace_7', 'trace_6', 'trace_5', 'trace_4', 'trace_3', 'trace_2', 'trace_1')))+ WHERE and(equals(events.team_id, 99999), and(in(events.event, tuple('$ai_span', '$ai_generation', '$ai_embedding', '$ai_metric', '$ai_feedback', '$ai_trace')), and(greaterOrEquals(events.timestamp, assumeNotNull(toDateTime('2025-01-15 01:50:00', 'UTC'))), lessOrEquals(events.timestamp, assumeNotNull(toDateTime('2025-01-15 10:10:00', 'UTC'))))), in(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_trace_id'), ''), 'null'), '^"|"$', ''), tuple('trace_10', 'trace_9', 'trace_8', 'trace_7', 'trace_6', 'trace_5', 'trace_4', 'trace_3', 'trace_2')))GROUP BY replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_trace_id'), ''), 'null'), '^"|"$', '')ORDER BY first_timestamp DESCLIMIT 5- OFFSET 5 SETTINGS readonly=2,+ OFFSET 4 SETTINGS readonly=2,max_execution_time=60,allow_experimental_object_type=1,max_ast_elements=4000000,@@ -546,7 +546,7 @@GROUP BY trace_idHAVING and(lessOrEquals(min(toTimeZone(events.timestamp, 'UTC')), assumeNotNull(toDateTime('2025-01-16 00:00:59', 'UTC'))), greaterOrEquals(max(toTimeZone(events.timestamp, 'UTC')), assumeNotNull(toDateTime('2025-01-09 00:00:00', 'UTC'))))ORDER BY min(toTimeZone(events.timestamp, 'UTC')) DESC- LIMIT 15)+ LIMIT 13)LIMIT 100 SETTINGS readonly=2,max_execution_time=60,allow_experimental_object_type=1,@@ -590,18 +590,18 @@GROUP BY replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_trace_id'), ''), 'null'), '^"|"$', '')ORDER BY first_timestamp DESCLIMIT 5- OFFSET 10 SETTINGS readonly=2,- max_execution_time=60,- allow_experimental_object_type=1,- max_ast_elements=4000000,- max_expanded_ast_elements=4000000,- max_bytes_before_external_group_by=0,- transform_null_in=1,- optimize_min_equality_disjunction_chain_length=4294967295,- optimize_rewrite_aggregate_function_with_if=0,- optimize_min_inequality_conjunction_chain_length=4294967295,- allow_experimental_join_condition=1,- use_hive_partitioning=0+ OFFSET 8 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ optimize_rewrite_aggregate_function_with_if=0,+ optimize_min_inequality_conjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0'''# ---# name: TestTracesQueryRunner.test_properties_filter_with_multiple_events_in_groupdiff --git a/posthog/hogql_queries/ai/test/test_traces_query_runner.py b/posthog/hogql_queries/ai/test/test_traces_query_runner.pyindex 989f94e9cce1..c2bce44a1512 100644--- a/posthog/hogql_queries/ai/test/test_traces_query_runner.py+++ b/posthog/hogql_queries/ai/test/test_traces_query_runner.py@@ -426,26 +426,15 @@ class TestTracesQueryRunner(ClickhouseTestMixin, BaseTest):)response = TracesQueryRunner(team=self.team, query=TracesQuery(limit=4, offset=0)).calculate()self.assertEqual(response.hasMore, True)- self.assertEqual(len(response.results), 5)- self.assertEqual(response.results[0].id, "trace_10")- self.assertEqual(response.results[1].id, "trace_9")- self.assertEqual(response.results[2].id, "trace_8")- self.assertEqual(response.results[3].id, "trace_7")- self.assertEqual(response.results[4].id, "trace_6")-- response = TracesQueryRunner(team=self.team, query=TracesQuery(limit=4, offset=5)).calculate()+ self.assertEqual([t.id for t in response.results], ["trace_10", "trace_9", "trace_8", "trace_7"])++ response = TracesQueryRunner(team=self.team, query=TracesQuery(limit=4, offset=4)).calculate()self.assertEqual(response.hasMore, True)- self.assertEqual(len(response.results), 5)- self.assertEqual(response.results[0].id, "trace_5")- self.assertEqual(response.results[1].id, "trace_4")- self.assertEqual(response.results[2].id, "trace_3")- self.assertEqual(response.results[3].id, "trace_2")- self.assertEqual(response.results[4].id, "trace_1")-- response = TracesQueryRunner(team=self.team, query=TracesQuery(limit=4, offset=10)).calculate()+ self.assertEqual([t.id for t in response.results], ["trace_6", "trace_5", "trace_4", "trace_3"])++ response = TracesQueryRunner(team=self.team, query=TracesQuery(limit=4, offset=8)).calculate()self.assertEqual(response.hasMore, False)- self.assertEqual(len(response.results), 1)- self.assertEqual(response.results[0].id, "trace_0")+ self.assertEqual([t.id for t in response.results], ["trace_2", "trace_1", "trace_0"])@freeze_time("2025-01-16T00:00:00Z")def test_pagination_with_multi_event_traces(self):@@ -481,20 +470,23 @@ class TestTracesQueryRunner(ClickhouseTestMixin, BaseTest):timestamp=datetime(2025, 1, 15, 10 - i),)- # Page 1 (limit=2, offset=0): returns limit+1=3 results, hasMore=Trueresponse = TracesQueryRunner(team=self.team, query=TracesQuery(limit=2, offset=0)).calculate()self.assertEqual(response.hasMore, True)page1_ids = [t.id for t in response.results]- self.assertEqual(page1_ids, ["trace_4", "trace_3", "trace_2"])+ self.assertEqual(page1_ids, ["trace_4", "trace_3"])- # Page 2 (limit=2, offset=3): returns remaining 2 traces, hasMore=False- response = TracesQueryRunner(team=self.team, query=TracesQuery(limit=2, offset=3)).calculate()- self.assertEqual(response.hasMore, False)+ response = TracesQueryRunner(team=self.team, query=TracesQuery(limit=2, offset=2)).calculate()+ self.assertEqual(response.hasMore, True)page2_ids = [t.id for t in response.results]- self.assertEqual(page2_ids, ["trace_1", "trace_0"])+ self.assertEqual(page2_ids, ["trace_2", "trace_1"])++ response = TracesQueryRunner(team=self.team, query=TracesQuery(limit=2, offset=4)).calculate()+ self.assertEqual(response.hasMore, False)+ page3_ids = [t.id for t in response.results]+ self.assertEqual(page3_ids, ["trace_0"])- # No trace ID appears on both pages- self.assertEqual(len(set(page1_ids) & set(page2_ids)), 0)+ # Walking the pages visits every trace exactly once+ self.assertEqual(page1_ids + page2_ids + page3_ids, ["trace_4", "trace_3", "trace_2", "trace_1", "trace_0"])@freeze_time("2025-01-16T00:00:00Z")def test_maps_all_fields(self):@@ -738,8 +730,8 @@ class TestTracesQueryRunner(ClickhouseTestMixin, BaseTest):result_ids = [t.id for t in response.results]self.assertEqual(len(response.results),- 5,- f"expected 5 in-window traces; got {len(response.results)}: {result_ids}",+ 4,+ f"expected a full page of in-window traces; got {len(response.results)}: {result_ids}",)for rid in result_ids:self.assertTrue(rid.startswith("in_window_"), f"unexpected trace id {rid} in results")@@ -2182,8 +2174,7 @@ class TestTracesQueryRunner(ClickhouseTestMixin, BaseTest):# Default ordering (timestamp DESC) should return newest firstresponse_default = TracesQueryRunner(team=self.team, query=TracesQuery(limit=5)).calculate()- # Paginator returns limit+1 to determine hasMore- self.assertGreaterEqual(len(response_default.results), 5)+ self.assertEqual(len(response_default.results), 5)# Should be in descending timestamp order (newest first)self.assertEqual(response_default.results[0].id, "trace_9")self.assertEqual(response_default.results[1].id, "trace_8")@@ -2191,8 +2182,7 @@ class TestTracesQueryRunner(ClickhouseTestMixin, BaseTest):# Random ordering should return different orderresponse_random = TracesQueryRunner(team=self.team, query=TracesQuery(limit=5, randomOrder=True)).calculate()- # Paginator returns limit+1 to determine hasMore- self.assertGreaterEqual(len(response_random.results), 5)+ self.assertEqual(len(response_random.results), 5)# Get IDs from random orderingrandom_ids = [trace.id for trace in response_random.results]diff --git a/posthog/hogql_queries/ai/traces_query_runner.py b/posthog/hogql_queries/ai/traces_query_runner.pyindex d0a1141b7eee..05109f66288f 100644--- a/posthog/hogql_queries/ai/traces_query_runner.py+++ b/posthog/hogql_queries/ai/traces_query_runner.py@@ -217,9 +217,9 @@ class TracesQueryRunner(AnalyticsQueryRunner[TracesQueryResponse]):columns: list[str] = query_result.columns or []sentiment_lookup = EMPTY_SENTIMENT_EVALUATION_LOOKUP- if self.query.includeSentiment and query_result.results and columns:+ if self.query.includeSentiment and self.paginator.results and columns:id_index = columns.index("id") if "id" in columns else -1- result_trace_ids = [str(row[id_index]) for row in query_result.results if id_index >= 0 and row[id_index]]+ result_trace_ids = [str(row[id_index]) for row in self.paginator.results if id_index >= 0 and row[id_index]]sentiment_lookup = SentimentEvaluationLookup(by_trace_id=load_trace_sentiment_evaluations(team=self.team,@@ -232,7 +232,9 @@ class TracesQueryRunner(AnalyticsQueryRunner[TracesQueryResponse]):by_generation_id={},)- results = self._map_results(columns, query_result.results, sentiment_lookup)+ # `paginator.results` drops the extra row the paginator fetches to compute `hasMore`,+ # so the response never carries more traces than the caller asked for.+ results = self._map_results(columns, self.paginator.results, sentiment_lookup)return TracesQueryResponse(columns=columns,