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.

fix(aio): stop clusters page emptying under filters (#94706)

posthog[bot]e7c98bd6a552
diff --git a/products/ai_observability/frontend/clusters/clusterDetailLogic.test.ts b/products/ai_observability/frontend/clusters/clusterDetailLogic.test.ts
index 20715d1e3e63..f3977f04e43e 100644
--- a/products/ai_observability/frontend/clusters/clusterDetailLogic.test.ts
+++ b/products/ai_observability/frontend/clusters/clusterDetailLogic.test.ts
@@ -243,6 +243,27 @@ describe('clusterDetailLogic', () => {
expect(series[0].shape).toBe('cross')
})
+
+ it.each([
+ ['a subset', ['trace-2'], true],
+ ['nothing', [], false],
+ ])(
+ 'plots only items that match active filters when they match %s',
+ async (_name, matchedIds, hasCentroid) => {
+ logic.actions.loadClusterDataSuccess({
+ cluster: mockCluster,
+ runTimestamp: '2025-01-05T00:00:00Z',
+ windowStart: '2025-01-01T00:00:00Z',
+ windowEnd: '2025-01-05T00:00:00Z',
+ clusteringLevel: 'trace',
+ })
+ logic.actions.loadFilteredItemIdsSuccess(new Set(matchedIds))
+
+ const series = logic.values.scatterPlotSeries
+ expect(series[0].points.map((point) => point.meta?.traceId)).toEqual(matchedIds)
+ expect(series.some((s) => s.key === 'centroid')).toBe(hasCentroid)
+ }
+ )
})
describe('sortedTraceIds', () => {
diff --git a/products/ai_observability/frontend/clusters/clusterDetailLogic.ts b/products/ai_observability/frontend/clusters/clusterDetailLogic.ts
index d073e0043e00..0d2ce9ceee83 100644
--- a/products/ai_observability/frontend/clusters/clusterDetailLogic.ts
+++ b/products/ai_observability/frontend/clusters/clusterDetailLogic.ts
@@ -9,9 +9,9 @@ import { dayjs } from 'lib/dayjs'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
-import { EventsQuery, NodeKind, ProductIntentContext, ProductKey } from '~/queries/schema/schema-general'
+import { ProductIntentContext, ProductKey } from '~/queries/schema/schema-general'
import { hogql } from '~/queries/utils'
-import { AnyPropertyFilter, Breadcrumb, PropertyFilterType, PropertyOperator } from '~/types'
+import { AnyPropertyFilter, Breadcrumb } from '~/types'
import type { ProductIntentProperties } from '../../../../frontend/src/lib/utils/product-intents'
import { aiObservabilitySharedLogic } from '../aiObservabilitySharedLogic'
@@ -20,14 +20,13 @@ import { llmEvaluationsLogic, waitForEvaluationsSettled } from '../evaluations/l
import { loadClusterMetrics } from './clusterMetricsLoader'
import type { ClusterScatterSeries } from './clusterScatter'
import {
- FILTER_QUERY_MAX_ROWS,
AI_OBSERVABILITY_CLUSTER_SCENE_TAG,
AI_OBSERVABILITY_CLUSTER_URL_PATTERN,
NOISE_CLUSTER_ID,
OUTLIER_COLOR,
- SAFE_ID_RE,
TRACES_PER_PAGE,
} from './constants'
+import { loadFilterMatchedItemIds } from './filteredItemIdsLoader'
import { loadTraceSummaries } from './traceSummaryLoader'
import {
Cluster,
@@ -180,7 +179,11 @@ export interface clusterDetailLogicMeta {
windowEnd: (clusterData: ClusterData | null) => string
clusteringLevel: (clusterData: ClusterData | null) => ClusteringLevel
isOutlierCluster: (cluster: Cluster | null) => boolean
- scatterPlotSeries: (cluster: Cluster | null, isOutlierCluster: boolean) => ClusterScatterSeries[]
+ scatterPlotSeries: (
+ cluster: Cluster | null,
+ isOutlierCluster: boolean,
+ filteredItemIds: Set<string> | null
+ ) => ClusterScatterSeries[]
sortedTraceIds: (cluster: Cluster | null, filteredItemIds: Set<string> | null) => string[]
totalTraces: (sortedTraceIds: string[]) => number
unfilteredTotalTraces: (cluster: Cluster | null) => number
@@ -273,97 +276,34 @@ export const clusterDetailLogic = kea<clusterDetailLogicType>([
// Subset of cluster item IDs that match the user's active property filters
// (cohorts, person properties, etc.). Null when no filters are active —
// selectors treat null as "show everything", which avoids forcing every
- // unfiltered cluster view to round-trip an EventsQuery on mount.
+ // unfiltered cluster view to round-trip a query on mount.
filteredItemIds: [
null as Set<string> | null,
{
loadFilteredItemIds: async (_, breakpoint) => {
// Debounce to coalesce overlapping filter changes (e.g. quick toggles
// of the test-accounts switch or successive cohort selections) into a
- // single EventsQuery round-trip.
+ // single round-trip.
await breakpoint(150)
- const propertyFilters: AnyPropertyFilter[] = values.propertyFilters || []
- const shouldFilterTestAccounts: boolean = values.shouldFilterTestAccounts
const cluster = values.cluster
const windowStart = values.windowStart
const windowEnd = values.windowEnd
- const clusteringLevel: ClusteringLevel = values.clusteringLevel
if (!cluster || !windowStart || !windowEnd) {
return null
}
- if (propertyFilters.length === 0 && !shouldFilterTestAccounts) {
- return null
- }
-
- // Eval clusters key on $ai_evaluation event UUIDs, which don't carry the
- // person/cohort fields the user filters by. Skip filtering for now rather
- // than silently producing empty results.
- if (clusteringLevel === 'evaluation') {
- return null
- }
-
- const clusterIds = Object.keys(cluster.traces).filter((id) => SAFE_ID_RE.test(id))
- if (clusterIds.length === 0) {
- return new Set<string>()
- }
-
- // For clusters larger than the server's row cap we'd silently miss matches,
- // which would render a misleading partial result. Skip filtering instead and
- // surface a warning — a future change can paginate via offset if this becomes
- // a real-world hit rather than a theoretical one.
- if (clusterIds.length > FILTER_QUERY_MAX_ROWS) {
- console.warn(
- `Cluster has ${clusterIds.length} items, exceeding the ${FILTER_QUERY_MAX_ROWS}-row cap for filter queries. Filters not applied.`
- )
- return null
- }
-
- const idPropertyKey = clusteringLevel === 'generation' ? '$ai_generation_id' : '$ai_trace_id'
- const idSelectExpression = `properties['${idPropertyKey}']`
-
- // Constrain to cluster items via a typed event-property filter rather than a
- // raw HogQL `where` clause: `properties.$ai_generation_id` doesn't parse cleanly
- // as a column reference because of the leading `$`, which would 500 the
- // EventsQuery. The typed filter routes through `property_to_expr` which knows
- // how to escape it.
- const idsFilter: AnyPropertyFilter = {
- type: PropertyFilterType.Event,
- key: idPropertyKey,
- operator: PropertyOperator.Exact,
- value: clusterIds,
- }
-
- const eventsQuery: EventsQuery = {
- kind: NodeKind.EventsQuery,
- // The Set accumulator below already dedupes, so we don't need DISTINCT —
- // and `DISTINCT col` is not a valid HogQL select expression anyway (it's a
- // query-level modifier, not a per-column prefix).
- select: [idSelectExpression],
- event: '$ai_generation',
- properties: [idsFilter, ...propertyFilters],
- after: windowStart,
- before: windowEnd,
- filterTestAccounts: shouldFilterTestAccounts,
- limit: clusterIds.length + 1,
- // Required for the query runner to populate the `product` ClickHouse
- // tag — without it the dev-mode `UntaggedQueryError` enforcement 500s
- // every request.
- tags: { productKey: ProductKey.AI_OBSERVABILITY, scene: AI_OBSERVABILITY_CLUSTER_SCENE_TAG },
- }
-
- const response = await api.query(eventsQuery)
+ const matched = await loadFilterMatchedItemIds({
+ itemIds: Object.keys(cluster.traces),
+ level: values.clusteringLevel,
+ windowStart,
+ windowEnd,
+ propertyFilters: values.propertyFilters || [],
+ filterTestAccounts: values.shouldFilterTestAccounts,
+ scene: AI_OBSERVABILITY_CLUSTER_SCENE_TAG,
+ })
breakpoint()
-
- const matched = new Set<string>()
- for (const row of response.results || []) {
- const id = (row as unknown[])[0]
- if (typeof id === 'string' && id) {
- matched.add(id)
- }
- }
return matched
},
},
@@ -473,12 +413,19 @@ export const clusterDetailLogic = kea<clusterDetailLogicType>([
],
scatterPlotSeries: [
- (s) => [s.cluster, s.isOutlierCluster],
- (cluster: Cluster | null, isOutlier: boolean): ClusterScatterSeries[] => {
+ (s) => [s.cluster, s.isOutlierCluster, s.filteredItemIds],
+ (
+ cluster: Cluster | null,
+ isOutlier: boolean,
+ filteredItemIds: Set<string> | null
+ ): ClusterScatterSeries[] => {
if (!cluster) {
return []
}
+ // Same membership rule as sortedTraceIds, so the plot and the list show the same items
+ const entries = Object.entries(cluster.traces)
+ const visibleEntries = filteredItemIds ? entries.filter(([id]) => filteredItemIds.has(id)) : entries
const color = isOutlier ? OUTLIER_COLOR : getSeriesColor(cluster.cluster_id)
const result: ClusterScatterSeries[] = [
@@ -488,7 +435,7 @@ export const clusterDetailLogic = kea<clusterDetailLogicType>([
color,
pointRadius: 5,
shape: isOutlier ? 'cross' : 'circle',
- points: Object.entries(cluster.traces).map(([itemKey, traceInfo]) => ({
+ points: visibleEntries.map(([itemKey, traceInfo]) => ({
x: traceInfo.x,
y: traceInfo.y,
meta: {
@@ -501,7 +448,7 @@ export const clusterDetailLogic = kea<clusterDetailLogicType>([
]
// Add centroid marker for non-outlier clusters
- if (!isOutlier) {
+ if (!isOutlier && visibleEntries.length > 0) {
result.push({
key: 'centroid',
label: 'Centroid',
diff --git a/products/ai_observability/frontend/clusters/clustersLogic.ts b/products/ai_observability/frontend/clusters/clustersLogic.ts
index c97fb61a1cde..f6ff0d6a7ac7 100644
--- a/products/ai_observability/frontend/clusters/clustersLogic.ts
+++ b/products/ai_observability/frontend/clusters/clustersLogic.ts
@@ -10,9 +10,8 @@ import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { trackedActionToUrl } from 'lib/logic/scenes/trackedActionToUrl'
import { urls } from 'scenes/urls'
-import { EventsQuery, NodeKind, ProductKey } from '~/queries/schema/schema-general'
import { hogql } from '~/queries/utils'
-import { AnyPropertyFilter, Breadcrumb, PropertyFilterType, PropertyOperator } from '~/types'
+import { AnyPropertyFilter, Breadcrumb } from '~/types'
import { aiObservabilitySharedLogic } from '../aiObservabilitySharedLogic'
import type { ApplyUrlStatePayload } from '../aiObservabilitySharedLogic'
@@ -20,14 +19,13 @@ import { llmEvaluationsLogic, waitForEvaluationsSettled } from '../evaluations/l
import { loadClusterMetrics } from './clusterMetricsLoader'
import type { ClusterScatterSeries } from './clusterScatter'
import {
- FILTER_QUERY_MAX_ROWS,
AI_OBSERVABILITY_CLUSTERS_SCENE_TAG,
CLUSTERING_RUNS_LOOKBACK_DAYS,
MAX_CLUSTERING_RUNS,
NOISE_CLUSTER_ID,
OUTLIER_COLOR,
- SAFE_ID_RE,
} from './constants'
+import { loadFilterMatchedItemIds } from './filteredItemIdsLoader'
import {
EvaluationItemAttributes,
EvaluationVerdict,
@@ -416,88 +414,24 @@ export const clustersLogic = kea<clustersLogicType>([
{
loadPropertyFilteredItemIds: async (_, breakpoint) => {
// Debounce overlapping filter changes (quick toggles or successive
- // cohort selections) into a single EventsQuery round-trip.
+ // cohort selections) into a single round-trip.
await breakpoint(150)
- const propertyFilters: AnyPropertyFilter[] = values.propertyFilters || []
- const shouldFilterTestAccounts: boolean = values.shouldFilterTestAccounts
const run = values.currentRun
-
if (!run) {
return null
}
- if (propertyFilters.length === 0 && !shouldFilterTestAccounts) {
- return null
- }
-
- // Eval clusters key on $ai_evaluation event UUIDs which don't carry
- // the person/cohort fields these filters target. The eval-specific
- // filter bar handles those.
- const level = run.level || values.clusteringLevel
- if (level === 'evaluation') {
- return null
- }
-
- const allIds: string[] = []
- for (const cluster of run.clusters) {
- for (const id of Object.keys(cluster.traces)) {
- if (SAFE_ID_RE.test(id)) {
- allIds.push(id)
- }
- }
- }
- if (allIds.length === 0) {
- return new Set<string>()
- }
-
- if (allIds.length > FILTER_QUERY_MAX_ROWS) {
- console.warn(
- `Run has ${allIds.length} items, exceeding the ${FILTER_QUERY_MAX_ROWS}-row cap for filter queries. Filters not applied.`
- )
- return null
- }
-
- const idPropertyKey = level === 'generation' ? '$ai_generation_id' : '$ai_trace_id'
- const idSelectExpression = `properties['${idPropertyKey}']`
-
- // Restrict the events to the cluster's items via a typed event-property
- // filter rather than a raw HogQL `where` clause: `properties.$ai_generation_id`
- // doesn't parse cleanly as a column reference because of the leading `$`,
- // which would 500 the EventsQuery. The typed filter goes through
- // `property_to_expr` which knows how to escape it.
- const idsFilter: AnyPropertyFilter = {
- type: PropertyFilterType.Event,
- key: idPropertyKey,
- operator: PropertyOperator.Exact,
- value: allIds,
- }
-
- const eventsQuery: EventsQuery = {
- kind: NodeKind.EventsQuery,
- select: [idSelectExpression],
- event: '$ai_generation',
- properties: [idsFilter, ...propertyFilters],
- after: run.windowStart,
- before: run.windowEnd,
- filterTestAccounts: shouldFilterTestAccounts,
- limit: allIds.length + 1,
- // Required for the query runner to populate the `product` ClickHouse
- // tag — without it the dev-mode `UntaggedQueryError` enforcement 500s
- // every request.
- tags: { productKey: ProductKey.AI_OBSERVABILITY, scene: AI_OBSERVABILITY_CLUSTERS_SCENE_TAG },
- }
-
- const response = await api.query(eventsQuery)
+ const matched = await loadFilterMatchedItemIds({
+ itemIds: run.clusters.flatMap((cluster) => Object.keys(cluster.traces)),
+ level: run.level || values.clusteringLevel,
+ windowStart: run.windowStart,
+ windowEnd: run.windowEnd,
+ propertyFilters: values.propertyFilters || [],
+ filterTestAccounts: values.shouldFilterTestAccounts,
+ scene: AI_OBSERVABILITY_CLUSTERS_SCENE_TAG,
+ })
breakpoint()
-
- const matched = new Set<string>()
- for (const row of response?.results || []) {
- const id = (row as unknown[])[0]
- if (typeof id === 'string' && id) {
- matched.add(id)
- }
- }
return matched
},
},
@@ -1045,7 +979,7 @@ export const clustersLogic = kea<clustersLogicType>([
},
// Property filter state lives in the shared logic; mirror its updates into a
- // fresh EventsQuery scoped to the current run's items. Both listener entries are
+ // fresh query scoped to the current run's items. Both listener entries are
// needed because the dispatch path differs by trigger:
// - UI clicks dispatch `setPropertyFilters` / `setShouldFilterTestAccounts`
// directly. The shared logic's `actionToUrl` then echoes the new state into
diff --git a/products/ai_observability/frontend/clusters/constants.ts b/products/ai_observability/frontend/clusters/constants.ts
index 14c3b6fd0f53..31785db70831 100644
--- a/products/ai_observability/frontend/clusters/constants.ts
+++ b/products/ai_observability/frontend/clusters/constants.ts
@@ -28,12 +28,21 @@ export const AI_OBSERVABILITY_CLUSTER_URL_PATTERN = '/ai-observability/clusters/
export const AI_OBSERVABILITY_CLUSTERS_SCENE_TAG = 'AIObservabilityClusters'
export const AI_OBSERVABILITY_CLUSTER_SCENE_TAG = 'AIObservabilityCluster'
-// Cluster items are keyed by UUIDs from precomputed clustering events. Restrict to
-// hex / dashes before interpolating into a HogQL `IN` literal so a malformed key
-// can't break out of the string. UUIDs already match this character set.
+// Characters a UUID can contain. This is a character check, not a full UUID check.
export const SAFE_ID_RE = /^[a-f0-9-]+$/i
-// Mirrors `MAX_SELECT_RETURNED_ROWS` in `posthog/hogql/constants.py`. EventsQuery rows above
+// Mirrors `MAX_SELECT_RETURNED_ROWS` in `posthog/hogql/constants.py`. Query rows above
// this are silently truncated server-side, so post-hoc property-filter queries against the
// full set of cluster items must either fit under the cap or fall back to "no filtering".
export const FILTER_QUERY_MAX_ROWS = 50000
+
+// Events that belong to a trace. Keep in sync with `traces_query_runner.py`, so a filter keeps
+// the same traces on the clusters page and the traces list.
+export const TRACE_MEMBER_EVENTS = [
+ '$ai_span',
+ '$ai_generation',
+ '$ai_embedding',
+ '$ai_metric',
+ '$ai_feedback',
+ '$ai_trace',
+]
diff --git a/products/ai_observability/frontend/clusters/filteredItemIdsLoader.test.ts b/products/ai_observability/frontend/clusters/filteredItemIdsLoader.test.ts
new file mode 100644
index 000000000000..a78d130cfa4a
--- /dev/null
+++ b/products/ai_observability/frontend/clusters/filteredItemIdsLoader.test.ts
@@ -0,0 +1,96 @@
+import api from 'lib/api'
+
+import { AnyPropertyFilter, PropertyFilterType, PropertyOperator } from '~/types'
+
+import { loadFilterMatchedItemIds } from './filteredItemIdsLoader'
+import { ClusteringLevel } from './types'
+
+jest.mock('lib/api')
+
+const mockApi = api as jest.Mocked<typeof api>
+
+const personFilter: AnyPropertyFilter = {
+ type: PropertyFilterType.Person,
+ key: 'email',
+ operator: PropertyOperator.IContains,
+ value: 'example.com',
+}
+
+function callLoader(
+ overrides: Partial<Parameters<typeof loadFilterMatchedItemIds>[0]> = {}
+): ReturnType<typeof loadFilterMatchedItemIds> {
+ return loadFilterMatchedItemIds({
+ itemIds: ['aaaaaaaa-0000-0000-0000-000000000001'],
+ level: 'trace' as ClusteringLevel,
+ windowStart: '2026-09-01T00:00:00Z',
+ windowEnd: '2026-09-02T00:00:00Z',
+ propertyFilters: [personFilter],
+ filterTestAccounts: false,
+ scene: 'AIObservabilityClusters',
+ ...overrides,
+ })
+}
+
+describe('loadFilterMatchedItemIds', () => {
+ beforeEach(() => {
+ jest.clearAllMocks()
+ mockApi.queryHogQL.mockResolvedValue({ results: [] } as any)
+ })
+
+ it('matches a trace on any of its events, not only generations', async () => {
+ await callLoader()
+
+ const [query] = mockApi.queryHogQL.mock.calls[0]
+ expect(query).toContain('$ai_span')
+ expect(query).toContain('$ai_embedding')
+ expect(query).toContain('$ai_trace')
+ expect(query).toContain("properties.$ai_trace_id IN ['aaaaaaaa-0000-0000-0000-000000000001']")
+ expect(query).toContain("parseDateTimeBestEffort('2026-09-01T00:00:00Z') - INTERVAL 7 DAY")
+ })
+
+ it('keeps trace ids of any shape and escapes them in the query', async () => {
+ await callLoader({ itemIds: ['trace_1', 'conv:abc', "o'brien\\x"] })
+
+ const [query] = mockApi.queryHogQL.mock.calls[0]
+ expect(query).toContain("properties.$ai_trace_id IN ['trace_1', 'conv:abc', 'o\\'brien\\\\x']")
+ })
+
+ it('matches generation items on the event uuid, which is the id clustering stores', async () => {
+ await callLoader({
+ level: 'generation' as ClusteringLevel,
+ itemIds: ['aaaaaaaa-0000-0000-0000-000000000001', 'not-a-uuid'],
+ })
+
+ const [query] = mockApi.queryHogQL.mock.calls[0]
+ expect(query).toContain("event = '$ai_generation'")
+ expect(query).toContain("uuid IN ['aaaaaaaa-0000-0000-0000-000000000001']")
+ expect(query).toContain("parseDateTimeBestEffort('2026-09-01T00:00:00Z') - INTERVAL 7 DAY")
+ // Clustering stores the event uuid, not $ai_generation_id.
+ expect(query).not.toContain('$ai_generation_id')
+ })
+
+ it('passes property filters and the test-account toggle to the {filters} placeholder', async () => {
+ await callLoader({ filterTestAccounts: true })
+
+ const [query, , options] = mockApi.queryHogQL.mock.calls[0]
+ expect(query).toContain('{filters}')
+ expect(options?.queryParams?.filters).toEqual({
+ properties: [personFilter],
+ filterTestAccounts: true,
+ })
+ })
+
+ it('returns the matched ids', async () => {
+ mockApi.queryHogQL.mockResolvedValue({ results: [['trace-a'], ['trace-b']] } as any)
+
+ await expect(callLoader()).resolves.toEqual(new Set(['trace-a', 'trace-b']))
+ })
+
+ it.each([
+ ['no filters are active', { propertyFilters: [], filterTestAccounts: false }],
+ ['the run is an evaluation run', { level: 'evaluation' as ClusteringLevel }],
+ ])('skips filtering and queries nothing when %s', async (_name, overrides) => {
+ await expect(callLoader(overrides)).resolves.toBeNull()
+ expect(mockApi.queryHogQL).not.toHaveBeenCalled()
+ })
+})
diff --git a/products/ai_observability/frontend/clusters/filteredItemIdsLoader.ts b/products/ai_observability/frontend/clusters/filteredItemIdsLoader.ts
new file mode 100644
index 000000000000..c36df8cf42cc
--- /dev/null
+++ b/products/ai_observability/frontend/clusters/filteredItemIdsLoader.ts
@@ -0,0 +1,121 @@
+import api from 'lib/api'
+
+import { HogQLQueryString, hogql } from '~/queries/utils'
+import { AnyPropertyFilter } from '~/types'
+
+import { FILTER_QUERY_MAX_ROWS, SAFE_ID_RE, TRACE_MEMBER_EVENTS } from './constants'
+import { ClusteringLevel } from './types'
+
+export interface FilterMatchedItemIdsParams {
+ /** Cluster item ids to test: trace ids at trace level, `$ai_generation` event UUIDs at generation level. */
+ itemIds: string[]
+ level: ClusteringLevel
+ windowStart: string
+ windowEnd: string
+ propertyFilters: AnyPropertyFilter[]
+ filterTestAccounts: boolean
+ scene: string
+}
+
+/**
+ * A trace matches when any of its events matches. Clustering stores generation items as
+ * `$ai_generation` event UUIDs, so they match on `uuid`, the same as cluster metrics.
+ *
+ * The run window bounds when the embeddings were written, and a trace's events come before its
+ * embedding, so the lower bound starts 7 days before the window start. Seven days also covers
+ * most manual summarization runs over an older window.
+ */
+function buildFilterQuery(
+ level: ClusteringLevel,
+ ids: string[],
+ windowStart: string,
+ windowEnd: string
+): HogQLQueryString {
+ if (level === 'generation') {
+ return hogql`
+ SELECT DISTINCT toString(uuid) AS item_id
+ FROM events
+ WHERE event = '$ai_generation'
+ AND timestamp >= parseDateTimeBestEffort(${windowStart}) - INTERVAL 7 DAY
+ AND timestamp <= parseDateTimeBestEffort(${windowEnd})
+ AND uuid IN ${ids}
+ AND {filters}
+ LIMIT ${ids.length}
+ `
+ }
+ return hogql`
+ SELECT DISTINCT properties.$ai_trace_id AS item_id
+ FROM events
+ WHERE event IN ${TRACE_MEMBER_EVENTS}
+ AND timestamp >= parseDateTimeBestEffort(${windowStart}) - INTERVAL 7 DAY
+ AND timestamp <= parseDateTimeBestEffort(${windowEnd})
+ AND properties.$ai_trace_id IN ${ids}
+ AND {filters}
+ LIMIT ${ids.length}
+ `
+}
+
+function toItemIdSet(results: unknown[] | undefined): Set<string> {
+ const matched = new Set<string>()
+ for (const row of results || []) {
+ const id = (row as unknown[])[0]
+ if (typeof id === 'string' && id) {
+ matched.add(id)
+ }
+ }
+ return matched
+}
+
+/**
+ * Subset of `itemIds` whose events match the active filters. Null means "show everything": no filters
+ * are on, the level carries no person data, or the run is too large for one query.
+ */
+export async function loadFilterMatchedItemIds({
+ itemIds,
+ level,
+ windowStart,
+ windowEnd,
+ propertyFilters,
+ filterTestAccounts,
+ scene,
+}: FilterMatchedItemIdsParams): Promise<Set<string> | null> {
+ if (propertyFilters.length === 0 && !filterTestAccounts) {
+ return null
+ }
+
+ // Eval clusters key on $ai_evaluation event UUIDs, which carry none of the person or cohort
+ // fields these filters target. The eval-specific filter bar handles those.
+ if (level === 'evaluation') {
+ return null
+ }
+
+ // Trace ids are free-form strings, and the `hogql` tag escapes them. Generation ids go into a
+ // comparison with the uuid column, where one value that is not a UUID fails the whole query.
+ // So drop generation ids with characters a UUID never has.
+ const safeIds = level === 'generation' ? itemIds.filter((id) => SAFE_ID_RE.test(id)) : itemIds.filter(Boolean)
+ if (safeIds.length === 0) {
+ return new Set<string>()
+ }
+
+ // Above the row cap the query would silently miss matches, so skip filtering instead.
+ if (safeIds.length > FILTER_QUERY_MAX_ROWS) {
+ console.warn(
+ `Skipping cluster filters: ${safeIds.length} items exceed the ${FILTER_QUERY_MAX_ROWS}-row cap for filter queries.`
+ )
+ return null
+ }
+
+ const response = await api.queryHogQL(
+ buildFilterQuery(level, safeIds, windowStart, windowEnd),
+ { productKey: 'llm_analytics', scene },
+ {
+ queryParams: {
+ filters: { properties: propertyFilters, filterTestAccounts },
+ // Window bounds are in UTC (from the backend), so compare timestamps in UTC
+ modifiers: { convertToProjectTimezone: false },
+ },
+ }
+ )
+
+ return toItemIdSet(response.results)
+}