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.

feat(llma): add text search to traces list (#68617)

Carlos Marchal90f761197443
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index ebdbe4bcdcf9..2d3135818bab 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -6035,7 +6035,7 @@ snapshots:
scenes-app-insights-trendsslopegraph--trends-slope-graph--dark:
hash: v1.k794b7964.7b6bb33aaba2c334ded0898f97b7e316248e1639144c49e2039c880a16672ce3.RFWxmLTjalbL8Nszbl4hySEvS8xYi28uZJp2_E9EtxQ
scenes-app-insights-trendsslopegraph--trends-slope-graph--light:
- hash: v1.k794b7964.2aa9edc0701e25a08dc51f5d8ab61e2390b0d1a8dfb56f53153832a1ab5dd864._ZxWCehsllN_1Y0FGVmNeCTABpxnEoOiO3d6RUjOqXA
+ hash: v1.k794b7964.435ec6cacedc635d128f46c84567002eae11aa76758c130c39ff877197a75542.B6jsuSizg7bPm8wDE8N62O1k-C5CPomtRNXHXkSzwK8
scenes-app-insights-trendsslopegraph--trends-slope-graph-edit--dark:
hash: v1.k794b7964.a79e9f9b09872c1379566cac070987db5158b3f47129fe653ff1a4ec94e51ce5.WmkWzqWIPX_nHjS0tiGL8wPflEpxIM0itFt1G_ULgFM
scenes-app-insights-trendsslopegraph--trends-slope-graph-edit--light:
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 15f210d7a8a1..770367a76870 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -353,6 +353,7 @@ export const FEATURE_FLAGS = {
LLM_ANALYTICS_TRACE_NAVIGATION: 'llm-analytics-trace-navigation', // owner: #team-ai-observability
LLM_ANALYTICS_USER_FEEDBACK: 'llm-analytics-user-feedback', // owner: @adboio #team-surveys
LLM_OBSERVABILITY_SHOW_INPUT_OUTPUT: 'llm-observability-show-input-output', // owner: #team-ai-observability
+ LLM_OBSERVABILITY_TRACE_SEARCH: 'llm-observability-trace-search', // owner: #team-ai-observability
LOGS: 'logs', // owner: #team-logs
LOGS_ALERTING: 'logs-alerting', // owner: #team-logs
LOGS_GROUP_BY: 'logs-group-by', // owner: #team-logs
diff --git a/frontend/src/queries/nodes/DataTable/DataTable.tsx b/frontend/src/queries/nodes/DataTable/DataTable.tsx
index d84b42934131..1169ce3c86d0 100644
--- a/frontend/src/queries/nodes/DataTable/DataTable.tsx
+++ b/frontend/src/queries/nodes/DataTable/DataTable.tsx
@@ -58,6 +58,7 @@ import { OpenEditorButton } from '~/queries/nodes/Node/OpenEditorButton'
import { PersonPropertyFilters } from '~/queries/nodes/PersonsNode/PersonPropertyFilters'
import { PersonsSearch } from '~/queries/nodes/PersonsNode/PersonsSearch'
import { SessionPropertyFilters } from '~/queries/nodes/SessionsNode/SessionPropertyFilters'
+import { TracesSearch } from '~/queries/nodes/TracesQuery/TracesSearch'
import {
ActorsQuery,
AnyResponseType,
@@ -864,6 +865,9 @@ export function DataTable({
groupTypeLabel={context?.groupTypeLabel}
/>
) : null,
+ showSearch && sourceFeatures.has(QueryFeature.tracesSearch) ? (
+ <TracesSearch key="traces-search" query={query.source as TracesQuery} setQuery={setQuerySource} />
+ ) : null,
showPropertyFilter &&
sourceFeatures.has(QueryFeature.eventPropertyFilters) &&
!isSessionsQuery(query.source) ? (
diff --git a/frontend/src/queries/nodes/DataTable/queryFeatures.ts b/frontend/src/queries/nodes/DataTable/queryFeatures.ts
index 969d0e1b8757..462ce86c4b18 100644
--- a/frontend/src/queries/nodes/DataTable/queryFeatures.ts
+++ b/frontend/src/queries/nodes/DataTable/queryFeatures.ts
@@ -33,6 +33,7 @@ export enum QueryFeature {
linkDataButton,
personsSearch,
groupsSearch,
+ tracesSearch,
savedEventsQueries,
columnConfigurator,
resultIsArrayOfArrays,
@@ -152,6 +153,7 @@ export function getQueryFeatures(query: Node): Set<QueryFeature> {
features.add(QueryFeature.supportTracesFilters)
features.add(QueryFeature.columnConfigurator)
features.add(QueryFeature.displayResponseError)
+ features.add(QueryFeature.tracesSearch)
}
if (isEndpointsUsageTableQuery(query)) {
diff --git a/frontend/src/queries/nodes/TracesQuery/TracesSearch.tsx b/frontend/src/queries/nodes/TracesQuery/TracesSearch.tsx
new file mode 100644
index 000000000000..c4cb11698273
--- /dev/null
+++ b/frontend/src/queries/nodes/TracesQuery/TracesSearch.tsx
@@ -0,0 +1,30 @@
+import { LemonInput } from 'lib/lemon-ui/LemonInput/LemonInput'
+
+import { useDebouncedQuery } from '~/queries/hooks/useDebouncedQuery'
+import { TracesQuery } from '~/queries/schema/schema-general'
+
+interface TracesSearchProps {
+ query: TracesQuery
+ setQuery?: (query: TracesQuery) => void
+}
+
+export function TracesSearch({ query, setQuery }: TracesSearchProps): JSX.Element {
+ const { value, onChange } = useDebouncedQuery<TracesQuery, string>(
+ query,
+ setQuery,
+ (query) => query.searchTerm || '',
+ (query, value) => ({ ...query, searchTerm: value })
+ )
+
+ return (
+ <LemonInput
+ type="search"
+ className="min-w-60"
+ value={value}
+ placeholder="Search content"
+ data-attr="llm-traces-search"
+ disabled={!setQuery}
+ onChange={onChange}
+ />
+ )
+}
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index 3fc83214972b..f2407195c0ab 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -45149,6 +45149,9 @@
"response": {
"$ref": "#/definitions/TracesQueryResponse"
},
+ "searchTerm": {
+ "type": "string"
+ },
"showColumnConfigurator": {
"type": "boolean"
},
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index 1f375831e6d8..64553141ebde 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -5626,6 +5626,7 @@ export interface TracesQuery extends DataNode<TracesQueryResponse> {
includeSentiment?: boolean
/** Use random ordering instead of timestamp DESC. Useful for representative sampling to avoid recency bias. */
randomOrder?: boolean
+ searchTerm?: string
}
export interface TraceQueryResponse extends AnalyticsQueryResponseBase {
diff --git a/posthog/hogql_queries/ai/test/test_traces_query_runner.py b/posthog/hogql_queries/ai/test/test_traces_query_runner.py
index e08fbe2229ce..4daa39743839 100644
--- a/posthog/hogql_queries/ai/test/test_traces_query_runner.py
+++ b/posthog/hogql_queries/ai/test/test_traces_query_runner.py
@@ -8,6 +8,8 @@ from freezegun import freeze_time
from posthog.test.base import BaseTest, ClickhouseTestMixin, _create_event, _create_person, snapshot_clickhouse_queries
from unittest.mock import patch
+from parameterized import parameterized
+
from posthog.schema import (
DateRange,
EventPropertyFilter,
@@ -19,6 +21,9 @@ from posthog.schema import (
)
from posthog.hogql.constants import MAX_SELECT_TRACES_LIMIT_EXPORT, LimitContext
+from posthog.hogql.context import HogQLContext
+from posthog.hogql.modifiers import create_default_modifiers_for_team
+from posthog.hogql.printer import prepare_and_print_ast
from posthog.hogql_queries.ai.traces_query_runner import TracesQueryRunner
from posthog.models import PropertyDefinition, Team
@@ -853,6 +858,203 @@ class TestTracesQueryRunner(ClickhouseTestMixin, BaseTest):
self.assertEqual(len(response.results), 1)
self.assertEqual(response.results[0].id, "trace1")
+ def _create_search_fixture(self):
+ _create_person(distinct_ids=["person1"], team=self.team)
+ _create_ai_generation_event(
+ distinct_id="person1",
+ trace_id="trace_walrus",
+ team=self.team,
+ input="Where does the walrus sleep?",
+ output="On an ice floe.",
+ timestamp=datetime(2024, 12, 1, 0, 0),
+ )
+ _create_ai_generation_event(
+ distinct_id="person1",
+ trace_id="trace_penguin",
+ team=self.team,
+ input="Tell me about penguins.",
+ output="Penguins prefer icebergs.",
+ timestamp=datetime(2024, 12, 1, 0, 10),
+ )
+ _create_ai_generation_event(
+ distinct_id="person1",
+ trace_id="trace_paris",
+ team=self.team,
+ input="What is the capital of France?",
+ output="Paris.",
+ timestamp=datetime(2024, 12, 1, 0, 20),
+ )
+ # Older SDKs emit $ai_output (the `output` column) instead of $ai_output_choices.
+ _create_ai_generation_event(
+ distinct_id="person1",
+ trace_id="trace_albatross",
+ team=self.team,
+ input="What flies at night?",
+ properties={"$ai_output": {"role": "assistant", "content": "The albatross flies at night."}},
+ timestamp=datetime(2024, 12, 1, 0, 30),
+ )
+
+ def _run_search_query(self, search_term: str, **kwargs: Any):
+ return TracesQueryRunner(
+ team=self.team,
+ query=TracesQuery(
+ dateRange=DateRange(date_from="2024-12-01T00:00:00Z", date_to="2024-12-01T01:00:00Z"),
+ searchTerm=search_term,
+ **kwargs,
+ ),
+ ).calculate()
+
+ @parameterized.expand(
+ [
+ ("input_match", "walrus", {"trace_walrus"}),
+ ("output_choices_match", "icebergs", {"trace_penguin"}),
+ ("legacy_output_match", "albatross", {"trace_albatross"}),
+ ("case_insensitive", "WALRUS", {"trace_walrus"}),
+ ("multiple_traces", "ice", {"trace_walrus", "trace_penguin"}),
+ ("no_match", "platypus", set()),
+ ("blank_is_ignored", " ", {"trace_walrus", "trace_penguin", "trace_paris", "trace_albatross"}),
+ ]
+ )
+ def test_search_term_filters_by_generation_content(self, _name, search_term, expected_trace_ids):
+ self._create_search_fixture()
+
+ response = self._run_search_query(search_term)
+ self.assertEqual({trace.id for trace in response.results}, expected_trace_ids)
+
+ @parameterized.expand(
+ [
+ ("percent", "100% off", "Discount is 100% off", "Discount is 100x off today"),
+ ("underscore", "sold a_b units", "We sold a_b units", "We sold aXb units"),
+ ]
+ )
+ def test_search_term_treats_like_metacharacters_literally(self, _name, search_term, matching, non_matching):
+ _create_person(distinct_ids=["person1"], team=self.team)
+ _create_ai_generation_event(
+ distinct_id="person1",
+ trace_id="trace_literal",
+ team=self.team,
+ input=matching,
+ timestamp=datetime(2024, 12, 1, 0, 0),
+ )
+ _create_ai_generation_event(
+ distinct_id="person1",
+ trace_id="trace_wildcard",
+ team=self.team,
+ input=non_matching,
+ timestamp=datetime(2024, 12, 1, 0, 10),
+ )
+
+ response = self._run_search_query(search_term)
+ self.assertEqual({trace.id for trace in response.results}, {"trace_literal"})
+
+ def test_search_term_combines_with_property_filters(self):
+ _create_person(distinct_ids=["person1"], team=self.team)
+ # Filter and search match different events of trace_both: they must combine at trace level.
+ _create_ai_generation_event(
+ distinct_id="person1",
+ trace_id="trace_both",
+ team=self.team,
+ input="Contains the needle.",
+ timestamp=datetime(2024, 12, 1, 0, 0),
+ )
+ _create_ai_generation_event(
+ distinct_id="person1",
+ trace_id="trace_both",
+ team=self.team,
+ input="Unrelated content.",
+ properties={"foo": "bar"},
+ timestamp=datetime(2024, 12, 1, 0, 1),
+ )
+ _create_ai_generation_event(
+ distinct_id="person1",
+ trace_id="trace_search_only",
+ team=self.team,
+ input="Contains the needle.",
+ timestamp=datetime(2024, 12, 1, 0, 10),
+ )
+ _create_ai_generation_event(
+ distinct_id="person1",
+ trace_id="trace_filter_only",
+ team=self.team,
+ input="Unrelated content.",
+ properties={"foo": "bar"},
+ timestamp=datetime(2024, 12, 1, 0, 20),
+ )
+
+ response = self._run_search_query(
+ "needle",
+ properties=[EventPropertyFilter(key="foo", value="bar", operator=PropertyOperator.EXACT)],
+ )
+ self.assertEqual({trace.id for trace in response.results}, {"trace_both"})
+
+ def test_search_term_respects_date_range(self):
+ _create_person(distinct_ids=["person1"], team=self.team)
+ _create_ai_generation_event(
+ distinct_id="person1",
+ trace_id="trace_in_range",
+ team=self.team,
+ input="Contains the needle.",
+ timestamp=datetime(2024, 12, 1, 0, 0),
+ )
+ _create_ai_generation_event(
+ distinct_id="person1",
+ trace_id="trace_out_of_range",
+ team=self.team,
+ input="Contains the needle.",
+ timestamp=datetime(2024, 12, 2, 5, 0),
+ )
+
+ response = self._run_search_query("needle")
+ self.assertEqual({trace.id for trace in response.results}, {"trace_in_range"})
+
+ def test_search_filter_prints_as_global_in(self):
+ # A plain IN passes single-node CI but re-executes the subquery per events
+ # shard in production; only the printed SQL can catch the downgrade.
+ runner = TracesQueryRunner(
+ team=self.team,
+ query=TracesQuery(
+ dateRange=DateRange(date_from="2024-12-01T00:00:00Z", date_to="2024-12-01T01:00:00Z"),
+ searchTerm="needle",
+ ),
+ )
+ context = HogQLContext(
+ team_id=self.team.pk,
+ enable_select_queries=True,
+ modifiers=create_default_modifiers_for_team(self.team),
+ )
+ sql, _ = prepare_and_print_ast(runner._build_trace_ids_query(), context, "clickhouse")
+ # The printer emits GLOBAL IN in function form.
+ assert "globalIn(" in sql
+ assert "ai_events" in sql
+
+ def test_search_candidate_cap_applies_after_filters(self):
+ # With the cap at 1, the more recent trace matches the term but not the property
+ # filter. Drawing the cap from the filtered set keeps the older matching trace;
+ # capping raw text matches first would keep the recent one and empty the page.
+ _create_person(distinct_ids=["person1"], team=self.team)
+ _create_ai_generation_event(
+ distinct_id="person1",
+ trace_id="trace_match",
+ team=self.team,
+ input="Contains the needle.",
+ properties={"foo": "bar"},
+ timestamp=datetime(2024, 12, 1, 0, 0),
+ )
+ _create_ai_generation_event(
+ distinct_id="person1",
+ trace_id="trace_recent",
+ team=self.team,
+ input="Contains the needle.",
+ timestamp=datetime(2024, 12, 1, 0, 30),
+ )
+
+ with patch("posthog.hogql_queries.ai.traces_query_runner.SEARCH_CANDIDATE_TRACE_LIMIT", 1):
+ response = self._run_search_query(
+ "needle",
+ properties=[EventPropertyFilter(key="foo", value="bar", operator=PropertyOperator.EXACT)],
+ )
+ self.assertEqual({trace.id for trace in response.results}, {"trace_match"})
+
def test_model_parameters(self):
_create_person(distinct_ids=["person1"], team=self.team, properties={"foo": "bar"})
_create_ai_generation_event(
diff --git a/posthog/hogql_queries/ai/traces_query_runner.py b/posthog/hogql_queries/ai/traces_query_runner.py
index 5f970e1e87c7..283e29f47e7e 100644
--- a/posthog/hogql_queries/ai/traces_query_runner.py
+++ b/posthog/hogql_queries/ai/traces_query_runner.py
@@ -37,6 +37,14 @@ from posthog.hogql_queries.utils.query_date_range import QueryDateRange
logger = structlog.get_logger(__name__)
+# Recency-ordered cap on the filtered candidate set: matches beyond it drop on deep
+# pages or when a group filter (not pushed into the subquery) discards most candidates.
+SEARCH_CANDIDATE_TRACE_LIMIT = 100_000
+
+
+def _escape_like_pattern(term: str) -> str:
+ return term.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
+
class TracesQueryDateRange(QueryDateRange):
"""
@@ -92,59 +100,60 @@ class TracesQueryRunner(AnalyticsQueryRunner[TracesQueryResponse]):
offset=self.query.offset,
)
- def _get_trace_ids(self) -> tuple[list[str], datetime | None, datetime | None]:
- """Execute a separate query to get relevant trace IDs and their time range."""
- with self.timings.measure("traces_query_trace_ids_execute"), tags_context(product=Product.LLM_ANALYTICS):
- # Calculate max number of events needed with current offset and limit
- limit_value = self.paginator.limit
- offset_value = self.paginator.offset
- pagination_limit = limit_value + offset_value + 1
-
- # The subquery ordering must match the main query's ORDER BY first_timestamp DESC
- # (where first_timestamp = min(timestamp)). Using a different ordering here (e.g.
- # max(timestamp)) causes pagination bugs: the subquery selects trace IDs in one
- # order but the main query re-sorts them differently, so OFFSET-based slicing
- # produces overlapping or missing traces across pages.
- order_clause = "rand()" if self.query.randomOrder else "min(timestamp) DESC"
-
- # The HAVING clause enforces the same overlap semantics as the post-filter
- # in `_map_results` (a trace counts if any of its events overlap the user
- # window). Without it, the LIMIT runs over the buffered window — so for a
- # high-volume team a `date_to`-anchored filter (e.g. "yesterday") can have
- # its entire LIMIT consumed by traces in the trailing +10 min capture buffer,
- # which the post-filter then drops, producing an empty page.
- trace_ids_query = parse_select(
- f"""
+ def _build_trace_ids_query(self) -> ast.SelectQuery | ast.SelectSetQuery:
+ # Calculate max number of events needed with current offset and limit
+ limit_value = self.paginator.limit
+ offset_value = self.paginator.offset
+ pagination_limit = limit_value + offset_value + 1
+
+ # The subquery ordering must match the main query's ORDER BY first_timestamp DESC
+ # (where first_timestamp = min(timestamp)). Using a different ordering here (e.g.
+ # max(timestamp)) causes pagination bugs: the subquery selects trace IDs in one
+ # order but the main query re-sorts them differently, so OFFSET-based slicing
+ # produces overlapping or missing traces across pages.
+ order_clause = "rand()" if self.query.randomOrder else "min(timestamp) DESC"
+
+ # The HAVING clause enforces the same overlap semantics as the post-filter
+ # in `_map_results` (a trace counts if any of its events overlap the user
+ # window). Without it, the LIMIT runs over the buffered window — so for a
+ # high-volume team a `date_to`-anchored filter (e.g. "yesterday") can have
+ # its entire LIMIT consumed by traces in the trailing +10 min capture buffer,
+ # which the post-filter then drops, producing an empty page.
+ return parse_select(
+ f"""
+ SELECT
+ groupArray(trace_id) as trace_ids,
+ min(first_ts) as min_timestamp,
+ max(last_ts) as max_timestamp
+ FROM (
SELECT
- groupArray(trace_id) as trace_ids,
- min(first_ts) as min_timestamp,
- max(last_ts) as max_timestamp
- FROM (
- SELECT
- properties.$ai_trace_id as trace_id,
- min(timestamp) as first_ts,
- max(timestamp) as last_ts
- FROM events
- WHERE event IN ('$ai_span', '$ai_generation', '$ai_embedding', '$ai_metric', '$ai_feedback', '$ai_trace')
- AND {{conditions}}
- GROUP BY trace_id
- HAVING min(timestamp) <= {{unbuffered_date_to}}
- AND max(timestamp) >= {{unbuffered_date_from}}
- ORDER BY {order_clause}
- LIMIT {{limit}}
- )
- """,
+ properties.$ai_trace_id as trace_id,
+ min(timestamp) as first_ts,
+ max(timestamp) as last_ts
+ FROM events
+ WHERE event IN ('$ai_span', '$ai_generation', '$ai_embedding', '$ai_metric', '$ai_feedback', '$ai_trace')
+ AND {{conditions}}
+ GROUP BY trace_id
+ HAVING min(timestamp) <= {{unbuffered_date_to}}
+ AND max(timestamp) >= {{unbuffered_date_from}}
+ ORDER BY {order_clause}
+ LIMIT {{limit}}
)
+ """,
+ placeholders={
+ "conditions": self._get_subquery_filter(),
+ "limit": ast.Constant(value=pagination_limit),
+ "unbuffered_date_from": self._date_range.date_from_for_filtering_as_hogql(),
+ "unbuffered_date_to": self._date_range.date_to_for_filtering_as_hogql(),
+ },
+ )
+ def _get_trace_ids(self) -> tuple[list[str], datetime | None, datetime | None]:
+ """Execute a separate query to get relevant trace IDs and their time range."""
+ with self.timings.measure("traces_query_trace_ids_execute"), tags_context(product=Product.LLM_ANALYTICS):
trace_ids_result = execute_hogql_query(
query_type="TracesQuery_TraceIds",
- query=trace_ids_query,
- placeholders={
- "conditions": self._get_subquery_filter(),
- "limit": ast.Constant(value=pagination_limit),
- "unbuffered_date_from": self._date_range.date_from_for_filtering_as_hogql(),
- "unbuffered_date_to": self._date_range.date_to_for_filtering_as_hogql(),
- },
+ query=self._build_trace_ids_query(),
team=self.team,
user=self.user,
timings=self.timings,
@@ -527,8 +536,88 @@ class TracesQueryRunner(AnalyticsQueryRunner[TracesQueryResponse]):
)
)
+ search_filter = self._get_search_filter()
+ if search_filter is not None:
+ exprs.append(search_filter)
+
return ast.And(exprs=exprs)
+ def _get_search_filter(self) -> ast.Expr | None:
+ """Content columns live only in ai_events (a satellite cluster), so this
+ semijoins with GLOBAL IN. Person/property filters are pushed in too so the
+ recency cap is drawn from the already-filtered set, not from raw text matches
+ the outer scan later discards; group filters stay outer ($group_N isn't a
+ column here). Each condition is a trace-level countIf so a term and a filter
+ matching different events of the same trace still count.
+ """
+ search_term = (self.query.searchTerm or "").strip()
+ if not search_term:
+ return None
+
+ pattern = ast.Constant(value=f"%{_escape_like_pattern(search_term)}%")
+ search_subquery = cast(
+ ast.SelectQuery,
+ parse_select(
+ """
+ SELECT trace_id
+ FROM posthog.ai_events
+ WHERE timestamp >= {date_from} AND timestamp <= {date_to}
+ GROUP BY trace_id
+ HAVING countIf(
+ event IN ('$ai_generation', '$ai_embedding')
+ AND (input ILIKE {pattern} OR output ILIKE {pattern} OR output_choices ILIKE {pattern})
+ ) > 0
+ ORDER BY max(timestamp) DESC
+ LIMIT {candidate_limit}
+ """,
+ placeholders={
+ "date_from": self._date_range.date_from_as_hogql(),
+ "date_to": self._date_range.date_to_as_hogql(),
+ "pattern": pattern,
+ "candidate_limit": ast.Constant(value=SEARCH_CANDIDATE_TRACE_LIMIT),
+ },
+ ),
+ )
+
+ candidate_filters = self._search_candidate_filters()
+ if candidate_filters:
+ base_having = search_subquery.having
+ assert base_having is not None, "parsed search subquery always has a HAVING clause"
+ search_subquery.having = ast.And(
+ exprs=[
+ base_having,
+ *(
+ ast.CompareOperation(
+ op=ast.CompareOperationOp.Gt,
+ left=ast.Call(name="countIf", args=[expr]),
+ right=ast.Constant(value=0),
+ )
+ for expr in candidate_filters
+ ),
+ ]
+ )
+
+ return ast.CompareOperation(
+ op=ast.CompareOperationOp.GlobalIn,
+ left=ast.Field(chain=["properties", "$ai_trace_id"]),
+ right=search_subquery,
+ )
+
+ def _search_candidate_filters(self) -> list[ast.Expr]:
+ filters: list[ast.Expr] = []
+ properties_filter = self._get_properties_filter()
+ if properties_filter is not None:
+ filters.append(properties_filter)
+ if self.query.personId:
+ filters.append(
+ ast.CompareOperation(
+ op=ast.CompareOperationOp.Eq,
+ left=ast.Field(chain=["person_id"]),
+ right=ast.Constant(value=self.query.personId),
+ )
+ )
+ return filters
+
def _get_properties_filter(self) -> ast.Expr | None:
property_filters: list[ast.Expr] = []
if self.query.properties:
diff --git a/posthog/schema.py b/posthog/schema.py
index 2f264360abd0..4cdad8ac670b 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -21628,6 +21628,7 @@ class TracesQuery(BaseModel):
),
)
response: TracesQueryResponse | None = None
+ searchTerm: str | None = None
showColumnConfigurator: bool | None = None
tags: QueryLogTags | None = None
version: float | None = Field(default=None, description="version of the node, used for schema migrations")
diff --git a/products/ai_observability/frontend/AIObservabilityTracesScene.tsx b/products/ai_observability/frontend/AIObservabilityTracesScene.tsx
index bf202acf75f5..2e3ca064206f 100644
--- a/products/ai_observability/frontend/AIObservabilityTracesScene.tsx
+++ b/products/ai_observability/frontend/AIObservabilityTracesScene.tsx
@@ -46,10 +46,17 @@ export function AIObservabilityTraces(): JSX.Element {
const { applyUrlState, setShouldFilterSupportTraces } = useActions(aiObservabilitySharedLogic)
const { dateFilter, propertyFilters: currentPropertyFilters } = useValues(aiObservabilitySharedLogic)
const { tracesQuery } = useValues(aiObservabilityTracesTabLogic)
+ const appliedSearchTerm = isTracesQuery(tracesQuery.source) ? tracesQuery.source.searchTerm : undefined
const baseContext = useTracesQueryContext()
const context: QueryContext<DataTableNode> = {
...baseContext,
+ ...(appliedSearchTerm
+ ? {
+ emptyStateHeading: 'No traces matched your search',
+ emptyStateDetail: 'Try a different search term, date range, or filters.',
+ }
+ : {}),
customActions: <TracesOptionsMenu key="traces-options-menu" />,
}
@@ -69,15 +76,13 @@ export function AIObservabilityTraces(): JSX.Element {
// separate — it cannot contribute to the URL-change counter.
setShouldFilterSupportTraces(query.source.filterSupportTraces ?? true)
- // Batch the remaining three URL-synced fields into a single
- // applyUrlState dispatch so the DataTable's setQuery emits
- // one URL change instead of three.
applyUrlState(
buildApplyUrlStatePayload({
dateFrom: query.source.dateRange?.date_from || null,
dateTo: query.source.dateRange?.date_to || null,
shouldFilterTestAccounts: query.source.filterTestAccounts || false,
propertyFilters: query.source.properties || [],
+ searchQuery: query.source.searchTerm || '',
currentDateFilter: dateFilter,
currentPropertyFilters,
})
diff --git a/products/ai_observability/frontend/aiObservabilityLogic.test.ts b/products/ai_observability/frontend/aiObservabilityLogic.test.ts
index b02f84d5e087..6bd8d3edfdd7 100644
--- a/products/ai_observability/frontend/aiObservabilityLogic.test.ts
+++ b/products/ai_observability/frontend/aiObservabilityLogic.test.ts
@@ -4,10 +4,13 @@ import { router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
import api from 'lib/api'
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { emptySceneParams } from 'scenes/scenes'
import { urls } from 'scenes/urls'
import { productRedirects } from '~/products'
+import { isTracesQuery } from '~/queries/utils'
import { initKeaTests } from '~/test/init'
import { PropertyFilterType, PropertyOperator } from '~/types'
@@ -158,6 +161,7 @@ describe('aiObservabilitySharedLogic', () => {
])
logic.actions.setDates('-30d', '-1d')
logic.actions.setShouldFilterTestAccounts(true)
+ logic.actions.setSearchQuery('walrus')
// Navigate to another tab without params
router.actions.push(urls.aiObservabilityGenerations())
@@ -170,8 +174,61 @@ describe('aiObservabilitySharedLogic', () => {
dateTo: null,
},
shouldFilterTestAccounts: false,
+ searchQuery: '',
})
})
+
+ it('syncs the trace content search between the URL, state, and traces query', () => {
+ featureFlagLogic.mount()
+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.LLM_OBSERVABILITY_TRACE_SEARCH], {
+ [FEATURE_FLAGS.LLM_OBSERVABILITY_TRACE_SEARCH]: true,
+ })
+
+ router.actions.push(urls.aiObservabilityTraces(), { trace_search: 'walrus' })
+ expectLogic(logic).toMatchValues({ searchQuery: 'walrus' })
+
+ const tabLogic = aiObservabilityTracesTabLogic()
+ tabLogic.mount()
+ const source = tabLogic.values.tracesQuery.source
+ expect(isTracesQuery(source) && source.searchTerm).toBe('walrus')
+ tabLogic.unmount()
+
+ logic.actions.setSearchQuery('penguin')
+ expect(router.values.searchParams).toMatchObject({ trace_search: 'penguin' })
+
+ logic.actions.setSearchQuery('')
+ expect(router.values.searchParams).not.toHaveProperty('trace_search')
+ })
+
+ it('does not apply the search to the traces query when the flag is off', () => {
+ // A shared URL must not invisibly filter a list with no visible search box.
+ featureFlagLogic.mount()
+ featureFlagLogic.actions.setFeatureFlags([], {})
+
+ router.actions.push(urls.aiObservabilityTraces(), { trace_search: 'walrus' })
+ expectLogic(logic).toMatchValues({ searchQuery: 'walrus' })
+
+ const tabLogic = aiObservabilityTracesTabLogic()
+ tabLogic.mount()
+ const source = tabLogic.values.tracesQuery.source
+ expect(isTracesQuery(source) && source.searchTerm).toBeUndefined()
+ tabLogic.unmount()
+ })
+
+ it('keeps the search when URL state applies without a searchQuery', () => {
+ // Payloads built by other tabs omit searchQuery — they must not clear it.
+ logic.actions.setSearchQuery('walrus')
+ logic.actions.applyUrlState({
+ propertyFilters: [],
+ dateFrom: '-14d',
+ dateTo: null,
+ shouldFilterTestAccounts: false,
+ datesChanged: true,
+ })
+
+ expectLogic(logic).toMatchValues({ searchQuery: 'walrus' })
+ expect(router.values.searchParams).toMatchObject({ trace_search: 'walrus' })
+ })
})
describe('aiObservabilitySessionsViewLogic', () => {
diff --git a/products/ai_observability/frontend/aiObservabilitySharedLogic.ts b/products/ai_observability/frontend/aiObservabilitySharedLogic.ts
index 9ca546d537b6..49c3e6e68cf0 100644
--- a/products/ai_observability/frontend/aiObservabilitySharedLogic.ts
+++ b/products/ai_observability/frontend/aiObservabilitySharedLogic.ts
@@ -26,7 +26,9 @@ export const AI_OBSERVABILITY_DATA_COLLECTION_NODE_ID = 'ai-observability-data'
// Params this logic owns and rewrites when its state changes. Everything else is
// passed through untouched — other logics (e.g. reviews' `review_*`, queues'
// `queue_*`) own their params, so an allowlist here must never strip them.
-const SHARED_PARAMS = new Set(['filters', 'date_from', 'date_to', 'filter_test_accounts'])
+// `trace_search`, not `search`: the trace view owns `search` for its in-trace
+// search, and back navigation would leak it into the list's content filter.
+const SHARED_PARAMS = new Set(['filters', 'date_from', 'date_to', 'filter_test_accounts', 'trace_search'])
// Params from the trace view that must not linger on list-tab URLs.
const STALE_PARAMS = new Set(['event', 'timestamp', 'msg'])
@@ -71,6 +73,7 @@ export interface ApplyUrlStatePayload {
dateFrom: string | null
dateTo: string | null
shouldFilterTestAccounts: boolean
+ searchQuery?: string
datesChanged: boolean
}
@@ -79,6 +82,7 @@ interface BuildApplyUrlStatePayloadInput {
dateTo: string | null
shouldFilterTestAccounts: boolean
propertyFilters: AnyPropertyFilter[]
+ searchQuery?: string
currentDateFilter: { dateFrom: string | null; dateTo: string | null }
currentPropertyFilters: AnyPropertyFilter[]
}
@@ -94,6 +98,7 @@ export function buildApplyUrlStatePayload({
dateTo,
shouldFilterTestAccounts,
propertyFilters,
+ searchQuery,
currentDateFilter,
currentPropertyFilters,
}: BuildApplyUrlStatePayloadInput): ApplyUrlStatePayload {
@@ -104,6 +109,7 @@ export function buildApplyUrlStatePayload({
dateFrom,
dateTo,
shouldFilterTestAccounts,
+ searchQuery,
datesChanged: dateFrom !== currentDateFilter.dateFrom || dateTo !== currentDateFilter.dateTo,
}
}
@@ -134,6 +140,7 @@ export const aiObservabilitySharedLogic = kea<aiObservabilitySharedLogicType>([
setShouldFilterTestAccounts: (shouldFilterTestAccounts: boolean) => ({ shouldFilterTestAccounts }),
setShouldFilterSupportTraces: (shouldFilterSupportTraces: boolean) => ({ shouldFilterSupportTraces }),
setPropertyFilters: (propertyFilters: AnyPropertyFilter[]) => ({ propertyFilters }),
+ setSearchQuery: (searchQuery: string) => ({ searchQuery }),
// Batched action for URL-to-state sync. Dispatched once from urlToAction
// or scene-level setQuery handlers instead of multiple individual actions,
// producing a single actionToUrl URL change instead of 3-4 separate ones.
@@ -186,6 +193,14 @@ export const aiObservabilitySharedLogic = kea<aiObservabilitySharedLogicType>([
applyUrlState: (_, { propertyFilters }) => propertyFilters,
},
],
+
+ searchQuery: [
+ '' as string,
+ {
+ setSearchQuery: (_, { searchQuery }) => searchQuery,
+ applyUrlState: (state, { searchQuery }) => searchQuery ?? state,
+ },
+ ],
}),
loaders(() => ({
@@ -263,7 +278,7 @@ export const aiObservabilitySharedLogic = kea<aiObservabilitySharedLogicType>([
urlToAction(({ actions, values, cache }) => {
function applySearchParams(searchParams: Record<string, unknown>): void {
- const { filters, date_from, date_to, filter_test_accounts } = searchParams
+ const { filters, date_from, date_to, filter_test_accounts, trace_search } = searchParams
const parsedFilters = isAnyPropertyFilters(filters) ? filters : []
const newDateFrom = (date_from as string | null) || INITIAL_EVENTS_DATE_FROM
@@ -271,12 +286,14 @@ export const aiObservabilitySharedLogic = kea<aiObservabilitySharedLogicType>([
const filterTestAccountsValue = [true, 'true', 1, '1'].includes(
filter_test_accounts as string | number | boolean
)
+ const newSearchQuery = typeof trace_search === 'string' ? trace_search : ''
const filtersChanged = !objectsEqual(parsedFilters, values.propertyFilters)
const datesChanged = newDateFrom !== values.dateFilter.dateFrom || newDateTo !== values.dateFilter.dateTo
const testAccountsChanged = filterTestAccountsValue !== values.shouldFilterTestAccounts
+ const searchQueryChanged = newSearchQuery !== values.searchQuery
- if (filtersChanged || datesChanged || testAccountsChanged) {
+ if (filtersChanged || datesChanged || testAccountsChanged || searchQueryChanged) {
// Dispatch a single batched action so actionToUrl produces one URL
// change instead of up to 3 separate ones. The actionToUrl handler
// for applyUrlState rewrites the shared params and drops stale
@@ -286,6 +303,7 @@ export const aiObservabilitySharedLogic = kea<aiObservabilitySharedLogicType>([
dateFrom: newDateFrom,
dateTo: newDateTo,
shouldFilterTestAccounts: filterTestAccountsValue,
+ searchQuery: newSearchQuery,
datesChanged,
})
} else {
@@ -361,12 +379,12 @@ export const aiObservabilitySharedLogic = kea<aiObservabilitySharedLogicType>([
}
function sharedSearchParams(): Record<string, unknown> {
- const { filters, date_from, date_to, filter_test_accounts } = router.values.searchParams
- return { ...passthroughSearchParams(), filters, date_from, date_to, filter_test_accounts }
+ const { filters, date_from, date_to, filter_test_accounts, trace_search } = router.values.searchParams
+ return { ...passthroughSearchParams(), filters, date_from, date_to, filter_test_accounts, trace_search }
}
return {
- applyUrlState: ({ propertyFilters, dateFrom, dateTo, shouldFilterTestAccounts }) => [
+ applyUrlState: ({ propertyFilters, dateFrom, dateTo, shouldFilterTestAccounts, searchQuery }) => [
router.values.location.pathname,
{
...passthroughSearchParams(),
@@ -374,6 +392,8 @@ export const aiObservabilitySharedLogic = kea<aiObservabilitySharedLogicType>([
date_from: dateFrom === INITIAL_EVENTS_DATE_FROM ? undefined : dateFrom || undefined,
date_to: dateTo || undefined,
filter_test_accounts: shouldFilterTestAccounts ? 'true' : undefined,
+ trace_search:
+ (searchQuery ?? (router.values.searchParams.trace_search as string | undefined)) || undefined,
},
],
setPropertyFilters: ({ propertyFilters }) => [
@@ -398,6 +418,13 @@ export const aiObservabilitySharedLogic = kea<aiObservabilitySharedLogicType>([
filter_test_accounts: shouldFilterTestAccounts ? 'true' : undefined,
},
],
+ setSearchQuery: ({ searchQuery }) => [
+ router.values.location.pathname,
+ {
+ ...sharedSearchParams(),
+ trace_search: searchQuery || undefined,
+ },
+ ],
}
}),
diff --git a/products/ai_observability/frontend/tabs/aiObservabilityTracesTabLogic.ts b/products/ai_observability/frontend/tabs/aiObservabilityTracesTabLogic.ts
index bd1076a7d046..ff34572078f1 100644
--- a/products/ai_observability/frontend/tabs/aiObservabilityTracesTabLogic.ts
+++ b/products/ai_observability/frontend/tabs/aiObservabilityTracesTabLogic.ts
@@ -28,7 +28,7 @@ export const aiObservabilityTracesTabLogic = kea<aiObservabilityTracesTabLogicTy
connect((props: AIObservabilityTracesTabLogicProps) => ({
values: [
aiObservabilitySharedLogic({ personId: props.personId, group: props.group }),
- ['dateFilter', 'shouldFilterTestAccounts', 'shouldFilterSupportTraces', 'propertyFilters'],
+ ['dateFilter', 'shouldFilterTestAccounts', 'shouldFilterSupportTraces', 'propertyFilters', 'searchQuery'],
groupsModel,
['groupsTaxonomicTypes'],
featureFlagLogic,
@@ -79,6 +79,7 @@ export const aiObservabilityTracesTabLogic = kea<aiObservabilityTracesTabLogicTy
s.shouldFilterTestAccounts,
s.shouldFilterSupportTraces,
s.propertyFilters,
+ s.searchQuery,
(_, props) => props.personId,
(_, props) => props.group,
s.groupsTaxonomicTypes,
@@ -92,6 +93,7 @@ export const aiObservabilityTracesTabLogic = kea<aiObservabilityTracesTabLogicTy
shouldFilterTestAccounts: boolean,
shouldFilterSupportTraces: boolean,
propertyFilters,
+ searchQuery: string,
personId: string | undefined,
group: { groupKey: string; groupTypeIndex: number } | undefined,
groupsTaxonomicTypes: TaxonomicFilterGroupType[],
@@ -116,6 +118,9 @@ export const aiObservabilityTracesTabLogic = kea<aiObservabilityTracesTabLogicTy
filterTestAccounts: shouldFilterTestAccounts ?? false,
filterSupportTraces,
properties: propertyFilters,
+ searchTerm: featureFlags[FEATURE_FLAGS.LLM_OBSERVABILITY_TRACE_SEARCH]
+ ? searchQuery || undefined
+ : undefined,
personId: personId ?? undefined,
groupKey: group?.groupKey,
groupTypeIndex: group?.groupTypeIndex,
@@ -139,7 +144,7 @@ export const aiObservabilityTracesTabLogic = kea<aiObservabilityTracesTabLogicTy
],
showDateRange: true,
showReload: true,
- showSearch: true,
+ showSearch: !!featureFlags[FEATURE_FLAGS.LLM_OBSERVABILITY_TRACE_SEARCH],
showTestAccountFilters: true,
showExport: false,
showOpenEditorButton: false,
diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.ts
index f1926cb3b4a4..8da80bc18390 100644
--- a/products/dashboards/frontend/generated/api.schemas.ts
+++ b/products/dashboards/frontend/generated/api.schemas.ts
@@ -7375,6 +7375,7 @@ export interface TracesQueryApi {
/** Use random ordering instead of timestamp DESC. Useful for representative sampling to avoid recency bias. */
randomOrder?: boolean | null
response?: TracesQueryResponseApi | null
+ searchTerm?: string | null
showColumnConfigurator?: boolean | null
tags?: QueryLogTagsApi | null
/** version of the node, used for schema migrations */
diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.ts
index 56e728495f96..4fa2af7ca410 100644
--- a/products/product_analytics/frontend/generated/api.schemas.ts
+++ b/products/product_analytics/frontend/generated/api.schemas.ts
@@ -6729,6 +6729,7 @@ export interface TracesQueryApi {
/** Use random ordering instead of timestamp DESC. Useful for representative sampling to avoid recency bias. */
randomOrder?: boolean | null
response?: TracesQueryResponseApi | null
+ searchTerm?: string | null
showColumnConfigurator?: boolean | null
tags?: QueryLogTagsApi | null
/** version of the node, used for schema migrations */
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 37bb67348ac6..c8985a78e647 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -7084,6 +7084,7 @@ export namespace Schemas {
/** Use random ordering instead of timestamp DESC. Useful for representative sampling to avoid recency bias. */
randomOrder?: boolean | null;
response?: TracesQueryResponse | null;
+ searchTerm?: string | null;
showColumnConfigurator?: boolean | null;
tags?: QueryLogTags | null;
/** version of the node, used for schema migrations */