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.

feat(cdp): page a realtime cohort's members for a batch hogflow run (#117740)

Harley Alexander77f18adc7ec7
diff --git a/nodejs/src/cdp/cdp-api.ts b/nodejs/src/cdp/cdp-api.ts
index 771fba5000f4..ae46852b622c 100644
--- a/nodejs/src/cdp/cdp-api.ts
+++ b/nodejs/src/cdp/cdp-api.ts
@@ -128,6 +128,16 @@ function canDedupeByEmail(hogFlow: { actions?: unknown }): boolean {
export type CdpApiConfig = PluginsServerConfig
export type CdpApiDeps = CdpConsumerBaseDeps
+function parseRealtimeCohort(value: unknown): BatchResolverState['realtimeCohort'] {
+ if (typeof value !== 'object' || value === null) {
+ return undefined
+ }
+ const { id, team_id } = value as { id?: unknown; team_id?: unknown }
+ return Number.isInteger(id) && Number.isInteger(team_id)
+ ? { id: id as number, teamId: team_id as number }
+ : undefined
+}
+
export class CdpApi {
private hogExecutorAsync: HogExecutorAsyncService
private hogInputsService: HogInputsService
@@ -1435,6 +1445,7 @@ export class CdpApi {
// dedupe than dedupe wrongly. Also skip when the flow has no email action at all.
// Account audiences carry no person (and external ids are already unique), so never dedupe.
dedupeKey: audienceType !== 'accounts' && canDedupeByEmail(hogFlow) ? ('email' as const) : undefined,
+ realtimeCohort: parseRealtimeCohort(req.body.realtime_cohort),
maxAudienceSize: maxAudienceSize ?? this.config.CDP_BATCH_WORKFLOW_MAX_AUDIENCE_SIZE,
cursor: null,
totalEnqueued: 0,
diff --git a/nodejs/src/cdp/consumers/cdp-cyclotron-worker-batch-resolve.consumer.test.ts b/nodejs/src/cdp/consumers/cdp-cyclotron-worker-batch-resolve.consumer.test.ts
index ec4e9be5c481..a53ee91c03c8 100644
--- a/nodejs/src/cdp/consumers/cdp-cyclotron-worker-batch-resolve.consumer.test.ts
+++ b/nodejs/src/cdp/consumers/cdp-cyclotron-worker-batch-resolve.consumer.test.ts
@@ -163,6 +163,28 @@ describe('CdpCyclotronWorkerBatchResolve', () => {
})
})
+ it('pages a realtime cohort audience from realtime membership, not the Django audience query', async () => {
+ const getMemberPage = jest.fn().mockResolvedValue({
+ ids: ['member-1', 'member-2', 'member-3'],
+ cursor: 'member-3',
+ has_more: false,
+ })
+ Object.assign(consumer, {
+ config: { SITE_URL: 'https://us.posthog.com', BEHAVIORAL_COHORTS_DATABASE_URL: 'postgres://cohorts' },
+ realtimeCohortAudience: { getMemberPage },
+ })
+
+ await (consumer as any).processOnePage(
+ { bulkCreateAndCheckIn, reschedule: jest.fn() },
+ { ...state, realtimeCohort: { id: 42, teamId: 7 } }
+ )
+
+ // Membership rows belong to the cohort's own team, which can differ from the workflow's.
+ expect(getMemberPage).toHaveBeenCalledWith(7, 42, null)
+ expect((consumer as any).hogFlowBatchPersonQueryService.getBlastRadiusPersons).not.toHaveBeenCalled()
+ expect(triggeredMetrics()).toHaveLength(3)
+ })
+
it('counts each enrolled person as a triggered run against the batch job', async () => {
await processPage()
@@ -453,6 +475,27 @@ describe('CdpCyclotronWorkerBatchResolve', () => {
)
})
+ it('fails a realtime cohort run at once when the resolver has no behavioral cohorts database', async () => {
+ // Without its own URL the router reads the main database, so retrying would never succeed.
+ const queueLogs = jest.fn()
+ const getBlastRadiusPersons = jest.fn()
+ const consumer = buildConsumer(getBlastRadiusPersons, queueLogs)
+ const job = buildJob({ ...lastAttemptState(), attempts: 0, realtimeCohort: { id: 42, teamId: team.id } })
+
+ await consumer.processResolverJob(job)
+
+ expect(getBlastRadiusPersons).not.toHaveBeenCalled()
+ expect(queueLogs).toHaveBeenCalledWith(
+ [
+ expect.objectContaining({
+ message:
+ "Batch resolver failed: Sending to a realtime cohort isn't available here yet. Use a different audience.",
+ }),
+ ],
+ 'hog_flow'
+ )
+ })
+
it('keeps the generic reason for a failure that is not a timeout', async () => {
const queueLogs = jest.fn()
const consumer = buildConsumer(jest.fn().mockRejectedValue(new Error('network down')), queueLogs)
diff --git a/nodejs/src/cdp/consumers/cdp-cyclotron-worker-batch-resolve.consumer.ts b/nodejs/src/cdp/consumers/cdp-cyclotron-worker-batch-resolve.consumer.ts
index c284aabd6862..69d52c8c06cb 100644
--- a/nodejs/src/cdp/consumers/cdp-cyclotron-worker-batch-resolve.consumer.ts
+++ b/nodejs/src/cdp/consumers/cdp-cyclotron-worker-batch-resolve.consumer.ts
@@ -20,6 +20,7 @@ import {
AudienceFetchTimeoutError,
HogFlowBatchPersonQueryService,
} from '../services/hogflows/hogflow-batch-person-query.service'
+import { RealtimeCohortAudienceService } from '../services/hogflows/realtime-cohort-audience.service'
import { invocationToV2JobInit } from '../services/job-queue/job-queue-postgres-v2'
import { CyclotronJobInvocationHogFlow } from '../types'
import {
@@ -89,8 +90,11 @@ export class CdpCyclotronWorkerBatchResolve extends CdpConsumerBase<PluginsServe
private internalFetchService: InternalFetchService
) {
super(config, deps)
+ this.realtimeCohortAudience = new RealtimeCohortAudienceService(deps.postgres)
}
+ private realtimeCohortAudience: RealtimeCohortAudienceService
+
public override async start(): Promise<void> {
await super.start()
@@ -288,16 +292,52 @@ export class CdpCyclotronWorkerBatchResolve extends CdpConsumerBase<PluginsServe
accountGroupType: accountPage.group_type,
}
} else {
- const personsPage = await instrumentFn('cdpBatchResolve.getBlastRadiusPersons', () =>
- this.hogFlowBatchPersonQueryService.getBlastRadiusPersons(
- team,
- state.filters,
- state.groupTypeIndex,
- state.cursor,
- state.dedupeKey
+ // An audience of one realtime cohort reads that cohort's members from the realtime
+ // pipeline's Postgres table, which is the source of truth. It skips the email dedupe,
+ // because Postgres holds no emails.
+ const realtimeCohort = state.realtimeCohort
+ if (realtimeCohort && !this.config.BEHAVIORAL_COHORTS_DATABASE_URL) {
+ // Without its own URL the router reads the main database, which has no
+ // cohort_membership table, so every retry would fail the same way.
+ logger.error(
+ '🔴',
+ `${this.name} - realtime cohort audience without a behavioral cohorts database`,
+ {
+ batchJobId: state.batchJobId,
+ cohortId: realtimeCohort.id,
+ }
)
- )
- page = { ids: personsPage.users_affected, cursor: personsPage.cursor, has_more: personsPage.has_more }
+ await this.transitionToFailedTerminal(
+ job,
+ state,
+ "Sending to a realtime cohort isn't available here yet. Use a different audience."
+ )
+ return
+ }
+ if (realtimeCohort) {
+ page = await instrumentFn('cdpBatchResolve.getRealtimeCohortMemberPage', () =>
+ this.realtimeCohortAudience.getMemberPage(
+ realtimeCohort.teamId,
+ realtimeCohort.id,
+ state.cursor
+ )
+ )
+ } else {
+ const personsPage = await instrumentFn('cdpBatchResolve.getBlastRadiusPersons', () =>
+ this.hogFlowBatchPersonQueryService.getBlastRadiusPersons(
+ team,
+ state.filters,
+ state.groupTypeIndex,
+ state.cursor,
+ state.dedupeKey
+ )
+ )
+ page = {
+ ids: personsPage.users_affected,
+ cursor: personsPage.cursor,
+ has_more: personsPage.has_more,
+ }
+ }
}
} catch (err) {
counterBatchHogFlowResolverPagesProcessed.labels({ outcome: 'fetch_failure' }).inc()
diff --git a/nodejs/src/cdp/services/hogflows/batch-resolver.types.ts b/nodejs/src/cdp/services/hogflows/batch-resolver.types.ts
index f40b014a7484..ae8b5f235be2 100644
--- a/nodejs/src/cdp/services/hogflows/batch-resolver.types.ts
+++ b/nodejs/src/cdp/services/hogflows/batch-resolver.types.ts
@@ -40,6 +40,10 @@ export const BatchResolverStateSchema = z.object({
// mid-run flow edits can't flip dedup semantics between pages. Optional so
// jobs written by older deploys keep parsing (they run un-deduped).
dedupeKey: z.enum(['email']).optional(),
+ // Set by Django when the audience is exactly one realtime cohort. The resolver then pages that
+ // cohort's members from the realtime pipeline's Postgres table instead of the Django audience
+ // query. `teamId` is the cohort's own team, which owns its membership rows.
+ realtimeCohort: z.object({ id: z.number().int(), teamId: z.number().int() }).optional(),
maxAudienceSize: z.number().int().nonnegative(),
cursor: z.string().nullable(),
totalEnqueued: z.number().int().nonnegative(),
diff --git a/nodejs/src/cdp/services/hogflows/realtime-cohort-audience.service.serial.test.ts b/nodejs/src/cdp/services/hogflows/realtime-cohort-audience.service.serial.test.ts
new file mode 100644
index 000000000000..c2f102e25090
--- /dev/null
+++ b/nodejs/src/cdp/services/hogflows/realtime-cohort-audience.service.serial.test.ts
@@ -0,0 +1,79 @@
+import { defaultConfig } from '~/common/config/config'
+import { PostgresRouter, PostgresUse } from '~/common/utils/db/postgres'
+import { UUIDT } from '~/common/utils/utils'
+
+import { resetBehavioralCohortsDatabase } from '../../../../tests/helpers/sql'
+import { MEMBER_PAGE_DEADLINE_MS, RealtimeCohortAudienceService } from './realtime-cohort-audience.service'
+
+describe('RealtimeCohortAudienceService', () => {
+ const TEAM_ID = 4242
+ const COHORT_ID = 91204
+
+ let postgres: PostgresRouter
+ let service: RealtimeCohortAudienceService
+
+ beforeEach(async () => {
+ postgres = new PostgresRouter(defaultConfig)
+ await resetBehavioralCohortsDatabase(postgres)
+ service = new RealtimeCohortAudienceService(postgres)
+ })
+
+ afterEach(async () => {
+ await postgres.end()
+ })
+
+ const insertMembership = async (teamId: number, cohortId: number, inCohort: boolean): Promise<string> => {
+ const personId = new UUIDT().toString()
+ await postgres.query(
+ PostgresUse.BEHAVIORAL_COHORTS_RW,
+ `INSERT INTO cohort_membership (team_id, cohort_id, person_id, in_cohort) VALUES ($1, $2, $3, $4)`,
+ [teamId, cohortId, personId, inCohort],
+ 'test'
+ )
+ return personId
+ }
+
+ it('pages every current member of the cohort exactly once, and nobody else', async () => {
+ const members = await Promise.all([1, 2, 3].map(() => insertMembership(TEAM_ID, COHORT_ID, true)))
+ await insertMembership(TEAM_ID, COHORT_ID, false)
+ await insertMembership(TEAM_ID, COHORT_ID + 1, true)
+ // The same cohort id under another team must never reach this audience.
+ await insertMembership(TEAM_ID + 1, COHORT_ID, true)
+
+ const collected: string[] = []
+ let cursor: string | null = null
+ for (let pages = 0; pages < 10; pages++) {
+ const page = await service.getMemberPage(TEAM_ID, COHORT_ID, cursor, 2)
+ collected.push(...page.ids)
+ cursor = page.cursor
+ if (!page.has_more) {
+ break
+ }
+ }
+
+ expect(collected).toEqual([...members].sort())
+ })
+
+ it.each([
+ ['the connection checkout', () => new Promise(() => {}), undefined],
+ ['a query', undefined, () => new Promise(() => {})],
+ ])('rejects at the deadline and ends the connection when %s stalls', async (_stage, connect, query) => {
+ jest.useFakeTimers()
+ try {
+ const client = { on: jest.fn(), removeListener: jest.fn(), release: jest.fn(), query }
+ const stalledRouter = {
+ connect: connect ?? (() => Promise.resolve(client)),
+ } as unknown as PostgresRouter
+ const page = new RealtimeCohortAudienceService(stalledRouter).getMemberPage(TEAM_ID, COHORT_ID, null)
+ const outcome = expect(page).rejects.toThrow('took longer than')
+ await jest.advanceTimersByTimeAsync(MEMBER_PAGE_DEADLINE_MS)
+ await outcome
+ if (query) {
+ // Releasing with an error makes the pool end the connection instead of reusing it.
+ expect(client.release).toHaveBeenCalledWith(expect.any(Error))
+ }
+ } finally {
+ jest.useRealTimers()
+ }
+ })
+})
diff --git a/nodejs/src/cdp/services/hogflows/realtime-cohort-audience.service.ts b/nodejs/src/cdp/services/hogflows/realtime-cohort-audience.service.ts
new file mode 100644
index 000000000000..cab036aa1a06
--- /dev/null
+++ b/nodejs/src/cdp/services/hogflows/realtime-cohort-audience.service.ts
@@ -0,0 +1,107 @@
+import { PoolClient } from 'pg'
+
+import { PostgresRouter, PostgresUse } from '~/common/utils/db/postgres'
+import { logger } from '~/common/utils/logger'
+
+/** Members read per page. Matches the default page size of the Django audience query. */
+export const REALTIME_COHORT_AUDIENCE_PAGE_SIZE = 5000
+
+const MEMBER_PAGE_TIMEOUT_MS = 30_000
+// Covers the connection checkout and BEGIN too, which the statement timeout can't bound.
+export const MEMBER_PAGE_DEADLINE_MS = 60_000
+
+export type RealtimeCohortAudiencePage = {
+ ids: string[]
+ cursor: string | null
+ has_more: boolean
+}
+
+/**
+ * Pages the members of a realtime cohort straight from the realtime pipeline's Postgres table.
+ *
+ * Postgres is the source of truth for realtime membership, so there is no copy to lag behind it.
+ * The workflow worker loads each person when it runs, so the page only carries person ids. Django
+ * decides which audiences take this path, and passes the cohort with the batch run.
+ */
+export class RealtimeCohortAudienceService {
+ constructor(private postgres: PostgresRouter) {}
+
+ async getMemberPage(
+ cohortTeamId: number,
+ cohortId: number,
+ cursor: string | null,
+ pageSize: number = REALTIME_COHORT_AUDIENCE_PAGE_SIZE
+ ): Promise<RealtimeCohortAudiencePage> {
+ // The resolver heartbeats its job while it waits, so a stalled read would hold the job without
+ // ever failing. The deadline turns a stall into an error, which the resolver retries.
+ let timer: NodeJS.Timeout | undefined
+ let timedOut = false
+ const deadline = new Promise<never>((_, reject) => {
+ timer = setTimeout(() => {
+ timedOut = true
+ reject(new Error(`Realtime cohort member page took longer than ${MEMBER_PAGE_DEADLINE_MS}ms`))
+ }, MEMBER_PAGE_DEADLINE_MS)
+ })
+
+ const checkout = this.postgres.connect(PostgresUse.BEHAVIORAL_COHORTS_RW)
+ // A connection that arrives after the deadline goes straight back to the pool.
+ void checkout.then(
+ (late) => timedOut && late.release(),
+ () => undefined
+ )
+
+ let client: PoolClient | undefined
+ // pg drops the pool's error listener from a checked-out client, and an unhandled 'error'
+ // event would crash the process.
+ const onClientError = (error: Error): void => {
+ logger.warn('🔌', 'Realtime cohort member page connection error', { error: String(error) })
+ }
+ try {
+ client = await Promise.race([checkout, deadline])
+ client.on('error', onClientError)
+ const ids = await Promise.race([this.readPage(client, cohortTeamId, cohortId, cursor, pageSize), deadline])
+ client.removeListener('error', onClientError)
+ client.release()
+ return {
+ ids,
+ cursor: ids.length > 0 ? ids[ids.length - 1] : cursor,
+ has_more: ids.length === pageSize,
+ }
+ } catch (error) {
+ // Releasing with an error ends the connection. That stops a read that is still running,
+ // so a stall can't keep the connection out of the pool.
+ client?.release(error instanceof Error ? error : new Error(String(error)))
+ throw error
+ } finally {
+ clearTimeout(timer)
+ }
+ }
+
+ private async readPage(
+ client: PoolClient,
+ cohortTeamId: number,
+ cohortId: number,
+ cursor: string | null,
+ pageSize: number
+ ): Promise<string[]> {
+ const afterCursor = cursor === null ? '' : 'AND person_id > $4::uuid'
+ const values: unknown[] = [cohortTeamId, cohortId, pageSize]
+ if (cursor !== null) {
+ values.push(cursor)
+ }
+ await client.query('BEGIN')
+ await client.query(`SET LOCAL statement_timeout = ${MEMBER_PAGE_TIMEOUT_MS}`)
+ const result = await client.query<{ person_id: string }>(
+ `
+ SELECT person_id
+ FROM cohort_membership
+ WHERE team_id = $1 AND cohort_id = $2 AND in_cohort ${afterCursor}
+ ORDER BY person_id
+ LIMIT $3
+ `,
+ values
+ )
+ await client.query('COMMIT')
+ return result.rows.map((row) => row.person_id)
+ }
+}
diff --git a/nodejs/src/common/utils/db/postgres.ts b/nodejs/src/common/utils/db/postgres.ts
index ee7011d85ba9..030afebffdf8 100644
--- a/nodejs/src/common/utils/db/postgres.ts
+++ b/nodejs/src/common/utils/db/postgres.ts
@@ -71,6 +71,9 @@ export function isTransientPgError(err: unknown): boolean {
return !!message && POSTGRES_UNAVAILABLE_ERROR_MESSAGES.some((m) => message.includes(m))
}
+// Below the realtime cohort member page deadline, so a stalled connection fails before the page does.
+const BEHAVIORAL_COHORTS_CONNECTION_TIMEOUT_MS = 30_000
+
export enum PostgresUse {
COMMON_READ, // Read replica on the common tables, uses need to account for possible replication delay
COMMON_WRITE, // Main PG master with common tables, we need to move as many queries away from it as possible
@@ -158,7 +161,10 @@ export class PostgresRouter {
createPostgresPool(
serverConfig.BEHAVIORAL_COHORTS_DATABASE_URL,
serverConfig.POSTGRES_CONNECTION_POOL_SIZE,
- app_name
+ app_name,
+ undefined,
+ // A connection whose startup stalls would otherwise hold a pool slot forever.
+ BEHAVIORAL_COHORTS_CONNECTION_TIMEOUT_MS
)
)
logger.info('👍', `Behavioral cohorts Postgresql ready`)
diff --git a/nodejs/src/common/utils/utils.ts b/nodejs/src/common/utils/utils.ts
index 64f57b9b71b6..0bf4b45b5a8c 100644
--- a/nodejs/src/common/utils/utils.ts
+++ b/nodejs/src/common/utils/utils.ts
@@ -423,13 +423,15 @@ export function createPostgresPool(
connectionString: string,
poolSize: number,
applicationName: string,
- onError?: (error: Error) => any
+ onError?: (error: Error) => any,
+ connectionTimeoutMillis?: number
): Pool {
const pgPool = new Pool({
connectionString,
idleTimeoutMillis: 500,
application_name: applicationName,
max: poolSize,
+ connectionTimeoutMillis,
})
const handleError =