: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(replay): fetch pinned session properties for the overview tab (#67528)
Tue Haulund3e2e2cc28bc8
diff --git a/frontend/src/scenes/session-recordings/player/player-meta/playerMetaLogic.tsx b/frontend/src/scenes/session-recordings/player/player-meta/playerMetaLogic.tsxindex 1530b2721fab..8a4842c22c97 100644--- a/frontend/src/scenes/session-recordings/player/player-meta/playerMetaLogic.tsx+++ b/frontend/src/scenes/session-recordings/player/player-meta/playerMetaLogic.tsx@@ -118,11 +118,11 @@ export function getPropertyDisplayInfo(type: TaxonomicFilterGroupTypepropertyFilterType?: PropertyFilterType} {- const propertyType = recordingProperties?.[property]- ? // HogQL query can return multiple types, so we need to check- // but if it doesn't match a core definition it must be an event property- getFirstFilterTypeFor(property) || TaxonomicFilterGroupType.EventProperties- : TaxonomicFilterGroupType.PersonProperties+ const propertyType =+ recordingProperties && property in recordingProperties+ ? // anything the query returned that doesn't match a core definition must be an event property+ getFirstFilterTypeFor(property) || TaxonomicFilterGroupType.EventProperties+ : TaxonomicFilterGroupType.PersonPropertiesconst propertyFilterType: PropertyFilterType | undefined =propertyType === TaxonomicFilterGroupType.EventProperties@@ -500,39 +500,49 @@ export const playerMetaLogic = kea<playerMetaLogicType>([},],})),- listeners(({ actions, values, props }) => ({- loadRecordingMetaSuccess: () => {- // Skip if the list-wide fetch is in flight; calling again cancels it via breakpoint.+ listeners(({ actions, values, props }) => {+ // Skip if the list-wide fetch is in flight; calling again cancels it via breakpoint.+ const maybeLoadRecordingProperties = (): void => {if (values.sessionPlayerMetaData && !values.recordingPropertiesLoading) {actions.maybeLoadPropertiesForSessions([values.sessionPlayerMetaData])}- if (values.sessionPlayerMetaData?.has_summary && !values.sessionSummary && !values.sessionSummaryLoading) {- actions.summarizeSession()- }- },- sessionSummaryFeedback: ({ feedback }) => {- posthog.capture('session summary feedback', {- feedback,- session_summary: values.sessionSummary,- summary_id: values.sessionSummaryId,- summarized_session_id: props.sessionRecordingId,- })- actions.markFeedbackGiven(props.sessionRecordingId)- },- summarizeSession: () => {- // TODO: Remove after testing- const local = false- if (local) {- actions.setSummary(props.sessionRecordingId, aiSummaryMock)- return- }- const id = props.sessionRecordingId || props.sessionRecordingData?.sessionRecordingId- if (!id) {- return- }- // Delegates the SSE stream + per-session state to the singleton so that- // progress survives navigation away from and back to a recording mid-stream.- actions.startSummarization(id)- },- })),+ }+ return {+ // a newly pinned session property may not be in the cached recording properties yet+ setPinnedProperties: maybeLoadRecordingProperties,+ loadRecordingMetaSuccess: () => {+ maybeLoadRecordingProperties()+ if (+ values.sessionPlayerMetaData?.has_summary &&+ !values.sessionSummary &&+ !values.sessionSummaryLoading+ ) {+ actions.summarizeSession()+ }+ },+ sessionSummaryFeedback: ({ feedback }) => {+ posthog.capture('session summary feedback', {+ feedback,+ session_summary: values.sessionSummary,+ summary_id: values.sessionSummaryId,+ summarized_session_id: props.sessionRecordingId,+ })+ actions.markFeedbackGiven(props.sessionRecordingId)+ },+ summarizeSession: () => {+ // TODO: Remove after testing+ const local = false+ if (local) {+ actions.setSummary(props.sessionRecordingId, aiSummaryMock)+ return+ }+ const id = props.sessionRecordingId || props.sessionRecordingData?.sessionRecordingId+ if (!id) {+ return+ }+ // delegates the SSE stream + per-session state to the singleton so progress survives navigating away and back mid-stream+ actions.startSummarization(id)+ },+ }+ }),])diff --git a/frontend/src/scenes/session-recordings/playlist/sessionRecordingsListPropertiesLogic.test.ts b/frontend/src/scenes/session-recordings/playlist/sessionRecordingsListPropertiesLogic.test.tsindex b9ccd20dba02..8c114c2b74d9 100644--- a/frontend/src/scenes/session-recordings/playlist/sessionRecordingsListPropertiesLogic.test.ts+++ b/frontend/src/scenes/session-recordings/playlist/sessionRecordingsListPropertiesLogic.test.ts@@ -1,5 +1,6 @@import { expectLogic } from 'kea-test-utils'+import { sessionRecordingPinnedPropertiesLogic } from 'scenes/session-recordings/player/player-meta/sessionRecordingPinnedPropertiesLogic'import { sessionRecordingsListPropertiesLogic } from 'scenes/session-recordings/playlist/sessionRecordingsListPropertiesLogic'import { useMocks } from '~/mocks/jest'@@ -81,6 +82,22 @@ const mockSessons: SessionRecordingType[] = [},]+// matches the order of the base columns in the properties query, after the leading session_id+const S1_BASE_ROW = ['s1', 'AU', 'Chrome', 'Desktop', 'Windows', 'Windows 10', 'google.com', null, null, null]+const S2_BASE_ROW = ['s2', 'GB', 'Safari', 'Mobile', 'iOS', 'iOS 14', 'google.com', null, null, null]++// mock the query endpoint with a per-request handler that receives the HogQL query string+const useQueryMocks = (handler: (query: string) => unknown): void => {+ useMocks({+ post: {+ '/api/environments/:team_id/query/:kind': async (info: any) => {+ const body = await info.request.json()+ return handler(body.query.query)+ },+ },+ })+}+describe('sessionRecordingsListPropertiesLogic', () => {let logic: ReturnType<typeof sessionRecordingsListPropertiesLogic.build>@@ -88,10 +105,7 @@ describe('sessionRecordingsListPropertiesLogic', () => {useMocks({post: {'/api/environments/:team_id/query/:kind': {- results: [- ['s1', 'AU', 'Chrome', 'Desktop', 'Windows', 'Windows 10', 'google.com'],- ['s2', 'GB', 'Safari', 'Mobile', 'iOS', 'iOS 14', 'google.com'],- ],+ results: [S1_BASE_ROW, S2_BASE_ROW],},},})@@ -101,6 +115,7 @@ describe('sessionRecordingsListPropertiesLogic', () => {beforeEach(() => {logic = sessionRecordingsListPropertiesLogic()logic.mount()+ sessionRecordingPinnedPropertiesLogic.actions.setPinnedProperties([])})it('loads properties', async () => {@@ -131,4 +146,128 @@ describe('sessionRecordingsListPropertiesLogic', () => {recordingPropertiesById: EXPECTED_RECORDING_PROPERTIES_BY_ID,})})++ it('fetches pinned session properties alongside the base properties', async () => {+ const issuedQueries: string[] = []+ useQueryMocks((query) => {+ issuedQueries.push(query)+ return { results: [[...S1_BASE_ROW, 'paid', 'Paid Search']] }+ })++ sessionRecordingPinnedPropertiesLogic.actions.setPinnedProperties([+ 'Start',+ 'email',+ '$entry_utm_medium',+ '$channel_type',+ ])++ await expectLogic(logic, () => {+ logic.actions.loadPropertiesForSessions([mockSessons[0]])+ }).toDispatchActions(['loadPropertiesForSessionsSuccess'])++ expect(issuedQueries).toHaveLength(1)+ expect(issuedQueries[0]).toContain('any(session.$entry_utm_medium) as $entry_utm_medium')+ expect(issuedQueries[0]).toContain('any(session.$channel_type) as $channel_type')+ // non-session pins must not leak into the query+ expect(issuedQueries[0]).not.toContain('email')+ expect(issuedQueries[0]).not.toContain('Start')++ expect(logic.values.recordingPropertiesById['s1']).toMatchObject({+ $browser: 'Chrome',+ $entry_utm_medium: 'paid',+ $channel_type: 'Paid Search',+ })+ })++ it('refetches cached sessions that are missing newly pinned session properties', async () => {+ await expectLogic(logic, () => {+ logic.actions.loadPropertiesForSessions(mockSessons)+ }).toDispatchActions(['loadPropertiesForSessionsSuccess'])++ useQueryMocks(() => ({ results: [[...S1_BASE_ROW, 'paid']] }))+ sessionRecordingPinnedPropertiesLogic.actions.setPinnedProperties(['$entry_utm_medium'])++ await expectLogic(logic, () => {+ logic.actions.maybeLoadPropertiesForSessions([mockSessons[0]])+ }).toDispatchActions(['loadPropertiesForSessionsSuccess'])++ expect(logic.values.recordingPropertiesById['s1']).toMatchObject({ $entry_utm_medium: 'paid' })++ await expectLogic(logic, () => {+ logic.actions.maybeLoadPropertiesForSessions([mockSessons[0]])+ }).toNotHaveDispatchedActions(['loadPropertiesForSessions'])+ })++ it('falls back to the base properties when a pinned session property fails to query', async () => {+ const issuedQueries: string[] = []+ useQueryMocks((query) => {+ issuedQueries.push(query)+ if (query.includes('$entry_utm_medium')) {+ return [400, { detail: 'unknown field' }]+ }+ return {+ results: [query.includes('$channel_type') ? [...S1_BASE_ROW, 'Paid Search'] : S1_BASE_ROW],+ }+ })++ // a queryable pin loads fine on its own+ sessionRecordingPinnedPropertiesLogic.actions.setPinnedProperties(['$channel_type'])+ await expectLogic(logic, () => {+ logic.actions.loadPropertiesForSessions([mockSessons[0]])+ }).toDispatchActions(['loadPropertiesForSessionsSuccess'])+ expect(logic.values.recordingPropertiesById['s1']).toMatchObject({ $channel_type: 'Paid Search' })++ // adding an unqueryable pin fails the wide query and falls back to the base one+ sessionRecordingPinnedPropertiesLogic.actions.setPinnedProperties(['$channel_type', '$entry_utm_medium'])+ await expectLogic(logic, () => {+ logic.actions.maybeLoadPropertiesForSessions([mockSessons[0]])+ }).toDispatchActions(['loadPropertiesForSessionsSuccess'])++ // cached values survive the fallback and the failed pin reads as complete (null), so no refetch loop+ expect(logic.values.recordingPropertiesById['s1']).toMatchObject({+ $browser: 'Chrome',+ $channel_type: 'Paid Search',+ $entry_utm_medium: null,+ })+ await expectLogic(logic, () => {+ logic.actions.maybeLoadPropertiesForSessions([mockSessons[0]])+ }).toNotHaveDispatchedActions(['loadPropertiesForSessions'])++ // the failed pin set is remembered: new sessions load with a single base query+ const queriesSoFar = issuedQueries.length+ await expectLogic(logic, () => {+ logic.actions.maybeLoadPropertiesForSessions([mockSessons[1]])+ }).toDispatchActions(['loadPropertiesForSessionsSuccess'])+ expect(issuedQueries).toHaveLength(queriesSoFar + 1)+ expect(issuedQueries[issuedQueries.length - 1]).not.toContain('$entry_utm_medium')+ })++ it('retries the extended query after a transient failure', async () => {+ const issuedQueries: string[] = []+ let failWideQuery = true+ useQueryMocks((query) => {+ issuedQueries.push(query)+ if (query.includes('$entry_utm_medium')) {+ if (failWideQuery) {+ return [500, { detail: 'timeout' }]+ }+ return { results: [[...S2_BASE_ROW, 'paid']] }+ }+ return { results: [S1_BASE_ROW] }+ })+ sessionRecordingPinnedPropertiesLogic.actions.setPinnedProperties(['$entry_utm_medium'])++ await expectLogic(logic, () => {+ logic.actions.loadPropertiesForSessions([mockSessons[0]])+ }).toDispatchActions(['loadPropertiesForSessionsSuccess'])++ // a 5xx does not mark the pin set unqueryable — the next batch retries the wide query+ failWideQuery = false+ await expectLogic(logic, () => {+ logic.actions.maybeLoadPropertiesForSessions([mockSessons[1]])+ }).toDispatchActions(['loadPropertiesForSessionsSuccess'])++ expect(issuedQueries[issuedQueries.length - 1]).toContain('$entry_utm_medium')+ expect(logic.values.recordingPropertiesById['s2']).toMatchObject({ $entry_utm_medium: 'paid' })+ })})diff --git a/frontend/src/scenes/session-recordings/playlist/sessionRecordingsListPropertiesLogic.ts b/frontend/src/scenes/session-recordings/playlist/sessionRecordingsListPropertiesLogic.tsindex 83f989344fbf..a5924d067c5d 100644--- a/frontend/src/scenes/session-recordings/playlist/sessionRecordingsListPropertiesLogic.ts+++ b/frontend/src/scenes/session-recordings/playlist/sessionRecordingsListPropertiesLogic.ts@@ -1,30 +1,87 @@-import { actions, connect, kea, listeners, path, reducers } from 'kea'+import { actions, connect, kea, listeners, path, reducers, selectors } from 'kea'import { loaders } from 'kea-loaders'-import api from 'lib/api'+import api, { ApiError } from 'lib/api'import { dayjs } from 'lib/dayjs'import { sessionRecordingEventUsageLogic } from 'scenes/session-recordings/sessionRecordingEventUsageLogic'-import { hogql } from '~/queries/utils'+import { QueryLogTags } from '~/queries/schema/schema-general'+import { HogQLQueryString, escapePropertyAsHogQLIdentifier, hogql } from '~/queries/utils'import { CORE_FILTER_DEFINITIONS_BY_GROUP } from '~/taxonomy/taxonomy'import { SessionRecordingPropertiesType, SessionRecordingType } from '~/types'+import { sessionRecordingPinnedPropertiesLogic } from '../player/player-meta/sessionRecordingPinnedPropertiesLogic'import type { sessionRecordingsListPropertiesLogicType } from './sessionRecordingsListPropertiesLogicType'+const QUERY_TAGS: QueryLogTags = { scene: 'Replay', productKey: 'session_replay' }++// [source table, property] pairs; order defines the result columns+const BASE_QUERY_PROPERTIES: [string, string][] = [+ ['properties', '$geoip_country_code'],+ ['properties', '$browser'],+ ['properties', '$device_type'],+ ['properties', '$os'],+ ['properties', '$os_name'],+ ['session', '$entry_referring_domain'],+ ['properties', '$geoip_subdivision_1_name'],+ ['properties', '$geoip_city_name'],+ ['session', '$entry_current_url'],+]+const BASE_PROPERTIES = BASE_QUERY_PROPERTIES.map(([, property]) => property)++function pinnedSessionProperties(pinnedProperties: string[]): string[] {+ return pinnedProperties.filter(+ (property) =>+ Object.hasOwn(CORE_FILTER_DEFINITIONS_BY_GROUP.session_properties, property) &&+ !BASE_PROPERTIES.includes(property)+ )+}++function buildPropertiesQuery(+ sessionIds: string[],+ oldestTimestamp: string,+ newestTimestamp: string | undefined,+ extraSessionProperties: string[]+): HogQLQueryString {+ const selects = [+ ...BASE_QUERY_PROPERTIES,+ ...extraSessionProperties.map((property): [string, string] => ['session', property]),+ ]+ .map(([source, property]) => {+ const identifier = escapePropertyAsHogQLIdentifier(property)+ return `any(${source}.${identifier}) as ${identifier}`+ })+ .join(',\n ')++ return hogql`+ SELECT+ $session_id as session_id,+ ${hogql.raw(selects)}+ FROM events+ WHERE event IN ${Object.keys(CORE_FILTER_DEFINITIONS_BY_GROUP['events'])}+ AND session_id IN ${sessionIds}+ -- the timestamp range only bounds the events-table scan, padded a day each side so timezones can't cause issues+ AND timestamp >= ${dayjs(oldestTimestamp).subtract(1, 'day')}+ AND timestamp <= ${dayjs(newestTimestamp).add(1, 'day')}+ GROUP BY session_id`+}+// This logic is used to fetch properties for a list of recordings// It is used in a global way as the cached values can be re-usedexport const sessionRecordingsListPropertiesLogic = kea<sessionRecordingsListPropertiesLogicType>([path(() => ['scenes', 'session-recordings', 'playlist', 'sessionRecordingsListPropertiesLogic']),connect(() => ({actions: [sessionRecordingEventUsageLogic, ['reportRecordingsListPropertiesFetched']],+ values: [sessionRecordingPinnedPropertiesLogic, ['pinnedProperties']],})),actions({loadPropertiesForSessions: (sessions: SessionRecordingType[]) => ({ sessions }),maybeLoadPropertiesForSessions: (sessions: SessionRecordingType[]) => ({ sessions }),+ markExtraPropertiesUnqueryable: (properties: string[]) => ({ properties }),}),- loaders(({ actions }) => ({+ loaders(({ actions, values }) => ({recordingProperties: [[] as SessionRecordingPropertiesType[],{@@ -37,66 +94,49 @@ export const sessionRecordingsListPropertiesLogic = kea<sessionRecordingsListProconst oldestTimestamp = sessions.map((x) => x.start_time).sort()[0]const newestTimestamp = sessions.map((x) => x.end_time).sort()[sessions.length - 1]- const query = hogql`- SELECT- $session_id as session_id,- any(properties.$geoip_country_code) as $geoip_country_code,- any(properties.$browser) as $browser,- any(properties.$device_type) as $device_type,- any(properties.$os) as $os,- any(properties.$os_name) as $os_name,- any(session.$entry_referring_domain) as $entry_referring_domain,- any(properties.$geoip_subdivision_1_name) as $geoip_subdivision_1_name,- any(properties.$geoip_city_name) as $geoip_city_name,- any(session.$entry_current_url) as $entry_current_url- FROM events- WHERE event IN ${Object.keys(CORE_FILTER_DEFINITIONS_BY_GROUP['events'])}- AND session_id IN ${sessionIds}- -- the timestamp range here is only to avoid querying too much of the events table- -- we don't really care about the absolute value,- -- but we do care about whether timezones have an odd impact- -- so, we extend the range by a day on each side so that timezones don't cause issues- AND timestamp >= ${dayjs(oldestTimestamp).subtract(1, 'day')}- AND timestamp <= ${dayjs(newestTimestamp).add(1, 'day')}- GROUP BY session_id`-- const response = await api.queryHogQL(query, { scene: 'Replay', productKey: 'session_replay' })+ const extraSessionProperties = values.extraSessionProperties+ let response+ try {+ response = await api.queryHogQL(+ buildPropertiesQuery(sessionIds, oldestTimestamp, newestTimestamp, extraSessionProperties),+ QUERY_TAGS+ )+ } catch (e) {+ if (!extraSessionProperties.length) {+ throw e+ }+ response = await api.queryHogQL(+ buildPropertiesQuery(sessionIds, oldestTimestamp, newestTimestamp, []),+ QUERY_TAGS+ )+ // only a 400 (a pin missing from this project's session table) blacklists the pin set — transient errors retry next batch+ if (e instanceof ApiError && e.status === 400) {+ actions.markExtraPropertiesUnqueryable(extraSessionProperties)+ }+ }const loadTimeMs = performance.now() - startTimeactions.reportRecordingsListPropertiesFetched(loadTimeMs)breakpoint()- return (response.results || []).map((x: any): SessionRecordingPropertiesType => {- return {- id: x[0],- properties: {- $geoip_country_code: x[1],- $browser: x[2],- $device_type: x[3],- $os: x[4],- $os_name: x[5],- $entry_referring_domain: x[6],- $geoip_subdivision_1_name: x[7],- $geoip_city_name: x[8],- $entry_current_url: x[9],- },- }+ return (response.results || []).map((row: any[]): SessionRecordingPropertiesType => {+ const cachedProperties = values.recordingPropertiesById[row[0]]+ const properties: Record<string, any> = {}+ BASE_PROPERTIES.forEach((property, index) => {+ properties[property] = row[index + 1]+ })+ // fallback rows have no extra columns — keep cached values (or null) so entries read as complete+ extraSessionProperties.forEach((property, index) => {+ properties[property] =+ row[BASE_PROPERTIES.length + 1 + index] ?? cachedProperties?.[property] ?? null+ })+ return { id: row[0], properties }})},},],})),- listeners(({ actions, values }) => ({- maybeLoadPropertiesForSessions: ({ sessions }) => {- const newSessions = sessions.filter((session) => !values.recordingPropertiesById[session.id])-- if (newSessions.length > 0) {- actions.loadPropertiesForSessions(newSessions)- }- },- })),-reducers({recordingPropertiesById: [{} as Record<string, SessionRecordingPropertiesType['properties']>,@@ -116,5 +156,43 @@ export const sessionRecordingsListPropertiesLogic = kea<sessionRecordingsListPro},},],+ unqueryableExtraProperties: [+ null as string[] | null,+ {+ markExtraPropertiesUnqueryable: (_, { properties }) => properties,+ },+ ],}),++ selectors({+ extraSessionProperties: [+ (s) => [s.pinnedProperties, s.unqueryableExtraProperties],+ (pinnedProperties, unqueryableExtraProperties): string[] => {+ const extras = pinnedSessionProperties(pinnedProperties)+ // while the pin set that failed to query is unchanged, don't retry it+ if (+ unqueryableExtraProperties &&+ extras.length === unqueryableExtraProperties.length &&+ extras.every((property, index) => property === unqueryableExtraProperties[index])+ ) {+ return []+ }+ return extras+ },+ ],+ }),++ listeners(({ actions, values }) => ({+ maybeLoadPropertiesForSessions: ({ sessions }) => {+ const wantedSessionProperties = values.extraSessionProperties+ const newSessions = sessions.filter((session) => {+ const cached = values.recordingPropertiesById[session.id]+ return !cached || wantedSessionProperties.some((property) => !(property in cached))+ })++ if (newSessions.length > 0) {+ actions.loadPropertiesForSessions(newSessions)+ }+ },+ })),])