Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(workflows): two-phase event sampling in testing tabs (#62626)

Meikel Ratz05419616da8d
diff --git a/frontend/src/scenes/hog-functions/configuration/hogFunctionConfigurationLogic.tsx b/frontend/src/scenes/hog-functions/configuration/hogFunctionConfigurationLogic.tsx
index cb3f2bb59a5f..31a5ef2cf4bc 100644
--- a/frontend/src/scenes/hog-functions/configuration/hogFunctionConfigurationLogic.tsx
+++ b/frontend/src/scenes/hog-functions/configuration/hogFunctionConfigurationLogic.tsx
@@ -64,6 +64,7 @@ import {
SurveyEventProperties,
} from '~/types'
+import { performWideEventsQueryInTwoPhases } from '../sampleEventsQuery'
import { eventToHogFunctionContextId } from '../sub-templates/sub-templates'
import type { hogFunctionConfigurationLogicType } from './hogFunctionConfigurationLogicType'
@@ -609,7 +610,7 @@ export const hogFunctionConfigurationLogic = kea<hogFunctionConfigurationLogicTy
'No events match these filters in the last 30 days. Showing an example $pageview event instead.'
try {
await breakpoint(values.sampleGlobals === null ? 10 : 1000)
- let response = await performQuery({
+ let response = await performWideEventsQueryInTwoPhases({
...values.lastEventQuery,
properties: eventId
? [
@@ -621,7 +622,7 @@ export const hogFunctionConfigurationLogic = kea<hogFunctionConfigurationLogicTy
: undefined,
})
if (!response?.results?.[0] && values.lastEventSecondQuery) {
- response = await performQuery({
+ response = await performWideEventsQueryInTwoPhases({
...values.lastEventSecondQuery,
properties: eventId
? [
diff --git a/frontend/src/scenes/hog-functions/sampleEventsQuery.test.ts b/frontend/src/scenes/hog-functions/sampleEventsQuery.test.ts
new file mode 100644
index 000000000000..6d8cd1a55d1d
--- /dev/null
+++ b/frontend/src/scenes/hog-functions/sampleEventsQuery.test.ts
@@ -0,0 +1,146 @@
+import { performQuery } from '~/queries/query'
+import { EventsQuery, NodeKind } from '~/queries/schema/schema-general'
+import { FilterLogicalOperator, PropertyFilterType } from '~/types'
+
+import { performWideEventsQueryInTwoPhases } from './sampleEventsQuery'
+
+jest.mock('~/queries/query', () => ({
+ performQuery: jest.fn(),
+}))
+
+const mockedPerformQuery = performQuery as jest.MockedFunction<typeof performQuery>
+
+const intent: EventsQuery = {
+ kind: NodeKind.EventsQuery,
+ select: ['*', 'person', 'tuple(organization.created_at, organization.index, organization.key)'],
+ fixedProperties: [
+ {
+ type: FilterLogicalOperator.And,
+ values: [{ type: PropertyFilterType.HogQL, key: "event = '$pageview'" }],
+ },
+ ],
+ after: '-7d',
+ limit: 10,
+ orderBy: ['timestamp DESC'],
+ modifiers: { personsOnEventsMode: 'person_id_no_override_properties_on_events' },
+}
+
+describe('performWideEventsQueryInTwoPhases', () => {
+ beforeEach(() => {
+ mockedPerformQuery.mockReset()
+ })
+
+ it('strips wide select in phase 1 while preserving filters, window, order, limit', async () => {
+ mockedPerformQuery.mockResolvedValueOnce({ results: [] })
+
+ await performWideEventsQueryInTwoPhases(intent)
+
+ expect(mockedPerformQuery).toHaveBeenCalledTimes(1)
+ const phaseOne = mockedPerformQuery.mock.calls[0][0] as EventsQuery
+ expect(phaseOne.select).toEqual(['uuid', 'timestamp'])
+ expect(phaseOne.fixedProperties).toEqual(intent.fixedProperties)
+ expect(phaseOne.after).toBe('-7d')
+ expect(phaseOne.limit).toBe(10)
+ expect(phaseOne.orderBy).toEqual(['timestamp DESC'])
+ expect(phaseOne.modifiers).toEqual(intent.modifiers)
+ })
+
+ it('returns the phase-1 response without running phase 2 when nothing matches', async () => {
+ const emptyResponse = { results: [], columns: [], types: [], hogql: 'SELECT' }
+ mockedPerformQuery.mockResolvedValueOnce(emptyResponse)
+
+ const result = await performWideEventsQueryInTwoPhases(intent)
+
+ expect(mockedPerformQuery).toHaveBeenCalledTimes(1)
+ expect(result).toBe(emptyResponse)
+ })
+
+ it('hydrates phase 2 with uuid filter and a narrow time window derived from phase-1 timestamps', async () => {
+ const phaseOneRows = [
+ ['uuid-newest', '2024-06-09T12:00:05.000Z'],
+ ['uuid-middle', '2024-06-09T12:00:03.000Z'],
+ ['uuid-oldest', '2024-06-09T12:00:01.000Z'],
+ ]
+ const hydratedResponse = { results: [['event-row', 'person-row']] }
+
+ mockedPerformQuery.mockResolvedValueOnce({ results: phaseOneRows }).mockResolvedValueOnce(hydratedResponse)
+
+ const result = await performWideEventsQueryInTwoPhases(intent)
+
+ expect(mockedPerformQuery).toHaveBeenCalledTimes(2)
+ const phaseTwo = mockedPerformQuery.mock.calls[1][0] as EventsQuery
+
+ // Phase 2 keeps the original wide select so the caller still gets the hydrated columns.
+ expect(phaseTwo.select).toEqual(intent.select)
+
+ // Phase 2 appends an extra fixedProperties group with `uuid IN [...]` and keeps the original filter.
+ expect(phaseTwo.fixedProperties).toHaveLength((intent.fixedProperties?.length ?? 0) + 1)
+ const uuidFilterGroup = phaseTwo.fixedProperties![phaseTwo.fixedProperties!.length - 1]
+ expect(uuidFilterGroup).toEqual({
+ type: FilterLogicalOperator.And,
+ values: [
+ {
+ type: PropertyFilterType.HogQL,
+ key: expect.stringMatching(/uuid IN \['uuid-newest', 'uuid-middle', 'uuid-oldest'\]/),
+ },
+ ],
+ })
+
+ // Phase 2 window is bounded by the oldest/newest phase-1 timestamps with a 1-second pad on each side.
+ expect(phaseTwo.after).toBe('2024-06-09T12:00:00.000Z')
+ expect(phaseTwo.before).toBe('2024-06-09T12:00:06.000Z')
+
+ // Phase 2 limit matches the candidate count so we never re-widen the result.
+ expect(phaseTwo.limit).toBe(phaseOneRows.length)
+
+ expect(result).toBe(hydratedResponse)
+ })
+
+ it('passes through additional fields on the intent query (filterTestAccounts, properties, where)', async () => {
+ const intentWithExtras: EventsQuery = {
+ ...intent,
+ filterTestAccounts: true,
+ where: ['team_id = 1'],
+ properties: [{ type: PropertyFilterType.HogQL, key: "properties.foo = 'bar'" }],
+ }
+ mockedPerformQuery
+ .mockResolvedValueOnce({ results: [['uuid-a', '2024-06-09T12:00:00.000Z']] })
+ .mockResolvedValueOnce({ results: [] })
+
+ await performWideEventsQueryInTwoPhases(intentWithExtras)
+
+ const phaseOne = mockedPerformQuery.mock.calls[0][0] as EventsQuery
+ const phaseTwo = mockedPerformQuery.mock.calls[1][0] as EventsQuery
+
+ expect(phaseOne.filterTestAccounts).toBe(true)
+ expect(phaseOne.where).toEqual(['team_id = 1'])
+ expect(phaseOne.properties).toEqual(intentWithExtras.properties)
+ expect(phaseTwo.filterTestAccounts).toBe(true)
+ expect(phaseTwo.where).toEqual(['team_id = 1'])
+ expect(phaseTwo.properties).toEqual(intentWithExtras.properties)
+ })
+
+ it('handles single-result phase 1 by collapsing the window to one timestamp ± 1s', async () => {
+ mockedPerformQuery
+ .mockResolvedValueOnce({ results: [['uuid-solo', '2024-06-09T12:00:05.000Z']] })
+ .mockResolvedValueOnce({ results: [['hydrated']] })
+
+ await performWideEventsQueryInTwoPhases(intent)
+
+ const phaseTwo = mockedPerformQuery.mock.calls[1][0] as EventsQuery
+ expect(phaseTwo.after).toBe('2024-06-09T12:00:04.000Z')
+ expect(phaseTwo.before).toBe('2024-06-09T12:00:06.000Z')
+ expect(phaseTwo.limit).toBe(1)
+ })
+
+ it('does not mutate the intent query', async () => {
+ const intentCopy = JSON.parse(JSON.stringify(intent))
+ mockedPerformQuery
+ .mockResolvedValueOnce({ results: [['uuid-a', '2024-06-09T12:00:00.000Z']] })
+ .mockResolvedValueOnce({ results: [] })
+
+ await performWideEventsQueryInTwoPhases(intent)
+
+ expect(intent).toEqual(intentCopy)
+ })
+})
diff --git a/frontend/src/scenes/hog-functions/sampleEventsQuery.ts b/frontend/src/scenes/hog-functions/sampleEventsQuery.ts
new file mode 100644
index 000000000000..80781c5d7ecc
--- /dev/null
+++ b/frontend/src/scenes/hog-functions/sampleEventsQuery.ts
@@ -0,0 +1,57 @@
+import { dayjs } from 'lib/dayjs'
+
+import { performQuery } from '~/queries/query'
+import { EventsQuery, EventsQueryResponse } from '~/queries/schema/schema-general'
+import { hogql } from '~/queries/utils'
+import { FilterLogicalOperator, PropertyFilterType } from '~/types'
+
+// Run an EventsQuery in two phases to avoid reading wide columns (`properties`, `elements_chain`,
+// `person_properties`, `groupN_properties`) for every row ClickHouse must scan to satisfy the filter.
+// Phase 1 scans only `uuid, timestamp` with the original filter + window + order + limit. Phase 2
+// re-issues the wide query constrained to those UUIDs and the narrow time window they landed in,
+// so the wide-column read only happens for the rows we keep.
+//
+// Filter evaluation cost is unchanged — both phases evaluate the same WHERE clause. The win is on
+// per-scanned-row projection cost during deep scans for sparse filters. See sessionEventsDataLogic
+// for the same window-bounded `uuid IN (...)` pattern applied elsewhere.
+export async function performWideEventsQueryInTwoPhases(intent: EventsQuery): Promise<EventsQueryResponse> {
+ const phaseOne: EventsQuery = {
+ ...intent,
+ select: ['uuid', 'timestamp'],
+ }
+ const phaseOneResponse = await performQuery(phaseOne)
+ const phaseOneResults = phaseOneResponse.results as Array<[string, string]>
+ if (phaseOneResults.length === 0) {
+ return phaseOneResponse
+ }
+
+ const uuids = phaseOneResults.map((r) => r[0])
+ const timestampsMs = phaseOneResults.map((r) => dayjs(r[1]).valueOf())
+ const after = dayjs(Math.min(...timestampsMs))
+ .subtract(1, 'second')
+ .toISOString()
+ const before = dayjs(Math.max(...timestampsMs))
+ .add(1, 'second')
+ .toISOString()
+
+ const phaseTwo: EventsQuery = {
+ ...intent,
+ fixedProperties: [
+ ...(intent.fixedProperties ?? []),
+ {
+ type: FilterLogicalOperator.And,
+ values: [
+ {
+ type: PropertyFilterType.HogQL,
+ key: hogql`uuid IN ${uuids}`,
+ },
+ ],
+ },
+ ],
+ after,
+ before,
+ limit: uuids.length,
+ }
+
+ return await performQuery(phaseTwo)
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/panel/testing/hogFlowEditorNotificationTestLogic.ts b/products/workflows/frontend/Workflows/hogflows/panel/testing/hogFlowEditorNotificationTestLogic.ts
index f6d73adb4f54..825247345643 100644
--- a/products/workflows/frontend/Workflows/hogflows/panel/testing/hogFlowEditorNotificationTestLogic.ts
+++ b/products/workflows/frontend/Workflows/hogflows/panel/testing/hogFlowEditorNotificationTestLogic.ts
@@ -7,8 +7,8 @@ import { lemonToast } from '@posthog/lemon-ui'
import api from 'lib/api'
import { dayjs } from 'lib/dayjs'
import { uuid } from 'lib/utils'
+import { performWideEventsQueryInTwoPhases } from 'scenes/hog-functions/sampleEventsQuery'
-import { performQuery } from '~/queries/query'
import { EventsQuery, NodeKind } from '~/queries/schema/schema-general'
import { hogql } from '~/queries/utils'
import { CyclotronJobInvocationGlobals, FilterLogicalOperator, PersonType, PropertyFilterType } from '~/types'
@@ -271,7 +271,7 @@ export const hogFlowEditorNotificationTestLogic = kea<hogFlowEditorNotificationT
},
}
- const eventResponse = await performQuery(query)
+ const eventResponse = await performWideEventsQueryInTwoPhases(query)
let event = eventResponse?.results?.[0]?.[0]
if (!event) {
diff --git a/products/workflows/frontend/Workflows/hogflows/panel/testing/hogFlowEditorTestLogic.ts b/products/workflows/frontend/Workflows/hogflows/panel/testing/hogFlowEditorTestLogic.ts
index 64d45b9007f6..b35d788427fa 100644
--- a/products/workflows/frontend/Workflows/hogflows/panel/testing/hogFlowEditorTestLogic.ts
+++ b/products/workflows/frontend/Workflows/hogflows/panel/testing/hogFlowEditorTestLogic.ts
@@ -9,9 +9,9 @@ import api from 'lib/api'
import { dayjs } from 'lib/dayjs'
import { groupsAccessLogic } from 'lib/introductions/groupsAccessLogic'
import { uuid } from 'lib/utils'
+import { performWideEventsQueryInTwoPhases } from 'scenes/hog-functions/sampleEventsQuery'
import { groupsModel } from '~/models/groupsModel'
-import { performQuery } from '~/queries/query'
import { EventsQuery, NodeKind } from '~/queries/schema/schema-general'
import { escapePropertyAsHogQLIdentifier, hogql } from '~/queries/utils'
import {
@@ -328,7 +328,7 @@ export const hogFlowEditorTestLogic = kea<hogFlowEditorTestLogicType>([
},
}
- const response = await performQuery(query)
+ const response = await performWideEventsQueryInTwoPhases(query)
if (!response?.results?.[0]) {
// No matching events found
@@ -417,7 +417,7 @@ export const hogFlowEditorTestLogic = kea<hogFlowEditorTestLogicType>([
},
}
- const response = await performQuery(query)
+ const response = await performWideEventsQueryInTwoPhases(query)
if (!response?.results?.[0]) {
// No matching events found, use standard example event