: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): count conversions from per-run watchers (#82953)
Daniel Marchukc75b28d30ccf
diff --git a/nodejs/src/cdp/cdp-api.serial.test.ts b/nodejs/src/cdp/cdp-api.serial.test.tsindex cfd31e787ea4..3376177f29a6 100644--- a/nodejs/src/cdp/cdp-api.serial.test.ts+++ b/nodejs/src/cdp/cdp-api.serial.test.ts@@ -2049,6 +2049,7 @@ describe('CDP API', () => {capturedPostHogEvents: [],warehouseWebhookPayloads: [],messageAssets: [],+ conversionWatchers: [],}))})diff --git a/nodejs/src/cdp/cdp-api.ts b/nodejs/src/cdp/cdp-api.tsindex 50bce174e39e..66ca2496d596 100644--- a/nodejs/src/cdp/cdp-api.ts+++ b/nodejs/src/cdp/cdp-api.ts@@ -248,6 +248,7 @@ export class CdpApi {this.cdpSourceWebhooksConsumer.stop(),this.batchExportHogFunctionService.stop(),this.rerunJobManager?.disconnect() ?? Promise.resolve(),+ this.invocationResultsService.stop(),])}diff --git a/nodejs/src/cdp/cdp-services.ts b/nodejs/src/cdp/cdp-services.tsindex 720733bddb44..7d73e7c62bfc 100644--- a/nodejs/src/cdp/cdp-services.ts+++ b/nodejs/src/cdp/cdp-services.ts@@ -18,6 +18,7 @@ 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 { ConversionWatchersService } from './services/conversion-watchers/conversion-watchers.service'import { HogExecutorAsyncService } from './services/hog-executor-async.service'import { HogExecutorService } from './services/hog-executor.service'import { HogInputsService } from './services/hog-inputs.service'@@ -134,6 +135,8 @@ export type CdpCoreServicesConfig = Pick<| 'CDP_VALKEY_READER_PORT'| 'CDP_VALKEY_TLS'| 'CDP_VALKEY_READ_FEATURES'+ | 'CYCLOTRON_NODE_DATABASE_URL'+ | 'CYCLOTRON_NODE_MAX_CONNECTIONS'| 'CDP_WATCHER_HOG_COST_TIMING_LOWER_MS'| 'CDP_WATCHER_HOG_COST_TIMING_UPPER_MS'| 'CDP_WATCHER_HOG_COST_TIMING'@@ -531,12 +534,17 @@ export function createCdpCoreServices(const hogInvocationResultsService = new HogInvocationResultsService(outputs, config)const warehouseWebhooksService = new WarehouseWebhooksService(outputs)const capturedEventsService = new CapturedEventsService(deps.internalCaptureService, deps.teamManager)+ const conversionWatchersService = new ConversionWatchersService(+ config.CYCLOTRON_NODE_DATABASE_URL,+ config.CYCLOTRON_NODE_MAX_CONNECTIONS+ )const invocationResultsService = new InvocationResultsService(hogFunctionMonitoringService,hogInvocationResultsService,warehouseWebhooksService,capturedEventsService,- messageAssetsService+ messageAssetsService,+ conversionWatchersService)const nativeDestinationExecutorService = new NativeDestinationExecutorService(config)diff --git a/nodejs/src/cdp/consumers/cdp-base.consumer.ts b/nodejs/src/cdp/consumers/cdp-base.consumer.tsindex 34b7af63624d..212e9ca646ee 100644--- a/nodejs/src/cdp/consumers/cdp-base.consumer.ts+++ b/nodejs/src/cdp/consumers/cdp-base.consumer.ts@@ -137,6 +137,9 @@ export abstract class CdpConsumerBase<TConfig extends CdpConsumerBaseConfig = Cdthis.isStopping = true// Billing records live only in memory until they are sent, so a graceful stop drains them.await this.cdpUsageReporter.shutdown()+ // Release the per-consumer conversion-watcher pool created in createCdpCoreServices, so+ // graceful shutdown frees its cyclotron connections like the other cyclotron pools do.+ await this.invocationResultsService.stop()logger.info('👍', `${this.name} - stopped!`)}diff --git a/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.test.ts b/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.test.tsindex 2b879679a08a..54186b36ba6a 100644--- a/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.test.ts+++ b/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.test.ts@@ -36,6 +36,22 @@ type MockRow = {const eventBytecode = (eventName: string): any[] => ['_H', 1, 32, eventName, 32, 'event', 1, 1, 11]+const personPropertyBytecode = (key: string, value: string): any[] => [+ '_H',+ 1,+ 32,+ value,+ 32,+ key,+ 32,+ 'properties',+ 32,+ 'person',+ 1,+ 3,+ 11,+]+const makeHogFlow = (overrides: Partial<HogFlow> & { id: string; waitUntil?: boolean }): HogFlow => {const { id, team_id, waitUntil = true, ...rest } = overridesconst waitAction = {@@ -100,6 +116,11 @@ interface QueryCall {class MatcherUnderTest extends CdpHogflowSubscriptionMatcherConsumer {public calls: QueryCall[] = []public findRows: MockRow[] = []+ // Conversion watchers are a separate table with its own lookup; default empty so the wake-path+ // fixtures below aren't also served to it.+ public watcherRows: MockRow[] = []+ // null = every requested row is claimed; an array narrows it to those ids.+ public claimedWatcherIds: string[] | null = nullpublic wakeRows: MockRow[] = []public moveRows: MockRow[] = []public updateRowCount = 0@@ -114,6 +135,18 @@ class MatcherUnderTest extends CdpHogflowSubscriptionMatcherConsumer {return Promise.resolve({ rows: [], rowCount: 0 })}this.calls.push({ sql, params })+ if (sql.startsWith('DELETE FROM conversion_watchers')) {+ // Deleting the row IS the claim, so only rows this DELETE removed may be counted.+ // `claimedWatcherIds` models another instance having won some of them first.+ const claimed = this.watcherRows+ .map((r: any) => ({ id: r.id }))+ .filter((r) => this.claimedWatcherIds === null || this.claimedWatcherIds.includes(r.id))+ return Promise.resolve({ rows: claimed, rowCount: claimed.length })+ }+ // Checked before the parked-job lookup: both select `id, team_id, function_id`.+ if (sql.includes('FROM conversion_watchers')) {+ return Promise.resolve({ rows: this.watcherRows, rowCount: this.watcherRows.length })+ }if (sql.includes('SELECT id, team_id, function_id')) {return Promise.resolve({ rows: this.findRows, rowCount: this.findRows.length })}@@ -180,6 +213,15 @@ class MatcherUnderTest extends CdpHogflowSubscriptionMatcherConsumer {public async runWake(invocationGlobals: HogFunctionInvocationGlobals[]): Promise<void> {await (this as any).wakeMatchingWorkflows(invocationGlobals)}++ // start() arms the watcher sweep and team-refresh intervals, and only stop() clears them. This+ // suite starts a consumer without a matching stop, and CI runs the whole shard --runInBand, so a+ // leaked pair keeps firing in that one process for the rest of the run — long after the mocks+ // they call have been reset.+ public clearWatcherTimers(): void {+ clearInterval((this as any).watcherTeamsRefreshTimer)+ clearInterval((this as any).watcherSweepTimer)+ }}const stateBuffer = (state: any): Buffer => Buffer.from(JSON.stringify({ state }))@@ -191,12 +233,18 @@ describe('CdpHogflowSubscriptionMatcherConsumer', () => {matcher = new MatcherUnderTest()})+ afterEach(() => {+ matcher.clearWatcherTimers()+ })+describe('wakeMatchingWorkflows', () => {it('is a no-op when no events have person_id', async () => {await matcher.runWake([makeGlobals({ person: undefined as any, event: { ...makeGlobals({}).event, distinct_id: '' } }),])- expect(matcher.calls).toHaveLength(0)+ // The watcher lookup still runs: a watcher's run may have finished long ago, so gating it+ // on the team having a live actionable flow would restore the blind spot watchers remove.+ expect(matcher.calls.filter((c) => c.sql.includes('FROM cyclotron_jobs')).map((c) => c.sql)).toHaveLength(0)})it('passes both distinct_ids and person_ids to the lookup query', async () => {@@ -209,7 +257,9 @@ describe('CdpHogflowSubscriptionMatcherConsumer', () => {person: { id: 'person-uuid-2', properties: {}, name: '', url: '' },}),])- const lookup = matcher.calls.find((c) => c.sql.includes('SELECT id, team_id, function_id'))!+ const lookup = matcher.calls.find(+ (c) => c.sql.includes('FROM cyclotron_jobs') && c.sql.includes('SELECT id, team_id, function_id')+ )!expect(lookup).not.toBeUndefined()// Params are correlated (team, id) pairs: distinctTeamIds/distinctIds zip row-wise,// and personTeamIds/personIds zip row-wise. Both events are team 1.@@ -226,7 +276,9 @@ describe('CdpHogflowSubscriptionMatcherConsumer', () => {// already scopes the results to hogflow jobs.matcher.setHogFlows({ 'flow-1': makeHogFlow({ id: 'flow-1' }) })await matcher.runWake([makeGlobals({})])- const lookup = matcher.calls.find((c) => c.sql.includes('SELECT id, team_id, function_id'))!+ const lookup = matcher.calls.find(+ (c) => c.sql.includes('FROM cyclotron_jobs') && c.sql.includes('SELECT id, team_id, function_id')+ )!expect(lookup).not.toBeUndefined()expect(lookup.sql).not.toContain('queue_name')})@@ -271,7 +323,9 @@ describe('CdpHogflowSubscriptionMatcherConsumer', () => {// The correlated lookup params zip (team, distinct_id) row-wise: {(1,alice),(2,bob)}.// (1,bob) must not appear — that's the cross-team combination that doesn't exist.- const lookup = matcher.calls.find((c) => c.sql.includes('SELECT id, team_id, function_id'))!+ const lookup = matcher.calls.find(+ (c) => c.sql.includes('FROM cyclotron_jobs') && c.sql.includes('SELECT id, team_id, function_id')+ )!expect(lookup).not.toBeUndefined()const pairs = lookup.params[0].map((teamId: number, i: number) => `${teamId}:${lookup.params[1][i]}`)expect(pairs).toEqual(['1:alice', '2:bob'])@@ -290,7 +344,9 @@ describe('CdpHogflowSubscriptionMatcherConsumer', () => {'flow-2': makeHogFlow({ id: 'flow-2', waitUntil: false }),})await matcher.runWake([makeGlobals({})])- const lookup = matcher.calls.find((c) => c.sql.includes('SELECT id, team_id, function_id'))!+ const lookup = matcher.calls.find(+ (c) => c.sql.includes('FROM cyclotron_jobs') && c.sql.includes('SELECT id, team_id, function_id')+ )!expect(lookup).not.toBeUndefined()expect(lookup.params[4]).toEqual(['flow-1'])})@@ -299,7 +355,11 @@ describe('CdpHogflowSubscriptionMatcherConsumer', () => {// Default: no hogflows configured → team has nothing the matcher could wake.// The cyclotron lookup must NOT fire.await matcher.runWake([makeGlobals({})])- expect(matcher.calls.find((c) => c.sql.includes('SELECT id, team_id, function_id'))).toBeUndefined()+ expect(+ matcher.calls.find(+ (c) => c.sql.includes('FROM cyclotron_jobs') && c.sql.includes('SELECT id, team_id, function_id')+ )+ ).toBeUndefined()})it('wakes when the matching event is not the first event in the batch for a distinct_id', async () => {@@ -483,7 +543,6 @@ describe('CdpHogflowSubscriptionMatcherConsumer', () => {expect(update).not.toBeUndefined()const newState = parseJSON(update!.params[1][0].toString('utf-8')) as anyexpect(newState.state.conversionMatched).toBe(true)- expect(newState.state.conversionCounted).toBe(true)// currentAction is missing in input state, so eventMatched must not have been setexpect(newState.state.currentAction).toBeUndefined()})@@ -563,97 +622,6 @@ describe('CdpHogflowSubscriptionMatcherConsumer', () => {expect(wake).not.toBeUndefined()const newState = parseJSON(wake!.params[1][0].toString('utf-8')) as anyexpect(newState.state.conversionMatched).toBe(true)- expect(newState.state.conversionCounted).toBe(true)- // The conversion is also counted as a metric exactly once.- expect(matcher.queueAppMetricMock).toHaveBeenCalledTimes(1)- expect(matcher.queueAppMetricMock).toHaveBeenCalledWith(- expect.objectContaining({- app_source_id: 'flow-1',- metric_name: 'conversion',- count: 1,- app_source_version: { id: expect.any(String), version: 1 },- }),- 'hog_flow'- )- // ...and emitted once as a billable $workflows_conversion event for the converting person.- expect(matcher.queueConversionEventMock).toHaveBeenCalledTimes(1)- expect(matcher.queueConversionEventMock).toHaveBeenCalledWith(- expect.objectContaining({- team_id: 1,- event: '$workflows_conversion',- distinct_id: 'user-1',- properties: expect.objectContaining({- $workflow_id: 'flow-1',- $workflow_version: 1,- $workflow_conversion_type: 'event',- $workflow_conversion_event: 'wuc_cancelled',- }),- })- )- })-- // The whole point of the versioned series: "did conversion rate drop after we changed the- // email?" is only answerable if a conversion is credited to the version that sent to that- // person. Reading it off the freshly loaded flow credits whatever is live when they convert,- // so a broadcast under v1 followed by a republish silently moves all of v1's conversions to v2.- it.each([- {- name: 'the version the run started under, not the one live at conversion time',- parkedState: { currentAction: { id: 'wait_node' }, flowVersion: 1 },- expectedVersion: { id: 'flow-1', version: 1 },- expectedEventVersion: 1,- },- {- name: 'no version at all when the run predates the stamp',- parkedState: { currentAction: { id: 'wait_node' } },- expectedVersion: undefined,- expectedEventVersion: undefined,- },- ])('attributes a conversion to $name', async ({ parkedState, expectedVersion, expectedEventVersion }) => {- // The published flow has moved on to v2 since this run started.- const flow = makeHogFlow({- id: 'flow-1',- version: 2,- exit_condition: 'exit_on_conversion',- conversion: {- events: [- {- filters: {- bytecode: eventBytecode('wuc_cancelled'),- events: [{ id: 'wuc_cancelled', name: 'wuc_cancelled', type: 'events', order: 0 }],- },- },- ],- } as any,- } as any)- matcher.findRows = [- {- id: 'job-c',- team_id: 1,- function_id: 'flow-1',- action_id: 'wait_node',- distinct_id: 'user-1',- person_id: null,- },- ]- matcher.wakeRows = [{ ...matcher.findRows[0], state: stateBuffer(parkedState) }]- matcher.updateRowCount = 1- matcher.setHogFlows({ 'flow-1': flow })-- await matcher.runWake([makeGlobals({ event: { ...makeGlobals({}).event, event: 'wuc_cancelled' } })])-- expect(matcher.queueAppMetricMock).toHaveBeenCalledWith(- expect.objectContaining({- metric_name: 'conversion',- app_source_version: expectedVersion,- }),- 'hog_flow'- )- expect(matcher.queueConversionEventMock).toHaveBeenCalledWith(- expect.objectContaining({- properties: expect.objectContaining({ $workflow_version: expectedEventVersion }),- })- )})it('does not wake on a conversion match when the workflow does not exit on conversion', async () => {@@ -698,77 +666,11 @@ describe('CdpHogflowSubscriptionMatcherConsumer', () => {(c) => c.sql.startsWith('UPDATE cyclotron_jobs') && c.sql.includes('SET scheduled = NOW()'))expect(wake).toBeUndefined()- // But a state-only `SET state = u.state` UPDATE persists conversionCounted.- const stateOnly = matcher.calls.find(- (c) =>- c.sql.startsWith('UPDATE cyclotron_jobs') &&- c.sql.includes('SET state = u.state') &&- !c.sql.includes('scheduled')- )- expect(stateOnly).not.toBeUndefined()- const newState = parseJSON(stateOnly!.params[1][0].toString('utf-8')) as any- expect(newState.state.conversionCounted).toBe(true)- expect(newState.state.conversionMatched).toBeUndefined()- // ...and the conversion is counted once (measurement-only).- expect(matcher.queueAppMetricMock).toHaveBeenCalledTimes(1)- expect(matcher.queueAppMetricMock).toHaveBeenCalledWith(- expect.objectContaining({ app_source_id: 'flow-1', metric_name: 'conversion', count: 1 }),- 'hog_flow'- )- })-- it('counts a conversion (without waking) for a conversion-only flow that has no wait step', async () => {- // Broadened gating: a flow whose only actionable feature is an event-based conversion goal- // (no wait_until_condition) is now evaluated regardless of exit condition, so the metric is- // tracked. exit_only_at_end means it must not be woken.- const flow = makeHogFlow({- id: 'flow-1',- waitUntil: false,- exit_condition: 'exit_only_at_end',- conversion: {- events: [- {- filters: {- bytecode: eventBytecode('wuc_cancelled'),- events: [{ id: 'wuc_cancelled', name: 'wuc_cancelled', type: 'events', order: 0 }],- },- },- ],- } as any,- } as any)- matcher.findRows = [- {- id: 'job-c',- team_id: 1,- function_id: 'flow-1',- action_id: null,- distinct_id: 'user-1',- person_id: null,- },- ]- matcher.wakeRows = [{ ...matcher.findRows[0], state: stateBuffer({}) }]- matcher.updateRowCount = 1- matcher.setHogFlows({ 'flow-1': flow })-- await matcher.runWake([makeGlobals({ event: { ...makeGlobals({}).event, event: 'wuc_cancelled' } })])-- // No wake, but a state-only UPDATE persists conversionCounted.- const wake = matcher.calls.find(- (c) => c.sql.startsWith('UPDATE cyclotron_jobs') && c.sql.includes('SET scheduled = NOW()')- )- expect(wake).toBeUndefined()- const stateOnly = matcher.calls.find(- (c) =>- c.sql.startsWith('UPDATE cyclotron_jobs') &&- c.sql.includes('SET state = u.state') &&- !c.sql.includes('scheduled')- )- expect(stateOnly).not.toBeUndefined()- expect(matcher.queueAppMetricMock).toHaveBeenCalledTimes(1)- expect(matcher.queueAppMetricMock).toHaveBeenCalledWith(- expect.objectContaining({ app_source_id: 'flow-1', metric_name: 'conversion', count: 1 }),- 'hog_flow'- )+ // No state write either: with counting on the watcher there is no flag left to+ // persist, so a measurement-only match must leave the parked job completely untouched.+ const stateOnly = matcher.calls.find((c) => c.sql.startsWith('UPDATE cyclotron_jobs'))+ expect(stateOnly).toBeUndefined()+ expect(matcher.queueAppMetricMock).not.toHaveBeenCalled()})it('does not re-count or update a conversion already counted this run (per-run dedup)', async () => {@@ -816,57 +718,6 @@ describe('CdpHogflowSubscriptionMatcherConsumer', () => {expect(matcher.queueAppMetricMock).not.toHaveBeenCalled()})- it('attributes a conversion to the batch parent_run_id when set', async () => {- // Batch-workflow jobs carry a parent_run_id (the batch job). The emitted conversion metric- // must key app_source_id by that run id, not the function id, so it lands under the batch.- const flow = makeHogFlow({- id: 'flow-1',- waitUntil: false,- exit_condition: 'exit_only_at_end',- conversion: {- events: [- {- filters: {- bytecode: eventBytecode('wuc_cancelled'),- events: [{ id: 'wuc_cancelled', name: 'wuc_cancelled', type: 'events', order: 0 }],- },- },- ],- } as any,- } as any)- matcher.findRows = [- {- id: 'job-c',- team_id: 1,- function_id: 'flow-1',- parent_run_id: 'batch-run-1',- action_id: null,- distinct_id: 'user-1',- person_id: null,- },- ]- matcher.wakeRows = [{ ...matcher.findRows[0], state: stateBuffer({ flowVersion: 2 }) }]- matcher.updateRowCount = 1- matcher.setHogFlows({ 'flow-1': flow })-- await matcher.runWake([makeGlobals({ event: { ...makeGlobals({}).event, event: 'wuc_cancelled' } })])-- expect(matcher.queueAppMetricMock).toHaveBeenCalledTimes(1)- expect(matcher.queueAppMetricMock).toHaveBeenCalledWith(- expect.objectContaining({- app_source_id: 'batch-run-1',- instance_id: 'flow-1',- metric_name: 'conversion',- count: 1,- // The run id keys app_source_id, but the versioned mirror keys on the flow —- // otherwise every batch run mints its own key and a broadcast's versions never- // aggregate.- app_source_version: { id: 'flow-1', version: 2 },- }),- 'hog_flow'- )- })-it('does not wake on an empty conversion "events" entry (always-true bytecode)', async () => {// A conversion entry that targets neither events nor actions compiles to always-true// bytecode and would otherwise mark every incoming event as a conversion.@@ -1075,7 +926,11 @@ describe('CdpHogflowSubscriptionMatcherConsumer', () => {await matcher.runWake([makeGlobals({})])- expect(matcher.calls.find((c) => c.sql.includes('SELECT id, team_id, function_id'))).not.toBeUndefined()+ expect(+ matcher.calls.find(+ (c) => c.sql.includes('FROM cyclotron_jobs') && c.sql.includes('SELECT id, team_id, function_id')+ )+ ).not.toBeUndefined()expect(matcher.calls.find((c) => c.sql.startsWith('UPDATE cyclotron_jobs'))).toBeUndefined()})@@ -1609,10 +1464,150 @@ describe('CdpHogflowSubscriptionMatcherConsumer', () => {const newState = parseJSON((update.params[2][0] as Buffer).toString('utf-8')) as anyexpect(newState.state.currentAction.rekeyWake).toBe(true)})++ it('scopes the watcher re-key so a first mapping only fills an empty anchor', async () => {+ // The watcher path needs the same null-anchor scope the parked-job path has: a first mapping+ // (version 0) may fill an empty watcher anchor but must not overwrite one a merge already set,+ // so the re-key UPDATE gates the version-0 fill on `person_id IS NULL` and threads the move+ // version through so the DB can tell a first mapping from a repoint.+ await matcher.processMoveBatch([+ { teamId: 1, distinctId: 'anon-did', newPersonId: 'first-person-uuid', version: 0 },+ ])++ const rekey = matcher.calls.find((c) => c.sql.startsWith('UPDATE conversion_watchers'))+ expect(rekey).toBeDefined()+ expect(rekey!.sql).toContain('w.person_id IS NULL')+ expect(rekey!.params[3]).toEqual([0])+ })++ it('propagates a watcher re-key failure instead of swallowing it', async () => {+ // The re-key must fail the batch like applyMoves and the read/wake path do, so the Kafka+ // offset doesn't advance and the pod replays; the UPDATE is idempotent, so replay is safe.+ // Swallowing the error would strand the batch's watchers on their pre-merge person.+ const failure = new Error('connection refused')+ ;(matcher as any).cyclotronPool.query = jest.fn().mockRejectedValue(failure)++ // version 0 → no repoint applyMoves runs before the re-key, so the rejection is the re-key's.+ await expect(+ matcher.processMoveBatch([+ { teamId: 1, distinctId: 'anon-did', newPersonId: 'survivor-uuid', version: 0 },+ ])+ ).rejects.toBe(failure)+ })})// The full combination matrix lives here (mocked pg, ~ms each) rather than in the E2E suite:// it exercises the same wake decision the matcher makes for every events/property/action shape.+ describe('conversion watchers', () => {+ const watcher = (overrides: Record<string, any> = {}): any => ({+ id: 'watcher-1',+ team_id: 1,+ function_id: 'flow-1',+ run_id: 'run-1',+ parent_run_id: null,+ distinct_id: 'user-1',+ person_id: null,+ flow_version: 1,+ goal: { events: [eventBytecode('wuc_cancelled')] },+ ...overrides,+ })++ const cancelledEvent = (): HogFunctionInvocationGlobals =>+ makeGlobals({ event: { ...makeGlobals({}).event, event: 'wuc_cancelled' } })++ it('counts a claimed watcher and emits the conversion event with its run id', async () => {+ matcher.watcherRows = [watcher()]++ await matcher.runWake([cancelledEvent()])++ expect(matcher.queueAppMetricMock).toHaveBeenCalledTimes(1)+ expect(matcher.queueAppMetricMock).toHaveBeenCalledWith(+ expect.objectContaining({+ team_id: 1,+ app_source_id: 'flow-1',+ metric_name: 'conversion',+ count: 1,+ app_source_version: { id: 'flow-1', version: 1 },+ }),+ 'hog_flow'+ )+ expect(matcher.queueConversionEventMock).toHaveBeenCalledWith(+ expect.objectContaining({+ event: '$workflows_conversion',+ distinct_id: 'user-1',+ properties: expect.objectContaining({+ $workflow_id: 'flow-1',+ // Joins the conversion to the enrollment that earned it.+ $workflow_run_id: 'run-1',+ $workflow_version: 1,+ $workflow_conversion_type: 'event',+ }),+ })+ )+ })++ it('counts only the watchers the delete actually claimed', async () => {+ // Two instances can evaluate the same watcher in the same moment; the one whose DELETE+ // removed the row owns the count. Counting an unclaimed row would double-count the run.+ matcher.watcherRows = [watcher(), watcher({ id: 'watcher-2', run_id: 'run-2' })]+ matcher.claimedWatcherIds = ['watcher-2']++ await matcher.runWake([cancelledEvent()])++ expect(matcher.queueAppMetricMock).toHaveBeenCalledTimes(1)+ expect(matcher.queueConversionEventMock).toHaveBeenCalledWith(+ expect.objectContaining({ properties: expect.objectContaining({ $workflow_run_id: 'run-2' }) })+ )+ })++ it('attributes a batch child conversion to its parent run', async () => {+ // Batch runs report every other metric under the parent job, so a conversion filed under+ // the flow id instead would be missing from the batch's own numbers.+ matcher.watcherRows = [watcher({ parent_run_id: 'batch-1' })]++ await matcher.runWake([cancelledEvent()])++ expect(matcher.queueAppMetricMock).toHaveBeenCalledWith(+ expect.objectContaining({ app_source_id: 'batch-1', metric_name: 'conversion' }),+ 'hog_flow'+ )+ })++ it('counts a property goal from a person-property change', async () => {+ // Property goals are the half a ClickHouse query cannot reach, and they arrive on the+ // person stream with no distinct_id — so they can only ever match by person_id.+ matcher.watcherRows = [+ watcher({+ distinct_id: null,+ person_id: 'person-uuid-1',+ goal: { properties: personPropertyBytecode('plan', 'enterprise') },+ }),+ ]++ await matcher.runWake([+ makeGlobals({+ event: { ...makeGlobals({}).event, event: '$person_updated', distinct_id: '' },+ person: { id: 'person-uuid-1', properties: { plan: 'enterprise' }, name: '', url: '' },+ }),+ ])++ expect(matcher.queueAppMetricMock).toHaveBeenCalledTimes(1)+ // No billable event: a person-triggered run has no distinct_id, and a person-property+ // change carries none, so there is nothing to attribute a capture event to. The metric+ // counts, but anything reading conversions off the event stream misses these.+ expect(matcher.queueConversionEventMock).not.toHaveBeenCalled()+ })++ it('does not count a watcher whose goal does not match', async () => {+ matcher.watcherRows = [watcher()]++ await matcher.runWake([makeGlobals({})])++ expect(matcher.queueAppMetricMock).not.toHaveBeenCalled()+ expect(matcher.calls.find((c) => c.sql.startsWith('DELETE FROM conversion_watchers'))).toBeUndefined()+ })+ })+describe('wake matrix: events / property / action combinations', () => {const ALWAYS_TRUE = ['_H', 1, 29]// Real, serializer-compiled bytecode for event.properties.plan == 'growth'.diff --git a/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts b/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.tsindex d82a3822f6ef..bbf229f9066d 100644--- a/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts+++ b/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts@@ -1,6 +1,6 @@import { Message } from 'node-rdkafka'import { Pool } from 'pg'-import { Counter, Histogram } from 'prom-client'+import { Counter, Gauge, Histogram } from 'prom-client'import { HogFlow, HogFlowAction } from '~/cdp/schema/hogflow'import {@@ -10,7 +10,6 @@ import {KAFKA_PERSON_DISTINCT_ID,} from '~/common/config/kafka-topics'import { KafkaConsumerInterface, START_AT_LATEST, createKafkaConsumer } from '~/common/kafka/consumer'-import { InternalCaptureEvent } from '~/common/services/internal-capture'import { instrumentFn, instrumented } from '~/common/tracing/tracing-utils'import { parseJSON } from '~/common/utils/json-parse'import { logger } from '~/common/utils/logger'@@ -31,7 +30,7 @@ import {matchesWaitUntilCondition,runFilterBytecode,} from '../services/hogflows/hogflow-utils'-import { CyclotronPerson, HogFlowInvocationContext, HogFunctionInvocationGlobals, MinimalAppMetric } from '../types'+import { CyclotronPerson, HogFlowInvocationContext, HogFunctionInvocationGlobals, PinnedConversionGoal } from '../types'import {convertInternalEventToHogFunctionInvocationGlobals,convertToHogFunctionInvocationGlobals,@@ -48,6 +47,14 @@ import { counterParseError } from './metrics'// the first bootstrap and offset-loss edge cases (covered by the deferred lag alerting follow-up).const startAtLatest = START_AT_LATEST+// Expired watchers are not urgent — they have already stopped matching via the expires_at predicate,+// so this only reclaims space.+const WATCHER_SWEEP_INTERVAL_MS = 60_000++// How stale the has-live-watchers gate may be. A team that just enrolled its first run while its only+// goal flow was already paused waits at most this long to be admitted.+const WATCHER_TEAMS_REFRESH_INTERVAL_MS = 30_000+const counterHogflowMatcherCandidatesEvaluated = new Counter({name: 'cdp_hogflow_matcher_candidates_evaluated',help: 'Parked hogflow jobs the matcher loaded from cyclotron and evaluated against a batch.',@@ -60,7 +67,7 @@ const counterHogflowMatcherJobsWoken = new Counter({const counterHogflowMatcherConversionsCounted = new Counter({name: 'cdp_hogflow_matcher_conversions_counted',- help: 'Event-based conversions counted by the matcher (deduped to once per run via conversionCounted).',+ help: "Conversions counted by claiming a run's watcher row. Deleting the row is the claim, so a run counts at most once however many matching events arrive.",})// A person merge repoints the merged-away person's distinct_ids at the survivor. A wait parked while@@ -83,6 +90,37 @@ const counterHogflowMatcherFirstMapping = new Counter({labelNames: ['outcome'],})+const counterHogflowMatcherWatchersRekeyed = new Counter({+ name: 'cdp_hogflow_matcher_watchers_rekeyed',+ help: 'Conversion watchers repointed onto a merge survivor. Without this they would be addressed to a person no update will ever mention again.',+})++const counterHogflowMatcherConversionEventSkipped = new Counter({+ name: 'cdp_hogflow_matcher_conversion_event_skipped',+ help: 'Conversions counted as a metric but not emitted as $workflows_conversion, because the run had no distinct_id to attribute a capture event to.',+})++const counterHogflowMatcherWatchersSkipped = new Counter({+ name: 'cdp_hogflow_matcher_watchers_skipped',+ help: 'Watcher rows skipped because their pinned goal was missing or unreadable. Each one is a run that can never record a conversion.',+})++const counterHogflowMatcherWatchersEvaluated = new Counter({+ name: 'cdp_hogflow_matcher_watchers_evaluated',+ help: 'Conversion watcher rows loaded and evaluated against a batch.',+})++const gaugeHogflowMatcherTeamsWithWatchers = new Gauge({+ name: 'cdp_hogflow_matcher_teams_with_live_watchers',+ help: 'Teams admitted through the parse gate purely because they still have unexpired conversion watchers.',+})++const histogramHogflowMatcherFindWatchers = new Histogram({+ name: 'cdp_hogflow_matcher_find_watchers_seconds',+ help: 'Duration of the conversion_watchers lookup.',+ buckets: [0.001, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5],+})+// Latency of the cyclotron lookup for parked jobs. Watch this for cyclotron-node// read pressure as the wait-until-event feature ramps.const histogramHogflowMatcherFindParkedJobs = new Histogram({@@ -143,9 +181,6 @@ type MatchedJob = {conversionEventUuid?: string}-// Payload for capturedEventsService.queueEvent — a resolved PostHog capture event minus the token.-type CapturedConversionEvent = { team_id: number } & Omit<InternalCaptureEvent, 'team_token'>-type FilterGlobals = ReturnType<typeof convertToHogFunctionFilterGlobal>// Wakes parked hogflow jobs when an event matches a `wait_until_condition` step@@ -168,6 +203,11 @@ export class CdpHogflowSubscriptionMatcherConsumer<// the survivor's id so the survivor's person/event updates can wake them.private personDistinctIdKafkaConsumer: KafkaConsumerInterfaceprivate cyclotronPool: Pool+ private watcherSweepTimer: NodeJS.Timeout | null = null+ private watcherTeamsRefreshTimer: NodeJS.Timeout | null = null+ // Teams with at least one unexpired watcher. Empty until the first refresh, which start() awaits+ // before consuming, so the gate is never consulted against an unpopulated set.+ private teamsWithLiveWatchers: Set<number> = new Set()constructor(config: TConfig, deps: CdpConsumerBaseDeps) {super(config, deps)@@ -244,12 +284,30 @@ export class CdpHogflowSubscriptionMatcherConsumer<invocationGlobals: HogFunctionInvocationGlobals[],source: WakeSource = 'events'): Promise<void> {- const { teamIds, distinctTeamIds, distinctIds, personTeamIds, personIds, byDistinctId, byPersonId } =- indexBatch(invocationGlobals)+ const indexed = indexBatch(invocationGlobals)+ const { teamIds, distinctTeamIds, distinctIds, personTeamIds, personIds, byDistinctId, byPersonId } = indexedif (byDistinctId.size === 0 && byPersonId.size === 0) {return}+ // Compute filterGlobals once per event; the same event can match many candidates and many+ // watchers.+ const filterGlobalsByEvent = new Map<HogFunctionInvocationGlobals, FilterGlobals>()+ const filterGlobalsFor = (g: HogFunctionInvocationGlobals): FilterGlobals => {+ let fg = filterGlobalsByEvent.get(g)+ if (!fg) {+ fg = convertToHogFunctionFilterGlobal(g)+ filterGlobalsByEvent.set(g, fg)+ }+ return fg+ }++ // Claimed before the parked-job work and independently of it: a watcher's run may have+ // finished long ago, so gating this on the flow still having something parked would put back+ // exactly the blind spot watchers exist to remove.+ const conversionsCounted = await this.claimConversionWatchers(indexed, filterGlobalsFor)+ counterHogflowMatcherConversionsCounted.inc(conversionsCounted)+// Build the set of actionable flows from the in-memory hogflow cache (same pattern as// cdp-events). Only flows with a wait_until_condition step or an event-based conversion// goal can ever be woken; scoping to them keeps the function_id list in findParkedJobs@@ -281,17 +339,6 @@ export class CdpHogflowSubscriptionMatcherConsumer<}counterHogflowMatcherCandidatesEvaluated.inc(candidates.length)- // Compute filterGlobals once per event; the same event can match many candidates.- const filterGlobalsByEvent = new Map<HogFunctionInvocationGlobals, FilterGlobals>()- const filterGlobalsFor = (g: HogFunctionInvocationGlobals): FilterGlobals => {- let fg = filterGlobalsByEvent.get(g)- if (!fg) {- fg = convertToHogFunctionFilterGlobal(g)- filterGlobalsByEvent.set(g, fg)- }- return fg- }-const matchedJobs: MatchedJob[] = []for (const candidate of candidates) {const hogflow = hogflows[candidate.functionId]@@ -371,14 +418,12 @@ export class CdpHogflowSubscriptionMatcherConsumer<return}- const { woken, conversionsCounted } = await this.processMatchedJobs(matchedJobs)+ const woken = await this.processMatchedJobs(matchedJobs)counterHogflowMatcherJobsWoken.inc(woken)- counterHogflowMatcherConversionsCounted.inc(conversionsCounted)logger.info('⚡', 'Processed waiting workflows from event match', {evaluated: candidates.length,matched: matchedJobs.length,woken,- conversionsCounted,})}@@ -453,18 +498,18 @@ export class CdpHogflowSubscriptionMatcherConsumer<}))}- private async processMatchedJobs(matched: MatchedJob[]): Promise<{ woken: number; conversionsCounted: number }> {+ // Only ever resumes runs. Conversions are counted by claimConversionWatchers, which is what keeps+ // a conversion countable after the run it belongs to has finished.+ private async processMatchedJobs(matched: MatchedJob[]): Promise<number> {if (matched.length === 0) {- return { woken: 0, conversionsCounted: 0 }+ return 0}const ids = matched.map((m) => m.id)// The state read-modify-write must be atomic: two matcher instances acting on the same job// would otherwise both read the original state and the later UPDATE would drop the earlier- // flag — and both would count the same conversion. SELECT ... FOR UPDATE inside a transaction- // serializes them: the second instance blocks, then reads our committed `conversionCounted`- // and skips the duplicate. ORDER BY id keeps lock acquisition order consistent across- // instances so concurrent batches can't deadlock.+ // flag. SELECT ... FOR UPDATE inside a transaction serializes them. ORDER BY id keeps lock+ // acquisition order consistent across instances so concurrent batches can't deadlock.const client = await this.cyclotronPool.connect()try {await client.query('BEGIN')@@ -478,13 +523,10 @@ export class CdpHogflowSubscriptionMatcherConsumer<)const matchedById = new Map(matched.map((m) => [m.id, m]))- // Woken jobs get `scheduled = NOW()`; count-only jobs (measurement-only conversions on- // non-exit flows) get a state write that leaves `scheduled` untouched, so we persist- // `conversionCounted` without pulling a parked job forward.+ // Woken jobs get `scheduled = NOW()`; the rest get a state write that leaves `scheduled`+ // untouched, so a flag persists without pulling a parked job forward.const wakeUpdates: { id: string; state: Buffer }[] = []const stateOnlyUpdates: { id: string; state: Buffer }[] = []- const conversionMetrics: MinimalAppMetric[] = []- const conversionEvents: CapturedConversionEvent[] = []for (const row of stateRows.rows) {if (!row.state) {continue@@ -497,43 +539,6 @@ export class CdpHogflowSubscriptionMatcherConsumer<if (!outcome) {continue}- if (outcome.countConversion) {- conversionMetrics.push({- team_id: m.teamId,- // Key by the run id so batch-workflow conversions land under the batch job- // (parentRunId), matching how the executor records property-based conversions.- app_source_id: m.parentRunId ?? m.functionId,- instance_id: m.functionId,- metric_kind: 'other',- metric_name: 'conversion',- count: 1,- // Omitted rather than defaulted when the run predates the stamp: the- // conversion then lands only in the version-agnostic series, which is- // better than crediting it to a version that never sent to this person.- app_source_version:- outcome.flowVersion !== undefined- ? { id: m.functionId, version: outcome.flowVersion }- : undefined,- })- // Emit the same billable $workflows_conversion event as the executor's property- // path, so event-based conversions also power insights/cohorts. Needs a- // distinct_id to attribute to a person.- if (m.conversionDistinctId) {- conversionEvents.push({- team_id: m.teamId,- event: '$workflows_conversion',- distinct_id: m.conversionDistinctId,- timestamp: new Date().toISOString(),- properties: {- $workflow_id: m.functionId,- $workflow_version: outcome.flowVersion,- $workflow_conversion_type: 'event',- $workflow_conversion_event: m.conversionEventName,- $workflow_conversion_event_uuid: m.conversionEventUuid,- },- })- }- }if (outcome.wake) {wakeUpdates.push({ id: row.id, state: outcome.state })} else {@@ -567,15 +572,7 @@ export class CdpHogflowSubscriptionMatcherConsumer<}await client.query('COMMIT')- // Queue metrics/events only after the dedup write commits: if the transaction rolled back,- // the run is still uncounted in state, so a retry must be free to count it (no double-count).- for (const metric of conversionMetrics) {- this.hogFunctionMonitoringService.queueAppMetric(metric, 'hog_flow')- }- await Promise.all(- conversionEvents.map((event) => this.invocationResultsService.capturedEventsService.queueEvent(event))- )- return { woken, conversionsCounted: conversionMetrics.length }+ return woken} catch (err) {await client.query('ROLLBACK').catch(() => {})throw err@@ -584,6 +581,169 @@ export class CdpHogflowSubscriptionMatcherConsumer<}}+ /**+ * Counts conversions by claiming the watcher rows of runs whose goal this batch satisfied.+ *+ * Runs against watchers rather than parked jobs, which is what lets a conversion count after the+ * run has ended — by then the run's cyclotron job is gone. Deleting the watcher IS the claim, so+ * two matcher instances racing on the same run cannot both count it, and no lock or state parse+ * is involved. Never touches cyclotron_jobs: exiting early on conversion is the run's business,+ * handled by processMatchedJobs.+ */+ private async claimConversionWatchers(+ indexed: IndexedBatch,+ filterGlobalsFor: (globals: HogFunctionInvocationGlobals) => FilterGlobals+ ): Promise<number> {+ const { distinctTeamIds, distinctIds, personTeamIds, personIds, byDistinctId, byPersonId } = indexed++ const stopTimer = histogramHogflowMatcherFindWatchers.startTimer()+ let found+ try {+ found = await this.cyclotronPool.query(+ `SELECT id, team_id, function_id, run_id, parent_run_id, distinct_id, person_id, flow_version, goal+ FROM conversion_watchers+ WHERE expires_at > NOW()+ AND (team_id, distinct_id) IN (SELECT * FROM unnest($1::int[], $2::text[]))+ UNION+ SELECT id, team_id, function_id, run_id, parent_run_id, distinct_id, person_id, flow_version, goal+ FROM conversion_watchers+ WHERE expires_at > NOW()+ AND (team_id, person_id) IN (SELECT * FROM unnest($3::int[], $4::text[]))`,+ [distinctTeamIds, distinctIds, personTeamIds, personIds]+ )+ } finally {+ stopTimer()+ }+ if (found.rows.length === 0) {+ return 0+ }+ counterHogflowMatcherWatchersEvaluated.inc(found.rows.length)++ const converted: {+ row: any+ distinctId?: string+ conversionType: 'property' | 'event'+ eventName?: string+ eventUuid?: string+ }[] = []+ for (const row of found.rows) {+ // A watcher with no usable goal can never convert. Skipping it keeps a malformed row from+ // throwing out of the whole batch, which also carries the unrelated wake path.+ if (!row.goal || typeof row.goal !== 'object') {+ counterHogflowMatcherWatchersSkipped.inc()+ continue+ }+ const candidateGlobals = collectCandidateGlobals(+ { teamId: row.team_id, distinctId: row.distinct_id, personId: row.person_id },+ byDistinctId,+ byPersonId+ )+ for (const globals of candidateGlobals) {+ const conversionType = await matchesPinnedGoal(row.goal, filterGlobalsFor(globals), row.function_id)+ if (conversionType) {+ converted.push({+ row,+ distinctId: globals.event.distinct_id || row.distinct_id || undefined,+ conversionType,+ // Only an event goal is caused by the event that matched. A property goal is+ // detected against person state carried by whatever event delivered the update+ // (often the synthetic $person_updated, or an unrelated event), so stamping that+ // event would attribute the conversion to something that did not cause it.+ eventName: conversionType === 'event' ? globals.event.event : undefined,+ eventUuid: conversionType === 'event' ? globals.event.uuid : undefined,+ })+ break+ }+ }+ }+ if (converted.length === 0) {+ return 0+ }++ // The delete is the claim: only rows this statement actually removed are counted, so a+ // concurrent instance that removed the same row first counts it and we do not.+ const claimed = await this.cyclotronPool.query(+ `DELETE FROM conversion_watchers WHERE id = ANY($1::uuid[]) RETURNING id`,+ [converted.map((c) => c.row.id)]+ )+ const claimedIds = new Set(claimed.rows.map((r) => r.id))++ for (const { row, distinctId, conversionType, eventName, eventUuid } of converted) {+ if (!claimedIds.has(row.id)) {+ continue+ }+ this.hogFunctionMonitoringService.queueAppMetric(+ {+ team_id: row.team_id,+ // Batch children attribute to the parent batch job, matching every other run metric.+ app_source_id: row.parent_run_id ?? row.function_id,+ instance_id: row.function_id,+ metric_kind: 'other',+ metric_name: 'conversion',+ count: 1,+ app_source_version:+ row.flow_version !== null ? { id: row.function_id, version: row.flow_version } : undefined,+ },+ 'hog_flow'+ )+ // Surfaced as a billable event too, so conversions can power insights and cohorts. The run+ // id is what joins it back to the enrollment that earned it.+ //+ // A person-triggered run (batch audience, manual person trigger) enrolls with no+ // distinct_id, and a person-property change carries none either, so there is nothing to+ // attribute a capture event to. The app metric still counts, but any consumer reading+ // conversions from the event stream will not see these — watch the counter.+ if (!distinctId) {+ counterHogflowMatcherConversionEventSkipped.inc()+ }+ if (distinctId) {+ await this.invocationResultsService.capturedEventsService.queueEvent({+ team_id: row.team_id,+ event: '$workflows_conversion',+ distinct_id: distinctId,+ timestamp: new Date().toISOString(),+ properties: {+ $workflow_id: row.function_id,+ $workflow_run_id: row.run_id,+ $workflow_version: row.flow_version ?? undefined,+ $workflow_conversion_type: conversionType,+ $workflow_conversion_event: eventName,+ $workflow_conversion_event_uuid: eventUuid,+ },+ })+ }+ }+ return claimedIds.size+ }++ /**+ * Whether a team's messages are worth the full parse. True when it has a flow the matcher can act+ * on, or when it still has live conversion watchers.+ *+ * The watcher half matters because the flow cache is active-only. Pausing or archiving a team's+ * only goal workflow, or removing its goal, would otherwise drop every message for that team, and+ * its already-enrolled watchers would expire uncounted — silently under-reporting, and defeating+ * the point of pinning the goal to the run in the first place.+ */+ private async teamIsActionable(teamId: number): Promise<boolean> {+ const teamHogFlows = await this.hogFlowManager.getHogFlowsForTeam(teamId)+ if (teamHogFlows.some(hasWaitUntilOrConversion)) {+ return true+ }+ return this.teamsWithLiveWatchers.has(teamId)+ }++ // One small query per refresh, returning at most one row per team that has ever enrolled a run on+ // a goal workflow. Kept as a whole-set replace so a team whose watchers have all expired drops out+ // without needing its own invalidation.+ private async refreshTeamsWithLiveWatchers(): Promise<void> {+ const result = await this.cyclotronPool.query(+ `SELECT DISTINCT team_id FROM conversion_watchers WHERE expires_at > NOW()`+ )+ this.teamsWithLiveWatchers = new Set(result.rows.map((row) => row.team_id))+ gaugeHogflowMatcherTeamsWithWatchers.set(this.teamsWithLiveWatchers.size)+ }+@instrumented('cdpHogflowSubscriptionMatcher.parseKafkaMessages')public async _parseKafkaBatch(messages: Message[]): Promise<HogFunctionInvocationGlobals[]> {const events: HogFunctionInvocationGlobals[] = []@@ -601,8 +761,7 @@ export class CdpHogflowSubscriptionMatcherConsumer<// The vast majority of events belong to teams with no wait_until_condition// step and no event conversion goal. Bail on those via the in-memory hogflow// cache before paying for getTeam + full globals conversion.- const teamHogFlows = await this.hogFlowManager.getHogFlowsForTeam(clickHouseEvent.team_id)- if (!teamHogFlows.some(hasWaitUntilOrConversion)) {+ if (!(await this.teamIsActionable(clickHouseEvent.team_id))) {counterHogflowMatcherEventSkipped.labels({ reason: 'no_actionable_flow' }).inc()return}@@ -642,8 +801,7 @@ export class CdpHogflowSubscriptionMatcherConsumer<}// clickhouse_person is a firehose; bail before getTeam + JSON parse for teams// with no flow the matcher can act on.- const teamHogFlows = await this.hogFlowManager.getHogFlowsForTeam(data.team_id)- if (!teamHogFlows.some(hasWaitUntilOrConversion)) {+ if (!(await this.teamIsActionable(data.team_id))) {counterHogflowMatcherEventSkipped.labels({ reason: 'no_actionable_flow' }).inc()return}@@ -675,8 +833,7 @@ export class CdpHogflowSubscriptionMatcherConsumer<counterHogflowMatcherEventSkipped.labels({ reason: 'no_identifiers' }).inc()return}- const teamHogFlows = await this.hogFlowManager.getHogFlowsForTeam(parsed.team_id)- if (!teamHogFlows.some(hasWaitUntilOrConversion)) {+ if (!(await this.teamIsActionable(parsed.team_id))) {counterHogflowMatcherEventSkipped.labels({ reason: 'no_actionable_flow' }).inc()return}@@ -753,12 +910,65 @@ export class CdpHogflowSubscriptionMatcherConsumer<if (repoints.length > 0) {await this.applyMoves(repoints, false)}+ // Watchers are keyed the same two ways parked jobs are, so a merge that repoints a distinct_id+ // leaves the watcher addressed to a person nothing will ever update again. A watcher can live+ // for the whole attribution window, so it is far more likely than a parked job to outlast a+ // merge, and an unreachable one silently stops counting.+ await this.rekeyWatchers(moves)if (firstMappings.length > 0) {counterHogflowMatcherFirstMapping.labels({ outcome: 'seen' }).inc(firstMappings.length)await this.applyMoves(firstMappings, true)}}+ private async rekeyWatchers(moves: PersonDistinctIdMove[]): Promise<void> {+ // Highest version wins per distinct_id: repoints are not Kafka-keyed, so a batch can carry a+ // chain (anon -> A -> B) out of order, and re-keying onto an intermediate person would leave+ // the watcher just as unreachable.+ const survivorByKey = new Map<string, { personId: string; version: number }>()+ for (const move of moves) {+ const key = `${move.teamId}:${move.distinctId}`+ const existing = survivorByKey.get(key)+ if (!existing || move.version > existing.version) {+ survivorByKey.set(key, { personId: move.newPersonId, version: move.version })+ }+ }+ const teamIds: number[] = []+ const distinctIds: string[] = []+ const personIds: string[] = []+ const versions: number[] = []+ for (const [key, survivor] of survivorByKey) {+ const [teamId, ...distinctIdParts] = key.split(':')+ teamIds.push(Number(teamId))+ distinctIds.push(distinctIdParts.join(':'))+ personIds.push(survivor.personId)+ versions.push(survivor.version)+ }++ // Let a re-key failure propagate, like applyMoves and the read/wake path do: it fails the batch+ // so the offset doesn't advance and the pod replays. The UPDATE is idempotent — a no-op once+ // person_id already matches — so replay is safe. Swallowing it here instead would strand every+ // watcher in the batch on its pre-merge person until it expires, silently under-counting.+ const result = await this.cyclotronPool.query(+ `UPDATE conversion_watchers w+ SET person_id = u.person_id, person_version = u.version+ FROM (+ SELECT unnest($1::int[]) AS team_id, unnest($2::text[]) AS distinct_id, unnest($3::text[]) AS person_id, unnest($4::int[]) AS version+ ) u+ WHERE w.team_id = u.team_id AND w.distinct_id = u.distinct_id AND w.person_id IS DISTINCT FROM u.person_id+ -- Ordering within a batch is handled above; this is the cross-batch half. A repoint that+ -- arrives after a higher-versioned one would otherwise rewind the anchor to an+ -- intermediate person, leaving the watcher unreachable by person_id until it expires.+ AND u.version > w.person_version+ -- A first mapping (version 0) only says "this distinct_id now has a person"; it may fill+ -- an empty anchor but must not overwrite one a merge already set, mirroring the+ -- onlyNullAnchor scope applyMoves uses. Repoints (version > 0) may repoint any anchor.+ AND (u.version > 0 OR w.person_id IS NULL)`,+ [teamIds, distinctIds, personIds, versions]+ )+ counterHogflowMatcherWatchersRekeyed.inc(result.rowCount ?? 0)+ }+private async applyMoves(moves: PersonDistinctIdMove[], onlyNullAnchor: boolean): Promise<void> {// Only flows with a wait_until_condition step can have a parked wait to re-key. Scope the// function_id filter to them so the cyclotron query stays index-friendly and skips repoints for@@ -882,6 +1092,33 @@ export class CdpHogflowSubscriptionMatcherConsumer<public override async start(): Promise<void> {await super.start()+ // Watchers that convert are deleted by the claim; ones that never convert are only removed+ // here, so without this the table grows for the lifetime of the deployment.+ // Awaited so the first batches are gated against a populated set rather than an empty one,+ // which would drop messages for teams whose only goal flow is paused. A failure here must not+ // stop the matcher starting: an empty set degrades the gate to its previous flow-only+ // behavior for one refresh interval, which is milder than refusing to consume at all.+ await this.refreshTeamsWithLiveWatchers().catch((err) => {+ logger.error('⚠️', 'Initial conversion-watcher team refresh failed; gating on flows alone', { err })+ captureException(err)+ })+ this.watcherTeamsRefreshTimer = setInterval(() => {+ void this.refreshTeamsWithLiveWatchers().catch((err) => {+ logger.error('⚠️', 'Failed to refresh teams with live conversion watchers', { err })+ captureException(err)+ })+ }, WATCHER_TEAMS_REFRESH_INTERVAL_MS)+ this.watcherSweepTimer = setInterval(() => {+ void this.invocationResultsService.conversionWatchersService.sweepExpired().catch((err) => {+ logger.error('⚠️', 'Conversion watcher sweep failed', { err })+ captureException(err)+ })+ }, WATCHER_SWEEP_INTERVAL_MS)+ // Neither timer is work the process should stay alive for: both are periodic maintenance that+ // the next start picks up. Unref'd, a consumer that was started but never stopped cannot hold+ // the event loop open — which is what a leaked one does to a long single-process test run.+ this.watcherTeamsRefreshTimer.unref()+ this.watcherSweepTimer.unref()// Surface failures to each kafka consumer so the offset doesn't advance past a batch we// couldn't match. The pod will crash and replay; the SELECT is read-only and the UPDATE// (with `status = 'available'` guards) is idempotent, so replay is safe. All three streams@@ -921,6 +1158,12 @@ export class CdpHogflowSubscriptionMatcherConsumer<public override async stop(): Promise<void> {logger.info('💤', `Stopping ${this.name}...`)+ if (this.watcherSweepTimer) {+ clearInterval(this.watcherSweepTimer)+ }+ if (this.watcherTeamsRefreshTimer) {+ clearInterval(this.watcherTeamsRefreshTimer)+ }await Promise.all([this.kafkaConsumer.disconnect(),this.personKafkaConsumer.disconnect(),@@ -1008,10 +1251,36 @@ function hasWaitUntilOrConversion(hogflow: HogFlow): boolean {if (hogflow.actions.some((a: HogFlowAction) => a.type === 'wait_until_condition')) {return true}+ // Property goals count as actionable: their watchers are evaluated against person-property+ // changes, and gating on `events` alone would skip the team before those watchers were ever read,+ // leaving every property-only goal permanently at zero conversions.+ if (hogflow.conversion?.filters?.length) {+ return true+ }const conversionEvents = hogflow.conversion?.eventsreturn Array.isArray(conversionEvents) && conversionEvents.length > 0}+// A pinned goal converts when the property branch matches, or any event branch does. The two are+// independent detectors of the same goal, so they are OR'd — matching the UI, where a person who+// does either is converted.+async function matchesPinnedGoal(+ goal: PinnedConversionGoal,+ filterGlobals: FilterGlobals,+ hogFlowId: string+): Promise<'property' | 'event' | null> {+ const context = { hogFlowId }+ if (goal.properties?.length && (await runFilterBytecode(goal.properties, filterGlobals, context))) {+ return 'property'+ }+ for (const bytecode of goal.events ?? []) {+ if (await runFilterBytecode(bytecode, filterGlobals, context)) {+ return 'event'+ }+ }+ return null+}+// Single pass over the batch: dedup distinct/person ids, collect team ids,// and bucket every event under all the keys it could match a candidate by.function indexBatch(invocationGlobals: HogFunctionInvocationGlobals[]): IndexedBatch {@@ -1068,7 +1337,7 @@ function pushToMap<K, V>(map: Map<K, V[]>, key: K, value: V): void {}function collectCandidateGlobals(- candidate: ParkedCandidate,+ candidate: Pick<ParkedCandidate, 'teamId' | 'distinctId' | 'personId'>,byDistinctId: Map<string, HogFunctionInvocationGlobals[]>,byPersonId: Map<string, HogFunctionInvocationGlobals[]>): HogFunctionInvocationGlobals[] {@@ -1130,11 +1399,7 @@ function rewriteStatePersonId(}}-// `flowVersion` is the version the run *started* under, read out of the parked job's own state.-// It is deliberately not taken from the freshly loaded flow: a conversion arriving after a-// republish belongs to the version whose message the person received. Undefined for runs parked-// before the stamp existed.-type MatchOutcome = { state: Buffer; wake: boolean; countConversion: boolean; flowVersion?: number }+type MatchOutcome = { state: Buffer; wake: boolean }// Applies a batch match to a parked job's state. Returns the new state plus whether the job should// be woken (`scheduled = NOW()`) and whether its conversion should be counted this run. Returns null@@ -1146,17 +1411,6 @@ function applyMatchToState(stateBuffer: Buffer, m: MatchedJob): MatchOutcome | nlet changed = falselet wake = false- let countConversion = false-- // Count each run's conversion at most once, regardless of exit condition. The same flag is- // set by the executor's property-based path, so a run is counted once whether it converts via- // a property change or a conversion event — and repeated conversion events no longer inflate- // the count for measurement-only (non-exit) flows.- if (m.conversionMatched && !updatedState.conversionCounted) {- updatedState.conversionCounted = true- changed = true- countConversion = true- }// A matched wait_until_condition step resumes the job, tagged so the resume reads as an event// match rather than a timeout.@@ -1179,9 +1433,10 @@ function applyMatchToState(stateBuffer: Buffer, m: MatchedJob): MatchOutcome | n}}- // Only exit-on-conversion flows resume on a conversion match (so shouldExitEarly can exit).- // For any other exit condition the conversion is measurement-only: we persist conversionCounted- // above but must not reschedule, or we'd pull a parked job (e.g. one in a delay) forward.+ // Only exit-on-conversion flows resume on a conversion match, so shouldExitEarly can exit. For+ // any other exit condition the goal is measurement-only and the run must not be rescheduled,+ // or we'd pull a parked job (e.g. one in a delay) forward. Counting happens on the watcher+ // either way, so a measurement-only flow needs no write here at all.if (m.conversionMatched && m.exitsOnConversion) {updatedState.conversionMatched = truechanged = true@@ -1192,12 +1447,7 @@ function applyMatchToState(stateBuffer: Buffer, m: MatchedJob): MatchOutcome | nreturn null}parsed.state = updatedState- return {- state: Buffer.from(JSON.stringify(parsed)),- wake,- countConversion,- flowVersion: updatedState.flowVersion,- }+ return { state: Buffer.from(JSON.stringify(parsed)), wake }} catch (err) {logger.warn('Failed to parse state during match', { jobId: m.id, err })return nulldiff --git a/nodejs/src/cdp/consumers/cdp-rerun-worker.consumer.ts b/nodejs/src/cdp/consumers/cdp-rerun-worker.consumer.tsindex 25a5edbfd535..826fe81334a0 100644--- a/nodejs/src/cdp/consumers/cdp-rerun-worker.consumer.ts+++ b/nodejs/src/cdp/consumers/cdp-rerun-worker.consumer.ts@@ -128,6 +128,9 @@ export class CdpRerunWorkerConsumer extends CdpConsumerBase<PluginsServerConfig>await this.jobQueues.hog_flow.stopProducer()await this.clickhouseClient?.close()await this.invocationResultsService.flush()+ // This consumer overrides stop() without calling super.stop(), so close the conversion-watcher+ // pool here too rather than relying on the base teardown.+ await this.invocationResultsService.stop()}override isHealthy(): HealthCheckResult {diff --git a/nodejs/src/cdp/services/captured-events/captured-events.service.ts b/nodejs/src/cdp/services/captured-events/captured-events.service.tsindex 9eeb2f9673ad..fa5c61886a41 100644--- a/nodejs/src/cdp/services/captured-events/captured-events.service.ts+++ b/nodejs/src/cdp/services/captured-events/captured-events.service.ts@@ -86,6 +86,12 @@ export class CapturedEventsService {)}+ // Required by ResultSink. This sink holds nothing of its own: it writes through the shared+ // Kafka outputs, which the server disconnects separately on shutdown.+ async stop(): Promise<void> {+ return Promise.resolve()+ }+async flush(): Promise<void> {const events = this.queuedEventsthis.queuedEvents = []diff --git a/nodejs/src/cdp/services/conversion-watchers/conversion-watchers.service.ts b/nodejs/src/cdp/services/conversion-watchers/conversion-watchers.service.tsnew file mode 100644index 000000000000..04a6b9cb1c82--- /dev/null+++ b/nodejs/src/cdp/services/conversion-watchers/conversion-watchers.service.ts@@ -0,0 +1,198 @@+import { Pool } from 'pg'+import { Counter, Gauge } from 'prom-client'++import { logger } from '~/common/utils/logger'+import { captureException } from '~/common/utils/posthog'++import { ConversionWatcherRow, CyclotronJobInvocationResult } from '../../types'++const counterConversionWatchersInserted = new Counter({+ name: 'cdp_conversion_watchers_inserted',+ help: 'Conversion watcher rows written at run start, one per enrolled run on a goal workflow.',+})++const counterConversionWatchersFailed = new Counter({+ name: 'cdp_conversion_watchers_failed',+ help: 'Watcher rows dropped because the insert failed. Each one is a run whose conversion can never be counted, so the conversion rate under-reports by exactly this much.',+})++const counterConversionWatchersSwept = new Counter({+ name: 'cdp_conversion_watchers_swept',+ help: 'Expired watcher rows deleted. These are runs that reached the end of their attribution window without converting.',+})++const gaugeConversionWatchersPending = new Gauge({+ name: 'cdp_conversion_watchers_pending_rows',+ help: 'Watcher rows queued in memory waiting for the next flush. Resets to 0 after each flush.',+})++// Bounds a single INSERT's parameter count: Postgres caps a statement at 65535 bindings, and each row+// binds 10.+const INSERT_CHUNK_SIZE = 1000++// Bounds one sweep so a long-neglected table can't lock a huge delete; the interval simply runs again.+const SWEEP_LIMIT = 10000++/**+ * Owns the `conversion_watchers` table: writes a watcher when a run enrolls, and deletes expired ones.+ *+ * Reading and claiming watchers belongs to the subscription matcher, which is where the event stream+ * is. This service is the write side, wired into `InvocationResultsService` alongside the other+ * result-borne row sinks.+ */+export class ConversionWatchersService {+ private queuedRows: ConversionWatcherRow[] = []+ private pool: Pool | null = null+ private stopped = false+ private inFlight = new Set<Promise<unknown>>()++ // Owns its pool rather than taking one, mirroring the subscription matcher: the table lives in the+ // cyclotron database, which nothing else in the result-sink chain connects to. A process without+ // the connection string drops watchers via the failure counter rather than throwing, so processes+ // that never run workflows are unaffected.+ constructor(+ private readonly databaseUrl: string | undefined,+ private readonly maxConnections?: number+ ) {}++ // Built on first use, not in the constructor. Every CDP service set constructs this service, but+ // only the ones that actually run workflows ever write a row — an eager pool would have every+ // consumer, and every test that builds a service set, holding cyclotron connections it never uses.+ private getPool(): Pool | null {+ if (this.pool || this.stopped || !this.databaseUrl) {+ return this.pool+ }+ this.pool = new Pool({ connectionString: this.databaseUrl, max: this.maxConnections })+ // pg throws an uncaught exception if an idle client errors with no listener attached, which+ // would take down the process for something this sink is allowed to drop.+ this.pool.on('error', (err) => {+ logger.error('⚠️', 'Conversion watcher pool error', { err })+ })+ return this.pool+ }++ // Idempotent: pg rejects a second end() with "Called end on pool more than once", and several+ // shutdown paths reach this one service — the base consumer teardown, CdpRerunWorkerConsumer's+ // own stop(), and CdpApi.stop(). A consumer stopped twice must not fail its own shutdown.+ public async stop(): Promise<void> {+ // Set first so a flush that has not started yet gets no pool and drops its rows through the+ // failure counter, rather than opening a connection this method is about to close.+ this.stopped = true+ // A flush or a sweep that is already running holds a pool reference and awaits a query. Ending+ // the pool under it would fail the work it has not finished, so wait for every one of them.+ // Each operation reports its own failure, and shutdown must not re-raise that.+ await Promise.all([...this.inFlight].map((operation) => operation.catch(() => {})))+ const pool = this.pool+ this.pool = null+ await pool?.end()+ }++ public queueInvocationResults(results: CyclotronJobInvocationResult[]): void {+ for (const result of results) {+ if (result.conversionWatchers.length) {+ this.queuedRows.push(...result.conversionWatchers)+ }+ }+ gaugeConversionWatchersPending.set(this.queuedRows.length)+ }++ // Registers a running operation so stop() can wait for it before it closes the pool. The operation+ // takes its pool reference before the first await, so by the time it is tracked it already holds+ // one, and stop() cannot slip in between. The returned promise is the caller's, so a failure still+ // surfaces where it was started.+ private track<T>(operation: Promise<T>): Promise<T> {+ this.inFlight.add(operation)+ void operation.catch(() => {}).finally(() => this.inFlight.delete(operation))+ return operation+ }++ public async flush(): Promise<void> {+ await this.track(this.writeQueuedRows())+ }++ private async writeQueuedRows(): Promise<void> {+ if (!this.queuedRows.length) {+ return+ }+ const rows = this.queuedRows+ this.queuedRows = []+ gaugeConversionWatchersPending.set(0)++ const pool = this.getPool()+ if (!pool) {+ counterConversionWatchersFailed.inc(rows.length)+ logger.error('⚠️', 'Dropping conversion watchers: no cyclotron database configured', {+ count: rows.length,+ })+ return+ }++ for (let offset = 0; offset < rows.length; offset += INSERT_CHUNK_SIZE) {+ const chunk = rows.slice(offset, offset + INSERT_CHUNK_SIZE)+ try {+ await this.insertChunk(pool, chunk)+ counterConversionWatchersInserted.inc(chunk.length)+ } catch (err) {+ // Dropping a watcher silently under-reports conversions rather than failing loudly, so+ // this counter is the only signal that it happened. Not rethrown: a failed insert must+ // not take down the batch that produced the run, which has already executed.+ counterConversionWatchersFailed.inc(chunk.length)+ logger.error('⚠️', 'Failed to insert conversion watchers', { err, count: chunk.length })+ captureException(err)+ }+ }+ }++ private async insertChunk(pool: Pool, rows: ConversionWatcherRow[]): Promise<void> {+ const values: any[] = []+ const placeholders = rows.map((row, index) => {+ const base = index * 10+ values.push(+ row.id,+ row.team_id,+ row.function_id,+ row.run_id,+ row.parent_run_id,+ row.distinct_id,+ row.person_id,+ row.flow_version,+ JSON.stringify(row.goal),+ row.expires_at+ )+ return `($${base + 1}, $${base + 2}, $${base + 3}, $${base + 4}, $${base + 5}, $${base + 6}, $${base + 7}, $${base + 8}, $${base + 9}, $${base + 10})`+ })++ await pool.query(+ `INSERT INTO conversion_watchers+ (id, team_id, function_id, run_id, parent_run_id, distinct_id, person_id, flow_version, goal, expires_at)+ VALUES ${placeholders.join(', ')}+ ON CONFLICT (id) DO NOTHING`,+ values+ )+ }++ /**+ * Deletes watchers whose attribution window has closed. Nothing else removes them: a watcher that+ * converts is deleted by the claim, and one that never converts would otherwise live forever.+ */+ public async sweepExpired(): Promise<number> {+ return this.track(this.deleteExpiredRows())+ }++ private async deleteExpiredRows(): Promise<number> {+ const pool = this.getPool()+ if (!pool) {+ return 0+ }+ const result = await pool.query(+ `DELETE FROM conversion_watchers+ WHERE id IN (+ SELECT id FROM conversion_watchers WHERE expires_at <= NOW() LIMIT $1+ )`,+ [SWEEP_LIMIT]+ )+ const deleted = result.rowCount ?? 0+ counterConversionWatchersSwept.inc(deleted)+ return deleted+ }+}diff --git a/nodejs/src/cdp/services/hog-executor.service.test.ts b/nodejs/src/cdp/services/hog-executor.service.test.tsindex 80b6452661b9..fe5683332f33 100644--- a/nodejs/src/cdp/services/hog-executor.service.test.ts+++ b/nodejs/src/cdp/services/hog-executor.service.test.ts@@ -161,6 +161,7 @@ describe('Hog Executor', () => {capturedPostHogEvents: [],warehouseWebhookPayloads: [],messageAssets: [],+ conversionWatchers: [],invocation: {state: {globals: invocation.state.globals,diff --git a/nodejs/src/cdp/services/hogflows/actions/hog_function.test.ts b/nodejs/src/cdp/services/hogflows/actions/hog_function.test.tsindex 657c82304664..e723157e082f 100644--- a/nodejs/src/cdp/services/hogflows/actions/hog_function.test.ts+++ b/nodejs/src/cdp/services/hogflows/actions/hog_function.test.ts@@ -554,6 +554,7 @@ describe('HogFunctionHandler', () => {capturedPostHogEvents: [],warehouseWebhookPayloads: [],messageAssets: [],+ conversionWatchers: [],})const invocationResult = createInvocationResult<CyclotronJobInvocationHogFlow>(invocation, {diff --git a/nodejs/src/cdp/services/hogflows/actions/hog_function.ts b/nodejs/src/cdp/services/hogflows/actions/hog_function.tsindex f5550bb23505..e7e9ad05700c 100644--- a/nodejs/src/cdp/services/hogflows/actions/hog_function.ts+++ b/nodejs/src/cdp/services/hogflows/actions/hog_function.ts@@ -177,6 +177,7 @@ export class HogFunctionHandler implements ActionHandler {capturedPostHogEvents: [],warehouseWebhookPayloads: [],messageAssets: [],+ conversionWatchers: [],}}@@ -206,6 +207,7 @@ export class HogFunctionHandler implements ActionHandler {capturedPostHogEvents: [],warehouseWebhookPayloads: [],messageAssets: [],+ conversionWatchers: [],}}diff --git a/nodejs/src/cdp/services/hogflows/conversion-watcher.ts b/nodejs/src/cdp/services/hogflows/conversion-watcher.tsnew file mode 100644index 000000000000..288fab48c1d7--- /dev/null+++ b/nodejs/src/cdp/services/hogflows/conversion-watcher.ts@@ -0,0 +1,74 @@+import { HogFlow } from '~/cdp/schema/hogflow'++import { ConversionWatcherRow, CyclotronJobInvocationHogFlow, PinnedConversionGoal } from '../../types'+import { hasEventOrActionTarget } from './hogflow-utils'++// A goal is configured if either detection path has something to evaluate. Gates the watcher: a+// workflow with no goal has nothing to measure, so it writes no rows.+function pinConversionGoal(hogFlow: HogFlow): PinnedConversionGoal | null {+ const properties = hogFlow.conversion?.filters?.length ? hogFlow.conversion.bytecode : undefined+ // Drop entries that target neither events nor actions: those compile to always-true bytecode and+ // would count a conversion on the first event of any kind. Same guard the wait_until and conversion+ // evaluators apply — pin it here too so the watcher path agrees with them.+ const events = (hogFlow.conversion?.events ?? [])+ .filter(hasEventOrActionTarget)+ .map((eventConfig) => eventConfig.filters?.bytecode)+ .filter((bytecode): bytecode is any[] => Array.isArray(bytecode) && bytecode.length > 0)++ if (!properties?.length && !events.length) {+ return null+ }+ return {+ ...(properties?.length ? { properties } : {}),+ ...(events.length ? { events } : {}),+ }+}++// The watcher outlives the run, which is the whole point: once the run finishes its cyclotron job is+// gone, and a conversion landing after that has nothing left to match against. See the+// conversion_watchers migration.+//+// A run is enrolling iff it has no `currentAction` yet: every dispatch path (events, warehouse,+// webhooks, batch children, reruns) creates the invocation without one, and `ensureCurrentAction`+// fills it in on the first execution. `ON CONFLICT (id) DO NOTHING` on the insert makes a retry after+// a crash idempotent, since the id is derived from the run.+export function buildConversionWatcher(invocation: CyclotronJobInvocationHogFlow): ConversionWatcherRow | null {+ if (invocation.state.currentAction) {+ return null+ }+ const goal = pinConversionGoal(invocation.hogFlow)+ if (!goal) {+ return null+ }+ const distinctId = invocation.state.event?.distinct_id || null+ const personId = invocation.person?.id ?? invocation.state.personId ?? null+ // Without either key the matcher can never look this watcher up, so the row would be dead weight.+ if (!distinctId && !personId) {+ return null+ }+ return {+ id: invocation.id,+ team_id: invocation.hogFlow.team_id,+ function_id: invocation.hogFlow.id,+ run_id: invocation.id,+ parent_run_id: invocation.parentRunId ?? null,+ distinct_id: distinctId,+ person_id: personId,+ flow_version: invocation.state.flowVersion ?? null,+ goal,+ expires_at: new Date(Date.now() + conversionWindowMinutes(invocation.hogFlow) * 60_000),+ }+}++// A null window means "no explicit window", which cannot mean "forever": the row would never be+// swept and the table would grow without bound. The cap is also what keeps the watcher population+// proportional to recent traffic rather than to all traffic ever.+export const MAX_CONVERSION_WINDOW_MINUTES = 30 * 24 * 60++function conversionWindowMinutes(hogFlow: HogFlow): number {+ const configured = hogFlow.conversion?.window_minutes+ if (!configured || configured <= 0) {+ return MAX_CONVERSION_WINDOW_MINUTES+ }+ return Math.min(configured, MAX_CONVERSION_WINDOW_MINUTES)+}diff --git a/nodejs/src/cdp/services/hogflows/hogflow-conversion-watcher.test.ts b/nodejs/src/cdp/services/hogflows/hogflow-conversion-watcher.test.tsnew file mode 100644index 000000000000..d39a3fde255f--- /dev/null+++ b/nodejs/src/cdp/services/hogflows/hogflow-conversion-watcher.test.ts@@ -0,0 +1,96 @@+import { HogFlow } from '~/cdp/schema/hogflow'++import { createExampleHogFlowInvocation } from '../../_tests/fixtures-hogflows'+import { CyclotronJobInvocationHogFlow } from '../../types'+import { MAX_CONVERSION_WINDOW_MINUTES, buildConversionWatcher } from './conversion-watcher'++describe('buildConversionWatcher', () => {+ const propertyBytecode = ['_H', 1, 32, 'Chrome', 32, '$browser', 32, 'properties', 32, 'person', 1, 3, 11]+ const eventBytecode = ['_H', 1, 32, 'signed_up', 32, 'event', 1, 1, 11]++ const propertyGoal = {+ filters: [{ key: '$browser', type: 'person', value: ['Chrome'], operator: 'exact' }],+ bytecode: propertyBytecode,+ window_minutes: null,+ }+ const eventGoal = {+ filters: [],+ bytecode: [],+ window_minutes: null,+ events: [{ filters: { events: [{ id: 'signed_up' }], bytecode: eventBytecode } }],+ }+ const noGoal = { filters: [], bytecode: [], window_minutes: null }++ const invocationFor = (conversion: any, flowOverrides: Partial<HogFlow> = {}): CyclotronJobInvocationHogFlow => {+ const hogFlow = { id: 'flow-1', team_id: 1, version: 3, conversion, ...flowOverrides } as unknown as HogFlow+ // Every production dispatch path seeds flowVersion when it builds the invocation+ // (createHogFlowInvocation, and the batch-resolve consumer); the shared fixture does not.+ return createExampleHogFlowInvocation(hogFlow, { flowVersion: hogFlow.version })+ }++ it.each([+ ['a property goal', propertyGoal, true],+ ['an event goal', eventGoal, true],+ ['no goal configured', noGoal, false],+ ])('builds a watcher for a workflow with %s', (_name, conversion, expected) => {+ expect(buildConversionWatcher(invocationFor(conversion)) !== null).toBe(expected)+ })++ it('carries the ids the matcher and the conversion query both need', () => {+ const invocation = invocationFor(propertyGoal)++ expect(buildConversionWatcher(invocation)).toMatchObject({+ run_id: invocation.id,+ function_id: 'flow-1',+ team_id: 1,+ distinct_id: 'distinct_id',+ // Pinned from state, so a conversion divides by a denominator of the same version.+ flow_version: 3,+ })+ })++ it('pins the goal as it stood at enrollment', () => {+ // Read from the watcher rather than the live flow, so editing a goal changes what later runs+ // are measured against without re-judging cohorts already in flight under the old one.+ expect(buildConversionWatcher(invocationFor(propertyGoal))?.goal).toEqual({ properties: propertyBytecode })+ expect(buildConversionWatcher(invocationFor(eventGoal))?.goal).toEqual({ events: [eventBytecode] })+ })++ it('drops an event goal that targets neither an event nor an action', () => {+ // Such an entry compiles to always-true bytecode, which would convert on the first event of+ // any kind. The wait_until and conversion evaluators guard it, so the watcher must too.+ const emptyTarget = {+ filters: [],+ bytecode: [],+ window_minutes: null,+ events: [{ filters: { bytecode: [1] } }],+ }++ expect(buildConversionWatcher(invocationFor(emptyTarget))).toBeNull()+ })++ it.each([+ ['an unbounded window', null, MAX_CONVERSION_WINDOW_MINUTES],+ ['a window longer than the cap', 60 * 24 * 90, MAX_CONVERSION_WINDOW_MINUTES],+ ['a window inside the cap', 60, 60],+ ])('expires after %s', (_name, windowMinutes, expectedMinutes) => {+ // Treating null as "forever" would leave rows the expiry sweep can never reach.+ const before = Date.now()+ const watcher = buildConversionWatcher(invocationFor({ ...propertyGoal, window_minutes: windowMinutes }))++ // Measured from `before`, so the window is at least the expected value and at most a+ // fraction of a minute more.+ const minutes = (watcher!.expires_at.getTime() - before) / 60_000+ expect(minutes).toBeGreaterThanOrEqual(expectedMinutes)+ expect(minutes).toBeLessThan(expectedMinutes + 1)+ })++ it('does not build a watcher for a run that has already started', () => {+ // A run with several delays would otherwise enroll once per wake, inflating the denominator+ // and the row count together.+ const invocation = invocationFor(propertyGoal)+ invocation.state.currentAction = { id: 'some_action', startedAtTimestamp: Date.now() }++ expect(buildConversionWatcher(invocation)).toBeNull()+ })+})diff --git a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.tsindex 90eecdbf890f..b8c60750f734 100644--- a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts+++ b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts@@ -303,6 +303,7 @@ describe('Hogflow Executor', () => {capturedPostHogEvents: [],warehouseWebhookPayloads: [],messageAssets: [],+ conversionWatchers: [],invocation: {state: {actionStepCount: 1,@@ -1465,76 +1466,34 @@ describe('Hogflow Executor', () => {`)})- it('counts a property-based conversion without exiting when exit condition is exit_only_at_end', async () => {+ // Counting at enrollment and counting from the watcher must stay disjoint. A goal already+ // satisfied when the run enrolls can never be claimed from a watcher — the matcher reads the+ // enrollment event before the row exists — so it is counted here and writes no row. A goal+ // not yet satisfied writes the row and is counted by the matcher later. Either path counting+ // twice, or neither counting, is the bug this guards.+ test.each([+ { name: 'goal not yet satisfied', browser: 'Firefox', watchers: 1, conversions: 0 },+ { name: 'goal already satisfied at enrollment', browser: 'Chrome', watchers: 0, conversions: 1 },+ ])('$name: writes $watchers watcher and counts $conversions conversion', async (params) => {hogFlow.exit_condition = 'exit_only_at_end'hogFlow.conversion = {filters: [{ key: '$browser', type: 'person', value: ['Chrome'], operator: 'exact' }],bytecode: ['_H', 1, 32, 'Chrome', 32, '$browser', 32, 'properties', 32, 'person', 1, 3, 11],window_minutes: null,- }+ } as anyconst invocation = createExampleHogFlowInvocation(hogFlow,- {- event: {- ...createHogExecutionGlobals().event,- event: '$pageview',- properties: { name: 'John Doe', $current_url: 'https://posthog.com' },- },- },- { properties: { $browser: 'Chrome' } }+ {},+ { properties: { $browser: params.browser } })-const result = await executor.execute(invocation)- // The run completes normally (no early exit) but the conversion is counted exactly once- expect(result.finished).toBe(true)- expect(result.metrics.map((m) => m.metric_name)).toEqual([- 'conversion',- 'fetch',- 'billable_invocation',- 'succeeded',- 'succeeded',- ])- expect(result.metrics.filter((m) => m.metric_name === 'conversion')).toHaveLength(1)- expect(invocation.state.conversionCounted).toBe(true)- // The conversion is also surfaced as a billable $workflows_conversion event exactly once.- const conversionEvents = result.capturedPostHogEvents.filter((e) => e.event === '$workflows_conversion')- expect(conversionEvents).toHaveLength(1)- expect(conversionEvents[0]).toMatchObject({- distinct_id: 'distinct_id',- properties: {- $workflow_id: hogFlow.id,- $workflow_version: hogFlow.version,- $workflow_conversion_type: 'property',- },- })- })- it('does not re-count a property-based conversion on a resume that already counted', async () => {- hogFlow.exit_condition = 'exit_only_at_end'- hogFlow.conversion = {- filters: [{ key: '$browser', type: 'person', value: ['Chrome'], operator: 'exact' }],- bytecode: ['_H', 1, 32, 'Chrome', 32, '$browser', 32, 'properties', 32, 'person', 1, 3, 11],- window_minutes: null,+ expect(result.conversionWatchers).toHaveLength(params.watchers)+ expect(result.metrics.filter((m) => m.metric_name === 'conversion')).toHaveLength(params.conversions)+ if (params.watchers) {+ expect(result.conversionWatchers[0].run_id).toEqual(invocation.id)}-- const invocation = createExampleHogFlowInvocation(- hogFlow,- {- event: {- ...createHogExecutionGlobals().event,- event: '$pageview',- properties: { name: 'John Doe', $current_url: 'https://posthog.com' },- },- },- { properties: { $browser: 'Chrome' } }- )- // Simulate a prior step in this run having already counted the conversion- invocation.state.conversionCounted = true-- const result = await executor.execute(invocation)- expect(result.finished).toBe(true)- expect(result.metrics.map((m) => m.metric_name)).not.toContain('conversion')})it('does not count event-based conversions in the executor (counted by the matcher)', async () => {diff --git a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.tsindex 1a65c9c13269..18bb526b7ebf 100644--- a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts+++ b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts@@ -7,6 +7,7 @@ import { logger } from '~/common/utils/logger'import { UUIDT } from '~/common/utils/utils'import {+ ConversionWatcherRow,CyclotronJobInvocationHogFlow,CyclotronJobInvocationResult,HogFunctionCapturedEvent,@@ -34,6 +35,7 @@ import { HogFunctionHandler } from './actions/hog_function'import { RandomCohortBranchHandler } from './actions/random_cohort_branch'import { TriggerHandler } from './actions/trigger.handler'import { WaitUntilTimeWindowHandler } from './actions/wait_until_time_window'+import { buildConversionWatcher } from './conversion-watcher'import { HogFlowDuplicateObserverService } from './hogflow-duplicate-observer.service'import { HogFlowFunctionsService } from './hogflow-functions.service'import {@@ -239,11 +241,26 @@ export class HogFlowExecutorService {const capturedPostHogEvents: HogFunctionCapturedEvent[] = []const warehouseWebhookPayloads: WarehouseWebhookPayload[] = []const messageAssets: MessageAssetRow[] = []+ const conversionWatchers: ConversionWatcherRow[] = []- const earlyExitResult = await this.shouldExitEarly(invocation, metrics, capturedPostHogEvents)+ // A run enrolls on its first execution, before any exit check: a run that exits immediately+ // still consumed an enrollment, and `triggered` already counted it, so leaving it out would+ // overstate the rate.+ const watcher = buildConversionWatcher(invocation)+ const enrollmentConversion = watcher ? await this.conversionAtEnrollment(invocation) : null++ const earlyExitResult = await this.shouldExitEarly(invocation)if (earlyExitResult) {+ this.recordEnrollment(+ enrollmentConversion,+ watcher,+ earlyExitResult.metrics,+ earlyExitResult.capturedPostHogEvents,+ earlyExitResult.conversionWatchers+ )return earlyExitResult}+ this.recordEnrollment(enrollmentConversion, watcher, metrics, capturedPostHogEvents, conversionWatchers)// Routing-only reschedule: the previous dequeue moved this job onto a dedicated queue// (e.g. 'email' for SES rate-limit gating) and is continuing the same action. Suppress@@ -277,6 +294,7 @@ export class HogFlowExecutorService {capturedPostHogEvents.push(...result.capturedPostHogEvents)warehouseWebhookPayloads.push(...result.warehouseWebhookPayloads)messageAssets.push(...result.messageAssets)+ conversionWatchers.push(...result.conversionWatchers)if (this.shouldEndHogFlowExecution(result, logs)) {break@@ -288,10 +306,83 @@ export class HogFlowExecutorService {result.capturedPostHogEvents = capturedPostHogEventsresult.warehouseWebhookPayloads = warehouseWebhookPayloadsresult.messageAssets = messageAssets+ result.conversionWatchers = conversionWatchersreturn result}+ /**+ * A property goal already satisfied when the run enrolls can never be counted from its watcher.+ * The matcher reads the enrollment event off Kafka long before the run has written the row, and+ * on `exit_on_conversion` the run is gone before any later event could claim it — so the run+ * would record `early_exit` and no `conversion` at all.+ *+ * Counting it here keeps the two paths disjoint: a run that converts at enrollment writes no+ * watcher, so it is still counted exactly once.+ */+ private async conversionAtEnrollment(+ invocation: CyclotronJobInvocationHogFlow+ ): Promise<{ metric: MinimalAppMetric; event: HogFunctionCapturedEvent | null } | null> {+ const { hogFlow } = invocation+ if (!invocation.person || !hogFlow.conversion?.filters?.length || !hogFlow.conversion.bytecode?.length) {+ return null+ }+ const filterResult = await filterFunctionInstrumented({+ fn: hogFlow,+ filters: { bytecode: hogFlow.conversion.bytecode, properties: hogFlow.conversion.filters },+ filterGlobals: invocation.filterGlobals,+ })+ if (!filterResult.match) {+ return null+ }+ const distinctId = invocation.state.event?.distinct_id+ return {+ metric: {+ team_id: hogFlow.team_id,+ app_source_id: invocation.parentRunId ?? hogFlow.id,+ instance_id: hogFlow.id,+ metric_kind: 'other',+ metric_name: 'conversion',+ count: 1,+ },+ // Mirrors the matcher's payload so both paths produce the same billable event. A run with+ // no distinct_id has nothing to attribute the capture to; the metric still counts.+ event: distinctId+ ? {+ team_id: hogFlow.team_id,+ event: '$workflows_conversion',+ distinct_id: distinctId,+ timestamp: new Date().toISOString(),+ properties: {+ $workflow_id: hogFlow.id,+ $workflow_run_id: invocation.id,+ $workflow_version: invocation.state.flowVersion ?? hogFlow.version,+ $workflow_conversion_type: 'property',+ },+ }+ : null,+ }+ }++ private recordEnrollment(+ enrollmentConversion: { metric: MinimalAppMetric; event: HogFunctionCapturedEvent | null } | null,+ watcher: ConversionWatcherRow | null,+ metrics: MinimalAppMetric[],+ capturedPostHogEvents: HogFunctionCapturedEvent[],+ conversionWatchers: ConversionWatcherRow[]+ ): void {+ if (enrollmentConversion) {+ metrics.push(enrollmentConversion.metric)+ if (enrollmentConversion.event) {+ capturedPostHogEvents.push(enrollmentConversion.event)+ }+ return+ }+ if (watcher) {+ conversionWatchers.push(watcher)+ }+ }+private shouldEndHogFlowExecution(result: CyclotronJobInvocationResult<CyclotronJobInvocationHogFlow>,logs: MinimalLogEntry[]@@ -342,9 +433,7 @@ export class HogFlowExecutorService {* Determines if the invocation should exit early based on the hogflow's exit condition*/private async shouldExitEarly(- invocation: CyclotronJobInvocationHogFlow,- metrics: MinimalAppMetric[],- capturedPostHogEvents: HogFunctionCapturedEvent[]+ invocation: CyclotronJobInvocationHogFlow): Promise<CyclotronJobInvocationResult<CyclotronJobInvocationHogFlow> | null> {let earlyExitResult: CyclotronJobInvocationResult<CyclotronJobInvocationHogFlow> | null = null@@ -381,42 +470,10 @@ export class HogFlowExecutorService {)}}- // Count property-based conversions here, regardless of exit condition, so the metric is- // meaningful even for flows that don't exit on conversion. Captured before the event-flag- // override below: event-based conversions are counted by the subscription matcher, so the- // executor must only emit for the property path or exit-on-conversion event flows double-count.- // Guarded once-per-run by `conversionCounted` since shouldExitEarly runs on every resume.- const propertyConversionMatched = conversionMatch === true- let conversionMetric: MinimalAppMetric | null = null- let conversionEvent: HogFunctionCapturedEvent | null = null- if (propertyConversionMatched && !invocation.state.conversionCounted) {- invocation.state.conversionCounted = true- conversionMetric = {- team_id: hogFlow.team_id,- app_source_id: invocation.parentRunId ?? hogFlow.id,- instance_id: hogFlow.id,- metric_kind: 'other',- metric_name: 'conversion',- count: 1,- }- // Also surface the conversion as a billable PostHog event so it can power insights and- // cohorts (mirrors the $workflows_email_* engagement events). Event-based conversions are- // emitted by the subscription matcher, so this only fires for the property path.- const distinctId = invocation.state.event?.distinct_id- if (distinctId) {- conversionEvent = {- team_id: hogFlow.team_id,- event: '$workflows_conversion',- distinct_id: distinctId,- timestamp: new Date().toISOString(),- properties: {- $workflow_id: hogFlow.id,- $workflow_version: hogFlow.version,- $workflow_conversion_type: 'property',- },- }- }- }+ // Counting lives entirely on the run's conversion watcher, which the matcher claims. The run+ // only decides whether to exit. Keeping the two apart is what makes the count survive the run+ // finishing, and stops a watcher and a still-live run from both counting the same conversion.+ //// Event-based conversion goals are evaluated by the subscription matcher (against the live// event stream), which flags the job when the conversion event fires. The property-based// check above can't see those, so honor the flag here. It is a one-shot signal ("the@@ -469,16 +526,6 @@ export class HogFlowExecutorService {})}- // Route the conversion metric/event onto whichever result is actually flushed: the early-exit- // result when we exit, otherwise the caller's arrays (which become result.metrics /- // result.capturedPostHogEvents once the run continues and finishes).- if (conversionMetric) {- ;(earlyExitResult?.metrics ?? metrics).push(conversionMetric)- }- if (conversionEvent) {- ;(earlyExitResult?.capturedPostHogEvents ?? capturedPostHogEvents).push(conversionEvent)- }-return earlyExitResult}diff --git a/nodejs/src/cdp/services/invocation-results.service.test.ts b/nodejs/src/cdp/services/invocation-results.service.test.tsindex 0332f382eab7..00ab9ed588f3 100644--- a/nodejs/src/cdp/services/invocation-results.service.test.ts+++ b/nodejs/src/cdp/services/invocation-results.service.test.ts@@ -1,5 +1,6 @@import { CyclotronJobInvocationResult } from '../types'import { CapturedEventsService } from './captured-events/captured-events.service'+import { ConversionWatchersService } from './conversion-watchers/conversion-watchers.service'import { InvocationResultsService } from './invocation-results.service'import { MessageAssetsService } from './messaging/message-assets.service'import { HogFunctionMonitoringService } from './monitoring/hog-function-monitoring.service'@@ -12,6 +13,7 @@ describe('InvocationResultsService', () => {let warehouseWebhooksService: jest.Mocked<WarehouseWebhooksService>let capturedEventsService: jest.Mocked<CapturedEventsService>let messageAssetsService: jest.Mocked<MessageAssetsService>+ let conversionWatchersService: jest.Mocked<ConversionWatchersService>let service: InvocationResultsServiceconst results = [@@ -45,12 +47,18 @@ describe('InvocationResultsService', () => {flush: jest.fn().mockResolvedValue(undefined),} as unknown as jest.Mocked<MessageAssetsService>+ conversionWatchersService = {+ queueInvocationResults: jest.fn(),+ flush: jest.fn().mockResolvedValue(undefined),+ } as unknown as jest.Mocked<ConversionWatchersService>+service = new InvocationResultsService(monitoringService,invocationResultsRowsService,warehouseWebhooksService,capturedEventsService,- messageAssetsService+ messageAssetsService,+ conversionWatchersService)})diff --git a/nodejs/src/cdp/services/invocation-results.service.ts b/nodejs/src/cdp/services/invocation-results.service.tsindex 0effda1d2631..200fdb0798ba 100644--- a/nodejs/src/cdp/services/invocation-results.service.ts+++ b/nodejs/src/cdp/services/invocation-results.service.ts@@ -2,11 +2,23 @@ import { instrumentFn } from '~/common/tracing/tracing-utils'import { CyclotronJobInvocationResult } from '../types'import { CapturedEventsService } from './captured-events/captured-events.service'+import { ConversionWatchersService } from './conversion-watchers/conversion-watchers.service'import { MessageAssetsService } from './messaging/message-assets.service'import { HogFunctionMonitoringService } from './monitoring/hog-function-monitoring.service'import { HogInvocationResultsService } from './monitoring/hog-invocation-results.service'import { WarehouseWebhooksService } from './warehouse/warehouse-webhooks.service'+/**+ * What every result sink has to expose so this service can drive it by list rather+ * than by name. `stop` is on the interface even though most sinks hold nothing to+ * release: a sink that later acquires a resource then has one obvious place to free+ * it, and teardown cannot quietly skip a sink because someone forgot to add a call.+ */+export interface ResultSink {+ flush(): Promise<void>+ stop(): Promise<void>+}+/*** Fans `CyclotronJobInvocationResult` batches out to the sinks every* CDP consumer/API caller needs:@@ -18,6 +30,8 @@ import { WarehouseWebhooksService } from './warehouse/warehouse-webhooks.service* - `CapturedEventsService` — PostHog events emitted via posthog.capture()* - `MessageAssetsService` — rendered-email snapshots for the workflow* Assets tab+ * - `ConversionWatchersService` — per-run conversion watchers, which outlive the+ * run so a late conversion stays observable** Callers interact with this one service instead of coordinating queue/flush* calls across the five individually. `queueInvocationResultsAndFlush` is the@@ -26,13 +40,25 @@ import { WarehouseWebhooksService } from './warehouse/warehouse-webhooks.service* asynchronously after the HTTP response).*/export class InvocationResultsService {+ private readonly sinks: ResultSink[]+constructor(public readonly monitoringService: HogFunctionMonitoringService,public readonly invocationResultsRowsService: HogInvocationResultsService,public readonly warehouseWebhooksService: WarehouseWebhooksService,public readonly capturedEventsService: CapturedEventsService,- public readonly messageAssetsService: MessageAssetsService- ) {}+ public readonly messageAssetsService: MessageAssetsService,+ public readonly conversionWatchersService: ConversionWatchersService+ ) {+ this.sinks = [+ monitoringService,+ invocationResultsRowsService,+ warehouseWebhooksService,+ capturedEventsService,+ messageAssetsService,+ conversionWatchersService,+ ]+ }queueInvocationResults(results: CyclotronJobInvocationResult[]): Promise<void> {return instrumentFn(`cdpConsumer.handleEachBatch.produceResults`, async () => {@@ -40,22 +66,21 @@ export class InvocationResultsService {this.invocationResultsRowsService.queueInvocationResults(results)this.warehouseWebhooksService.queueInvocationResults(results)this.messageAssetsService.queueInvocationResults(results)+ this.conversionWatchersService.queueInvocationResults(results)await this.capturedEventsService.queueInvocationResults(results)})}async flush(): Promise<void> {- await Promise.all([- this.monitoringService.flush(),- this.invocationResultsRowsService.flush(),- this.warehouseWebhooksService.flush(),- this.capturedEventsService.flush(),- this.messageAssetsService.flush(),- ])+ await Promise.all(this.sinks.map((sink) => sink.flush()))}async queueInvocationResultsAndFlush(results: CyclotronJobInvocationResult[]): Promise<void> {await this.queueInvocationResults(results)await this.flush()}++ async stop(): Promise<void> {+ await Promise.all(this.sinks.map((sink) => sink.stop()))+ }}diff --git a/nodejs/src/cdp/services/job-queue/job-queue-postgres-v2.test.ts b/nodejs/src/cdp/services/job-queue/job-queue-postgres-v2.test.tsindex cd644ac4afd3..ebb5e2aaaabb 100644--- a/nodejs/src/cdp/services/job-queue/job-queue-postgres-v2.test.ts+++ b/nodejs/src/cdp/services/job-queue/job-queue-postgres-v2.test.ts@@ -53,6 +53,7 @@ describe('CyclotronJobQueuePostgresV2', () => {capturedPostHogEvents: [],warehouseWebhookPayloads: [],messageAssets: [],+ conversionWatchers: [],...overrides,}}diff --git a/nodejs/src/cdp/services/job-queue/shared.test.ts b/nodejs/src/cdp/services/job-queue/shared.test.tsindex e36f10ce6604..7901b256ceb7 100644--- a/nodejs/src/cdp/services/job-queue/shared.test.ts+++ b/nodejs/src/cdp/services/job-queue/shared.test.ts@@ -267,6 +267,7 @@ describe('createInvocationSanitizer', () => {capturedPostHogEvents: [],warehouseWebhookPayloads: [],messageAssets: [],+ conversionWatchers: [],}const [sanitized] = sanitizer.sanitizeResults([result])diff --git a/nodejs/src/cdp/services/messaging/message-assets.service.ts b/nodejs/src/cdp/services/messaging/message-assets.service.tsindex d808561e22f3..a0d041c5a5d2 100644--- a/nodejs/src/cdp/services/messaging/message-assets.service.ts+++ b/nodejs/src/cdp/services/messaging/message-assets.service.ts@@ -220,6 +220,12 @@ export class MessageAssetsService {messageAssetsPendingRows.set(this.queuedRows.length)}+ // Required by ResultSink. This sink holds nothing of its own: it writes through the shared+ // Kafka outputs, which the server disconnects separately on shutdown.+ async stop(): Promise<void> {+ return Promise.resolve()+ }+async flush(): Promise<void> {if (this.queuedRows.length === 0) {returndiff --git a/nodejs/src/cdp/services/monitoring/hog-function-monitoring.service.ts b/nodejs/src/cdp/services/monitoring/hog-function-monitoring.service.tsindex 303157afac94..65c58f842fb5 100644--- a/nodejs/src/cdp/services/monitoring/hog-function-monitoring.service.ts+++ b/nodejs/src/cdp/services/monitoring/hog-function-monitoring.service.ts@@ -72,6 +72,12 @@ export class HogFunctionMonitoringService {this.appMetricsAggregator = new AppMetricsAggregator(outputs)}+ // Required by ResultSink. This sink holds nothing of its own: it writes through the shared+ // Kafka outputs, which the server disconnects separately on shutdown.+ async stop(): Promise<void> {+ return Promise.resolve()+ }+async flush() {const messages = [...this.queuedLogMessages]this.queuedLogMessages = []diff --git a/nodejs/src/cdp/services/monitoring/hog-invocation-results.service.ts b/nodejs/src/cdp/services/monitoring/hog-invocation-results.service.tsindex 794c375384ed..2fadfa43abed 100644--- a/nodejs/src/cdp/services/monitoring/hog-invocation-results.service.ts+++ b/nodejs/src/cdp/services/monitoring/hog-invocation-results.service.ts@@ -586,6 +586,12 @@ export class HogInvocationResultsService {hogInvocationResultsPendingMessages.set(this.queuedRows.length)}+ // Required by ResultSink. This sink holds nothing of its own: it writes through the shared+ // Kafka outputs, which the server disconnects separately on shutdown.+ async stop(): Promise<void> {+ return Promise.resolve()+ }+async flush(): Promise<void> {if (this.queuedRows.length === 0) {returndiff --git a/nodejs/src/cdp/services/warehouse/warehouse-webhooks.service.ts b/nodejs/src/cdp/services/warehouse/warehouse-webhooks.service.tsindex d41d0a193fde..3c6524c933a0 100644--- a/nodejs/src/cdp/services/warehouse/warehouse-webhooks.service.ts+++ b/nodejs/src/cdp/services/warehouse/warehouse-webhooks.service.ts@@ -41,6 +41,12 @@ export class WarehouseWebhooksService {}}+ // Required by ResultSink. This sink holds nothing of its own: it writes through the shared+ // Kafka outputs, which the server disconnects separately on shutdown.+ async stop(): Promise<void> {+ return Promise.resolve()+ }+async flush(): Promise<void> {const payloads = this.queuedPayloadsthis.queuedPayloads = []diff --git a/nodejs/src/cdp/types.ts b/nodejs/src/cdp/types.tsindex 344500a97dc6..800838d02d9a 100644--- a/nodejs/src/cdp/types.ts+++ b/nodejs/src/cdp/types.ts@@ -334,9 +334,36 @@ export type CyclotronJobInvocationResult<T extends CyclotronJobInvocation = CyclcapturedPostHogEvents: HogFunctionCapturedEvent[]warehouseWebhookPayloads: WarehouseWebhookPayload[]messageAssets: MessageAssetRow[]+ conversionWatchers: ConversionWatcherRow[]execResult?: unknown}+// The compiled conversion goal as it stood when a run enrolled. Pinned to the run rather than read+// from the live flow, so editing a goal changes what future runs are measured against without+// re-judging cohorts already in flight under the old one.+export type PinnedConversionGoal = {+ // Property-based goal, evaluated against person properties.+ properties?: any[]+ // Event-based goals, any one of which converts.+ events?: any[][]+}++// One per enrolled run on a workflow with a conversion goal, outliving the run so a conversion that+// lands after the last step is still observable. See the conversion_watchers migration for why this+// is not a cyclotron_jobs row.+export type ConversionWatcherRow = {+ id: string+ team_id: number+ function_id: string+ run_id: string+ parent_run_id: string | null+ distinct_id: string | null+ person_id: string | null+ flow_version: number | null+ goal: PinnedConversionGoal+ expires_at: Date+}+export type CyclotronJobInvocationHogFunctionContext = {globals: HogFunctionInvocationGlobalsWithInputsvmState?: VMStatediff --git a/nodejs/src/cdp/utils/invocation-utils.ts b/nodejs/src/cdp/utils/invocation-utils.tsindex 072793815cb3..6e6d3f5bf560 100644--- a/nodejs/src/cdp/utils/invocation-utils.ts+++ b/nodejs/src/cdp/utils/invocation-utils.ts@@ -202,6 +202,7 @@ export function createInvocationResult<T extends CyclotronJobInvocation>(| 'capturedPostHogEvents'| 'warehouseWebhookPayloads'| 'messageAssets'+ | 'conversionWatchers'| 'logs'| 'metrics'| 'error'@@ -214,6 +215,7 @@ export function createInvocationResult<T extends CyclotronJobInvocation>(capturedPostHogEvents: [],warehouseWebhookPayloads: [],messageAssets: [],+ conversionWatchers: [],logs: [],metrics: [],...resultParams,