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.

perf(insights): load only referenced cohorts (#102626)

Matt Puae4b31061b7c9
diff --git a/docs/internal/taxonomic-filter-search.md b/docs/internal/taxonomic-filter-search.md
index b906e82ec7aa..0d61bc882521 100644
--- a/docs/internal/taxonomic-filter-search.md
+++ b/docs/internal/taxonomic-filter-search.md
@@ -25,3 +25,21 @@ Local filtering and rendering still update on each keystroke.
The event definitions API counts matching rows separately and applies `LIMIT` and `OFFSET` in PostgreSQL. The count describes all matches, including matches outside the requested page. Explicit ordering uses the project-unique event name as a final tie-breaker so equal timestamps do not cause skipped or repeated results between pages.
Tag-filtered requests retain ORM pagination after resolving matching event IDs. Both paths preserve the same response fields and project scope, including legacy definitions whose `project_id` is null.
+
+## Cohort names on individual insights
+
+Individual insight pages load cohort names by ID from the query's cohort property filters and cohort breakdowns.
+This includes edit, subscriptions, alerts, and sharing routes with optional item IDs; the separate `quick-start` scene keeps the full list load.
+These requests use the parent project ID, which can differ from the current environment ID.
+They reuse the shared cohort cache when the query changes, and resolve nested cohort references for definition popovers.
+The shared model queues cohort detail requests with at most 10 in flight across overlapping loads and nested references.
+This limits concurrent requests, not the total number of references an insight can resolve.
+An insight without cohort references does not load the cohort list.
+The insight breadcrumb subscribes to the resolved insight name so generated titles update when cohort names arrive.
+The cohort picker continues to load its options independently.
+Opening an AI visualization's definition resolves its cohort references even when the chart is collapsed.
+Navigating from a dashboard reuses the cohorts already in the shared cache and fetches only missing references.
+
+Other pages retain the shared model's full-list loading behavior.
+The model stays mounted across navigation, so leaving an individual insight must trigger the list load if it has not already run.
+Keep both `cohortsById` and `allCohorts.results` populated: insight titles and filter chips use the former, while charts, legends, tooltips, and color settings use the latter.
diff --git a/frontend/src/lib/components/DefinitionPopover/definitionPopoverLogic.test.ts b/frontend/src/lib/components/DefinitionPopover/definitionPopoverLogic.test.ts
index 935dc1d3d4b0..9e3ae8f2f1d7 100644
--- a/frontend/src/lib/components/DefinitionPopover/definitionPopoverLogic.test.ts
+++ b/frontend/src/lib/components/DefinitionPopover/definitionPopoverLogic.test.ts
@@ -1,5 +1,6 @@
import { MOCK_TEAM_ID } from 'lib/api.mock'
+import { router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
import api from 'lib/api'
@@ -81,6 +82,22 @@ describe('definitionPopoverLogic', () => {
cohortsModel.mount()
})
+ it('resolves nested names when previewing an unselected cohort on an insight', async () => {
+ await expectLogic(cohortsModel).toFinishAllListeners()
+ router.actions.push('/insights/123')
+ useMocks({ get: { '/api/projects/:team/cohorts/3000/': { ...mockCohort, id: 3000, name: 'Nested cohort' } } })
+ logic = definitionPopoverLogic({ type: TaxonomicFilterGroupType.Cohorts })
+ logic.mount()
+ await expectLogic(logic, () =>
+ logic.actions.setDefinition({
+ ...mockCohort,
+ filters: { properties: { type: 'AND', values: [{ type: 'cohort', value: 3000 }] } },
+ } as unknown as CohortType)
+ ).toFinishAllListeners()
+ await expectLogic(cohortsModel).toFinishAllListeners()
+ expect(cohortsModel.values.cohortsById[3000]?.name).toBe('Nested cohort')
+ })
+
describe('editing mode', () => {
beforeEach(() => {
logic = definitionPopoverLogic({
diff --git a/frontend/src/lib/components/DefinitionPopover/definitionPopoverLogic.ts b/frontend/src/lib/components/DefinitionPopover/definitionPopoverLogic.ts
index fcaff2eba6e4..77a92b99a34a 100644
--- a/frontend/src/lib/components/DefinitionPopover/definitionPopoverLogic.ts
+++ b/frontend/src/lib/components/DefinitionPopover/definitionPopoverLogic.ts
@@ -1,6 +1,7 @@
import { deepEqual as equal } from 'fast-equals'
import { MakeLogicType, actions, connect, events, kea, listeners, path, props, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
+import { router } from 'kea-router'
import api from 'lib/api'
import { getSingularType } from 'lib/components/DefinitionPopover/utils'
@@ -14,7 +15,7 @@ import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
import { actionsModel } from '~/models/actionsModel'
-import { cohortsModel } from '~/models/cohortsModel'
+import { cohortsModel, getReferencedCohortIds, isIndividualInsightPath } from '~/models/cohortsModel'
import { propertyDefinitionsModel, updatePropertyDefinitions } from '~/models/propertyDefinitionsModel'
import { ActionType, CohortType, EventDefinition, PropertyDefinition } from '~/types'
@@ -438,7 +439,13 @@ export const definitionPopoverLogic = kea<definitionPopoverLogicType>([
],
}),
listeners(({ actions, selectors, values, props, cache }) => ({
- setDefinition: (_, __, ___, previousState) => {
+ setDefinition: ({ item }, __, ___, previousState) => {
+ if (values.isCohort && isIndividualInsightPath(router.values.location.pathname)) {
+ const ids = getReferencedCohortIds((item as Partial<CohortType>).filters)
+ if (ids.length) {
+ cohortsModel.findMounted()?.actions.loadCohortsByIds({ ids })
+ }
+ }
// Reset definition popover to view mode if context is switched
if (
selectors.definition(previousState)?.name &&
diff --git a/frontend/src/models/cohortsModel.test.ts b/frontend/src/models/cohortsModel.test.ts
index 618429aa67d9..3528b5f291d2 100644
--- a/frontend/src/models/cohortsModel.test.ts
+++ b/frontend/src/models/cohortsModel.test.ts
@@ -1,14 +1,19 @@
+import { MOCK_DEFAULT_TEAM } from 'lib/api.mock'
+
import { router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
import api from 'lib/api'
+import { promiseResolveReject } from 'lib/utils/async'
import { urls } from 'scenes/urls'
import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
import { CohortType, FilterLogicalOperator } from '~/types'
-import { cohortsModel, processCohort } from './cohortsModel'
+import { cohortsModel, getReferencedCohortIds, processCohort } from './cohortsModel'
+
+jest.unmock('lib/utils/concurrencyController')
const MOCK_COHORTS = {
count: 2,
@@ -102,6 +107,232 @@ describe('cohortsModel', () => {
})
})
+ describe('individual insights', () => {
+ const list = jest.fn(() => MOCK_COHORTS)
+ const requestedIds: number[] = []
+
+ beforeEach(async () => {
+ await expectLogic(logic).toFinishAllListeners()
+ initKeaTests(true, { ...MOCK_DEFAULT_TEAM, id: MOCK_DEFAULT_TEAM.id + 1 })
+ router.actions.push('/project/997/insights/abc123')
+ list.mockClear()
+ requestedIds.length = 0
+ useMocks({
+ get: {
+ '/api/projects/:team/cohorts/': list,
+ '/api/projects/:team/cohorts/:id/': ({ params }) => {
+ if (params.team !== String(MOCK_DEFAULT_TEAM.project_id)) {
+ return [404, { detail: 'Project not found.' }]
+ }
+ const id = Number(params.id)
+ requestedIds.push(id)
+ return { ...MOCK_COHORTS.results[0], id, name: `Cohort ${id}` }
+ },
+ },
+ })
+ logic = cohortsModel()
+ logic.mount()
+ })
+
+ it('skips the list, resolves only missing IDs, and preserves both cache views', async () => {
+ await expectLogic(logic).toFinishAllListeners()
+ expect(list).not.toHaveBeenCalled()
+ await expectLogic(logic, () => {
+ logic.actions.loadCohortsByIds({ ids: [1, 1, 3000, 0, -1] })
+ logic.actions.loadCohortsByIds({ ids: [1, 2] })
+ }).toFinishAllListeners()
+ expect(requestedIds.sort((a, b) => a - b)).toEqual([1, 2, 3000])
+ expect(Object.keys(logic.values.cohortsById)).toEqual(['1', '2', '3000'])
+ expect(logic.values.cohortsById[3000]?.name).toBe('Cohort 3000')
+ expect(logic.values.allCohorts.results).toHaveLength(3)
+ await expectLogic(logic, () => logic.actions.loadCohortsByIds({ ids: [1, 3000] })).toFinishAllListeners()
+ expect(requestedIds).toHaveLength(3)
+ expect(list).not.toHaveBeenCalled()
+ })
+
+ it('limits overlapping and nested cohort requests to ten in flight and drains after failures', async () => {
+ const firstTen = promiseResolveReject<void>()
+ const nextStarted = promiseResolveReject<void>()
+ const firstResponse = promiseResolveReject<void>()
+ const remainingResponses = promiseResolveReject<void>()
+ let active = 0
+ let peak = 0
+ useMocks({
+ get: {
+ '/api/projects/:team/cohorts/:id/': async ({ params }) => {
+ const id = Number(params.id)
+ requestedIds.push(id)
+ peak = Math.max(peak, ++active)
+ if (requestedIds.length === 10) {
+ firstTen.resolve()
+ }
+ if (requestedIds.length === 11) {
+ nextStarted.resolve()
+ }
+ await (id === 1 ? firstResponse.promise : remainingResponses.promise)
+ active--
+ if (id === 2) {
+ return [403, { detail: 'Forbidden.' }]
+ }
+ return {
+ ...MOCK_COHORTS.results[0],
+ id,
+ filters: {
+ properties: {
+ type: 'AND',
+ values:
+ id === 1
+ ? [{ type: 'cohort', value: Array.from({ length: 15 }, (_, i) => i + 21) }]
+ : [],
+ },
+ },
+ }
+ },
+ },
+ })
+ logic.actions.loadCohortsByIds({ ids: Array.from({ length: 15 }, (_, i) => i + 1) })
+ logic.actions.loadCohortsByIds({ ids: Array.from({ length: 11 }, (_, i) => i + 10) })
+ await firstTen.promise
+ expect(active).toBe(10)
+ expect(requestedIds).toHaveLength(10)
+ firstResponse.resolve()
+ await nextStarted.promise
+ expect(active).toBe(10)
+ remainingResponses.resolve()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(peak).toBe(10)
+ expect(requestedIds.sort((a, b) => a - b)).toEqual(Array.from({ length: 35 }, (_, i) => i + 1))
+ expect(logic.values.allCohorts.results).toHaveLength(34)
+ expect(logic.values.cohortsById[35]).toMatchObject({ id: 35 })
+ })
+
+ it.each([
+ '/insights/abc123/edit',
+ '/project/997/insights/abc123/subscriptions',
+ '/project/997/insights/abc123/subscriptions/123',
+ '/insights/abc123/alerts',
+ '/insights/abc123/alerts/123/',
+ '/project/997/insights/abc123/sharing',
+ '/insights/new',
+ ])('keeps targeted loading when navigating to %s', async (pathname) => {
+ await expectLogic(logic, () => router.actions.push(pathname)).toFinishAllListeners()
+ await expectLogic(logic, () => logic.actions.loadCohortsByIds({ ids: [3000] })).toFinishAllListeners()
+ expect(list).not.toHaveBeenCalled()
+ expect(requestedIds).toEqual([3000])
+ expect(logic.values.cohortsById[3000]?.name).toBe('Cohort 3000')
+ })
+
+ it.each([
+ '/insights',
+ '/insights/quick-start',
+ '/project/997/insights/quick-start/',
+ '/feature_flags',
+ '/cohorts',
+ '/dashboard/1',
+ ])('loads the full list after navigating to %s', async (pathname) => {
+ await expectLogic(logic, () => router.actions.push(pathname)).toFinishAllListeners()
+ expect(list).toHaveBeenCalledTimes(1)
+ expect(logic.values.cohortsById[2]?.name).toBe('Cohort two')
+ await expectLogic(logic, () => router.actions.replace(pathname, { search: 'test' })).toFinishAllListeners()
+ expect(list).toHaveBeenCalledTimes(1)
+ })
+
+ it('reuses dashboard cohorts and fetches only references outside the loaded list', async () => {
+ await expectLogic(logic, () => router.actions.push('/dashboard/1')).toFinishAllListeners()
+ expect(list).toHaveBeenCalledTimes(1)
+ await expectLogic(logic, () => router.actions.push('/insights/abc123')).toFinishAllListeners()
+ await expectLogic(logic, () => logic.actions.loadCohortsByIds({ ids: [1, 2, 3000] })).toFinishAllListeners()
+ expect(requestedIds).toEqual([3000])
+ expect(logic.values.cohortsById[2]?.name).toBe('Cohort two')
+ expect(logic.values.cohortsById[3000]?.name).toBe('Cohort 3000')
+ expect(list).toHaveBeenCalledTimes(1)
+ })
+
+ it('preserves targeted names when a list request finishes after returning to the insight', async () => {
+ let releaseList!: () => void
+ const listReady = new Promise<void>((resolve) => {
+ releaseList = resolve
+ })
+ useMocks({
+ get: {
+ '/api/projects/:team/cohorts/': async () => {
+ await listReady
+ return MOCK_COHORTS
+ },
+ },
+ })
+ await expectLogic(logic, () => logic.actions.loadCohortsByIds({ ids: [3000] })).toFinishAllListeners()
+ await expectLogic(logic, () => router.actions.push('/feature_flags')).toDispatchActions(['loadAllCohorts'])
+ router.actions.push('/insights/abc123')
+ releaseList()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(Object.keys(logic.values.cohortsById)).toEqual(['1', '2', '3000'])
+ expect(logic.values.cohortsById[3000]?.name).toBe('Cohort 3000')
+ })
+
+ it('loads nested cohort names without looping on circular references', async () => {
+ useMocks({
+ get: {
+ '/api/projects/:team/cohorts/:id/': ({ params }) => {
+ const id = Number(params.id)
+ requestedIds.push(id)
+ return {
+ ...MOCK_COHORTS.results[0],
+ id,
+ filters: {
+ properties: { type: 'AND', values: [{ type: 'cohort', value: id === 1 ? 2 : 1 }] },
+ },
+ }
+ },
+ },
+ })
+ await expectLogic(logic, () => logic.actions.loadCohortsByIds({ ids: [1] })).toFinishAllListeners()
+ expect(requestedIds).toEqual([1, 2])
+ expect(Object.keys(logic.values.cohortsById)).toEqual(['1', '2'])
+ })
+
+ it.each([403, 404, 500])('keeps successful names and allows retry after a %s response', async (status) => {
+ useMocks({
+ get: {
+ '/api/projects/:team/cohorts/2/': [status, { detail: 'Unavailable' }],
+ },
+ })
+ await expectLogic(logic, () => logic.actions.loadCohortsByIds({ ids: [1, 2] })).toFinishAllListeners()
+ expect(logic.values.cohortsById[1]?.name).toBe('Cohort 1')
+ expect(logic.values.cohortsById[2]).toBeUndefined()
+ useMocks({ get: { '/api/projects/:team/cohorts/2/': MOCK_COHORTS.results[1] } })
+ await expectLogic(logic, () => logic.actions.loadCohortsByIds({ ids: [2] })).toFinishAllListeners()
+ expect(logic.values.cohortsById[2]?.name).toBe('Cohort two')
+ })
+ })
+
+ describe('referenced cohort IDs', () => {
+ it.each([
+ [null, []],
+ [{ properties: [{ type: 'event', key: 'cohort', value: 42 }] }, []],
+ [
+ {
+ source: {
+ properties: {
+ type: 'AND',
+ values: [
+ { type: 'cohort', value: '12' },
+ { type: 'cohort', value: [12, 34] },
+ ],
+ },
+ series: [{ properties: [{ type: 'cohort', value: 56 }] }],
+ breakdownFilter: { breakdown_type: 'cohort', breakdown: [34, '78', 'all', 0, -1] },
+ },
+ },
+ [12, 34, 56, 78],
+ ],
+ [{ breakdownFilter: { breakdown_type: 'cohort', breakdown: 99 } }, [99]],
+ [{ properties: [{ type: 'cohort', value: ['nope', null, true, 1.2] }] }, []],
+ ])('extracts references from %j', (query, expected) => {
+ expect(getReferencedCohortIds(query)).toEqual(expected)
+ })
+ })
+
describe('cohort operations', () => {
it('can update a cohort', async () => {
// Wait for initial load
diff --git a/frontend/src/models/cohortsModel.ts b/frontend/src/models/cohortsModel.ts
index e09a1b481ef5..5c53162e29b8 100644
--- a/frontend/src/models/cohortsModel.ts
+++ b/frontend/src/models/cohortsModel.ts
@@ -12,6 +12,7 @@ import {
} from 'kea'
import { loaders } from 'kea-loaders'
import { router } from 'kea-router'
+import type { LocationChangedPayload } from 'kea-router/lib/types'
import { v4 as uuidv4 } from 'uuid'
import api, { CountedPaginatedResponse } from 'lib/api'
@@ -21,6 +22,7 @@ import {
invalidateTaxonomicResourcesWhere,
} from 'lib/components/TaxonomicFilter/hooks/useTaxonomicResource'
import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
+import { ConcurrencyController } from 'lib/utils/concurrencyController'
import { deleteWithUndo } from 'lib/utils/deleteWithUndo'
import { permanentlyMount } from 'lib/utils/kea-logic-builders'
import { COHORT_EVENT_TYPES_WITH_EXPLICIT_DATETIME } from 'scenes/cohorts/CohortFilters/constants'
@@ -39,12 +41,51 @@ import {
FilterLogicalOperator,
} from '~/types'
+import * as cohortsApi from 'products/cohorts/frontend/generated/api'
import { personsLogic } from 'products/persons/frontend/logics/personsLogic'
import type { TeamPublicType, TeamType } from '../types'
const POLL_TIMEOUT = 5000
+export function getReferencedCohortIds(query: unknown): number[] {
+ const ids = new Set<number>()
+ const add = (value: unknown): void => {
+ for (const candidate of Array.isArray(value) ? value : [value]) {
+ if (typeof candidate === 'number' || (typeof candidate === 'string' && /^\d+$/.test(candidate))) {
+ const id = Number(candidate)
+ if (Number.isSafeInteger(id) && id > 0) {
+ ids.add(id)
+ }
+ }
+ }
+ }
+ const visit = (value: unknown): void => {
+ if (!value || typeof value !== 'object') {
+ return
+ }
+ if (Array.isArray(value)) {
+ value.forEach(visit)
+ return
+ }
+ const node = value as Record<string, unknown>
+ if (node.type === 'cohort') {
+ add(node.value)
+ }
+ if (node.breakdown_type === 'cohort') {
+ add(node.breakdown)
+ }
+ Object.values(node).forEach(visit)
+ }
+ visit(query)
+ return [...ids]
+}
+
+export function isIndividualInsightPath(pathname: string): boolean {
+ const match = pathname.match(/^(?:\/project\/[^/]+)?\/insights\/([^/]+)(?:\/[^/]+){0,2}\/?$/)
+ return !!match && match[1] !== 'quick-start'
+}
+
export const COHORTS_PER_PAGE = 100
export const MAX_COHORTS_FOR_FULL_LIST = 2000
@@ -175,6 +216,30 @@ export interface cohortsModelValues {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface cohortsModelActions {
+ locationChanged: ({
+ method,
+ pathname,
+ search,
+ searchParams,
+ hash,
+ hashParams,
+ initial,
+ url,
+ routerState,
+ }: LocationChangedPayload) => {
+ hash: string
+ hashParams: Record<string, any>
+ initial: boolean
+ method: 'POP' | 'PUSH' | 'REPLACE'
+ pathname: string
+ routerState: Record<string, any>
+ search: string
+ searchParams: Record<string, any>
+ url: string
+ } // router
+ cacheCohort: (cohort: CohortType) => {
+ cohort: CohortType
+ }
cohortCreated: (cohort: CohortType) => {
cohort: CohortType
}
@@ -206,6 +271,27 @@ export interface cohortsModelActions {
payload?: any
}
loadCohorts: () => any
+ loadCohortsByIds: ({ ids }: { ids: number[] }) => {
+ ids: number[]
+ }
+ loadCohortsByIdsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadCohortsByIdsSuccess: (
+ allCohorts: CountedPaginatedResponse<CohortType>,
+ payload?: {
+ ids: number[]
+ }
+ ) => {
+ allCohorts: CountedPaginatedResponse<CohortType>
+ payload?: {
+ ids: number[]
+ }
+ }
loadCohortsFailure: (
error: string,
errorObject?: any
@@ -253,15 +339,17 @@ export const cohortsModel = kea<cohortsModelType>([
path(['models', 'cohortsModel']),
connect(() => ({
values: [teamLogic, ['currentTeam']],
+ actions: [router, ['locationChanged']],
})),
actions(() => ({
setPollTimeout: (pollTimeout: number | null) => ({ pollTimeout }),
updateCohort: (cohort: CohortType) => ({ cohort }),
+ cacheCohort: (cohort: CohortType) => ({ cohort }),
deleteCohort: (cohort: Partial<CohortType>) => ({ cohort }),
cohortCreated: (cohort: CohortType) => ({ cohort }),
hydrateAllCohortsFromExport: (cohorts: Pick<CohortType, 'id' | 'name'>[]) => ({ cohorts }),
})),
- loaders(() => ({
+ loaders(({ actions, values, cache }) => ({
cohorts: {
__default: { count: 0, results: [] } as CountedPaginatedResponse<CohortType>,
loadCohorts: async () => {
@@ -277,7 +365,46 @@ export const cohortsModel = kea<cohortsModelType>([
},
allCohorts: {
__default: { count: 0, results: [] } as CountedPaginatedResponse<CohortType>,
+ loadCohortsByIds: async ({ ids }: { ids: number[] }) => {
+ if (!isAuthenticatedTeam(values.currentTeam)) {
+ return values.allCohorts
+ }
+ const projectId = String(values.currentTeam.project_id)
+ const requests: ConcurrencyController = (cache.cohortRequests ??= new ConcurrencyController(10))
+ const referenced: Set<number> = (cache.referencedCohortIds ??= new Set<number>())
+ ids.forEach((id) => referenced.add(id))
+ const pending: Set<number> = (cache.pendingCohortIds ??= new Set<number>())
+ const missing = [...new Set(ids)].filter(
+ (id) => Number.isSafeInteger(id) && id > 0 && !values.cohortsById[id] && !pending.has(id)
+ )
+ missing.forEach((id) => pending.add(id))
+ const results = await Promise.allSettled(
+ missing.map(async (id) => {
+ try {
+ const cohort = await requests.run({ fn: () => cohortsApi.cohortsRetrieve(projectId, id) })
+ // The shared cache still exposes the legacy shape to its consumers.
+ actions.cacheCohort(cohort as unknown as CohortType)
+ const referencedIds = getReferencedCohortIds(cohort.filters)
+ if (referencedIds.length) {
+ actions.loadCohortsByIds({ ids: referencedIds })
+ }
+ } catch (error) {
+ if (![403, 404].includes((error as { status?: number }).status ?? 0)) {
+ throw error
+ }
+ } finally {
+ pending.delete(id)
+ }
+ })
+ )
+ const failure = results.find((result) => result.status === 'rejected')
+ if (failure?.status === 'rejected') {
+ throw failure.reason
+ }
+ return values.allCohorts
+ },
loadAllCohorts: async () => {
+ cache.fullListRequested = true
// `allCohorts` feeds `cohortsById`, mostly id + name lookups, so request the
// basic payload that drops the legacy `groups`/`query` JSON. Fetching the full
// payload for up to 2,000 cohorts on this hot path was slow enough to hit the
@@ -288,11 +415,17 @@ export const cohortsModel = kea<cohortsModelType>([
const response = await api.cohorts.listBasic({
limit: MAX_COHORTS_FOR_FULL_LIST,
})
+ const listedIds = new Set(response.results.map(({ id }) => id))
return {
count: response.count,
// `groups` is dropped from the basic payload but required on CohortType, so
// add the empty default back — nothing reading `cohortsById` uses `groups`.
- results: response.results.map((cohort): CohortType => ({ ...cohort, groups: [] })),
+ results: [
+ ...response.results.map((cohort): CohortType => ({ ...cohort, groups: [] })),
+ ...values.allCohorts.results.filter(
+ ({ id }) => !listedIds.has(id) && cache.referencedCohortIds?.has(id)
+ ),
+ ],
}
},
},
@@ -338,6 +471,10 @@ export const cohortsModel = kea<cohortsModelType>([
// Update allCohorts state to keep breadcrumbs in sync when cohorts are modified
// The cohortsById selector depends on allCohorts, not cohorts
allCohorts: {
+ cacheCohort: (state, { cohort }) => ({
+ ...state,
+ results: [...state.results.filter(({ id }) => id !== cohort.id), cohort],
+ }),
updateCohort: (state, { cohort }) => {
if (!cohort) {
return state
@@ -396,7 +533,19 @@ export const cohortsModel = kea<cohortsModelType>([
],
count: [(selectors) => [selectors.cohorts], (cohorts: CountedPaginatedResponse<CohortType>) => cohorts.count],
}),
- listeners(({ actions }) => ({
+ listeners(({ actions, values, cache }) => ({
+ loadAllCohortsFailure: () => {
+ cache.fullListRequested = false
+ },
+ locationChanged: ({ pathname }) => {
+ if (
+ !isIndividualInsightPath(pathname) &&
+ isAuthenticatedTeam(values.currentTeam) &&
+ !cache.fullListRequested
+ ) {
+ actions.loadAllCohorts()
+ }
+ },
// Flush the TaxonomicFilter cohort cache whenever cohorts mutate
// so the next open of the cohort picker re-fetches the first page.
// The picker pins its request to `?search=&limit=100` and runs
@@ -453,7 +602,10 @@ export const cohortsModel = kea<cohortsModelType>([
}),
afterMount(({ actions, values }) => {
if (isAuthenticatedTeam(values.currentTeam)) {
- actions.loadAllCohorts()
+ // Other scenes still rely on eager loading; insightDataLogic resolves its own references.
+ if (!isIndividualInsightPath(router.values.location.pathname)) {
+ actions.loadAllCohorts()
+ }
} else {
// Shared views can't hit /api/cohorts — seed from the inlined export payload.
const exportedCohorts = getCurrentExporterData()?.cohorts
diff --git a/frontend/src/scenes/insights/insightDataLogic.test.ts b/frontend/src/scenes/insights/insightDataLogic.test.ts
index 285e11f9bfae..3a0d9e3b3ba2 100644
--- a/frontend/src/scenes/insights/insightDataLogic.test.ts
+++ b/frontend/src/scenes/insights/insightDataLogic.test.ts
@@ -6,6 +6,7 @@ jest.mock('~/queries/query', () => ({
import { MOCK_TEAM_ID } from 'lib/api.mock'
+import { router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
import posthog from 'posthog-js'
@@ -19,6 +20,7 @@ import { sceneLogic } from 'scenes/sceneLogic'
import { Scene } from 'scenes/sceneTypes'
import { useMocks } from '~/mocks/jest'
+import { cohortsModel } from '~/models/cohortsModel'
import { insightsModel } from '~/models/insightsModel'
import { examples } from '~/queries/examples'
import { getDefaultQuery } from '~/queries/nodes/InsightViz/utils'
@@ -78,6 +80,64 @@ describe('insightDataLogic', () => {
theInsightLogic.mount()
})
+ describe('referenced cohorts on an individual insight', () => {
+ it('resolves saved, edited, and prop-synced cohort names without requesting the list', async () => {
+ await expectLogic(theInsightDataLogic).toFinishAllListeners()
+ initKeaTests()
+ router.actions.push('/insights/123')
+ const list = jest.fn(() => ({ count: 0, results: [] }))
+ const requestedIds: number[] = []
+ const query = (ids: number[]): InsightVizNode => ({
+ kind: NodeKind.InsightVizNode,
+ source: {
+ kind: NodeKind.TrendsQuery,
+ series: [{ kind: NodeKind.EventsNode, event: '$pageview' }],
+ breakdownFilter: { breakdown_type: 'cohort', breakdown: ids },
+ },
+ })
+ useMocks({
+ get: {
+ '/api/environments/:team/insights/': {
+ results: [{ id: 1, short_id: Insight123, query: query([1]) }],
+ },
+ '/api/projects/:team/cohorts/': list,
+ '/api/projects/:team/cohorts/:id/': ({ params }) => {
+ const id = Number(params.id)
+ requestedIds.push(id)
+ return {
+ id,
+ name: `Referenced cohort ${id}`,
+ groups: [],
+ filters: { properties: { type: 'AND', values: [] } },
+ }
+ },
+ },
+ })
+ const props = { dashboardItemId: Insight123, doNotLoad: true }
+ const dataLogic = insightDataLogic(props)
+ dataLogic.mount()
+ await expectLogic(dataLogic).toFinishAllListeners()
+ expect(list).not.toHaveBeenCalled()
+ expect(requestedIds).toEqual([])
+
+ await expectLogic(dataLogic, () =>
+ insightLogic(props).actions.loadInsight(Insight123)
+ ).toFinishAllListeners()
+ await expectLogic(cohortsModel).toFinishAllListeners()
+ expect(insightLogic(props).values.derivedName).toContain('Referenced cohort 1')
+
+ await expectLogic(dataLogic, () => dataLogic.actions.setQuery(query([1, 3000]))).toFinishAllListeners()
+ await expectLogic(cohortsModel).toFinishAllListeners()
+ expect(insightLogic(props).values.derivedName).toContain('Referenced cohort 3000')
+
+ await expectLogic(dataLogic, () => dataLogic.actions.syncQueryFromProps(query([2]))).toFinishAllListeners()
+ await expectLogic(cohortsModel).toFinishAllListeners()
+ expect(insightLogic(props).values.derivedName).toContain('Referenced cohort 2')
+ expect(requestedIds).toEqual([1, 3000, 2])
+ expect(list).not.toHaveBeenCalled()
+ })
+ })
+
describe('syncQueryFromProps', () => {
const funnelsSource: FunnelsQuery = {
kind: NodeKind.FunnelsQuery,
diff --git a/frontend/src/scenes/insights/insightDataLogic.tsx b/frontend/src/scenes/insights/insightDataLogic.tsx
index f2e8035aeb36..3a7a4681e1c2 100644
--- a/frontend/src/scenes/insights/insightDataLogic.tsx
+++ b/frontend/src/scenes/insights/insightDataLogic.tsx
@@ -29,6 +29,7 @@ import { Scene } from 'scenes/sceneTypes'
import { filterTestAccountsDefaultsLogic } from 'scenes/settings/environment/filterTestAccountDefaultsLogic'
import { sceneLayoutLogic } from '~/layout/scenes/sceneLayoutLogic'
+import { cohortsModel, getReferencedCohortIds, isIndividualInsightPath } from '~/models/cohortsModel'
import { insightsModel } from '~/models/insightsModel'
import { examples } from '~/queries/examples'
import { DataNodeLogicProps, dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'
@@ -415,6 +416,9 @@ export interface insightDataLogicActions {
} | null
payload?: any
}
+ loadReferencedCohorts: () => {
+ value: true
+ }
persistDisplayOptions: (query: Node) => {
query: Node<Record<string, any>>
}
@@ -542,6 +546,7 @@ export const insightDataLogic = kea<insightDataLogicType>([
})),
actions({
+ loadReferencedCohorts: true,
setQuery: (query: Node | null, fromUrl: boolean = false) => ({ query, fromUrl }),
syncQueryFromProps: (query: Node | null) => ({ query }),
toggleQueryEditorPanel: true,
@@ -793,6 +798,15 @@ export const insightDataLogic = kea<insightDataLogicType>([
}),
listeners(({ actions, cache, values, props }) => ({
+ loadReferencedCohorts: () => {
+ if (isIndividualInsightPath(router.values.location.pathname)) {
+ const ids = getReferencedCohortIds(values.query)
+ if (ids.length) {
+ cohortsModel.actions.loadCohortsByIds({ ids })
+ }
+ }
+ },
+ syncQueryFromProps: () => actions.loadReferencedCohorts(),
persistDisplayOptions: async ({ query }, breakpoint) => {
// Never auto-persist while the user is editing this insight in the insight scene.
// insightDataLogic is keyed `${shortId}/on-dashboard-${dashboardId}`, so an insight
@@ -979,6 +993,7 @@ export const insightDataLogic = kea<insightDataLogicType>([
}
},
loadInsightSuccess: ({ insight }) => {
+ actions.loadReferencedCohorts()
// A shared link's query (`#q=`) is applied before the saved insight arrives, so re-syncing
// here would silently discard the date range and interval the sender chose.
if (values.queryFromUrl) {
@@ -999,6 +1014,7 @@ export const insightDataLogic = kea<insightDataLogicType>([
actions.setInsightData({ ...values.insightData, result: savedResult ? savedResult : null })
},
setQuery: ({ query }) => {
+ actions.loadReferencedCohorts()
// When this is the insight scene's own insight, sync the query to the URL
if (isInsightSceneInstance(props)) {
const insightId = insightSceneLogic.findMounted()?.values.insightId
@@ -1103,6 +1119,7 @@ export const insightDataLogic = kea<insightDataLogicType>([
}
}),
afterMount(({ actions, props }) => {
+ actions.loadReferencedCohorts()
// On a dashboard, the first response for a tile can say “we don’t have chart numbers yet”
// (`result: null`) instead of leaving the field unset. Without a real fetch, the UI can look
// like a failed load (“Chart data didn’t load”) even though we simply haven’t run the query.
diff --git a/frontend/src/scenes/insights/insightSceneLogic.test.ts b/frontend/src/scenes/insights/insightSceneLogic.test.ts
index 754030a44885..49d3b19f3a37 100644
--- a/frontend/src/scenes/insights/insightSceneLogic.test.ts
+++ b/frontend/src/scenes/insights/insightSceneLogic.test.ts
@@ -11,11 +11,12 @@ import { Scene } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'
import { useMocks } from '~/mocks/jest'
+import { cohortsModel } from '~/models/cohortsModel'
import { examples } from '~/queries/examples'
import { DashboardFilter, HogQLVariable, InsightVizNode, NodeKind, ProductKey } from '~/queries/schema/schema-general'
import { setLatestVersionsOnQuery } from '~/queries/utils'
import { initKeaTests } from '~/test/init'
-import { ActivityScope, InsightShortId, InsightType, ItemMode } from '~/types'
+import { ActivityScope, CohortType, InsightShortId, InsightType, ItemMode } from '~/types'
const Insight12 = '12' as InsightShortId
const Insight42 = '42' as InsightShortId
@@ -55,6 +56,28 @@ describe('insightSceneLogic', () => {
})
})
+ it('updates the generated breadcrumb when cohort names arrive after the query', async () => {
+ router.actions.push(urls.insightNew())
+ logic = insightSceneLogic()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ logic.values.insightDataLogicRef!.logic.actions.setQuery({
+ kind: NodeKind.InsightVizNode,
+ source: {
+ kind: NodeKind.TrendsQuery,
+ series: [{ kind: NodeKind.EventsNode, event: '$pageview', math: 'total' }],
+ breakdownFilter: { breakdown_type: 'cohort', breakdown: [987] },
+ },
+ } as InsightVizNode)
+ expect(logic.values.breadcrumbs.at(-1)?.name).toContain('ID 987')
+
+ cohortsModel.actions.cacheCohort({ id: 987, name: 'Returning users' } as CohortType)
+
+ expect(logic.values.breadcrumbs.at(-1)?.name).toContain('Returning users')
+ expect(logic.values.breadcrumbs.at(-1)?.name).not.toContain('ID 987')
+ })
+
it('disables discussions for an unsaved insight so comments do not leak across the team', async () => {
// A new insight has no numeric id yet. The side panel context must still declare the Insight
// scope (so sidePanelContextLogic does not fall back to the URL guesser and drop item_id, which
diff --git a/frontend/src/scenes/insights/insightSceneLogic.tsx b/frontend/src/scenes/insights/insightSceneLogic.tsx
index a53943416512..33d0137f6105 100644
--- a/frontend/src/scenes/insights/insightSceneLogic.tsx
+++ b/frontend/src/scenes/insights/insightSceneLogic.tsx
@@ -285,7 +285,8 @@ export interface insightSceneLogicMeta {
dashboardId: number | null,
dashboardName: string | null,
sceneSource: InsightSceneSource | null,
- dashboardBackPath: string | null
+ dashboardBackPath: string | null,
+ arg: string | undefined
) => Breadcrumb[]
projectTreeRef: (insightId: InsightId) => ProjectTreeRef
sidePanelContext: (
@@ -553,6 +554,7 @@ export const insightSceneLogic = kea<insightSceneLogicType>([
s.dashboardName,
s.sceneSource,
s.dashboardBackPath,
+ (state, props) => s.insightLogicRef(state, props)?.logic.selectors.insightName(state, props),
],
(
insightLogicRef: {
@@ -564,7 +566,8 @@ export const insightSceneLogic = kea<insightSceneLogicType>([
dashboardId: DashboardType['id'] | null,
dashboardName: DashboardType['name'] | null,
sceneSource: InsightSceneSource | null,
- dashboardBackPath: string | null
+ dashboardBackPath: string | null,
+ insightName: string | undefined
): Breadcrumb[] => {
const dashboardLabel = dashboardName ?? 'Dashboard'
return [
@@ -615,7 +618,7 @@ export const insightSceneLogic = kea<insightSceneLogicType>([
]),
{
key: [Scene.Insight, insight?.short_id || 'new'],
- name: insightLogicRef?.logic.values.insightName,
+ name: insightName,
forceEditMode: insightLogicRef?.logic.values.canEditInsight,
iconType: getInsightIconTypeFromQuery(insightQuery),
},
diff --git a/products/posthog_ai/frontend/components/tool/widgets/VisualizationWidget.test.tsx b/products/posthog_ai/frontend/components/tool/widgets/VisualizationWidget.test.tsx
new file mode 100644
index 000000000000..e854ac2ff019
--- /dev/null
+++ b/products/posthog_ai/frontend/components/tool/widgets/VisualizationWidget.test.tsx
@@ -0,0 +1,70 @@
+import '@testing-library/jest-dom'
+
+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { Provider } from 'kea'
+import { router } from 'kea-router'
+
+import { useMocks } from '~/mocks/jest'
+import { ArtifactContentType, VisualizationArtifactContent } from '~/queries/schema/schema-assistant-messages'
+import { NodeKind } from '~/queries/schema/schema-general'
+import { initKeaTests } from '~/test/init'
+import { PropertyFilterType, PropertyOperator } from '~/types'
+
+import { VisualizationWidget } from './VisualizationWidget'
+
+jest.mock('~/queries/Query/Query', () => ({
+ Query: () => {
+ throw new Error('The collapsed visualization must not mount its query')
+ },
+}))
+
+describe('VisualizationWidget', () => {
+ beforeEach(() => {
+ initKeaTests()
+ router.actions.push('/project/997/insights/current')
+ })
+
+ afterEach(cleanup)
+
+ it('resolves a collapsed AI definition without loading the chart or full cohort list', async () => {
+ const list = jest.fn(() => ({ count: 0, results: [] }))
+ const detail = jest.fn(({ params }) => ({
+ id: Number(params.id),
+ name: params.id === '3000' ? 'Returning visitors' : 'Paid visitors',
+ groups: [],
+ filters: { properties: { type: 'AND', values: [] } },
+ }))
+ useMocks({
+ get: {
+ '/api/projects/:team/cohorts/': list,
+ '/api/projects/:team/cohorts/:id/': detail,
+ },
+ })
+ const content: VisualizationArtifactContent = {
+ content_type: ArtifactContentType.Visualization,
+ query: {
+ kind: NodeKind.TrendsQuery,
+ series: [{ kind: NodeKind.EventsNode, event: '$pageview' }],
+ properties: [
+ { type: PropertyFilterType.Cohort, key: 'id', value: 3000, operator: PropertyOperator.In },
+ ],
+ breakdownFilter: { breakdown_type: 'cohort', breakdown: [3001] },
+ },
+ }
+ render(
+ <Provider>
+ <VisualizationWidget content={content} isCollapsed embedded />
+ </Provider>
+ )
+ expect(detail).not.toHaveBeenCalled()
+ fireEvent.click(screen.getByText('Trends'))
+ await waitFor(() => {
+ expect(screen.getByText(/Returning visitors/)).toBeInTheDocument()
+ expect(screen.getByText(/Paid visitors/)).toBeInTheDocument()
+ })
+ fireEvent.click(screen.getByText('Trends'))
+ fireEvent.click(screen.getByText('Trends'))
+ expect(detail).toHaveBeenCalledTimes(2)
+ expect(list).not.toHaveBeenCalled()
+ })
+})
diff --git a/products/posthog_ai/frontend/components/tool/widgets/VisualizationWidget.tsx b/products/posthog_ai/frontend/components/tool/widgets/VisualizationWidget.tsx
index 314666211bd8..0656795fd946 100644
--- a/products/posthog_ai/frontend/components/tool/widgets/VisualizationWidget.tsx
+++ b/products/posthog_ai/frontend/components/tool/widgets/VisualizationWidget.tsx
@@ -1,4 +1,5 @@
import clsx from 'clsx'
+import { useActions } from 'kea'
import React, { useMemo, useState } from 'react'
import { IconCollapse, IconExpand, IconEye, IconHide, IconWarning } from '@posthog/icons'
@@ -13,6 +14,7 @@ import { TopHeading } from 'lib/components/Cards/InsightCard/TopHeading'
import { IconOpenInNew } from 'lib/lemon-ui/icons'
import { urls } from 'scenes/urls'
+import { cohortsModel, getReferencedCohortIds } from '~/models/cohortsModel'
import { Query } from '~/queries/Query/Query'
import {
ArtifactMessage,
@@ -77,6 +79,7 @@ export const VisualizationWidget = React.memo(function VisualizationWidget({
extraActions,
embedded = false,
}: VisualizationWidgetProps): JSX.Element {
+ const { loadCohortsByIds } = useActions(cohortsModel)
const [isSummaryShown, setIsSummaryShown] = useState(false)
const [internalCollapsed, setInternalCollapsed] = useState(false)
const isCollapsed = controlledCollapsed ?? internalCollapsed
@@ -110,7 +113,12 @@ export const VisualizationWidget = React.memo(function VisualizationWidget({
<div className="flex items-center gap-1.5">
<LemonButton
sideIcon={isSummaryShown ? <IconCollapse /> : <IconExpand />}
- onClick={() => setIsSummaryShown(!isSummaryShown)}
+ onClick={() => {
+ if (!isSummaryShown) {
+ loadCohortsByIds({ ids: getReferencedCohortIds(query) })
+ }
+ setIsSummaryShown(!isSummaryShown)
+ }}
size="xsmall"
className="-m-1 shrink"
tooltip={isSummaryShown ? 'Hide definition' : 'Show definition'}