: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
feat(llma): add cohort/property filters to cluster pages (#56877)
Richard Solomou8d73fedadd76
diff --git a/frontend/jest.config.ts b/frontend/jest.config.tsindex 78495921d515..5b65cf606a50 100644--- a/frontend/jest.config.ts+++ b/frontend/jest.config.ts@@ -15,6 +15,7 @@ const esmModules = ['@posthog/hedgehog-mode','escape-string-regexp','@tiptap',+ '@mathjax','marked','lowlight','devlop',diff --git a/frontend/src/products.tsx b/frontend/src/products.tsxindex 71e6a55afd57..4e86067aedbc 100644--- a/frontend/src/products.tsx+++ b/frontend/src/products.tsx@@ -32,6 +32,7 @@ import type {SchemaSceneTab,} from '../../products/data_warehouse/frontend/scenes/SchemaScene/SchemaScene'import type { SourceSceneTab } from '../../products/data_warehouse/frontend/scenes/SourceScene/SourceScene'+import { LLM_ANALYTICS_CLUSTER_URL_PATTERN } from '../../products/llm_analytics/frontend/clusters/constants'import type { WorkflowsSceneTab } from '../../products/workflows/frontend/WorkflowsScene'import {ActionType,@@ -213,7 +214,7 @@ export const productRoutes: Record<string, [string, string]> = {'/llm-analytics/skills/:name': ['LLMAnalyticsSkill', 'llmAnalyticsSkill'],'/llm-analytics/clusters': ['LLMAnalyticsClusters', 'llmAnalyticsClusters'],'/llm-analytics/clusters/:runId': ['LLMAnalyticsClusters', 'llmAnalyticsClusters'],- '/llm-analytics/clusters/:runId/:clusterId': ['LLMAnalyticsCluster', 'llmAnalyticsCluster'],+ [LLM_ANALYTICS_CLUSTER_URL_PATTERN]: ['LLMAnalyticsCluster', 'llmAnalyticsCluster'],'/logs': ['Logs', 'logs'],'/logs/alerts/:id': ['LogsAlertDetail', 'logsAlertDetail'],'/logs/drop-rules/new': ['LogsSamplingNew', 'logsSamplingNew'],diff --git a/products/llm_analytics/frontend/clusters/ClustersView.tsx b/products/llm_analytics/frontend/clusters/ClustersView.tsxindex 30a62d3631c1..fb863ff42fa4 100644--- a/products/llm_analytics/frontend/clusters/ClustersView.tsx+++ b/products/llm_analytics/frontend/clusters/ClustersView.tsx@@ -4,10 +4,14 @@ import { IconChevronDown, IconChevronRight, IconGear, IconInfo, IconQuestion, Icimport { LemonButton, LemonSegmentedButton, LemonSelect, Spinner, Tooltip } from '@posthog/lemon-ui'import { AccessControlAction } from 'lib/components/AccessControlAction'+import { PropertyFilters } from 'lib/components/PropertyFilters/PropertyFilters'+import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'+import { TestAccountFilterSwitch } from 'lib/components/TestAccountFiltersSwitch'import { FEATURE_FLAGS } from 'lib/constants'import { dayjs } from 'lib/dayjs'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { groupsModel } from '~/models/groupsModel'import { AccessControlLevel, AccessControlResourceType } from '~/types'import { ClusterCard } from './ClusterCard'@@ -38,9 +42,14 @@ export function ClustersView(): JSX.Element {isScatterPlotExpanded,clusterMetrics,clusterMetricsLoading,+ propertyFilters,+ shouldFilterTestAccounts,+ propertyFilteredItemIdsLoading,} = useValues(clustersLogic)const { setClusteringLevel, setSelectedRunId, toggleClusterExpanded, toggleScatterPlotExpanded } =useActions(clustersLogic)+ const { setPropertyFilters, setShouldFilterTestAccounts } = useActions(clustersLogic)+ const { groupsTaxonomicTypes } = useValues(groupsModel)const { featureFlags } = useValues(featureFlagLogic)const { openModal } = useActions(clustersAdminLogic)const { jobs } = useValues(clusteringJobsLogic)@@ -63,17 +72,11 @@ export function ClustersView(): JSX.Element {jobNameById[String(job.id)] = job.name}- if (clusteringRunsLoading) {- return (- <div className="flex items-center justify-center p-8">- <Spinner className="text-2xl" captureTime />- </div>- )- }-- // Show empty state only after checking both trace and generation levels- // Always show the level toggle so users can switch between levels- const showEmptyState = clusteringRuns.length === 0+ // Show empty state only after the runs query has resolved — otherwise the user+ // sees a "no clusters found" flash whenever they switch levels or first land on+ // the page, then it gets replaced by the actual data a moment later.+ const showEmptyState = !clusteringRunsLoading && clusteringRuns.length === 0+ const isLoadingData = clusteringRunsLoading || currentRunLoadingif (showEmptyState) {return (@@ -183,11 +186,16 @@ export function ClustersView(): JSX.Element {label: jobName ? `${run.label} (${jobName})` : run.label,}})}- placeholder="Select a run"+ placeholder={clusteringRunsLoading ? 'Loading runs…' : 'Select a run'}+ disabled={clusteringRunsLoading}+ loading={clusteringRunsLoading}data-attr="clusters-run-select"/></span></Tooltip>+ {/* Inline indicator while a run is loading. Doesn't blank the rest of+ the page — cluster cards stay visible until the new run resolves. */}+ {isLoadingData && <Spinner className="text-base" captureTime />}</div><div className="flex items-center gap-4">@@ -262,15 +270,11 @@ export function ClustersView(): JSX.Element {</div></div>- {/* Loading State */}- {currentRunLoading && (- <div className="flex items-center justify-center p-8">- <Spinner className="text-2xl" captureTime />- </div>- )}-- {/* Scatter Plot Visualization */}- {!currentRunLoading && !traceSummariesLoading && sortedClusters.length > 0 && (+ {/* Scatter Plot Visualization. We deliberately don't gate on `traceSummariesLoading`+ here — the plot is meaningful with raw points alone (UMAP coordinates ship in the+ cluster event), so hiding it for the seconds it takes to fetch tooltip summaries+ makes the whole page flash blank. Tooltips degrade to ID-only until summaries land. */}+ {sortedClusters.length > 0 && (<div className="border rounded-lg bg-surface-primary overflow-hidden transition-all"><divclassName="p-4 cursor-pointer hover:bg-surface-secondary transition-colors"@@ -334,18 +338,45 @@ export function ClustersView(): JSX.Element {</div>)}+ {/* Property filter bar — narrows clusters by cohort / person property / etc.+ Hidden for evaluation-level runs because eval items key on $ai_evaluation+ event UUIDs that don't carry the person/cohort fields these filters target;+ the EvaluationFilterBar below handles that level instead. */}+ {sortedClusters.length > 0 && clusteringLevel !== 'evaluation' && (+ <div className="flex gap-x-4 gap-y-2 items-center flex-wrap">+ <PropertyFilters+ propertyFilters={propertyFilters}+ taxonomicGroupTypes={[+ TaxonomicFilterGroupType.EventProperties,+ TaxonomicFilterGroupType.PersonProperties,+ ...groupsTaxonomicTypes,+ TaxonomicFilterGroupType.Cohorts,+ TaxonomicFilterGroupType.HogQLExpression,+ ]}+ onChange={setPropertyFilters}+ pageKey={`llm-analytics-clusters-${effectiveRunId || 'none'}`}+ />+ <div className="flex-1" />+ {propertyFilteredItemIdsLoading && <Spinner className="text-sm" captureTime />}+ <TestAccountFilterSwitch+ checked={shouldFilterTestAccounts}+ onChange={setShouldFilterTestAccounts}+ />+ </div>+ )}+{/* Eval-only post-hoc filter (renders below the scatter, above the cards) */}- {!currentRunLoading && sortedClusters.length > 0 && <EvaluationFilterBar />}+ {sortedClusters.length > 0 && <EvaluationFilterBar />}{/* Empty result after filtering */}- {!currentRunLoading && sortedClusters.length > 0 && filteredSortedClusters.length === 0 && (+ {sortedClusters.length > 0 && filteredSortedClusters.length === 0 && (<div className="border rounded-lg p-6 text-center text-muted">- No clusters match the current evaluation filters.+ No clusters match the current filters.</div>)}{/* Cluster Cards */}- {!currentRunLoading && filteredSortedClusters.length > 0 && (+ {filteredSortedClusters.length > 0 && (<div className="grid grid-cols-1 lg:grid-cols-2 gap-4">{filteredSortedClusters.map((cluster: Cluster) => (<ClusterCard@@ -365,11 +396,23 @@ export function ClustersView(): JSX.Element {</div>)}- {/* Empty State */}- {!currentRunLoading && sortedClusters.length === 0 && currentRun && (+ {/* Empty State — only after the run has actually loaded. While `currentRunLoading`+ is true and `currentRun` is null, we suppress this so the user doesn't see a+ "no clusters" message when really we're still fetching the run. */}+ {!isLoadingData && sortedClusters.length === 0 && currentRun && (<div className="text-center p-8 text-muted">No clusters found in this run.</div>)}+ {/* Centered placeholder while the very first run is loading and we have nothing+ to show yet. Avoids a totally blank data area between the chrome and the jobs+ panel on cold starts and level switches. */}+ {isLoadingData && !currentRun && (+ <div className="flex items-center justify-center p-12 text-muted">+ <Spinner className="text-2xl mr-3" captureTime />+ <span>Loading clusters…</span>+ </div>+ )}+{/* Jobs Panel */}<ClusteringJobsPanel />diff --git a/products/llm_analytics/frontend/clusters/LLMAnalyticsClusterScene.tsx b/products/llm_analytics/frontend/clusters/LLMAnalyticsClusterScene.tsxindex 4736528569d3..0c3b7f72f018 100644--- a/products/llm_analytics/frontend/clusters/LLMAnalyticsClusterScene.tsx+++ b/products/llm_analytics/frontend/clusters/LLMAnalyticsClusterScene.tsx@@ -5,12 +5,16 @@ import { IconChevronDown, IconChevronLeft, IconChevronRight } from '@posthog/icoimport { LemonButton, LemonSkeleton, LemonTag, Link, Spinner, Tooltip } from '@posthog/lemon-ui'import { NotFound } from 'lib/components/NotFound'+import { PropertyFilters } from 'lib/components/PropertyFilters/PropertyFilters'+import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'+import { TestAccountFilterSwitch } from 'lib/components/TestAccountFiltersSwitch'import { dayjs } from 'lib/dayjs'import { SceneExport } from 'scenes/sceneTypes'import { urls } from 'scenes/urls'import { SceneContent } from '~/layout/scenes/components/SceneContent'import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'+import { groupsModel } from '~/models/groupsModel'import { ProductKey } from '~/queries/schema/schema-general'import { formatErrorRate, formatLLMCost, formatLLMLatency, formatTokens } from '../utils'@@ -38,6 +42,7 @@ export function LLMAnalyticsClusterScene(): JSX.Element {clusteringLevel,isOutlierCluster,totalTraces,+ unfilteredTotalTraces,totalPages,currentPage,paginatedTracesWithSummaries,@@ -46,8 +51,13 @@ export function LLMAnalyticsClusterScene(): JSX.Element {windowEnd,clusterMetrics,clusterMetricsLoading,+ propertyFilters,+ shouldFilterTestAccounts,+ hasActiveFilters,+ filteredItemIdsLoading,} = useValues(clusterDetailLogic)- const { setPage } = useActions(clusterDetailLogic)+ const { setPage, setPropertyFilters, setShouldFilterTestAccounts } = useActions(clusterDetailLogic)+ const { groupsTaxonomicTypes } = useValues(groupsModel)if (clusterDataLoading) {return (@@ -75,6 +85,7 @@ export function LLMAnalyticsClusterScene(): JSX.Element {const itemLabel =clusteringLevel === 'generation' ? 'generations' : clusteringLevel === 'evaluation' ? 'evaluations' : 'traces'+ const filtersSupported = clusteringLevel !== 'evaluation'return (<SceneContent>@@ -98,7 +109,10 @@ export function LLMAnalyticsClusterScene(): JSX.Element {><div className="flex flex-wrap items-center gap-3 mb-2"><LemonTag type={isOutlierCluster ? 'caution' : 'primary'} size="medium">- {totalTraces} {itemLabel}+ {hasActiveFilters && filtersSupported+ ? `${totalTraces} of ${unfilteredTotalTraces}`+ : totalTraces}{' '}+ {itemLabel}</LemonTag>{windowStart && windowEnd && (<span className="text-muted text-sm">@@ -115,6 +129,30 @@ export function LLMAnalyticsClusterScene(): JSX.Element {/></div>+ {/* Filter bar — eval clusters key on $ai_evaluation event UUIDs which don't carry+ the person/cohort fields the filters are built around, so the bar is hidden there. */}+ {filtersSupported && (+ <div className="flex gap-x-4 gap-y-2 items-center flex-wrap mb-4">+ <PropertyFilters+ propertyFilters={propertyFilters}+ taxonomicGroupTypes={[+ TaxonomicFilterGroupType.EventProperties,+ TaxonomicFilterGroupType.PersonProperties,+ ...groupsTaxonomicTypes,+ TaxonomicFilterGroupType.Cohorts,+ TaxonomicFilterGroupType.HogQLExpression,+ ]}+ onChange={setPropertyFilters}+ pageKey={`llm-analytics-cluster-${cluster.cluster_id}`}+ />+ <div className="flex-1" />+ <TestAccountFilterSwitch+ checked={shouldFilterTestAccounts}+ onChange={setShouldFilterTestAccounts}+ />+ </div>+ )}+{/* Cluster scatter plot */}<div className="border rounded-lg p-4 mb-4 bg-surface-primary"><h3 className="font-semibold text-sm mb-2">Cluster visualization</h3>@@ -157,11 +195,17 @@ export function LLMAnalyticsClusterScene(): JSX.Element {{/* Trace list */}<div className="border rounded-lg overflow-hidden divide-y">- {traceSummariesLoading && paginatedTracesWithSummaries.length === 0 ? (+ {(traceSummariesLoading || filteredItemIdsLoading) && paginatedTracesWithSummaries.length === 0 ? (<div className="p-4 flex items-center justify-center"><Spinner className="mr-2" captureTime /><span className="text-muted">Loading {itemLabel}...</span></div>+ ) : paginatedTracesWithSummaries.length === 0 ? (+ <div className="p-6 text-center text-muted text-sm">+ {hasActiveFilters+ ? `No ${itemLabel} match the current filters in this cluster.`+ : `No ${itemLabel} in this cluster.`}+ </div>) : (paginatedTracesWithSummaries.map((diff --git a/products/llm_analytics/frontend/clusters/clusterDetailLogic.test.ts b/products/llm_analytics/frontend/clusters/clusterDetailLogic.test.tsindex fa3f35916986..b9ffd0beedeb 100644--- a/products/llm_analytics/frontend/clusters/clusterDetailLogic.test.ts+++ b/products/llm_analytics/frontend/clusters/clusterDetailLogic.test.ts@@ -1,6 +1,7 @@import { expectLogic } from 'kea-test-utils'import { initKeaTests } from '~/test/init'+import { CohortPropertyFilter, PropertyFilterType, PropertyOperator } from '~/types'import { clusterDetailLogic } from './clusterDetailLogic'import { NOISE_CLUSTER_ID, TRACES_PER_PAGE } from './constants'@@ -416,5 +417,82 @@ describe('clusterDetailLogic', () => {expect(breadcrumbs[2].name).toBe('Cluster')})})++ describe('filteredItemIds', () => {+ it('defaults to null when no filters are active', () => {+ expect(logic.values.filteredItemIds).toBeNull()+ })++ it('treats null as "no filtering" — sortedTraceIds returns all entries', async () => {+ 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',+ })++ expect(logic.values.filteredItemIds).toBeNull()+ expect(logic.values.sortedTraceIds).toEqual(['trace-1', 'trace-2', 'trace-3'])+ expect(logic.values.totalTraces).toBe(3)+ expect(logic.values.unfilteredTotalTraces).toBe(3)+ })++ it('restricts sortedTraceIds to the matched subset when filteredItemIds is set', async () => {+ 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(['trace-1', 'trace-3']))++ expect(logic.values.sortedTraceIds).toEqual(['trace-1', 'trace-3'])+ expect(logic.values.totalTraces).toBe(2)+ // The unfiltered count should still reflect the underlying cluster size, so+ // the UI can show "2 of 3" rather than just "2".+ expect(logic.values.unfilteredTotalTraces).toBe(3)+ })++ it('returns an empty list when the filter matches nothing', async () => {+ 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<string>())++ expect(logic.values.sortedTraceIds).toEqual([])+ expect(logic.values.totalTraces).toBe(0)+ expect(logic.values.unfilteredTotalTraces).toBe(3)+ })+ })++ describe('hasActiveFilters', () => {+ it('is false when no property filters and test accounts toggle is off', () => {+ expect(logic.values.hasActiveFilters).toBe(false)+ })++ it('is true once property filters are set', () => {+ const cohortFilter: CohortPropertyFilter = {+ type: PropertyFilterType.Cohort,+ key: 'id',+ value: 7,+ operator: PropertyOperator.In,+ }+ logic.actions.setPropertyFilters([cohortFilter])+ expect(logic.values.hasActiveFilters).toBe(true)+ })++ it('is true when filtering test accounts even without property filters', () => {+ logic.actions.setShouldFilterTestAccounts(true)+ expect(logic.values.hasActiveFilters).toBe(true)+ })+ })})})diff --git a/products/llm_analytics/frontend/clusters/clusterDetailLogic.ts b/products/llm_analytics/frontend/clusters/clusterDetailLogic.tsindex e7a1c8ff26ba..64f8cc094999 100644--- a/products/llm_analytics/frontend/clusters/clusterDetailLogic.ts+++ b/products/llm_analytics/frontend/clusters/clusterDetailLogic.ts@@ -9,13 +9,22 @@ import { tabAwareUrlToAction } from 'lib/logic/scenes/tabAwareUrlToAction'import { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'-import { ProductIntentContext, ProductKey } from '~/queries/schema/schema-general'+import { EventsQuery, NodeKind, ProductIntentContext, ProductKey } from '~/queries/schema/schema-general'import { hogql } from '~/queries/utils'-import { Breadcrumb } from '~/types'+import { AnyPropertyFilter, Breadcrumb, PropertyFilterType, PropertyOperator } from '~/types'+import { llmAnalyticsSharedLogic } from '../llmAnalyticsSharedLogic'import type { clusterDetailLogicType } from './clusterDetailLogicType'import { loadClusterMetrics } from './clusterMetricsLoader'-import { NOISE_CLUSTER_ID, OUTLIER_COLOR, TRACES_PER_PAGE } from './constants'+import {+ FILTER_QUERY_MAX_ROWS,+ LLM_ANALYTICS_CLUSTER_SCENE_TAG,+ LLM_ANALYTICS_CLUSTER_URL_PATTERN,+ NOISE_CLUSTER_ID,+ OUTLIER_COLOR,+ SAFE_ID_RE,+ TRACES_PER_PAGE,+} from './constants'import { loadTraceSummaries } from './traceSummaryLoader'import {Cluster,@@ -62,8 +71,14 @@ export const clusterDetailLogic = kea<clusterDetailLogicType>([path(['products', 'llm_analytics', 'frontend', 'clusters', 'clusterDetailLogic']),props({} as ClusterDetailLogicProps),key((props) => `${props.runId}:${props.clusterId}::${props.tabId ?? 'default'}`),- connect(() => ({- actions: [teamLogic, ['addProductIntent']],+ connect((props: ClusterDetailLogicProps) => ({+ values: [llmAnalyticsSharedLogic({ tabId: props.tabId }), ['propertyFilters', 'shouldFilterTestAccounts']],+ actions: [+ teamLogic,+ ['addProductIntent'],+ llmAnalyticsSharedLogic({ tabId: props.tabId }),+ ['setPropertyFilters', 'setShouldFilterTestAccounts', 'applyUrlState'],+ ],})),actions({@@ -74,6 +89,10 @@ export const clusterDetailLogic = kea<clusterDetailLogicType>([setClusterMetrics: (metrics: ClusterMetrics | null) => ({ metrics }),setClusterMetricsLoading: (loading: boolean) => ({ loading }),loadClusterMetricsForCluster: true,+ // Declared explicitly so kea-typegen generates a no-arg signature for the+ // loader action below — without this, the `(_, breakpoint)` loader signature+ // forces every call site to pass a placeholder argument.+ loadFilteredItemIds: true,}),reducers({@@ -109,7 +128,106 @@ export const clusterDetailLogic = kea<clusterDetailLogicType>([],}),- loaders(({ props }) => ({+ loaders(({ props, values }) => ({+ // 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.+ 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.+ 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.LLM_ANALYTICS, scene: LLM_ANALYTICS_CLUSTER_SCENE_TAG },+ }++ const response = await api.query(eventsQuery)+ 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+ },+ },+ ],+clusterData: [null as ClusterData | null,{@@ -264,22 +382,32 @@ export const clusterDetailLogic = kea<clusterDetailLogicType>([],sortedTraceIds: [- (s) => [s.cluster],- (cluster: Cluster | null): string[] => {+ (s) => [s.cluster, s.filteredItemIds],+ (cluster: Cluster | null, filteredItemIds: Set<string> | null): string[] => {if (!cluster) {return []}- return Object.entries(cluster.traces)+ const entries = Object.entries(cluster.traces)+ const filtered = filteredItemIds ? entries.filter(([id]) => filteredItemIds.has(id)) : entries+ return filtered.sort(([, a], [, b]) => (a as ClusterItemInfo).rank - (b as ClusterItemInfo).rank).map(([traceId]) => traceId)},],- totalTraces: [+ totalTraces: [(s) => [s.sortedTraceIds], (sortedTraceIds: string[]): number => sortedTraceIds.length],++ unfilteredTotalTraces: [(s) => [s.cluster],(cluster: Cluster | null): number => (cluster ? Object.keys(cluster.traces).length : 0),],+ hasActiveFilters: [+ (s) => [s.propertyFilters, s.shouldFilterTestAccounts],+ (propertyFilters: AnyPropertyFilter[], shouldFilterTestAccounts: boolean): boolean =>+ (propertyFilters?.length ?? 0) > 0 || shouldFilterTestAccounts,+ ],+totalPages: [(s) => [s.totalTraces], (totalTraces: number): number => Math.ceil(totalTraces / TRACES_PER_PAGE)],paginatedTraceIds: [@@ -339,6 +467,7 @@ export const clusterDetailLogic = kea<clusterDetailLogicType>([loadClusterDataSuccess: () => {actions.setPage(1)actions.loadClusterMetricsForCluster()+ actions.loadFilteredItemIds()void actions.addProductIntent({product_type: ProductKey.LLM_CLUSTERS,@@ -346,6 +475,24 @@ export const clusterDetailLogic = kea<clusterDetailLogicType>([})},+ // Filter-change listeners only kick the loader; resetting the page and reloading+ // summaries waits for the loader's success path so we don't burn a round-trip on+ // summaries for items the user is about to filter out. Both `setPropertyFilters`+ // and `applyUrlState` are needed: the first covers UI clicks (where actionToUrl+ // updates the URL but doesn't re-fire applyUrlState), the second covers deep+ // links and browser back/forward where applyUrlState is the only dispatch.+ setPropertyFilters: () => actions.loadFilteredItemIds(),+ setShouldFilterTestAccounts: () => actions.loadFilteredItemIds(),+ applyUrlState: () => actions.loadFilteredItemIds(),++ loadFilteredItemIdsSuccess: () => {+ // Resetting to page 1 fans out to the setPage listener, which loads summaries+ // for the now-correct first-page IDs. Doing it here keeps a single source of+ // truth for paging-reset-and-resummarize across both initial load and filter+ // changes.+ actions.setPage(1)+ },+loadClusterMetricsForCluster: async () => {const { cluster, windowStart, windowEnd, clusteringLevel } = valuesif (!cluster || !windowStart || !windowEnd) {@@ -409,7 +556,7 @@ export const clusterDetailLogic = kea<clusterDetailLogicType>([}),tabAwareUrlToAction(({ actions, props }) => ({- '/llm-analytics/clusters/:runId/:clusterId': ({ runId, clusterId }: { runId?: string; clusterId?: string }) => {+ [LLM_ANALYTICS_CLUSTER_URL_PATTERN]: ({ runId, clusterId }: { runId?: string; clusterId?: string }) => {const decodedRunId = runId ? decodeURIComponent(runId) : ''const parsedClusterId = clusterId ? parseInt(clusterId, 10) : 0diff --git a/products/llm_analytics/frontend/clusters/clustersLogic.test.ts b/products/llm_analytics/frontend/clusters/clustersLogic.test.tsindex 29075497dca8..60900e594f1f 100644--- a/products/llm_analytics/frontend/clusters/clustersLogic.test.ts+++ b/products/llm_analytics/frontend/clusters/clustersLogic.test.ts@@ -5,7 +5,7 @@ import { initKeaTests } from '~/test/init'import { clustersLogic } from './clustersLogic'import { NOISE_CLUSTER_ID } from './constants'import { EvaluationItemAttributes } from './traceSummaryLoader'-import { Cluster, ClusterMetrics, ClusteringRun } from './types'+import { Cluster, ClusterMetrics, ClusteringLevel, ClusteringRun } from './types'describe('clustersLogic', () => {let logic: ReturnType<typeof clustersLogic.build>@@ -498,6 +498,62 @@ describe('clustersLogic', () => {})})+ describe('currentRunMatchesLevel', () => {+ it('is false when no run is loaded', () => {+ expect(logic.values.currentRunMatchesLevel).toBe(false)+ })++ it('is true when the loaded run matches the active level', () => {+ logic.actions.setClusteringLevel('generation')+ logic.actions.loadClusteringRunSuccess({+ runId: 'r',+ clusters: [],+ level: 'generation',+ } as unknown as ClusteringRun)++ expect(logic.values.currentRunMatchesLevel).toBe(true)+ })++ it('is false when the loaded run is from a different level (level switch in flight)', () => {+ logic.actions.setClusteringLevel('trace')+ logic.actions.loadClusteringRunSuccess({+ runId: 'r',+ clusters: [],+ level: 'trace',+ } as unknown as ClusteringRun)+ expect(logic.values.currentRunMatchesLevel).toBe(true)++ // Simulate the user switching tabs — the previous run is still in state+ // until the new level's first run resolves. The guard should suppress it.+ logic.actions.setClusteringLevel('generation')+ expect(logic.values.currentRunMatchesLevel).toBe(false)+ })++ it('gates sortedClusters during a level switch', () => {+ logic.actions.setClusteringLevel('trace')+ logic.actions.loadClusteringRunSuccess({+ runId: 'r',+ clusters: [+ {+ cluster_id: 0,+ size: 1,+ title: 'T',+ description: '',+ traces: {},+ centroid: [],+ centroid_x: 0,+ centroid_y: 0,+ },+ ] as Cluster[],+ level: 'trace',+ } as unknown as ClusteringRun)+ expect(logic.values.sortedClusters).toHaveLength(1)++ logic.actions.setClusteringLevel('generation')+ expect(logic.values.sortedClusters).toEqual([])+ })+ })+describe('evaluation filter logic', () => {const sampleAttrs: Record<string, EvaluationItemAttributes> = {'id-pass-a': { evaluatorName: 'Accuracy', verdict: 'pass' },@@ -674,17 +730,20 @@ describe('clustersLogic', () => {},]- const loadClustersAsCurrentRun = (): void => {+ const loadClustersAsCurrentRun = (level?: ClusteringLevel): void => {// filteredSortedClusters reads off the currentRun; seed a run and hydrate the cache.+ // We pass the run's level so the level-mismatch guard in `sortedClusters` (which+ // exists to suppress stale cards during a level switch) treats the seed as live.logic.actions.loadClusteringRunSuccess({runId: 'test-run',clusters: sampleClusters,+ level: level ?? logic.values.clusteringLevel,} as ClusteringRun)}it('returns clusters unchanged when no filter is active', () => {- loadClustersAsCurrentRun()setEvalLevelAndAttrs()+ loadClustersAsCurrentRun()const result = logic.values.filteredSortedClustersexpect(result).toHaveLength(2)@@ -694,8 +753,8 @@ describe('clustersLogic', () => {})it('drops non-matching traces, rewrites size, and prunes clusters that empty out', () => {- loadClustersAsCurrentRun()setEvalLevelAndAttrs()+ loadClustersAsCurrentRun()logic.actions.setEvalVerdictsFilter(['pass'])// Cluster 0 keeps its two pass traces; cluster 1's items are all fail/n/a so it's pruned.@@ -705,6 +764,90 @@ describe('clustersLogic', () => {expect(Object.keys(result[0].traces).sort()).toEqual(['id-pass-a', 'id-pass-b'])expect(result[0].size).toBe(2)})++ it('narrows clusters by propertyFilteredItemIds (cohort / property filter)', () => {+ loadClustersAsCurrentRun()+ // Property filter alone — the eval-level branch isn't relevant here.+ logic.actions.loadPropertyFilteredItemIdsSuccess(new Set(['id-pass-a', 'id-fail-b']))++ // Without an active filter declared, anyFiltersActive is false, so+ // filteredSortedClusters short-circuits to the unfiltered list. Set+ // a property filter to make the gate true.+ logic.actions.setPropertyFilters([+ {+ type: 'person' as any,+ key: 'email',+ value: '@example.com',+ operator: 'icontains' as any,+ } as any,+ ])++ const result = logic.values.filteredSortedClusters+ expect(result).toHaveLength(2)+ const byId = Object.fromEntries(result.map((c) => [c.cluster_id, c]))+ // Cluster 0 keeps only id-pass-a; size becomes 1.+ expect(Object.keys(byId[0].traces).sort()).toEqual(['id-pass-a'])+ expect(byId[0].size).toBe(1)+ // Cluster 1 keeps only id-fail-b; size becomes 1.+ expect(Object.keys(byId[1].traces).sort()).toEqual(['id-fail-b'])+ expect(byId[1].size).toBe(1)+ })++ it('combines property and eval filters (intersection)', () => {+ setEvalLevelAndAttrs()+ loadClustersAsCurrentRun()+ // Property filter narrows to {id-pass-a, id-pass-b, id-fail-b}, eval verdict+ // narrows to {id-pass-a, id-pass-b}; the intersection should be {id-pass-a,+ // id-pass-b}, so cluster 1 (only id-fail-b survives the property filter,+ // but verdict 'pass' rules it out) drops entirely.+ logic.actions.loadPropertyFilteredItemIdsSuccess(new Set(['id-pass-a', 'id-pass-b', 'id-fail-b']))+ logic.actions.setEvalVerdictsFilter(['pass'])++ const result = logic.values.filteredSortedClusters+ expect(result).toHaveLength(1)+ expect(result[0].cluster_id).toBe(0)+ expect(Object.keys(result[0].traces).sort()).toEqual(['id-pass-a', 'id-pass-b'])+ })++ it('treats null propertyFilteredItemIds as "no property filter applied"', () => {+ loadClustersAsCurrentRun()+ // Property filter set but loader returned null — e.g. cluster too large+ // for the row cap. We must show every cluster rather than empty out.+ logic.actions.setPropertyFilters([+ {+ type: 'person' as any,+ key: 'email',+ value: '@example.com',+ operator: 'icontains' as any,+ } as any,+ ])+ logic.actions.loadPropertyFilteredItemIdsSuccess(null)++ const result = logic.values.filteredSortedClusters+ expect(result).toHaveLength(2)+ })+ })++ describe('propertyFiltersActive / anyFiltersActive', () => {+ it('propertyFiltersActive flips with property filters and the test-accounts toggle', () => {+ expect(logic.values.propertyFiltersActive).toBe(false)++ logic.actions.setShouldFilterTestAccounts(true)+ expect(logic.values.propertyFiltersActive).toBe(true)++ logic.actions.setShouldFilterTestAccounts(false)+ logic.actions.setPropertyFilters([+ { type: 'cohort' as any, key: 'id', value: 7, operator: 'in' as any } as any,+ ])+ expect(logic.values.propertyFiltersActive).toBe(true)+ })++ it('anyFiltersActive is true when either filter family is active', () => {+ expect(logic.values.anyFiltersActive).toBe(false)++ logic.actions.setShouldFilterTestAccounts(true)+ expect(logic.values.anyFiltersActive).toBe(true)+ })})})})diff --git a/products/llm_analytics/frontend/clusters/clustersLogic.ts b/products/llm_analytics/frontend/clusters/clustersLogic.tsindex 72fd540fbc87..a36734e16dcf 100644--- a/products/llm_analytics/frontend/clusters/clustersLogic.ts+++ b/products/llm_analytics/frontend/clusters/clustersLogic.ts@@ -1,5 +1,6 @@-import { actions, afterMount, kea, key, listeners, path, props, reducers, selectors } from 'kea'+import { actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'import { loaders } from 'kea-loaders'+import { router } from 'kea-router'import posthog from 'posthog-js'import api from 'lib/api'@@ -10,12 +11,21 @@ import { tabAwareActionToUrl } from 'lib/logic/scenes/tabAwareActionToUrl'import { tabAwareUrlToAction } from 'lib/logic/scenes/tabAwareUrlToAction'import { urls } from 'scenes/urls'+import { EventsQuery, NodeKind, ProductKey } from '~/queries/schema/schema-general'import { hogql } from '~/queries/utils'-import { Breadcrumb } from '~/types'+import { AnyPropertyFilter, Breadcrumb, PropertyFilterType, PropertyOperator } from '~/types'+import { llmAnalyticsSharedLogic } from '../llmAnalyticsSharedLogic'import { loadClusterMetrics } from './clusterMetricsLoader'import type { clustersLogicType } from './clustersLogicType'-import { MAX_CLUSTERING_RUNS, NOISE_CLUSTER_ID, OUTLIER_COLOR } from './constants'+import {+ FILTER_QUERY_MAX_ROWS,+ LLM_ANALYTICS_CLUSTERS_SCENE_TAG,+ MAX_CLUSTERING_RUNS,+ NOISE_CLUSTER_ID,+ OUTLIER_COLOR,+ SAFE_ID_RE,+} from './constants'import {EvaluationItemAttributes,EvaluationVerdict,@@ -85,8 +95,20 @@ export const clustersLogic = kea<clustersLogicType>([props({} as ClustersLogicProps),key((props) => props.tabId ?? 'default'),+ connect((props: ClustersLogicProps) => ({+ values: [llmAnalyticsSharedLogic({ tabId: props.tabId }), ['propertyFilters', 'shouldFilterTestAccounts']],+ actions: [+ llmAnalyticsSharedLogic({ tabId: props.tabId }),+ ['setPropertyFilters', 'setShouldFilterTestAccounts', 'applyUrlState'],+ ],+ })),+actions({setClusteringLevel: (level: ClusteringLevel) => ({ level }),+ // Declared explicitly so kea-typegen emits a no-arg signature for the loader+ // action below — without this, the `(_, breakpoint)` loader signature forces+ // every call site to pass a placeholder argument.+ loadPropertyFilteredItemIds: true,syncClusteringLevelFromRun: (level: ClusteringLevel) => ({ level }),setSelectedRunId: (runId: string | null) => ({ runId }),toggleClusterExpanded: (clusterId: number) => ({ clusterId }),@@ -202,6 +224,102 @@ export const clustersLogic = kea<clustersLogicType>([}),loaders(({ values }) => ({+ // Subset of the current run's item IDs that match the user's active property+ // filters (cohorts, person properties, group properties, etc.). Null when no+ // filters are active or filtering can't be applied — selectors treat null as+ // "show everything" so unfiltered runs skip the round-trip.+ propertyFilteredItemIds: [+ null as Set<string> | null,+ {+ loadPropertyFilteredItemIds: async (_, breakpoint) => {+ // Debounce overlapping filter changes (quick toggles or successive+ // cohort selections) into a single EventsQuery 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.LLM_ANALYTICS, scene: LLM_ANALYTICS_CLUSTERS_SCENE_TAG },+ }++ const response = await api.query(eventsQuery)+ 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+ },+ },+ ],+clusteringRuns: [[] as ClusteringRunOption[],{@@ -346,10 +464,26 @@ export const clustersLogic = kea<clustersLogicType>([},],+ // True while the loaded run still belongs to the level the user is currently+ // looking at. Goes false the moment the user switches levels, until the new+ // level's first run resolves — gates downstream selectors so we don't paint+ // trace cards on the Generations tab during the load. kea-loaders preserves+ // the previous loader value, so without this check `currentRun` would still+ // be the trace-level run for a few hundred milliseconds.+ //+ // Runs emitted before the `clustering_level` event property existed are inferred+ // as 'trace' by `loadClusteringRun` via `getLevelFromRunId`, so the same default+ // applies here for any path that bypasses the loader (e.g. test fixtures).+ currentRunMatchesLevel: [+ (s) => [s.currentRun, s.clusteringLevel],+ (currentRun: ClusteringRun | null, level: ClusteringLevel): boolean =>+ !!currentRun && (currentRun.level || 'trace') === level,+ ],+sortedClusters: [- (s) => [s.currentRun],- (currentRun: ClusteringRun | null): Cluster[] => {- if (!currentRun?.clusters) {+ (s) => [s.currentRun, s.currentRunMatchesLevel],+ (currentRun: ClusteringRun | null, matches: boolean): Cluster[] => {+ if (!matches || !currentRun?.clusters) {return []}return [...currentRun.clusters].sort((a, b) => b.size - a.size)@@ -421,8 +555,41 @@ export const clustersLogic = kea<clustersLogicType>([},],+ propertyFiltersActive: [+ (s) => [s.propertyFilters, s.shouldFilterTestAccounts],+ (propertyFilters: AnyPropertyFilter[], shouldFilterTestAccounts: boolean): boolean =>+ (propertyFilters?.length ?? 0) > 0 || shouldFilterTestAccounts,+ ],++ anyFiltersActive: [+ (s) => [s.evalFiltersActive, s.propertyFiltersActive],+ (evalActive: boolean, propertyActive: boolean): boolean => evalActive || propertyActive,+ ],++ // Single predicate combines the eval-specific filter (for evaluation-level clusters)+ // with the cohort/property filter (for trace and generation levels). Cluster cards,+ // scatter plot, and distribution bar all derive from this so the views can never+ // diverge on which items count as "in" the filtered set.+ clusterMembershipPredicate: [+ (s) => [s.evalFilterPredicate, s.propertyFilteredItemIds],+ (+ evalPredicate: (id: string) => boolean,+ propertyFilteredItemIds: Set<string> | null+ ): ((id: string) => boolean) => {+ return (id: string) => {+ if (!evalPredicate(id)) {+ return false+ }+ if (propertyFilteredItemIds && !propertyFilteredItemIds.has(id)) {+ return false+ }+ return true+ }+ },+ ],+filteredSortedClusters: [- (s) => [s.sortedClusters, s.evalFilterPredicate, s.evalFiltersActive],+ (s) => [s.sortedClusters, s.clusterMembershipPredicate, s.anyFiltersActive],(clusters: Cluster[], predicate: (id: string) => boolean, active: boolean): Cluster[] => {if (!active) {return clusters@@ -671,9 +838,29 @@ export const clustersLogic = kea<clustersLogicType>([// For evaluation runs, also load the per-item (evaluator name, verdict) lookup// so the post-hoc filter bar can drive scatter + cluster card filtering.actions.loadEvaluationAttributesForRun(currentRun)+ // Re-run the property filter against the new run's items. The shared filter+ // state is preserved across run switches, so a previously filtered view+ // should immediately narrow the new run's clusters.+ actions.loadPropertyFilteredItemIds()}},+ // 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+ // 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+ // the URL, but `applySearchParams` short-circuits because URL and state+ // already agree, so `applyUrlState` is *not* fired in this path.+ // - Deep links and browser back/forward fire the URL handler first; that+ // path detects the divergence and dispatches `applyUrlState` (not+ // `setPropertyFilters`) to sync state.+ // The 150ms breakpoint debounce inside the loader collapses any stray double+ // dispatches into a single round-trip.+ setPropertyFilters: () => actions.loadPropertyFilteredItemIds(),+ setShouldFilterTestAccounts: () => actions.loadPropertyFilteredItemIds(),+ applyUrlState: () => actions.loadPropertyFilteredItemIds(),+loadClusteringRunFailure: () => {lemonToast.error('Failed to load clustering run')},@@ -709,22 +896,37 @@ export const clustersLogic = kea<clustersLogicType>([actions.loadClusteringRuns()}),- tabAwareUrlToAction(({ actions }) => ({+ tabAwareUrlToAction(({ actions, values }) => ({'/llm-analytics/clusters': () => {- actions.setSelectedRunId(null)+ if (values.selectedRunId !== null) {+ actions.setSelectedRunId(null)+ }},'/llm-analytics/clusters/:runId': ({ runId }: { runId?: string }) => {- // Decode the URL-encoded runId- actions.setSelectedRunId(runId ? decodeURIComponent(runId) : null)+ // Decode the URL-encoded runId. Only re-dispatch when the runId actually+ // changed — a filter change updates the URL's search params (?filters=…)+ // but keeps the same path, and re-firing `setSelectedRunId` here would+ // chain into `loadClusteringRun` → `loadClusteringRunSuccess` →+ // `loadPropertyFilteredItemIds`, which races with the loader the+ // `setPropertyFilters` listener already kicked off and silently aborts it.+ const newRunId = runId ? decodeURIComponent(runId) : null+ if (newRunId !== values.selectedRunId) {+ actions.setSelectedRunId(newRunId)+ }},})),tabAwareActionToUrl(({ values }) => ({setSelectedRunId: () => {- if (values.selectedRunId) {- return urls.llmAnalyticsClusters(values.selectedRunId)- }- return urls.llmAnalyticsClusters()+ // Preserve any search params already on the URL — `setPropertyFilters` (in the+ // shared logic) writes `?filters=...` and `?filter_test_accounts=...`, and the+ // route handler immediately echoes that back through `setSelectedRunId(currentRunId)`.+ // Returning a bare path here would strip those params, the URL handler would re-fire+ // with an empty `filters` set, and the property filter would be reset on every change.+ const pathname = values.selectedRunId+ ? urls.llmAnalyticsClusters(values.selectedRunId)+ : urls.llmAnalyticsClusters()+ return [pathname, router.values.searchParams]},})),])diff --git a/products/llm_analytics/frontend/clusters/constants.ts b/products/llm_analytics/frontend/clusters/constants.tsindex c5219567f013..404db91ab1c1 100644--- a/products/llm_analytics/frontend/clusters/constants.ts+++ b/products/llm_analytics/frontend/clusters/constants.ts@@ -10,6 +10,28 @@ export const TRACES_PER_PAGE = 50// Query limitsexport const MAX_CLUSTERING_RUNS = 20+// Cluster detail URL pattern. Mirrored in `manifest.tsx`'s route registration so any+// `tabAwareUrlToAction` matcher (e.g. `clusterDetailLogic`, `llmAnalyticsSharedLogic`)+// stays in lockstep with the actual route.+export const LLM_ANALYTICS_CLUSTER_URL_PATTERN = '/llm-analytics/clusters/:runId/:clusterId'++// Scene names used as ClickHouse query tags. These match the route registrations in+// `manifest.tsx`, and the query runner pulls them off `query.tags.scene` to attach to+// every executed query for analytics. Centralised so the tags don't drift if the scene+// names ever change.+export const LLM_ANALYTICS_CLUSTERS_SCENE_TAG = 'LLMAnalyticsClusters'+export const LLM_ANALYTICS_CLUSTER_SCENE_TAG = 'LLMAnalyticsCluster'++// 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.+export const SAFE_ID_RE = /^[a-f0-9-]+$/i++// Mirrors `MAX_SELECT_RETURNED_ROWS` in `posthog/hogql/constants.py`. EventsQuery 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+/*** Centroid detection for chart.js scatter datasets.*diff --git a/products/llm_analytics/frontend/llmAnalyticsSharedLogic.ts b/products/llm_analytics/frontend/llmAnalyticsSharedLogic.tsindex 265e683e2109..d672108ea6c8 100644--- a/products/llm_analytics/frontend/llmAnalyticsSharedLogic.ts+++ b/products/llm_analytics/frontend/llmAnalyticsSharedLogic.ts@@ -18,6 +18,7 @@ import { isAnyPropertyFilters } from '~/queries/schema-guards'import { ProductIntentContext, ProductKey } from '~/queries/schema/schema-general'import { AnyPropertyFilter, Breadcrumb } from '~/types'+import { LLM_ANALYTICS_CLUSTER_URL_PATTERN } from './clusters/constants'import type { llmAnalyticsSharedLogicType } from './llmAnalyticsSharedLogicType'export const LLM_ANALYTICS_DATA_COLLECTION_NODE_ID = 'llm-analytics-data'@@ -337,6 +338,11 @@ export const llmAnalyticsSharedLogic = kea<llmAnalyticsSharedLogicType>([[urls.llmAnalyticsSentiment()]: (_, searchParams) => applyNonDashboard(searchParams),[urls.llmAnalyticsSessions()]: (_, searchParams) => applyNonDashboard(searchParams),[urls.llmAnalyticsPlayground()]: (_, searchParams) => applyNonDashboard(searchParams),+ // Cluster list and detail both honor the same `filters` / `filter_test_accounts`+ // params so deep links from generations/traces tabs carry their filter set through.+ [urls.llmAnalyticsClusters()]: (_, searchParams) => applyNonDashboard(searchParams),+ '/llm-analytics/clusters/:runId': (_, searchParams) => applyNonDashboard(searchParams),+ [LLM_ANALYTICS_CLUSTER_URL_PATTERN]: (_, searchParams) => applyNonDashboard(searchParams),}}),diff --git a/products/llm_analytics/manifest.tsx b/products/llm_analytics/manifest.tsxindex b8ec5f3ef940..90e9a96633b5 100644--- a/products/llm_analytics/manifest.tsx+++ b/products/llm_analytics/manifest.tsx@@ -6,6 +6,7 @@ import { urls } from 'scenes/urls'import { FileSystemIconType, ProductItemCategory, ProductKey } from '~/queries/schema/schema-general'import { FileSystemIconColor, ProductManifest } from '../../frontend/src/types'+import { LLM_ANALYTICS_CLUSTER_URL_PATTERN } from './frontend/clusters/constants'export const manifest: ProductManifest = {name: 'LLM Analytics',@@ -178,7 +179,7 @@ export const manifest: ProductManifest = {'/llm-analytics/skills/:name': ['LLMAnalyticsSkill', 'llmAnalyticsSkill'],'/llm-analytics/clusters': ['LLMAnalyticsClusters', 'llmAnalyticsClusters'],'/llm-analytics/clusters/:runId': ['LLMAnalyticsClusters', 'llmAnalyticsClusters'],- '/llm-analytics/clusters/:runId/:clusterId': ['LLMAnalyticsCluster', 'llmAnalyticsCluster'],+ [LLM_ANALYTICS_CLUSTER_URL_PATTERN]: ['LLMAnalyticsCluster', 'llmAnalyticsCluster'],},redirects: {'/llm-analytics': (_params, searchParams, hashParams) =>