: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
feat(workflows): add cohort membership repository for behavioral cohort point lookups (#83798)
Meikel Ratz7b984ad446f0
diff --git a/nodejs/src/cdp/cdp-services.ts b/nodejs/src/cdp/cdp-services.tsindex 3e4d2fcbd093..a06ea4a7250b 100644--- a/nodejs/src/cdp/cdp-services.ts+++ b/nodejs/src/cdp/cdp-services.ts@@ -15,6 +15,8 @@ import { WarehouseSourceWebhooksOutput } from './outputs/outputs'import { CdpProducerName } from './outputs/producers'import { createCdpOutputsRegistry } from './outputs/registry'import { CapturedEventsService } from './services/captured-events/captured-events.service'+import { CohortMembershipRepository } from './services/cohorts/cohort-membership-repository'+import { PostgresCohortMembershipRepository } from './services/cohorts/postgres-cohort-membership-repository'import { HogExecutorAsyncService } from './services/hog-executor-async.service'import { HogExecutorService } from './services/hog-executor.service'import { HogInputsService } from './services/hog-inputs.service'@@ -83,6 +85,8 @@ export interface CdpCoreServices {recipientPreferencesService: RecipientPreferencesServiceemailSuppressionService: EmailSuppressionServiceteamWorkflowsConfigService: TeamWorkflowsConfigService+ /** Point lookups for realtime/behavioral cohort membership (behavioral cohorts DB). */+ cohortMembershipRepository: CohortMembershipRepositoryhogFlowExecutor: HogFlowExecutorServicehogFunctionMonitoringService: HogFunctionMonitoringServicecapturedEventsService: CapturedEventsService@@ -466,6 +470,7 @@ export function createCdpCoreServices(// whose capabilities execute email actions; everywhere else this is null// and EmailValidationService degrades to the local cache + DNS.const emailValidationService = new EmailValidationService(deps.emailValidationValkey)+ const cohortMembershipRepository = new PostgresCohortMembershipRepository(deps.postgres)// Observer writes to both stores; the read source decides which verdict drives the metric.const hogFlowDuplicateObserver = new HogFlowDuplicateObserverService(redis, valkeyShadow.writer)const hogFlowExecutor = new HogFlowExecutorService(@@ -505,6 +510,7 @@ export function createCdpCoreServices(recipientPreferencesService,emailSuppressionService,teamWorkflowsConfigService,+ cohortMembershipRepository,hogFlowExecutor,hogFunctionMonitoringService,capturedEventsService,diff --git a/nodejs/src/cdp/services/cohorts/cohort-membership-repository.ts b/nodejs/src/cdp/services/cohorts/cohort-membership-repository.tsnew file mode 100644index 000000000000..5f9d89d62221--- /dev/null+++ b/nodejs/src/cdp/services/cohorts/cohort-membership-repository.ts@@ -0,0 +1,8 @@+export interface CohortMembershipRepository {+ /**+ * The full set of cohort ids the person is currently a member of. Deliberately no+ * degraded implementation: a failed lookup must surface as an error, never silently+ * answer non-member.+ */+ getMemberCohortIds(teamId: number, personUuid: string): Promise<number[]>+}diff --git a/nodejs/src/cdp/services/cohorts/postgres-cohort-membership-repository.test.ts b/nodejs/src/cdp/services/cohorts/postgres-cohort-membership-repository.test.tsnew file mode 100644index 000000000000..aea42ae7910d--- /dev/null+++ b/nodejs/src/cdp/services/cohorts/postgres-cohort-membership-repository.test.ts@@ -0,0 +1,105 @@+import { register } from 'prom-client'++import { defaultConfig } from '~/common/config/config'+import { PostgresRouter } from '~/common/utils/db/postgres'+import { UUIDT } from '~/common/utils/utils'+import { resetBehavioralCohortsDatabase } from '~/tests/helpers/sql'++import { insertCohortMemberships } from '../../_tests/fixtures'+import {+ CohortMembershipLookupTimeoutError,+ PostgresCohortMembershipRepository,+} from './postgres-cohort-membership-repository'++// Counter is a module-scoped global, so compare deltas rather than reset shared state between tests.+const outcomeCount = async (outcome: string): Promise<number> => {+ const metric = register.getSingleMetric('cdp_cohort_membership_lookups_total')+ if (!metric) {+ return 0+ }+ const data = await metric.get()+ return data.values.find((v) => (v.labels as Record<string, string>).outcome === outcome)?.value ?? 0+}++describe('PostgresCohortMembershipRepository', () => {+ let postgres: PostgresRouter+ let repository: PostgresCohortMembershipRepository++ beforeAll(async () => {+ postgres = new PostgresRouter(defaultConfig)+ await resetBehavioralCohortsDatabase(postgres)+ })++ afterAll(async () => {+ await postgres.end()+ })++ beforeEach(() => {+ repository = new PostgresCohortMembershipRepository(postgres)+ })++ it('returns the cohorts the person is currently in, scoped to the team', async () => {+ const teamId = 2+ const personUuid = new UUIDT().toString()+ await insertCohortMemberships(postgres, [+ { team_id: teamId, cohort_id: 101, person_id: personUuid, in_cohort: true },+ { team_id: teamId, cohort_id: 102, person_id: personUuid, in_cohort: false }, // person left+ { team_id: teamId + 1, cohort_id: 103, person_id: personUuid, in_cohort: true }, // another team, must not leak+ { team_id: teamId, cohort_id: 104, person_id: personUuid, in_cohort: true },+ ])++ const result = await repository.getMemberCohortIds(teamId, personUuid)++ expect(result.sort()).toEqual([101, 104])+ })++ it('returns an empty set for a person the pipeline never wrote a row for', async () => {+ const result = await repository.getMemberCohortIds(2, new UUIDT().toString())++ expect(result).toEqual([])+ })++ it('rejects with a retriable timeout error when the lookup hangs', async () => {+ jest.useFakeTimers()+ try {+ const hangingRouter = { query: () => new Promise(() => {}) } as unknown as PostgresRouter+ const hangingRepository = new PostgresCohortMembershipRepository(hangingRouter, 500)++ const lookup = hangingRepository.getMemberCohortIds(2, new UUIDT().toString())+ const assertion = expect(lookup).rejects.toThrow(CohortMembershipLookupTimeoutError)+ jest.advanceTimersByTime(500)+ await assertion+ await expect(lookup.catch((e) => e.isRetriable)).resolves.toBe(true)+ } finally {+ jest.useRealTimers()+ }+ })++ it('records exactly one outcome when the query settles after timing out', async () => {+ jest.useFakeTimers()+ try {+ let resolveQuery!: (value: { rows: { cohort_id: string }[] }) => void+ const lateRouter = {+ query: () => new Promise((resolve) => (resolveQuery = resolve)),+ } as unknown as PostgresRouter+ const lateRepository = new PostgresCohortMembershipRepository(lateRouter, 500)++ const timeoutBefore = await outcomeCount('timeout')+ const successBefore = await outcomeCount('success')++ const lookup = lateRepository.getMemberCohortIds(2, new UUIDT().toString())+ jest.advanceTimersByTime(500)+ await expect(lookup).rejects.toThrow(CohortMembershipLookupTimeoutError)++ // The underlying query settles a moment later; its handler must not record a second outcome+ resolveQuery({ rows: [{ cohort_id: '101' }] })+ await Promise.resolve()+ await Promise.resolve()++ expect(await outcomeCount('timeout')).toBe(timeoutBefore + 1)+ expect(await outcomeCount('success')).toBe(successBefore)+ } finally {+ jest.useRealTimers()+ }+ })+})diff --git a/nodejs/src/cdp/services/cohorts/postgres-cohort-membership-repository.ts b/nodejs/src/cdp/services/cohorts/postgres-cohort-membership-repository.tsnew file mode 100644index 000000000000..bd9a9f09d4c5--- /dev/null+++ b/nodejs/src/cdp/services/cohorts/postgres-cohort-membership-repository.ts@@ -0,0 +1,80 @@+import { Counter } from 'prom-client'++import { PostgresRouter, PostgresUse } from '~/common/utils/db/postgres'++import { CohortMembershipRepository } from './cohort-membership-repository'++const cohortMembershipLookupsCounter = new Counter({+ name: 'cdp_cohort_membership_lookups_total',+ help: 'Point lookups against the behavioral cohorts cohort_membership table, by outcome.',+ labelNames: ['outcome'],+})++export class CohortMembershipLookupTimeoutError extends Error {+ constructor(timeoutMs: number) {+ super(`Cohort membership lookup timed out after ${timeoutMs}ms`)+ this.name = 'CohortMembershipLookupTimeoutError'+ }+ readonly isRetriable = true+}++// Bounds pool-acquire stalls and network black holes that a statement timeout cannot cover+export const DEFAULT_LOOKUP_TIMEOUT_MS = 1000++export class PostgresCohortMembershipRepository implements CohortMembershipRepository {+ constructor(+ private postgres: PostgresRouter,+ private lookupTimeoutMs: number = DEFAULT_LOOKUP_TIMEOUT_MS+ ) {}++ async getMemberCohortIds(teamId: number, personUuid: string): Promise<number[]> {+ const queryPromise = this.postgres.query<{ cohort_id: string }>(+ PostgresUse.BEHAVIORAL_COHORTS_RW,+ `SELECT cohort_id+ FROM cohort_membership+ WHERE team_id = $1+ AND person_id = $2+ AND in_cohort = true`,+ [teamId, personUuid],+ 'fetchCohortMemberships'+ )++ const result = await new Promise<Awaited<typeof queryPromise>>((resolve, reject) => {+ // The timer and the query race. The query's handlers stay registered after the timer+ // wins and fire when it settles late, so this flag stops the loser from recording a+ // second outcome and double-counting the lookup in the metric.+ let settled = false+ const timer = setTimeout(() => {+ settled = true+ // Swallow the losing query's settlement so it can't become an unhandled rejection+ queryPromise.catch(() => undefined)+ cohortMembershipLookupsCounter.labels('timeout').inc()+ reject(new CohortMembershipLookupTimeoutError(this.lookupTimeoutMs))+ }, this.lookupTimeoutMs)++ queryPromise.then(+ (res) => {+ if (settled) {+ return+ }+ settled = true+ clearTimeout(timer)+ cohortMembershipLookupsCounter.labels('success').inc()+ resolve(res)+ },+ (err) => {+ if (settled) {+ return+ }+ settled = true+ clearTimeout(timer)+ cohortMembershipLookupsCounter.labels('error').inc()+ reject(err)+ }+ )+ })++ // BIGINT columns come back from pg as strings+ return result.rows.map((row) => Number(row.cohort_id))+ }+}