: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(cdp): tighten phase-2 hydration and add 24h pre-stage to event sampler (#62701)
Meikel Ratz270a66b333fa
diff --git a/frontend/src/scenes/hog-functions/sampleEventsQuery.test.ts b/frontend/src/scenes/hog-functions/sampleEventsQuery.test.tsindex 6d8cd1a55d1d..c7a325f90013 100644--- a/frontend/src/scenes/hog-functions/sampleEventsQuery.test.ts+++ b/frontend/src/scenes/hog-functions/sampleEventsQuery.test.ts@@ -30,117 +30,199 @@ describe('performWideEventsQueryInTwoPhases', () => {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)+ describe('24h pre-stage', () => {+ it('runs a 24h two-phase first when the caller window is wider than 24h, and returns it on success', async () => {+ mockedPerformQuery+ // Pre-stage phase 1 (24h)+ .mockResolvedValueOnce({+ results: [['019eacd8-2ab7-76b0-8e40-604d7f8e6961', '2026-06-09T07:45:08.404000-07:00']],+ })+ // Pre-stage phase 2 (24h hydration)+ .mockResolvedValueOnce({ results: [['hydrated-recent']] })++ const result = await performWideEventsQueryInTwoPhases(intent)++ expect(mockedPerformQuery).toHaveBeenCalledTimes(2)+ const preStagePhaseOne = mockedPerformQuery.mock.calls[0][0] as EventsQuery+ expect(preStagePhaseOne.after).toBe('-24h')+ expect(preStagePhaseOne.select).toEqual(['uuid', 'timestamp'])++ expect((result.results as unknown[])[0]).toEqual(['hydrated-recent'])+ })- const result = await performWideEventsQueryInTwoPhases(intent)+ it('falls through to the original window when the 24h pre-stage finds nothing', async () => {+ mockedPerformQuery+ // Pre-stage phase 1 (24h) — empty+ .mockResolvedValueOnce({ results: [] })+ // Main phase 1 (7d)+ .mockResolvedValueOnce({+ results: [['019eacd8-2ab7-76b0-8e40-604d7f8e6961', '2026-06-09T07:45:08.404000-07:00']],+ })+ // Main phase 2 (hydration)+ .mockResolvedValueOnce({ results: [['hydrated-week']] })++ const result = await performWideEventsQueryInTwoPhases(intent)++ expect(mockedPerformQuery).toHaveBeenCalledTimes(3)+ expect((mockedPerformQuery.mock.calls[0][0] as EventsQuery).after).toBe('-24h')+ expect((mockedPerformQuery.mock.calls[1][0] as EventsQuery).after).toBe('-7d')+ expect((result.results as unknown[])[0]).toEqual(['hydrated-week'])+ })- expect(mockedPerformQuery).toHaveBeenCalledTimes(1)- expect(result).toBe(emptyResponse)+ // Boundary table: each row asserts the full sequence of `after` values ClickHouse sees.+ // A leading `-24h` means the pre-stage fired; otherwise it was skipped. All mocked phase-1+ // responses are empty so each entry in `expectedAfters` corresponds to exactly one query.+ it.each([+ { label: 'exactly 24h', after: '-24h', expectedAfters: ['-24h'] },+ { label: 'narrower than 24h', after: '-1h', expectedAfters: ['-1h'] },+ { label: 'no window specified', after: undefined, expectedAfters: [undefined] },+ { label: '30d', after: '-30d', expectedAfters: ['-24h', '-30d'] },+ ])('pre-stage boundary: $label', async ({ after, expectedAfters }) => {+ for (let i = 0; i < expectedAfters.length; i++) {+ mockedPerformQuery.mockResolvedValueOnce({ results: [] })+ }++ await performWideEventsQueryInTwoPhases({ ...intent, after })++ const actualAfters = mockedPerformQuery.mock.calls.map((c) => (c[0] as EventsQuery).after)+ expect(actualAfters).toEqual(expectedAfters)+ })})- 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)+ describe('two-phase mechanics (pre-stage empty, falling through to caller window)', () => {+ // Pre-stage is always empty in this block so the assertions read against the main two-phase+ // call, which is what each test actually exercises.+ const emptyPreStage = (): void => {+ mockedPerformQuery.mockResolvedValueOnce({ results: [] })+ }- expect(mockedPerformQuery).toHaveBeenCalledTimes(2)- const phaseTwo = mockedPerformQuery.mock.calls[1][0] as EventsQuery+ it('strips wide select in phase 1 while preserving filters, window, order, limit', async () => {+ emptyPreStage()+ mockedPerformQuery.mockResolvedValueOnce({ results: [] })- // Phase 2 keeps the original wide select so the caller still gets the hydrated columns.- expect(phaseTwo.select).toEqual(intent.select)+ await performWideEventsQueryInTwoPhases(intent)- // 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'\]/),- },- ],+ expect(mockedPerformQuery).toHaveBeenCalledTimes(2)+ const phaseOne = mockedPerformQuery.mock.calls[1][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)})- // 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)+ it('returns the phase-1 response without running phase 2 when nothing matches', async () => {+ emptyPreStage()+ const emptyResponse = { results: [], columns: [], types: [], hogql: 'SELECT' }+ mockedPerformQuery.mockResolvedValueOnce(emptyResponse)- 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: [] })+ const result = await performWideEventsQueryInTwoPhases(intent)- await performWideEventsQueryInTwoPhases(intentWithExtras)+ expect(mockedPerformQuery).toHaveBeenCalledTimes(2)+ expect(result).toBe(emptyResponse)+ })- const phaseOne = mockedPerformQuery.mock.calls[0][0] as EventsQuery- const phaseTwo = mockedPerformQuery.mock.calls[1][0] as EventsQuery+ it('hydrates phase 2 by exact (uuid, timestamp) tuples, drops the original filter, and bounds the window', async () => {+ emptyPreStage()+ const phaseOneRows = [+ ['019eacd8-2ab7-76b0-8e40-604d7f8e6961', '2026-06-09T07:45:08.404000-07:00'],+ ['019eaca0-c933-7806-9aab-e211b2cdf59b', '2026-06-09T06:44:38.960000-07:00'],+ ['019e8f53-c8b8-748d-8619-f4ffb26e8e93', '2026-06-03T14:11:33.301000-07:00'],+ ]+ const hydratedResponse = { results: [['event-row', 'person-row']] }++ mockedPerformQuery.mockResolvedValueOnce({ results: phaseOneRows }).mockResolvedValueOnce(hydratedResponse)++ const result = await performWideEventsQueryInTwoPhases(intent)++ expect(mockedPerformQuery).toHaveBeenCalledTimes(3)+ const phaseTwo = mockedPerformQuery.mock.calls[2][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 drops the original filter — phase 1 already certified those UUIDs.+ expect(phaseTwo.fixedProperties).toBeUndefined()+ expect(phaseTwo.properties).toBeUndefined()++ // Phase 2 hydrates by exact (uuid, timestamp) tuples for primary-key granule pruning.+ // Timestamps are converted to UTC microsecond precision so the equality match is exact.+ expect(phaseTwo.where).toHaveLength(1)+ const whereFragment = phaseTwo.where![0]+ expect(whereFragment).toContain('(uuid, timestamp) IN (')+ expect(whereFragment).toContain("'019eacd8-2ab7-76b0-8e40-604d7f8e6961'")+ expect(whereFragment).toContain("'019eaca0-c933-7806-9aab-e211b2cdf59b'")+ expect(whereFragment).toContain("'019e8f53-c8b8-748d-8619-f4ffb26e8e93'")+ expect(whereFragment).toContain("toDateTime64('2026-06-09 14:45:08.404000', 6, 'UTC')")+ expect(whereFragment).toContain("toDateTime64('2026-06-09 13:44:38.960000', 6, 'UTC')")+ expect(whereFragment).toContain("toDateTime64('2026-06-03 21:11:33.301000', 6, 'UTC')")++ // Phase 2 window is bounded by the oldest/newest phase-1 timestamps with a 1-second pad+ // on each side as a belt-and-suspenders narrowing for granule pruning.+ expect(phaseTwo.after).toBe('2026-06-03T21:11:32.301Z')+ expect(phaseTwo.before).toBe('2026-06-09T14:45:09.404Z')++ // Phase 2 limit matches the candidate count so we never re-widen the result.+ expect(phaseTwo.limit).toBe(phaseOneRows.length)++ expect(result).toBe(hydratedResponse)+ })- 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('preserves caller-supplied `where` fragments in phase 2 and appends the tuple filter', async () => {+ emptyPreStage()+ const intentWithWhere: EventsQuery = {+ ...intent,+ where: ['team_id = 1'],+ }+ mockedPerformQuery+ .mockResolvedValueOnce({+ results: [['019eacd8-2ab7-76b0-8e40-604d7f8e6961', '2026-06-09T07:45:08.404000-07:00']],+ })+ .mockResolvedValueOnce({ results: [] })++ await performWideEventsQueryInTwoPhases(intentWithWhere)++ const phaseOne = mockedPerformQuery.mock.calls[1][0] as EventsQuery+ const phaseTwo = mockedPerformQuery.mock.calls[2][0] as EventsQuery++ // Phase 1 keeps the original `where` alongside the original filter for correctness.+ expect(phaseOne.where).toEqual(['team_id = 1'])++ // Phase 2 keeps the caller's `where` and appends the tuple filter at the end.+ expect(phaseTwo.where).toHaveLength(2)+ expect(phaseTwo.where![0]).toBe('team_id = 1')+ expect(phaseTwo.where![1]).toContain('(uuid, timestamp) IN (')+ })- 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']] })+ it('handles single-result phase 1 by collapsing the window to one timestamp ± 1s', async () => {+ emptyPreStage()+ mockedPerformQuery+ .mockResolvedValueOnce({+ results: [['019eacd8-2ab7-76b0-8e40-604d7f8e6961', '2026-06-09T12:00:05.000000Z']],+ })+ .mockResolvedValueOnce({ results: [['hydrated']] })- await performWideEventsQueryInTwoPhases(intent)+ 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)- })+ const phaseTwo = mockedPerformQuery.mock.calls[2][0] as EventsQuery+ expect(phaseTwo.after).toBe('2026-06-09T12:00:04.000Z')+ expect(phaseTwo.before).toBe('2026-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: [] })+ it('does not mutate the intent query', async () => {+ emptyPreStage()+ const intentCopy = JSON.parse(JSON.stringify(intent))+ mockedPerformQuery+ .mockResolvedValueOnce({+ results: [['019eacd8-2ab7-76b0-8e40-604d7f8e6961', '2026-06-09T12:00:00.000000Z']],+ })+ .mockResolvedValueOnce({ results: [] })- await performWideEventsQueryInTwoPhases(intent)+ await performWideEventsQueryInTwoPhases(intent)- expect(intent).toEqual(intentCopy)+ expect(intent).toEqual(intentCopy)+ })})})diff --git a/frontend/src/scenes/hog-functions/sampleEventsQuery.ts b/frontend/src/scenes/hog-functions/sampleEventsQuery.tsindex 80781c5d7ecc..f2a22704051f 100644--- a/frontend/src/scenes/hog-functions/sampleEventsQuery.ts+++ b/frontend/src/scenes/hog-functions/sampleEventsQuery.ts@@ -2,19 +2,33 @@ 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.++// Two-phase EventsQuery to keep memory bounded on high-volume teams.+//+// Phase 1 keeps the original filter but projects only `uuid, timestamp` — wide JSON columns+// (`properties`, `person_properties`, `groupN_properties`, `elements_chain`) aren't decompressed.//-// 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.+// Phase 2 hydrates by exact `(uuid, timestamp)` tuples and drops the original filter. Phase 1+// already certified the matches, so re-applying the filter would force ClickHouse to re-read+// `properties` for filter evaluation across the same granule set — and now also project the wide+// JSON columns on top, which is what trips the per-query memory limit. The tuple constraint lets+// the primary-key sparse index over `(team_id, toDate(timestamp), event, ...)` prune to just the+// granules holding those rows.+//+// On top of that, when the caller's window is wider than 24h we try a 24h pre-stage first. Most+// matching events the user wants to test against fire recently, so this skips the deep scan when+// possible. If the 24h pre-stage returns nothing we fall through to the caller's original window.export async function performWideEventsQueryInTwoPhases(intent: EventsQuery): Promise<EventsQueryResponse> {+ if (shouldTry24hPreStage(intent.after)) {+ const preResponse = await runTwoPhase({ ...intent, after: '-24h' })+ if ((preResponse.results as unknown[]).length > 0) {+ return preResponse+ }+ }+ return await runTwoPhase(intent)+}++async function runTwoPhase(intent: EventsQuery): Promise<EventsQueryResponse> {const phaseOne: EventsQuery = {...intent,select: ['uuid', 'timestamp'],@@ -25,8 +39,7 @@ export async function performWideEventsQueryInTwoPhases(intent: EventsQuery): Prreturn phaseOneResponse}- const uuids = phaseOneResults.map((r) => r[0])- const timestampsMs = phaseOneResults.map((r) => dayjs(r[1]).valueOf())+ const timestampsMs = phaseOneResults.map(([, t]) => dayjs(t).valueOf())const after = dayjs(Math.min(...timestampsMs)).subtract(1, 'second').toISOString()@@ -34,24 +47,46 @@ export async function performWideEventsQueryInTwoPhases(intent: EventsQuery): Pr.add(1, 'second').toISOString()+ const tupleList = phaseOneResults.map(([u, t]) => `('${u}', ${formatClickHouseUtcDateTime64(t)})`).join(', ')+const phaseTwo: EventsQuery = {...intent,- fixedProperties: [- ...(intent.fixedProperties ?? []),- {- type: FilterLogicalOperator.And,- values: [- {- type: PropertyFilterType.HogQL,- key: hogql`uuid IN ${uuids}`,- },- ],- },- ],+ fixedProperties: undefined,+ properties: undefined,+ where: [...(intent.where ?? []), `(uuid, timestamp) IN (${tupleList})`],after,before,- limit: uuids.length,+ limit: phaseOneResults.length,}return await performQuery(phaseTwo)}++// dayjs only has millisecond precision, so lift the microseconds straight from the source string+// and reattach them after converting the base to UTC.+function formatClickHouseUtcDateTime64(timestamp: string): string {+ const microsMatch = timestamp.match(/\.(\d{1,6})/)+ const micros = (microsMatch?.[1] ?? '').padEnd(6, '0')+ const base = dayjs(timestamp).utc().format('YYYY-MM-DD HH:mm:ss')+ return `toDateTime64('${base}.${micros}', 6, 'UTC')`+}++// Returns true if `after` represents a window strictly wider than 24h. Accepts the relative range+// shorthand the testing flows use (`-7d`, `-30d`, `-24h`, `-1h`, etc.) and absolute ISO timestamps.+// If the window is 24h or narrower we skip the pre-stage so we never widen a caller's request.+function shouldTry24hPreStage(after: string | undefined): boolean {+ if (!after) {+ return false+ }+ const relativeMatch = after.match(/^-(\d+)([smhdwMy])$/)+ if (relativeMatch) {+ const value = parseInt(relativeMatch[1], 10)+ const unit = relativeMatch[2] as 's' | 'm' | 'h' | 'd' | 'w' | 'M' | 'y'+ return dayjs.duration(value, unit).asHours() > 24+ }+ const parsed = dayjs(after)+ if (parsed.isValid()) {+ return dayjs().diff(parsed, 'hour', true) > 24+ }+ return false+}