:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(persons): show key properties in the persons modal timeline (#119572)
Thomas Obermüllerdc99a9987059
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex cea76c6b7093..04f449aa4b4b 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -13887,9 +13887,9 @@ snapshots:scenes-app-persons-modal--timeout-error--light:hash: v1.k794b7964.5a2ad450f0349efcede6d2ec38acce96d01c2405b15cb7192046e1b1e52017ed.lZuhlqm687KvYF-lLjyj1Q-62-bEOORChVa3s3I4S1Uscenes-app-persons-modal--with-results--dark:- hash: v1.k794b7964.543e6b89c21b4a0de9fca38a2a7b585c4e467382f5ce5772d50424b866ec9f31.ya9rrl_NUzwRgesGT5CjUr6YpnBH7zRoH2U6TQnyZ5U+ hash: v1.k794b7964.1183fb98eaeadb4e88d5d8852691e3973816743334cd41c5c8e188bb188bea08.-wJe2jsIRnhyq306Jd9NaWOV0YvFj_NkUzki4fGIE1Escenes-app-persons-modal--with-results--light:- hash: v1.k794b7964.892edabd980ca7b6b06f80ed8879ef4b9100ae8ff6a6c03fc77d9a9574a4f553.YVtPZaAGoU1C4_4htQ_YK_xO1AxKBVtTuEEYW-n0eUM+ hash: v1.k794b7964.1d68e8130c9b1e10c8a3108db32fd637d3eb1dd754fad89686983be07b5fed52.CO-rdGDtzu5D-dBdjJ0YjkhsqRfjs3zjpi97Ewbkef0scenes-app-platformalerts--detail--dark:hash: v1.k794b7964.178c9c6382e3fd11c229bf0624fda3606d4898d770ee731ef82f376b8007eca3.J5rYYX2mDsjd0mH-9oWjB2tqtkQmhTPzh0FGmz7C7icscenes-app-platformalerts--detail--light:diff --git a/frontend/src/lib/components/PropertiesTimeline/PropertiesTimeline.stories.tsx b/frontend/src/lib/components/PropertiesTimeline/PropertiesTimeline.stories.tsxindex 15beb52c2bed..1611aeb8c7ae 100644--- a/frontend/src/lib/components/PropertiesTimeline/PropertiesTimeline.stories.tsx+++ b/frontend/src/lib/components/PropertiesTimeline/PropertiesTimeline.stories.tsx@@ -1,12 +1,13 @@-import { MOCK_TEAM_ID } from 'lib/api.mock'-import { Meta } from '@storybook/react'import { useStorybookMocks } from '~/mocks/browser'+import { InsightActorsQuery, NodeKind } from '~/queries/schema/schema-general'import { ChartDisplayType, PersonActorType } from '~/types'+import type { PropertiesTimelineResponseApi } from 'products/persons/frontend/generated/api.schemas'+import { PropertiesTimeline } from '.'-import { PropertiesTimelineProps, RawPropertiesTimelineResult } from './propertiesTimelineLogic'+import { PropertiesTimelineProps } from './propertiesTimelineLogic'const meta: Meta<PropertiesTimelineProps> = {title: 'Components/Properties Timeline',@@ -24,11 +25,21 @@ const EXAMPLE_PERSON: Omit<PersonActorType, 'id' | 'uuid'> = {value_at_data_point: null,}+const EXAMPLE_QUERY: InsightActorsQuery = {+ kind: NodeKind.InsightActorsQuery,+ source: {+ kind: NodeKind.TrendsQuery,+ series: [{ kind: NodeKind.EventsNode, event: '$pageview' }],+ dateRange: { date_from: '2021-01-01', date_to: '2021-06-01' },+ trendsFilter: { display: ChartDisplayType.BoldNumber },+ },+}+export function MultiplePointsForOnePersonProperty(): JSX.Element {const examplePerson: PersonActorType = { ...EXAMPLE_PERSON, id: '012e89b5-4239-4319-8ae4-d3cae2f5deb1' }useStorybookMocks({- get: {- [`/api/environments/${MOCK_TEAM_ID}/persons/${examplePerson.id}/properties_timeline/`]: {+ post: {+ [`/api/projects/:team_id/persons/${examplePerson.id}/properties_timeline/`]: {points: [{timestamp: '2021-01-01T00:00:00.000Z',@@ -66,21 +77,13 @@ export function MultiplePointsForOnePersonProperty(): JSX.Element {crucial_property_keys: ['name'],effective_date_from: '2021-01-01T00:00:00.000000+00:00',effective_date_to: '2021-06-01T23:59:59.999999+00:00',- } as RawPropertiesTimelineResult,+ } as PropertiesTimelineResponseApi,},})return (<div className="border rounded w-120">- <PropertiesTimeline- actor={examplePerson}- filter={{- date_from: '2021-01-01',- date_to: '2021-06-01',- interval: 'day',- display: ChartDisplayType.ActionsLineGraph,- }}- />+ <PropertiesTimeline actor={examplePerson} query={EXAMPLE_QUERY} /></div>)}@@ -88,8 +91,8 @@ export function MultiplePointsForOnePersonProperty(): JSX.Element {export function OnePointForOnePersonProperty(): JSX.Element {const examplePerson: PersonActorType = { ...EXAMPLE_PERSON, id: '012e89b5-4239-4319-8ae4-d3cae2f5deb2' }useStorybookMocks({- get: {- [`/api/environments/${MOCK_TEAM_ID}/persons/${examplePerson.id}/properties_timeline/`]: {+ post: {+ [`/api/projects/:team_id/persons/${examplePerson.id}/properties_timeline/`]: {points: [{timestamp: '2021-05-01T00:00:00.000Z',@@ -103,21 +106,13 @@ export function OnePointForOnePersonProperty(): JSX.Element {crucial_property_keys: ['name'],effective_date_from: '2021-01-01T00:00:00.000000+00:00',effective_date_to: '2021-06-01T23:59:59.999999+00:00',- } as RawPropertiesTimelineResult,+ } as PropertiesTimelineResponseApi,},})return (<div className="border rounded w-120">- <PropertiesTimeline- actor={examplePerson}- filter={{- date_from: '2021-01-01',- date_to: '2021-06-01',- interval: 'day',- display: ChartDisplayType.ActionsLineGraph,- }}- />+ <PropertiesTimeline actor={examplePerson} query={EXAMPLE_QUERY} /></div>)}@@ -125,8 +120,8 @@ export function OnePointForOnePersonProperty(): JSX.Element {export function NoPointsForNoPersonProperties(): JSX.Element {const examplePerson: PersonActorType = { ...EXAMPLE_PERSON, id: '012e89b5-4239-4319-8ae4-d3cae2f5deb3' }useStorybookMocks({- get: {- [`/api/environments/${MOCK_TEAM_ID}/persons/${examplePerson.id}/properties_timeline/`]: {+ post: {+ [`/api/projects/:team_id/persons/${examplePerson.id}/properties_timeline/`]: {points: [{timestamp: '2021-01-01T00:00:00.000Z',@@ -140,21 +135,13 @@ export function NoPointsForNoPersonProperties(): JSX.Element {crucial_property_keys: [], // No key properties hereeffective_date_from: '2021-01-01T00:00:00.000000+00:00',effective_date_to: '2021-06-01T23:59:59.999999+00:00',- } as RawPropertiesTimelineResult,+ } as PropertiesTimelineResponseApi,},})return (<div className="border rounded w-120">- <PropertiesTimeline- actor={examplePerson}- filter={{- date_from: '2021-01-01',- date_to: '2021-06-01',- interval: 'day',- display: ChartDisplayType.ActionsLineGraph,- }}- />+ <PropertiesTimeline actor={examplePerson} query={EXAMPLE_QUERY} /></div>)}diff --git a/frontend/src/lib/components/PropertiesTimeline/PropertiesTimeline.tsx b/frontend/src/lib/components/PropertiesTimeline/PropertiesTimeline.tsxindex ec901bf2e976..1541da928417 100644--- a/frontend/src/lib/components/PropertiesTimeline/PropertiesTimeline.tsx+++ b/frontend/src/lib/components/PropertiesTimeline/PropertiesTimeline.tsx@@ -14,8 +14,8 @@ import { PropertyDefinitionType } from '~/types'import { TimelineSeekbar } from '../TimelineSeekbar'import { PropertiesTimelineProps, propertiesTimelineLogic } from './propertiesTimelineLogic'-export function PropertiesTimeline({ actor, filter }: PropertiesTimelineProps): JSX.Element {- const logic = propertiesTimelineLogic({ actor, filter })+export function PropertiesTimeline({ actor, query }: PropertiesTimelineProps): JSX.Element {+ const logic = propertiesTimelineLogic({ actor, query })const { points, crucialPropertyKeys, dateRange, resultLoading, selectedPointIndex } = useValues(logic)const { setSelectedPointIndex } = useActions(logic)const { currentTeam } = useValues(teamLogic)@@ -77,7 +77,7 @@ export function PropertiesTimeline({ actor, filter }: PropertiesTimelineProps):/><LemonDivider className="h-0" /><PropertiesTable- type={actor.type /* "person" or "group" */ as PropertyDefinitionType}+ type={PropertyDefinitionType.Person}properties={propertiesShown}nestingLevel={1}highlightedKeys={crucialPropertyKeys}diff --git a/frontend/src/lib/components/PropertiesTimeline/propertiesTimelineLogic.ts b/frontend/src/lib/components/PropertiesTimeline/propertiesTimelineLogic.tsindex 57c21d27d5eb..a2f9e862fbbb 100644--- a/frontend/src/lib/components/PropertiesTimeline/propertiesTimelineLogic.ts+++ b/frontend/src/lib/components/PropertiesTimeline/propertiesTimelineLogic.ts@@ -1,14 +1,19 @@-import { MakeLogicType, actions, afterMount, connect, kea, key, path, props, reducers, selectors } from 'kea'+import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'import { loaders } from 'kea-loaders'import posthog from 'posthog-js'-import api from 'lib/api'import { Dayjs, dayjsUtcToTimezone } from 'lib/dayjs'-import { toParams } from 'lib/utils/url'import { teamLogic } from 'scenes/teamLogic'import { Properties } from '~/legacy-plugin-scaffold'-import { ActorType, PropertiesTimelineFilterType } from '~/types'+import { InsightActorsQuery } from '~/queries/schema/schema-general'+import { PersonActorType } from '~/types'++import { personsPropertiesTimelineCreate } from 'products/persons/frontend/generated/api'+import type {+ PropertiesTimelineRequestApi,+ PropertiesTimelineResponseApi,+} from 'products/persons/frontend/generated/api.schemas'export interface PropertiesTimelinePoint {timestamp: Dayjs@@ -16,22 +21,10 @@ export interface PropertiesTimelinePoint {relevantEventCount: number}-export interface RawPropertiesTimelinePoint {- timestamp: string- properties: Properties- relevant_event_count: number-}--export interface RawPropertiesTimelineResult {- points: RawPropertiesTimelinePoint[]- crucial_property_keys: string[]- effective_date_from: string- effective_date_to: string-}-export interface PropertiesTimelineProps {- actor: ActorType- filter: PropertiesTimelineFilterType+ actor: PersonActorType+ /** The actors query of the clicked Trends data point. */+ query: InsightActorsQuery}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -41,7 +34,7 @@ export interface propertiesTimelineLogicValues {crucialPropertyKeys: (keyof Properties)[]dateRange: [Dayjs, Dayjs] | nullpoints: PropertiesTimelinePoint[]- result: RawPropertiesTimelineResult | null+ result: PropertiesTimelineResponseApi | nullresultLoading: booleanselectedPointIndex: number | null}@@ -57,10 +50,10 @@ export interface propertiesTimelineLogicActions {errorObject?: any}loadResultSuccess: (- result: RawPropertiesTimelineResult,+ result: PropertiesTimelineResponseApi,payload?: any) => {- result: RawPropertiesTimelineResult+ result: PropertiesTimelineResponseApipayload?: any}setSelectedPointIndex: (index: number | null) => {@@ -72,9 +65,9 @@ export interface propertiesTimelineLogicActions {export interface propertiesTimelineLogicMeta {key: string__keaTypeGenInternalSelectorTypes: {- points: (result: RawPropertiesTimelineResult | null, timezone: string) => PropertiesTimelinePoint[]- crucialPropertyKeys: (result: RawPropertiesTimelineResult | null) => (keyof Properties)[]- dateRange: (result: RawPropertiesTimelineResult | null, timezone: string) => [Dayjs, Dayjs] | null+ points: (result: PropertiesTimelineResponseApi | null, timezone: string) => PropertiesTimelinePoint[]+ crucialPropertyKeys: (result: PropertiesTimelineResponseApi | null) => (keyof Properties)[]+ dateRange: (result: PropertiesTimelineResponseApi | null, timezone: string) => [Dayjs, Dayjs] | null}}@@ -88,7 +81,7 @@ export type propertiesTimelineLogicType = MakeLogicType<export const propertiesTimelineLogic = kea<propertiesTimelineLogicType>([path(['lib', 'components', 'PropertiesTimeline', 'propertiesTimelineLogic']),props({} as PropertiesTimelineProps),- key((props) => `${props.actor.id}-${JSON.stringify(props.filter)}`),+ key((props) => `${props.actor.id}-${JSON.stringify(props.query)}`),connect(() => ({values: [teamLogic, ['currentTeamId', 'timezone']],})),@@ -110,29 +103,25 @@ export const propertiesTimelineLogic = kea<propertiesTimelineLogicType>([loaders(({ values, props }) => ({// This reducer is for loading convenience, for actual data use `points`, `crucialPropertyKeys`, and `dateRange`result: [- null as RawPropertiesTimelineResult | null,+ null as PropertiesTimelineResponseApi | null,{loadResult: async () => {- if (props.actor.type === 'person') {- // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. personsPropertiesTimelineRetrieve() from 'products/persons/frontend/generated/api' serves this route, but its generated types do not describe this call yet, so fix the endpoint's OpenAPI schema first.- const response = await api.get<RawPropertiesTimelineResult>(- `api/projects/${values.currentTeamId}/persons/${- props.actor.id- }/properties_timeline/?${toParams(props.filter)}`- )- if (response.points.length === 0) {- // It should not be possible for a properties timeline to have zero points, as all actors- // shown in the actors modal must have at least one relevant event in the period- posthog.captureException(new Error('Properties Timeline returned no points'), {- tags: { 'team.id': values.currentTeamId },- extra: {- params: props.filter,- },- })- }- return response+ const response = await personsPropertiesTimelineCreate(+ String(values.currentTeamId),+ props.actor.id,+ // The OpenAPI query type differs from the query schema in details such as funnel `binCount`+ { query: props.query as PropertiesTimelineRequestApi['query'] }+ )+ if (response.points.length === 0) {+ // It should not be possible for a properties timeline to have zero points, as all actors+ // shown in the actors modal must have at least one relevant event in the period.+ // pinned: error tracking groups by this message, so keep it unchanged.+ posthog.captureException(new Error('Properties Timeline returned no points'), {+ tags: { 'team.id': values.currentTeamId },+ extra: { query: props.query },+ })}- throw new Error("Properties Timeline doesn't support groups-on-events yet")+ return response},},],@@ -140,7 +129,7 @@ export const propertiesTimelineLogic = kea<propertiesTimelineLogicType>([selectors({points: [(s) => [s.result, s.timezone],- (result: RawPropertiesTimelineResult | null, timezone: string) =>+ (result: PropertiesTimelineResponseApi | null, timezone: string) =>result? result.points.map((point): PropertiesTimelinePoint => ({@@ -153,18 +142,37 @@ export const propertiesTimelineLogic = kea<propertiesTimelineLogicType>([],crucialPropertyKeys: [(s) => [s.result],- (result: RawPropertiesTimelineResult | null): (keyof Properties)[] =>+ (result: PropertiesTimelineResponseApi | null): (keyof Properties)[] =>result ? result.crucial_property_keys : [],],dateRange: [(s) => [s.result, s.timezone],- (result: RawPropertiesTimelineResult | null, timezone: string): [Dayjs, Dayjs] | null =>+ (result: PropertiesTimelineResponseApi | null, timezone: string): [Dayjs, Dayjs] | null =>result && [dayjsUtcToTimezone(result.effective_date_from, timezone),dayjsUtcToTimezone(result.effective_date_to, timezone),],],}),+ listeners(({ props, values }) => ({+ loadResultSuccess: ({ result }) => {+ // pinned: analytics event and property names, renaming breaks the usage insights+ posthog.capture('insight person modal properties timeline loaded', {+ source_kind: props.query.source.kind,+ has_key_properties: result.crucial_property_keys.length > 0,+ key_property_count: result.crucial_property_keys.length,+ point_count: result.points.length,+ })+ },+ setSelectedPointIndex: ({ index }) => {+ // pinned: analytics event and property names, renaming breaks the usage insights+ posthog.capture('insight person modal properties timeline point selected', {+ source_kind: props.query.source.kind,+ point_count: values.points.length,+ selected_present: index !== null,+ })+ },+ })),afterMount(({ actions }) => {actions.loadResult()}),diff --git a/frontend/src/scenes/insights/sharedUtils.ts b/frontend/src/scenes/insights/sharedUtils.tsindex 3181d319520c..9d4c25533ca9 100644--- a/frontend/src/scenes/insights/sharedUtils.ts+++ b/frontend/src/scenes/insights/sharedUtils.ts@@ -4,12 +4,8 @@ import { ApiError } from 'lib/api-error'import {ChartDisplayType,FilterType,- FunnelsFilterType,InsightLogicProps,InsightType,- LifecycleFilterType,- PathsFilterType,- RetentionFilterType,StickinessFilterType,TrendsFilterType,} from '~/types'@@ -73,21 +69,9 @@ export function filterTrendsClientSideParams(export function isTrendsFilter(filters?: Partial<FilterType>): filters is Partial<TrendsFilterType> {return filters?.insight === InsightType.TRENDS || (!!filters && !filters.insight)}-export function isFunnelsFilter(filters?: Partial<FilterType>): filters is Partial<FunnelsFilterType> {- return filters?.insight === InsightType.FUNNELS-}-export function isRetentionFilter(filters?: Partial<FilterType>): filters is Partial<RetentionFilterType> {- return filters?.insight === InsightType.RETENTION-}export function isStickinessFilter(filters?: Partial<FilterType>): filters is Partial<StickinessFilterType> {return filters?.insight === InsightType.STICKINESS}-export function isLifecycleFilter(filters?: Partial<FilterType>): filters is Partial<LifecycleFilterType> {- return filters?.insight === InsightType.LIFECYCLE-}-export function isPathsFilter(filters?: Partial<FilterType>): filters is Partial<PathsFilterType> {- return filters?.insight === InsightType.PATHS-}export function isFilterWithDisplay(filters: Partial<FilterType>diff --git a/frontend/src/scenes/insights/utils/cleanFilters.test.ts b/frontend/src/scenes/insights/utils/cleanFilters.test.tsdeleted file mode 100644index ceaf6c267355..000000000000--- a/frontend/src/scenes/insights/utils/cleanFilters.test.ts+++ /dev/null@@ -1,391 +0,0 @@-import { NON_VALUES_ON_SERIES_DISPLAY_TYPES, ShownAsValue } from 'lib/constants'--import {- ChartDisplayType,- FilterType,- FunnelStepReference,- FunnelVizType,- FunnelsFilterType,- InsightType,- TrendsFilterType,-} from '~/types'--import { cleanFilters } from './cleanFilters'--describe('cleanFilters', () => {- it('removes shownas from trends insights', () => {- expect(cleanFilters({ insight: InsightType.TRENDS, shown_as: ShownAsValue.STICKINESS })).toEqual(- expect.objectContaining({ insight: InsightType.TRENDS, shown_as: undefined })- )- })-- it('removes breakdown when it also has breakdowns', () => {- const cleanedFilters = cleanFilters({- breakdown: '$browser',- breakdowns: [{ property: '$browser', type: 'event' }],- insight: InsightType.FUNNELS,- funnel_viz_type: FunnelVizType.Steps,- } as FunnelsFilterType)-- expect(cleanedFilters).toHaveProperty('breakdown', undefined)-- expect(cleanedFilters).toEqual(- expect.objectContaining({ breakdowns: [{ property: '$browser', type: 'event' }] })- )- })-- it('allows breakdown_type with breakdown', () => {- const cleanedFilters = cleanFilters({- breakdown: '$thing',- breakdown_type: 'event',- insight: InsightType.FUNNELS,- funnel_viz_type: FunnelVizType.Steps,- } as FunnelsFilterType)-- expect(cleanedFilters).toHaveProperty('breakdown', '$thing')- expect(cleanedFilters).toHaveProperty('breakdown_type', 'event')- })-- it('allows breakdown_type when adding breakdowns', () => {- const cleanedFilters = cleanFilters({- breakdowns: [{ property: '$browser', type: 'event' }],- breakdown_type: 'event',- insight: InsightType.FUNNELS,- funnel_viz_type: FunnelVizType.Steps,- } as FunnelsFilterType)-- expect(cleanedFilters).toHaveProperty('breakdowns', [{ property: '$browser', type: 'event' }])- expect(cleanedFilters).toHaveProperty('breakdown_type', 'event')- })-- it('defaults to normalizing URL for breakdowns by $current_url', () => {- const cleanedFilters = cleanFilters({- breakdowns: [{ property: '$current_url', type: 'event' }],- breakdown_type: 'event',- } as TrendsFilterType)-- expect(cleanedFilters).toMatchObject({- breakdowns: [- {- property: '$current_url',- type: 'event',- normalize_url: true,- },- ],- })- })-- it('defaults to normalizing URL for breakdown by $current_url', () => {- const cleanedFilters = cleanFilters({- breakdown: '$current_url',- breakdown_type: 'event',- } as TrendsFilterType)-- expect(cleanedFilters).toHaveProperty('breakdown_normalize_url', true)- })-- it('defaults to normalizing URL for breakdowns by $pathname', () => {- const cleanedFilters = cleanFilters({- breakdowns: [{ property: '$pathname', type: 'event' }],- breakdown_type: 'event',- } as TrendsFilterType)-- expect(cleanedFilters).toMatchObject({- breakdowns: [- {- property: '$pathname',- type: 'event',- normalize_url: true,- },- ],- })- })-- it('defaults to normalizing URL for breakdown by $pathname', () => {- const cleanedFilters = cleanFilters({- breakdown: '$pathname',- breakdown_type: 'event',- } as TrendsFilterType)-- expect(cleanedFilters).toHaveProperty('breakdown_normalize_url', true)- })-- it('can set normalizing URL for breakdown to false', () => {- const cleanedFilters = cleanFilters({- breakdown: '$current_url',- breakdown_type: 'event',- breakdown_normalize_url: false,- } as TrendsFilterType)-- expect(cleanedFilters).toHaveProperty('breakdown_normalize_url', false)- })-- it('removes normalizing URL for breakdown by other properties', () => {- const cleanedFilters = cleanFilters({- breakdowns: [{ property: '$pageview', type: 'event' }],- breakdown_type: 'event',- } as TrendsFilterType)-- expect(cleanedFilters).toHaveProperty('breakdown_normalize_url', undefined)- })-- const breakdownIndexTestCases = [- {- filters: { breakdown_type: 'group', breakdown_group_type_index: 0, insight: InsightType.TRENDS },- expected: 0,- },- {- filters: { breakdown_type: 'group', breakdown_group_type_index: 3, insight: InsightType.TRENDS },- expected: 3,- },- {- filters: { breakdown_type: 'group', breakdown_group_type_index: null, insight: InsightType.TRENDS },- expected: undefined,- },- {- filters: { breakdown_type: 'group', breakdown_group_type_index: undefined, insight: InsightType.TRENDS },- expected: undefined,- },- {- filters: { breakdown_type: 'event', breakdown_group_type_index: 0, insight: InsightType.TRENDS },- expected: undefined,- },- ]- breakdownIndexTestCases.forEach((testCase) => {- it(`can add a breakdown_group_type_index of ${testCase.filters.breakdown_group_type_index} when breakdown type is ${testCase.filters.breakdown_type}`, () => {- const cleanedFilters = cleanFilters(testCase.filters as Partial<FilterType>)- expect(cleanedFilters.breakdown_group_type_index).toEqual(testCase.expected)- })- })-- it('removes empty breakdowns array', () => {- const cleanedFilters = cleanFilters({- breakdowns: [],- insight: InsightType.FUNNELS,- funnel_viz_type: FunnelVizType.Steps,- } as FunnelsFilterType)-- expect(cleanedFilters).toHaveProperty('breakdowns', undefined)- expect(cleanedFilters).toHaveProperty('breakdown', undefined)- expect(cleanedFilters).toHaveProperty('breakdown_type', undefined)- })-- it('does not include breakdown properties if funnel is time to convert', () => {- const cleanedFilters = cleanFilters({- breakdowns: [{ property: 'any', type: 'event' }],- breakdown: 'something',- breakdown_type: 'event',- breakdown_group_type_index: 1,- insight: InsightType.FUNNELS,- funnel_viz_type: FunnelVizType.TimeToConvert,- } as FunnelsFilterType)-- expect(cleanedFilters).toHaveProperty('breakdowns', undefined)- expect(cleanedFilters).toHaveProperty('breakdown', undefined)- expect(cleanedFilters).toHaveProperty('breakdown_type', undefined)- expect(cleanedFilters).toHaveProperty('breakdown_group_type_index', undefined)- })-- it('keeps multiple breakdowns', () => {- const cleanedFilters = cleanFilters({- breakdowns: [{ property: 'any', type: 'event' }],- insight: InsightType.TRENDS,- } as TrendsFilterType)-- expect(cleanedFilters).toHaveProperty('breakdowns', [{ property: 'any', type: 'event' }])- })-- it('keeps normalize_url for multiple breakdowns', () => {- const cleanedFilters = cleanFilters({- breakdowns: [{ property: '$current_url', type: 'event', normalize_url: true }],- insight: InsightType.TRENDS,- } as TrendsFilterType)-- expect(cleanedFilters).toHaveProperty('breakdowns', [- { property: '$current_url', type: 'event', normalize_url: true },- ])-- cleanedFilters.breakdowns![0].normalize_url = false- expect(cleanedFilters).toHaveProperty('breakdowns', [- { property: '$current_url', type: 'event', normalize_url: false },- ])- })-- it('restores a breakdown type for legacy multiple breakdowns', () => {- const cleanedFilters = cleanFilters({- breakdowns: [{ property: 'any' }],- breakdown_type: 'event',- insight: InsightType.TRENDS,- } as TrendsFilterType)-- expect(cleanedFilters).toHaveProperty('breakdowns', [{ property: 'any', type: 'event' }])- expect(cleanedFilters.breakdown_type).toBeUndefined()- })-- it('cleans a breakdown when multiple breakdowns are used', () => {- const cleanedFilters = cleanFilters({- breakdowns: [{ property: 'any', type: 'event' }],- breakdown_type: 'event',- breakdown: 'test',- insight: InsightType.TRENDS,- } as TrendsFilterType)-- expect(cleanedFilters).toHaveProperty('breakdowns', [{ property: 'any', type: 'event' }])- expect(cleanedFilters).toHaveProperty('breakdown_type', undefined)- expect(cleanedFilters).toHaveProperty('breakdown', undefined)- })-- it('uses a breakdown when multiple breakdowns are empty', () => {- const cleanedFilters = cleanFilters({- breakdowns: [],- breakdown_type: 'event',- breakdown: 'test',- insight: InsightType.TRENDS,- } as TrendsFilterType)-- expect(cleanedFilters).toHaveProperty('breakdown', 'test')- expect(cleanedFilters).toHaveProperty('breakdown_type', 'event')- expect(cleanedFilters).toHaveProperty('breakdowns', undefined)- })-- it('keeps a breakdown limit', () => {- const cleanedFilters = cleanFilters({- breakdown_limit: 22,- insight: InsightType.TRENDS,- } as TrendsFilterType)-- expect(cleanedFilters).toHaveProperty('breakdown_limit', 22)- })-- it('keeps single property filters for trends', () => {- const cleanedFilters = cleanFilters({- breakdown: 'one thing',- breakdown_type: 'event',- insight: InsightType.TRENDS,- })-- expect(cleanedFilters).toHaveProperty('breakdowns', undefined)- expect(cleanedFilters).toHaveProperty('breakdown', 'one thing')- expect(cleanedFilters).toHaveProperty('breakdown_type', 'event')- expect(cleanedFilters).toHaveProperty('breakdown_group_type_index', undefined)- })-- it('keeps single property filters for funnels', () => {- const cleanedFilters = cleanFilters({- breakdown: 'one thing',- breakdown_type: 'event',- insight: InsightType.FUNNELS,- funnel_viz_type: FunnelVizType.Steps,- } as FunnelsFilterType)-- expect(cleanedFilters).toHaveProperty('breakdowns', undefined)- expect(cleanedFilters).toHaveProperty('breakdown', 'one thing')- expect(cleanedFilters).toHaveProperty('breakdown_type', 'event')- expect(cleanedFilters).toHaveProperty('breakdown_group_type_index', undefined)- })-- it('keeps a multi property breakdown for trends', () => {- const cleanedFilters = cleanFilters({- breakdowns: [- { property: 'one thing', type: 'event' },- { property: 'two thing', type: 'event' },- ],- breakdown_type: 'event',- insight: InsightType.TRENDS,- })-- expect(cleanedFilters).toHaveProperty('breakdowns', [- { property: 'one thing', type: 'event' },- { property: 'two thing', type: 'event' },- ])- expect(cleanedFilters.breakdown_type).toBeUndefined()- })-- it('reads "smoothing_intervals" and "interval" from URL when viewing and corrects bad pairings', () => {- const cleanedFilters = cleanFilters({- interval: 'day',- smoothing_intervals: 4,- })-- expect(cleanedFilters).toHaveProperty('smoothing_intervals', 1)- })-- it('can add funnel step reference', () => {- const cleanedFilters = cleanFilters({- funnel_step_reference: FunnelStepReference.previous,- insight: InsightType.FUNNELS,- })-- expect(cleanedFilters).toHaveProperty('funnel_step_reference', FunnelStepReference.previous)- })-- it('removes the interval from funnels', () => {- const cleanedFilters = cleanFilters({- insight: InsightType.FUNNELS,- interval: 'hour',- })-- expect(cleanedFilters).toHaveProperty('interval', undefined)- })-- it('keeps the interval for trends funnels', () => {- const cleanedFilters = cleanFilters({- insight: InsightType.FUNNELS,- funnel_viz_type: FunnelVizType.Trends,- interval: 'hour',- })-- expect(cleanedFilters).toHaveProperty('interval', 'hour')- })-- describe('show_values_on_series', () => {- ;[InsightType.TRENDS, InsightType.LIFECYCLE, InsightType.STICKINESS].forEach((insight) => {- it(`keeps show values on series for ${insight}`, () => {- const cleanedFilters = cleanFilters({- insight,- show_values_on_series: true,- })-- expect(cleanedFilters).toHaveProperty('show_values_on_series', true)- })- })- NON_VALUES_ON_SERIES_DISPLAY_TYPES.forEach((display) => {- it(`removes show values on series for ${display}`, () => {- const cleanedFilters = cleanFilters({- insight: InsightType.TRENDS,- display,- show_values_on_series: true,- })-- expect(cleanedFilters).not.toHaveProperty('show_values_on_series')- })- })- ;[(InsightType.PATHS, InsightType.FUNNELS, InsightType.RETENTION)].forEach((insight) => {- it(`removes show values on series for ${insight}`, () => {- const cleanedFilters = cleanFilters({- insight,- show_values_on_series: true,- })-- expect(cleanedFilters).not.toHaveProperty('show_values_on_series')- })- })- it('sets show values on series for piecharts if it is undefined', () => {- const cleanedFilters = cleanFilters({- insight: InsightType.TRENDS,- display: ChartDisplayType.ActionsPie,- })-- expect(cleanedFilters).toHaveProperty('show_values_on_series', true)- })- it('can set show values on series for piecharts to false', () => {- const cleanedFilters = cleanFilters({- insight: InsightType.TRENDS,- display: ChartDisplayType.ActionsPie,- show_values_on_series: false,- })-- expect(cleanedFilters).toHaveProperty('show_values_on_series', false)- })- })-})diff --git a/frontend/src/scenes/insights/utils/cleanFilters.ts b/frontend/src/scenes/insights/utils/cleanFilters.tsdeleted file mode 100644index 7c643d14f367..000000000000--- a/frontend/src/scenes/insights/utils/cleanFilters.ts+++ /dev/null@@ -1,537 +0,0 @@-import { smoothingOptions } from 'lib/components/SmoothingFilter/smoothings'-import {- BIN_COUNT_AUTO,- NON_TIME_SERIES_DISPLAY_TYPES,- NON_VALUES_ON_SERIES_DISPLAY_TYPES,- PERCENT_STACK_VIEW_DISPLAY_TYPE,- PIE_DISPLAY_TYPES,- RETENTION_FIRST_OCCURRENCE_MATCHING_FILTERS,- RETENTION_MEAN_NONE,- ShownAsValue,-} from 'lib/constants'-import { getDefaultEventName } from 'lib/utils/getAppContext'-import { clamp } from 'lib/utils/numbers'-import { isURLNormalizeable } from 'scenes/insights/filters/BreakdownFilter/taxonomicBreakdownFilterUtils'-import {- isFunnelsFilter,- isLifecycleFilter,- isPathsFilter,- isRetentionFilter,- isStickinessFilter,- isTrendsFilter,-} from 'scenes/insights/sharedUtils'--import {- AnyFilterType,- ChartDisplayType,- Entity,- EntityTypes,- FilterType,- FunnelExclusionLegacy,- FunnelVizType,- FunnelsFilterType,- InsightType,- IntervalType,- LifecycleFilterType,- PathType,- PathsFilterType,- RetentionFilterType,- RetentionPeriod,- StickinessFilterType,- TrendsFilterType,-} from '~/types'--import { DEFAULT_STEP_LIMIT } from 'products/product_analytics/frontend/insights/paths/pathsDataLogic'--import { LocalFilter, toLocalFilters } from '../filters/ActionFilter/legacyFilters'--export function getDefaultEvent(): Entity {- const event = getDefaultEventName()- // When event is null (all events), we need to use null as the id but provide a display name- const displayName = event === null ? 'All events' : event- return {- id: event,- name: displayName,- type: EntityTypes.EVENTS,- order: 0,- }-}--export const isStepsUndefined = (filters: FunnelsFilterType): boolean =>- typeof filters.events === 'undefined' &&- (typeof filters.actions === 'undefined' || filters.actions.length === 0) &&- (typeof filters.data_warehouse === 'undefined' || filters.data_warehouse.length === 0)--const findFirstNumber = (candidates: (number | undefined)[]): number | undefined =>- candidates.find((s) => typeof s === 'number')--export const getClampedStepRangeFilter = ({- stepRange,- filters,-}: {- stepRange?: FunnelExclusionLegacy | { funnel_from_step?: number; funnel_to_step?: number }- filters: FunnelsFilterType-}): FunnelExclusionLegacy | { funnel_from_step?: number; funnel_to_step?: number } => {- const maxStepIndex = Math.max((filters.events?.length || 0) + (filters.actions?.length || 0) - 1, 1)-- let funnel_from_step = findFirstNumber([stepRange?.funnel_from_step, filters.funnel_from_step])- let funnel_to_step = findFirstNumber([stepRange?.funnel_to_step, filters.funnel_to_step])-- const funnelFromStepIsSet = typeof funnel_from_step === 'number'- const funnelToStepIsSet = typeof funnel_to_step === 'number'-- if (funnelFromStepIsSet && funnelToStepIsSet) {- funnel_from_step = clamp(funnel_from_step ?? 0, 0, maxStepIndex)- funnel_to_step = clamp(funnel_to_step ?? maxStepIndex, funnel_from_step + 1, maxStepIndex)- }-- return {- ...stepRange,- funnel_from_step,- funnel_to_step,- }-}--export const deepCleanFunnelExclusionEvents = (filters: FunnelsFilterType): FunnelExclusionLegacy[] | undefined => {- if (!filters.exclusions) {- return undefined- }-- const lastIndex = Math.max((filters.events?.length || 0) + (filters.actions?.length || 0) - 1, 1)- const exclusions = filters.exclusions.map((event) => {- const funnel_from_step = event.funnel_from_step ? clamp(event.funnel_from_step, 0, lastIndex - 1) : 0- return {- ...event,- funnel_from_step,-- funnel_to_step: event.funnel_to_step- ? clamp(event.funnel_to_step, funnel_from_step + 1, lastIndex)- : lastIndex,- }- })- return exclusions.length > 0 ? exclusions : undefined-}--/** Take the first series from filters and, based on it, apply the most relevant breakdown type to cleanedParams. */-const useMostRelevantBreakdownType = (cleanedParams: Partial<FilterType>, filters: Partial<FilterType>): void => {- const series: LocalFilter | undefined = toLocalFilters(filters)[0]- cleanedParams['breakdown_type'] = ['dau', 'weekly_active', 'monthly_active'].includes(series?.math || '')- ? 'person'- : 'event'-}--function cleanBreakdownNormalizeURL(- breakdown: string,- breakdownNormalizeURL: boolean | undefined-): boolean | undefined {- return isURLNormalizeable(breakdown)- ? breakdownNormalizeURL !== undefined- ? breakdownNormalizeURL- : true- : undefined-}--const cleanBreakdownParams = (cleanedParams: Partial<FilterType>, filters: Partial<FilterType>): void => {- const isStepsFunnel = isFunnelsFilter(filters) && filters.funnel_viz_type === FunnelVizType.Steps- const isTrendsFunnel = isFunnelsFilter(filters) && filters.funnel_viz_type === FunnelVizType.Trends- const isTrends = isTrendsFilter(filters)- const canBreakdown = isStepsFunnel || isTrendsFunnel || isTrends-- const canMultiPropertyBreakdown = isStepsFunnel-- cleanedParams['breakdowns'] = undefined- cleanedParams['breakdown'] = undefined- cleanedParams['breakdown_type'] = undefined- cleanedParams['breakdown_group_type_index'] = undefined- cleanedParams['breakdown_normalize_url'] = undefined-- if (isTrends && filters.display === ChartDisplayType.WorldMap) {- // For the map, make sure we are breaking down by country- // Support automatic switching to country code breakdown both from no breakdown and from country name breakdown- cleanedParams['breakdown'] = '$geoip_country_code'- // this isn't a react hook- // oxlint-disable-next-line react-hooks/rules-of-hooks- useMostRelevantBreakdownType(cleanedParams, filters)- return- }-- if (canBreakdown) {- if (filters.breakdown_type && (filters.breakdown || filters.breakdowns)) {- cleanedParams['breakdown_type'] = filters.breakdown_type- }-- if (canMultiPropertyBreakdown && filters.breakdowns && filters.breakdowns.length > 0) {- cleanedParams['breakdowns'] = filters.breakdowns- } else if (isTrends && filters.breakdowns && filters.breakdowns.length > 0) {- cleanedParams['breakdown_type'] = undefined- cleanedParams['breakdowns'] = filters.breakdowns.map((b) => ({- property: b.property,- type: b.type || filters.breakdown_type || 'event',- histogram_bin_count: b.histogram_bin_count,- group_type_index: b.group_type_index,- normalize_url:- typeof b.property === 'string'- ? cleanBreakdownNormalizeURL(- b.property,- typeof b.normalize_url === 'boolean' ? b.normalize_url : filters.breakdown_normalize_url- )- : undefined,- }))- } else if (filters.breakdown) {- cleanedParams['breakdown'] = filters.breakdown- cleanedParams['breakdown_normalize_url'] = cleanBreakdownNormalizeURL(- filters.breakdown as string,- filters.breakdown_normalize_url- )- }-- if (filters.breakdown_type === 'group' && filters.breakdown_group_type_index != undefined) {- cleanedParams['breakdown_group_type_index'] = filters.breakdown_group_type_index- }- }-}--type CommonFiltersTypeKeys = keyof TrendsFilterType &- keyof FunnelsFilterType &- keyof RetentionFilterType &- keyof PathsFilterType &- keyof StickinessFilterType &- keyof LifecycleFilterType--type CommonFiltersType = {- [K in CommonFiltersTypeKeys]: FilterType[K]-}--/** Heuristic for determining wether this is a new insight, usually set by url.- * In the most basic case something like `/insights/new?insight=TRENDS`. */-const isNewInsight = (filters: Partial<AnyFilterType>): boolean => {- if (Object.keys(filters).length === 0) {- return true- }-- if (- isTrendsFilter(filters) ||- isFunnelsFilter(filters) ||- isStickinessFilter(filters) ||- isLifecycleFilter(filters)- ) {- return !filters.actions && !filters.events- }-- if (isRetentionFilter(filters)) {- return !filters.returning_entity && !filters.target_entity- }-- if (isPathsFilter(filters)) {- return !filters.include_event_types- }-- return true-}--export const setTestAccountFilterForNewInsight = (- filter: Partial<AnyFilterType>,- test_account_filters_default_checked?: boolean-): void => {- if (localStorage.getItem('default_filter_test_accounts') !== null) {- // use current user default- filter.filter_test_accounts = localStorage.getItem('default_filter_test_accounts') === 'true'- } else if (!filter.filter_test_accounts && test_account_filters_default_checked !== undefined) {- // overwrite with team default, only if not set- filter.filter_test_accounts = test_account_filters_default_checked- }-}--const disableHourFor: Record<string, boolean> = {- dStart: false,- '-1d': false,- '-7d': false,- '-14d': false,- '-30d': false,- '-90d': true,- mStart: false,- '-1mStart': false,- yStart: true,- all: true,- other: false,-}--export function autocorrectInterval(filters: Partial<AnyFilterType>): IntervalType | undefined {- if ('display' in filters && filters.display && NON_TIME_SERIES_DISPLAY_TYPES.includes(filters.display)) {- // Non-time-series insights should not have an interval- return undefined- }- if (isFunnelsFilter(filters) && filters.funnel_viz_type !== FunnelVizType.Trends) {- // Only trend funnels support intervals- return undefined- }- if (!filters.interval) {- return 'day'- }-- const minute_disabled = filters.interval === 'minute'- const hour_disabled = disableHourFor[filters.date_from || 'other'] && filters.interval === 'hour'-- if (minute_disabled) {- return 'hour'- } else if (hour_disabled) {- return 'day'- }- return filters.interval-}--export function cleanFilters(- filters: Partial<AnyFilterType>,- test_account_filters_default_checked?: boolean-): Partial<FilterType> {- const commonFilters: Partial<CommonFiltersType> = {- ...(filters.sampling_factor ? { sampling_factor: filters.sampling_factor } : {}),- ...(filters.filter_test_accounts ? { filter_test_accounts: filters.filter_test_accounts } : {}),- ...(filters.properties ? { properties: filters.properties } : {}),- ...(filters.filter_test_accounts ? { filter_test_accounts: filters.filter_test_accounts } : {}),- }-- // set test account filter default for new insights from team and local storage settings- if (isNewInsight(filters)) {- setTestAccountFilterForNewInsight(commonFilters, test_account_filters_default_checked)- }-- if (isRetentionFilter(filters)) {- const retentionFilter: Partial<RetentionFilterType> = {- insight: InsightType.RETENTION,- target_entity: filters.target_entity || {- id: '$pageview',- name: '$pageview',- type: 'events',- },- returning_entity: filters.returning_entity || { id: '$pageview', type: 'events', name: '$pageview' },- date_to: filters.date_to,- period: filters.period || RetentionPeriod.Day,- retention_type:- filters.retention_type ||- (filters as any)['retentionType'] ||- RETENTION_FIRST_OCCURRENCE_MATCHING_FILTERS,- breakdowns: filters.breakdowns,- breakdown_type: filters.breakdown_type,- retention_reference: filters.retention_reference,- show_mean: filters.show_mean,- ...(filters.mean_retention_calculation && filters.mean_retention_calculation !== RETENTION_MEAN_NONE- ? { mean_retention_calculation: filters.mean_retention_calculation }- : { mean_retention_calculation: 'simple' }),- cumulative: filters.cumulative,- total_intervals: Math.min(Math.max(filters.total_intervals ?? 11, 0), 100),- ...(filters.aggregation_group_type_index != null- ? { aggregation_group_type_index: filters.aggregation_group_type_index }- : {}),- ...commonFilters,- }- return retentionFilter- } else if (isFunnelsFilter(filters)) {- const funnelsFilter: Partial<FunnelsFilterType> = {- insight: InsightType.FUNNELS,- ...(filters.date_from ? { date_from: filters.date_from } : {}),- ...(filters.date_to ? { date_to: filters.date_to } : {}),- ...(filters.actions ? { actions: filters.actions } : {}),- ...(filters.events ? { events: filters.events } : {}),- ...(filters.layout ? { layout: filters.layout } : {}),- ...(filters.new_entity ? { new_entity: filters.new_entity } : {}),- ...(filters.interval ? { interval: filters.interval } : {}),- ...(filters.funnel_step ? { funnel_step: filters.funnel_step } : {}),- ...(filters.funnel_from_step ? { funnel_from_step: filters.funnel_from_step } : {}),- ...(filters.funnel_to_step ? { funnel_to_step: filters.funnel_to_step } : {}),- ...(filters.funnel_step_reference ? { funnel_step_reference: filters.funnel_step_reference } : {}),- ...(filters.funnel_viz_type- ? { funnel_viz_type: filters.funnel_viz_type }- : { funnel_viz_type: FunnelVizType.Steps }),- ...(filters.entrance_period_start ? { entrance_period_start: filters.entrance_period_start } : {}),- ...(filters.drop_off != undefined ? { drop_off: filters.drop_off } : {}),- ...(filters.funnel_step_breakdown !== undefined- ? { funnel_step_breakdown: filters.funnel_step_breakdown }- : {}),- ...(filters.bin_count && filters.bin_count !== BIN_COUNT_AUTO ? { bin_count: filters.bin_count } : {}),- ...(filters.funnel_window_interval_unit- ? { funnel_window_interval_unit: filters.funnel_window_interval_unit }- : {}),- ...(filters.funnel_window_interval ? { funnel_window_interval: filters.funnel_window_interval } : {}),- ...(filters.funnel_order_type ? { funnel_order_type: filters.funnel_order_type } : {}),- ...(filters.hidden_legend_keys ? { hidden_legend_keys: filters.hidden_legend_keys } : {}),- ...(filters.funnel_aggregate_by_hogql- ? { funnel_aggregate_by_hogql: filters.funnel_aggregate_by_hogql }- : {}),- ...(filters.breakdown_attribution_type- ? { breakdown_attribution_type: filters.breakdown_attribution_type }- : {}),- ...(filters.breakdown_attribution_value !== undefined- ? { breakdown_attribution_value: filters.breakdown_attribution_value }- : {}),- exclusions: deepCleanFunnelExclusionEvents(filters),- interval: autocorrectInterval(filters),- funnel_custom_steps: filters.funnel_custom_steps || undefined,- ...(filters.aggregation_group_type_index != null- ? { aggregation_group_type_index: filters.aggregation_group_type_index }- : {}),- ...commonFilters,- }-- cleanBreakdownParams(funnelsFilter, filters)-- // if we came from an URL with just `#q={insight:TRENDS}` (no `events`/`actions`), add the default states `[]`- if (isStepsUndefined(funnelsFilter)) {- funnelsFilter.events = [getDefaultEvent()]- funnelsFilter.actions = []- }-- // make sure exclusion steps are clamped within new step range- const returnedParams: Partial<FunnelsFilterType> = {- ...funnelsFilter,- ...getClampedStepRangeFilter({ filters: funnelsFilter }),- exclusions: (funnelsFilter.exclusions || []).map((e) =>- getClampedStepRangeFilter({- stepRange: e,- filters: funnelsFilter,- })- ) as FunnelExclusionLegacy[],- }- return returnedParams- } else if (isPathsFilter(filters)) {- const pathsFilter: Partial<PathsFilterType> = {- insight: InsightType.PATHS,- start_point: filters.start_point || undefined,- end_point: filters.end_point || undefined,- step_limit: filters.step_limit || DEFAULT_STEP_LIMIT,- // TODO: use FF for path_type undefined- path_type: filters.path_type ? filters.path_type || PathType.PageView : undefined,- include_event_types: filters.include_event_types || (filters.funnel_filter ? [] : [PathType.PageView]),- paths_hogql_expression: filters.paths_hogql_expression || undefined,- path_groupings: filters.path_groupings || [],- exclude_events: filters.exclude_events || [],- ...(filters.include_event_types ? { include_event_types: filters.include_event_types } : {}),- date_from: filters.date_from,- date_to: filters.date_to,- path_start_key: filters.path_start_key || undefined,- path_end_key: filters.path_end_key || undefined,- path_dropoff_key: filters.path_dropoff_key || undefined,- funnel_filter: filters.funnel_filter || { date_from: filters.date_from },- funnel_paths: filters.funnel_paths,- path_replacements: filters.path_replacements || undefined,- local_path_cleaning_filters: filters.local_path_cleaning_filters || [],- edge_limit: filters.edge_limit || undefined,- min_edge_weight: filters.min_edge_weight || undefined,- max_edge_weight: filters.max_edge_weight || undefined,- ...commonFilters,- }- return pathsFilter- } else if (isTrendsFilter(filters) || isLifecycleFilter(filters) || isStickinessFilter(filters)) {- const trendLikeFilter: Partial<TrendsFilterType> = {- insight: isLifecycleFilter(filters)- ? InsightType.LIFECYCLE- : isStickinessFilter(filters)- ? InsightType.STICKINESS- : InsightType.TRENDS,- ...filters,- interval: autocorrectInterval(filters),- ...(isTrendsFilter(filters) ? { display: filters.display || ChartDisplayType.ActionsLineGraph } : {}),- actions: Array.isArray(filters.actions) ? filters.actions : undefined,- events: Array.isArray(filters.events) ? filters.events : undefined,- ...(isTrendsFilter(filters) && isStickinessFilter(filters) && filters.hidden_legend_keys- ? { hidden_legend_keys: filters.hidden_legend_keys }- : {}),- ...(filters.show_values_on_series ? { show_values_on_series: filters.show_values_on_series } : {}),- ...(isTrendsFilter(filters) && filters?.show_percent_stack_view- ? { show_percent_stack_view: filters.show_percent_stack_view }- : {}),- y_axis_scale_type: isTrendsFilter(filters) ? filters.y_axis_scale_type : undefined,- ...commonFilters,- }-- if (- 'show_values_on_series' in trendLikeFilter &&- !!trendLikeFilter.display &&- NON_VALUES_ON_SERIES_DISPLAY_TYPES.includes(trendLikeFilter.display)- ) {- delete trendLikeFilter.show_values_on_series- }-- if (- !!trendLikeFilter.display &&- PIE_DISPLAY_TYPES.includes(trendLikeFilter.display) &&- trendLikeFilter.show_values_on_series === undefined- ) {- trendLikeFilter.show_values_on_series = true- }-- if (- 'show_percent_stack_view' in trendLikeFilter &&- !!trendLikeFilter.display &&- !PERCENT_STACK_VIEW_DISPLAY_TYPE.includes(trendLikeFilter.display)- ) {- delete trendLikeFilter.show_percent_stack_view- }-- if (- !!trendLikeFilter.display &&- PIE_DISPLAY_TYPES.includes(trendLikeFilter.display) &&- trendLikeFilter.show_percent_stack_view === undefined- ) {- trendLikeFilter.show_percent_stack_view = true- }-- cleanBreakdownParams(trendLikeFilter, filters)-- // TODO: Deprecated; should be removed once backend is updated- trendLikeFilter['shown_as'] = isStickinessFilter(filters)- ? ShownAsValue.STICKINESS- : isLifecycleFilter(filters)- ? ShownAsValue.LIFECYCLE- : undefined-- if (filters.date_from === 'all' || isLifecycleFilter(filters)) {- trendLikeFilter['compare'] = false- trendLikeFilter['compare_to'] = undefined- }-- if (trendLikeFilter.interval && trendLikeFilter.smoothing_intervals) {- if (- !smoothingOptions[trendLikeFilter.interval].find(- (option) => option.value === trendLikeFilter.smoothing_intervals- )- ) {- if (trendLikeFilter.smoothing_intervals !== 1) {- trendLikeFilter.smoothing_intervals = 1- }- }- }-- if (trendLikeFilter.insight === InsightType.LIFECYCLE) {- if (trendLikeFilter.events?.length) {- trendLikeFilter.events = [- {- ...trendLikeFilter.events[0],- math: 'total',- },- ]- trendLikeFilter.actions = []- } else if (trendLikeFilter.actions?.length) {- trendLikeFilter.events = []- trendLikeFilter.actions = [- {- ...trendLikeFilter.actions[0],- math: 'total',- },- ]- }- }-- if (isStepsUndefined(trendLikeFilter)) {- trendLikeFilter.events = [getDefaultEvent()]- trendLikeFilter.actions = []- }-- return trendLikeFilter- } else if ((filters as any).insight === 'SESSIONS') {- // DEPRECATED: Used to show deprecation warning for dashboard items- return cleanFilters({ insight: InsightType.TRENDS })- }-- throw new Error(`Unknown insight type "${(filters as any).insight}" given to cleanFilters`)-}diff --git a/frontend/src/scenes/trends/persons-modal/PersonsModal.stories.tsx b/frontend/src/scenes/trends/persons-modal/PersonsModal.stories.tsxindex acbb5b1a246d..ac8821f06cd6 100644--- a/frontend/src/scenes/trends/persons-modal/PersonsModal.stories.tsx+++ b/frontend/src/scenes/trends/persons-modal/PersonsModal.stories.tsx@@ -1,9 +1,10 @@import { Meta, StoryObj } from '@storybook/react'import { delay, HttpResponse } from 'msw'-import { RawPropertiesTimelineResult } from 'lib/components/PropertiesTimeline/propertiesTimelineLogic'-import { useStorybookMocks } from '~/mocks/browser'+import { InsightActorsQuery, NodeKind } from '~/queries/schema/schema-general'++import type { PropertiesTimelineResponseApi } from 'products/persons/frontend/generated/api.schemas'import EXAMPLE_PERSONS_RESPONSE from './__mocks__/examplePersonsResponse.json'import EXAMPLE_SESSION_ACTORS_RESPONSE from './__mocks__/exampleSessionActorsResponse.json'@@ -17,11 +18,47 @@ export default metatype Story = StoryObj<{}>+const EXAMPLE_TRENDS_ACTORS_QUERY: InsightActorsQuery = {+ kind: NodeKind.InsightActorsQuery,+ source: {+ kind: NodeKind.TrendsQuery,+ series: [{ kind: NodeKind.EventsNode, event: '$pageview', name: '$pageview' }],+ interval: 'day',+ dateRange: { date_from: '2022-12-01', date_to: '2022-12-13' },+ breakdownFilter: { breakdown: '$geoip_country_code', breakdown_type: 'person' },+ },+ day: '2022-12-02',+ series: 0,+ includeRecordings: true,+}++const EXAMPLE_ACTORS_QUERY_RESPONSE = {+ columns: ['actor', 'event_count', 'matched_recordings'],+ results: EXAMPLE_PERSONS_RESPONSE.results[0].people.map((person) => [+ {+ id: person.uuid,+ distinct_ids: person.distinct_ids,+ is_identified: person.is_identified,+ properties: person.properties,+ created_at: person.created_at,+ },+ person.value_at_data_point,+ person.matched_recordings.map((session_id) => ({ session_id, events: [] })),+ ]),+ hasMore: false,+ limit: 100,+ offset: 0,+ missing_actors_count: 0,+}+export const WithResults: Story = {render: () => {useStorybookMocks({- get: {- [EXAMPLE_PERSONS_RESPONSE.initial]: EXAMPLE_PERSONS_RESPONSE,+ post: {+ '/api/environments/:team_id/query/:kind/': ({ params }) => [+ 200,+ params.kind === NodeKind.ActorsQuery ? EXAMPLE_ACTORS_QUERY_RESPONSE : {},+ ],[`/api/projects/:team_id/persons/${EXAMPLE_PERSONS_RESPONSE.results[0].people[0].uuid}/properties_timeline/`]:{points: [@@ -32,7 +69,6 @@ export const WithResults: Story = {email: '[email protected]',$geoip_country_code: 'US',},- matched_recordings: ['1234567890'],relevant_event_count: 2,},{@@ -45,34 +81,30 @@ export const WithResults: Story = {relevant_event_count: 9,},{- timestamp: '2022-12-08T00:00:00.000Z',+ timestamp: '2022-12-02T14:00:00.000Z',properties: {name: 'Francisco Elliott',email: '[email protected]',$geoip_country_code: 'DE',},- relevant_event_count: 155,- },- {- timestamp: '2022-12-12T00:00:00.000Z',- properties: {- name: 'Francisco Elliott',- email: '[email protected]',- $geoip_country_code: 'CN',- },- relevant_event_count: 13,+ relevant_event_count: 3,},],crucial_property_keys: ['$geoip_country_code'],- effective_date_from: '2022-12-01T00:00:00.000+00:00',- effective_date_to: '2022-12-13T23:59:59.999999+00:00',- } as RawPropertiesTimelineResult,+ effective_date_from: '2022-12-02T00:00:00+00:00',+ effective_date_to: '2022-12-03T00:00:00+00:00',+ } as PropertiesTimelineResponseApi,},})return (<div className="flex max-h-200">- <PersonsModalComponent title="Hello!" url={EXAMPLE_PERSONS_RESPONSE.initial} inline />+ <PersonsModalComponent+ title="Hello!"+ query={EXAMPLE_TRENDS_ACTORS_QUERY}+ additionalSelect={{ value_at_data_point: 'event_count', matched_recordings: 'matched_recordings' }}+ inline+ /></div>)},diff --git a/frontend/src/scenes/trends/persons-modal/PersonsModal.tsx b/frontend/src/scenes/trends/persons-modal/PersonsModal.tsxindex 456837bd9294..2057ac0a2ca2 100644--- a/frontend/src/scenes/trends/persons-modal/PersonsModal.tsx+++ b/frontend/src/scenes/trends/persons-modal/PersonsModal.tsx@@ -40,13 +40,12 @@ import { isSharedView } from '~/exporter/exporterViewLogic'import { Noun } from '~/models/groupsModel'import { MAX_SELECT_RETURNED_ROWS } from '~/queries/nodes/DataTable/DataTableExport'import { extractValidationErrorCode } from '~/queries/nodes/InsightViz/utils'-import { FunnelsActorsQuery, NodeKind } from '~/queries/schema/schema-general'+import { FunnelsActorsQuery, InsightActorsQuery, NodeKind } from '~/queries/schema/schema-general'import {AccessControlLevel,AccessControlResourceType,ActorType,ExporterFormat,- PropertiesTimelineFilterType,PropertyDefinitionType,} from '~/types'@@ -107,7 +106,7 @@ export function PersonsModal({isCohortModalOpen,isModalOpen,missingActorsCount,- propertiesTimelineFilterFromUrl,+ propertiesTimelineQuery,insightEventsQueryUrl,exploreUrl,actorsQuery,@@ -325,11 +324,11 @@ export function PersonsModal({// created_at is null for actors without a PostgreSQL Person record// (personless mode, merged, or deleted persons) — skip the// timeline which would 404, and show static properties instead.- propertiesTimelineFilter={+ propertiesTimelineQuery={actor.type == 'person' &&actor.created_at &¤tTeam?.person_on_events_querying_enabled- ? propertiesTimelineFilterFromUrl+ ? (propertiesTimelineQuery ?? undefined): undefined}/>@@ -437,10 +436,11 @@ export function PersonsModal({interface ActorRowProps {actor: ActorType- propertiesTimelineFilter?: PropertiesTimelineFilterType+ /** The clicked data point's actors query, when the timeline supports it and the actor is a person. */+ propertiesTimelineQuery?: InsightActorsQuery}-export function ActorRow({ actor, propertiesTimelineFilter }: ActorRowProps): JSX.Element {+export function ActorRow({ actor, propertiesTimelineQuery }: ActorRowProps): JSX.Element {const [expanded, setExpanded] = useState(false)const [tab, setTab] = useState('properties')const isSession = isSessionType(actor)@@ -557,14 +557,15 @@ export function ActorRow({ actor, propertiesTimelineFilter }: ActorRowProps): JS{key: 'properties',label: 'Properties',- content: propertiesTimelineFilter ? (- <PropertiesTimeline actor={actor} filter={propertiesTimelineFilter} />- ) : (- <PropertiesTable- type={actor.type as PropertyDefinitionType}- properties={actor.properties}- />- ),+ content:+ propertiesTimelineQuery && actor.type === 'person' ? (+ <PropertiesTimeline actor={actor} query={propertiesTimelineQuery} />+ ) : (+ <PropertiesTable+ type={actor.type as PropertyDefinitionType}+ properties={actor.properties}+ />+ ),},...(isSession && actor.person? [diff --git a/frontend/src/scenes/trends/persons-modal/peronsModalLogic.test.ts b/frontend/src/scenes/trends/persons-modal/peronsModalLogic.test.tsdeleted file mode 100644index ba343a2ffe02..000000000000--- a/frontend/src/scenes/trends/persons-modal/peronsModalLogic.test.ts+++ /dev/null@@ -1,65 +0,0 @@-import { expectLogic } from 'kea-test-utils'--import { useMocks } from '~/mocks/jest'-import { initKeaTests } from '~/test/init'--import { personsModalLogic } from './personsModalLogic'--describe('personsModalLogic', () => {- let logic: ReturnType<typeof personsModalLogic.build>-- beforeEach(() => {- useMocks({- get: {- 'api/environments/:team_id/persons/trends': {},- },- })- initKeaTests()- })-- afterEach(() => {- logic.unmount()- })-- describe('propertiesTimelineFilterFromUrl selector', () => {- it('extract only the relevant properties from URL', async () => {- logic = personsModalLogic({- url: '/api/projects/1/persons/trends/?breakdown_attribution_type=first_touch&breakdown_normalize_url=False&date_from=2022-12-01T00%3A00%3A00%2B00%3A00&display=ActionsLineGraph&events=%5B%7B%22id%22%3A+%22%24pageview%22%2C+%22type%22%3A+%22events%22%2C+%22order%22%3A+0%2C+%22name%22%3A+%22%24pageview%22%2C+%22custom_name%22%3A+null%2C+%22math%22%3A+null%2C+%22math_property%22%3A+null%2C+%22math_group_type_index%22%3A+null%2C+%22properties%22%3A+%7B%7D%7D%5D&insight=TRENDS&interval=day&properties=%7B%22type%22%3A+%22AND%22%2C+%22values%22%3A+%5B%7B%22key%22%3A+%22id%22%2C+%22type%22%3A+%22precalculated-cohort%22%2C+%22value%22%3A+6%7D%5D%7D&smoothing_intervals=1&entity_id=%24pageview&entity_type=events&date_to=2022-12-13T00%3A00%3A00%2B00%3A00&entity_order=0&include_recordings=true',- })- logic.mount()- await expectLogic(logic).toMatchValues({- propertiesTimelineFilterFromUrl: {- date_from: '2022-12-01T00:00:00+00:00',- date_to: '2022-12-13T00:00:00+00:00',- display: 'ActionsLineGraph',- insight: 'TRENDS',- interval: 'day',- events: [- {- custom_name: null,- id: '$pageview',- math: null,- math_group_type_index: null,-- math_property: null,- name: '$pageview',- order: 0,- properties: {},- type: 'events',- },- ],- properties: {- type: 'AND',- values: [- {- key: 'id',- type: 'precalculated-cohort',- value: 6,- },- ],- },- },- })- })- })-})diff --git a/frontend/src/scenes/trends/persons-modal/personsModalLogic.test.ts b/frontend/src/scenes/trends/persons-modal/personsModalLogic.test.tsindex f767271dfb12..c09636cf8c84 100644--- a/frontend/src/scenes/trends/persons-modal/personsModalLogic.test.ts+++ b/frontend/src/scenes/trends/persons-modal/personsModalLogic.test.ts@@ -4,7 +4,14 @@ import { expectLogic } from 'kea-test-utils'import { urls } from 'scenes/urls'import { useMocks } from '~/mocks/jest'-import { FunnelsActorsQuery, FunnelsQuery, NodeKind } from '~/queries/schema/schema-general'+import {+ DataWarehouseNode,+ FunnelsActorsQuery,+ FunnelsQuery,+ InsightActorsQuery,+ NodeKind,+ TrendsQuery,+} from '~/queries/schema/schema-general'import { initKeaTests } from '~/test/init'import { ActivityTab, FilterLogicalOperator, PersonActorType, PropertyFilterType, PropertyOperator } from '~/types'@@ -689,4 +696,57 @@ describe('personsModalLogic', () => {expect(logic.values.insightEventsQueryUrl).toBeNull()})})++ describe('propertiesTimelineQuery', () => {+ const trendsQuery = (series: TrendsQuery['series']): InsightActorsQuery => ({+ kind: NodeKind.InsightActorsQuery,+ source: { kind: NodeKind.TrendsQuery, series },+ day: '2024-05-01',+ series: 1,+ })++ it.each([+ [+ 'a Trends events series',+ true,+ trendsQuery([+ { kind: NodeKind.DataWarehouseNode } as DataWarehouseNode,+ { kind: NodeKind.EventsNode, event: '$pageview' },+ ]),+ ],+ [+ 'a Trends actions series',+ true,+ trendsQuery([{ kind: NodeKind.EventsNode }, { kind: NodeKind.ActionsNode, id: 1 }]),+ ],+ [+ 'a Trends data warehouse series',+ false,+ trendsQuery([{ kind: NodeKind.EventsNode }, { kind: NodeKind.DataWarehouseNode } as DataWarehouseNode]),+ ],+ [+ 'a Stickiness data point',+ false,+ {+ kind: NodeKind.InsightActorsQuery,+ source: { kind: NodeKind.StickinessQuery, series: [{ kind: NodeKind.EventsNode }] },+ day: 2,+ } as InsightActorsQuery,+ ],+ [+ 'a funnel step',+ false,+ {+ kind: NodeKind.FunnelsActorsQuery,+ source: { kind: NodeKind.FunnelsQuery, series: [] },+ funnelStep: 1,+ } as FunnelsActorsQuery,+ ],+ ])('%s gets a properties timeline: %s', (_name, expectsTimeline, query) => {+ logic = personsModalLogic({ query, url: null })+ logic.mount()++ expect(logic.values.propertiesTimelineQuery).toEqual(expectsTimeline ? query : null)+ })+ })})diff --git a/frontend/src/scenes/trends/persons-modal/personsModalLogic.ts b/frontend/src/scenes/trends/persons-modal/personsModalLogic.tsindex 3e82a5abb880..b4ce895a825d 100644--- a/frontend/src/scenes/trends/persons-modal/personsModalLogic.ts+++ b/frontend/src/scenes/trends/persons-modal/personsModalLogic.ts@@ -18,7 +18,6 @@ import api from 'lib/api'import { eventUsageLogic } from 'lib/utils/eventUsageLogic'import { assignField, isGroupType, isSessionType } from 'lib/utils/guards'import { cohortSavedToast } from 'scenes/cohorts/cohortSavedToast'-import { cleanFilters } from 'scenes/insights/utils/cleanFilters'import { sceneLogic } from 'scenes/sceneLogic'import { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'@@ -44,14 +43,10 @@ import { setLatestVersionsOnQuery } from '~/queries/utils'import {ActivityTab,ActorType,- BreakdownType,- ChartDisplayType,CommonActorType,FilterLogicalOperator,GroupActorType,- IntervalType,PersonActorType,- PropertiesTimelineFilterType,SessionActorType,PropertyFilterType,PropertyOperator,@@ -174,7 +169,7 @@ export interface personsModalLogicValues {isCohortModalOpen: booleanisModalOpen: booleanmissingActorsCount: number- propertiesTimelineFilterFromUrl: PropertiesTimelineFilterType+ propertiesTimelineQuery: InsightActorsQuery | nullquery: FunnelsActorsQuery | InsightActorsQuery | nullrecordingFilters: Partial<RecordingUniversalFilters>searchTerm: string@@ -282,7 +277,6 @@ export interface personsModalLogicMeta {aggregationLabel: (groupTypeIndex: number | null | undefined, deferToUserWording?: boolean) => Noun) => NounvalidationError: (errorObject: Record<string, any> | null) => string | null- propertiesTimelineFilterFromUrl: (arg: any) => PropertiesTimelineFilterTypeselectFields: (arg: any) => string[]actorsQuery: (arg: any,@@ -292,10 +286,12 @@ export interface personsModalLogicMeta {) => ActorsQuery | nullexploreUrl: (actorsQuery: ActorsQuery | null) => string | nullinsightEventsQueryUrl: (actorsQuery: ActorsQuery | null) => string | null+ propertiesTimelineQuery: (+ query: FunnelsActorsQuery | InsightActorsQuery<InsightQueryNode> | null+ ) => InsightActorsQuery | nullsessionIdsFromLoadedActors: (actors: ActorType[]) => string[]recordingFilters: (actorsQuery: ActorsQuery | null,- propertiesTimelineFilterFromUrl: PropertiesTimelineFilterType,sessionIdsFromLoadedActors: string[]) => Partial<RecordingUniversalFilters>}@@ -589,32 +585,6 @@ export const personsModalLogic = kea<personsModalLogicType>([return extractValidationError(errorObject)},],- propertiesTimelineFilterFromUrl: [- () => [(_, p) => p.url],- (url): PropertiesTimelineFilterType => {- // PersonsModal only gets an persons URL and not its underlying filters, so we need to extract those- const params = new URLSearchParams(url.split('?')[1])- const eventsString = params.get('events')- const actionsString = params.get('actions')- const propertiesString = params.get('properties')- const aggregationGroupTypeIndexString = params.get('aggregation_group_type_index')- const filter: PropertiesTimelineFilterType = {- date_from: params.get('date_from') || undefined,- date_to: params.get('date_to') || undefined,- interval: (params.get('interval') || undefined) as IntervalType | undefined,- events: eventsString ? JSON.parse(eventsString) : undefined,- actions: actionsString ? JSON.parse(actionsString) : undefined,- properties: propertiesString ? JSON.parse(propertiesString) : undefined,- aggregation_group_type_index: aggregationGroupTypeIndexString- ? parseInt(aggregationGroupTypeIndexString)- : undefined,- display: (params.get('display') || undefined) as ChartDisplayType | undefined,- breakdown: params.get('breakdown') || undefined,- breakdown_type: (params.get('breakdown_type') || undefined) as BreakdownType | undefined,- }- return cleanFilters(filter)- },- ],selectFields: [() => [(_, p) => p.additionalSelect],(additionalSelect: PersonModalLogicProps['additionalSelect']): string[] => {@@ -710,6 +680,18 @@ export const personsModalLogic = kea<personsModalLogicType>([return combineUrl(urls.activity(ActivityTab.ExploreEvents), {}, { q: query }).url},],+ propertiesTimelineQuery: [+ (s) => [s.query],+ (query: FunnelsActorsQuery | InsightActorsQuery | null): InsightActorsQuery | null => {+ // The backend supports Trends data points of events or actions series. Stickiness, funnel and path+ // data points have no single time window, and a dormant lifecycle actor has no events in its window.+ if (query?.kind !== NodeKind.InsightActorsQuery || query.source.kind !== NodeKind.TrendsQuery) {+ return null+ }+ const series = query.source.series[query.series ?? 0]+ return series?.kind === NodeKind.EventsNode || series?.kind === NodeKind.ActionsNode ? query : null+ },+ ],sessionIdsFromLoadedActors: [(s) => [s.actors],(actors: ActorType[]): string[] => {@@ -728,12 +710,8 @@ export const personsModalLogic = kea<personsModalLogicType>([},],recordingFilters: [- (s) => [s.actorsQuery, s.propertiesTimelineFilterFromUrl, s.sessionIdsFromLoadedActors],- (- actorsQuery: ActorsQuery | null,- propertiesTimelineFilter: PropertiesTimelineFilterType,- sessionIds: string[]- ): Partial<RecordingUniversalFilters> => {+ (s) => [s.actorsQuery, s.sessionIdsFromLoadedActors],+ (actorsQuery: ActorsQuery | null, sessionIds: string[]): Partial<RecordingUniversalFilters> => {if (!actorsQuery || !actorsQuery.source) {return {}}@@ -749,13 +727,13 @@ export const personsModalLogic = kea<personsModalLogicType>([insightQuery = source.source as any}- let date_from = propertiesTimelineFilter?.date_from- let date_to = propertiesTimelineFilter?.date_to+ let date_from: string | undefined+ let date_to: string | undefinedif ('dateRange' in insightQuery && insightQuery.dateRange) {const dateRange = insightQuery.dateRange as any- date_from = dateRange.date_from || date_from- date_to = dateRange.date_to || date_to+ date_from = dateRange.date_from || undefined+ date_to = dateRange.date_to || undefined}// If we have session IDs from matched_recordings, use them directly for efficient lookup@@ -819,17 +797,6 @@ export const personsModalLogic = kea<personsModalLogicType>([})}- // Add breakdown filters if present (trends path)- if ('breakdown' in source && source.breakdown && propertiesTimelineFilter?.breakdown) {- const breakdownFilter = {- key: propertiesTimelineFilter.breakdown,- value: source.breakdown,- operator: PropertyOperator.Exact,- type: PropertyFilterType.Event,- }- filters.push(breakdownFilter as UniversalFilterValue)- }-// Add breakdown filter for funnelsif (funnelBreakdownFilter) {filters.push(funnelBreakdownFilter)diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex 1c56c81de115..c32be4f233ec 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -3295,19 +3295,6 @@ export interface TemplateVariableStep {custom_event?: boolean}-export interface PropertiesTimelineFilterType {- date_from?: string | null // DateMixin- date_to?: string | null // DateMixin- interval?: IntervalType // IntervalMixin- properties?: AnyPropertyFilter[] | PropertyGroupFilter // PropertyMixin- events?: Record<string, any>[] // EntitiesMixin- actions?: Record<string, any>[] // EntitiesMixin- aggregation_group_type_index?: number // GroupsAggregationMixin- display?: ChartDisplayType // DisplayDerivedMixin- breakdown_type?: BreakdownType | null- breakdown?: BreakdownKeyType-}-export interface TrendsFilterType extends FilterType {// Specifies that we want to smooth the aggregation over the specified// number of intervals, e.g. for a day interval, we may want to smooth overdiff --git a/posthog/api/person.py b/posthog/api/person.pyindex 33a14be5fc84..ddc9b572c669 100644--- a/posthog/api/person.py+++ b/posthog/api/person.py@@ -10,6 +10,7 @@ from django.conf import settingsfrom django.db.models import TextChoicesimport structlog+from dateutil.parser import parse as parse_datetimefrom drf_spectacular.types import OpenApiTypesfrom drf_spectacular.utils import (OpenApiExample,@@ -30,9 +31,10 @@ from rest_framework.response import Responsefrom rest_framework.settings import api_settingsfrom rest_framework_csv import renderers as csvrenderers-from posthog.schema import ActorsQuery, ProductKey+from posthog.schema import ActionsNode, ActorsQuery, EventsNode, InsightActorsQuery, ProductKey, TrendsQueryfrom posthog.hogql.constants import CSV_EXPORT_LIMIT+from posthog.hogql.errors import ExposedHogQLErrorfrom posthog.api.capture import CaptureInternalError, capture_internalfrom posthog.api.documentation import PersonPropertiesSerializer@@ -74,6 +76,7 @@ from posthog.models.person.util import (from posthog.personhog_client.caller_tag import personhog_caller_tagfrom posthog.rate_limit import ClickHouseBurstRateThrottle, PersonalApiKeyRateThrottle, UserOrEmailRateThrottlefrom posthog.renderers import SafeJSONRenderer+from posthog.schema_migrations.upgrade import upgradefrom posthog.slo.context import JsonValue, SloSpec, slo_operationfrom posthog.slo.types import SloArea, SloOperationfrom posthog.tasks.delete_persons import queue_person_deletion@@ -515,6 +518,76 @@ class PersonPropertiesAtTimeResponseSerializer(serializers.Serializer):)+def _is_date_string(day: str | int) -> bool:+ if not isinstance(day, str):+ return False+ # The trends actors query parses the day with dateutil, so the same parse checks it here.+ try:+ parse_datetime(day)+ except (ValueError, OverflowError):+ return False+ return True+++@extend_schema_field(InsightActorsQuery) # type: ignore[arg-type] # Supported by the Pydantic schema extension.+class InsightActorsQueryField(serializers.JSONField):+ """Types the field as an `InsightActorsQuery` in the OpenAPI schema. `validate_query` parses it."""+++class PropertiesTimelineRequestSerializer(serializers.Serializer):+ query = InsightActorsQueryField(+ help_text=(+ "The actors query of the insight data point, as the persons modal sends it. The timeline reads the "+ "person's events in the data point's time window, and tracks the person properties that the series, "+ "the insight's filters and its breakdown use. The source must be a Trends query, and the selected "+ "series must be an events or actions series."+ )+ )++ def validate_query(self, value: Any) -> InsightActorsQuery:+ try:+ query = InsightActorsQuery.model_validate(upgrade(value) if isinstance(value, dict) else value)+ except (ValueError, TypeError):+ raise serializers.ValidationError("Provide a valid insight actors query.")+ if not isinstance(query.source, TrendsQuery):+ raise serializers.ValidationError("The properties timeline supports Trends insights only.")+ series_index = query.series or 0+ if not 0 <= series_index < len(query.source.series):+ raise serializers.ValidationError("The query's series index is out of range.")+ if not isinstance(query.source.series[series_index], EventsNode | ActionsNode):+ raise serializers.ValidationError("The properties timeline supports events and actions series only.")+ if query.source.aggregation_group_type_index is not None:+ # The actor is a person, so a group-aggregated source would read the group's properties.+ raise serializers.ValidationError("The properties timeline supports person aggregation only.")+ if query.day is not None and not _is_date_string(query.day):+ raise serializers.ValidationError("A Trends data point's day must be a date string.")+ return query+++class PropertiesTimelinePointSerializer(serializers.Serializer):+ timestamp = serializers.DateTimeField(+ help_text="The time of the first event in the window that has this combination of key property values."+ )+ properties = serializers.DictField(+ child=serializers.JSONField(), help_text="The person's properties as that event recorded them."+ )+ relevant_event_count = serializers.IntegerField(+ help_text="The number of the person's events in the window from this point until the next point."+ )+++class PropertiesTimelineResponseSerializer(serializers.Serializer):+ points = PropertiesTimelinePointSerializer(+ many=True, help_text="One point for each change of the key property values, oldest first."+ )+ crucial_property_keys = serializers.ListField(+ child=serializers.CharField(),+ help_text="The key person properties: those the insight's query uses. Empty when it uses none.",+ )+ effective_date_from = serializers.DateTimeField(help_text="The start of the window, in the project's time zone.")+ effective_date_to = serializers.DateTimeField(help_text="The end of the window, in the project's time zone.")++# Not in `posthog/api/cohort.py` because that module cannot be imported here at module level: it# reaches back into this one through `posthog/hogql_queries/actors_query_runner.py`.class CohortMinimalSerializer(serializers.ModelSerializer):@@ -1636,15 +1709,43 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):)# PRAGMA: Methods for getting Persons via clickhouse queries- @action(methods=["GET"], detail=True)+ @extend_schema(+ methods=["GET"],+ deprecated=True,+ parameters=[_PERSON_ID_PARAMETER],+ responses={200: PropertiesTimelineResponseSerializer},+ summary="Get a person's properties timeline from legacy filter parameters",+ description="Reads a legacy insight filter from the query string. Send a POST with the data point's actors query instead.",+ )+ @extend_schema(+ methods=["POST"],+ parameters=[_PERSON_ID_PARAMETER],+ request=PropertiesTimelineRequestSerializer,+ responses={200: PropertiesTimelineResponseSerializer},+ summary="Get a person's properties timeline for an insight data point",+ description=(+ "Shows how the person's key properties changed within the time window of a Trends data point. The key "+ "properties are the person properties that the insight's query uses."+ ),+ )+ @action(methods=["GET", "POST"], detail=True, required_scopes=["person:read"])def properties_timeline(self, request: request.Request, *args: Any, **kwargs: Any) -> Response:if request.user.is_anonymous or not self.team:return response.Response(data=[])person = self.get_object()- filter = PropertiesTimelineFilter(request=request, team=self.team)+ tag_queries(product=ProductKey.PERSONS, feature=Feature.QUERY)+ if request.method == "GET":+ filter = PropertiesTimelineFilter(request=request, team=self.team)+ return response.Response(data=PropertiesTimeline().run_for_filter(filter, self.team, person))- properties_timeline = PropertiesTimeline().run(filter, self.team, person)+ serializer = PropertiesTimelineRequestSerializer(data=request.data)+ serializer.is_valid(raise_exception=True)+ try:+ properties_timeline = PropertiesTimeline().run(serializer.validated_data["query"], self.team, person)+ except ExposedHogQLError as error:+ # Covers both `QueryError` and the `SyntaxError` a malformed HogQL filter parses into.+ raise ValidationError({"query": [str(error)]})return response.Response(data=properties_timeline)diff --git a/posthog/api/test/test_properties_timeline.py b/posthog/api/test/test_properties_timeline.pyindex bfc760f35662..8d39433beebf 100644--- a/posthog/api/test/test_properties_timeline.py+++ b/posthog/api/test/test_properties_timeline.py@@ -14,10 +14,37 @@ from posthog.test.base import (snapshot_clickhouse_queries,)+from django.test import SimpleTestCase++from parameterized import parameterizedfrom rest_framework import status+from rest_framework.renderers import JSONRenderer++from posthog.schema import (+ Breakdown,+ BreakdownFilter,+ Compare,+ CompareFilter,+ DateRange,+ EventPropertyFilter,+ EventsNode,+ FilterLogicalOperator,+ HogQLPropertyFilter,+ InsightActorsQuery,+ PersonPropertyFilter,+ PropertyGroupFilter,+ PropertyGroupFilterValue,+ PropertyOperator,+ StickinessQuery,+ TrendsQuery,+)++from posthog.hogql.errors import ExposedHogQLError-from posthog.hogql_queries.properties_timeline.properties_timeline import PropertiesTimelineResult+from posthog.api.person import PropertiesTimelineRequestSerializer+from posthog.hogql_queries.properties_timeline.properties_timeline import PropertiesTimeline, PropertiesTimelineResultfrom posthog.models.filters.mixins.base import BreakdownType+from posthog.models.person.util import get_person_by_uuidMATERIALIZED_COLUMN_KWARGS = {"person_properties": ["foo", "bar"]}TEST_PERSON_ID = uuid.UUID("12345678-0000-0000-0000-000000000001")@@ -71,6 +98,172 @@ class TestPersonPropertiesTimeline(ClickhouseTestMixin, APIBaseTest):self.assertEqual(properties_timeline.status_code, expected_status)return properties_timeline.json()+ def _get_query_timeline_result(self, query: InsightActorsQuery) -> PropertiesTimelineResult:+ person = get_person_by_uuid(self.team.pk, str(TEST_PERSON_ID))+ assert person is not None+ # Rendered like the API response, so timestamps compare as the strings clients receive.+ return json.loads(JSONRenderer().render(PropertiesTimeline().run(query, self.team, person)))++ @parameterized.expand(+ [+ (+ "series_filter",+ {+ "series": [+ EventsNode(+ event="$pageview",+ properties=[+ PersonPropertyFilter(key="foo", value="whatever", operator=PropertyOperator.EXACT),+ EventPropertyFilter(key="fin", value="anything", operator=PropertyOperator.EXACT),+ ],+ )+ ]+ },+ ),+ (+ "nested_property_group",+ {+ "properties": PropertyGroupFilter(+ type=FilterLogicalOperator.OR_,+ values=[+ PropertyGroupFilterValue(+ type=FilterLogicalOperator.AND_,+ values=[+ PersonPropertyFilter(key="foo", value="whatever", operator=PropertyOperator.EXACT),+ EventPropertyFilter(key="fin", value="anything", operator=PropertyOperator.EXACT),+ ],+ )+ ],+ )+ },+ ),+ ("hogql_filter", {"properties": [HogQLPropertyFilter(key="person.properties.foo != 'whatever'")]}),+ ("person_breakdown", {"breakdownFilter": BreakdownFilter(breakdown="foo", breakdown_type="person")}),+ (+ "multiple_breakdowns",+ {+ "breakdownFilter": BreakdownFilter(+ breakdowns=[Breakdown(property="$browser"), Breakdown(property="foo", type="person")]+ )+ },+ ),+ ]+ )+ def test_query_timeline_tracks_key_properties_within_clicked_day(self, _name: str, source_fields: dict):+ self._create_person({"foo": "abc", "bar": 123})+ self._create_event(+ event="$pageview", actor_properties={"foo": "abc", "bar": 123}, timestamp="2020-01-01T00:00:00Z"+ )+ self._create_event(+ event="$pageview", actor_properties={"foo": "klm", "bar": 456}, timestamp="2020-01-01T21:37:00Z"+ )+ self._create_event(+ event="$pageview", actor_properties={"foo": "xyz", "bar": 456}, timestamp="2020-01-02T08:00:00Z"+ )+ flush_persons_and_events()++ source = TrendsQuery(+ series=[EventsNode(event="$pageview")],+ dateRange=DateRange(date_from="2020-01-01", date_to="2020-01-05"),+ ).model_copy(update=source_fields)+ timeline = self._get_query_timeline_result(InsightActorsQuery(source=source, day="2020-01-01", series=0))++ self.assertEqual(+ timeline,+ {+ "points": [+ {+ "properties": {"foo": "abc", "bar": 123},+ "relevant_event_count": 1,+ "timestamp": "2020-01-01T00:00:00Z",+ },+ {+ "properties": {"foo": "klm", "bar": 456},+ "relevant_event_count": 1,+ "timestamp": "2020-01-01T21:37:00Z",+ },+ ],+ "crucial_property_keys": ["foo"],+ "effective_date_from": "2020-01-01T00:00:00+00:00",+ "effective_date_to": "2020-01-02T00:00:00+00:00",+ },+ )++ @parameterized.expand(+ [+ (Compare.CURRENT, "2020-01-10", "2020-01-11", {"foo": "abc", "bar": 789}),+ (Compare.PREVIOUS, "2020-01-03", "2020-01-04", {"foo": "abc", "bar": 456}),+ ]+ )+ def test_query_timeline_uses_clicked_day_of_compared_period(+ self, compare: Compare, expected_day: str, expected_next_day: str, expected_properties: dict+ ):+ self._create_person({"foo": "abc", "bar": 123})+ self._create_event(+ event="$pageview", actor_properties={"foo": "abc", "bar": 456}, timestamp="2020-01-03T10:00:00Z"+ )+ self._create_event(+ event="$pageview", actor_properties={"foo": "abc", "bar": 789}, timestamp="2020-01-10T10:00:00Z"+ )+ flush_persons_and_events()++ source = TrendsQuery(+ series=[EventsNode(event="$pageview")],+ properties=[PersonPropertyFilter(key="bar", value="xyz", operator=PropertyOperator.EXACT)],+ dateRange=DateRange(date_from="2020-01-08", date_to="2020-01-14"),+ compareFilter=CompareFilter(compare=True),+ )+ timeline = self._get_query_timeline_result(InsightActorsQuery(source=source, day="2020-01-10", compare=compare))++ self.assertEqual(+ timeline,+ {+ "points": [+ {+ "properties": expected_properties,+ "relevant_event_count": 1,+ "timestamp": f"{expected_day}T10:00:00Z",+ }+ ],+ "crucial_property_keys": ["bar"],+ "effective_date_from": f"{expected_day}T00:00:00+00:00",+ "effective_date_to": f"{expected_next_day}T00:00:00+00:00",+ },+ )++ def test_query_timeline_rejects_invalid_query(self):+ self._create_person({"foo": "abc"})+ flush_persons_and_events()++ response = self.client.post(+ f"/api/projects/{self.team.id}/persons/{TEST_PERSON_ID}/properties_timeline/",+ {"query": {"kind": "InsightActorsQuery"}},+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertEqual(response.json()["attr"], "query")++ def test_query_timeline_raises_an_exposed_error_for_a_malformed_hogql_filter(self):+ # Key extraction parses the filter, raising a hogql `SyntaxError` — a sibling of `QueryError`, not a+ # subclass. The endpoint turns any `ExposedHogQLError` into a 400, so this is what keeps it off a 500.+ self._create_person({"foo": "abc"})+ flush_persons_and_events()+ person = get_person_by_uuid(self.team.pk, str(TEST_PERSON_ID))+ assert person is not None++ query = InsightActorsQuery(+ source=TrendsQuery(+ series=[EventsNode(event="$pageview")],+ properties=[HogQLPropertyFilter(key="person.properties.foo !!")],+ ),+ day="2020-01-01",+ series=0,+ )++ with self.assertRaises(ExposedHogQLError):+ PropertiesTimeline().run(query, self.team, person)+@also_test_with_materialized_columns(**MATERIALIZED_COLUMN_KWARGS)@snapshot_clickhouse_queriesdef test_timeline_for_new_actor_with_one_event_in_range(self):@@ -778,3 +971,42 @@ class TestPersonPropertiesTimeline(ClickhouseTestMixin, APIBaseTest):"effective_date_to": "2020-01-05T23:59:59.999999+00:00",},)+++class TestPropertiesTimelineRequestSerializer(SimpleTestCase):+ @parameterized.expand(+ [+ (+ "stickiness_source",+ InsightActorsQuery(source=StickinessQuery(series=[EventsNode(event="$pageview")]), day=3).model_dump(+ mode="json"+ ),+ "The properties timeline supports Trends insights only.",+ ),+ (+ "unparseable_day",+ InsightActorsQuery(+ source=TrendsQuery(series=[EventsNode(event="$pageview")]), day="not-a-date"+ ).model_dump(mode="json"),+ "A Trends data point's day must be a date string.",+ ),+ (+ "group_aggregated_source",+ InsightActorsQuery(+ source=TrendsQuery(series=[EventsNode(event="$pageview")], aggregation_group_type_index=0),+ day="2020-01-01",+ ).model_dump(mode="json"),+ "The properties timeline supports person aggregation only.",+ ),+ (+ "non_integer_source_version",+ {"kind": "InsightActorsQuery", "source": {"kind": "TrendsQuery", "version": "x", "series": []}},+ "Provide a valid insight actors query.",+ ),+ ]+ )+ def test_rejects_query_the_timeline_cannot_window(self, _name: str, query: dict, error: str):+ serializer = PropertiesTimelineRequestSerializer(data={"query": query})++ assert not serializer.is_valid()+ assert serializer.errors["query"] == [error]diff --git a/posthog/hogql_queries/properties_timeline/properties_timeline.py b/posthog/hogql_queries/properties_timeline/properties_timeline.pyindex 178ae27d5413..9a7f3e3b40ac 100644--- a/posthog/hogql_queries/properties_timeline/properties_timeline.py+++ b/posthog/hogql_queries/properties_timeline/properties_timeline.py@@ -6,7 +6,20 @@ from zoneinfo import ZoneInfofrom dateutil.relativedelta import relativedelta-from posthog.schema import HogQLQueryModifiers, PersonsOnEventsMode+from posthog.schema import (+ ActionsNode,+ BreakdownFilter,+ EventsNode,+ GroupPropertyFilter,+ HogQLPropertyFilter,+ HogQLQueryModifiers,+ InsightActorsQuery,+ PersonPropertyFilter,+ PersonsOnEventsMode,+ PropertyGroupFilter,+ PropertyGroupFilterValue,+ TrendsQuery,+)from posthog.hogql import astfrom posthog.hogql.parser import parse_select@@ -14,15 +27,17 @@ from posthog.hogql.property import action_to_exprfrom posthog.hogql.query import execute_hogql_queryfrom posthog.constants import NON_TIME_SERIES_DISPLAY_TYPES, TREND_FILTER_TYPE_ACTIONS+from posthog.dataclasses import frozenfrom posthog.hogql_queries.properties_timeline.query_date_range import QueryDateRangefrom posthog.models.entity import Entityfrom posthog.models.filters.properties_timeline_filter import PropertiesTimelineFilterfrom posthog.models.group.group import Groupfrom posthog.models.person.person import Person-from posthog.models.property.util import extract_tables_and_properties+from posthog.models.property.util import count_hogql_properties, extract_tables_and_propertiesfrom posthog.models.team.team import Teamfrom products.actions.backend.models.action import Action+from products.product_analytics.backend.facade import queries as product_analytics_queriesdef offset_time_series_date_by_interval(@@ -44,6 +59,91 @@ def offset_time_series_date_by_interval(return date+@frozen+class _TimelineScope:+ """The actor's events that the timeline reads, and the properties whose changes it tracks."""++ entity_exprs: tuple[ast.Expr, ...]+ crucial_property_keys: tuple[str, ...]+ aggregation_group_type_index: int | None+ date_from: datetime.datetime+ date_to: datetime.datetime+ date_to_inclusive: bool+++def _crucial_keys_in_hogql(expression: str, aggregation_group_type_index: int | None) -> set[str]:+ if aggregation_group_type_index is not None:+ return set()+ return {key for key, property_type, _ in count_hogql_properties(expression) if property_type == "person"}+++def _crucial_keys_in_properties(properties: object, aggregation_group_type_index: int | None) -> set[str]:+ """Keys of the aggregated actor's properties that a property filter list or group uses."""+ match properties:+ case list():+ return set().union(+ *(_crucial_keys_in_properties(item, aggregation_group_type_index) for item in properties)+ )+ case PropertyGroupFilter() | PropertyGroupFilterValue():+ return _crucial_keys_in_properties(properties.values, aggregation_group_type_index)+ case PersonPropertyFilter(key=key) if aggregation_group_type_index is None:+ return {key}+ case GroupPropertyFilter(key=key, group_type_index=group_type_index) if (+ group_type_index is not None and group_type_index == aggregation_group_type_index+ ):+ return {key}+ case HogQLPropertyFilter(key=expression):+ return _crucial_keys_in_hogql(expression, aggregation_group_type_index)+ case _:+ return set()+++def _crucial_keys_in_breakdown(+ breakdown_type: str | None,+ breakdown_properties: list[str | int],+ breakdown_group_type_index: int | None,+ aggregation_group_type_index: int | None,+) -> set[str]:+ if breakdown_type == "person" and aggregation_group_type_index is None:+ return {str(breakdown_property) for breakdown_property in breakdown_properties}+ if (+ breakdown_type == "group"+ and breakdown_group_type_index is not None+ and breakdown_group_type_index == aggregation_group_type_index+ ):+ return {str(breakdown_property) for breakdown_property in breakdown_properties}+ if breakdown_type == "hogql":+ return set().union(+ *(+ _crucial_keys_in_hogql(str(expression), aggregation_group_type_index)+ for expression in breakdown_properties+ )+ )+ return set()+++def _crucial_keys_in_breakdown_filter(+ breakdown_filter: BreakdownFilter | None, aggregation_group_type_index: int | None+) -> set[str]:+ if breakdown_filter is None:+ return set()+ keys: set[str] = set()+ if breakdown_filter.breakdown is not None:+ keys |= _crucial_keys_in_breakdown(+ breakdown_filter.breakdown_type,+ breakdown_filter.breakdown+ if isinstance(breakdown_filter.breakdown, list)+ else [breakdown_filter.breakdown],+ breakdown_filter.breakdown_group_type_index,+ aggregation_group_type_index,+ )+ for breakdown in breakdown_filter.breakdowns or []:+ keys |= _crucial_keys_in_breakdown(+ breakdown.type, [breakdown.property], breakdown.group_type_index, aggregation_group_type_index+ )+ return keys++class PropertiesTimelinePoint(TypedDict):timestamp: strproperties: dict[str, Any]@@ -122,12 +222,12 @@ class PropertiesTimeline:return crucial_property_keys- def _actor_properties_chain(self, filter: PropertiesTimelineFilter) -> list[Union[str, int]]:+ def _actor_properties_chain(self, aggregation_group_type_index: int | None) -> list[Union[str, int]]:# Read the actor's properties as frozen on the event (persons-on-events columns), so the# timeline reflects the values at the time of each event rather than current values.- if filter.aggregation_group_type_index is None:+ if aggregation_group_type_index is None:return ["poe", "properties"]- return [f"goe_{filter.aggregation_group_type_index}", "properties"]+ return [f"goe_{aggregation_group_type_index}", "properties"]def _entity_expr(self, entity: Entity, team: Team) -> ast.Expr:# Only the entity's event/action identity filters the timeline events — the entity's ad-hoc@@ -142,9 +242,21 @@ class PropertiesTimeline:right=ast.Constant(value=entity.id),)- def run(- self, filter: PropertiesTimelineFilter, team: Team, actor: Union[Person, Group]- ) -> PropertiesTimelineResult:+ def _series_expr(self, series: EventsNode | ActionsNode, team: Team) -> ast.Expr | None:+ # Like `_entity_expr`, only the series' event or action selects events. Its property filters+ # name key properties, and filtering on them would hide the changes the timeline shows.+ if isinstance(series, ActionsNode):+ action = Action.objects.filter(pk=series.id, team__project_id=team.project_id).first()+ return action_to_expr(action) if action is not None else ast.Constant(value=False)+ if series.event is None:+ return None+ return ast.CompareOperation(+ op=ast.CompareOperationOp.Eq,+ left=ast.Field(chain=["event"]),+ right=ast.Constant(value=series.event),+ )++ def _scope_from_filter(self, filter: PropertiesTimelineFilter, team: Team) -> _TimelineScope:if filter._date_from is not None and filter._date_to is not None and filter._date_from == filter._date_to:# A single-point range is widened by one interval so the window actually spans some events.filter = filter.shallow_clone(@@ -158,20 +270,63 @@ class PropertiesTimeline:)query_date_range = QueryDateRange(filter, team)- effective_date_from = query_date_range.date_from_param.replace(tzinfo=team.timezone_info)- effective_date_to = query_date_range.date_to_param.replace(tzinfo=team.timezone_info)+ return _TimelineScope(+ entity_exprs=tuple(self._entity_expr(entity, team) for entity in filter.entities),+ crucial_property_keys=tuple(sorted(self.extract_crucial_property_keys(filter, team_id=team.pk))),+ aggregation_group_type_index=filter.aggregation_group_type_index,+ date_from=query_date_range.date_from_param.replace(tzinfo=team.timezone_info),+ date_to=query_date_range.date_to_param.replace(tzinfo=team.timezone_info),+ date_to_inclusive=True,+ )- crucial_property_keys = sorted(self.extract_crucial_property_keys(filter, team_id=team.pk))- actor_properties_chain = self._actor_properties_chain(filter)+ def _scope_from_query(self, query: InsightActorsQuery, team: Team) -> _TimelineScope:+ source = query.source+ if not isinstance(source, TrendsQuery):+ raise ValueError(f"The properties timeline does not support {source.kind} insights")+ series = source.series[query.series or 0]+ if not isinstance(series, EventsNode | ActionsNode):+ raise ValueError(f"The properties timeline does not support {series.kind} series")++ aggregation_group_type_index = source.aggregation_group_type_index+ crucial_property_keys = (+ _crucial_keys_in_properties(series.properties, aggregation_group_type_index)+ | _crucial_keys_in_properties(source.properties, aggregation_group_type_index)+ | _crucial_keys_in_breakdown_filter(source.breakdownFilter, aggregation_group_type_index)+ )+ # The facade imports the trends runner on first attribute access, which keeps it off the startup import path.+ window = product_analytics_queries.trends_actors_date_window(team=team, query=query)+ series_expr = self._series_expr(series, team)+ return _TimelineScope(+ entity_exprs=(series_expr,) if series_expr is not None else (),+ crucial_property_keys=tuple(sorted(crucial_property_keys)),+ aggregation_group_type_index=aggregation_group_type_index,+ date_from=window.date_from.astimezone(team.timezone_info),+ date_to=window.date_to.astimezone(team.timezone_info),+ date_to_inclusive=window.date_to_inclusive,+ )++ def run(self, query: InsightActorsQuery, team: Team, actor: Union[Person, Group]) -> PropertiesTimelineResult:+ """The actor's key property values over the window of the Trends data point that `query` selects."""+ return self._run(self._scope_from_query(query, team), team, actor)++ def run_for_filter(+ self, filter: PropertiesTimelineFilter, team: Team, actor: Union[Person, Group]+ ) -> PropertiesTimelineResult:+ return self._run(self._scope_from_filter(filter, team), team, actor)++ def _run(self, scope: _TimelineScope, team: Team, actor: Union[Person, Group]) -> PropertiesTimelineResult:+ actor_properties_chain = self._actor_properties_chain(scope.aggregation_group_type_index)# Serialize the crucial property values to a single string for change detection. A tuple would# break `lagInFrame`, whose out-of-frame default is an empty tuple that ClickHouse refuses to# compare against a sized tuple.crucial_properties: ast.Expr- if crucial_property_keys:+ if scope.crucial_property_keys:crucial_properties = ast.Call(name="toString",args=[- ast.Tuple(exprs=[ast.Field(chain=[*actor_properties_chain, key]) for key in crucial_property_keys])+ ast.Tuple(+ exprs=[ast.Field(chain=[*actor_properties_chain, key]) for key in scope.crucial_property_keys]+ )],)else:@@ -186,17 +341,18 @@ class PropertiesTimeline:ast.CompareOperation(op=ast.CompareOperationOp.GtEq,left=ast.Field(chain=["timestamp"]),- right=ast.Constant(value=effective_date_from),+ right=ast.Constant(value=scope.date_from),),ast.CompareOperation(- op=ast.CompareOperationOp.LtEq,+ op=ast.CompareOperationOp.LtEq if scope.date_to_inclusive else ast.CompareOperationOp.Lt,left=ast.Field(chain=["timestamp"]),- right=ast.Constant(value=effective_date_to),+ right=ast.Constant(value=scope.date_to),),]- entity_exprs = [self._entity_expr(entity, team) for entity in filter.entities]- if entity_exprs:- where_exprs.append(ast.Or(exprs=entity_exprs) if len(entity_exprs) > 1 else entity_exprs[0])+ if scope.entity_exprs:+ where_exprs.append(+ ast.Or(exprs=list(scope.entity_exprs)) if len(scope.entity_exprs) > 1 else scope.entity_exprs[0]+ )query = parse_select(PROPERTIES_TIMELINE_HOGQL,@@ -226,7 +382,7 @@ class PropertiesTimeline:)for timestamp, properties, relevant_event_count in response.results],- crucial_property_keys=crucial_property_keys,- effective_date_from=effective_date_from.isoformat(),- effective_date_to=effective_date_to.isoformat(),+ crucial_property_keys=list(scope.crucial_property_keys),+ effective_date_from=scope.date_from.isoformat(),+ effective_date_to=scope.date_to.isoformat(),)diff --git a/posthog/middleware.py b/posthog/middleware.pyindex 47e8ffb8e9df..348333e39596 100644--- a/posthog/middleware.py+++ b/posthog/middleware.py@@ -1544,6 +1544,14 @@ READ_ONLY_IMPERSONATION_ALLOWLISTED_PATHS: list[tuple[str, str | re.Pattern]] =("POST", re.compile(r"^/api/(environments|projects)/([0-9]+|@current)/endpoints/[^/]+/materialization_preview/?$")),("POST", re.compile(r"^/api/(environments|projects)/([0-9]+|@current)/endpoints/last_execution_times/?$")),("POST", re.compile(r"^/api/(environments|projects)/([0-9]+|@current)/persons/batch_by_distinct_ids/?$")),+ # POST but read-only: reads how the person's key properties changed within an insight data point's+ # time window. It takes the data point's actors query as the body, which is why it is not a GET. The+ # action is named exactly, because the same detail prefix hosts the mutating person actions+ # (delete_property, update_property, split).+ (+ "POST",+ re.compile(r"^/api/(environments|projects)/([0-9]+|@current)/persons/[^/]+/properties_timeline/?$"),+ ),# POST but read-only: loads stack frame records (source context) for error tracking UI("POST", re.compile(r"^/api/(environments|projects)/([0-9]+|@current)/error_tracking/stack_frames/batch_get/?$")),# POST but read-only: returns metadata about available incremental fields / columnsdiff --git a/posthog/test/test_middleware.py b/posthog/test/test_middleware.pyindex 4b9b9e6dcde1..9ac1aeff7e9f 100644--- a/posthog/test/test_middleware.py+++ b/posthog/test/test_middleware.py@@ -1188,6 +1188,11 @@ class TestImpersonationReadOnlyMiddleware(APIBaseTest):("tracing_trace_by_id", "tracing/spans/trace/zzz/", {}),("metrics_query", "metrics/query/", {}),("experiments_setup_context", "experiments/setup_context/", {}),+ (+ "persons_properties_timeline",+ "persons/00000000-0000-0000-0000-000000000000/properties_timeline/",+ {},+ ),])def test_read_only_impersonation_allows_allowlisted_post(self, _name, path_suffix, body):diff --git a/products/persons/frontend/generated/api.schemas.ts b/products/persons/frontend/generated/api.schemas.tsindex b65d9c0fdf72..bfb87ed27258 100644--- a/products/persons/frontend/generated/api.schemas.ts+++ b/products/persons/frontend/generated/api.schemas.ts@@ -311,6 +311,3598 @@ export interface MessageAssetApi {sent_at: string}+export type CompareApi = (typeof CompareApi)[keyof typeof CompareApi]++export const CompareApi = {+ Current: 'current',+ Previous: 'previous',+} as const++export type BounceRatePageViewModeApi = (typeof BounceRatePageViewModeApi)[keyof typeof BounceRatePageViewModeApi]++export const BounceRatePageViewModeApi = {+ CountPageviews: 'count_pageviews',+ UniqUrls: 'uniq_urls',+ UniqPageScreenAutocaptures: 'uniq_page_screen_autocaptures',+} as const++export type FilterLogicalOperatorApi = (typeof FilterLogicalOperatorApi)[keyof typeof FilterLogicalOperatorApi]++export const FilterLogicalOperatorApi = {+ And: 'AND',+ Or: 'OR',+} as const++export type CustomBotFieldApi = (typeof CustomBotFieldApi)[keyof typeof CustomBotFieldApi]++export const CustomBotFieldApi = {+ RawUserAgent: '$raw_user_agent',+ Ip: '$ip',+ Lib: '$lib',+ Host: '$host',+ Pathname: '$pathname',+ CurrentUrl: '$current_url',+ Browser: '$browser',+ Os: '$os',+ BrowserLanguage: '$browser_language',+ ScreenWidth: '$screen_width',+ ScreenHeight: '$screen_height',+ GeoipCountryCode: '$geoip_country_code',+ Referrer: '$referrer',+ ReferringDomain: '$referring_domain',+} as const++export type CustomBotMatcherApi = (typeof CustomBotMatcherApi)[keyof typeof CustomBotMatcherApi]++export const CustomBotMatcherApi = {+ Contains: 'contains',+ Regex: 'regex',+ Exact: 'exact',+ Cidr: 'cidr',+} as const++export interface CustomBotConditionApi {+ id: string+ /** The event property this condition reads. */+ key: CustomBotFieldApi+ matcher: CustomBotMatcherApi+ /** Matched against the property named by `key`. */+ pattern: string+}++export interface CustomBotRuleApi {+ /** Reported by `$virt_traffic_category`. Defaults to `custom`. */+ category?: string | null+ /** Whether every condition must match (AND) or any one of them (OR). */+ combiner: FilterLogicalOperatorApi+ id: string+ items: CustomBotConditionApi[]+ /** Reported by `$virt_bot_name` and `$virt_bot_operator` when the rule matches. */+ name: string+}++export type CustomChannelFieldApi = (typeof CustomChannelFieldApi)[keyof typeof CustomChannelFieldApi]++export const CustomChannelFieldApi = {+ UtmSource: 'utm_source',+ UtmMedium: 'utm_medium',+ UtmCampaign: 'utm_campaign',+ ReferringDomain: 'referring_domain',+ Url: 'url',+ Pathname: 'pathname',+ Hostname: 'hostname',+} as const++export type CustomChannelOperatorApi = (typeof CustomChannelOperatorApi)[keyof typeof CustomChannelOperatorApi]++export const CustomChannelOperatorApi = {+ Exact: 'exact',+ IsNot: 'is_not',+ IsSet: 'is_set',+ IsNotSet: 'is_not_set',+ Icontains: 'icontains',+ NotIcontains: 'not_icontains',+ Regex: 'regex',+ NotRegex: 'not_regex',+} as const++export interface CustomChannelConditionApi {+ id: string+ key: CustomChannelFieldApi+ op: CustomChannelOperatorApi+ value?: string | string[] | null+}++export interface CustomChannelRuleApi {+ channel_type: string+ combiner: FilterLogicalOperatorApi+ id: string+ items: CustomChannelConditionApi[]+}++export interface DataWarehouseEventsModifierApi {+ distinct_id_field: string+ id_field: string+ table_name: string+ timestamp_field: string+}++export type InCohortViaApi = (typeof InCohortViaApi)[keyof typeof InCohortViaApi]++export const InCohortViaApi = {+ Auto: 'auto',+ Leftjoin: 'leftjoin',+ Subquery: 'subquery',+ LeftjoinConjoined: 'leftjoin_conjoined',+} as const++export type InlineCohortCalculationApi = (typeof InlineCohortCalculationApi)[keyof typeof InlineCohortCalculationApi]++export const InlineCohortCalculationApi = {+ Off: 'off',+ Auto: 'auto',+ Always: 'always',+} as const++export type MaterializationModeApi = (typeof MaterializationModeApi)[keyof typeof MaterializationModeApi]++export const MaterializationModeApi = {+ Auto: 'auto',+ LegacyNullAsString: 'legacy_null_as_string',+ LegacyNullAsNull: 'legacy_null_as_null',+ Disabled: 'disabled',+} as const++export type MaterializedColumnsOptimizationModeApi =+ (typeof MaterializedColumnsOptimizationModeApi)[keyof typeof MaterializedColumnsOptimizationModeApi]++export const MaterializedColumnsOptimizationModeApi = {+ Disabled: 'disabled',+ Optimized: 'optimized',+} as const++export type ParserModeApi = (typeof ParserModeApi)[keyof typeof ParserModeApi]++export const ParserModeApi = {+ CppOnly: 'cpp_only',+ CppWithRustShadow: 'cpp_with_rust_shadow',+ CppWithRustPyShadow: 'cpp_with_rust_py_shadow',+ RustWithCppShadow: 'rust_with_cpp_shadow',+ RustOnly: 'rust_only',+ RustPyOnly: 'rust_py_only',+ RustPyWithCppShadow: 'rust_py_with_cpp_shadow',+} as const++export type PersonsArgMaxVersionApi = (typeof PersonsArgMaxVersionApi)[keyof typeof PersonsArgMaxVersionApi]++export const PersonsArgMaxVersionApi = {+ Auto: 'auto',+ V1: 'v1',+ V2: 'v2',+} as const++export type PersonsJoinModeApi = (typeof PersonsJoinModeApi)[keyof typeof PersonsJoinModeApi]++export const PersonsJoinModeApi = {+ Inner: 'inner',+ Left: 'left',+} as const++export type PersonsOnEventsModeApi = (typeof PersonsOnEventsModeApi)[keyof typeof PersonsOnEventsModeApi]++export const PersonsOnEventsModeApi = {+ Disabled: 'disabled',+ PersonIdNoOverridePropertiesOnEvents: 'person_id_no_override_properties_on_events',+ PersonIdOverridePropertiesOnEvents: 'person_id_override_properties_on_events',+ PersonIdOverridePropertiesJoined: 'person_id_override_properties_joined',+} as const++export type PropertyGroupsModeApi = (typeof PropertyGroupsModeApi)[keyof typeof PropertyGroupsModeApi]++export const PropertyGroupsModeApi = {+ Enabled: 'enabled',+ Disabled: 'disabled',+ Optimized: 'optimized',+} as const++export type SessionTableVersionApi = (typeof SessionTableVersionApi)[keyof typeof SessionTableVersionApi]++export const SessionTableVersionApi = {+ Auto: 'auto',+ V1: 'v1',+ V2: 'v2',+ V3: 'v3',+} as const++export type SessionsV2JoinModeApi = (typeof SessionsV2JoinModeApi)[keyof typeof SessionsV2JoinModeApi]++export const SessionsV2JoinModeApi = {+ String: 'string',+ Uuid: 'uuid',+} as const++export interface HogQLQueryModifiersApi {+ bounceRateDurationSeconds?: number | null+ bounceRatePageViewMode?: BounceRatePageViewModeApi | null+ convertToProjectTimezone?: boolean | null+ /** Do not treat a missing user agent as automation on cookieless events. Positive bot signals and custom project rules still apply. Resolved server-side; not intended to be set by clients. */+ cookielessTrafficIsRegular?: boolean | null+ customBotDefinitions?: CustomBotRuleApi[] | null+ customChannelTypeRules?: CustomChannelRuleApi[] | null+ dataWarehouseEventsModifiers?: DataWarehouseEventsModifierApi[] | null+ debug?: boolean | null+ /** If these are provided, the query will fail if these skip indexes are not used */+ forceClickhouseDataSkippingIndexes?: string[] | null+ formatCsvAllowDoubleQuotes?: boolean | null+ inCohortVia?: InCohortViaApi | null+ inlineCohortCalculation?: InlineCohortCalculationApi | null+ materializationMode?: MaterializationModeApi | null+ materializedColumnsOptimizationMode?: MaterializedColumnsOptimizationModeApi | null+ /** Merge sibling aggregating LEFT JOINs over federated Postgres tables into one UNION ALL join, so their scans overlap */+ mergeFederatedAggregateJoins?: boolean | null+ /** Replace negated person-property filters in the WHERE of an `events` query (such as `email not_icontains`) with `person_id NOT IN (SELECT id FROM persons WHERE <the filters fail>)`, so the query no longer joins every person. Applies only when every filtered person property has a materialized column, nothing else in the query reads that persons join, and the join would be a LEFT JOIN. */+ negatedPersonFiltersNotIn?: boolean | null+ optimizeJoinedFilters?: boolean | null+ optimizeProjections?: boolean | null+ /** HogQL parser backend; absent → `rust_py_with_cpp_shadow` (rust-py is primary, cpp runs as a sampled shadow). `*_shadow` modes return the primary result and sample-compare against the other parser, reporting divergences without failing the request. The `rust_py_*` modes drive the same hand-rolled Rust parser as `rust_*` but build `posthog.hogql.ast` dataclass instances directly via PyO3, skipping the JSON round-trip. */+ parserMode?: ParserModeApi | null+ /** Push an `id IN (SELECT person_id FROM <left table> WHERE …)` predicate into the joined persons subquery, so the latest-version lookup only reads persons that the outer query's left-table filters can reach. Applies only to a persons join from the query's own FROM table. */+ personIdPushdown?: boolean | null+ personsArgMaxVersion?: PersonsArgMaxVersionApi | null+ personsJoinMode?: PersonsJoinModeApi | null+ personsOnEventsMode?: PersonsOnEventsModeApi | null+ propertyGroupsMode?: PropertyGroupsModeApi | null+ pushDownPredicates?: boolean | null+ s3TableUseInvalidColumns?: boolean | null+ /** Push a `session_id_v7 IN (SELECT … FROM events WHERE …)` predicate into the raw_sessions subquery to limit aggregation to sessions that participate in the outer events filter. */+ sessionIdPushdown?: boolean | null+ /** Pre-filter raw_sessions aggregation by `session_id_v7 IN (cheap pre-aggregation that only materializes the columns referenced by the outer-WHERE session predicate)`. Useful when the breakdown/SELECT pulls in many session columns (e.g. `$channel_type`) but the filter only references one (e.g. `$entry_current_url`). */+ sessionPropertyPreAggregation?: boolean | null+ sessionTableVersion?: SessionTableVersionApi | null+ /** Padding, in minutes, on each side of the event time range when it filters the sessions table by session start. Defaults to 3 days. It can only narrow the range: values above the default are ignored. Lower it only for a query that keeps just the sessions that start inside its own time range. */+ sessionTimestampBufferMinutes?: number | null+ sessionsV2JoinMode?: SessionsV2JoinModeApi | null+ timings?: boolean | null+ /** Remove provably redundant casts and nullability wrappers (e.g. `toString(String)`, `assumeNotNull(non_nullable)`, dead `ifNull` fallbacks) using inferred expression types */+ typeAwareCastSimplification?: boolean | null+ useMaterializedViews?: boolean | null+ /** Read this query from the native events cluster and native JSON events table (`true`), or keep its existing connection (`false` or unset). This is an internal rollout switch for eligible projects. PostHog staff manage eligibility through instance settings. Each query must opt in; project defaults cannot enable it. Only synchronous HogQLQuery SQL comparisons are supported. */+ useNewEventsCluster?: boolean | null+ /** Read events from the native JSON events table (`true`) or the legacy events table (`false`). When unset, the project's stored value applies, then the `CLICKHOUSE_HOGQL_USE_NEW_EVENTS_SCHEMA` instance settings. This is an internal rollout switch. PostHog staff set the project value in Django admin and the project settings API ignores it. */+ useNewEventsSchema?: boolean | null+ usePreaggregatedIntermediateResults?: boolean | null+ /** Try to automatically convert HogQL queries to use preaggregated tables at the AST level * */+ usePreaggregatedTableTransforms?: boolean | null+ useWebAnalyticsPreAggregatedTables?: boolean | null+ /** Serve filters on the stored session-entry attribution properties (`$channel_type`, `$entry_utm_*`, `$entry_referring_domain`) by recomputing the value from the session's first pageview. Resolved server-side; not intended to be set by clients. */+ webAnalyticsFirstPageviewFilters?: boolean | null+}++export interface ClickhouseQueryProgressApi {+ active_cpu_time: number+ bytes_read: number+ estimated_rows_total: number+ rows_read: number+ time_elapsed: number+}++export type QueryScanFixLocationApi = (typeof QueryScanFixLocationApi)[keyof typeof QueryScanFixLocationApi]++export const QueryScanFixLocationApi = {+ Query: 'query',+ Subquery: 'subquery',+ View: 'view',+ InsightDateRange: 'insight_date_range',+ DashboardDateFilter: 'dashboard_date_filter',+} as const++export type QueryScanFindingKindApi = (typeof QueryScanFindingKindApi)[keyof typeof QueryScanFindingKindApi]++export const QueryScanFindingKindApi = {+ NoEventFilter: 'no_event_filter',+ NoStartDate: 'no_start_date',+ PersonsJoin: 'persons_join',+} as const++export interface QueryScanWarningApi {+ /** Whether the person can change the query so it reads less and still answers the same question. Surfaces show the full advice and "Fix with AI" only when a finding is actionable. */+ actionable: boolean+ /** True when the query reads this much on purpose, so reading less would change the answer. Absent means no. */+ by_design?: boolean | null+ /** A label for what in the query text kept the read wide, such as `in_or`. Only analytics and the assistant read it, and the labels can change. */+ cause?: string | null+ /** The one fact the finding rests on. */+ evidence?: string | null+ /** What "Fix with AI" and the assistant are told to do. */+ fix: string+ /** Where the change goes. Absent means the query itself. */+ fix_location?: QueryScanFixLocationApi | null+ kind: QueryScanFindingKindApi+ /** Shown to the person: what happened and what to do. */+ message: string+}++export interface QueryScanAnalysisApi {+ /** The message the Fix with AI button sends to the assistant. Absent when no finding can be fixed in the query. */+ assistant_prompt?: string | null+ /** Every finding, fixable or not. Empty when the analysis found none. */+ findings: QueryScanWarningApi[]+ /** How much of all the project's events the query read, 0 to 1. */+ project_share?: number | null+ /** How much of the project's events in the query's date range the query read, 0 to 1. */+ range_share?: number | null+}++export interface QueryScanSummaryApi {+ /** The stored analysis, put on the response when it is served. Absent while the analysis runs, and when none was requested. */+ analysis?: QueryScanAnalysisApi | null+ /** True when the run asked for an analysis, or found one stored. While `analysis` is absent, poll `GET /query/scan/{cache_key}` for it. */+ analysis_requested?: boolean | null+ /** ClickHouse time for the last fresh run, summed over its ClickHouse queries. */+ duration_ms: number+ /** True when ClickHouse stopped the run instead of finishing it. */+ killed?: boolean | null+ /** Rows ClickHouse read for the last fresh run, all tables included. */+ rows_read: number+}++export interface QueryStatusApi {+ budget_remaining_bytes?: number | null+ bytes_read?: number | null+ /** Cache key of the run that failed, so clients can ask for its query scan. */+ cache_key?: string | null+ /** Whether the query is still running. Will be true if the query is complete, even if it errored. Either result or error will be set. */+ complete?: boolean | null+ dashboard_id?: number | null+ /** When did the query execution task finish (whether successfully or not). */+ end_time?: string | null+ /** If the query failed, this will be set to true. More information can be found in the error_message field. */+ error?: boolean | null+ /** Stable machine-readable code for the error, when known: the DRF exception code, the ClickHouse error name, the HogQL error code, or `unhandled_<exception class>` for a failure that no handler classified. */+ error_code?: string | null+ error_message?: string | null+ expiration_time?: string | null+ id: string+ insight_id?: number | null+ labels?: string[] | null+ /** When was the query execution task picked up by a worker. */+ pickup_time?: string | null+ /** ONLY async queries use QueryStatus. */+ query_async?: true+ query_progress?: ClickhouseQueryProgressApi | null+ query_scan?: QueryScanSummaryApi | null+ results?: unknown+ /** When was query execution task enqueued. */+ start_time?: string | null+ task_id?: string | null+ team_id: number+}++export interface ResolvedDateRangeResponseApi {+ date_from: string+ date_to: string+}++export interface QueryTimingApi {+ /** Key. Shortened to 'k' to save on data. */+ k: string+ /** Time in seconds. Shortened to 't' to save on data. */+ t: number+}++export interface DataWarehouseSourceUsageApi {+ /** ExternalDataSource id */+ id: string+ /** Connector type of the source (e.g. Stripe, Postgres), if known */+ source_type?: string | null+ /** Warehouse table name that was referenced */+ table_name: string+}++export interface DataWarehouseSyncWarningApi {+ /** True when the last sync is still within the table's sync interval, so the data is current and the warning only says it will stop updating (a sync paused recently). False or absent when the data is out of date. */+ data_is_current?: boolean | null+ /** Human-readable warning shown to the user */+ message: string+ /** Name of the ExternalDataSchema responsible for syncing the table */+ schema_name: string+ /** ID of the ExternalDataSource, used to link to its management page. Null for self-managed tables. */+ source_id?: string | null+ /** Source type, e.g. "Stripe", "Hubspot" */+ source_type: string+ /** Sync status that triggered the warning, e.g. "Failed", "Paused", "BillingLimitReached" */+ status: string+ /** Name of the warehouse table the warning refers to */+ table_name: string+ /** Tells warning kinds apart in the shared `warnings` list */+ type?: 'warehouse_sync'+}++export interface AccessControlFilterWarningApi {+ /** Human-readable warning shown to the user */+ message: string+ /** Resource types the user has access restrictions on, referenced by the query, e.g. ["insight", "dashboard"] */+ resources: string[]+ /** Tells warning kinds apart in the shared `warnings` list */+ type?: 'access_control'+}++export interface ActorsQueryResponseApi {+ columns: unknown[]+ /** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */+ error?: string | null+ hasMore?: boolean | null+ /** Generated HogQL query. */+ hogql: string+ limit: number+ missing_actors_count?: number | null+ /** Modifiers used when performing the query */+ modifiers?: HogQLQueryModifiersApi | null+ offset: number+ /** Query status indicates whether next to the provided data, a query is still running. */+ query_status?: QueryStatusApi | null+ /** The resolved previous/comparison period date range, when comparing against another period */+ resolved_compare_date_range?: ResolvedDateRangeResponseApi | null+ /** The date range used for the query */+ resolved_date_range?: ResolvedDateRangeResponseApi | null+ results: unknown[][]+ /** Measured timings for different parts of the query generation process */+ timings?: QueryTimingApi[] | null+ types?: string[] | null+ /** Connector-synced data warehouse sources referenced by this query, if any. */+ used_data_warehouse_sources?: DataWarehouseSourceUsageApi[] | null+ /** Warnings about data warehouse sources referenced by the query whose latest sync failed, is paused, hit a billing limit, or is otherwise stale. Results may not reflect current source data. Accumulated across every HogQL execution that contributes to this response — so insights backed by warehouse tables (Trends, Funnels, etc.) receive the same warnings as raw HogQL queries. Also carries access control warnings when a system-table query filters out objects the user can't access. */+ warnings?: (DataWarehouseSyncWarningApi | AccessControlFilterWarningApi)[] | null+}++export type BreakdownTypeApi = (typeof BreakdownTypeApi)[keyof typeof BreakdownTypeApi]++export const BreakdownTypeApi = {+ Cohort: 'cohort',+ Person: 'person',+ Event: 'event',+ EventMetadata: 'event_metadata',+ Element: 'element',+ Group: 'group',+ Session: 'session',+ Hogql: 'hogql',+ DataWarehouse: 'data_warehouse',+ DataWarehousePersonProperty: 'data_warehouse_person_property',+ RevenueAnalytics: 'revenue_analytics',+} as const++export type MultipleBreakdownTypeApi = (typeof MultipleBreakdownTypeApi)[keyof typeof MultipleBreakdownTypeApi]++export const MultipleBreakdownTypeApi = {+ Person: 'person',+ Event: 'event',+ EventMetadata: 'event_metadata',+ Element: 'element',+ Group: 'group',+ Session: 'session',+ Hogql: 'hogql',+ Cohort: 'cohort',+ RevenueAnalytics: 'revenue_analytics',+ DataWarehouse: 'data_warehouse',+ DataWarehousePersonProperty: 'data_warehouse_person_property',+} as const++export interface BreakdownApi {+ group_type_index?: number | null+ histogram_bin_count?: number | null+ normalize_url?: boolean | null+ property: string | number+ type?: MultipleBreakdownTypeApi | null+}++export interface BreakdownFilterApi {+ breakdown?: string | (string | number)[] | number | null+ breakdown_group_type_index?: number | null+ breakdown_hide_other_aggregation?: boolean | null+ breakdown_histogram_bin_count?: number | null+ breakdown_limit?: number | null+ breakdown_normalize_url?: boolean | null+ breakdown_path_cleaning?: boolean | null+ breakdown_type?: BreakdownTypeApi | null+ breakdowns?: BreakdownApi[] | null+}++export interface CalendarHeatmapFilterApi {+ /** When true and the series math is `dau`/`unique_users`, each user contributes to the (day-of-week, hour) bucket of their session's first event only — matching the web overview session-start attribution. When false (default), the user contributes to every bucket they have any event in. No effect on `total` math (event counts are unchanged either way). */+ bucketBySessionStart?: boolean | null+}++export interface CompareFilterApi {+ /** Whether to compare the current date range to a previous date range. */+ compare?: boolean | null+ /** The date range to compare to. The value is a relative date. Examples of relative dates are: `-1y` for 1 year ago, `-14m` for 14 months ago, `-100w` for 100 weeks ago, `-14d` for 14 days ago, `-30h` for 30 hours ago. */+ compare_to?: string | null+}++export type PropertyOperatorApi = (typeof PropertyOperatorApi)[keyof typeof PropertyOperatorApi]++export const PropertyOperatorApi = {+ Exact: 'exact',+ IsNot: 'is_not',+ Icontains: 'icontains',+ NotIcontains: 'not_icontains',+ StartsWith: 'starts_with',+ NotStartsWith: 'not_starts_with',+ EndsWith: 'ends_with',+ NotEndsWith: 'not_ends_with',+ Regex: 'regex',+ NotRegex: 'not_regex',+ Gt: 'gt',+ Gte: 'gte',+ Lt: 'lt',+ Lte: 'lte',+ IsSet: 'is_set',+ IsNotSet: 'is_not_set',+ IsDateExact: 'is_date_exact',+ IsDateBefore: 'is_date_before',+ IsDateAfter: 'is_date_after',+ Between: 'between',+ NotBetween: 'not_between',+ Min: 'min',+ Max: 'max',+ In: 'in',+ NotIn: 'not_in',+ IsCleanedPathExact: 'is_cleaned_path_exact',+ IsCleanedPathNotExact: 'is_cleaned_path_not_exact',+ FlagEvaluatesTo: 'flag_evaluates_to',+ SemverEq: 'semver_eq',+ SemverNeq: 'semver_neq',+ SemverGt: 'semver_gt',+ SemverGte: 'semver_gte',+ SemverLt: 'semver_lt',+ SemverLte: 'semver_lte',+ SemverTilde: 'semver_tilde',+ SemverCaret: 'semver_caret',+ SemverWildcard: 'semver_wildcard',+ IcontainsMulti: 'icontains_multi',+ NotIcontainsMulti: 'not_icontains_multi',+} as const++export interface EventPropertyFilterApi {+ key: string+ label?: string | null+ operator?: PropertyOperatorApi | null+ /** Event properties */+ type?: 'event'+ value?: (string | number | boolean)[] | string | number | boolean | null+}++export interface PersonPropertyFilterApi {+ key: string+ label?: string | null+ operator: PropertyOperatorApi+ /** Person properties */+ type?: 'person'+ value?: (string | number | boolean)[] | string | number | boolean | null+}++export interface SessionPropertyFilterApi {+ key: string+ label?: string | null+ operator: PropertyOperatorApi+ type?: 'session'+ value?: (string | number | boolean)[] | string | number | boolean | null+}++export interface CohortPropertyFilterApi {+ cohort_name?: string | null+ key?: 'id'+ label?: string | null+ operator?: PropertyOperatorApi | null+ type?: 'cohort'+ value: number+}++export interface ActionConversionGoalApi {+ actionId: number+ properties?:+ | (EventPropertyFilterApi | PersonPropertyFilterApi | SessionPropertyFilterApi | CohortPropertyFilterApi)[]+ | null+}++export interface CustomEventConversionGoalApi {+ customEventName: string+ properties?:+ | (EventPropertyFilterApi | PersonPropertyFilterApi | SessionPropertyFilterApi | CohortPropertyFilterApi)[]+ | null+}++export type DaysOfWeekEnumApi = (typeof DaysOfWeekEnumApi)[keyof typeof DaysOfWeekEnumApi]++export const DaysOfWeekEnumApi = {+ Number1: 1,+ Number2: 2,+ Number3: 3,+ Number4: 4,+ Number5: 5,+ Number6: 6,+ Number7: 7,+} as const++export interface DateRangeApi {+ /** Start of the date range. Accepts ISO 8601 timestamps (e.g., 2024-01-15T00:00:00Z) or relative formats: -7d (7 days ago), -2w (2 weeks ago), -1m (1 month ago),+ * -1h (1 hour ago), -1mStart (start of last month), -1yStart (start of last year). */+ date_from?: string | null+ /** End of the date range. Same format as date_from. Omit or null for "now". A calendar day without a time (2024-01-15) is inclusive: it rounds to the last moment of that day in the project timezone, unless explicitDate is set. */+ date_to?: string | null+ /** Restrict the query to events occurring on these ISO days of week (1=Monday to 7=Sunday), evaluated in the project timezone. Omit or empty for all days. Only applied by insight queries. */+ daysOfWeek?: DaysOfWeekEnumApi[] | null+ /** Exclude the current, still-collecting period by clipping date_to to the end of the last complete interval (evaluated in the project timezone). No-op when the range contains no complete interval. Only applied by insight queries. */+ excludeIncompletePeriods?: boolean | null+ /** Whether the date_from and date_to should be used verbatim. Disables rounding to the start and end of period. */+ explicitDate?: boolean | null+}++export type IntervalTypeApi = (typeof IntervalTypeApi)[keyof typeof IntervalTypeApi]++export const IntervalTypeApi = {+ Second: 'second',+ Minute: 'minute',+ Hour: 'hour',+ Day: 'day',+ Week: 'week',+ Month: 'month',+ Quarter: 'quarter',+ Year: 'year',+} as const++export interface PersonMetadataPropertyFilterApi {+ key: string+ label?: string | null+ operator: PropertyOperatorApi+ /** Top-level columns on the persons table (e.g. created_at), not properties JSON */+ type?: 'person_metadata'+ value?: (string | number | boolean)[] | string | number | boolean | null+}++export type Key10Api = (typeof Key10Api)[keyof typeof Key10Api]++export const Key10Api = {+ TagName: 'tag_name',+ Text: 'text',+ Href: 'href',+ Selector: 'selector',+} as const++export interface ElementPropertyFilterApi {+ key: Key10Api+ label?: string | null+ operator: PropertyOperatorApi+ type?: 'element'+ value?: (string | number | boolean)[] | string | number | boolean | null+}++export interface EventMetadataPropertyFilterApi {+ key: string+ label?: string | null+ operator: PropertyOperatorApi+ type?: 'event_metadata'+ value?: (string | number | boolean)[] | string | number | boolean | null+}++export type DurationTypeApi = (typeof DurationTypeApi)[keyof typeof DurationTypeApi]++export const DurationTypeApi = {+ Duration: 'duration',+ ActiveSeconds: 'active_seconds',+ InactiveSeconds: 'inactive_seconds',+} as const++export interface RecordingPropertyFilterApi {+ key: DurationTypeApi | string+ label?: string | null+ operator: PropertyOperatorApi+ type?: 'recording'+ value?: (string | number | boolean)[] | string | number | boolean | null+}++export interface LogEntryPropertyFilterApi {+ key: string+ label?: string | null+ operator: PropertyOperatorApi+ type?: 'log_entry'+ value?: (string | number | boolean)[] | string | number | boolean | null+}++export type GroupPropertyFilterApiGroupKeyNames = { [key: string]: string } | null++export interface GroupPropertyFilterApi {+ group_key_names?: GroupPropertyFilterApiGroupKeyNames+ group_type_index?: number | null+ key: string+ label?: string | null+ operator: PropertyOperatorApi+ type?: 'group'+ value?: (string | number | boolean)[] | string | number | boolean | null+}++export interface FeaturePropertyFilterApi {+ key: string+ label?: string | null+ operator: PropertyOperatorApi+ /** Event property with "$feature/" prepended */+ type?: 'feature'+ value?: (string | number | boolean)[] | string | number | boolean | null+}++export interface FlagPropertyFilterApi {+ /** The key should be the flag ID */+ key: string+ label?: string | null+ /** Only flag_evaluates_to operator is allowed for flag dependencies */+ operator?: 'flag_evaluates_to'+ /** Feature flag dependency */+ type?: 'flag'+ /** The value can be true, false, or a variant name */+ value: boolean | string+}++export interface HogQLPropertyFilterApi {+ key: string+ label?: string | null+ type?: 'hogql'+ value?: (string | number | boolean)[] | string | number | boolean | null+}++export const EmptyPropertyFilterApiValue = {+ type: 'empty',+} as const+export type EmptyPropertyFilterApi = typeof EmptyPropertyFilterApiValue++export interface DataWarehousePropertyFilterApi {+ key: string+ label?: string | null+ operator: PropertyOperatorApi+ type?: 'data_warehouse'+ value?: (string | number | boolean)[] | string | number | boolean | null+}++export interface DataWarehousePersonPropertyFilterApi {+ key: string+ label?: string | null+ operator: PropertyOperatorApi+ type?: 'data_warehouse_person_property'+ value?: (string | number | boolean)[] | string | number | boolean | null+}++export interface ErrorTrackingIssueFilterApi {+ key: string+ label?: string | null+ operator: PropertyOperatorApi+ type?: 'error_tracking_issue'+ value?: (string | number | boolean)[] | string | number | boolean | null+}++export type LogPropertyFilterTypeApi = (typeof LogPropertyFilterTypeApi)[keyof typeof LogPropertyFilterTypeApi]++export const LogPropertyFilterTypeApi = {+ Log: 'log',+ LogAttribute: 'log_attribute',+ LogResourceAttribute: 'log_resource_attribute',+} as const++export interface LogPropertyFilterApi {+ key: string+ label?: string | null+ operator: PropertyOperatorApi+ type: LogPropertyFilterTypeApi+ value?: (string | number | boolean)[] | string | number | boolean | null+}++export interface MetricPropertyFilterApi {+ key: string+ label?: string | null+ operator: PropertyOperatorApi+ type?: 'metric_attribute'+ value?: (string | number | boolean)[] | string | number | boolean | null+}++export type SpanPropertyFilterTypeApi = (typeof SpanPropertyFilterTypeApi)[keyof typeof SpanPropertyFilterTypeApi]++export const SpanPropertyFilterTypeApi = {+ Span: 'span',+ SpanAttribute: 'span_attribute',+ SpanResourceAttribute: 'span_resource_attribute',+} as const++export interface SpanPropertyFilterApi {+ key: string+ label?: string | null+ operator: PropertyOperatorApi+ type: SpanPropertyFilterTypeApi+ value?: (string | number | boolean)[] | string | number | boolean | null+}++export interface RevenueAnalyticsPropertyFilterApi {+ key: string+ label?: string | null+ operator: PropertyOperatorApi+ type?: 'revenue_analytics'+ value?: (string | number | boolean)[] | string | number | boolean | null+}++export interface AccountCustomPropertyFilterApi {+ key: string+ label?: string | null+ operator: PropertyOperatorApi+ /** Customer analytics account custom property — the key is the property definition id */+ type?: 'account_custom_property'+ value?: (string | number | boolean)[] | string | number | boolean | null+}++export interface WorkflowVariablePropertyFilterApi {+ key: string+ label?: string | null+ operator: PropertyOperatorApi+ type?: 'workflow_variable'+ value?: (string | number | boolean)[] | string | number | boolean | null+}++export type BehavioralEventSourceApi = (typeof BehavioralEventSourceApi)[keyof typeof BehavioralEventSourceApi]++export const BehavioralEventSourceApi = {+ Events: 'events',+ Actions: 'actions',+} as const++export type TimeUnitTypeApi = (typeof TimeUnitTypeApi)[keyof typeof TimeUnitTypeApi]++export const TimeUnitTypeApi = {+ Day: 'day',+ Week: 'week',+ Month: 'month',+ Year: 'year',+} as const++export type InlineBehavioralTypeApi = (typeof InlineBehavioralTypeApi)[keyof typeof InlineBehavioralTypeApi]++export const InlineBehavioralTypeApi = {+ PerformedEvent: 'performed_event',+ PerformedEventMultiple: 'performed_event_multiple',+} as const++export interface BehavioralPropertyFilterApi {+ /** Extra property filters the matching events must satisfy. Deliberately excludes nested behavioral/cohort filters and groups */+ event_filters?:+ | (+ | EventPropertyFilterApi+ | PersonPropertyFilterApi+ | ElementPropertyFilterApi+ | FeaturePropertyFilterApi+ | HogQLPropertyFilterApi+ )[]+ | null+ event_type: BehavioralEventSourceApi+ /** Absolute or relative (e.g. -30d) lower date bound — alternative to time_value/time_interval */+ explicit_datetime?: string | null+ explicit_datetime_to?: string | null+ /** Event name, or action id when event_type is 'actions' */+ key: string+ label?: string | null+ /** Match persons who did NOT satisfy the criterion. Not the same as a low count — zero-occurrence persons never match count operators */+ negation?: boolean | null+ /** Count comparison for performed_event_multiple, defaults to exact */+ operator?: PropertyOperatorApi | null+ /** Count threshold for performed_event_multiple */+ operator_value?: number | null+ time_interval?: TimeUnitTypeApi | null+ /** Relative time window size, paired with time_interval */+ time_value?: number | null+ /** Person performed (or didn't perform) an event in a time window. ClickHouse-only — not evaluable by flags or CDP */+ type?: 'behavioral'+ value: InlineBehavioralTypeApi+}++export type BaseMathTypeApi = (typeof BaseMathTypeApi)[keyof typeof BaseMathTypeApi]++export const BaseMathTypeApi = {+ Total: 'total',+ Dau: 'dau',+ WeeklyActive: 'weekly_active',+ MonthlyActive: 'monthly_active',+ UniqueSession: 'unique_session',+ FirstTimeForUser: 'first_time_for_user',+ FirstMatchingEventForUser: 'first_matching_event_for_user',+} as const++export type FunnelMathTypeApi = (typeof FunnelMathTypeApi)[keyof typeof FunnelMathTypeApi]++export const FunnelMathTypeApi = {+ Total: 'total',+ FirstTimeForUser: 'first_time_for_user',+ FirstTimeForUserWithFilters: 'first_time_for_user_with_filters',+} as const++export type PropertyMathTypeApi = (typeof PropertyMathTypeApi)[keyof typeof PropertyMathTypeApi]++export const PropertyMathTypeApi = {+ Avg: 'avg',+ Sum: 'sum',+ Min: 'min',+ Max: 'max',+ Median: 'median',+ P75: 'p75',+ P90: 'p90',+ P95: 'p95',+ P99: 'p99',+} as const++export type CountPerActorMathTypeApi = (typeof CountPerActorMathTypeApi)[keyof typeof CountPerActorMathTypeApi]++export const CountPerActorMathTypeApi = {+ AvgCountPerActor: 'avg_count_per_actor',+ MinCountPerActor: 'min_count_per_actor',+ MaxCountPerActor: 'max_count_per_actor',+ MedianCountPerActor: 'median_count_per_actor',+ P75CountPerActor: 'p75_count_per_actor',+ P90CountPerActor: 'p90_count_per_actor',+ P95CountPerActor: 'p95_count_per_actor',+ P99CountPerActor: 'p99_count_per_actor',+} as const++export type GroupMathTypeApi = (typeof GroupMathTypeApi)[keyof typeof GroupMathTypeApi]++export const GroupMathTypeApi = {+ UniqueGroup: 'unique_group',+ FirstTimeForGroup: 'first_time_for_group',+ FirstMatchingEventForGroup: 'first_matching_event_for_group',+} as const++export type ExperimentMetricMathTypeApi = (typeof ExperimentMetricMathTypeApi)[keyof typeof ExperimentMetricMathTypeApi]++export const ExperimentMetricMathTypeApi = {+ Total: 'total',+ Sum: 'sum',+ UniqueSession: 'unique_session',+ Min: 'min',+ Max: 'max',+ Avg: 'avg',+ Dau: 'dau',+ UniqueGroup: 'unique_group',+ Hogql: 'hogql',+} as const++export type CalendarHeatmapMathTypeApi = (typeof CalendarHeatmapMathTypeApi)[keyof typeof CalendarHeatmapMathTypeApi]++export const CalendarHeatmapMathTypeApi = {+ Total: 'total',+ Dau: 'dau',+} as const++export type MathGroupTypeIndexApi = (typeof MathGroupTypeIndexApi)[keyof typeof MathGroupTypeIndexApi]++export const MathGroupTypeIndexApi = {+ Number0: 0,+ Number1: 1,+ Number2: 2,+ Number3: 3,+ Number4: 4,+} as const++export type CurrencyCodeApi = (typeof CurrencyCodeApi)[keyof typeof CurrencyCodeApi]++export const CurrencyCodeApi = {+ Aed: 'AED',+ Afn: 'AFN',+ All: 'ALL',+ Amd: 'AMD',+ Ang: 'ANG',+ Aoa: 'AOA',+ Ars: 'ARS',+ Aud: 'AUD',+ Awg: 'AWG',+ Azn: 'AZN',+ Bam: 'BAM',+ Bbd: 'BBD',+ Bdt: 'BDT',+ Bgn: 'BGN',+ Bhd: 'BHD',+ Bif: 'BIF',+ Bmd: 'BMD',+ Bnd: 'BND',+ Bob: 'BOB',+ Brl: 'BRL',+ Bsd: 'BSD',+ Btc: 'BTC',+ Btn: 'BTN',+ Bwp: 'BWP',+ Byn: 'BYN',+ Bzd: 'BZD',+ Cad: 'CAD',+ Cdf: 'CDF',+ Chf: 'CHF',+ Clp: 'CLP',+ Cny: 'CNY',+ Cop: 'COP',+ Crc: 'CRC',+ Cve: 'CVE',+ Czk: 'CZK',+ Djf: 'DJF',+ Dkk: 'DKK',+ Dop: 'DOP',+ Dzd: 'DZD',+ Egp: 'EGP',+ Ern: 'ERN',+ Etb: 'ETB',+ Eur: 'EUR',+ Fjd: 'FJD',+ Gbp: 'GBP',+ Gel: 'GEL',+ Ghs: 'GHS',+ Gip: 'GIP',+ Gmd: 'GMD',+ Gnf: 'GNF',+ Gtq: 'GTQ',+ Gyd: 'GYD',+ Hkd: 'HKD',+ Hnl: 'HNL',+ Hrk: 'HRK',+ Htg: 'HTG',+ Huf: 'HUF',+ Idr: 'IDR',+ Ils: 'ILS',+ Inr: 'INR',+ Iqd: 'IQD',+ Irr: 'IRR',+ Isk: 'ISK',+ Jmd: 'JMD',+ Jod: 'JOD',+ Jpy: 'JPY',+ Kes: 'KES',+ Kgs: 'KGS',+ Khr: 'KHR',+ Kmf: 'KMF',+ Krw: 'KRW',+ Kwd: 'KWD',+ Kyd: 'KYD',+ Kzt: 'KZT',+ Lak: 'LAK',+ Lbp: 'LBP',+ Lkr: 'LKR',+ Lrd: 'LRD',+ Ltl: 'LTL',+ Lvl: 'LVL',+ Lsl: 'LSL',+ Lyd: 'LYD',+ Mad: 'MAD',+ Mdl: 'MDL',+ Mga: 'MGA',+ Mkd: 'MKD',+ Mmk: 'MMK',+ Mnt: 'MNT',+ Mop: 'MOP',+ Mru: 'MRU',+ Mtl: 'MTL',+ Mur: 'MUR',+ Mvr: 'MVR',+ Mwk: 'MWK',+ Mxn: 'MXN',+ Myr: 'MYR',+ Mzn: 'MZN',+ Nad: 'NAD',+ Ngn: 'NGN',+ Nio: 'NIO',+ Nok: 'NOK',+ Npr: 'NPR',+ Nzd: 'NZD',+ Omr: 'OMR',+ Pab: 'PAB',+ Pen: 'PEN',+ Pgk: 'PGK',+ Php: 'PHP',+ Pkr: 'PKR',+ Pln: 'PLN',+ Pyg: 'PYG',+ Qar: 'QAR',+ Ron: 'RON',+ Rsd: 'RSD',+ Rub: 'RUB',+ Rwf: 'RWF',+ Sar: 'SAR',+ Sbd: 'SBD',+ Scr: 'SCR',+ Sdg: 'SDG',+ Sek: 'SEK',+ Sgd: 'SGD',+ Srd: 'SRD',+ Ssp: 'SSP',+ Stn: 'STN',+ Syp: 'SYP',+ Szl: 'SZL',+ Thb: 'THB',+ Tjs: 'TJS',+ Tmt: 'TMT',+ Tnd: 'TND',+ Top: 'TOP',+ Try: 'TRY',+ Ttd: 'TTD',+ Twd: 'TWD',+ Tzs: 'TZS',+ Uah: 'UAH',+ Ugx: 'UGX',+ Usd: 'USD',+ Uyu: 'UYU',+ Uzs: 'UZS',+ Ves: 'VES',+ Vnd: 'VND',+ Vuv: 'VUV',+ Wst: 'WST',+ Xaf: 'XAF',+ Xcd: 'XCD',+ Xof: 'XOF',+ Xpf: 'XPF',+ Yer: 'YER',+ Zar: 'ZAR',+ Zmw: 'ZMW',+} as const++export interface RevenueCurrencyPropertyConfigApi {+ property?: string | null+ static?: CurrencyCodeApi | null+}++export type DataWarehouseNodeApiResponse = { [key: string]: unknown } | null++export interface DataWarehouseNodeApi {+ custom_name?: string | null+ distinct_id_field: string+ dw_source_type?: string | null+ /** Fixed properties in the query, can't be edited in the interface (e.g. scoping down by person) */+ fixedProperties?:+ | (+ | EventPropertyFilterApi+ | PersonPropertyFilterApi+ | PersonMetadataPropertyFilterApi+ | ElementPropertyFilterApi+ | EventMetadataPropertyFilterApi+ | SessionPropertyFilterApi+ | CohortPropertyFilterApi+ | RecordingPropertyFilterApi+ | LogEntryPropertyFilterApi+ | GroupPropertyFilterApi+ | FeaturePropertyFilterApi+ | FlagPropertyFilterApi+ | HogQLPropertyFilterApi+ | EmptyPropertyFilterApi+ | DataWarehousePropertyFilterApi+ | DataWarehousePersonPropertyFilterApi+ | ErrorTrackingIssueFilterApi+ | LogPropertyFilterApi+ | MetricPropertyFilterApi+ | SpanPropertyFilterApi+ | RevenueAnalyticsPropertyFilterApi+ | AccountCustomPropertyFilterApi+ | WorkflowVariablePropertyFilterApi+ | BehavioralPropertyFilterApi+ )[]+ | null+ id: string+ id_field: string+ kind?: 'DataWarehouseNode'+ math?:+ | BaseMathTypeApi+ | FunnelMathTypeApi+ | PropertyMathTypeApi+ | CountPerActorMathTypeApi+ | GroupMathTypeApi+ | ExperimentMetricMathTypeApi+ | CalendarHeatmapMathTypeApi+ | 'hogql'+ | null+ math_group_type_index?: MathGroupTypeIndexApi | null+ math_hogql?: string | null+ math_multiplier?: number | null+ math_property?: string | null+ math_property_revenue_currency?: RevenueCurrencyPropertyConfigApi | null+ math_property_type?: string | null+ name?: string | null+ optionalInFunnel?: boolean | null+ /** Properties configurable in the interface */+ properties?:+ | (+ | EventPropertyFilterApi+ | PersonPropertyFilterApi+ | PersonMetadataPropertyFilterApi+ | ElementPropertyFilterApi+ | EventMetadataPropertyFilterApi+ | SessionPropertyFilterApi+ | CohortPropertyFilterApi+ | RecordingPropertyFilterApi+ | LogEntryPropertyFilterApi+ | GroupPropertyFilterApi+ | FeaturePropertyFilterApi+ | FlagPropertyFilterApi+ | HogQLPropertyFilterApi+ | EmptyPropertyFilterApi+ | DataWarehousePropertyFilterApi+ | DataWarehousePersonPropertyFilterApi+ | ErrorTrackingIssueFilterApi+ | LogPropertyFilterApi+ | MetricPropertyFilterApi+ | SpanPropertyFilterApi+ | RevenueAnalyticsPropertyFilterApi+ | AccountCustomPropertyFilterApi+ | WorkflowVariablePropertyFilterApi+ | BehavioralPropertyFilterApi+ )[]+ | null+ response?: DataWarehouseNodeApiResponse+ table_name: string+ timestamp_field: string+ /** version of the node, used for schema migrations */+ version?: number | null+}++export interface MarketingAnalyticsCostFallbackApi {+ /**+ * @minItems 1+ * @maxItems 200+ */+ series: DataWarehouseNodeApi[]+ /**+ * @minItems 1+ * @maxItems 200+ */+ sourceIds: string[]+}++export interface PropertyGroupFilterValueApi {+ type: FilterLogicalOperatorApi+ values: (+ | PropertyGroupFilterValueApi+ | EventPropertyFilterApi+ | PersonPropertyFilterApi+ | PersonMetadataPropertyFilterApi+ | ElementPropertyFilterApi+ | EventMetadataPropertyFilterApi+ | SessionPropertyFilterApi+ | CohortPropertyFilterApi+ | RecordingPropertyFilterApi+ | LogEntryPropertyFilterApi+ | GroupPropertyFilterApi+ | FeaturePropertyFilterApi+ | FlagPropertyFilterApi+ | HogQLPropertyFilterApi+ | EmptyPropertyFilterApi+ | DataWarehousePropertyFilterApi+ | DataWarehousePersonPropertyFilterApi+ | ErrorTrackingIssueFilterApi+ | LogPropertyFilterApi+ | MetricPropertyFilterApi+ | SpanPropertyFilterApi+ | RevenueAnalyticsPropertyFilterApi+ | AccountCustomPropertyFilterApi+ | WorkflowVariablePropertyFilterApi+ | BehavioralPropertyFilterApi+ )[]+}++export interface PropertyGroupFilterApi {+ type: FilterLogicalOperatorApi+ values: PropertyGroupFilterValueApi[]+}++export interface BoxPlotDatumApi {+ day: string+ label: string+ max: number+ mean: number+ median: number+ min: number+ p25: number+ p75: number+ series_index?: number | null+ series_label?: string | null+}++export type TrendsQueryResponseApiResultsItem = { [key: string]: unknown }++export interface TrendsQueryResponseApi {+ boxplot_data?: BoxPlotDatumApi[] | null+ /** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */+ error?: string | null+ /** Wether more breakdown values are available. */+ hasMore?: boolean | null+ /** Generated HogQL query. */+ hogql?: string | null+ /** Modifiers used when performing the query */+ modifiers?: HogQLQueryModifiersApi | null+ /** Query status indicates whether next to the provided data, a query is still running. */+ query_status?: QueryStatusApi | null+ /** The resolved previous/comparison period date range, when comparing against another period */+ resolved_compare_date_range?: ResolvedDateRangeResponseApi | null+ /** The date range used for the query */+ resolved_date_range?: ResolvedDateRangeResponseApi | null+ results: TrendsQueryResponseApiResultsItem[]+ /** Measured timings for different parts of the query generation process */+ timings?: QueryTimingApi[] | null+ /** Connector-synced data warehouse sources referenced by this query, if any. */+ used_data_warehouse_sources?: DataWarehouseSourceUsageApi[] | null+ /** Warnings about data warehouse sources referenced by the query whose latest sync failed, is paused, hit a billing limit, or is otherwise stale. Results may not reflect current source data. Accumulated across every HogQL execution that contributes to this response — so insights backed by warehouse tables (Trends, Funnels, etc.) receive the same warnings as raw HogQL queries. Also carries access control warnings when a system-table query filters out objects the user can't access. */+ warnings?: (DataWarehouseSyncWarningApi | AccessControlFilterWarningApi)[] | null+}++export type EventsNodeApiResponse = { [key: string]: unknown } | null++export interface EventsNodeApi {+ custom_name?: string | null+ /** The event or `null` for all events. */+ event?: string | null+ /** Fixed properties in the query, can't be edited in the interface (e.g. scoping down by person) */+ fixedProperties?:+ | (+ | EventPropertyFilterApi+ | PersonPropertyFilterApi+ | PersonMetadataPropertyFilterApi+ | ElementPropertyFilterApi+ | EventMetadataPropertyFilterApi+ | SessionPropertyFilterApi+ | CohortPropertyFilterApi+ | RecordingPropertyFilterApi+ | LogEntryPropertyFilterApi+ | GroupPropertyFilterApi+ | FeaturePropertyFilterApi+ | FlagPropertyFilterApi+ | HogQLPropertyFilterApi+ | EmptyPropertyFilterApi+ | DataWarehousePropertyFilterApi+ | DataWarehousePersonPropertyFilterApi+ | ErrorTrackingIssueFilterApi+ | LogPropertyFilterApi+ | MetricPropertyFilterApi+ | SpanPropertyFilterApi+ | RevenueAnalyticsPropertyFilterApi+ | AccountCustomPropertyFilterApi+ | WorkflowVariablePropertyFilterApi+ | BehavioralPropertyFilterApi+ )[]+ | null+ kind?: 'EventsNode'+ limit?: number | null+ math?:+ | BaseMathTypeApi+ | FunnelMathTypeApi+ | PropertyMathTypeApi+ | CountPerActorMathTypeApi+ | GroupMathTypeApi+ | ExperimentMetricMathTypeApi+ | CalendarHeatmapMathTypeApi+ | 'hogql'+ | null+ math_group_type_index?: MathGroupTypeIndexApi | null+ math_hogql?: string | null+ math_multiplier?: number | null+ math_property?: string | null+ math_property_revenue_currency?: RevenueCurrencyPropertyConfigApi | null+ math_property_type?: string | null+ name?: string | null+ optionalInFunnel?: boolean | null+ /** Columns to order by */+ orderBy?: string[] | null+ /** Properties configurable in the interface */+ properties?:+ | (+ | EventPropertyFilterApi+ | PersonPropertyFilterApi+ | PersonMetadataPropertyFilterApi+ | ElementPropertyFilterApi+ | EventMetadataPropertyFilterApi+ | SessionPropertyFilterApi+ | CohortPropertyFilterApi+ | RecordingPropertyFilterApi+ | LogEntryPropertyFilterApi+ | GroupPropertyFilterApi+ | FeaturePropertyFilterApi+ | FlagPropertyFilterApi+ | HogQLPropertyFilterApi+ | EmptyPropertyFilterApi+ | DataWarehousePropertyFilterApi+ | DataWarehousePersonPropertyFilterApi+ | ErrorTrackingIssueFilterApi+ | LogPropertyFilterApi+ | MetricPropertyFilterApi+ | SpanPropertyFilterApi+ | RevenueAnalyticsPropertyFilterApi+ | AccountCustomPropertyFilterApi+ | WorkflowVariablePropertyFilterApi+ | BehavioralPropertyFilterApi+ )[]+ | null+ response?: EventsNodeApiResponse+ /** version of the node, used for schema migrations */+ version?: number | null+}++export type ActionsNodeApiResponse = { [key: string]: unknown } | null++export interface ActionsNodeApi {+ custom_name?: string | null+ /** Fixed properties in the query, can't be edited in the interface (e.g. scoping down by person) */+ fixedProperties?:+ | (+ | EventPropertyFilterApi+ | PersonPropertyFilterApi+ | PersonMetadataPropertyFilterApi+ | ElementPropertyFilterApi+ | EventMetadataPropertyFilterApi+ | SessionPropertyFilterApi+ | CohortPropertyFilterApi+ | RecordingPropertyFilterApi+ | LogEntryPropertyFilterApi+ | GroupPropertyFilterApi+ | FeaturePropertyFilterApi+ | FlagPropertyFilterApi+ | HogQLPropertyFilterApi+ | EmptyPropertyFilterApi+ | DataWarehousePropertyFilterApi+ | DataWarehousePersonPropertyFilterApi+ | ErrorTrackingIssueFilterApi+ | LogPropertyFilterApi+ | MetricPropertyFilterApi+ | SpanPropertyFilterApi+ | RevenueAnalyticsPropertyFilterApi+ | AccountCustomPropertyFilterApi+ | WorkflowVariablePropertyFilterApi+ | BehavioralPropertyFilterApi+ )[]+ | null+ id: number+ kind?: 'ActionsNode'+ math?:+ | BaseMathTypeApi+ | FunnelMathTypeApi+ | PropertyMathTypeApi+ | CountPerActorMathTypeApi+ | GroupMathTypeApi+ | ExperimentMetricMathTypeApi+ | CalendarHeatmapMathTypeApi+ | 'hogql'+ | null+ math_group_type_index?: MathGroupTypeIndexApi | null+ math_hogql?: string | null+ math_multiplier?: number | null+ math_property?: string | null+ math_property_revenue_currency?: RevenueCurrencyPropertyConfigApi | null+ math_property_type?: string | null+ name?: string | null+ optionalInFunnel?: boolean | null+ /** Properties configurable in the interface */+ properties?:+ | (+ | EventPropertyFilterApi+ | PersonPropertyFilterApi+ | PersonMetadataPropertyFilterApi+ | ElementPropertyFilterApi+ | EventMetadataPropertyFilterApi+ | SessionPropertyFilterApi+ | CohortPropertyFilterApi+ | RecordingPropertyFilterApi+ | LogEntryPropertyFilterApi+ | GroupPropertyFilterApi+ | FeaturePropertyFilterApi+ | FlagPropertyFilterApi+ | HogQLPropertyFilterApi+ | EmptyPropertyFilterApi+ | DataWarehousePropertyFilterApi+ | DataWarehousePersonPropertyFilterApi+ | ErrorTrackingIssueFilterApi+ | LogPropertyFilterApi+ | MetricPropertyFilterApi+ | SpanPropertyFilterApi+ | RevenueAnalyticsPropertyFilterApi+ | AccountCustomPropertyFilterApi+ | WorkflowVariablePropertyFilterApi+ | BehavioralPropertyFilterApi+ )[]+ | null+ response?: ActionsNodeApiResponse+ /** version of the node, used for schema migrations */+ version?: number | null+}++export type GroupNodeApiResponse = { [key: string]: unknown } | null++export interface GroupNodeApi {+ custom_name?: string | null+ /** Fixed properties in the query, can't be edited in the interface (e.g. scoping down by person) */+ fixedProperties?:+ | (+ | EventPropertyFilterApi+ | PersonPropertyFilterApi+ | PersonMetadataPropertyFilterApi+ | ElementPropertyFilterApi+ | EventMetadataPropertyFilterApi+ | SessionPropertyFilterApi+ | CohortPropertyFilterApi+ | RecordingPropertyFilterApi+ | LogEntryPropertyFilterApi+ | GroupPropertyFilterApi+ | FeaturePropertyFilterApi+ | FlagPropertyFilterApi+ | HogQLPropertyFilterApi+ | EmptyPropertyFilterApi+ | DataWarehousePropertyFilterApi+ | DataWarehousePersonPropertyFilterApi+ | ErrorTrackingIssueFilterApi+ | LogPropertyFilterApi+ | MetricPropertyFilterApi+ | SpanPropertyFilterApi+ | RevenueAnalyticsPropertyFilterApi+ | AccountCustomPropertyFilterApi+ | WorkflowVariablePropertyFilterApi+ | BehavioralPropertyFilterApi+ )[]+ | null+ kind?: 'GroupNode'+ limit?: number | null+ math?:+ | BaseMathTypeApi+ | FunnelMathTypeApi+ | PropertyMathTypeApi+ | CountPerActorMathTypeApi+ | GroupMathTypeApi+ | ExperimentMetricMathTypeApi+ | CalendarHeatmapMathTypeApi+ | 'hogql'+ | null+ math_group_type_index?: MathGroupTypeIndexApi | null+ math_hogql?: string | null+ math_multiplier?: number | null+ math_property?: string | null+ math_property_revenue_currency?: RevenueCurrencyPropertyConfigApi | null+ math_property_type?: string | null+ name?: string | null+ /** Entities to combine in this group */+ nodes: (EventsNodeApi | ActionsNodeApi | DataWarehouseNodeApi)[]+ /** Group of entities combined with AND/OR operator */+ operator: FilterLogicalOperatorApi+ optionalInFunnel?: boolean | null+ /** Columns to order by */+ orderBy?: string[] | null+ /** Properties configurable in the interface */+ properties?:+ | (+ | EventPropertyFilterApi+ | PersonPropertyFilterApi+ | PersonMetadataPropertyFilterApi+ | ElementPropertyFilterApi+ | EventMetadataPropertyFilterApi+ | SessionPropertyFilterApi+ | CohortPropertyFilterApi+ | RecordingPropertyFilterApi+ | LogEntryPropertyFilterApi+ | GroupPropertyFilterApi+ | FeaturePropertyFilterApi+ | FlagPropertyFilterApi+ | HogQLPropertyFilterApi+ | EmptyPropertyFilterApi+ | DataWarehousePropertyFilterApi+ | DataWarehousePersonPropertyFilterApi+ | ErrorTrackingIssueFilterApi+ | LogPropertyFilterApi+ | MetricPropertyFilterApi+ | SpanPropertyFilterApi+ | RevenueAnalyticsPropertyFilterApi+ | AccountCustomPropertyFilterApi+ | WorkflowVariablePropertyFilterApi+ | BehavioralPropertyFilterApi+ )[]+ | null+ response?: GroupNodeApiResponse+ /** version of the node, used for schema migrations */+ version?: number | null+}++export interface QueryLogTagsApi {+ /** Name of the query, preferably unique. For example web_analytics_vitals */+ name?: string | null+ /** Short id of the saved Web analytics filter preset this query was run under, if any. */+ presetId?: string | null+ /** Product responsible for this query. Use string, there's no need to churn the Schema when we add a new product * */+ productKey?: string | null+ /** Scene where this query is shown in the UI. Use string, there's no need to churn the Schema when we add a new Scene * */+ scene?: string | null+}++export type AggregationAxisFormatApi = (typeof AggregationAxisFormatApi)[keyof typeof AggregationAxisFormatApi]++export const AggregationAxisFormatApi = {+ Numeric: 'numeric',+ Duration: 'duration',+ DurationMs: 'duration_ms',+ DurationNs: 'duration_ns',+ Percentage: 'percentage',+ PercentageScaled: 'percentage_scaled',+ Currency: 'currency',+ Short: 'short',+} as const++export type AnnotationScopeApi = (typeof AnnotationScopeApi)[keyof typeof AnnotationScopeApi]++export const AnnotationScopeApi = {+ DashboardItem: 'dashboard_item',+ Dashboard: 'dashboard',+ Project: 'project',+ Organization: 'organization',+} as const++export type CurveApi = (typeof CurveApi)[keyof typeof CurveApi]++export const CurveApi = {+ Linear: 'linear',+ Smooth: 'smooth',+} as const++export type SeriesColorModeApi = (typeof SeriesColorModeApi)[keyof typeof SeriesColorModeApi]++export const SeriesColorModeApi = {+ Palette: 'palette',+ Opacity: 'opacity',+} as const++export interface ChartStyleApi {+ /** Line interpolation: straight segments or a smoothed curve through the points. */+ curve?: CurveApi | null+ /** How series are told apart: one color per series, or one color at stepped opacities. */+ seriesColorMode?: SeriesColorModeApi | null+}++export type DetailedResultsAggregationTypeApi =+ (typeof DetailedResultsAggregationTypeApi)[keyof typeof DetailedResultsAggregationTypeApi]++export const DetailedResultsAggregationTypeApi = {+ Total: 'total',+ Average: 'average',+ Median: 'median',+} as const++export type ChartDisplayTypeApi = (typeof ChartDisplayTypeApi)[keyof typeof ChartDisplayTypeApi]++export const ChartDisplayTypeApi = {+ Auto: 'Auto',+ ActionsLineGraph: 'ActionsLineGraph',+ ActionsBar: 'ActionsBar',+ ActionsUnstackedBar: 'ActionsUnstackedBar',+ ActionsStackedBar: 'ActionsStackedBar',+ ActionsAreaGraph: 'ActionsAreaGraph',+ ActionsLineGraphCumulative: 'ActionsLineGraphCumulative',+ BoldNumber: 'BoldNumber',+ Metric: 'Metric',+ ActionsPie: 'ActionsPie',+ ActionsDonut: 'ActionsDonut',+ ActionsProportionBar: 'ActionsProportionBar',+ ActionsBarValue: 'ActionsBarValue',+ ActionsTable: 'ActionsTable',+ WorldMap: 'WorldMap',+ CalendarHeatmap: 'CalendarHeatmap',+ TwoDimensionalHeatmap: 'TwoDimensionalHeatmap',+ BoxPlot: 'BoxPlot',+ SlopeGraph: 'SlopeGraph',+ ScatterPlot: 'ScatterPlot',+} as const++export interface TrendsFormulaNodeApi {+ /** Optional user-defined name for the formula */+ custom_name?: string | null+ formula: string+}++export type CalculationApi = (typeof CalculationApi)[keyof typeof CalculationApi]++export const CalculationApi = {+ Fixed: 'fixed',+ Mean: 'mean',+ Median: 'median',+ Min: 'min',+ Max: 'max',+} as const++export type PositionApi = (typeof PositionApi)[keyof typeof PositionApi]++export const PositionApi = {+ Start: 'start',+ End: 'end',+} as const++export type ScopeApi = (typeof ScopeApi)[keyof typeof ScopeApi]++export const ScopeApi = {+ All: 'all',+ Series: 'series',+} as const++export interface GoalLineApi {+ borderColor?: string | null+ /** Recalculate from returned chart marks. An absent calculation uses the fixed value. */+ calculation?: CalculationApi | null+ displayIfCrossed?: boolean | null+ displayLabel?: boolean | null+ label: string+ position?: PositionApi | null+ /** SQL chart calculations use the primary axis, across all series or separately per series. */+ scope?: ScopeApi | null+ value: number+}++export type LegendPositionApi = (typeof LegendPositionApi)[keyof typeof LegendPositionApi]++export const LegendPositionApi = {+ Top: 'top',+ Bottom: 'bottom',+ Left: 'left',+ Right: 'right',+} as const++export type MetricSummaryApi = (typeof MetricSummaryApi)[keyof typeof MetricSummaryApi]++export const MetricSummaryApi = {+ Total: 'total',+ Average: 'average',+ Latest: 'latest',+} as const++export type ResultCustomizationByApi = (typeof ResultCustomizationByApi)[keyof typeof ResultCustomizationByApi]++export const ResultCustomizationByApi = {+ Value: 'value',+ Position: 'position',+} as const++export type DataColorTokenApi = (typeof DataColorTokenApi)[keyof typeof DataColorTokenApi]++export const DataColorTokenApi = {+ Preset1: 'preset-1',+ Preset2: 'preset-2',+ Preset3: 'preset-3',+ Preset4: 'preset-4',+ Preset5: 'preset-5',+ Preset6: 'preset-6',+ Preset7: 'preset-7',+ Preset8: 'preset-8',+ Preset9: 'preset-9',+ Preset10: 'preset-10',+ Preset11: 'preset-11',+ Preset12: 'preset-12',+ Preset13: 'preset-13',+ Preset14: 'preset-14',+ Preset15: 'preset-15',+} as const++export interface ResultCustomizationByValueApi {+ assignmentBy?: 'value'+ color?: DataColorTokenApi | null+ customColor?: string | null+ hidden?: boolean | null+}++export interface ResultCustomizationByPositionApi {+ assignmentBy?: 'position'+ color?: DataColorTokenApi | null+ hidden?: boolean | null+}++export type YAxisScaleTypeApi = (typeof YAxisScaleTypeApi)[keyof typeof YAxisScaleTypeApi]++export const YAxisScaleTypeApi = {+ Log10: 'log10',+ Linear: 'linear',+} as const++/**+ * Customizations for the appearance of result datasets.+ */+export type TrendsFilterApiResultCustomizations =+ | { [key: string]: ResultCustomizationByValueApi }+ | { [key: string]: ResultCustomizationByPositionApi }+ | null++export interface TrendsFilterApi {+ /** Y-axis value formatter. Picks a human-friendly unit per value at render time without changing the underlying series values.+ *+ * - `numeric` (default): raw numbers, e.g. `1,234`.+ * - `duration`: values are in seconds; rendered as friendly units per value (`45s`, `2m 12s`, `1h 4m`). Use this whenever the series is in seconds (latency, session length, time-to-event) instead of dividing in `formula` to force minutes or hours.+ * - `duration_ms`: values are in milliseconds; rendered as friendly units (`850ms`, `1.5s`, `1m 4s`).+ * - `percentage`: values are already in the 0-100 range; appends `%`.+ * - `percentage_scaled`: values are a 0-1 ratio; multiplied and rendered as `%`.+ * - `currency`: values are in the project's base currency (set in project settings, defaults to USD); rendered with that currency symbol. For values pinned to a specific currency regardless of project base (e.g. `$ai_total_cost_usd` is always USD), use `aggregationAxisPrefix` instead.+ * - `short`: compact notation for large counts (`1.2K`, `3.4M`). */+ aggregationAxisFormat?: AggregationAxisFormatApi | null+ /** Literal suffix applied to every value (e.g. ` req`). Reserve for units that `aggregationAxisFormat` cannot express. Do not use ` mins`, ` s`, ` ms`, `%` etc. — pick the matching `aggregationAxisFormat` instead so the underlying values stay numerically correct for breakdowns, formulas, and alerts. Include any leading space yourself. */+ aggregationAxisPostfix?: string | null+ /** Literal prefix applied to every value (e.g. `$`). Use to pin a unit or currency symbol that does not depend on `aggregationAxisFormat` — for example, when values are denominated in a fixed currency regardless of the project's base currency. Include any trailing space yourself. */+ aggregationAxisPrefix?: string | null+ /** Render only annotations with this scope. Unset renders every scope. */+ annotationsScope?: AnnotationScopeApi | null+ breakdown_histogram_bin_count?: number | null+ /** Chart rendering style overrides (line shape). */+ chartStyle?: ChartStyleApi | null+ confidenceLevel?: number | null+ /** Maximum number of decimal places shown. 1 or 2 is usually right for percentages and currency. */+ decimalPlaces?: number | null+ /** detailed results table */+ detailedResultsAggregationType?: DetailedResultsAggregationTypeApi | null+ display?: ChartDisplayTypeApi | null+ excludeBoxPlotOutliers?: boolean | null+ formula?: string | null+ /** List of formulas with optional custom names. Takes precedence over formula/formulas if set. */+ formulaNodes?: TrendsFormulaNodeApi[] | null+ formulas?: string[] | null+ /** Goal Lines */+ goalLines?: GoalLineApi[] | null+ hiddenLegendIndexes?: number[] | null+ /** Ignored. Superseded by `dateRange.daysOfWeek`, which excludes the days from the query instead of only hiding their buckets. Still accepted so existing API clients keep working. */+ hideWeekends?: boolean | null+ /** Where the in-chart legend sits relative to the plot. Only applies to the in-chart legend. */+ legendPosition?: LegendPositionApi | null+ /** Metric display: change pill color when the metric decreased. Defaults to red. */+ metricChangeDecreaseColor?: string | null+ /** Metric display: change pill color when the metric increased. Defaults to green. */+ metricChangeIncreaseColor?: string | null+ /** Metric display: color the sparkline by whether the metric increased or decreased. */+ metricColorByDirection?: boolean | null+ /** Metric display: line color when the metric decreased. Defaults to red. */+ metricLineDecreaseColor?: string | null+ /** Metric display: line color when the metric increased. Defaults to green. */+ metricLineIncreaseColor?: string | null+ /** Show the period-over-period change pill on the Metric display. */+ metricShowChange?: boolean | null+ /** Metric display: which summary the resting headline shows — the period total, the average, or the latest point. Hovering the sparkline always shows the hovered point's value. Also drives the change pill: total/average compare against the previous period when "compare to previous" is on; latest compares first→last of the series. */+ metricSummary?: MetricSummaryApi | null+ minDecimalPlaces?: number | null+ movingAverageIntervals?: number | null+ /** Wether result datasets are associated by their values or by their order. */+ resultCustomizationBy?: ResultCustomizationByApi | null+ /** Customizations for the appearance of result datasets. */+ resultCustomizations?: TrendsFilterApiResultCustomizations+ showAlertThresholdLines?: boolean | null+ showAnnotations?: boolean | null+ showConfidenceIntervals?: boolean | null+ showLabelsOnSeries?: boolean | null+ showLegend?: boolean | null+ showMovingAverage?: boolean | null+ showMultipleYAxes?: boolean | null+ showPercentStackView?: boolean | null+ showTrendLines?: boolean | null+ showValuesOnSeries?: boolean | null+ smoothingIntervals?: number | null+ /** On the horizontal bar-value chart, stack a series' breakdown values into a single bar instead of rendering one bar per breakdown value. */+ stackBreakdownValues?: boolean | null+ /** Custom label rendered under the X axis. */+ xAxisLabel?: string | null+ /** Custom label rendered alongside the Y axis. */+ yAxisLabel?: string | null+ /** Pins the top of the y-axis; unset means automatic. Ignored in the same cases as `yAxisStartAtZero`, and when `yAxisMin` is not below it. */+ yAxisMax?: number | null+ /** Pins the bottom of the y-axis; unset means automatic. Ignored in the same cases as `yAxisStartAtZero`, while it is on, and when not below `yAxisMax`. */+ yAxisMin?: number | null+ yAxisScaleType?: YAxisScaleTypeApi | null+ /** Y-axis baseline. When false the axis floats to the data range instead of starting at zero. Ignored on bar displays (bars always draw from zero), on a logarithmic scale, and while showing percentages. */+ yAxisStartAtZero?: boolean | null+}++export interface TrendsQueryApi {+ /** Groups aggregation */+ aggregation_group_type_index?: number | null+ /** Breakdown of the events and actions */+ breakdownFilter?: BreakdownFilterApi | null+ /** Properties specific to the calendar heatmap display variant. Only consulted when `trendsFilter.display === ChartDisplayType.CalendarHeatmap`; ignored otherwise. */+ calendarHeatmapFilter?: CalendarHeatmapFilterApi | null+ /** Compare to date range */+ compareFilter?: CompareFilterApi | null+ /** Whether we should be comparing against a specific conversion goal */+ conversionGoal?: ActionConversionGoalApi | CustomEventConversionGoalApi | null+ /** Colors used in the insight's visualization */+ dataColorTheme?: number | null+ /** Date range for the query */+ dateRange?: DateRangeApi | null+ /** Exclude internal and test users by applying the respective filters */+ filterTestAccounts?: boolean | null+ /** Granularity of the response. Can be one of `hour`, `day`, `week` or `month` */+ interval?: IntervalTypeApi | null+ kind?: 'TrendsQuery'+ /** Live series for a Marketing cost trend when materialization coverage is incomplete. */+ marketingAnalyticsCostFallback?: MarketingAnalyticsCostFallbackApi | null+ /** Modifiers used when performing the query */+ modifiers?: HogQLQueryModifiersApi | null+ /** Property filters for all series */+ properties?:+ | (+ | EventPropertyFilterApi+ | PersonPropertyFilterApi+ | PersonMetadataPropertyFilterApi+ | ElementPropertyFilterApi+ | EventMetadataPropertyFilterApi+ | SessionPropertyFilterApi+ | CohortPropertyFilterApi+ | RecordingPropertyFilterApi+ | LogEntryPropertyFilterApi+ | GroupPropertyFilterApi+ | FeaturePropertyFilterApi+ | FlagPropertyFilterApi+ | HogQLPropertyFilterApi+ | EmptyPropertyFilterApi+ | DataWarehousePropertyFilterApi+ | DataWarehousePersonPropertyFilterApi+ | ErrorTrackingIssueFilterApi+ | LogPropertyFilterApi+ | MetricPropertyFilterApi+ | SpanPropertyFilterApi+ | RevenueAnalyticsPropertyFilterApi+ | AccountCustomPropertyFilterApi+ | WorkflowVariablePropertyFilterApi+ | BehavioralPropertyFilterApi+ )[]+ | PropertyGroupFilterApi+ | null+ response?: TrendsQueryResponseApi | null+ /** Sampling rate */+ samplingFactor?: number | null+ /**+ * Events and actions to include+ * @maxItems 200+ */+ series: (EventsNodeApi | ActionsNodeApi | DataWarehouseNodeApi | GroupNodeApi)[]+ /** Tags that will be added to the Query log comment */+ tags?: QueryLogTagsApi | null+ /** Properties specific to the trends insight */+ trendsFilter?: TrendsFilterApi | null+ /** version of the node, used for schema migrations */+ version?: number | null+}++export type BreakdownAttributionTypeApi = (typeof BreakdownAttributionTypeApi)[keyof typeof BreakdownAttributionTypeApi]++export const BreakdownAttributionTypeApi = {+ FirstTouch: 'first_touch',+ LastTouch: 'last_touch',+ AllEvents: 'all_events',+ Step: 'step',+} as const++export type FunnelExclusionEventsNodeApiResponse = { [key: string]: unknown } | null++export interface FunnelExclusionEventsNodeApi {+ custom_name?: string | null+ /** The event or `null` for all events. */+ event?: string | null+ /** Fixed properties in the query, can't be edited in the interface (e.g. scoping down by person) */+ fixedProperties?:+ | (+ | EventPropertyFilterApi+ | PersonPropertyFilterApi+ | PersonMetadataPropertyFilterApi+ | ElementPropertyFilterApi+ | EventMetadataPropertyFilterApi+ | SessionPropertyFilterApi+ | CohortPropertyFilterApi+ | RecordingPropertyFilterApi+ | LogEntryPropertyFilterApi+ | GroupPropertyFilterApi+ | FeaturePropertyFilterApi+ | FlagPropertyFilterApi+ | HogQLPropertyFilterApi+ | EmptyPropertyFilterApi+ | DataWarehousePropertyFilterApi+ | DataWarehousePersonPropertyFilterApi+ | ErrorTrackingIssueFilterApi+ | LogPropertyFilterApi+ | MetricPropertyFilterApi+ | SpanPropertyFilterApi+ | RevenueAnalyticsPropertyFilterApi+ | AccountCustomPropertyFilterApi+ | WorkflowVariablePropertyFilterApi+ | BehavioralPropertyFilterApi+ )[]+ | null+ funnelFromStep: number+ funnelToStep: number+ kind?: 'EventsNode'+ limit?: number | null+ math?:+ | BaseMathTypeApi+ | FunnelMathTypeApi+ | PropertyMathTypeApi+ | CountPerActorMathTypeApi+ | GroupMathTypeApi+ | ExperimentMetricMathTypeApi+ | CalendarHeatmapMathTypeApi+ | 'hogql'+ | null+ math_group_type_index?: MathGroupTypeIndexApi | null+ math_hogql?: string | null+ math_multiplier?: number | null+ math_property?: string | null+ math_property_revenue_currency?: RevenueCurrencyPropertyConfigApi | null+ math_property_type?: string | null+ name?: string | null+ optionalInFunnel?: boolean | null+ /** Columns to order by */+ orderBy?: string[] | null+ /** Properties configurable in the interface */+ properties?:+ | (+ | EventPropertyFilterApi+ | PersonPropertyFilterApi+ | PersonMetadataPropertyFilterApi+ | ElementPropertyFilterApi+ | EventMetadataPropertyFilterApi+ | SessionPropertyFilterApi+ | CohortPropertyFilterApi+ | RecordingPropertyFilterApi+ | LogEntryPropertyFilterApi+ | GroupPropertyFilterApi+ | FeaturePropertyFilterApi+ | FlagPropertyFilterApi+ | HogQLPropertyFilterApi+ | EmptyPropertyFilterApi+ | DataWarehousePropertyFilterApi+ | DataWarehousePersonPropertyFilterApi+ | ErrorTrackingIssueFilterApi+ | LogPropertyFilterApi+ | MetricPropertyFilterApi+ | SpanPropertyFilterApi+ | RevenueAnalyticsPropertyFilterApi+ | AccountCustomPropertyFilterApi+ | WorkflowVariablePropertyFilterApi+ | BehavioralPropertyFilterApi+ )[]+ | null+ response?: FunnelExclusionEventsNodeApiResponse+ /** version of the node, used for schema migrations */+ version?: number | null+}++export type FunnelExclusionActionsNodeApiResponse = { [key: string]: unknown } | null++export interface FunnelExclusionActionsNodeApi {+ custom_name?: string | null+ /** Fixed properties in the query, can't be edited in the interface (e.g. scoping down by person) */+ fixedProperties?:+ | (+ | EventPropertyFilterApi+ | PersonPropertyFilterApi+ | PersonMetadataPropertyFilterApi+ | ElementPropertyFilterApi+ | EventMetadataPropertyFilterApi+ | SessionPropertyFilterApi+ | CohortPropertyFilterApi+ | RecordingPropertyFilterApi+ | LogEntryPropertyFilterApi+ | GroupPropertyFilterApi+ | FeaturePropertyFilterApi+ | FlagPropertyFilterApi+ | HogQLPropertyFilterApi+ | EmptyPropertyFilterApi+ | DataWarehousePropertyFilterApi+ | DataWarehousePersonPropertyFilterApi+ | ErrorTrackingIssueFilterApi+ | LogPropertyFilterApi+ | MetricPropertyFilterApi+ | SpanPropertyFilterApi+ | RevenueAnalyticsPropertyFilterApi+ | AccountCustomPropertyFilterApi+ | WorkflowVariablePropertyFilterApi+ | BehavioralPropertyFilterApi+ )[]+ | null+ funnelFromStep: number+ funnelToStep: number+ id: number+ kind?: 'ActionsNode'+ math?:+ | BaseMathTypeApi+ | FunnelMathTypeApi+ | PropertyMathTypeApi+ | CountPerActorMathTypeApi+ | GroupMathTypeApi+ | ExperimentMetricMathTypeApi+ | CalendarHeatmapMathTypeApi+ | 'hogql'+ | null+ math_group_type_index?: MathGroupTypeIndexApi | null+ math_hogql?: string | null+ math_multiplier?: number | null+ math_property?: string | null+ math_property_revenue_currency?: RevenueCurrencyPropertyConfigApi | null+ math_property_type?: string | null+ name?: string | null+ optionalInFunnel?: boolean | null+ /** Properties configurable in the interface */+ properties?:+ | (+ | EventPropertyFilterApi+ | PersonPropertyFilterApi+ | PersonMetadataPropertyFilterApi+ | ElementPropertyFilterApi+ | EventMetadataPropertyFilterApi+ | SessionPropertyFilterApi+ | CohortPropertyFilterApi+ | RecordingPropertyFilterApi+ | LogEntryPropertyFilterApi+ | GroupPropertyFilterApi+ | FeaturePropertyFilterApi+ | FlagPropertyFilterApi+ | HogQLPropertyFilterApi+ | EmptyPropertyFilterApi+ | DataWarehousePropertyFilterApi+ | DataWarehousePersonPropertyFilterApi+ | ErrorTrackingIssueFilterApi+ | LogPropertyFilterApi+ | MetricPropertyFilterApi+ | SpanPropertyFilterApi+ | RevenueAnalyticsPropertyFilterApi+ | AccountCustomPropertyFilterApi+ | WorkflowVariablePropertyFilterApi+ | BehavioralPropertyFilterApi+ )[]+ | null+ response?: FunnelExclusionActionsNodeApiResponse+ /** version of the node, used for schema migrations */+ version?: number | null+}++export type StepOrderValueApi = (typeof StepOrderValueApi)[keyof typeof StepOrderValueApi]++export const StepOrderValueApi = {+ Strict: 'strict',+ Unordered: 'unordered',+ Ordered: 'ordered',+} as const++export type FunnelStepReferenceApi = (typeof FunnelStepReferenceApi)[keyof typeof FunnelStepReferenceApi]++export const FunnelStepReferenceApi = {+ Total: 'total',+ Previous: 'previous',+} as const++export type FunnelVizTypeApi = (typeof FunnelVizTypeApi)[keyof typeof FunnelVizTypeApi]++export const FunnelVizTypeApi = {+ Steps: 'steps',+ TimeToConvert: 'time_to_convert',+ Trends: 'trends',+ Flow: 'flow',+} as const++export type FunnelConversionWindowTimeUnitApi =+ (typeof FunnelConversionWindowTimeUnitApi)[keyof typeof FunnelConversionWindowTimeUnitApi]++export const FunnelConversionWindowTimeUnitApi = {+ Second: 'second',+ Minute: 'minute',+ Hour: 'hour',+ Day: 'day',+ Week: 'week',+ Month: 'month',+} as const++export type FunnelLayoutApi = (typeof FunnelLayoutApi)[keyof typeof FunnelLayoutApi]++export const FunnelLayoutApi = {+ Horizontal: 'horizontal',+ Vertical: 'vertical',+} as const++/**+ * Customizations for the appearance of result datasets.+ */+export type FunnelsFilterApiResultCustomizations = { [key: string]: ResultCustomizationByValueApi } | null++export interface FunnelsFilterApi {+ /** Render only annotations with this scope. Only applies to historical-trends funnels. */+ annotationsScope?: AnnotationScopeApi | null+ binCount?: number | null+ breakdownAttributionType?: BreakdownAttributionTypeApi | null+ breakdownAttributionValue?: number | null+ /** Breakdown table sorting. Format: 'column_key' or '-column_key' (descending) */+ breakdownSorting?: string | null+ /** Chart rendering style overrides (line shape). Only applies to historical-trends funnels. */+ chartStyle?: ChartStyleApi | null+ /** For data warehouse based funnel insights when the aggregation target can't be mapped to persons or groups. */+ customAggregationTarget?: boolean | null+ exclusions?: (FunnelExclusionEventsNodeApi | FunnelExclusionActionsNodeApi)[] | null+ funnelAggregateByHogQL?: string | null+ funnelFromStep?: number | null+ funnelOrderType?: StepOrderValueApi | null+ funnelStepReference?: FunnelStepReferenceApi | null+ /** To select the range of steps for trends & time to convert funnels, 0-indexed */+ funnelToStep?: number | null+ funnelVizType?: FunnelVizTypeApi | null+ funnelWindowInterval?: number | null+ funnelWindowIntervalUnit?: FunnelConversionWindowTimeUnitApi | null+ /** Goal Lines */+ goalLines?: GoalLineApi[] | null+ hiddenLegendBreakdowns?: string[] | null+ /** Trends only: hide periods whose conversion window has not fully elapsed yet, so the recent tail of the trend isn't dragged down by entrants who still have time to convert. */+ hideIncompleteConversionWindowPeriods?: boolean | null+ layout?: FunnelLayoutApi | null+ /** Where the in-chart legend sits relative to the plot. Only applies to the in-chart legend. */+ legendPosition?: LegendPositionApi | null+ /** Customizations for the appearance of result datasets. */+ resultCustomizations?: FunnelsFilterApiResultCustomizations+ /** Whether to render annotations on the chart. Only applies to historical-trends funnels. */+ showAnnotations?: boolean | null+ /** Whether to show a legend describing the series. The legend only renders when the funnel has multiple series. Only applies to historical-trends funnels. */+ showLegend?: boolean | null+ /** Display linear regression trend lines on the chart (only for historical trends viz) */+ showTrendLines?: boolean | null+ showValuesOnSeries?: boolean | null+ useUdf?: boolean | null+}++export interface FunnelsQueryResponseApi {+ /** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */+ error?: string | null+ /** Generated HogQL query. */+ hogql?: string | null+ /** Modifiers used when performing the query */+ modifiers?: HogQLQueryModifiersApi | null+ /** Query status indicates whether next to the provided data, a query is still running. */+ query_status?: QueryStatusApi | null+ /** The resolved previous/comparison period date range, when comparing against another period */+ resolved_compare_date_range?: ResolvedDateRangeResponseApi | null+ /** The date range used for the query */+ resolved_date_range?: ResolvedDateRangeResponseApi | null+ results: unknown+ /** Measured timings for different parts of the query generation process */+ timings?: QueryTimingApi[] | null+ /** Median total conversion time across all completers, computed breakdown-agnostically for the Steps viz header. */+ total_median_conversion_time?: number | null+ /** Connector-synced data warehouse sources referenced by this query, if any. */+ used_data_warehouse_sources?: DataWarehouseSourceUsageApi[] | null+ /** Warnings about data warehouse sources referenced by the query whose latest sync failed, is paused, hit a billing limit, or is otherwise stale. Results may not reflect current source data. Accumulated across every HogQL execution that contributes to this response — so insights backed by warehouse tables (Trends, Funnels, etc.) receive the same warnings as raw HogQL queries. Also carries access control warnings when a system-table query filters out objects the user can't access. */+ warnings?: (DataWarehouseSyncWarningApi | AccessControlFilterWarningApi)[] | null+}++export type FunnelsDataWarehouseNodeApiResponse = { [key: string]: unknown } | null++export interface FunnelsDataWarehouseNodeApi {+ aggregation_target_field: string+ custom_name?: string | null+ dw_source_type?: string | null+ /** Fixed properties in the query, can't be edited in the interface (e.g. scoping down by person) */+ fixedProperties?:+ | (+ | EventPropertyFilterApi+ | PersonPropertyFilterApi+ | PersonMetadataPropertyFilterApi+ | ElementPropertyFilterApi+ | EventMetadataPropertyFilterApi+ | SessionPropertyFilterApi+ | CohortPropertyFilterApi+ | RecordingPropertyFilterApi+ | LogEntryPropertyFilterApi+ | GroupPropertyFilterApi+ | FeaturePropertyFilterApi+ | FlagPropertyFilterApi+ | HogQLPropertyFilterApi+ | EmptyPropertyFilterApi+ | DataWarehousePropertyFilterApi+ | DataWarehousePersonPropertyFilterApi+ | ErrorTrackingIssueFilterApi+ | LogPropertyFilterApi+ | MetricPropertyFilterApi+ | SpanPropertyFilterApi+ | RevenueAnalyticsPropertyFilterApi+ | AccountCustomPropertyFilterApi+ | WorkflowVariablePropertyFilterApi+ | BehavioralPropertyFilterApi+ )[]+ | null+ id: string+ id_field: string+ kind?: 'FunnelsDataWarehouseNode'+ math?:+ | BaseMathTypeApi+ | FunnelMathTypeApi+ | PropertyMathTypeApi+ | CountPerActorMathTypeApi+ | GroupMathTypeApi+ | ExperimentMetricMathTypeApi+ | CalendarHeatmapMathTypeApi+ | 'hogql'+ | null+ math_group_type_index?: MathGroupTypeIndexApi | null+ math_hogql?: string | null+ math_multiplier?: number | null+ math_property?: string | null+ math_property_revenue_currency?: RevenueCurrencyPropertyConfigApi | null+ math_property_type?: string | null+ name?: string | null+ optionalInFunnel?: boolean | null+ /** Properties configurable in the interface */+ properties?:+ | (+ | EventPropertyFilterApi+ | PersonPropertyFilterApi+ | PersonMetadataPropertyFilterApi+ | ElementPropertyFilterApi+ | EventMetadataPropertyFilterApi+ | SessionPropertyFilterApi+ | CohortPropertyFilterApi+ | RecordingPropertyFilterApi+ | LogEntryPropertyFilterApi+ | GroupPropertyFilterApi+ | FeaturePropertyFilterApi+ | FlagPropertyFilterApi+ | HogQLPropertyFilterApi+ | EmptyPropertyFilterApi+ | DataWarehousePropertyFilterApi+ | DataWarehousePersonPropertyFilterApi+ | ErrorTrackingIssueFilterApi+ | LogPropertyFilterApi+ | MetricPropertyFilterApi+ | SpanPropertyFilterApi+ | RevenueAnalyticsPropertyFilterApi+ | AccountCustomPropertyFilterApi+ | WorkflowVariablePropertyFilterApi+ | BehavioralPropertyFilterApi+ )[]+ | null+ response?: FunnelsDataWarehouseNodeApiResponse+ table_name: string+ timestamp_field: string+ /** version of the node, used for schema migrations */+ version?: number | null+}++export interface FunnelsQueryApi {+ /** Groups aggregation */+ aggregation_group_type_index?: number | null+ /** Breakdown of the events and actions */+ breakdownFilter?: BreakdownFilterApi | null+ /** Compare to date range */+ compareFilter?: CompareFilterApi | null+ /** Colors used in the insight's visualization */+ dataColorTheme?: number | null+ /** Date range for the query */+ dateRange?: DateRangeApi | null+ /** Exclude internal and test users by applying the respective filters */+ filterTestAccounts?: boolean | null+ /** Properties specific to the funnels insight */+ funnelsFilter?: FunnelsFilterApi | null+ /** Granularity of the response. Can be one of `hour`, `day`, `week` or `month` */+ interval?: IntervalTypeApi | null+ kind?: 'FunnelsQuery'+ /** Modifiers used when performing the query */+ modifiers?: HogQLQueryModifiersApi | null+ /** Property filters for all series */+ properties?:+ | (+ | EventPropertyFilterApi+ | PersonPropertyFilterApi+ | PersonMetadataPropertyFilterApi+ | ElementPropertyFilterApi+ | EventMetadataPropertyFilterApi+ | SessionPropertyFilterApi+ | CohortPropertyFilterApi+ | RecordingPropertyFilterApi+ | LogEntryPropertyFilterApi+ | GroupPropertyFilterApi+ | FeaturePropertyFilterApi+ | FlagPropertyFilterApi+ | HogQLPropertyFilterApi+ | EmptyPropertyFilterApi+ | DataWarehousePropertyFilterApi+ | DataWarehousePersonPropertyFilterApi+ | ErrorTrackingIssueFilterApi+ | LogPropertyFilterApi+ | MetricPropertyFilterApi+ | SpanPropertyFilterApi+ | RevenueAnalyticsPropertyFilterApi+ | AccountCustomPropertyFilterApi+ | WorkflowVariablePropertyFilterApi+ | BehavioralPropertyFilterApi+ )[]+ | PropertyGroupFilterApi+ | null+ response?: FunnelsQueryResponseApi | null+ /** Sampling rate */+ samplingFactor?: number | null+ /** Events and actions to include */+ series: (EventsNodeApi | ActionsNodeApi | FunnelsDataWarehouseNodeApi | GroupNodeApi)[]+ /** Tags that will be added to the Query log comment */+ tags?: QueryLogTagsApi | null+ /** version of the node, used for schema migrations */+ version?: number | null+}++export interface RetentionValueApi {+ aggregation_value?: number | null+ count: number+ label?: string | null+}++export interface RetentionResultApi {+ /** Optional breakdown value for retention cohorts */+ breakdown_value?: string | number | null+ date: string+ label: string+ values: RetentionValueApi[]+}++export interface RetentionQueryResponseApi {+ /** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */+ error?: string | null+ /** Generated HogQL query. */+ hogql?: string | null+ /** Modifiers used when performing the query */+ modifiers?: HogQLQueryModifiersApi | null+ /** Query status indicates whether next to the provided data, a query is still running. */+ query_status?: QueryStatusApi | null+ /** The resolved previous/comparison period date range, when comparing against another period */+ resolved_compare_date_range?: ResolvedDateRangeResponseApi | null+ /** The date range used for the query */+ resolved_date_range?: ResolvedDateRangeResponseApi | null+ results: RetentionResultApi[]+ /** Measured timings for different parts of the query generation process */+ timings?: QueryTimingApi[] | null+ /** Connector-synced data warehouse sources referenced by this query, if any. */+ used_data_warehouse_sources?: DataWarehouseSourceUsageApi[] | null+ /** Warnings about data warehouse sources referenced by the query whose latest sync failed, is paused, hit a billing limit, or is otherwise stale. Results may not reflect current source data. Accumulated across every HogQL execution that contributes to this response — so insights backed by warehouse tables (Trends, Funnels, etc.) receive the same warnings as raw HogQL queries. Also carries access control warnings when a system-table query filters out objects the user can't access. */+ warnings?: (DataWarehouseSyncWarningApi | AccessControlFilterWarningApi)[] | null+}++export type AggregationPropertyTypeApi = (typeof AggregationPropertyTypeApi)[keyof typeof AggregationPropertyTypeApi]++export const AggregationPropertyTypeApi = {+ Event: 'event',+ Person: 'person',+ DataWarehouse: 'data_warehouse',+} as const++export type AggregationTypeApi = (typeof AggregationTypeApi)[keyof typeof AggregationTypeApi]++export const AggregationTypeApi = {+ Count: 'count',+ Sum: 'sum',+ Avg: 'avg',+} as const++export type RetentionDashboardDisplayTypeApi =+ (typeof RetentionDashboardDisplayTypeApi)[keyof typeof RetentionDashboardDisplayTypeApi]++export const RetentionDashboardDisplayTypeApi = {+ TableOnly: 'table_only',+ GraphOnly: 'graph_only',+ All: 'all',+} as const++export type MeanRetentionCalculationApi = (typeof MeanRetentionCalculationApi)[keyof typeof MeanRetentionCalculationApi]++export const MeanRetentionCalculationApi = {+ Simple: 'simple',+ Weighted: 'weighted',+ None: 'none',+} as const++export type RetentionPeriodApi = (typeof RetentionPeriodApi)[keyof typeof RetentionPeriodApi]++export const RetentionPeriodApi = {+ Hour: 'Hour',+ Day: 'Day',+ Week: 'Week',+ Month: 'Month',+} as const++export type RetentionReferenceApi = (typeof RetentionReferenceApi)[keyof typeof RetentionReferenceApi]++export const RetentionReferenceApi = {+ Total: 'total',+ Previous: 'previous',+} as const++export type RetentionTypeApi = (typeof RetentionTypeApi)[keyof typeof RetentionTypeApi]++export const RetentionTypeApi = {+ RetentionRecurring: 'retention_recurring',+ RetentionFirstTime: 'retention_first_time',+ RetentionFirstEverOccurrence: 'retention_first_ever_occurrence',+} as const++export type RetentionEntityKindApi = (typeof RetentionEntityKindApi)[keyof typeof RetentionEntityKindApi]++export const RetentionEntityKindApi = {+ ActionsNode: 'ActionsNode',+ EventsNode: 'EventsNode',+} as const++export type EntityTypeApi = (typeof EntityTypeApi)[keyof typeof EntityTypeApi]++export const EntityTypeApi = {+ Actions: 'actions',+ Events: 'events',+ DataWarehouse: 'data_warehouse',+ NewEntity: 'new_entity',+ Groups: 'groups',+} as const++export interface RetentionEntityApi {+ /** Data warehouse field used as the actor identifier */+ aggregation_target_field?: string | null+ custom_name?: string | null+ id?: string | number | null+ kind?: RetentionEntityKindApi | null+ name?: string | null+ order?: number | null+ /** filters on the event */+ properties?:+ | (+ | EventPropertyFilterApi+ | PersonPropertyFilterApi+ | PersonMetadataPropertyFilterApi+ | ElementPropertyFilterApi+ | EventMetadataPropertyFilterApi+ | SessionPropertyFilterApi+ | CohortPropertyFilterApi+ | RecordingPropertyFilterApi+ | LogEntryPropertyFilterApi+ | GroupPropertyFilterApi+ | FeaturePropertyFilterApi+ | FlagPropertyFilterApi+ | HogQLPropertyFilterApi+ | EmptyPropertyFilterApi+ | DataWarehousePropertyFilterApi+ | DataWarehousePersonPropertyFilterApi+ | ErrorTrackingIssueFilterApi+ | LogPropertyFilterApi+ | MetricPropertyFilterApi+ | SpanPropertyFilterApi+ | RevenueAnalyticsPropertyFilterApi+ | AccountCustomPropertyFilterApi+ | WorkflowVariablePropertyFilterApi+ | BehavioralPropertyFilterApi+ )[]+ | null+ /** Data warehouse table name */+ table_name?: string | null+ /** Data warehouse timestamp field */+ timestamp_field?: string | null+ type?: EntityTypeApi | null+ uuid?: string | null+}++export type TimeWindowModeApi = (typeof TimeWindowModeApi)[keyof typeof TimeWindowModeApi]++export const TimeWindowModeApi = {+ StrictCalendarDates: 'strict_calendar_dates',+ '24HourWindows': '24_hour_windows',+} as const++export interface RetentionFilterApi {+ /** The property to aggregate when aggregationType is sum or avg */+ aggregationProperty?: string | null+ /** The type of property to aggregate on (event, person or data_warehouse). Defaults to event. */+ aggregationPropertyType?: AggregationPropertyTypeApi | null+ /** The aggregation type to use for retention */+ aggregationType?: AggregationTypeApi | null+ /** Chart rendering style overrides (line shape). */+ chartStyle?: ChartStyleApi | null+ /** Starting index used when labeling cohort columns (e.g. 0 for D0/D1/D2, 1 for D1/D2/D3). Display-only — does not affect retention calculations. */+ cohortLabelStartIndex?: number | null+ cumulative?: boolean | null+ /** For data warehouse based retention insights when the aggregation target can't be mapped to persons or groups. */+ customAggregationTarget?: boolean | null+ dashboardDisplay?: RetentionDashboardDisplayTypeApi | null+ /** controls the display of the retention graph */+ display?: ChartDisplayTypeApi | null+ goalLines?: GoalLineApi[] | null+ meanRetentionCalculation?: MeanRetentionCalculationApi | null+ minimumOccurrences?: number | null+ period?: RetentionPeriodApi | null+ /** Custom brackets for retention calculations */+ retentionCustomBrackets?: number[] | null+ /** Whether retention is with regard to initial cohort size, or that of the previous period. */+ retentionReference?: RetentionReferenceApi | null+ retentionType?: RetentionTypeApi | null+ returningEntity?: RetentionEntityApi | null+ /** The selected interval to display across all cohorts (null = show all intervals for each cohort) */+ selectedInterval?: number | null+ /** Draw the mean across cohorts as one line on the retention graph. */+ showMeanLine?: boolean | null+ showTrendLines?: boolean | null+ targetEntity?: RetentionEntityApi | null+ /** The time window mode to use for retention calculations */+ timeWindowMode?: TimeWindowModeApi | null+ totalIntervals?: number | null+}++export interface RetentionQueryApi {+ /** Groups aggregation */+ aggregation_group_type_index?: number | null+ /** Breakdown of the events and actions */+ breakdownFilter?: BreakdownFilterApi | null+ /** Colors used in the insight's visualization */+ dataColorTheme?: number | null+ /** Date range for the query */+ dateRange?: DateRangeApi | null+ /** Exclude internal and test users by applying the respective filters */+ filterTestAccounts?: boolean | null+ kind?: 'RetentionQuery'+ /** Modifiers used when performing the query */+ modifiers?: HogQLQueryModifiersApi | null+ /** Property filters for all series */+ properties?:+ | (+ | EventPropertyFilterApi+ | PersonPropertyFilterApi+ | PersonMetadataPropertyFilterApi+ | ElementPropertyFilterApi+ | EventMetadataPropertyFilterApi+ | SessionPropertyFilterApi+ | CohortPropertyFilterApi+ | RecordingPropertyFilterApi+ | LogEntryPropertyFilterApi+ | GroupPropertyFilterApi+ | FeaturePropertyFilterApi+ | FlagPropertyFilterApi+ | HogQLPropertyFilterApi+ | EmptyPropertyFilterApi+ | DataWarehousePropertyFilterApi+ | DataWarehousePersonPropertyFilterApi+ | ErrorTrackingIssueFilterApi+ | LogPropertyFilterApi+ | MetricPropertyFilterApi+ | SpanPropertyFilterApi+ | RevenueAnalyticsPropertyFilterApi+ | AccountCustomPropertyFilterApi+ | WorkflowVariablePropertyFilterApi+ | BehavioralPropertyFilterApi+ )[]+ | PropertyGroupFilterApi+ | null+ response?: RetentionQueryResponseApi | null+ /** Properties specific to the retention insight */+ retentionFilter: RetentionFilterApi+ /** Sampling rate */+ samplingFactor?: number | null+ /** Tags that will be added to the Query log comment */+ tags?: QueryLogTagsApi | null+ /** version of the node, used for schema migrations */+ version?: number | null+}++export type FunnelPathTypeApi = (typeof FunnelPathTypeApi)[keyof typeof FunnelPathTypeApi]++export const FunnelPathTypeApi = {+ FunnelPathBeforeStep: 'funnel_path_before_step',+ FunnelPathBetweenSteps: 'funnel_path_between_steps',+ FunnelPathAfterStep: 'funnel_path_after_step',+} as const++export interface FunnelPathsFilterApi {+ funnelPathType?: FunnelPathTypeApi | null+ funnelSource: FunnelsQueryApi+ funnelStep?: number | null+}++export type PathTypeApi = (typeof PathTypeApi)[keyof typeof PathTypeApi]++export const PathTypeApi = {+ Pageview: '$pageview',+ Screen: '$screen',+ CustomEvent: 'custom_event',+ Hogql: 'hogql',+} as const++export interface PathCleaningFilterApi {+ /** The replacement for the matched path. Use angle-bracket placeholders (`<id>`, `<uuid>`, `<slug>`) by convention, or reuse a capture group from the regex with ClickHouse `replaceRegexpAll` replacement syntax: `\1` to `\9` for a group and `\0` for the whole match. */+ alias?: string | null+ order?: number | null+ regex?: string | null+}++export interface PathsFilterApi {+ edgeLimit?: number | null+ endPoint?: string | null+ excludeEvents?: string[] | null+ includeEventTypes?: PathTypeApi[] | null+ localPathCleaningFilters?: PathCleaningFilterApi[] | null+ maxEdgeWeight?: number | null+ minEdgeWeight?: number | null+ /** Relevant only within actors query */+ pathDropoffKey?: string | null+ /** Relevant only within actors query */+ pathEndKey?: string | null+ pathGroupings?: string[] | null+ pathReplacements?: boolean | null+ /** Relevant only within actors query */+ pathStartKey?: string | null+ pathsHogQLExpression?: string | null+ showFullUrls?: boolean | null+ startPoint?: string | null+ stepLimit?: number | null+ /** Remove the query string from page view URLs, so pages that differ only in query parameters become one path item */+ stripQueryString?: boolean | null+}++export interface PathsLinkApi {+ average_conversion_time: number+ source: string+ target: string+ value: number+}++export interface PathsQueryResponseApi {+ /** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */+ error?: string | null+ /** Generated HogQL query. */+ hogql?: string | null+ /** Modifiers used when performing the query */+ modifiers?: HogQLQueryModifiersApi | null+ /** Query status indicates whether next to the provided data, a query is still running. */+ query_status?: QueryStatusApi | null+ /** The resolved previous/comparison period date range, when comparing against another period */+ resolved_compare_date_range?: ResolvedDateRangeResponseApi | null+ /** The date range used for the query */+ resolved_date_range?: ResolvedDateRangeResponseApi | null+ results: PathsLinkApi[]+ /** Measured timings for different parts of the query generation process */+ timings?: QueryTimingApi[] | null+ /** Connector-synced data warehouse sources referenced by this query, if any. */+ used_data_warehouse_sources?: DataWarehouseSourceUsageApi[] | null+ /** Warnings about data warehouse sources referenced by the query whose latest sync failed, is paused, hit a billing limit, or is otherwise stale. Results may not reflect current source data. Accumulated across every HogQL execution that contributes to this response — so insights backed by warehouse tables (Trends, Funnels, etc.) receive the same warnings as raw HogQL queries. Also carries access control warnings when a system-table query filters out objects the user can't access. */+ warnings?: (DataWarehouseSyncWarningApi | AccessControlFilterWarningApi)[] | null+}++export interface PathsQueryApi {+ /** Groups aggregation */+ aggregation_group_type_index?: number | null+ /** Colors used in the insight's visualization */+ dataColorTheme?: number | null+ /** Date range for the query */+ dateRange?: DateRangeApi | null+ /** Exclude internal and test users by applying the respective filters */+ filterTestAccounts?: boolean | null+ /** Used for displaying paths in relation to funnel steps. */+ funnelPathsFilter?: FunnelPathsFilterApi | null+ kind?: 'PathsQuery'+ /** Modifiers used when performing the query */+ modifiers?: HogQLQueryModifiersApi | null+ /** Properties specific to the paths insight */+ pathsFilter: PathsFilterApi+ /** Property filters for all series */+ properties?:+ | (+ | EventPropertyFilterApi+ | PersonPropertyFilterApi+ | PersonMetadataPropertyFilterApi+ | ElementPropertyFilterApi+ | EventMetadataPropertyFilterApi+ | SessionPropertyFilterApi+ | CohortPropertyFilterApi+ | RecordingPropertyFilterApi+ | LogEntryPropertyFilterApi+ | GroupPropertyFilterApi+ | FeaturePropertyFilterApi+ | FlagPropertyFilterApi+ | HogQLPropertyFilterApi+ | EmptyPropertyFilterApi+ | DataWarehousePropertyFilterApi+ | DataWarehousePersonPropertyFilterApi+ | ErrorTrackingIssueFilterApi+ | LogPropertyFilterApi+ | MetricPropertyFilterApi+ | SpanPropertyFilterApi+ | RevenueAnalyticsPropertyFilterApi+ | AccountCustomPropertyFilterApi+ | WorkflowVariablePropertyFilterApi+ | BehavioralPropertyFilterApi+ )[]+ | PropertyGroupFilterApi+ | null+ response?: PathsQueryResponseApi | null+ /** Sampling rate */+ samplingFactor?: number | null+ /** Tags that will be added to the Query log comment */+ tags?: QueryLogTagsApi | null+ /** version of the node, used for schema migrations */+ version?: number | null+}++export interface PathsV2ItemApi {+ /** Event of the step source this item belongs to. */+ event: string+ /** Label value from the source's naming property, after path cleaning. An empty string when the property is missing on the event. Null for sources without a naming property. */+ label?: string | null+}++export type PathsV2AnchorTypeApi = (typeof PathsV2AnchorTypeApi)[keyof typeof PathsV2AnchorTypeApi]++export const PathsV2AnchorTypeApi = {+ Start: 'start',+ End: 'end',+} as const++export interface PathsV2AnchorApi {+ /** The path item the chart anchors on. Its event must be one of the step sources. */+ item: PathsV2ItemApi+ /** `start` runs each actor's single sequence forward from the anchor item; `end` runs it up to the anchor item. Either way the anchor is the grid's single 100% node. */+ type: PathsV2AnchorTypeApi+}++export interface PathsV2StepSourceApi {+ /** Name of the event this source matches. */+ event: string+ /** Event property whose value labels the path item, e.g. `$pathname` for pageviews. Team path cleaning rules are applied to the value. Without a naming property, the event itself is the path item. */+ namingProperty?: string | null+}++export interface PathsV2FilterApi {+ /** Anchor selecting anchored mode. When set, each actor contributes exactly one sequence bounded by the conversion window, so every displayed segment equals a plain funnel. Absent selects open mode, which splits an actor's events into journeys on the inactivity gap instead. */+ anchor?: PathsV2AnchorApi | null+ /** Apply the team's path cleaning rules to naming property values before they become path items. */+ applyTeamPathCleaning?: boolean | null+ /** Merge immediate repeats of the same path item within a journey. */+ collapseRepeats?: boolean | null+ /** Anchored mode's single conversion window W, anchored at the anchor and reused verbatim as the emitted funnel's window. Bounds per unit are validated server-side against CONVERSION_WINDOW_INTERVAL_BOUNDS, the same funnel conversion window bounds as the gap. */+ conversionWindowInterval?: number | null+ conversionWindowIntervalUnit?: FunnelConversionWindowTimeUnitApi | null+ /** Path items dropped from the item universe: events deriving to one of these items are ignored as if their event were not a step source, on both the paths side and the "view as funnel" side. */+ excludedItems?: PathsV2ItemApi[] | null+ /** Inactivity gap that splits an actor's events into journeys. Bounds per unit are validated server-side against CONVERSION_WINDOW_INTERVAL_BOUNDS, the funnel conversion window bounds. */+ gapInterval?: number | null+ gapIntervalUnit?: FunnelConversionWindowTimeUnitApi | null+ /** Path cleaning rules for this insight only, applied after the team's rules. */+ localPathCleaningFilters?: PathCleaningFilterApi[] | null+ /** Number of path item rows per step; items beyond this go into the "other" row. */+ maxRowsPerStep?: number | null+ /** Number of journey steps (columns) shown. */+ maxSteps?: number | null+ /** Step sources defining which events can become path items. Defaults to the pageviews preset: `$pageview` named by `$pathname`. */+ stepSources?: PathsV2StepSourceApi[] | null+}++export interface PathsV2EdgeApi {+ /** Unique actors who transition from source to target at any step of any of their whole journeys, the position-free count behind "went source → target at any step". Equals the two-step item-strict funnel's converted count. Only set in open mode on edges between two named items. */+ anyStepCount?: number | null+ /** Unique actors with a journey that transitions from source to target between these steps. */+ count: number+ /** Source path item, or null for the source column's "other" row. */+ source: PathsV2ItemApi | null+ /** 0-based step index of the source column; the target sits at `stepIndex + 1`. */+ stepIndex: number+ /** Target path item, or null for the target column's "other" row. */+ target: PathsV2ItemApi | null+}++export interface PathsV2PrefixApi {+ /** Unique actors whose anchored sequence begins with exactly these items. */+ count: number+ /** The chain's path items in order, starting at the anchor. */+ items: PathsV2ItemApi[]+}++export interface PathsV2RowApi {+ /** Unique actors with a journey whose item at this step is this path item. */+ count: number+ item: PathsV2ItemApi+}++export interface PathsV2StepApi {+ /** Unique actors whose journey ends at this step. */+ dropOffCount: number+ /** Unique actors at this step whose path item is beyond the top rows. */+ otherCount: number+ /** Top path items at this step, ordered by unique-actor count descending. */+ rows: PathsV2RowApi[]+ /** 0-based step index (column) in the journey grid. */+ stepIndex: number+}++export interface PathsV2ResultsApi {+ edges: PathsV2EdgeApi[]+ /** Concrete anchored chains with per-chain unique-actor counts, ordered by descending count. Empty in open mode; in anchored mode it carries the counts the hover funnel preview reads per chain. Only chains the grid displays in full are carried: chains through the other bucket are omitted, so the response never exposes labels the chart hides. */+ prefixes: PathsV2PrefixApi[]+ steps: PathsV2StepApi[]+}++export interface PathsV2QueryResponseApi {+ /** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */+ error?: string | null+ /** Generated HogQL query. */+ hogql?: string | null+ /** Modifiers used when performing the query */+ modifiers?: HogQLQueryModifiersApi | null+ /** Query status indicates whether next to the provided data, a query is still running. */+ query_status?: QueryStatusApi | null+ /** The resolved previous/comparison period date range, when comparing against another period */+ resolved_compare_date_range?: ResolvedDateRangeResponseApi | null+ /** The date range used for the query */+ resolved_date_range?: ResolvedDateRangeResponseApi | null+ results: PathsV2ResultsApi+ /** Measured timings for different parts of the query generation process */+ timings?: QueryTimingApi[] | null+ /** Connector-synced data warehouse sources referenced by this query, if any. */+ used_data_warehouse_sources?: DataWarehouseSourceUsageApi[] | null+ /** Warnings about data warehouse sources referenced by the query whose latest sync failed, is paused, hit a billing limit, or is otherwise stale. Results may not reflect current source data. Accumulated across every HogQL execution that contributes to this response — so insights backed by warehouse tables (Trends, Funnels, etc.) receive the same warnings as raw HogQL queries. Also carries access control warnings when a system-table query filters out objects the user can't access. */+ warnings?: (DataWarehouseSyncWarningApi | AccessControlFilterWarningApi)[] | null+}++export interface PathsV2QueryApi {+ /** Colors used in the insight's visualization */+ dataColorTheme?: number | null+ /** Date range for the query */+ dateRange?: DateRangeApi | null+ /** Exclude internal and test users by applying the respective filters */+ filterTestAccounts?: boolean | null+ kind?: 'PathsV2Query'+ /** Modifiers used when performing the query */+ modifiers?: HogQLQueryModifiersApi | null+ /** Properties specific to the paths v2 insight */+ pathsV2Filter?: PathsV2FilterApi | null+ /** Property filters for all series */+ properties?:+ | (+ | EventPropertyFilterApi+ | PersonPropertyFilterApi+ | PersonMetadataPropertyFilterApi+ | ElementPropertyFilterApi+ | EventMetadataPropertyFilterApi+ | SessionPropertyFilterApi+ | CohortPropertyFilterApi+ | RecordingPropertyFilterApi+ | LogEntryPropertyFilterApi+ | GroupPropertyFilterApi+ | FeaturePropertyFilterApi+ | FlagPropertyFilterApi+ | HogQLPropertyFilterApi+ | EmptyPropertyFilterApi+ | DataWarehousePropertyFilterApi+ | DataWarehousePersonPropertyFilterApi+ | ErrorTrackingIssueFilterApi+ | LogPropertyFilterApi+ | MetricPropertyFilterApi+ | SpanPropertyFilterApi+ | RevenueAnalyticsPropertyFilterApi+ | AccountCustomPropertyFilterApi+ | WorkflowVariablePropertyFilterApi+ | BehavioralPropertyFilterApi+ )[]+ | PropertyGroupFilterApi+ | null+ response?: PathsV2QueryResponseApi | null+ /** Tags that will be added to the Query log comment */+ tags?: QueryLogTagsApi | null+ /** version of the node, used for schema migrations */+ version?: number | null+}++export type StickinessQueryResponseApiResultsItem = { [key: string]: unknown }++export interface StickinessQueryResponseApi {+ /** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */+ error?: string | null+ /** Generated HogQL query. */+ hogql?: string | null+ /** Modifiers used when performing the query */+ modifiers?: HogQLQueryModifiersApi | null+ /** Query status indicates whether next to the provided data, a query is still running. */+ query_status?: QueryStatusApi | null+ /** The resolved previous/comparison period date range, when comparing against another period */+ resolved_compare_date_range?: ResolvedDateRangeResponseApi | null+ /** The date range used for the query */+ resolved_date_range?: ResolvedDateRangeResponseApi | null+ results: StickinessQueryResponseApiResultsItem[]+ /** Measured timings for different parts of the query generation process */+ timings?: QueryTimingApi[] | null+ /** Connector-synced data warehouse sources referenced by this query, if any. */+ used_data_warehouse_sources?: DataWarehouseSourceUsageApi[] | null+ /** Warnings about data warehouse sources referenced by the query whose latest sync failed, is paused, hit a billing limit, or is otherwise stale. Results may not reflect current source data. Accumulated across every HogQL execution that contributes to this response — so insights backed by warehouse tables (Trends, Funnels, etc.) receive the same warnings as raw HogQL queries. Also carries access control warnings when a system-table query filters out objects the user can't access. */+ warnings?: (DataWarehouseSyncWarningApi | AccessControlFilterWarningApi)[] | null+}++export type StickinessComputationModeApi =+ (typeof StickinessComputationModeApi)[keyof typeof StickinessComputationModeApi]++export const StickinessComputationModeApi = {+ NonCumulative: 'non_cumulative',+ Cumulative: 'cumulative',+} as const++export type StickinessOperatorApi = (typeof StickinessOperatorApi)[keyof typeof StickinessOperatorApi]++export const StickinessOperatorApi = {+ Gte: 'gte',+ Lte: 'lte',+ Exact: 'exact',+} as const++export interface StickinessCriteriaApi {+ operator: StickinessOperatorApi+ /** @minimum 1 */+ value: number+}++/**+ * Customizations for the appearance of result datasets.+ */+export type StickinessFilterApiResultCustomizations =+ | { [key: string]: ResultCustomizationByValueApi }+ | { [key: string]: ResultCustomizationByPositionApi }+ | null++export interface StickinessFilterApi {+ /** Chart rendering style overrides (line shape). */+ chartStyle?: ChartStyleApi | null+ computedAs?: StickinessComputationModeApi | null+ display?: ChartDisplayTypeApi | null+ hiddenLegendIndexes?: number[] | null+ /** Where the in-chart legend sits relative to the plot. Only applies to the in-chart legend. */+ legendPosition?: LegendPositionApi | null+ /** Whether result datasets are associated by their values or by their order. */+ resultCustomizationBy?: ResultCustomizationByApi | null+ /** Customizations for the appearance of result datasets. */+ resultCustomizations?: StickinessFilterApiResultCustomizations+ showLegend?: boolean | null+ showMultipleYAxes?: boolean | null+ showValuesOnSeries?: boolean | null+ stickinessCriteria?: StickinessCriteriaApi | null+}++export interface StickinessQueryApi {+ /** Compare to date range */+ compareFilter?: CompareFilterApi | null+ /** Colors used in the insight's visualization */+ dataColorTheme?: number | null+ /** Date range for the query */+ dateRange?: DateRangeApi | null+ /** Exclude internal and test users by applying the respective filters */+ filterTestAccounts?: boolean | null+ /** Granularity of the response. Can be one of `hour`, `day`, `week` or `month` */+ interval?: IntervalTypeApi | null+ /** How many intervals comprise a period. Only used for cohorts, otherwise default 1. */+ intervalCount?: number | null+ kind?: 'StickinessQuery'+ /** Modifiers used when performing the query */+ modifiers?: HogQLQueryModifiersApi | null+ /** Property filters for all series */+ properties?:+ | (+ | EventPropertyFilterApi+ | PersonPropertyFilterApi+ | PersonMetadataPropertyFilterApi+ | ElementPropertyFilterApi+ | EventMetadataPropertyFilterApi+ | SessionPropertyFilterApi+ | CohortPropertyFilterApi+ | RecordingPropertyFilterApi+ | LogEntryPropertyFilterApi+ | GroupPropertyFilterApi+ | FeaturePropertyFilterApi+ | FlagPropertyFilterApi+ | HogQLPropertyFilterApi+ | EmptyPropertyFilterApi+ | DataWarehousePropertyFilterApi+ | DataWarehousePersonPropertyFilterApi+ | ErrorTrackingIssueFilterApi+ | LogPropertyFilterApi+ | MetricPropertyFilterApi+ | SpanPropertyFilterApi+ | RevenueAnalyticsPropertyFilterApi+ | AccountCustomPropertyFilterApi+ | WorkflowVariablePropertyFilterApi+ | BehavioralPropertyFilterApi+ )[]+ | PropertyGroupFilterApi+ | null+ response?: StickinessQueryResponseApi | null+ /** Sampling rate */+ samplingFactor?: number | null+ /**+ * Events and actions to include+ * @maxItems 200+ */+ series: (EventsNodeApi | ActionsNodeApi | DataWarehouseNodeApi)[]+ /** Properties specific to the stickiness insight */+ stickinessFilter?: StickinessFilterApi | null+ /** Tags that will be added to the Query log comment */+ tags?: QueryLogTagsApi | null+ /** version of the node, used for schema migrations */+ version?: number | null+}++export type LifecycleToggleApi = (typeof LifecycleToggleApi)[keyof typeof LifecycleToggleApi]++export const LifecycleToggleApi = {+ New: 'new',+ Resurrecting: 'resurrecting',+ Returning: 'returning',+ Dormant: 'dormant',+} as const++export interface LifecycleFilterApi {+ /** Where the in-chart legend sits relative to the plot. Only applies to the in-chart legend. */+ legendPosition?: LegendPositionApi | null+ showLegend?: boolean | null+ /** Append per-band percentage to each value label (e.g. `580 (42%)`). Requires `showValuesOnSeries` — on its own it has no visible effect. */+ showPercentagesOnSeries?: boolean | null+ showValuesOnSeries?: boolean | null+ stacked?: boolean | null+ toggledLifecycles?: LifecycleToggleApi[] | null+}++export type LifecycleQueryResponseApiResultsItem = { [key: string]: unknown }++export interface LifecycleQueryResponseApi {+ /** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */+ error?: string | null+ /** Generated HogQL query. */+ hogql?: string | null+ /** Modifiers used when performing the query */+ modifiers?: HogQLQueryModifiersApi | null+ /** Query status indicates whether next to the provided data, a query is still running. */+ query_status?: QueryStatusApi | null+ /** The resolved previous/comparison period date range, when comparing against another period */+ resolved_compare_date_range?: ResolvedDateRangeResponseApi | null+ /** The date range used for the query */+ resolved_date_range?: ResolvedDateRangeResponseApi | null+ results: LifecycleQueryResponseApiResultsItem[]+ /** Measured timings for different parts of the query generation process */+ timings?: QueryTimingApi[] | null+ /** Connector-synced data warehouse sources referenced by this query, if any. */+ used_data_warehouse_sources?: DataWarehouseSourceUsageApi[] | null+ /** Warnings about data warehouse sources referenced by the query whose latest sync failed, is paused, hit a billing limit, or is otherwise stale. Results may not reflect current source data. Accumulated across every HogQL execution that contributes to this response — so insights backed by warehouse tables (Trends, Funnels, etc.) receive the same warnings as raw HogQL queries. Also carries access control warnings when a system-table query filters out objects the user can't access. */+ warnings?: (DataWarehouseSyncWarningApi | AccessControlFilterWarningApi)[] | null+}++export type LifecycleDataWarehouseNodeApiResponse = { [key: string]: unknown } | null++export interface LifecycleDataWarehouseNodeApi {+ aggregation_target_field: string+ created_at_field: string+ custom_name?: string | null+ /** Fixed properties in the query, can't be edited in the interface (e.g. scoping down by person) */+ fixedProperties?:+ | (+ | EventPropertyFilterApi+ | PersonPropertyFilterApi+ | PersonMetadataPropertyFilterApi+ | ElementPropertyFilterApi+ | EventMetadataPropertyFilterApi+ | SessionPropertyFilterApi+ | CohortPropertyFilterApi+ | RecordingPropertyFilterApi+ | LogEntryPropertyFilterApi+ | GroupPropertyFilterApi+ | FeaturePropertyFilterApi+ | FlagPropertyFilterApi+ | HogQLPropertyFilterApi+ | EmptyPropertyFilterApi+ | DataWarehousePropertyFilterApi+ | DataWarehousePersonPropertyFilterApi+ | ErrorTrackingIssueFilterApi+ | LogPropertyFilterApi+ | MetricPropertyFilterApi+ | SpanPropertyFilterApi+ | RevenueAnalyticsPropertyFilterApi+ | AccountCustomPropertyFilterApi+ | WorkflowVariablePropertyFilterApi+ | BehavioralPropertyFilterApi+ )[]+ | null+ id: string+ kind?: 'LifecycleDataWarehouseNode'+ math?:+ | BaseMathTypeApi+ | FunnelMathTypeApi+ | PropertyMathTypeApi+ | CountPerActorMathTypeApi+ | GroupMathTypeApi+ | ExperimentMetricMathTypeApi+ | CalendarHeatmapMathTypeApi+ | 'hogql'+ | null+ math_group_type_index?: MathGroupTypeIndexApi | null+ math_hogql?: string | null+ math_multiplier?: number | null+ math_property?: string | null+ math_property_revenue_currency?: RevenueCurrencyPropertyConfigApi | null+ math_property_type?: string | null+ name?: string | null+ optionalInFunnel?: boolean | null+ /** Properties configurable in the interface */+ properties?:+ | (+ | EventPropertyFilterApi+ | PersonPropertyFilterApi+ | PersonMetadataPropertyFilterApi+ | ElementPropertyFilterApi+ | EventMetadataPropertyFilterApi+ | SessionPropertyFilterApi+ | CohortPropertyFilterApi+ | RecordingPropertyFilterApi+ | LogEntryPropertyFilterApi+ | GroupPropertyFilterApi+ | FeaturePropertyFilterApi+ | FlagPropertyFilterApi+ | HogQLPropertyFilterApi+ | EmptyPropertyFilterApi+ | DataWarehousePropertyFilterApi+ | DataWarehousePersonPropertyFilterApi+ | ErrorTrackingIssueFilterApi+ | LogPropertyFilterApi+ | MetricPropertyFilterApi+ | SpanPropertyFilterApi+ | RevenueAnalyticsPropertyFilterApi+ | AccountCustomPropertyFilterApi+ | WorkflowVariablePropertyFilterApi+ | BehavioralPropertyFilterApi+ )[]+ | null+ response?: LifecycleDataWarehouseNodeApiResponse+ table_name: string+ timestamp_field: string+ /** version of the node, used for schema migrations */+ version?: number | null+}++export interface LifecycleQueryApi {+ /** Groups aggregation */+ aggregation_group_type_index?: number | null+ /** For data warehouse based lifecycle insights when the aggregation target can't be mapped to persons or groups. */+ customAggregationTarget?: boolean | null+ /** Colors used in the insight's visualization */+ dataColorTheme?: number | null+ /** Date range for the query */+ dateRange?: DateRangeApi | null+ /** Exclude internal and test users by applying the respective filters */+ filterTestAccounts?: boolean | null+ /** Granularity of the response. Can be one of `hour`, `day`, `week` or `month` */+ interval?: IntervalTypeApi | null+ kind?: 'LifecycleQuery'+ /** Properties specific to the lifecycle insight */+ lifecycleFilter?: LifecycleFilterApi | null+ /** Modifiers used when performing the query */+ modifiers?: HogQLQueryModifiersApi | null+ /** Property filters for all series */+ properties?:+ | (+ | EventPropertyFilterApi+ | PersonPropertyFilterApi+ | PersonMetadataPropertyFilterApi+ | ElementPropertyFilterApi+ | EventMetadataPropertyFilterApi+ | SessionPropertyFilterApi+ | CohortPropertyFilterApi+ | RecordingPropertyFilterApi+ | LogEntryPropertyFilterApi+ | GroupPropertyFilterApi+ | FeaturePropertyFilterApi+ | FlagPropertyFilterApi+ | HogQLPropertyFilterApi+ | EmptyPropertyFilterApi+ | DataWarehousePropertyFilterApi+ | DataWarehousePersonPropertyFilterApi+ | ErrorTrackingIssueFilterApi+ | LogPropertyFilterApi+ | MetricPropertyFilterApi+ | SpanPropertyFilterApi+ | RevenueAnalyticsPropertyFilterApi+ | AccountCustomPropertyFilterApi+ | WorkflowVariablePropertyFilterApi+ | BehavioralPropertyFilterApi+ )[]+ | PropertyGroupFilterApi+ | null+ response?: LifecycleQueryResponseApi | null+ /** Sampling rate */+ samplingFactor?: number | null+ /** Events and actions to include */+ series: (EventsNodeApi | ActionsNodeApi | LifecycleDataWarehouseNodeApi)[]+ /** Tags that will be added to the Query log comment */+ tags?: QueryLogTagsApi | null+ /** version of the node, used for schema migrations */+ version?: number | null+}++export type WebStatsBreakdownApi = (typeof WebStatsBreakdownApi)[keyof typeof WebStatsBreakdownApi]++export const WebStatsBreakdownApi = {+ Page: 'Page',+ InitialPage: 'InitialPage',+ ExitPage: 'ExitPage',+ ExitClick: 'ExitClick',+ PreviousPage: 'PreviousPage',+ ScreenName: 'ScreenName',+ InitialChannelType: 'InitialChannelType',+ InitialReferringDomain: 'InitialReferringDomain',+ InitialReferringURL: 'InitialReferringURL',+ InitialUTMSource: 'InitialUTMSource',+ InitialUTMCampaign: 'InitialUTMCampaign',+ InitialUTMMedium: 'InitialUTMMedium',+ InitialUTMTerm: 'InitialUTMTerm',+ InitialUTMContent: 'InitialUTMContent',+ InitialUTMSourceMediumCampaign: 'InitialUTMSourceMediumCampaign',+ FirstPageviewChannelType: 'FirstPageviewChannelType',+ FirstPageviewReferringDomain: 'FirstPageviewReferringDomain',+ FirstPageviewUTMSource: 'FirstPageviewUTMSource',+ FirstPageviewUTMCampaign: 'FirstPageviewUTMCampaign',+ FirstPageviewUTMMedium: 'FirstPageviewUTMMedium',+ FirstPageviewUTMTerm: 'FirstPageviewUTMTerm',+ FirstPageviewUTMContent: 'FirstPageviewUTMContent',+ FirstPageviewUTMSourceMediumCampaign: 'FirstPageviewUTMSourceMediumCampaign',+ Browser: 'Browser',+ InAppBrowser: 'InAppBrowser',+ Os: 'OS',+ Viewport: 'Viewport',+ DeviceType: 'DeviceType',+ Country: 'Country',+ Region: 'Region',+ City: 'City',+ Timezone: 'Timezone',+ Language: 'Language',+ FrustrationMetrics: 'FrustrationMetrics',+} as const++export type WebAnalyticsOrderByFieldsApi =+ (typeof WebAnalyticsOrderByFieldsApi)[keyof typeof WebAnalyticsOrderByFieldsApi]++export const WebAnalyticsOrderByFieldsApi = {+ Visitors: 'Visitors',+ Views: 'Views',+ AvgTimeOnPage: 'AvgTimeOnPage',+ Clicks: 'Clicks',+ BounceRate: 'BounceRate',+ AverageScrollPercentage: 'AverageScrollPercentage',+ ScrollGt80Percentage: 'ScrollGt80Percentage',+ TotalConversions: 'TotalConversions',+ UniqueConversions: 'UniqueConversions',+ ConversionRate: 'ConversionRate',+ ConvertingUsers: 'ConvertingUsers',+ RageClicks: 'RageClicks',+ DeadClicks: 'DeadClicks',+ Errors: 'Errors',+} as const++export type WebAnalyticsOrderByDirectionApi =+ (typeof WebAnalyticsOrderByDirectionApi)[keyof typeof WebAnalyticsOrderByDirectionApi]++export const WebAnalyticsOrderByDirectionApi = {+ Asc: 'ASC',+ Desc: 'DESC',+} as const++export type WebAnalyticsPreComputeStrategyApi =+ (typeof WebAnalyticsPreComputeStrategyApi)[keyof typeof WebAnalyticsPreComputeStrategyApi]++export const WebAnalyticsPreComputeStrategyApi = {+ PreAggregated: 'pre_aggregated',+ LazyPrecompute: 'lazy_precompute',+ Live: 'live',+} as const++export interface SamplingRateApi {+ denominator?: number | null+ numerator: number+}++export interface WebStatsTableQueryResponseApi {+ columns?: unknown[] | null+ /** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */+ error?: string | null+ hasMore?: boolean | null+ /** Generated HogQL query. */+ hogql?: string | null+ limit?: number | null+ /** Modifiers used when performing the query */+ modifiers?: HogQLQueryModifiersApi | null+ offset?: number | null+ /** Why a live response skipped precompute: the eligibility-gate reason that refused it. Unset when the query was eligible. */+ preComputeIneligibleReason?: string | null+ /** Whether a lazy-precompute read was served from expired-within-grace (stale) jobs instead of recomputing inline. */+ preComputeStale?: boolean | null+ preComputeStrategy?: WebAnalyticsPreComputeStrategyApi | null+ /** Query status indicates whether next to the provided data, a query is still running. */+ query_status?: QueryStatusApi | null+ /** The resolved previous/comparison period date range, when comparing against another period */+ resolved_compare_date_range?: ResolvedDateRangeResponseApi | null+ /** The date range used for the query */+ resolved_date_range?: ResolvedDateRangeResponseApi | null+ results: unknown[]+ samplingRate?: SamplingRateApi | null+ /** Measured timings for different parts of the query generation process */+ timings?: QueryTimingApi[] | null+ types?: unknown[] | null+ /** Connector-synced data warehouse sources referenced by this query, if any. */+ used_data_warehouse_sources?: DataWarehouseSourceUsageApi[] | null+ /** Warnings about data warehouse sources referenced by the query whose latest sync failed, is paused, hit a billing limit, or is otherwise stale. Results may not reflect current source data. Accumulated across every HogQL execution that contributes to this response — so insights backed by warehouse tables (Trends, Funnels, etc.) receive the same warnings as raw HogQL queries. Also carries access control warnings when a system-table query filters out objects the user can't access. */+ warnings?: (DataWarehouseSyncWarningApi | AccessControlFilterWarningApi)[] | null+}++export interface WebAnalyticsSamplingApi {+ enabled?: boolean | null+ forceSamplingRate?: SamplingRateApi | null+}++export interface WebStatsTableQueryApi {+ /** Groups aggregation - not used in Web Analytics but required for type compatibility */+ aggregation_group_type_index?: number | null+ breakdownBy: WebStatsBreakdownApi+ compareFilter?: CompareFilterApi | null+ conversionGoal?: ActionConversionGoalApi | CustomEventConversionGoalApi | null+ /** Colors used in the insight's visualization - not used in Web Analytics but required for type compatibility */+ dataColorTheme?: number | null+ dateRange?: DateRangeApi | null+ doPathCleaning?: boolean | null+ filterTestAccounts?: boolean | null+ includeAvgTimeOnPage?: boolean | null+ includeBounceRate?: boolean | null+ includeHost?: boolean | null+ includeRevenue?: boolean | null+ includeScrollDepth?: boolean | null+ includeTrafficMetrics?: boolean | null+ /** Interval for date range calculation (affects date_to rounding for hour vs day ranges) */+ interval?: IntervalTypeApi | null+ kind?: 'WebStatsTableQuery'+ limit?: number | null+ /** Modifiers used when performing the query */+ modifiers?: HogQLQueryModifiersApi | null+ offset?: number | null+ orderBy?: (WebAnalyticsOrderByFieldsApi | WebAnalyticsOrderByDirectionApi)[] | null+ properties: (+ | EventPropertyFilterApi+ | PersonPropertyFilterApi+ | SessionPropertyFilterApi+ | CohortPropertyFilterApi+ )[]+ response?: WebStatsTableQueryResponseApi | null+ sampling?: WebAnalyticsSamplingApi | null+ /** Sampling rate */+ samplingFactor?: number | null+ tags?: QueryLogTagsApi | null+ useSessionsTable?: boolean | null+ /** Opt this specific query into the web stats table precompute path. Requires the `web-analytics-precompute-toggle` PostHog feature flag to be on for the team's organization for the gate to pass. * */+ useWebAnalyticsPrecompute?: boolean | null+ /** version of the node, used for schema migrations */+ version?: number | null+}++export type WebAnalyticsItemKindApi = (typeof WebAnalyticsItemKindApi)[keyof typeof WebAnalyticsItemKindApi]++export const WebAnalyticsItemKindApi = {+ Unit: 'unit',+ DurationS: 'duration_s',+ Percentage: 'percentage',+ Currency: 'currency',+} as const++export interface WebOverviewItemApi {+ changeFromPreviousPct?: number | null+ isIncreaseBad?: boolean | null+ key: string+ kind: WebAnalyticsItemKindApi+ previous?: number | null+ value?: number | null+}++export interface WebOverviewQueryResponseApi {+ dateFrom?: string | null+ dateTo?: string | null+ /** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */+ error?: string | null+ /** Generated HogQL query. */+ hogql?: string | null+ /** Modifiers used when performing the query */+ modifiers?: HogQLQueryModifiersApi | null+ /** Why a live response skipped precompute: the eligibility-gate reason that refused it. Unset when the query was eligible. */+ preComputeIneligibleReason?: string | null+ preComputeStrategy?: WebAnalyticsPreComputeStrategyApi | null+ /** Query status indicates whether next to the provided data, a query is still running. */+ query_status?: QueryStatusApi | null+ /** The resolved previous/comparison period date range, when comparing against another period */+ resolved_compare_date_range?: ResolvedDateRangeResponseApi | null+ /** The date range used for the query */+ resolved_date_range?: ResolvedDateRangeResponseApi | null+ results: WebOverviewItemApi[]+ samplingRate?: SamplingRateApi | null+ /** Measured timings for different parts of the query generation process */+ timings?: QueryTimingApi[] | null+ /** Connector-synced data warehouse sources referenced by this query, if any. */+ used_data_warehouse_sources?: DataWarehouseSourceUsageApi[] | null+ /** Warnings about data warehouse sources referenced by the query whose latest sync failed, is paused, hit a billing limit, or is otherwise stale. Results may not reflect current source data. Accumulated across every HogQL execution that contributes to this response — so insights backed by warehouse tables (Trends, Funnels, etc.) receive the same warnings as raw HogQL queries. Also carries access control warnings when a system-table query filters out objects the user can't access. */+ warnings?: (DataWarehouseSyncWarningApi | AccessControlFilterWarningApi)[] | null+}++export interface WebOverviewQueryApi {+ /** Groups aggregation - not used in Web Analytics but required for type compatibility */+ aggregation_group_type_index?: number | null+ compareFilter?: CompareFilterApi | null+ conversionGoal?: ActionConversionGoalApi | CustomEventConversionGoalApi | null+ /** Colors used in the insight's visualization - not used in Web Analytics but required for type compatibility */+ dataColorTheme?: number | null+ dateRange?: DateRangeApi | null+ doPathCleaning?: boolean | null+ filterTestAccounts?: boolean | null+ includeRevenue?: boolean | null+ /** Interval for date range calculation (affects date_to rounding for hour vs day ranges) */+ interval?: IntervalTypeApi | null+ kind?: 'WebOverviewQuery'+ /** Modifiers used when performing the query */+ modifiers?: HogQLQueryModifiersApi | null+ orderBy?: (WebAnalyticsOrderByFieldsApi | WebAnalyticsOrderByDirectionApi)[] | null+ properties: (+ | EventPropertyFilterApi+ | PersonPropertyFilterApi+ | SessionPropertyFilterApi+ | CohortPropertyFilterApi+ )[]+ response?: WebOverviewQueryResponseApi | null+ sampling?: WebAnalyticsSamplingApi | null+ /** Sampling rate */+ samplingFactor?: number | null+ tags?: QueryLogTagsApi | null+ useSessionsTable?: boolean | null+ /** Opt this specific query into the web_overview_query precompute path. Requires the `web-analytics-precompute-toggle` PostHog feature flag to be on for the team's organization for the gate to pass. * */+ useWebAnalyticsPrecompute?: boolean | null+ /** version of the node, used for schema migrations */+ version?: number | null+}++export interface InsightActorsQueryApi {+ breakdown?: string | string[] | number | null+ compare?: CompareApi | null+ day?: string | number | null+ includeRecordings?: boolean | null+ /** An interval selected out of available intervals in source query. */+ interval?: number | null+ kind?: 'InsightActorsQuery'+ /** Modifiers used when performing the query */+ modifiers?: HogQLQueryModifiersApi | null+ response?: ActorsQueryResponseApi | null+ series?: number | null+ source:+ | TrendsQueryApi+ | FunnelsQueryApi+ | RetentionQueryApi+ | PathsQueryApi+ | PathsV2QueryApi+ | StickinessQueryApi+ | LifecycleQueryApi+ | WebStatsTableQueryApi+ | WebOverviewQueryApi+ status?: string | null+ tags?: QueryLogTagsApi | null+ /** version of the node, used for schema migrations */+ version?: number | null+}++export interface PropertiesTimelineRequestApi {+ /** The actors query of the insight data point, as the persons modal sends it. The timeline reads the person's events in the data point's time window, and tracks the person properties that the series, the insight's filters and its breakdown use. The source must be a Trends query, and the selected series must be an events or actions series. */+ query: InsightActorsQueryApi+}++/**+ * The person's properties as that event recorded them.+ */+export type PropertiesTimelinePointApiProperties = { [key: string]: unknown }++export interface PropertiesTimelinePointApi {+ /** The time of the first event in the window that has this combination of key property values. */+ timestamp: string+ /** The person's properties as that event recorded them. */+ properties: PropertiesTimelinePointApiProperties+ /** The number of the person's events in the window from this point until the next point. */+ relevant_event_count: number+}++export interface PropertiesTimelineResponseApi {+ /** One point for each change of the key property values, oldest first. */+ points: PropertiesTimelinePointApi[]+ /** The key person properties: those the insight's query uses. Empty when it uses none. */+ crucial_property_keys: string[]+ /** The start of the window, in the project's time zone. */+ effective_date_from: string+ /** The end of the window, in the project's time zone. */+ effective_date_to: string+}+export interface PersonSplitRequestApi {/*** The distinct_id to **keep** on this person; every *other* distinct_id is moved to its own new single-id person. If omitted, the first distinct_id on the person is kept. The original person always retains its properties; to clear individual properties afterward, use the delete_property endpoint. To surgically *remove* one or more distinct_ids while leaving the merge intact, use `distinct_ids_to_split` instead — these parameters are inverses of each other and cannot be combined.@@ -600,14 +4192,14 @@ export const PersonsEmailsListFormat = {Json: 'json',} as const-export type PersonsPropertiesTimelineRetrieveParams = {- format?: PersonsPropertiesTimelineRetrieveFormat+export type PersonsPropertiesTimelineCreateParams = {+ format?: PersonsPropertiesTimelineCreateFormat}-export type PersonsPropertiesTimelineRetrieveFormat =- (typeof PersonsPropertiesTimelineRetrieveFormat)[keyof typeof PersonsPropertiesTimelineRetrieveFormat]+export type PersonsPropertiesTimelineCreateFormat =+ (typeof PersonsPropertiesTimelineCreateFormat)[keyof typeof PersonsPropertiesTimelineCreateFormat]-export const PersonsPropertiesTimelineRetrieveFormat = {+export const PersonsPropertiesTimelineCreateFormat = {Csv: 'csv',Json: 'json',} as constdiff --git a/products/persons/frontend/generated/api.ts b/products/persons/frontend/generated/api.tsindex f33c43fb5f5a..54ea1a8dd2da 100644--- a/products/persons/frontend/generated/api.ts+++ b/products/persons/frontend/generated/api.ts@@ -34,7 +34,7 @@ import type {PersonsListParams,PersonsPartialUpdateParams,PersonsPropertiesAtTimeRetrieveParams,- PersonsPropertiesTimelineRetrieveParams,+ PersonsPropertiesTimelineCreateParams,PersonsPushNotificationsListParams,PersonsResetPersonDistinctIdCreateParams,PersonsRetrieveParams,@@ -42,6 +42,8 @@ import type {PersonsUpdateParams,PersonsUpdatePropertyCreateParams,PersonsValuesRetrieveParams,+ PropertiesTimelineRequestApi,+ PropertiesTimelineResponseApi,} from './api.schemas'// https://stackoverflow.com/questions/49579094/typescript-conditional-types-filter-out-readonly-properties-pick-only-requir/49579497#49579497@@ -296,10 +298,10 @@ export const personsEmailsList = async (})}-export const getPersonsPropertiesTimelineRetrieveUrl = (+export const getPersonsPropertiesTimelineCreateUrl = (projectId: string,- id: number,- params?: PersonsPropertiesTimelineRetrieveParams+ id: string,+ params?: PersonsPropertiesTimelineCreateParams) => {const normalizedParams = new URLSearchParams()@@ -317,17 +319,21 @@ export const getPersonsPropertiesTimelineRetrieveUrl = (}/**- * This endpoint is meant for reading and deleting persons. To create or update persons, we recommend using the [capture API](https://posthog.com/docs/api/capture), the `$set` and `$unset` [properties](https://posthog.com/docs/product-analytics/user-properties), or one of our SDKs.+ * Shows how the person's key properties changed within the time window of a Trends data point. The key properties are the person properties that the insight's query uses.+ * @summary Get a person's properties timeline for an insight data point*/-export const personsPropertiesTimelineRetrieve = async (+export const personsPropertiesTimelineCreate = async (projectId: string,- id: number,- params?: PersonsPropertiesTimelineRetrieveParams,+ id: string,+ propertiesTimelineRequestApi: PropertiesTimelineRequestApi,+ params?: PersonsPropertiesTimelineCreateParams,options?: RequestInit-): Promise<void> => {- return apiMutator<void>(getPersonsPropertiesTimelineRetrieveUrl(projectId, id, params), {+): Promise<PropertiesTimelineResponseApi> => {+ return apiMutator<PropertiesTimelineResponseApi>(getPersonsPropertiesTimelineCreateUrl(projectId, id, params), {...options,- method: 'GET',+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(propertiesTimelineRequestApi),})}diff --git a/products/persons/frontend/generated/api.zod.ts b/products/persons/frontend/generated/api.zod.tsindex d913e880f7d9..27464741a5e7 100644--- a/products/persons/frontend/generated/api.zod.ts+++ b/products/persons/frontend/generated/api.zod.ts@@ -46,6 +46,14 @@ export const PersonsDeletePropertyCreateBody = /* @__PURE__ */ zod.object({.describe('A property key, or a list of property keys, to remove from this person.'),})+/**+ * Shows how the person's key properties changed within the time window of a Trends data point. The key properties are the person properties that the insight's query uses.+ * @summary Get a person's properties timeline for an insight data point+ */+export const PersonsPropertiesTimelineCreateBody = /* @__PURE__ */ zod+ .record(zod.string(), zod.unknown())+ .describe('Deep\/recursive schema (opaque in Zod — use TypeScript types for full shape)')+/*** Split distinct_ids off a merged person. Two mutually exclusive modes:*diff --git a/products/product_analytics/backend/facade/contracts.py b/products/product_analytics/backend/facade/contracts.pyindex 061313326cef..93029dac081a 100644--- a/products/product_analytics/backend/facade/contracts.py+++ b/products/product_analytics/backend/facade/contracts.py@@ -53,6 +53,18 @@ class TrendsQueryRunResult:last_refresh: datetime | None = None+@dataclass(frozen=True)+class TrendsActorsDateWindow:+ """The time window of the events that the actors of one Trends data point have.++ ``date_to`` is exclusive, unless ``date_to_inclusive`` is true.+ """++ date_from: datetime+ date_to: datetime+ date_to_inclusive: bool++@dataclass(frozen=True)class SavedInsightDefinition:id: intdiff --git a/products/product_analytics/backend/facade/queries.py b/products/product_analytics/backend/facade/queries.pyindex ff5e8e0d1337..aa4936184c5b 100644--- a/products/product_analytics/backend/facade/queries.py+++ b/products/product_analytics/backend/facade/queries.py@@ -37,6 +37,7 @@ _LAZY = {"StickinessQueryRunner": "stickiness.stickiness_query_runner","TrendsDisplay": "trends.display","TrendsQueryRunner": "trends.trends_query_runner",+ "trends_actors_date_window": "trends.trends_actors_date_window","anchored_segment_to_funnels_query": "paths_v2.funnel_converter","edge_to_funnels_query": "paths_v2.funnel_converter","get_properties_chain": "trends.utils",@@ -72,6 +73,9 @@ if TYPE_CHECKING:from products.product_analytics.backend.hogql_queries.trends.slope_graph_trends_query_runner import ( # noqa: F401SlopeGraphTrendsQueryRunner,)+ from products.product_analytics.backend.hogql_queries.trends.trends_actors_date_window import ( # noqa: F401+ trends_actors_date_window,+ )from products.product_analytics.backend.hogql_queries.trends.trends_query_runner import ( # noqa: F401TrendsQueryRunner,)diff --git a/products/product_analytics/backend/hogql_queries/trends/test/test_trends_actors_query_builder.py b/products/product_analytics/backend/hogql_queries/trends/test/test_trends_actors_query_builder.pyindex 91c04d050015..9222bed2587d 100644--- a/products/product_analytics/backend/hogql_queries/trends/test/test_trends_actors_query_builder.py+++ b/products/product_analytics/backend/hogql_queries/trends/test/test_trends_actors_query_builder.py@@ -447,6 +447,60 @@ class TestTrendsActorsQueryBuilder(BaseTest):"greaterOrEquals(timestamp, greatest(minus(toDateTime('2024-05-07 22:00:00.000000'), toIntervalDay(29)), toDateTime('2024-05-08 14:29:13.634000'))), less(timestamp, least(toDateTime('2024-05-08 22:00:00.000000'), toDateTime('2024-05-08 14:32:57.692000')))",)+ @parameterized.expand(+ [+ (+ "weekly_active_across_dst_change",+ {"series": [EventsNode(event="$pageview", math=BaseMathType.WEEKLY_ACTIVE)]},+ "2024-03-31",+ "2024-04-02T12:00:00Z",+ ("2024-03-24 23:00:00Z", "2024-03-31 22:00:00Z", ast.CompareOperationOp.Lt),+ ),+ (+ "weekly_active_total_value",+ {+ "series": [EventsNode(event="$pageview", math=BaseMathType.WEEKLY_ACTIVE)],+ "trendsFilter": TrendsFilter(display=ChartDisplayType.BOLD_NUMBER),+ },+ None,+ "2024-05-30T12:00:00Z",+ ("2024-05-24 21:59:59Z", "2024-05-30 21:59:59Z", ast.CompareOperationOp.LtEq),+ ),+ (+ "explicit_monthly_active",+ {+ "series": [EventsNode(event="$pageview", math=BaseMathType.MONTHLY_ACTIVE)],+ "dateRange": DateRange(+ date_from="2024-05-08T14:29:13.634000Z",+ date_to="2024-05-08T14:32:57.692000Z",+ explicitDate=True,+ ),+ },+ "2024-05-08",+ "2024-05-08T15:32:00Z",+ ("2024-05-08 14:29:13Z", "2024-05-08 14:32:57Z", ast.CompareOperationOp.Lt),+ ),+ ]+ )+ def test_actors_date_window_widens_for_active_users_math(+ self,+ _name: str,+ query_update: dict,+ time_frame: Optional[str],+ now: str,+ expected: tuple[str, str, ast.CompareOperationOp],+ ):+ self.team.timezone = "Europe/Berlin"+ trends_query = default_query.model_copy(update=query_update, deep=True)++ with time_machine.travel(now, tick=False):+ window = self._get_builder(trends_query=trends_query, time_frame=time_frame).actors_date_window()++ self.assertEqual(+ (self._get_utc_string(window.from_datetime), self._get_utc_string(window.to_datetime), window.to_op),+ expected,+ )+def test_actor_id_expr_for_groups_math(self):maths = [BaseMathType.DAU,diff --git a/products/product_analytics/backend/hogql_queries/trends/trends_actors_date_window.py b/products/product_analytics/backend/hogql_queries/trends/trends_actors_date_window.pynew file mode 100644index 000000000000..de9e4efb4513--- /dev/null+++ b/products/product_analytics/backend/hogql_queries/trends/trends_actors_date_window.py@@ -0,0 +1,31 @@+from typing import Optional, cast++from posthog.schema import InsightActorsQuery, TrendsQuery++from posthog.hogql import ast++from posthog.models import Team++from products.product_analytics.backend.facade.contracts import TrendsActorsDateWindow+from products.product_analytics.backend.hogql_queries.trends.trends_query_runner import TrendsQueryRunner+++def trends_actors_date_window(*, team: Team, query: InsightActorsQuery) -> TrendsActorsDateWindow:+ """The window of the events that the actors query for a Trends data point counts.++ Raises ``ValueError`` when the query's source is not a Trends query, and ``QueryError`` when the query's+ ``day`` does not suit the insight's display.+ """+ if not isinstance(query.source, TrendsQuery):+ raise ValueError(f"Expected a Trends query source, got {query.source.kind}")+ # The runner can rewrite its query's breakdown, so it gets a copy.+ window = TrendsQueryRunner(query=query.source.model_copy(deep=True), team=team).to_actors_date_window(+ time_frame=cast(Optional[str], query.day), # Trends data points are dates, never integers+ series_index=query.series or 0,+ compare_value=query.compare,+ )+ return TrendsActorsDateWindow(+ date_from=window.from_datetime,+ date_to=window.to_datetime,+ date_to_inclusive=window.to_op == ast.CompareOperationOp.LtEq,+ )diff --git a/products/product_analytics/backend/hogql_queries/trends/trends_actors_query_builder.py b/products/product_analytics/backend/hogql_queries/trends/trends_actors_query_builder.pyindex 2d8fc3ffb7b1..510236b349fc 100644--- a/products/product_analytics/backend/hogql_queries/trends/trends_actors_query_builder.py+++ b/products/product_analytics/backend/hogql_queries/trends/trends_actors_query_builder.py@@ -1,5 +1,5 @@import typing-from datetime import datetime+from datetime import datetime, timedeltafrom functools import cached_propertyfrom typing import Optional, cast@@ -201,6 +201,11 @@ class TrendsActorsQueryBuilder:def is_monthly_active_math(self) -> bool:return self.entity.math == BaseMathType.MONTHLY_ACTIVE+ @cached_property+ def active_users_lookback_days(self) -> int:+ # A weekly or monthly active actor has an event in the 7 or 30 days that end on the data point.+ return 6 if self.is_weekly_active_math else 29+@cached_propertydef is_hourly(self) -> bool:return self.trends_date_range.is_hourly@@ -433,16 +438,44 @@ class TrendsActorsQueryBuilder:return conditions- def _date_where_expr(self) -> DateWhereExprs:- date_range: QueryDateRange | QueryCompareToDateRange | QueryPreviousPeriodDateRange = (- self.trends_previous_date_range if self.is_compare_previous else self.trends_date_range- )+ def actors_date_window(self) -> ActorsDateWindow:+ """The window of the events that the actors query counts, as datetimes.++ The window matches the actors query's date condition. Use it to read the actors' events in another query.+ Call it once per builder, because a previous-period window moves `time_frame`.+ """+ date_range = self._actors_date_range()query_from, query_to = date_range.date_from(), date_range.date_to()+ window = self._actors_window(date_range, query_from, query_to)+ if not self.is_active_users_math:+ return window++ actors_from = window.to_datetime if self.is_total_value else window.from_datetime+ # The query subtracts calendar days in the team's time zone, so a DST change keeps the local time.+ actors_from = actors_from.astimezone(self.team.timezone_info) - timedelta(days=self.active_users_lookback_days)+ actors_to = window.to_datetime+ if self.is_explicit:+ actors_from = max(actors_from, query_from)+ actors_to = min(actors_to, query_to)+ return ActorsDateWindow(from_datetime=actors_from, to_datetime=actors_to, to_op=window.to_op)++ def _actors_date_range(self) -> QueryDateRange | QueryCompareToDateRange | QueryPreviousPeriodDateRange:+ return self.trends_previous_date_range if self.is_compare_previous else self.trends_date_range+ def _actors_window(+ self,+ date_range: QueryDateRange | QueryCompareToDateRange | QueryPreviousPeriodDateRange,+ query_from: datetime,+ query_to: datetime,+ ) -> ActorsDateWindow:if self.is_total_value:- window = self._total_value_actors_window(query_from, query_to)- else:- window = self._time_series_actors_window(date_range, query_from, query_to)+ return self._total_value_actors_window(query_from, query_to)+ return self._time_series_actors_window(date_range, query_from, query_to)++ def _date_where_expr(self) -> DateWhereExprs:+ date_range = self._actors_date_range()+ query_from, query_to = date_range.date_from(), date_range.date_to()+ window = self._actors_window(date_range, query_from, query_to)# adjust date_from for weekly and monthly active calculationsif self.is_active_users_math:@@ -539,20 +572,12 @@ class TrendsActorsQueryBuilder:# This way we at least ensure the date range is the probably expected 7 or 30 days.actors_from = actors_to- if self.is_weekly_active_math:- actors_from_expr = ast.ArithmeticOperation(- op=ast.ArithmeticOperationOp.Sub,- left=ast.Constant(value=actors_from),- right=ast.Call(name="toIntervalDay", args=[ast.Constant(value=6)]),- )- actors_to_expr = ast.Constant(value=actors_to)- elif self.is_monthly_active_math:- actors_from_expr = ast.ArithmeticOperation(- op=ast.ArithmeticOperationOp.Sub,- left=ast.Constant(value=actors_from),- right=ast.Call(name="toIntervalDay", args=[ast.Constant(value=29)]),- )- actors_to_expr = ast.Constant(value=actors_to)+ actors_from_expr = ast.ArithmeticOperation(+ op=ast.ArithmeticOperationOp.Sub,+ left=ast.Constant(value=actors_from),+ right=ast.Call(name="toIntervalDay", args=[ast.Constant(value=self.active_users_lookback_days)]),+ )+ actors_to_expr = ast.Constant(value=actors_to)if self.is_explicit:actors_from_expr = ast.Call(name="greatest", args=[actors_from_expr, ast.Constant(value=query_from)])diff --git a/products/product_analytics/backend/hogql_queries/trends/trends_query_runner.py b/products/product_analytics/backend/hogql_queries/trends/trends_query_runner.pyindex d538643b8eae..5837775d2a4d 100644--- a/products/product_analytics/backend/hogql_queries/trends/trends_query_runner.py+++ b/products/product_analytics/backend/hogql_queries/trends/trends_query_runner.py@@ -92,7 +92,10 @@ from products.product_analytics.backend.hogql_queries.trends.trend_validation_ruRequirePropertyForPropertyMath,ValidateDataWarehouseBreakdown,)-from products.product_analytics.backend.hogql_queries.trends.trends_actors_query_builder import TrendsActorsQueryBuilder+from products.product_analytics.backend.hogql_queries.trends.trends_actors_query_builder import (+ ActorsDateWindow,+ TrendsActorsQueryBuilder,+)from products.product_analytics.backend.hogql_queries.trends.trends_query_builder import TrendsQueryBuilderfrom products.warehouse_sources.backend.facade.hogql import get_view_or_table_by_name@@ -254,6 +257,13 @@ class TrendsQueryRunner(AnalyticsQueryRunner[TrendsQueryResponse]):return query+ def to_actors_date_window(+ self, time_frame: Optional[str], series_index: int, compare_value: Optional[Compare] = None+ ) -> ActorsDateWindow:+ return self._get_trends_actors_query_builder(+ time_frame=time_frame, series_index=series_index, compare_value=compare_value+ ).actors_date_window()+def _get_trends_actors_query_builder(self,time_frame: Optional[str],diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex bd9150396a60..3537d6d0d6c4 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -93488,6 +93488,36 @@ export namespace Schemas {results: ProjectUsageItem[];}+ /**+ * The person's properties as that event recorded them.+ */+ export type PropertiesTimelinePointProperties = { [key: string]: unknown };++ export interface PropertiesTimelinePoint {+ /** The time of the first event in the window that has this combination of key property values. */+ timestamp: string;+ /** The person's properties as that event recorded them. */+ properties: PropertiesTimelinePointProperties;+ /** The number of the person's events in the window from this point until the next point. */+ relevant_event_count: number;+ }++ export interface PropertiesTimelineRequest {+ /** The actors query of the insight data point, as the persons modal sends it. The timeline reads the person's events in the data point's time window, and tracks the person properties that the series, the insight's filters and its breakdown use. The source must be a Trends query, and the selected series must be an events or actions series. */+ query: InsightActorsQuery;+ }++ export interface PropertiesTimelineResponse {+ /** One point for each change of the key property values, oldest first. */+ points: PropertiesTimelinePoint[];+ /** The key person properties: those the insight's query uses. Empty when it uses none. */+ crucial_property_keys: string[];+ /** The start of the window, in the project's time zone. */+ effective_date_from: string;+ /** The end of the window, in the project's time zone. */+ effective_date_to: string;+ }+export interface Property {/*** You can use a simplified version:@@ -132658,6 +132688,18 @@ export namespace Schemas {Json: 'json',} as const;+ export type PersonsPropertiesTimelineCreateParams = {+ format?: PersonsPropertiesTimelineCreateFormat;+ };++ export type PersonsPropertiesTimelineCreateFormat = typeof PersonsPropertiesTimelineCreateFormat[keyof typeof PersonsPropertiesTimelineCreateFormat];+++ export const PersonsPropertiesTimelineCreateFormat = {+ Csv: 'csv',+ Json: 'json',+ } as const;+export type PersonsPushNotificationsListParams = {/*** Start of the time range, matched on sent time. Relative ('-30d', '-24h') or ISO 8601. Defaults to -30d (the retention window) — bounds the ClickHouse partition scan.